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