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