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