]> git.proxmox.com Git - pve-manager.git/blame - www/manager6/Utils.js
bump version to 4.1-23
[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
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() {
297 var data = [['', PVE.Utils.render_language('')]];
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') ],
552 vzcreate: ['CT', gettext('Create') ],
553 vzrestore: ['CT', gettext('Restore') ],
554 vzdestroy: ['CT', gettext('Destroy') ],
555 vzmigrate: [ 'CT', gettext('Migrate') ],
556 vzstart: ['CT', gettext('Start') ],
557 vzstop: ['CT', gettext('Stop') ],
558 vzmount: ['CT', gettext('Mount') ],
559 vzumount: ['CT', gettext('Unmount') ],
560 vzshutdown: ['CT', gettext('Shutdown') ],
561 vzsuspend: [ 'CT', gettext('Suspend') ],
562 vzresume: [ 'CT', gettext('Resume') ],
563 hamigrate: [ 'HA', gettext('Migrate') ],
564 hastart: [ 'HA', gettext('Start') ],
565 hastop: [ 'HA', gettext('Stop') ],
566 srvstart: ['SRV', gettext('Start') ],
567 srvstop: ['SRV', gettext('Stop') ],
568 srvrestart: ['SRV', gettext('Restart') ],
569 srvreload: ['SRV', gettext('Reload') ],
570 cephcreatemon: ['Ceph Monitor', gettext('Create') ],
571 cephdestroymon: ['Ceph Monitor', gettext('Destroy') ],
572 cephcreateosd: ['Ceph OSD', gettext('Create') ],
573 cephdestroyosd: ['Ceph OSD', gettext('Destroy') ],
574 imgcopy: ['', gettext('Copy data') ],
575 imgdel: ['', gettext('Erase data') ],
576 download: ['', gettext('Download') ],
577 vzdump: ['', gettext('Backup') ],
578 aptupdate: ['', gettext('Update package database') ],
579 startall: [ '', gettext('Start all VMs and Containers') ],
580 stopall: [ '', gettext('Stop all VMs and Containers') ],
581 migrateall: [ '', gettext('Migrate all VMs and Containers') ]
582 },
583
584 format_task_description: function(type, id) {
585 var farray = PVE.Utils.task_desc_table[type];
586 if (!farray) {
587 return type;
588 }
589 var prefix = farray[0];
590 var text = farray[1];
591 if (prefix) {
592 return prefix + ' ' + id + ' - ' + text;
593 }
594 return text;
595 },
596
597 parse_task_upid: function(upid) {
598 var task = {};
599
600 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]+):$/);
601 if (!res) {
602 throw "unable to parse upid '" + upid + "'";
603 }
604 task.node = res[1];
605 task.pid = parseInt(res[2], 16);
606 task.pstart = parseInt(res[3], 16);
607 task.starttime = parseInt(res[4], 16);
608 task.type = res[5];
609 task.id = res[6];
610 task.user = res[7];
611
612 task.desc = PVE.Utils.format_task_description(task.type, task.id);
613
614 return task;
615 },
616
617 format_size: function(size) {
618 /*jslint confusion: true */
619
620 if (size < 1024) {
621 return size;
622 }
623
624 var kb = size / 1024;
625
626 if (kb < 1024) {
7b9c038d 627 return kb.toFixed(0) + "KiB";
b0a6d326
EK
628 }
629
630 var mb = size / (1024*1024);
631
632 if (mb < 1024) {
7b9c038d 633 return mb.toFixed(0) + "MiB";
b0a6d326
EK
634 }
635
636 var gb = mb / 1024;
637
638 if (gb < 1024) {
7b9c038d 639 return gb.toFixed(2) + "GiB";
b0a6d326
EK
640 }
641
642 var tb = gb / 1024;
643
7b9c038d 644 return tb.toFixed(2) + "TiB";
b0a6d326
EK
645
646 },
647
648 format_html_bar: function(per, text) {
649
650 return "<div class='pve-bar-wrap'>" + text + "<div class='pve-bar-border'>" +
651 "<div class='pve-bar-inner' style='width:" + per + "%;'></div>" +
652 "</div></div>";
653
654 },
655
656 format_cpu_bar: function(per1, per2, text) {
657
658 return "<div class='pve-bar-border'>" +
659 "<div class='pve-bar-inner' style='width:" + per1 + "%;'></div>" +
660 "<div class='pve-bar-inner2' style='width:" + per2 + "%;'></div>" +
661 "<div class='pve-bar-text'>" + text + "</div>" +
662 "</div>";
663 },
664
665 format_large_bar: function(per, text) {
666
667 if (!text) {
668 text = per.toFixed(1) + "%";
669 }
670
671 return "<div class='pve-largebar-border'>" +
672 "<div class='pve-largebar-inner' style='width:" + per + "%;'></div>" +
673 "<div class='pve-largebar-text'>" + text + "</div>" +
674 "</div>";
675 },
676
677 format_duration_long: function(ut) {
678
679 var days = Math.floor(ut / 86400);
680 ut -= days*86400;
681 var hours = Math.floor(ut / 3600);
682 ut -= hours*3600;
683 var mins = Math.floor(ut / 60);
684 ut -= mins*60;
685
686 var hours_str = '00' + hours.toString();
687 hours_str = hours_str.substr(hours_str.length - 2);
688 var mins_str = "00" + mins.toString();
689 mins_str = mins_str.substr(mins_str.length - 2);
690 var ut_str = "00" + ut.toString();
691 ut_str = ut_str.substr(ut_str.length - 2);
692
693 if (days) {
694 var ds = days > 1 ? PVE.Utils.daysText : PVE.Utils.dayText;
695 return days.toString() + ' ' + ds + ' ' +
696 hours_str + ':' + mins_str + ':' + ut_str;
697 } else {
698 return hours_str + ':' + mins_str + ':' + ut_str;
699 }
700 },
701
702 format_duration_short: function(ut) {
703
704 if (ut < 60) {
705 return ut.toString() + 's';
706 }
707
708 if (ut < 3600) {
709 var mins = ut / 60;
710 return mins.toFixed(0) + 'm';
711 }
712
713 if (ut < 86400) {
714 var hours = ut / 3600;
715 return hours.toFixed(0) + 'h';
716 }
717
718 var days = ut / 86400;
719 return days.toFixed(0) + 'd';
720 },
721
722 yesText: gettext('Yes'),
723 noText: gettext('No'),
724 noneText: gettext('none'),
725 errorText: gettext('Error'),
726 unknownText: gettext('Unknown'),
727 defaultText: gettext('Default'),
728 daysText: gettext('days'),
729 dayText: gettext('day'),
730 runningText: gettext('running'),
731 stoppedText: gettext('stopped'),
732 neverText: gettext('never'),
733 totalText: gettext('Total'),
734 usedText: gettext('Used'),
735 directoryText: gettext('Directory'),
736 imagesText: gettext('Disk image'),
737 backupFileText: gettext('VZDump backup file'),
2c554952 738 vztmplText: gettext('Container template'),
b0a6d326 739 isoImageText: gettext('ISO image'),
2c554952 740 containersText: gettext('Container'),
b0a6d326
EK
741
742 format_expire: function(date) {
743 if (!date) {
744 return PVE.Utils.neverText;
745 }
746 return Ext.Date.format(date, "Y-m-d");
747 },
748
749 format_storage_type: function(value) {
750 if (value === 'dir') {
751 return PVE.Utils.directoryText;
752 } else if (value === 'nfs') {
753 return 'NFS';
754 } else if (value === 'glusterfs') {
755 return 'GlusterFS';
756 } else if (value === 'lvm') {
757 return 'LVM';
ffd96a3b
DM
758 } else if (value === 'lvmthin') {
759 return 'LVM-Thin';
b0a6d326
EK
760 } else if (value === 'iscsi') {
761 return 'iSCSI';
762 } else if (value === 'rbd') {
763 return 'RBD';
764 } else if (value === 'sheepdog') {
765 return 'Sheepdog';
766 } else if (value === 'zfs') {
767 return 'ZFS over iSCSI';
768 } else if (value === 'zfspool') {
769 return 'ZFS';
770 } else if (value === 'iscsidirect') {
771 return 'iSCSIDirect';
ffd96a3b
DM
772 } else if (value === 'drbd') {
773 return 'DRBD';
b0a6d326
EK
774 } else {
775 return PVE.Utils.unknownText;
776 }
777 },
778
779 format_boolean_with_default: function(value) {
f2782813 780 if (Ext.isDefined(value) && value !== '__default__') {
b0a6d326
EK
781 return value ? PVE.Utils.yesText : PVE.Utils.noText;
782 }
783 return PVE.Utils.defaultText;
784 },
785
786 format_boolean: function(value) {
787 return value ? PVE.Utils.yesText : PVE.Utils.noText;
788 },
789
790 format_neg_boolean: function(value) {
791 return !value ? PVE.Utils.yesText : PVE.Utils.noText;
792 },
793
794 format_content_types: function(value) {
795 var cta = [];
796
797 Ext.each(value.split(',').sort(), function(ct) {
798 if (ct === 'images') {
799 cta.push(PVE.Utils.imagesText);
800 } else if (ct === 'backup') {
801 cta.push(PVE.Utils.backupFileText);
802 } else if (ct === 'vztmpl') {
803 cta.push(PVE.Utils.vztmplText);
804 } else if (ct === 'iso') {
805 cta.push(PVE.Utils.isoImageText);
806 } else if (ct === 'rootdir') {
807 cta.push(PVE.Utils.containersText);
808 }
809 });
810
811 return cta.join(', ');
812 },
813
814 render_storage_content: function(value, metaData, record) {
815 var data = record.data;
816 if (Ext.isNumber(data.channel) &&
817 Ext.isNumber(data.id) &&
818 Ext.isNumber(data.lun)) {
819 return "CH " +
820 Ext.String.leftPad(data.channel,2, '0') +
821 " ID " + data.id + " LUN " + data.lun;
822 }
823 return data.volid.replace(/^.*:(.*\/)?/,'');
824 },
825
826 render_serverity: function (value) {
827 return PVE.Utils.log_severity_hash[value] || value;
828 },
829
830 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
831
832 if (!(record.data.uptime && Ext.isNumeric(value))) {
833 return '';
834 }
835
836 var maxcpu = record.data.maxcpu || 1;
837
838 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
839 return '';
840 }
841
842 var per = value * 100;
843
844 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
845 },
846
847 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
848 /*jslint confusion: true */
849
850 if (!Ext.isNumeric(value)) {
851 return '';
852 }
853
854 return PVE.Utils.format_size(value);
855 },
856
857 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
858 var servertime = new Date(value * 1000);
859 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
860 },
861
862 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
863
864 var mem = value;
865 var maxmem = record.data.maxmem;
866
867 if (!record.data.uptime) {
868 return '';
869 }
870
871 if (!(Ext.isNumeric(mem) && maxmem)) {
872 return '';
873 }
874
875 var per = (mem * 100) / maxmem;
876
877 return per.toFixed(1) + '%';
878 },
879
880 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
881
882 var disk = value;
883 var maxdisk = record.data.maxdisk;
884
885 if (!(Ext.isNumeric(disk) && maxdisk)) {
886 return '';
887 }
888
889 var per = (disk * 100) / maxdisk;
890
891 return per.toFixed(1) + '%';
892 },
893
894 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
895
896 var cls = 'pve-itype-icon-' + value;
897
898 if (record.data.running) {
899 metaData.tdCls = cls + "-running";
900 } else if (record.data.template) {
901 metaData.tdCls = cls + "-template";
902 } else {
903 metaData.tdCls = cls;
904 }
905
906 return value;
907 },
908
909 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
910
911 var uptime = value;
912
913 if (uptime === undefined) {
914 return '';
915 }
916
917 if (uptime <= 0) {
918 return '-';
919 }
920
921 return PVE.Utils.format_duration_long(uptime);
922 },
923
924 render_support_level: function(value, metaData, record) {
925 return PVE.Utils.support_level_hash[value] || '-';
926 },
927
928 render_upid: function(value, metaData, record) {
929 var type = record.data.type;
930 var id = record.data.id;
931
932 return PVE.Utils.format_task_description(type, id);
933 },
934
935 dialog_title: function(subject, create, isAdd) {
936 if (create) {
937 if (isAdd) {
938 return gettext('Add') + ': ' + subject;
939 } else {
940 return gettext('Create') + ': ' + subject;
941 }
942 } else {
943 return gettext('Edit') + ': ' + subject;
944 }
945 },
aa0819a8
WB
946
947 windowHostname: function() {
948 return window.location.hostname.replace(IP6_bracket_match,
949 function(m, addr, offset, original) { return addr; });
950 },
b0a6d326
EK
951
952 openDefaultConsoleWindow: function(allowSpice, vmtype, vmid, nodename, vmname) {
953 var dv = PVE.Utils.defaultViewer(allowSpice);
954 PVE.Utils.openConsoleWindow(dv, vmtype, vmid, nodename, vmname);
955 },
956
957 openConsoleWindow: function(viewer, vmtype, vmid, nodename, vmname) {
9e361643 958 // kvm, lxc, shell, upgrade
b0a6d326 959
9e361643 960 if (vmid == undefined && (vmtype === 'kvm' || vmtype === 'lxc')) {
b0a6d326
EK
961 throw "missing vmid";
962 }
963
964 if (!nodename) {
965 throw "no nodename specified";
966 }
967
c7218ab3
DC
968 if (viewer === 'html5') {
969 PVE.Utils.openVNCViewer(vmtype, vmid, nodename, vmname);
b0a6d326
EK
970 } else if (viewer === 'vv') {
971 var url;
aa0819a8 972 var params = { proxy: PVE.Utils.windowHostname() };
b0a6d326
EK
973 if (vmtype === 'kvm') {
974 url = '/nodes/' + nodename + '/qemu/' + vmid.toString() + '/spiceproxy';
975 PVE.Utils.openSpiceViewer(url, params);
9e361643
DM
976 } else if (vmtype === 'lxc') {
977 url = '/nodes/' + nodename + '/lxc/' + vmid.toString() + '/spiceproxy';
b0a6d326
EK
978 PVE.Utils.openSpiceViewer(url, params);
979 } else if (vmtype === 'shell') {
980 url = '/nodes/' + nodename + '/spiceshell';
981 PVE.Utils.openSpiceViewer(url, params);
982 } else if (vmtype === 'upgrade') {
983 url = '/nodes/' + nodename + '/spiceshell';
984 params.upgrade = 1;
985 PVE.Utils.openSpiceViewer(url, params);
986 }
987 } else {
988 throw "unknown viewer type";
989 }
990 },
991
992 defaultViewer: function(allowSpice) {
993 var vncdefault = 'html5';
994 var dv = PVE.VersionInfo.console || vncdefault;
995 if (dv === 'vv' && !allowSpice) {
996 dv = vncdefault;
997 }
998
999 return dv;
1000 },
1001
c7218ab3 1002 openVNCViewer: function(vmtype, vmid, nodename, vmname) {
b0a6d326 1003 var url = Ext.urlEncode({
9e361643 1004 console: vmtype, // kvm, lxc, upgrade or shell
c7218ab3 1005 novnc: 1,
b0a6d326
EK
1006 vmid: vmid,
1007 vmname: vmname,
1008 node: nodename
1009 });
1010 var nw = window.open("?" + url, '_blank', "innerWidth=745,innerheight=427");
1011 nw.focus();
1012 },
1013
1014 openSpiceViewer: function(url, params){
1015
1016 var downloadWithName = function(uri, name) {
1017 var link = Ext.DomHelper.append(document.body, {
1018 tag: 'a',
1019 href: uri,
1020 css : 'display:none;visibility:hidden;height:0px;'
1021 });
1022
1023 // Note: we need to tell android the correct file name extension
1024 // but we do not set 'download' tag for other environments, because
1025 // It can have strange side effects (additional user prompt on firefox)
1026 var andriod = navigator.userAgent.match(/Android/i) ? true : false;
1027 if (andriod) {
1028 link.download = name;
1029 }
1030
1031 if (link.fireEvent) {
1032 link.fireEvent('onclick');
1033 } else {
1034 var evt = document.createEvent("MouseEvents");
1035 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
1036 link.dispatchEvent(evt);
1037 }
1038 };
1039
1040 PVE.Utils.API2Request({
1041 url: url,
1042 params: params,
1043 method: 'POST',
1044 failure: function(response, opts){
1045 Ext.Msg.alert('Error', response.htmlStatus);
1046 },
1047 success: function(response, opts){
1048 var raw = "[virt-viewer]\n";
1049 Ext.Object.each(response.result.data, function(k, v) {
1050 raw += k + "=" + v + "\n";
1051 });
1052 var url = 'data:application/x-virt-viewer;charset=UTF-8,' +
1053 encodeURIComponent(raw);
1054
1055 downloadWithName(url, "pve-spice.vv");
1056 }
1057 });
1058 },
1059
1060 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
1061 // use el.mask() instead
1062 setErrorMask: function(comp, msg) {
1063 var el = comp.el;
1064 if (!el) {
1065 return;
1066 }
1067 if (!msg) {
1068 el.unmask();
1069 } else {
1070 if (msg === true) {
1071 el.mask(gettext("Loading..."));
1072 } else {
1073 el.mask(msg);
1074 }
1075 }
1076 },
1077
1078 monStoreErrors: function(me, store) {
1079 me.mon(store, 'beforeload', function(s, operation, eOpts) {
1080 if (!me.loadCount) {
1081 me.loadCount = 0; // make sure it is numeric
1082 PVE.Utils.setErrorMask(me, true);
1083 }
1084 });
1085
1086 // only works with 'pve' proxy
1087 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
1088 me.loadCount++;
1089
1090 if (success) {
1091 PVE.Utils.setErrorMask(me, false);
1092 return;
1093 }
1094
1095 var msg;
86826854 1096 var operation = request._operation;
b0a6d326
EK
1097 var error = operation.getError();
1098 if (error.statusText) {
1099 msg = error.statusText + ' (' + error.status + ')';
1100 } else {
1101 msg = gettext('Connection error');
1102 }
1103 PVE.Utils.setErrorMask(me, msg);
1104 });
1105 }
1106
1107}});
1108