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