]> git.proxmox.com Git - pve-manager.git/blame - www/manager6/Utils.js
Set VirtIO drivers as default when using the Qemu Wizard and the OS Type is Linux
[pve-manager.git] / www / manager6 / Utils.js
CommitLineData
b0a6d326
EK
1Ext.ns('PVE');
2
63b9faae
EK
3// avoid errors related to Accessible Rich Internet Applications
4// (access for people with disabilities)
0be88ae1 5// TODO reenable after all components are upgraded
63b9faae
EK
6Ext.enableAria = false;
7Ext.enableAriaButtons = false;
8Ext.enableAriaPanels = false;
9
b0a6d326 10// avoid errors when running without development tools
0be88ae1
DC
11if (!Ext.isDefined(Ext.global.console)) {
12 var console = {
13 dir: function() {},
14 log: function() {}
b0a6d326
EK
15 };
16}
0be88ae1 17console.log("Starting PVE Manager");
b0a6d326
EK
18
19Ext.Ajax.defaultHeaders = {
20 'Accept': 'application/json'
21};
22
23Ext.Ajax.on('beforerequest', function(conn, options) {
24 if (PVE.CSRFPreventionToken) {
0be88ae1 25 if (!options.headers) {
b0a6d326
EK
26 options.headers = {};
27 }
28 options.headers.CSRFPreventionToken = PVE.CSRFPreventionToken;
29 }
30});
31
32var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
33var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
34var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
35var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
36
37
38var IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
368df92e 39var IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")\/([0-9]{1,2})$");
b0a6d326
EK
40
41var IPV6_REGEXP = "(?:" +
42 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
43 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
44 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
45 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
46 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
47 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
48 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
49 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
50 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
51 ")";
52
8a52defd 53var IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
368df92e 54var IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")\/([0-9]{1,3})$");
aa0819a8 55var IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
8a52defd 56
b0a6d326
EK
57var IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
58
7b58d7b2
DC
59var DnsName_REGEXP = "(?:(([a-zA-Z0-9]([a-zA-Z0-9\\-]*[a-zA-Z0-9])?)\\.)*([A-Za-z0-9]([A-Za-z0-9\\-]*[A-Za-z0-9])?))";
60var DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
61
70e779e4
DC
62var HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
63var HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
64var IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
65
b0a6d326
EK
66Ext.define('PVE.Utils', { statics: {
67
68 // this class only contains static functions
69
0be88ae1 70 toolkit: undefined, // (extjs|touch), set inside Toolkit.js
b0a6d326
EK
71
72 log_severity_hash: {
73 0: "panic",
74 1: "alert",
75 2: "critical",
76 3: "error",
77 4: "warning",
78 5: "notice",
79 6: "info",
80 7: "debug"
81 },
82
83 support_level_hash: {
84 'c': gettext('Community'),
85 'b': gettext('Basic'),
86 's': gettext('Standard'),
87 'p': gettext('Premium')
88 },
89
90 noSubKeyHtml: 'You do not have a valid subscription for this server. Please visit <a target="_blank" href="http://www.proxmox.com/products/proxmox-ve/subscription-service-plans">www.proxmox.com</a> to get a list of available options.',
91
92 kvm_ostypes: {
93 other: gettext('Other OS types'),
94 wxp: 'Microsoft Windows XP/2003',
95 w2k: 'Microsoft Windows 2000',
96 w2k8: 'Microsoft Windows Vista/2008',
97 win7: 'Microsoft Windows 7/2008r2',
d481d825 98 win8: 'Microsoft Windows 8.x/10/2012/r2',
b0a6d326 99 l24: 'Linux 2.4 Kernel',
5a4ba3c2 100 l26: 'Linux 4.X/3.X/2.6 Kernel',
b0a6d326
EK
101 solaris: 'Solaris Kernel'
102 },
103
104 render_kvm_ostype: function (value) {
105 if (!value) {
106 return gettext('Other OS types');
107 }
108 var text = PVE.Utils.kvm_ostypes[value];
109 if (text) {
b7159d8b 110 return text;
b0a6d326
EK
111 }
112 return value;
113 },
114
115 render_hotplug_features: function (value) {
23d3881a 116 var fa = [];
b0a6d326
EK
117
118 if (!value || (value === '0')) {
119 return gettext('disabled');
120 }
121
4dcca8a4
DC
122 if (value === '1') {
123 value = 'disk,network,usb';
124 }
125
b0a6d326
EK
126 Ext.each(value.split(','), function(el) {
127 if (el === 'disk') {
128 fa.push(gettext('Disk'));
129 } else if (el === 'network') {
130 fa.push(gettext('Network'));
131 } else if (el === 'usb') {
132 fa.push(gettext('USB'));
133 } else if (el === 'memory') {
134 fa.push(gettext('Memory'));
135 } else if (el === 'cpu') {
136 fa.push(gettext('CPU'));
137 } else {
138 fa.push(el);
139 }
140 });
141
142 return fa.join(', ');
143 },
144
145 network_iface_types: {
146 eth: gettext("Network Device"),
147 bridge: 'Linux Bridge',
148 bond: 'Linux Bond',
149 OVSBridge: 'OVS Bridge',
150 OVSBond: 'OVS Bond',
151 OVSPort: 'OVS Port',
152 OVSIntPort: 'OVS IntPort'
153 },
154
155 render_network_iface_type: function(value) {
0be88ae1 156 return PVE.Utils.network_iface_types[value] ||
b0a6d326
EK
157 PVE.Utils.unknownText;
158 },
159
17c71f27
DC
160 render_qemu_bios: function(value) {
161 if (!value) {
162 return PVE.Utils.defaultText + ' (SeaBIOS)';
163 } else if (value === 'seabios') {
164 return "SeaBIOS";
165 } else if (value === 'ovmf') {
166 return "OVMF (UEFI)";
167 } else {
168 return value;
169 }
170 },
171
b0a6d326
EK
172 render_scsihw: function(value) {
173 if (!value) {
174 return PVE.Utils.defaultText + ' (LSI 53C895A)';
175 } else if (value === 'lsi') {
176 return 'LSI 53C895A';
177 } else if (value === 'lsi53c810') {
178 return 'LSI 53C810';
179 } else if (value === 'megasas') {
180 return 'MegaRAID SAS 8708EM2';
181 } else if (value === 'virtio-scsi-pci') {
49f5d1ab
EK
182 return 'VirtIO SCSI';
183 } else if (value === 'virtio-scsi-single') {
184 return 'VirtIO SCSI single';
b0a6d326
EK
185 } else if (value === 'pvscsi') {
186 return 'VMware PVSCSI';
187 } else {
188 return value;
189 }
190 },
191
192 // fixme: auto-generate this
193 // for now, please keep in sync with PVE::Tools::kvmkeymaps
194 kvm_keymaps: {
195 //ar: 'Arabic',
196 da: 'Danish',
0be88ae1
DC
197 de: 'German',
198 'de-ch': 'German (Swiss)',
199 'en-gb': 'English (UK)',
0a5b8747 200 'en-us': 'English (USA)',
b0a6d326
EK
201 es: 'Spanish',
202 //et: 'Estonia',
203 fi: 'Finnish',
0be88ae1
DC
204 //fo: 'Faroe Islands',
205 fr: 'French',
206 'fr-be': 'French (Belgium)',
b0a6d326
EK
207 'fr-ca': 'French (Canada)',
208 'fr-ch': 'French (Swiss)',
209 //hr: 'Croatia',
210 hu: 'Hungarian',
211 is: 'Icelandic',
0be88ae1 212 it: 'Italian',
b0a6d326
EK
213 ja: 'Japanese',
214 lt: 'Lithuanian',
215 //lv: 'Latvian',
0be88ae1 216 mk: 'Macedonian',
b0a6d326
EK
217 nl: 'Dutch',
218 //'nl-be': 'Dutch (Belgium)',
0be88ae1 219 no: 'Norwegian',
b0a6d326
EK
220 pl: 'Polish',
221 pt: 'Portuguese',
222 'pt-br': 'Portuguese (Brazil)',
223 //ru: 'Russian',
224 sl: 'Slovenian',
225 sv: 'Swedish',
226 //th: 'Thai',
227 tr: 'Turkish'
228 },
229
230 kvm_vga_drivers: {
231 std: gettext('Standard VGA'),
5ca366f2 232 vmware: gettext('VMware compatible'),
b0a6d326
EK
233 cirrus: 'Cirrus Logic GD5446',
234 qxl: 'SPICE',
235 qxl2: 'SPICE dual monitor',
236 qxl3: 'SPICE three monitors',
237 qxl4: 'SPICE four monitors',
238 serial0: gettext('Serial terminal') + ' 0',
239 serial1: gettext('Serial terminal') + ' 1',
240 serial2: gettext('Serial terminal') + ' 2',
241 serial3: gettext('Serial terminal') + ' 3'
242 },
243
244 render_kvm_language: function (value) {
245 if (!value) {
246 return PVE.Utils.defaultText;
247 }
248 var text = PVE.Utils.kvm_keymaps[value];
249 if (text) {
250 return text + ' (' + value + ')';
251 }
252 return value;
253 },
254
255 kvm_keymap_array: function() {
f2782813 256 var data = [['__default__', PVE.Utils.render_kvm_language('')]];
b0a6d326
EK
257 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
258 data.push([key, PVE.Utils.render_kvm_language(value)]);
259 });
260
261 return data;
262 },
263
264 render_console_viewer: function(value) {
f2782813 265 if (!value || value === '__default__') {
b0a6d326 266 return PVE.Utils.defaultText + ' (HTML5)';
b0a6d326
EK
267 } else if (value === 'vv') {
268 return 'SPICE (remote-viewer)';
269 } else if (value === 'html5') {
270 return 'HTML5 (noVNC)';
271 } else {
272 return value;
273 }
274 },
275
276 language_map: {
277 zh_CN: 'Chinese',
278 ca: 'Catalan',
279 da: 'Danish',
280 en: 'English',
281 eu: 'Euskera (Basque)',
282 fr: 'French',
283 de: 'German',
284 it: 'Italian',
285 ja: 'Japanese',
286 nb: 'Norwegian (Bokmal)',
287 nn: 'Norwegian (Nynorsk)',
288 fa: 'Persian (Farsi)',
289 pl: 'Polish',
290 pt_BR: 'Portuguese (Brazil)',
291 ru: 'Russian',
292 sl: 'Slovenian',
293 es: 'Spanish',
294 sv: 'Swedish',
295 tr: 'Turkish'
296 },
297
298 render_language: function (value) {
299 if (!value) {
300 return PVE.Utils.defaultText + ' (English)';
301 }
302 var text = PVE.Utils.language_map[value];
303 if (text) {
304 return text + ' (' + value + ')';
305 }
306 return value;
307 },
308
309 language_array: function() {
d98a2c3c 310 var data = [['__default__', PVE.Utils.render_language('')]];
b0a6d326
EK
311 Ext.Object.each(PVE.Utils.language_map, function(key, value) {
312 data.push([key, PVE.Utils.render_language(value)]);
313 });
314
315 return data;
316 },
317
318 render_kvm_vga_driver: function (value) {
319 if (!value) {
320 return PVE.Utils.defaultText;
321 }
322 var text = PVE.Utils.kvm_vga_drivers[value];
0be88ae1 323 if (text) {
b0a6d326
EK
324 return text + ' (' + value + ')';
325 }
326 return value;
327 },
328
329 kvm_vga_driver_array: function() {
f2782813 330 var data = [['__default__', PVE.Utils.render_kvm_vga_driver('')]];
b0a6d326
EK
331 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
332 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
333 });
334
335 return data;
336 },
337
338 render_kvm_startup: function(value) {
339 var startup = PVE.Parser.parseStartup(value);
340
341 var res = 'order=';
342 if (startup.order === undefined) {
343 res += 'any';
344 } else {
345 res += startup.order;
346 }
347 if (startup.up !== undefined) {
348 res += ',up=' + startup.up;
349 }
350 if (startup.down !== undefined) {
351 res += ',down=' + startup.down;
352 }
353
354 return res;
355 },
356
357 authOK: function() {
358 return Ext.util.Cookies.get('PVEAuthCookie');
359 },
360
361 authClear: function() {
362 Ext.util.Cookies.clear("PVEAuthCookie");
363 },
364
365 // fixme: remove - not needed?
366 gridLineHeigh: function() {
367 return 21;
0be88ae1 368
b0a6d326
EK
369 //if (Ext.isGecko)
370 //return 23;
371 //return 21;
372 },
373
374 extractRequestError: function(result, verbose) {
375 var msg = gettext('Successful');
376
377 if (!result.success) {
378 msg = gettext("Unknown error");
379 if (result.message) {
380 msg = result.message;
381 if (result.status) {
382 msg += ' (' + result.status + ')';
383 }
384 }
385 if (verbose && Ext.isObject(result.errors)) {
386 msg += "<br>";
387 Ext.Object.each(result.errors, function(prop, desc) {
0be88ae1 388 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
b0a6d326
EK
389 Ext.htmlEncode(desc);
390 });
0be88ae1 391 }
b0a6d326
EK
392 }
393
394 return msg;
395 },
396
397 extractFormActionError: function(action) {
398 var msg;
399 switch (action.failureType) {
400 case Ext.form.action.Action.CLIENT_INVALID:
401 msg = gettext('Form fields may not be submitted with invalid values');
402 break;
403 case Ext.form.action.Action.CONNECT_FAILURE:
404 msg = gettext('Connection error');
405 var resp = action.response;
406 if (resp.status && resp.statusText) {
407 msg += " " + resp.status + ": " + resp.statusText;
408 }
409 break;
410 case Ext.form.action.Action.LOAD_FAILURE:
411 case Ext.form.action.Action.SERVER_INVALID:
412 msg = PVE.Utils.extractRequestError(action.result, true);
413 break;
414 }
415 return msg;
416 },
417
418 // Ext.Ajax.request
419 API2Request: function(reqOpts) {
420
421 var newopts = Ext.apply({
422 waitMsg: gettext('Please wait...')
423 }, reqOpts);
424
425 if (!newopts.url.match(/^\/api2/)) {
426 newopts.url = '/api2/extjs' + newopts.url;
427 }
428 delete newopts.callback;
429
430 var createWrapper = function(successFn, callbackFn, failureFn) {
431 Ext.apply(newopts, {
432 success: function(response, options) {
433 if (options.waitMsgTarget) {
434 if (PVE.Utils.toolkit === 'touch') {
435 options.waitMsgTarget.setMasked(false);
436 } else {
437 options.waitMsgTarget.setLoading(false);
438 }
439 }
440 var result = Ext.decode(response.responseText);
441 response.result = result;
442 if (!result.success) {
443 response.htmlStatus = PVE.Utils.extractRequestError(result, true);
444 Ext.callback(callbackFn, options.scope, [options, false, response]);
445 Ext.callback(failureFn, options.scope, [response, options]);
446 return;
447 }
448 Ext.callback(callbackFn, options.scope, [options, true, response]);
449 Ext.callback(successFn, options.scope, [response, options]);
450 },
451 failure: function(response, options) {
452 if (options.waitMsgTarget) {
453 if (PVE.Utils.toolkit === 'touch') {
454 options.waitMsgTarget.setMasked(false);
455 } else {
456 options.waitMsgTarget.setLoading(false);
457 }
458 }
459 response.result = {};
460 try {
461 response.result = Ext.decode(response.responseText);
462 } catch(e) {}
463 var msg = gettext('Connection error') + ' - server offline?';
464 if (response.aborted) {
465 msg = gettext('Connection error') + ' - aborted.';
466 } else if (response.timedout) {
467 msg = gettext('Connection error') + ' - Timeout.';
468 } else if (response.status && response.statusText) {
469 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
470 }
471 response.htmlStatus = msg;
472 Ext.callback(callbackFn, options.scope, [options, false, response]);
473 Ext.callback(failureFn, options.scope, [response, options]);
474 }
475 });
476 };
477
478 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
479
480 var target = newopts.waitMsgTarget;
481 if (target) {
482 if (PVE.Utils.toolkit === 'touch') {
483 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg} );
484 } else {
485 // Note: ExtJS bug - this does not work when component is not rendered
486 target.setLoading(newopts.waitMsg);
487 }
488 }
489 Ext.Ajax.request(newopts);
490 },
491
492 assemble_field_data: function(values, data) {
493 if (Ext.isObject(data)) {
494 Ext.Object.each(data, function(name, val) {
495 if (values.hasOwnProperty(name)) {
496 var bucket = values[name];
497 if (!Ext.isArray(bucket)) {
498 bucket = values[name] = [bucket];
499 }
500 if (Ext.isArray(val)) {
501 values[name] = bucket.concat(val);
502 } else {
503 bucket.push(val);
504 }
505 } else {
506 values[name] = val;
507 }
508 });
509 }
510 },
511
512 checked_command: function(orig_cmd) {
513 PVE.Utils.API2Request({
514 url: '/nodes/localhost/subscription',
515 method: 'GET',
516 //waitMsgTarget: me,
517 failure: function(response, opts) {
518 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
519 },
520 success: function(response, opts) {
521 var data = response.result.data;
522
523 if (data.status !== 'Active') {
524 Ext.Msg.show({
525 title: gettext('No valid subscription'),
526 icon: Ext.Msg.WARNING,
527 msg: PVE.Utils.noSubKeyHtml,
528 buttons: Ext.Msg.OK,
529 callback: function(btn) {
530 if (btn !== 'ok') {
531 return;
532 }
533 orig_cmd();
534 }
535 });
536 } else {
537 orig_cmd();
538 }
539 }
540 });
541 },
542
543 task_desc_table: {
544 vncproxy: [ 'VM/CT', gettext('Console') ],
545 spiceproxy: [ 'VM/CT', gettext('Console') + ' (Spice)' ],
546 vncshell: [ '', gettext('Shell') ],
547 spiceshell: [ '', gettext('Shell') + ' (Spice)' ],
548 qmsnapshot: [ 'VM', gettext('Snapshot') ],
549 qmrollback: [ 'VM', gettext('Rollback') ],
550 qmdelsnapshot: [ 'VM', gettext('Delete Snapshot') ],
551 qmcreate: [ 'VM', gettext('Create') ],
552 qmrestore: [ 'VM', gettext('Restore') ],
553 qmdestroy: [ 'VM', gettext('Destroy') ],
554 qmigrate: [ 'VM', gettext('Migrate') ],
555 qmclone: [ 'VM', gettext('Clone') ],
556 qmmove: [ 'VM', gettext('Move disk') ],
557 qmtemplate: [ 'VM', gettext('Convert to template') ],
558 qmstart: [ 'VM', gettext('Start') ],
559 qmstop: [ 'VM', gettext('Stop') ],
560 qmreset: [ 'VM', gettext('Reset') ],
561 qmshutdown: [ 'VM', gettext('Shutdown') ],
562 qmsuspend: [ 'VM', gettext('Suspend') ],
563 qmresume: [ 'VM', gettext('Resume') ],
564 qmconfig: [ 'VM', gettext('Configure') ],
16152937
DM
565 vzsnapshot: [ 'CT', gettext('Snapshot') ],
566 vzrollback: [ 'CT', gettext('Rollback') ],
567 vzdelsnapshot: [ 'CT', gettext('Delete Snapshot') ],
b0a6d326
EK
568 vzcreate: ['CT', gettext('Create') ],
569 vzrestore: ['CT', gettext('Restore') ],
570 vzdestroy: ['CT', gettext('Destroy') ],
571 vzmigrate: [ 'CT', gettext('Migrate') ],
bfade4b4
DM
572 vzclone: [ 'CT', gettext('Clone') ],
573 vztemplate: [ 'CT', gettext('Convert to template') ],
b0a6d326
EK
574 vzstart: ['CT', gettext('Start') ],
575 vzstop: ['CT', gettext('Stop') ],
576 vzmount: ['CT', gettext('Mount') ],
577 vzumount: ['CT', gettext('Unmount') ],
578 vzshutdown: ['CT', gettext('Shutdown') ],
579 vzsuspend: [ 'CT', gettext('Suspend') ],
580 vzresume: [ 'CT', gettext('Resume') ],
581 hamigrate: [ 'HA', gettext('Migrate') ],
582 hastart: [ 'HA', gettext('Start') ],
583 hastop: [ 'HA', gettext('Stop') ],
584 srvstart: ['SRV', gettext('Start') ],
585 srvstop: ['SRV', gettext('Stop') ],
586 srvrestart: ['SRV', gettext('Restart') ],
587 srvreload: ['SRV', gettext('Reload') ],
588 cephcreatemon: ['Ceph Monitor', gettext('Create') ],
589 cephdestroymon: ['Ceph Monitor', gettext('Destroy') ],
590 cephcreateosd: ['Ceph OSD', gettext('Create') ],
591 cephdestroyosd: ['Ceph OSD', gettext('Destroy') ],
592 imgcopy: ['', gettext('Copy data') ],
593 imgdel: ['', gettext('Erase data') ],
594 download: ['', gettext('Download') ],
595 vzdump: ['', gettext('Backup') ],
596 aptupdate: ['', gettext('Update package database') ],
597 startall: [ '', gettext('Start all VMs and Containers') ],
598 stopall: [ '', gettext('Stop all VMs and Containers') ],
599 migrateall: [ '', gettext('Migrate all VMs and Containers') ]
600 },
601
0be88ae1 602 format_task_description: function(type, id) {
b0a6d326
EK
603 var farray = PVE.Utils.task_desc_table[type];
604 if (!farray) {
605 return type;
606 }
607 var prefix = farray[0];
608 var text = farray[1];
609 if (prefix) {
0be88ae1 610 return prefix + ' ' + id + ' - ' + text;
b0a6d326
EK
611 }
612 return text;
613 },
614
615 parse_task_upid: function(upid) {
616 var task = {};
617
618 var res = upid.match(/^UPID:(\S+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
619 if (!res) {
620 throw "unable to parse upid '" + upid + "'";
621 }
622 task.node = res[1];
623 task.pid = parseInt(res[2], 16);
624 task.pstart = parseInt(res[3], 16);
625 task.starttime = parseInt(res[4], 16);
626 task.type = res[5];
627 task.id = res[6];
628 task.user = res[7];
629
630 task.desc = PVE.Utils.format_task_description(task.type, task.id);
631
632 return task;
633 },
634
635 format_size: function(size) {
636 /*jslint confusion: true */
637
02f47fe8
DC
638 var units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
639 var num = 0;
b0a6d326 640
02f47fe8
DC
641 while (size >= 1024 && ((num++)+1) < units.length) {
642 size = size / 1024;
b0a6d326
EK
643 }
644
02f47fe8 645 return size.toFixed((num > 0)?2:0) + " " + units[num] + "B";
b0a6d326
EK
646 },
647
648 format_html_bar: function(per, text) {
649
650 return "<div class='pve-bar-wrap'>" + text + "<div class='pve-bar-border'>" +
651 "<div class='pve-bar-inner' style='width:" + per + "%;'></div>" +
652 "</div></div>";
0be88ae1 653
b0a6d326
EK
654 },
655
656 format_cpu_bar: function(per1, per2, text) {
657
658 return "<div class='pve-bar-border'>" +
659 "<div class='pve-bar-inner' style='width:" + per1 + "%;'></div>" +
660 "<div class='pve-bar-inner2' style='width:" + per2 + "%;'></div>" +
0be88ae1 661 "<div class='pve-bar-text'>" + text + "</div>" +
b0a6d326
EK
662 "</div>";
663 },
664
665 format_large_bar: function(per, text) {
666
667 if (!text) {
668 text = per.toFixed(1) + "%";
669 }
670
671 return "<div class='pve-largebar-border'>" +
672 "<div class='pve-largebar-inner' style='width:" + per + "%;'></div>" +
0be88ae1 673 "<div class='pve-largebar-text'>" + text + "</div>" +
b0a6d326
EK
674 "</div>";
675 },
676
677 format_duration_long: function(ut) {
678
679 var days = Math.floor(ut / 86400);
680 ut -= days*86400;
681 var hours = Math.floor(ut / 3600);
682 ut -= hours*3600;
683 var mins = Math.floor(ut / 60);
684 ut -= mins*60;
685
686 var hours_str = '00' + hours.toString();
687 hours_str = hours_str.substr(hours_str.length - 2);
688 var mins_str = "00" + mins.toString();
689 mins_str = mins_str.substr(mins_str.length - 2);
690 var ut_str = "00" + ut.toString();
691 ut_str = ut_str.substr(ut_str.length - 2);
692
693 if (days) {
694 var ds = days > 1 ? PVE.Utils.daysText : PVE.Utils.dayText;
0be88ae1 695 return days.toString() + ' ' + ds + ' ' +
b0a6d326
EK
696 hours_str + ':' + mins_str + ':' + ut_str;
697 } else {
698 return hours_str + ':' + mins_str + ':' + ut_str;
699 }
700 },
701
702 format_duration_short: function(ut) {
0be88ae1 703
b0a6d326
EK
704 if (ut < 60) {
705 return ut.toString() + 's';
706 }
707
708 if (ut < 3600) {
709 var mins = ut / 60;
710 return mins.toFixed(0) + 'm';
711 }
712
713 if (ut < 86400) {
714 var hours = ut / 3600;
715 return hours.toFixed(0) + 'h';
716 }
717
718 var days = ut / 86400;
0be88ae1 719 return days.toFixed(0) + 'd';
b0a6d326
EK
720 },
721
722 yesText: gettext('Yes'),
723 noText: gettext('No'),
724 noneText: gettext('none'),
725 errorText: gettext('Error'),
726 unknownText: gettext('Unknown'),
727 defaultText: gettext('Default'),
728 daysText: gettext('days'),
729 dayText: gettext('day'),
730 runningText: gettext('running'),
731 stoppedText: gettext('stopped'),
732 neverText: gettext('never'),
733 totalText: gettext('Total'),
734 usedText: gettext('Used'),
735 directoryText: gettext('Directory'),
736 imagesText: gettext('Disk image'),
737 backupFileText: gettext('VZDump backup file'),
2c554952 738 vztmplText: gettext('Container template'),
b0a6d326 739 isoImageText: gettext('ISO image'),
2c554952 740 containersText: gettext('Container'),
45ab85bb
DM
741 stateText: gettext('State'),
742 groupText: gettext('Group'),
b0a6d326
EK
743
744 format_expire: function(date) {
745 if (!date) {
746 return PVE.Utils.neverText;
747 }
748 return Ext.Date.format(date, "Y-m-d");
749 },
750
751 format_storage_type: function(value) {
752 if (value === 'dir') {
753 return PVE.Utils.directoryText;
754 } else if (value === 'nfs') {
755 return 'NFS';
756 } else if (value === 'glusterfs') {
757 return 'GlusterFS';
758 } else if (value === 'lvm') {
759 return 'LVM';
ffd96a3b
DM
760 } else if (value === 'lvmthin') {
761 return 'LVM-Thin';
b0a6d326
EK
762 } else if (value === 'iscsi') {
763 return 'iSCSI';
764 } else if (value === 'rbd') {
765 return 'RBD';
766 } else if (value === 'sheepdog') {
767 return 'Sheepdog';
768 } else if (value === 'zfs') {
769 return 'ZFS over iSCSI';
770 } else if (value === 'zfspool') {
771 return 'ZFS';
772 } else if (value === 'iscsidirect') {
773 return 'iSCSIDirect';
ffd96a3b
DM
774 } else if (value === 'drbd') {
775 return 'DRBD';
b0a6d326
EK
776 } else {
777 return PVE.Utils.unknownText;
778 }
779 },
780
781 format_boolean_with_default: function(value) {
f2782813 782 if (Ext.isDefined(value) && value !== '__default__') {
b0a6d326
EK
783 return value ? PVE.Utils.yesText : PVE.Utils.noText;
784 }
785 return PVE.Utils.defaultText;
786 },
787
788 format_boolean: function(value) {
789 return value ? PVE.Utils.yesText : PVE.Utils.noText;
790 },
791
792 format_neg_boolean: function(value) {
793 return !value ? PVE.Utils.yesText : PVE.Utils.noText;
794 },
795
ced1677b
TL
796 format_ha: function(value) {
797 var text = PVE.Utils.format_boolean(value.managed);
798
799 if (value.managed) {
45ab85bb 800 text += ', ' + PVE.Utils.stateText + ': ';
f25d7c4a 801 text += value.state || PVE.Utils.noneText;
ced1677b 802
45ab85bb 803 text += ', ' + PVE.Utils.groupText + ': ';
f25d7c4a 804 text += value.group || PVE.Utils.noneText;
ced1677b
TL
805 }
806
807 return text;
808 },
809
b0a6d326
EK
810 format_content_types: function(value) {
811 var cta = [];
812
813 Ext.each(value.split(',').sort(), function(ct) {
814 if (ct === 'images') {
815 cta.push(PVE.Utils.imagesText);
816 } else if (ct === 'backup') {
817 cta.push(PVE.Utils.backupFileText);
818 } else if (ct === 'vztmpl') {
819 cta.push(PVE.Utils.vztmplText);
820 } else if (ct === 'iso') {
821 cta.push(PVE.Utils.isoImageText);
822 } else if (ct === 'rootdir') {
823 cta.push(PVE.Utils.containersText);
824 }
825 });
826
827 return cta.join(', ');
828 },
829
830 render_storage_content: function(value, metaData, record) {
831 var data = record.data;
832 if (Ext.isNumber(data.channel) &&
833 Ext.isNumber(data.id) &&
834 Ext.isNumber(data.lun)) {
0be88ae1
DC
835 return "CH " +
836 Ext.String.leftPad(data.channel,2, '0') +
b0a6d326
EK
837 " ID " + data.id + " LUN " + data.lun;
838 }
839 return data.volid.replace(/^.*:(.*\/)?/,'');
840 },
841
842 render_serverity: function (value) {
843 return PVE.Utils.log_severity_hash[value] || value;
844 },
845
846 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
847
848 if (!(record.data.uptime && Ext.isNumeric(value))) {
849 return '';
850 }
851
852 var maxcpu = record.data.maxcpu || 1;
853
854 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
855 return '';
856 }
0be88ae1 857
b0a6d326
EK
858 var per = value * 100;
859
860 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
861 },
862
863 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
864 /*jslint confusion: true */
865
866 if (!Ext.isNumeric(value)) {
867 return '';
868 }
869
870 return PVE.Utils.format_size(value);
871 },
872
873 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
874 var servertime = new Date(value * 1000);
875 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
876 },
877
0bfc799f
DC
878 calculate_mem_usage: function(data) {
879 if (!Ext.isNumeric(data.mem) ||
880 data.maxmem === 0 ||
881 data.uptime < 1) {
882 return -1;
883 }
884
885 return (data.mem / data.maxmem);
886 },
887
888 render_mem_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
889 if (!Ext.isNumeric(value) || value === -1) {
890 return '';
891 }
892 if (value > 1 ) {
893 // we got no percentage but bytes
894 var mem = value;
895 var maxmem = record.data.maxmem;
896 if (!record.data.uptime ||
897 maxmem === 0 ||
898 !Ext.isNumeric(mem)) {
899 return '';
900 }
901
902 return ((mem*100)/maxmem).toFixed(1) + " %";
903 }
904 return (value*100).toFixed(1) + " %";
905 },
906
b0a6d326
EK
907 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
908
909 var mem = value;
910 var maxmem = record.data.maxmem;
0be88ae1 911
b0a6d326
EK
912 if (!record.data.uptime) {
913 return '';
914 }
915
916 if (!(Ext.isNumeric(mem) && maxmem)) {
917 return '';
918 }
919
728f1b97 920 return PVE.Utils.render_size(value);
b0a6d326
EK
921 },
922
0bfc799f
DC
923 calculate_disk_usage: function(data) {
924
925 if (!Ext.isNumeric(data.disk) ||
926 data.type === 'qemu' ||
927 (data.type === 'lxc' && data.uptime === 0) ||
928 data.maxdisk === 0) {
929 return -1;
930 }
931
932 return (data.disk / data.maxdisk);
933 },
934
935 render_disk_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
936 if (!Ext.isNumeric(value) || value === -1) {
937 return '';
938 }
939
940 return (value * 100).toFixed(1) + " %";
941 },
942
b0a6d326
EK
943 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
944
945 var disk = value;
946 var maxdisk = record.data.maxdisk;
728f1b97 947 var type = record.data.type;
b0a6d326 948
728f1b97
DC
949 if (!Ext.isNumeric(disk) ||
950 type === 'qemu' ||
951 maxdisk === 0 ||
952 (type === 'lxc' && record.data.uptime === 0)) {
b0a6d326
EK
953 return '';
954 }
955
728f1b97 956 return PVE.Utils.render_size(value);
b0a6d326
EK
957 },
958
959 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
960
b1d8e73d
DC
961 var icon = '';
962 var gridcls = '';
963
964 switch (value) {
965 case 'lxc': icon = 'cube';
966 gridcls = '-stopped';
967 break;
968 case 'qemu': icon = 'desktop';
969 gridcls = '-stopped';
970 break;
971 case 'node': icon = 'building';
972 gridcls = '-offline';
973 break;
974 case 'storage': icon = 'database'; break;
975 case 'pool': icon = 'tags'; break;
976 default: icon = 'file';
977 }
978
979 if (value === 'lxc' || value === 'qemu') {
980 if (record.data.running && record.data.status !== 'paused') {
981 gridcls = '-running';
982 } else if (record.data.running) {
983 gridcls = '-paused';
984 }
985 if (record.data.template) {
986 icon = 'file-o';
987 gridcls = '-template-' + value;
988 }
989 } else if (value === 'node') {
990 if (record.data.running) {
a764c5f7 991 gridcls = '-online';
b1d8e73d 992 }
b0a6d326
EK
993 }
994
a764c5f7 995 var fa = '<i class="fa fa-fw x-fa-grid' + gridcls + ' fa-' + icon + '"></i> ';
b1d8e73d 996 return fa + value;
b0a6d326
EK
997 },
998
999 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
1000
1001 var uptime = value;
1002
1003 if (uptime === undefined) {
1004 return '';
1005 }
0be88ae1 1006
b0a6d326
EK
1007 if (uptime <= 0) {
1008 return '-';
1009 }
1010
1011 return PVE.Utils.format_duration_long(uptime);
1012 },
1013
1014 render_support_level: function(value, metaData, record) {
1015 return PVE.Utils.support_level_hash[value] || '-';
1016 },
1017
0be88ae1 1018 render_upid: function(value, metaData, record) {
b0a6d326
EK
1019 var type = record.data.type;
1020 var id = record.data.id;
1021
1022 return PVE.Utils.format_task_description(type, id);
1023 },
1024
1025 dialog_title: function(subject, create, isAdd) {
1026 if (create) {
1027 if (isAdd) {
1028 return gettext('Add') + ': ' + subject;
1029 } else {
1030 return gettext('Create') + ': ' + subject;
1031 }
1032 } else {
1033 return gettext('Edit') + ': ' + subject;
1034 }
1035 },
aa0819a8
WB
1036
1037 windowHostname: function() {
1038 return window.location.hostname.replace(IP6_bracket_match,
1039 function(m, addr, offset, original) { return addr; });
1040 },
0be88ae1 1041
b0a6d326
EK
1042 openDefaultConsoleWindow: function(allowSpice, vmtype, vmid, nodename, vmname) {
1043 var dv = PVE.Utils.defaultViewer(allowSpice);
1044 PVE.Utils.openConsoleWindow(dv, vmtype, vmid, nodename, vmname);
1045 },
1046
1047 openConsoleWindow: function(viewer, vmtype, vmid, nodename, vmname) {
9e361643 1048 // kvm, lxc, shell, upgrade
b0a6d326 1049
9e361643 1050 if (vmid == undefined && (vmtype === 'kvm' || vmtype === 'lxc')) {
b0a6d326
EK
1051 throw "missing vmid";
1052 }
1053
1054 if (!nodename) {
1055 throw "no nodename specified";
1056 }
1057
c7218ab3
DC
1058 if (viewer === 'html5') {
1059 PVE.Utils.openVNCViewer(vmtype, vmid, nodename, vmname);
b0a6d326
EK
1060 } else if (viewer === 'vv') {
1061 var url;
aa0819a8 1062 var params = { proxy: PVE.Utils.windowHostname() };
b0a6d326
EK
1063 if (vmtype === 'kvm') {
1064 url = '/nodes/' + nodename + '/qemu/' + vmid.toString() + '/spiceproxy';
1065 PVE.Utils.openSpiceViewer(url, params);
9e361643
DM
1066 } else if (vmtype === 'lxc') {
1067 url = '/nodes/' + nodename + '/lxc/' + vmid.toString() + '/spiceproxy';
b0a6d326
EK
1068 PVE.Utils.openSpiceViewer(url, params);
1069 } else if (vmtype === 'shell') {
1070 url = '/nodes/' + nodename + '/spiceshell';
1071 PVE.Utils.openSpiceViewer(url, params);
1072 } else if (vmtype === 'upgrade') {
1073 url = '/nodes/' + nodename + '/spiceshell';
1074 params.upgrade = 1;
1075 PVE.Utils.openSpiceViewer(url, params);
1076 }
1077 } else {
1078 throw "unknown viewer type";
1079 }
1080 },
1081
1082 defaultViewer: function(allowSpice) {
1083 var vncdefault = 'html5';
1084 var dv = PVE.VersionInfo.console || vncdefault;
1085 if (dv === 'vv' && !allowSpice) {
1086 dv = vncdefault;
1087 }
1088
1089 return dv;
1090 },
1091
c7218ab3 1092 openVNCViewer: function(vmtype, vmid, nodename, vmname) {
b0a6d326 1093 var url = Ext.urlEncode({
9e361643 1094 console: vmtype, // kvm, lxc, upgrade or shell
c7218ab3 1095 novnc: 1,
b0a6d326
EK
1096 vmid: vmid,
1097 vmname: vmname,
1098 node: nodename
1099 });
1100 var nw = window.open("?" + url, '_blank', "innerWidth=745,innerheight=427");
1101 nw.focus();
1102 },
1103
1104 openSpiceViewer: function(url, params){
1105
1106 var downloadWithName = function(uri, name) {
1107 var link = Ext.DomHelper.append(document.body, {
1108 tag: 'a',
1109 href: uri,
1110 css : 'display:none;visibility:hidden;height:0px;'
1111 });
1112
1113 // Note: we need to tell android the correct file name extension
1114 // but we do not set 'download' tag for other environments, because
1115 // It can have strange side effects (additional user prompt on firefox)
1116 var andriod = navigator.userAgent.match(/Android/i) ? true : false;
1117 if (andriod) {
1118 link.download = name;
1119 }
1120
1121 if (link.fireEvent) {
1122 link.fireEvent('onclick');
1123 } else {
1124 var evt = document.createEvent("MouseEvents");
1125 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
1126 link.dispatchEvent(evt);
1127 }
1128 };
1129
1130 PVE.Utils.API2Request({
1131 url: url,
1132 params: params,
1133 method: 'POST',
1134 failure: function(response, opts){
1135 Ext.Msg.alert('Error', response.htmlStatus);
1136 },
1137 success: function(response, opts){
1138 var raw = "[virt-viewer]\n";
1139 Ext.Object.each(response.result.data, function(k, v) {
1140 raw += k + "=" + v + "\n";
1141 });
1142 var url = 'data:application/x-virt-viewer;charset=UTF-8,' +
1143 encodeURIComponent(raw);
0be88ae1 1144
b0a6d326
EK
1145 downloadWithName(url, "pve-spice.vv");
1146 }
1147 });
1148 },
1149
0be88ae1 1150 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
b0a6d326
EK
1151 // use el.mask() instead
1152 setErrorMask: function(comp, msg) {
1153 var el = comp.el;
1154 if (!el) {
1155 return;
1156 }
1157 if (!msg) {
1158 el.unmask();
1159 } else {
1160 if (msg === true) {
1161 el.mask(gettext("Loading..."));
1162 } else {
1163 el.mask(msg);
1164 }
1165 }
1166 },
1167
1168 monStoreErrors: function(me, store) {
1169 me.mon(store, 'beforeload', function(s, operation, eOpts) {
1170 if (!me.loadCount) {
1171 me.loadCount = 0; // make sure it is numeric
1172 PVE.Utils.setErrorMask(me, true);
1173 }
1174 });
1175
1176 // only works with 'pve' proxy
1177 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
1178 me.loadCount++;
1179
1180 if (success) {
1181 PVE.Utils.setErrorMask(me, false);
1182 return;
1183 }
1184
1185 var msg;
23d3881a 1186 /*jslint nomen: true */
86826854 1187 var operation = request._operation;
b0a6d326
EK
1188 var error = operation.getError();
1189 if (error.statusText) {
1190 msg = error.statusText + ' (' + error.status + ')';
1191 } else {
1192 msg = gettext('Connection error');
1193 }
1194 PVE.Utils.setErrorMask(me, msg);
1195 });
685b7aa4 1196 },
b0a6d326 1197
685b7aa4
DC
1198 createCmdMenu: function(v, record, item, index, event) {
1199 event.stopEvent();
cc1a91be
DC
1200 if (!(v instanceof Ext.tree.View)) {
1201 v.select(record);
1202 }
685b7aa4
DC
1203 var menu;
1204
1205 if (record.data.type === 'qemu' && !record.data.template) {
1206 menu = Ext.create('PVE.qemu.CmdMenu', {
1207 pveSelNode: record
1208 });
1209 } else if (record.data.type === 'qemu' && record.data.template) {
1210 menu = Ext.create('PVE.qemu.TemplateMenu', {
1211 pveSelNode: record
1212 });
1213 } else if (record.data.type === 'lxc' && !record.data.template) {
1214 menu = Ext.create('PVE.lxc.CmdMenu', {
1215 pveSelNode: record
1216 });
1217 } else if (record.data.type === 'lxc' && record.data.template) {
1218 /* since clone does not work reliably, disable for now
1219 menu = Ext.create('PVE.lxc.TemplateMenu', {
1220 pveSelNode: record
1221 });
1222 */
1223 return;
1224 } else {
1225 return;
1226 }
1227
1228 menu.showAt(event.getXY());
1229 }
b0a6d326
EK
1230}});
1231