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