popup dialog to remind user about subscriptions
[pve-manager.git] / www / manager / Utils.js
1 Ext.ns('PVE');
2
3 // avoid errors when running without development tools
4 if (!Ext.isDefined(Ext.global.console)) {
5 var console = {
6 dir: function() {},
7 log: function() {}
8 };
9 }
10 console.log("Starting PVE Manager");
11
12 Ext.Ajax.defaultHeaders = {
13 'Accept': 'application/json'
14 };
15
16 // do not send '_dc' parameter
17 Ext.Ajax.disableCaching = false;
18
19 Ext.Ajax.on('beforerequest', function(conn, options) {
20 if (PVE.CSRFPreventionToken) {
21 if (!options.headers) {
22 options.headers = {};
23 }
24 options.headers.CSRFPreventionToken = PVE.CSRFPreventionToken;
25 }
26 });
27
28 // custom Vtypes
29 Ext.apply(Ext.form.field.VTypes, {
30 IPAddress: function(v) {
31 return (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/).test(v);
32 },
33 IPAddressText: gettext('Example') + ': 192.168.1.1',
34 IPAddressMask: /[\d\.]/i,
35
36 MacAddress: function(v) {
37 return (/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/).test(v);
38 },
39 MacAddressMask: /[a-fA-F0-9:]/,
40 MacAddressText: gettext('Example') + ': 01:23:45:67:89:ab',
41
42 BridgeName: function(v) {
43 return (/^vmbr\d{1,4}$/).test(v);
44 },
45 BridgeNameText: gettext('Format') + ': vmbr<b>N</b>, where 0 <= <b>N</b> <= 9999',
46
47 BondName: function(v) {
48 return (/^bond\d{1,4}$/).test(v);
49 },
50 BondNameText: gettext('Format') + ': bond<b>N</b>, where 0 <= <b>N</b> <= 9999',
51
52 QemuStartDate: function(v) {
53 return (/^(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)$/).test(v);
54 },
55 QemuStartDateText: gettext('Format') + ': "now" or "2006-06-17T16:01:21" or "2006-06-17"',
56
57 StorageId: function(v) {
58 return (/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i).test(v);
59 },
60 StorageIdText: gettext("Allowed characters") + ": 'a-z', '0-9', '-', '_', '.'",
61
62 HttpProxy: function(v) {
63 return (/^http:\/\/.*$/).test(v);
64 },
65 HttpProxyText: gettext('Example') + ": http://username:password&#64;host:port/",
66
67 DnsName: function(v) {
68 return (/^(([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)\.)*([A-Za-z0-9]([A-Za-z0-9\-]*[A-Za-z0-9])?)$/).test(v);
69 },
70 DnsNameText: gettext('This is not a valid DNS name')
71 });
72
73 // we dont want that a displayfield set the form dirty flag!
74 Ext.override(Ext.form.field.Display, {
75 isDirty: function() { return false; }
76 });
77
78 // hack: ExtJS does not display the correct value if we
79 // call setValue while the store is loading, so we need
80 // to call it again after loading
81 Ext.override(Ext.form.field.ComboBox, {
82 onLoad: function() {
83 this.setValue(this.value, false);
84 this.callOverridden(arguments);
85 }
86 });
87
88 Ext.define('PVE.Utils', { statics: {
89
90 // this class only contains static functions
91
92 log_severity_hash: {
93 0: "panic",
94 1: "alert",
95 2: "critical",
96 3: "error",
97 4: "warning",
98 5: "notice",
99 6: "info",
100 7: "debug"
101 },
102
103 support_level_hash: {
104 'c': gettext('Community'),
105 'b': gettext('Basic'),
106 's': gettext('Standard'),
107 'p': gettext('Premium')
108 },
109
110 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.',
111
112 kvm_ostypes: {
113 other: gettext('Other OS types'),
114 wxp: 'Microsoft Windows XP/2003',
115 w2k: 'Microsoft Windows 2000',
116 w2k8: 'Microsoft Windows Vista/2008',
117 win7: 'Microsoft Windows 7/2008r2',
118 win8: 'Microsoft Windows 8/2012',
119 l24: 'Linux 2.4 Kernel',
120 l26: 'Linux 3.X/2.6 Kernel'
121 },
122
123 render_kvm_ostype: function (value) {
124 if (!value) {
125 return gettext('Other OS types');
126 }
127 var text = PVE.Utils.kvm_ostypes[value];
128 if (text) {
129 return text + ' (' + value + ')';
130 }
131 return value;
132 },
133
134 render_scsihw: function(value) {
135 if (!value) {
136 return PVE.Utils.defaultText + ' (lsi)';
137 } else if (value === 'lsi') {
138 return 'LSI 53C895A';
139 } else if (value === 'megasas') {
140 return 'MegaRAID SAS 8708EM2';
141 } else if (value === 'virtio-scsi-pci') {
142 return 'VIRTIO';
143 } else {
144 return value;
145 }
146 },
147
148 // fixme: auto-generate this
149 // for now, please keep in sync with PVE::Tools::kvmkeymaps
150 kvm_keymaps: {
151 //ar: 'Arabic',
152 da: 'Danish',
153 de: 'German',
154 'de-ch': 'German (Swiss)',
155 'en-gb': 'English (UK)',
156 'en-us': 'English (USA',
157 es: 'Spanish',
158 //et: 'Estonia',
159 fi: 'Finnish',
160 //fo: 'Faroe Islands',
161 fr: 'French',
162 'fr-be': 'French (Belgium)',
163 'fr-ca': 'French (Canada)',
164 'fr-ch': 'French (Swiss)',
165 //hr: 'Croatia',
166 hu: 'Hungarian',
167 is: 'Icelandic',
168 it: 'Italian',
169 ja: 'Japanese',
170 lt: 'Lithuanian',
171 //lv: 'Latvian',
172 mk: 'Macedonian',
173 nl: 'Dutch',
174 //'nl-be': 'Dutch (Belgium)',
175 no: 'Norwegian',
176 pl: 'Polish',
177 pt: 'Portuguese',
178 'pt-br': 'Portuguese (Brazil)',
179 //ru: 'Russian',
180 sl: 'Slovenian',
181 sv: 'Swedish',
182 //th: 'Thai',
183 tr: 'Turkish'
184 },
185
186 kvm_vga_drivers: {
187 std: 'Standard VGA',
188 vmware: 'VMWare compatible',
189 cirrus: 'Cirrus Logic GD5446'
190 },
191
192 render_kvm_language: function (value) {
193 if (!value) {
194 return PVE.Utils.defaultText;
195 }
196 var text = PVE.Utils.kvm_keymaps[value];
197 if (text) {
198 return text + ' (' + value + ')';
199 }
200 return value;
201 },
202
203 kvm_keymap_array: function() {
204 var data = [['', PVE.Utils.render_kvm_language('')]];
205 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
206 data.push([key, PVE.Utils.render_kvm_language(value)]);
207 });
208
209 return data;
210 },
211
212 language_map: {
213 zh_CN: 'Chinese',
214 ca: 'Catalan',
215 ja: 'Japanese',
216 en: 'English',
217 da: 'Danish',
218 de: 'German',
219 es: 'Spanish',
220 fr: 'French',
221 it: 'Italian',
222 nb: 'Norwegian (Bokmal)',
223 nn: 'Norwegian (Nynorsk)',
224 ru: 'Russian',
225 sl: 'Slovenian',
226 sv: 'Swedish',
227 pl: 'Polish',
228 pt_BR: 'Portuguese (Brazil)',
229 tr: 'Turkish'
230 },
231
232 render_language: function (value) {
233 if (!value) {
234 return PVE.Utils.defaultText + ' (English)';
235 }
236 var text = PVE.Utils.language_map[value];
237 if (text) {
238 return text + ' (' + value + ')';
239 }
240 return value;
241 },
242
243 language_array: function() {
244 var data = [['', PVE.Utils.render_language('')]];
245 Ext.Object.each(PVE.Utils.language_map, function(key, value) {
246 data.push([key, PVE.Utils.render_language(value)]);
247 });
248
249 return data;
250 },
251
252 render_kvm_vga_driver: function (value) {
253 if (!value) {
254 return PVE.Utils.defaultText;
255 }
256 var text = PVE.Utils.kvm_vga_drivers[value];
257 if (text) {
258 return text + ' (' + value + ')';
259 }
260 return value;
261 },
262
263 kvm_vga_driver_array: function() {
264 var data = [['', PVE.Utils.render_kvm_vga_driver('')]];
265 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
266 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
267 });
268
269 return data;
270 },
271
272 render_kvm_startup: function(value) {
273 var startup = PVE.Parser.parseStartup(value);
274
275 var res = 'order=';
276 if (startup.order === undefined) {
277 res += 'any';
278 } else {
279 res += startup.order;
280 }
281 if (startup.up !== undefined) {
282 res += ',up=' + startup.up;
283 }
284 if (startup.down !== undefined) {
285 res += ',down=' + startup.down;
286 }
287
288 return res;
289 },
290
291 authOK: function() {
292 return Ext.util.Cookies.get('PVEAuthCookie');
293 },
294
295 authClear: function() {
296 Ext.util.Cookies.clear("PVEAuthCookie");
297 },
298
299 // fixme: remove - not needed?
300 gridLineHeigh: function() {
301 return 21;
302
303 //if (Ext.isGecko)
304 //return 23;
305 //return 21;
306 },
307
308 extractRequestError: function(result, verbose) {
309 var msg = gettext('Successful');
310
311 if (!result.success) {
312 msg = gettext("Unknown error");
313 if (result.message) {
314 msg = result.message;
315 if (result.status) {
316 msg += ' (' + result.status + ')';
317 }
318 }
319 if (verbose && Ext.isObject(result.errors)) {
320 msg += "<br>";
321 Ext.Object.each(result.errors, function(prop, desc) {
322 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
323 Ext.htmlEncode(desc);
324 });
325 }
326 }
327
328 return msg;
329 },
330
331 extractFormActionError: function(action) {
332 var msg;
333 switch (action.failureType) {
334 case Ext.form.action.Action.CLIENT_INVALID:
335 msg = gettext('Form fields may not be submitted with invalid values');
336 break;
337 case Ext.form.action.Action.CONNECT_FAILURE:
338 msg = gettext('Connection error');
339 var resp = action.response;
340 if (resp.status && resp.statusText) {
341 msg += " " + resp.status + ": " + resp.statusText;
342 }
343 break;
344 case Ext.form.action.Action.LOAD_FAILURE:
345 case Ext.form.action.Action.SERVER_INVALID:
346 msg = PVE.Utils.extractRequestError(action.result, true);
347 break;
348 }
349 return msg;
350 },
351
352 // Ext.Ajax.request
353 API2Request: function(reqOpts) {
354
355 var newopts = Ext.apply({
356 waitMsg: gettext('Please wait...')
357 }, reqOpts);
358
359 if (!newopts.url.match(/^\/api2/)) {
360 newopts.url = '/api2/extjs' + newopts.url;
361 }
362 delete newopts.callback;
363
364 var createWrapper = function(successFn, callbackFn, failureFn) {
365 Ext.apply(newopts, {
366 success: function(response, options) {
367 if (options.waitMsgTarget) {
368 options.waitMsgTarget.setLoading(false);
369 }
370 var result = Ext.decode(response.responseText);
371 response.result = result;
372 if (!result.success) {
373 response.htmlStatus = PVE.Utils.extractRequestError(result, true);
374 Ext.callback(callbackFn, options.scope, [options, false, response]);
375 Ext.callback(failureFn, options.scope, [response, options]);
376 return;
377 }
378 Ext.callback(callbackFn, options.scope, [options, true, response]);
379 Ext.callback(successFn, options.scope, [response, options]);
380 },
381 failure: function(response, options) {
382 if (options.waitMsgTarget) {
383 options.waitMsgTarget.setLoading(false);
384 }
385 response.result = {};
386 try {
387 response.result = Ext.decode(response.responseText);
388 } catch(e) {}
389 var msg = gettext('Connection error') + ' - server offline?';
390 if (response.aborted) {
391 msg = gettext('Connection error') + ' - aborted.';
392 } else if (response.timedout) {
393 msg = gettext('Connection error') + ' - Timeout.';
394 } else if (response.status && response.statusText) {
395 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
396 }
397 response.htmlStatus = msg;
398 Ext.callback(callbackFn, options.scope, [options, false, response]);
399 Ext.callback(failureFn, options.scope, [response, options]);
400 }
401 });
402 };
403
404 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
405
406 var target = newopts.waitMsgTarget;
407 if (target) {
408 // Note: ExtJS bug - this does not work when component is not rendered
409 target.setLoading(newopts.waitMsg);
410 }
411 Ext.Ajax.request(newopts);
412 },
413
414 assemble_field_data: function(values, data) {
415 if (Ext.isObject(data)) {
416 Ext.Object.each(data, function(name, val) {
417 if (values.hasOwnProperty(name)) {
418 var bucket = values[name];
419 if (!Ext.isArray(bucket)) {
420 bucket = values[name] = [bucket];
421 }
422 if (Ext.isArray(val)) {
423 values[name] = bucket.concat(val);
424 } else {
425 bucket.push(val);
426 }
427 } else {
428 values[name] = val;
429 }
430 });
431 }
432 },
433
434 checked_command: function(orig_cmd) {
435 PVE.Utils.API2Request({
436 url: '/nodes/localhost/subscription',
437 method: 'GET',
438 //waitMsgTarget: me,
439 failure: function(response, opts) {
440 Ext.Msg.alert('Error', response.htmlStatus);
441 },
442 success: function(response, opts) {
443 var data = response.result.data;
444
445 if (data.status !== 'Active') {
446 Ext.Msg.show({
447 title: 'No valid subscription',
448 icon: Ext.Msg.WARNING,
449 msg: PVE.Utils.noSubKeyHtml,
450 buttons: Ext.Msg.OK,
451 callback: function(btn) {
452 if (btn !== 'ok') {
453 return;
454 }
455 orig_cmd();
456 }
457 });
458 } else {
459 orig_cmd();
460 }
461 }
462 });
463 },
464
465 task_desc_table: {
466 vncproxy: [ 'VM/CT', gettext('Console') ],
467 vncshell: [ '', gettext('Shell') ],
468 qmsnapshot: [ 'VM', gettext('Snapshot') ],
469 qmrollback: [ 'VM', gettext('Rollback') ],
470 qmdelsnapshot: [ 'VM', gettext('Delete Snapshot') ],
471 qmcreate: [ 'VM', gettext('Create') ],
472 qmrestore: [ 'VM', gettext('Restore') ],
473 qmdestroy: [ 'VM', gettext('Destroy') ],
474 qmigrate: [ 'VM', gettext('Migrate') ],
475 qmclone: [ 'VM', gettext('Clone') ],
476 qmmove: [ 'VM', gettext('Move disk') ],
477 qmtemplate: [ 'VM', gettext('Convert to template') ],
478 qmstart: [ 'VM', gettext('Start') ],
479 qmstop: [ 'VM', gettext('Stop') ],
480 qmreset: [ 'VM', gettext('Reset') ],
481 qmshutdown: [ 'VM', gettext('Shutdown') ],
482 qmsuspend: [ 'VM', gettext('Suspend') ],
483 qmresume: [ 'VM', gettext('Resume') ],
484 qmconfig: [ 'VM', gettext('Configure') ],
485 vzcreate: ['CT', gettext('Create') ],
486 vzrestore: ['CT', gettext('Restore') ],
487 vzdestroy: ['CT', gettext('Destroy') ],
488 vzmigrate: [ 'CT', gettext('Migrate') ],
489 vzstart: ['CT', gettext('Start') ],
490 vzstop: ['CT', gettext('Stop') ],
491 vzmount: ['CT', gettext('Mount') ],
492 vzumount: ['CT', gettext('Unmount') ],
493 vzshutdown: ['CT', gettext('Shutdown') ],
494 hamigrate: [ 'HA', gettext('Migrate') ],
495 hastart: [ 'HA', gettext('Start') ],
496 hastop: [ 'HA', gettext('Stop') ],
497 srvstart: ['SRV', gettext('Start') ],
498 srvstop: ['SRV', gettext('Stop') ],
499 srvrestart: ['SRV', gettext('Restart') ],
500 srvreload: ['SRV', gettext('Reload') ],
501 imgcopy: ['', gettext('Copy data') ],
502 imgdel: ['', gettext('Erase data') ],
503 download: ['', gettext('Download') ],
504 vzdump: ['', gettext('Backup') ],
505 aptupdate: ['', gettext('Update package database') ],
506 aptupgrade: ['', gettext('System upgrade') ],
507 startall: [ '', gettext('Start all VMs and Containers') ],
508 stopall: [ '', gettext('Stop all VMs and Containers') ]
509 },
510
511 format_task_description: function(type, id) {
512 var farray = PVE.Utils.task_desc_table[type];
513 if (!farray) {
514 return type;
515 }
516 var prefix = farray[0];
517 var text = farray[1];
518 if (prefix) {
519 return prefix + ' ' + id + ' - ' + text;
520 }
521 return text;
522 },
523
524 parse_task_upid: function(upid) {
525 var task = {};
526
527 var res = upid.match(/^UPID:(\S+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
528 if (!res) {
529 throw "unable to parse upid '" + upid + "'";
530 }
531 task.node = res[1];
532 task.pid = parseInt(res[2], 16);
533 task.pstart = parseInt(res[3], 16);
534 task.starttime = parseInt(res[4], 16);
535 task.type = res[5];
536 task.id = res[6];
537 task.user = res[7];
538
539 task.desc = PVE.Utils.format_task_description(task.type, task.id);
540
541 return task;
542 },
543
544 format_size: function(size) {
545 /*jslint confusion: true */
546
547 if (size < 1024) {
548 return size;
549 }
550
551 var kb = size / 1024;
552
553 if (kb < 1024) {
554 return kb.toFixed(0) + "KB";
555 }
556
557 var mb = size / (1024*1024);
558
559 if (mb < 1024) {
560 return mb.toFixed(0) + "MB";
561 }
562
563 var gb = mb / 1024;
564
565 if (gb < 1024) {
566 return gb.toFixed(2) + "GB";
567 }
568
569 var tb = gb / 1024;
570
571 return tb.toFixed(2) + "TB";
572
573 },
574
575 format_html_bar: function(per, text) {
576
577 return "<div class='pve-bar-wrap'>" + text + "<div class='pve-bar-border'>" +
578 "<div class='pve-bar-inner' style='width:" + per + "%;'></div>" +
579 "</div></div>";
580
581 },
582
583 format_cpu_bar: function(per1, per2, text) {
584
585 return "<div class='pve-bar-border'>" +
586 "<div class='pve-bar-inner' style='width:" + per1 + "%;'></div>" +
587 "<div class='pve-bar-inner2' style='width:" + per2 + "%;'></div>" +
588 "<div class='pve-bar-text'>" + text + "</div>" +
589 "</div>";
590 },
591
592 format_large_bar: function(per, text) {
593
594 if (!text) {
595 text = per.toFixed(1) + "%";
596 }
597
598 return "<div class='pve-largebar-border'>" +
599 "<div class='pve-largebar-inner' style='width:" + per + "%;'></div>" +
600 "<div class='pve-largebar-text'>" + text + "</div>" +
601 "</div>";
602 },
603
604 format_duration_long: function(ut) {
605
606 var days = Math.floor(ut / 86400);
607 ut -= days*86400;
608 var hours = Math.floor(ut / 3600);
609 ut -= hours*3600;
610 var mins = Math.floor(ut / 60);
611 ut -= mins*60;
612
613 var hours_str = '00' + hours.toString();
614 hours_str = hours_str.substr(hours_str.length - 2);
615 var mins_str = "00" + mins.toString();
616 mins_str = mins_str.substr(mins_str.length - 2);
617 var ut_str = "00" + ut.toString();
618 ut_str = ut_str.substr(ut_str.length - 2);
619
620 if (days) {
621 var ds = days > 1 ? PVE.Utils.daysText : PVE.Utils.dayText;
622 return days.toString() + ' ' + ds + ' ' +
623 hours_str + ':' + mins_str + ':' + ut_str;
624 } else {
625 return hours_str + ':' + mins_str + ':' + ut_str;
626 }
627 },
628
629 format_duration_short: function(ut) {
630
631 if (ut < 60) {
632 return ut.toString() + 's';
633 }
634
635 if (ut < 3600) {
636 var mins = ut / 60;
637 return mins.toFixed(0) + 'm';
638 }
639
640 if (ut < 86400) {
641 var hours = ut / 3600;
642 return hours.toFixed(0) + 'h';
643 }
644
645 var days = ut / 86400;
646 return days.toFixed(0) + 'd';
647 },
648
649 yesText: gettext('Yes'),
650 noText: gettext('No'),
651 errorText: gettext('Error'),
652 unknownText: gettext('Unknown'),
653 defaultText: gettext('Default'),
654 daysText: gettext('days'),
655 dayText: gettext('day'),
656 runningText: gettext('running'),
657 stoppedText: gettext('stopped'),
658 neverText: gettext('never'),
659
660 format_expire: function(date) {
661 if (!date) {
662 return PVE.Utils.neverText;
663 }
664 return Ext.Date.format(date, "Y-m-d");
665 },
666
667 format_storage_type: function(value) {
668 if (value === 'dir') {
669 return 'Directory';
670 } else if (value === 'nfs') {
671 return 'NFS';
672 } else if (value === 'lvm') {
673 return 'LVM';
674 } else if (value === 'iscsi') {
675 return 'iSCSI';
676 } else if (value === 'rbd') {
677 return 'RBD';
678 } else if (value === 'sheepdog') {
679 return 'Sheepdog';
680 } else if (value === 'nexenta') {
681 return 'Nexenta';
682 } else if (value === 'iscsidirect') {
683 return 'iSCSIDirect';
684 } else {
685 return PVE.Utils.unknownText;
686 }
687 },
688
689 format_boolean_with_default: function(value) {
690 if (Ext.isDefined(value) && value !== '') {
691 return value ? PVE.Utils.yesText : PVE.Utils.noText;
692 }
693 return PVE.Utils.defaultText;
694 },
695
696 format_boolean: function(value) {
697 return value ? PVE.Utils.yesText : PVE.Utils.noText;
698 },
699
700 format_neg_boolean: function(value) {
701 return !value ? PVE.Utils.yesText : PVE.Utils.noText;
702 },
703
704 format_content_types: function(value) {
705 var cta = [];
706
707 Ext.each(value.split(',').sort(), function(ct) {
708 if (ct === 'images') {
709 cta.push('Images');
710 } else if (ct === 'backup') {
711 cta.push('Backups');
712 } else if (ct === 'vztmpl') {
713 cta.push('Templates');
714 } else if (ct === 'iso') {
715 cta.push('ISO');
716 } else if (ct === 'rootdir') {
717 cta.push('Containers');
718 }
719 });
720
721 return cta.join(', ');
722 },
723
724 render_storage_content: function(value, metaData, record) {
725 var data = record.data;
726 if (Ext.isNumber(data.channel) &&
727 Ext.isNumber(data.id) &&
728 Ext.isNumber(data.lun)) {
729 return "CH " +
730 Ext.String.leftPad(data.channel,2, '0') +
731 " ID " + data.id + " LUN " + data.lun;
732 }
733 return data.volid.replace(/^.*:(.*\/)?/,'');
734 },
735
736 render_serverity: function (value) {
737 return PVE.Utils.log_severity_hash[value] || value;
738 },
739
740 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
741
742 if (!(record.data.uptime && Ext.isNumeric(value))) {
743 return '';
744 }
745
746 var maxcpu = record.data.maxcpu || 1;
747
748 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
749 return '';
750 }
751
752 var per = value * 100;
753
754 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
755 },
756
757 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
758 /*jslint confusion: true */
759
760 if (!Ext.isNumeric(value)) {
761 return '';
762 }
763
764 return PVE.Utils.format_size(value);
765 },
766
767 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
768 var servertime = new Date(value * 1000);
769 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
770 },
771
772 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
773
774 var mem = value;
775 var maxmem = record.data.maxmem;
776
777 if (!record.data.uptime) {
778 return '';
779 }
780
781 if (!(Ext.isNumeric(mem) && maxmem)) {
782 return '';
783 }
784
785 var per = (mem * 100) / maxmem;
786
787 return per.toFixed(1) + '%';
788 },
789
790 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
791
792 var disk = value;
793 var maxdisk = record.data.maxdisk;
794
795 if (!(Ext.isNumeric(disk) && maxdisk)) {
796 return '';
797 }
798
799 var per = (disk * 100) / maxdisk;
800
801 return per.toFixed(1) + '%';
802 },
803
804 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
805
806 var cls = 'pve-itype-icon-' + value;
807
808 if (record.data.running) {
809 metaData.tdCls = cls + "-running";
810 } else if (record.data.template) {
811 metaData.tdCls = cls + "-template";
812 } else {
813 metaData.tdCls = cls;
814 }
815
816 return value;
817 },
818
819 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
820
821 var uptime = value;
822
823 if (uptime === undefined) {
824 return '';
825 }
826
827 if (uptime <= 0) {
828 return '-';
829 }
830
831 return PVE.Utils.format_duration_long(uptime);
832 },
833
834 render_support_level: function(value, metaData, record) {
835 return PVE.Utils.support_level_hash[value] || '-';
836 },
837
838 render_upid: function(value, metaData, record) {
839 var type = record.data.type;
840 var id = record.data.id;
841
842 return PVE.Utils.format_task_description(type, id);
843 },
844
845 dialog_title: function(subject, create, isAdd) {
846 if (create) {
847 if (isAdd) {
848 return gettext('Add') + ': ' + subject;
849 } else {
850 return gettext('Create') + ': ' + subject;
851 }
852 } else {
853 return gettext('Edit') + ': ' + subject;
854 }
855 },
856
857 openConoleWindow: function(vmtype, vmid, nodename, vmname) {
858 var url = Ext.urlEncode({
859 console: vmtype, // kvm, openvz or shell
860 vmid: vmid,
861 vmname: vmname,
862 node: nodename
863 });
864 var nw = window.open("?" + url, '_blank',
865 "innerWidth=745,innerheight=427");
866 nw.focus();
867 },
868
869 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
870 // use el.mask() instead
871 setErrorMask: function(comp, msg) {
872 var el = comp.el;
873 if (!el) {
874 return;
875 }
876 if (!msg) {
877 el.unmask();
878 } else {
879 if (msg === true) {
880 el.mask(gettext("Loading..."));
881 } else {
882 el.mask(msg);
883 }
884 }
885 },
886
887 monStoreErrors: function(me, store) {
888 me.mon(store, 'beforeload', function(s, operation, eOpts) {
889 if (!me.loadCount) {
890 me.loadCount = 0; // make sure it is numeric
891 PVE.Utils.setErrorMask(me, true);
892 }
893 });
894
895 // only works with 'pve' proxy
896 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
897 me.loadCount++;
898
899 if (success) {
900 PVE.Utils.setErrorMask(me, false);
901 return;
902 }
903
904 var msg;
905 var operation = request.operation;
906 var error = operation.getError();
907 if (error.statusText) {
908 msg = error.statusText + ' (' + error.status + ')';
909 } else {
910 msg = gettext('Connection error');
911 }
912 PVE.Utils.setErrorMask(me, msg);
913 });
914 }
915
916 }});
917