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