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