]> git.proxmox.com Git - pve-manager.git/blame - www/manager6/Utils.js
add render_*_percentage and calculate_* to Utils
[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',
5a4ba3c2 93 l26: 'Linux 4.X/3.X/2.6 Kernel',
b0a6d326
EK
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) {
23d3881a 109 var fa = [];
b0a6d326
EK
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
17c71f27
DC
149 render_qemu_bios: function(value) {
150 if (!value) {
151 return PVE.Utils.defaultText + ' (SeaBIOS)';
152 } else if (value === 'seabios') {
153 return "SeaBIOS";
154 } else if (value === 'ovmf') {
155 return "OVMF (UEFI)";
156 } else {
157 return value;
158 }
159 },
160
b0a6d326
EK
161 render_scsihw: function(value) {
162 if (!value) {
163 return PVE.Utils.defaultText + ' (LSI 53C895A)';
164 } else if (value === 'lsi') {
165 return 'LSI 53C895A';
166 } else if (value === 'lsi53c810') {
167 return 'LSI 53C810';
168 } else if (value === 'megasas') {
169 return 'MegaRAID SAS 8708EM2';
170 } else if (value === 'virtio-scsi-pci') {
171 return 'VIRTIO';
172 } else if (value === 'pvscsi') {
173 return 'VMware PVSCSI';
174 } else {
175 return value;
176 }
177 },
178
179 // fixme: auto-generate this
180 // for now, please keep in sync with PVE::Tools::kvmkeymaps
181 kvm_keymaps: {
182 //ar: 'Arabic',
183 da: 'Danish',
184 de: 'German',
185 'de-ch': 'German (Swiss)',
186 'en-gb': 'English (UK)',
0a5b8747 187 'en-us': 'English (USA)',
b0a6d326
EK
188 es: 'Spanish',
189 //et: 'Estonia',
190 fi: 'Finnish',
191 //fo: 'Faroe Islands',
192 fr: 'French',
193 'fr-be': 'French (Belgium)',
194 'fr-ca': 'French (Canada)',
195 'fr-ch': 'French (Swiss)',
196 //hr: 'Croatia',
197 hu: 'Hungarian',
198 is: 'Icelandic',
199 it: 'Italian',
200 ja: 'Japanese',
201 lt: 'Lithuanian',
202 //lv: 'Latvian',
203 mk: 'Macedonian',
204 nl: 'Dutch',
205 //'nl-be': 'Dutch (Belgium)',
206 no: 'Norwegian',
207 pl: 'Polish',
208 pt: 'Portuguese',
209 'pt-br': 'Portuguese (Brazil)',
210 //ru: 'Russian',
211 sl: 'Slovenian',
212 sv: 'Swedish',
213 //th: 'Thai',
214 tr: 'Turkish'
215 },
216
217 kvm_vga_drivers: {
218 std: gettext('Standard VGA'),
219 vmware: gettext('VMWare compatible'),
220 cirrus: 'Cirrus Logic GD5446',
221 qxl: 'SPICE',
222 qxl2: 'SPICE dual monitor',
223 qxl3: 'SPICE three monitors',
224 qxl4: 'SPICE four monitors',
225 serial0: gettext('Serial terminal') + ' 0',
226 serial1: gettext('Serial terminal') + ' 1',
227 serial2: gettext('Serial terminal') + ' 2',
228 serial3: gettext('Serial terminal') + ' 3'
229 },
230
231 render_kvm_language: function (value) {
232 if (!value) {
233 return PVE.Utils.defaultText;
234 }
235 var text = PVE.Utils.kvm_keymaps[value];
236 if (text) {
237 return text + ' (' + value + ')';
238 }
239 return value;
240 },
241
242 kvm_keymap_array: function() {
f2782813 243 var data = [['__default__', PVE.Utils.render_kvm_language('')]];
b0a6d326
EK
244 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
245 data.push([key, PVE.Utils.render_kvm_language(value)]);
246 });
247
248 return data;
249 },
250
251 render_console_viewer: function(value) {
f2782813 252 if (!value || value === '__default__') {
b0a6d326 253 return PVE.Utils.defaultText + ' (HTML5)';
b0a6d326
EK
254 } else if (value === 'vv') {
255 return 'SPICE (remote-viewer)';
256 } else if (value === 'html5') {
257 return 'HTML5 (noVNC)';
258 } else {
259 return value;
260 }
261 },
262
263 language_map: {
264 zh_CN: 'Chinese',
265 ca: 'Catalan',
266 da: 'Danish',
267 en: 'English',
268 eu: 'Euskera (Basque)',
269 fr: 'French',
270 de: 'German',
271 it: 'Italian',
272 ja: 'Japanese',
273 nb: 'Norwegian (Bokmal)',
274 nn: 'Norwegian (Nynorsk)',
275 fa: 'Persian (Farsi)',
276 pl: 'Polish',
277 pt_BR: 'Portuguese (Brazil)',
278 ru: 'Russian',
279 sl: 'Slovenian',
280 es: 'Spanish',
281 sv: 'Swedish',
282 tr: 'Turkish'
283 },
284
285 render_language: function (value) {
286 if (!value) {
287 return PVE.Utils.defaultText + ' (English)';
288 }
289 var text = PVE.Utils.language_map[value];
290 if (text) {
291 return text + ' (' + value + ')';
292 }
293 return value;
294 },
295
296 language_array: function() {
d98a2c3c 297 var data = [['__default__', PVE.Utils.render_language('')]];
b0a6d326
EK
298 Ext.Object.each(PVE.Utils.language_map, function(key, value) {
299 data.push([key, PVE.Utils.render_language(value)]);
300 });
301
302 return data;
303 },
304
305 render_kvm_vga_driver: function (value) {
306 if (!value) {
307 return PVE.Utils.defaultText;
308 }
309 var text = PVE.Utils.kvm_vga_drivers[value];
310 if (text) {
311 return text + ' (' + value + ')';
312 }
313 return value;
314 },
315
316 kvm_vga_driver_array: function() {
f2782813 317 var data = [['__default__', PVE.Utils.render_kvm_vga_driver('')]];
b0a6d326
EK
318 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
319 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
320 });
321
322 return data;
323 },
324
325 render_kvm_startup: function(value) {
326 var startup = PVE.Parser.parseStartup(value);
327
328 var res = 'order=';
329 if (startup.order === undefined) {
330 res += 'any';
331 } else {
332 res += startup.order;
333 }
334 if (startup.up !== undefined) {
335 res += ',up=' + startup.up;
336 }
337 if (startup.down !== undefined) {
338 res += ',down=' + startup.down;
339 }
340
341 return res;
342 },
343
344 authOK: function() {
345 return Ext.util.Cookies.get('PVEAuthCookie');
346 },
347
348 authClear: function() {
349 Ext.util.Cookies.clear("PVEAuthCookie");
350 },
351
352 // fixme: remove - not needed?
353 gridLineHeigh: function() {
354 return 21;
355
356 //if (Ext.isGecko)
357 //return 23;
358 //return 21;
359 },
360
361 extractRequestError: function(result, verbose) {
362 var msg = gettext('Successful');
363
364 if (!result.success) {
365 msg = gettext("Unknown error");
366 if (result.message) {
367 msg = result.message;
368 if (result.status) {
369 msg += ' (' + result.status + ')';
370 }
371 }
372 if (verbose && Ext.isObject(result.errors)) {
373 msg += "<br>";
374 Ext.Object.each(result.errors, function(prop, desc) {
375 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
376 Ext.htmlEncode(desc);
377 });
378 }
379 }
380
381 return msg;
382 },
383
384 extractFormActionError: function(action) {
385 var msg;
386 switch (action.failureType) {
387 case Ext.form.action.Action.CLIENT_INVALID:
388 msg = gettext('Form fields may not be submitted with invalid values');
389 break;
390 case Ext.form.action.Action.CONNECT_FAILURE:
391 msg = gettext('Connection error');
392 var resp = action.response;
393 if (resp.status && resp.statusText) {
394 msg += " " + resp.status + ": " + resp.statusText;
395 }
396 break;
397 case Ext.form.action.Action.LOAD_FAILURE:
398 case Ext.form.action.Action.SERVER_INVALID:
399 msg = PVE.Utils.extractRequestError(action.result, true);
400 break;
401 }
402 return msg;
403 },
404
405 // Ext.Ajax.request
406 API2Request: function(reqOpts) {
407
408 var newopts = Ext.apply({
409 waitMsg: gettext('Please wait...')
410 }, reqOpts);
411
412 if (!newopts.url.match(/^\/api2/)) {
413 newopts.url = '/api2/extjs' + newopts.url;
414 }
415 delete newopts.callback;
416
417 var createWrapper = function(successFn, callbackFn, failureFn) {
418 Ext.apply(newopts, {
419 success: function(response, options) {
420 if (options.waitMsgTarget) {
421 if (PVE.Utils.toolkit === 'touch') {
422 options.waitMsgTarget.setMasked(false);
423 } else {
424 options.waitMsgTarget.setLoading(false);
425 }
426 }
427 var result = Ext.decode(response.responseText);
428 response.result = result;
429 if (!result.success) {
430 response.htmlStatus = PVE.Utils.extractRequestError(result, true);
431 Ext.callback(callbackFn, options.scope, [options, false, response]);
432 Ext.callback(failureFn, options.scope, [response, options]);
433 return;
434 }
435 Ext.callback(callbackFn, options.scope, [options, true, response]);
436 Ext.callback(successFn, options.scope, [response, options]);
437 },
438 failure: function(response, options) {
439 if (options.waitMsgTarget) {
440 if (PVE.Utils.toolkit === 'touch') {
441 options.waitMsgTarget.setMasked(false);
442 } else {
443 options.waitMsgTarget.setLoading(false);
444 }
445 }
446 response.result = {};
447 try {
448 response.result = Ext.decode(response.responseText);
449 } catch(e) {}
450 var msg = gettext('Connection error') + ' - server offline?';
451 if (response.aborted) {
452 msg = gettext('Connection error') + ' - aborted.';
453 } else if (response.timedout) {
454 msg = gettext('Connection error') + ' - Timeout.';
455 } else if (response.status && response.statusText) {
456 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
457 }
458 response.htmlStatus = msg;
459 Ext.callback(callbackFn, options.scope, [options, false, response]);
460 Ext.callback(failureFn, options.scope, [response, options]);
461 }
462 });
463 };
464
465 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
466
467 var target = newopts.waitMsgTarget;
468 if (target) {
469 if (PVE.Utils.toolkit === 'touch') {
470 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg} );
471 } else {
472 // Note: ExtJS bug - this does not work when component is not rendered
473 target.setLoading(newopts.waitMsg);
474 }
475 }
476 Ext.Ajax.request(newopts);
477 },
478
479 assemble_field_data: function(values, data) {
480 if (Ext.isObject(data)) {
481 Ext.Object.each(data, function(name, val) {
482 if (values.hasOwnProperty(name)) {
483 var bucket = values[name];
484 if (!Ext.isArray(bucket)) {
485 bucket = values[name] = [bucket];
486 }
487 if (Ext.isArray(val)) {
488 values[name] = bucket.concat(val);
489 } else {
490 bucket.push(val);
491 }
492 } else {
493 values[name] = val;
494 }
495 });
496 }
497 },
498
499 checked_command: function(orig_cmd) {
500 PVE.Utils.API2Request({
501 url: '/nodes/localhost/subscription',
502 method: 'GET',
503 //waitMsgTarget: me,
504 failure: function(response, opts) {
505 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
506 },
507 success: function(response, opts) {
508 var data = response.result.data;
509
510 if (data.status !== 'Active') {
511 Ext.Msg.show({
512 title: gettext('No valid subscription'),
513 icon: Ext.Msg.WARNING,
514 msg: PVE.Utils.noSubKeyHtml,
515 buttons: Ext.Msg.OK,
516 callback: function(btn) {
517 if (btn !== 'ok') {
518 return;
519 }
520 orig_cmd();
521 }
522 });
523 } else {
524 orig_cmd();
525 }
526 }
527 });
528 },
529
530 task_desc_table: {
531 vncproxy: [ 'VM/CT', gettext('Console') ],
532 spiceproxy: [ 'VM/CT', gettext('Console') + ' (Spice)' ],
533 vncshell: [ '', gettext('Shell') ],
534 spiceshell: [ '', gettext('Shell') + ' (Spice)' ],
535 qmsnapshot: [ 'VM', gettext('Snapshot') ],
536 qmrollback: [ 'VM', gettext('Rollback') ],
537 qmdelsnapshot: [ 'VM', gettext('Delete Snapshot') ],
538 qmcreate: [ 'VM', gettext('Create') ],
539 qmrestore: [ 'VM', gettext('Restore') ],
540 qmdestroy: [ 'VM', gettext('Destroy') ],
541 qmigrate: [ 'VM', gettext('Migrate') ],
542 qmclone: [ 'VM', gettext('Clone') ],
543 qmmove: [ 'VM', gettext('Move disk') ],
544 qmtemplate: [ 'VM', gettext('Convert to template') ],
545 qmstart: [ 'VM', gettext('Start') ],
546 qmstop: [ 'VM', gettext('Stop') ],
547 qmreset: [ 'VM', gettext('Reset') ],
548 qmshutdown: [ 'VM', gettext('Shutdown') ],
549 qmsuspend: [ 'VM', gettext('Suspend') ],
550 qmresume: [ 'VM', gettext('Resume') ],
551 qmconfig: [ 'VM', gettext('Configure') ],
16152937
DM
552 vzsnapshot: [ 'CT', gettext('Snapshot') ],
553 vzrollback: [ 'CT', gettext('Rollback') ],
554 vzdelsnapshot: [ 'CT', gettext('Delete Snapshot') ],
b0a6d326
EK
555 vzcreate: ['CT', gettext('Create') ],
556 vzrestore: ['CT', gettext('Restore') ],
557 vzdestroy: ['CT', gettext('Destroy') ],
558 vzmigrate: [ 'CT', gettext('Migrate') ],
bfade4b4
DM
559 vzclone: [ 'CT', gettext('Clone') ],
560 vztemplate: [ 'CT', gettext('Convert to template') ],
b0a6d326
EK
561 vzstart: ['CT', gettext('Start') ],
562 vzstop: ['CT', gettext('Stop') ],
563 vzmount: ['CT', gettext('Mount') ],
564 vzumount: ['CT', gettext('Unmount') ],
565 vzshutdown: ['CT', gettext('Shutdown') ],
566 vzsuspend: [ 'CT', gettext('Suspend') ],
567 vzresume: [ 'CT', gettext('Resume') ],
568 hamigrate: [ 'HA', gettext('Migrate') ],
569 hastart: [ 'HA', gettext('Start') ],
570 hastop: [ 'HA', gettext('Stop') ],
571 srvstart: ['SRV', gettext('Start') ],
572 srvstop: ['SRV', gettext('Stop') ],
573 srvrestart: ['SRV', gettext('Restart') ],
574 srvreload: ['SRV', gettext('Reload') ],
575 cephcreatemon: ['Ceph Monitor', gettext('Create') ],
576 cephdestroymon: ['Ceph Monitor', gettext('Destroy') ],
577 cephcreateosd: ['Ceph OSD', gettext('Create') ],
578 cephdestroyosd: ['Ceph OSD', gettext('Destroy') ],
579 imgcopy: ['', gettext('Copy data') ],
580 imgdel: ['', gettext('Erase data') ],
581 download: ['', gettext('Download') ],
582 vzdump: ['', gettext('Backup') ],
583 aptupdate: ['', gettext('Update package database') ],
584 startall: [ '', gettext('Start all VMs and Containers') ],
585 stopall: [ '', gettext('Stop all VMs and Containers') ],
586 migrateall: [ '', gettext('Migrate all VMs and Containers') ]
587 },
588
589 format_task_description: function(type, id) {
590 var farray = PVE.Utils.task_desc_table[type];
591 if (!farray) {
592 return type;
593 }
594 var prefix = farray[0];
595 var text = farray[1];
596 if (prefix) {
597 return prefix + ' ' + id + ' - ' + text;
598 }
599 return text;
600 },
601
602 parse_task_upid: function(upid) {
603 var task = {};
604
605 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]+):$/);
606 if (!res) {
607 throw "unable to parse upid '" + upid + "'";
608 }
609 task.node = res[1];
610 task.pid = parseInt(res[2], 16);
611 task.pstart = parseInt(res[3], 16);
612 task.starttime = parseInt(res[4], 16);
613 task.type = res[5];
614 task.id = res[6];
615 task.user = res[7];
616
617 task.desc = PVE.Utils.format_task_description(task.type, task.id);
618
619 return task;
620 },
621
622 format_size: function(size) {
623 /*jslint confusion: true */
624
02f47fe8
DC
625 var units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
626 var num = 0;
b0a6d326 627
02f47fe8
DC
628 while (size >= 1024 && ((num++)+1) < units.length) {
629 size = size / 1024;
b0a6d326
EK
630 }
631
02f47fe8 632 return size.toFixed((num > 0)?2:0) + " " + units[num] + "B";
b0a6d326
EK
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'),
2c554952 725 vztmplText: gettext('Container template'),
b0a6d326 726 isoImageText: gettext('ISO image'),
2c554952 727 containersText: gettext('Container'),
b0a6d326
EK
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';
ffd96a3b
DM
745 } else if (value === 'lvmthin') {
746 return 'LVM-Thin';
b0a6d326
EK
747 } else if (value === 'iscsi') {
748 return 'iSCSI';
749 } else if (value === 'rbd') {
750 return 'RBD';
751 } else if (value === 'sheepdog') {
752 return 'Sheepdog';
753 } else if (value === 'zfs') {
754 return 'ZFS over iSCSI';
755 } else if (value === 'zfspool') {
756 return 'ZFS';
757 } else if (value === 'iscsidirect') {
758 return 'iSCSIDirect';
ffd96a3b
DM
759 } else if (value === 'drbd') {
760 return 'DRBD';
b0a6d326
EK
761 } else {
762 return PVE.Utils.unknownText;
763 }
764 },
765
766 format_boolean_with_default: function(value) {
f2782813 767 if (Ext.isDefined(value) && value !== '__default__') {
b0a6d326
EK
768 return value ? PVE.Utils.yesText : PVE.Utils.noText;
769 }
770 return PVE.Utils.defaultText;
771 },
772
773 format_boolean: function(value) {
774 return value ? PVE.Utils.yesText : PVE.Utils.noText;
775 },
776
777 format_neg_boolean: function(value) {
778 return !value ? PVE.Utils.yesText : PVE.Utils.noText;
779 },
780
781 format_content_types: function(value) {
782 var cta = [];
783
784 Ext.each(value.split(',').sort(), function(ct) {
785 if (ct === 'images') {
786 cta.push(PVE.Utils.imagesText);
787 } else if (ct === 'backup') {
788 cta.push(PVE.Utils.backupFileText);
789 } else if (ct === 'vztmpl') {
790 cta.push(PVE.Utils.vztmplText);
791 } else if (ct === 'iso') {
792 cta.push(PVE.Utils.isoImageText);
793 } else if (ct === 'rootdir') {
794 cta.push(PVE.Utils.containersText);
795 }
796 });
797
798 return cta.join(', ');
799 },
800
801 render_storage_content: function(value, metaData, record) {
802 var data = record.data;
803 if (Ext.isNumber(data.channel) &&
804 Ext.isNumber(data.id) &&
805 Ext.isNumber(data.lun)) {
806 return "CH " +
807 Ext.String.leftPad(data.channel,2, '0') +
808 " ID " + data.id + " LUN " + data.lun;
809 }
810 return data.volid.replace(/^.*:(.*\/)?/,'');
811 },
812
813 render_serverity: function (value) {
814 return PVE.Utils.log_severity_hash[value] || value;
815 },
816
817 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
818
819 if (!(record.data.uptime && Ext.isNumeric(value))) {
820 return '';
821 }
822
823 var maxcpu = record.data.maxcpu || 1;
824
825 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
826 return '';
827 }
828
829 var per = value * 100;
830
831 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
832 },
833
834 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
835 /*jslint confusion: true */
836
837 if (!Ext.isNumeric(value)) {
838 return '';
839 }
840
841 return PVE.Utils.format_size(value);
842 },
843
844 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
845 var servertime = new Date(value * 1000);
846 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
847 },
848
0bfc799f
DC
849 calculate_mem_usage: function(data) {
850 if (!Ext.isNumeric(data.mem) ||
851 data.maxmem === 0 ||
852 data.uptime < 1) {
853 return -1;
854 }
855
856 return (data.mem / data.maxmem);
857 },
858
859 render_mem_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
860 if (!Ext.isNumeric(value) || value === -1) {
861 return '';
862 }
863 if (value > 1 ) {
864 // we got no percentage but bytes
865 var mem = value;
866 var maxmem = record.data.maxmem;
867 if (!record.data.uptime ||
868 maxmem === 0 ||
869 !Ext.isNumeric(mem)) {
870 return '';
871 }
872
873 return ((mem*100)/maxmem).toFixed(1) + " %";
874 }
875 return (value*100).toFixed(1) + " %";
876 },
877
b0a6d326
EK
878 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
879
880 var mem = value;
881 var maxmem = record.data.maxmem;
882
883 if (!record.data.uptime) {
884 return '';
885 }
886
887 if (!(Ext.isNumeric(mem) && maxmem)) {
888 return '';
889 }
890
891 var per = (mem * 100) / maxmem;
892
893 return per.toFixed(1) + '%';
894 },
895
0bfc799f
DC
896 calculate_disk_usage: function(data) {
897
898 if (!Ext.isNumeric(data.disk) ||
899 data.type === 'qemu' ||
900 (data.type === 'lxc' && data.uptime === 0) ||
901 data.maxdisk === 0) {
902 return -1;
903 }
904
905 return (data.disk / data.maxdisk);
906 },
907
908 render_disk_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
909 if (!Ext.isNumeric(value) || value === -1) {
910 return '';
911 }
912
913 return (value * 100).toFixed(1) + " %";
914 },
915
b0a6d326
EK
916 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
917
918 var disk = value;
919 var maxdisk = record.data.maxdisk;
920
921 if (!(Ext.isNumeric(disk) && maxdisk)) {
922 return '';
923 }
924
925 var per = (disk * 100) / maxdisk;
926
927 return per.toFixed(1) + '%';
928 },
929
930 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
931
b1d8e73d
DC
932 var icon = '';
933 var gridcls = '';
934
935 switch (value) {
936 case 'lxc': icon = 'cube';
937 gridcls = '-stopped';
938 break;
939 case 'qemu': icon = 'desktop';
940 gridcls = '-stopped';
941 break;
942 case 'node': icon = 'building';
943 gridcls = '-offline';
944 break;
945 case 'storage': icon = 'database'; break;
946 case 'pool': icon = 'tags'; break;
947 default: icon = 'file';
948 }
949
950 if (value === 'lxc' || value === 'qemu') {
951 if (record.data.running && record.data.status !== 'paused') {
952 gridcls = '-running';
953 } else if (record.data.running) {
954 gridcls = '-paused';
955 }
956 if (record.data.template) {
957 icon = 'file-o';
958 gridcls = '-template-' + value;
959 }
960 } else if (value === 'node') {
961 if (record.data.running) {
962 gridcls = '-online'
963 }
b0a6d326
EK
964 }
965
b1d8e73d
DC
966 var fa = '<i class="fa fa-fw x-fa-grid' + gridcls + ' fa-' + icon + '"></i> '
967 return fa + value;
b0a6d326
EK
968 },
969
970 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
971
972 var uptime = value;
973
974 if (uptime === undefined) {
975 return '';
976 }
977
978 if (uptime <= 0) {
979 return '-';
980 }
981
982 return PVE.Utils.format_duration_long(uptime);
983 },
984
985 render_support_level: function(value, metaData, record) {
986 return PVE.Utils.support_level_hash[value] || '-';
987 },
988
989 render_upid: function(value, metaData, record) {
990 var type = record.data.type;
991 var id = record.data.id;
992
993 return PVE.Utils.format_task_description(type, id);
994 },
995
996 dialog_title: function(subject, create, isAdd) {
997 if (create) {
998 if (isAdd) {
999 return gettext('Add') + ': ' + subject;
1000 } else {
1001 return gettext('Create') + ': ' + subject;
1002 }
1003 } else {
1004 return gettext('Edit') + ': ' + subject;
1005 }
1006 },
aa0819a8
WB
1007
1008 windowHostname: function() {
1009 return window.location.hostname.replace(IP6_bracket_match,
1010 function(m, addr, offset, original) { return addr; });
1011 },
b0a6d326
EK
1012
1013 openDefaultConsoleWindow: function(allowSpice, vmtype, vmid, nodename, vmname) {
1014 var dv = PVE.Utils.defaultViewer(allowSpice);
1015 PVE.Utils.openConsoleWindow(dv, vmtype, vmid, nodename, vmname);
1016 },
1017
1018 openConsoleWindow: function(viewer, vmtype, vmid, nodename, vmname) {
9e361643 1019 // kvm, lxc, shell, upgrade
b0a6d326 1020
9e361643 1021 if (vmid == undefined && (vmtype === 'kvm' || vmtype === 'lxc')) {
b0a6d326
EK
1022 throw "missing vmid";
1023 }
1024
1025 if (!nodename) {
1026 throw "no nodename specified";
1027 }
1028
c7218ab3
DC
1029 if (viewer === 'html5') {
1030 PVE.Utils.openVNCViewer(vmtype, vmid, nodename, vmname);
b0a6d326
EK
1031 } else if (viewer === 'vv') {
1032 var url;
aa0819a8 1033 var params = { proxy: PVE.Utils.windowHostname() };
b0a6d326
EK
1034 if (vmtype === 'kvm') {
1035 url = '/nodes/' + nodename + '/qemu/' + vmid.toString() + '/spiceproxy';
1036 PVE.Utils.openSpiceViewer(url, params);
9e361643
DM
1037 } else if (vmtype === 'lxc') {
1038 url = '/nodes/' + nodename + '/lxc/' + vmid.toString() + '/spiceproxy';
b0a6d326
EK
1039 PVE.Utils.openSpiceViewer(url, params);
1040 } else if (vmtype === 'shell') {
1041 url = '/nodes/' + nodename + '/spiceshell';
1042 PVE.Utils.openSpiceViewer(url, params);
1043 } else if (vmtype === 'upgrade') {
1044 url = '/nodes/' + nodename + '/spiceshell';
1045 params.upgrade = 1;
1046 PVE.Utils.openSpiceViewer(url, params);
1047 }
1048 } else {
1049 throw "unknown viewer type";
1050 }
1051 },
1052
1053 defaultViewer: function(allowSpice) {
1054 var vncdefault = 'html5';
1055 var dv = PVE.VersionInfo.console || vncdefault;
1056 if (dv === 'vv' && !allowSpice) {
1057 dv = vncdefault;
1058 }
1059
1060 return dv;
1061 },
1062
c7218ab3 1063 openVNCViewer: function(vmtype, vmid, nodename, vmname) {
b0a6d326 1064 var url = Ext.urlEncode({
9e361643 1065 console: vmtype, // kvm, lxc, upgrade or shell
c7218ab3 1066 novnc: 1,
b0a6d326
EK
1067 vmid: vmid,
1068 vmname: vmname,
1069 node: nodename
1070 });
1071 var nw = window.open("?" + url, '_blank', "innerWidth=745,innerheight=427");
1072 nw.focus();
1073 },
1074
1075 openSpiceViewer: function(url, params){
1076
1077 var downloadWithName = function(uri, name) {
1078 var link = Ext.DomHelper.append(document.body, {
1079 tag: 'a',
1080 href: uri,
1081 css : 'display:none;visibility:hidden;height:0px;'
1082 });
1083
1084 // Note: we need to tell android the correct file name extension
1085 // but we do not set 'download' tag for other environments, because
1086 // It can have strange side effects (additional user prompt on firefox)
1087 var andriod = navigator.userAgent.match(/Android/i) ? true : false;
1088 if (andriod) {
1089 link.download = name;
1090 }
1091
1092 if (link.fireEvent) {
1093 link.fireEvent('onclick');
1094 } else {
1095 var evt = document.createEvent("MouseEvents");
1096 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
1097 link.dispatchEvent(evt);
1098 }
1099 };
1100
1101 PVE.Utils.API2Request({
1102 url: url,
1103 params: params,
1104 method: 'POST',
1105 failure: function(response, opts){
1106 Ext.Msg.alert('Error', response.htmlStatus);
1107 },
1108 success: function(response, opts){
1109 var raw = "[virt-viewer]\n";
1110 Ext.Object.each(response.result.data, function(k, v) {
1111 raw += k + "=" + v + "\n";
1112 });
1113 var url = 'data:application/x-virt-viewer;charset=UTF-8,' +
1114 encodeURIComponent(raw);
1115
1116 downloadWithName(url, "pve-spice.vv");
1117 }
1118 });
1119 },
1120
1121 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
1122 // use el.mask() instead
1123 setErrorMask: function(comp, msg) {
1124 var el = comp.el;
1125 if (!el) {
1126 return;
1127 }
1128 if (!msg) {
1129 el.unmask();
1130 } else {
1131 if (msg === true) {
1132 el.mask(gettext("Loading..."));
1133 } else {
1134 el.mask(msg);
1135 }
1136 }
1137 },
1138
1139 monStoreErrors: function(me, store) {
1140 me.mon(store, 'beforeload', function(s, operation, eOpts) {
1141 if (!me.loadCount) {
1142 me.loadCount = 0; // make sure it is numeric
1143 PVE.Utils.setErrorMask(me, true);
1144 }
1145 });
1146
1147 // only works with 'pve' proxy
1148 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
1149 me.loadCount++;
1150
1151 if (success) {
1152 PVE.Utils.setErrorMask(me, false);
1153 return;
1154 }
1155
1156 var msg;
23d3881a 1157 /*jslint nomen: true */
86826854 1158 var operation = request._operation;
b0a6d326
EK
1159 var error = operation.getError();
1160 if (error.statusText) {
1161 msg = error.statusText + ' (' + error.status + ')';
1162 } else {
1163 msg = gettext('Connection error');
1164 }
1165 PVE.Utils.setErrorMask(me, msg);
1166 });
1167 }
1168
1169}});
1170