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