]> git.proxmox.com Git - pve-manager.git/blame_incremental - www/manager6/Utils.js
ui: storageSchema: add PBS and fix trailing comma
[pve-manager.git] / www / manager6 / Utils.js
... / ...
CommitLineData
1Ext.ns('PVE');
2
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
10// avoid errors when running without development tools
11if (!Ext.isDefined(Ext.global.console)) {
12 var console = {
13 log: function() {}
14 };
15}
16console.log("Starting PVE Manager");
17
18Ext.Ajax.defaultHeaders = {
19 'Accept': 'application/json'
20};
21
22/*jslint confusion: true */
23Ext.define('PVE.Utils', { utilities: {
24
25 // this singleton contains miscellaneous utilities
26
27 toolkit: undefined, // (extjs|touch), set inside Toolkit.js
28
29 bus_match: /^(ide|sata|virtio|scsi)\d+$/,
30
31 log_severity_hash: {
32 0: "panic",
33 1: "alert",
34 2: "critical",
35 3: "error",
36 4: "warning",
37 5: "notice",
38 6: "info",
39 7: "debug"
40 },
41
42 support_level_hash: {
43 'c': gettext('Community'),
44 'b': gettext('Basic'),
45 's': gettext('Standard'),
46 'p': gettext('Premium')
47 },
48
49 noSubKeyHtml: 'You do not have a valid subscription for this server. Please visit <a target="_blank" href="https://www.proxmox.com/products/proxmox-ve/subscription-service-plans">www.proxmox.com</a> to get a list of available options.',
50
51 kvm_ostypes: {
52 'Linux': [
53 { desc: '5.x - 2.6 Kernel', val: 'l26' },
54 { desc: '2.4 Kernel', val: 'l24' }
55 ],
56 'Microsoft Windows': [
57 { desc: '10/2016/2019', val: 'win10' },
58 { desc: '8.x/2012/2012r2', val: 'win8' },
59 { desc: '7/2008r2', val: 'win7' },
60 { desc: 'Vista/2008', val: 'w2k8' },
61 { desc: 'XP/2003', val: 'wxp' },
62 { desc: '2000', val: 'w2k' }
63 ],
64 'Solaris Kernel': [
65 { desc: '-', val: 'solaris'}
66 ],
67 'Other': [
68 { desc: '-', val: 'other'}
69 ]
70 },
71
72 get_health_icon: function(state, circle) {
73 if (circle === undefined) {
74 circle = false;
75 }
76
77 if (state === undefined) {
78 state = 'uknown';
79 }
80
81 var icon = 'faded fa-question';
82 switch(state) {
83 case 'good':
84 icon = 'good fa-check';
85 break;
86 case 'upgrade':
87 icon = 'warning fa-upload';
88 break;
89 case 'old':
90 icon = 'warning fa-refresh';
91 break;
92 case 'warning':
93 icon = 'warning fa-exclamation';
94 break;
95 case 'critical':
96 icon = 'critical fa-times';
97 break;
98 default: break;
99 }
100
101 if (circle) {
102 icon += '-circle';
103 }
104
105 return icon;
106 },
107
108 parse_ceph_version: function(service) {
109 if (service.ceph_version_short) {
110 return service.ceph_version_short;
111 }
112
113 if (service.ceph_version) {
114 var match = service.ceph_version.match(/version (\d+(\.\d+)*)/);
115 if (match) {
116 return match[1];
117 }
118 }
119
120 return undefined;
121 },
122
123 compare_ceph_versions: function(a, b) {
124 let avers = [];
125 let bvers = [];
126
127 if (a === b) {
128 return 0;
129 }
130
131 if (Ext.isArray(a)) {
132 avers = a.slice(); // copy array
133 } else {
134 avers = a.toString().split('.');
135 }
136
137 if (Ext.isArray(b)) {
138 bvers = b.slice(); // copy array
139 } else {
140 bvers = b.toString().split('.');
141 }
142
143 while (true) {
144 let av = avers.shift();
145 let bv = bvers.shift();
146
147 if (av === undefined && bv === undefined) {
148 return 0;
149 } else if (av === undefined) {
150 return -1;
151 } else if (bv === undefined) {
152 return 1;
153 } else {
154 let diff = parseInt(av, 10) - parseInt(bv, 10);
155 if (diff != 0) return diff;
156 // else we need to look at the next parts
157 }
158 }
159
160 },
161
162 get_ceph_icon_html: function(health, fw) {
163 var state = PVE.Utils.map_ceph_health[health];
164 var cls = PVE.Utils.get_health_icon(state);
165 if (fw) {
166 cls += ' fa-fw';
167 }
168 return "<i class='fa " + cls + "'></i> ";
169 },
170
171 map_ceph_health: {
172 'HEALTH_OK':'good',
173 'HEALTH_UPGRADE':'upgrade',
174 'HEALTH_OLD':'old',
175 'HEALTH_WARN':'warning',
176 'HEALTH_ERR':'critical'
177 },
178
179 render_ceph_health: function(healthObj) {
180 var state = {
181 iconCls: PVE.Utils.get_health_icon(),
182 text: ''
183 };
184
185 if (!healthObj || !healthObj.status) {
186 return state;
187 }
188
189 var health = PVE.Utils.map_ceph_health[healthObj.status];
190
191 state.iconCls = PVE.Utils.get_health_icon(health, true);
192 state.text = healthObj.status;
193
194 return state;
195 },
196
197 render_zfs_health: function(value) {
198 if (typeof value == 'undefined'){
199 return "";
200 }
201 var iconCls = 'question-circle';
202 switch (value) {
203 case 'AVAIL':
204 case 'ONLINE':
205 iconCls = 'check-circle good';
206 break;
207 case 'REMOVED':
208 case 'DEGRADED':
209 iconCls = 'exclamation-circle warning';
210 break;
211 case 'UNAVAIL':
212 case 'FAULTED':
213 case 'OFFLINE':
214 iconCls = 'times-circle critical';
215 break;
216 default: //unknown
217 }
218
219 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
220
221 },
222
223 get_kvm_osinfo: function(value) {
224 var info = { base: 'Other' }; // default
225 if (value) {
226 Ext.each(Object.keys(PVE.Utils.kvm_ostypes), function(k) {
227 Ext.each(PVE.Utils.kvm_ostypes[k], function(e) {
228 if (e.val === value) {
229 info = { desc: e.desc, base: k };
230 }
231 });
232 });
233 }
234 return info;
235 },
236
237 render_kvm_ostype: function (value) {
238 var osinfo = PVE.Utils.get_kvm_osinfo(value);
239 if (osinfo.desc && osinfo.desc !== '-') {
240 return osinfo.base + ' ' + osinfo.desc;
241 } else {
242 return osinfo.base;
243 }
244 },
245
246 render_hotplug_features: function (value) {
247 var fa = [];
248
249 if (!value || (value === '0')) {
250 return gettext('Disabled');
251 }
252
253 if (value === '1') {
254 value = 'disk,network,usb';
255 }
256
257 Ext.each(value.split(','), function(el) {
258 if (el === 'disk') {
259 fa.push(gettext('Disk'));
260 } else if (el === 'network') {
261 fa.push(gettext('Network'));
262 } else if (el === 'usb') {
263 fa.push('USB');
264 } else if (el === 'memory') {
265 fa.push(gettext('Memory'));
266 } else if (el === 'cpu') {
267 fa.push(gettext('CPU'));
268 } else {
269 fa.push(el);
270 }
271 });
272
273 return fa.join(', ');
274 },
275
276 render_qga_features: function(value) {
277 if (!value) {
278 return Proxmox.Utils.defaultText + ' (' + Proxmox.Utils.disabledText + ')';
279 }
280 var props = PVE.Parser.parsePropertyString(value, 'enabled');
281 if (!PVE.Parser.parseBoolean(props.enabled)) {
282 return Proxmox.Utils.disabledText;
283 }
284
285 delete props.enabled;
286 var agentstring = Proxmox.Utils.enabledText;
287
288 Ext.Object.each(props, function(key, value) {
289 var keystring = '' ;
290 agentstring += ', ' + key + ': ';
291
292 if (key === 'type') {
293 let map = {
294 isa: "ISA",
295 virtio: "VirtIO",
296 };
297 agentstring += map[value] || Proxmox.Utils.unknownText;
298 } else {
299 if (PVE.Parser.parseBoolean(value)) {
300 agentstring += Proxmox.Utils.enabledText;
301 } else {
302 agentstring += Proxmox.Utils.disabledText;
303 }
304 }
305 });
306
307 return agentstring;
308 },
309
310 render_qemu_machine: function(value) {
311 return value || (Proxmox.Utils.defaultText + ' (i440fx)');
312 },
313
314 render_qemu_bios: function(value) {
315 if (!value) {
316 return Proxmox.Utils.defaultText + ' (SeaBIOS)';
317 } else if (value === 'seabios') {
318 return "SeaBIOS";
319 } else if (value === 'ovmf') {
320 return "OVMF (UEFI)";
321 } else {
322 return value;
323 }
324 },
325
326 render_dc_ha_opts: function(value) {
327 if (!value) {
328 return Proxmox.Utils.defaultText;
329 } else {
330 return PVE.Parser.printPropertyString(value);
331 }
332 },
333 render_as_property_string: function(value) {
334 return (!value) ? Proxmox.Utils.defaultText
335 : PVE.Parser.printPropertyString(value);
336 },
337
338 render_scsihw: function(value) {
339 if (!value) {
340 return Proxmox.Utils.defaultText + ' (LSI 53C895A)';
341 } else if (value === 'lsi') {
342 return 'LSI 53C895A';
343 } else if (value === 'lsi53c810') {
344 return 'LSI 53C810';
345 } else if (value === 'megasas') {
346 return 'MegaRAID SAS 8708EM2';
347 } else if (value === 'virtio-scsi-pci') {
348 return 'VirtIO SCSI';
349 } else if (value === 'virtio-scsi-single') {
350 return 'VirtIO SCSI single';
351 } else if (value === 'pvscsi') {
352 return 'VMware PVSCSI';
353 } else {
354 return value;
355 }
356 },
357
358 render_spice_enhancements: function(values) {
359 let props = PVE.Parser.parsePropertyString(values);
360 if (Ext.Object.isEmpty(props)) {
361 return Proxmox.Utils.noneText;
362 }
363
364 let output = [];
365 if (PVE.Parser.parseBoolean(props.foldersharing)) {
366 output.push('Folder Sharing: ' + gettext('Enabled'));
367 }
368 if (props.videostreaming === 'all' || props.videostreaming === 'filter') {
369 output.push('Video Streaming: ' + props.videostreaming);
370 }
371 return output.join(', ');
372 },
373
374 // fixme: auto-generate this
375 // for now, please keep in sync with PVE::Tools::kvmkeymaps
376 kvm_keymaps: {
377 //ar: 'Arabic',
378 da: 'Danish',
379 de: 'German',
380 'de-ch': 'German (Swiss)',
381 'en-gb': 'English (UK)',
382 'en-us': 'English (USA)',
383 es: 'Spanish',
384 //et: 'Estonia',
385 fi: 'Finnish',
386 //fo: 'Faroe Islands',
387 fr: 'French',
388 'fr-be': 'French (Belgium)',
389 'fr-ca': 'French (Canada)',
390 'fr-ch': 'French (Swiss)',
391 //hr: 'Croatia',
392 hu: 'Hungarian',
393 is: 'Icelandic',
394 it: 'Italian',
395 ja: 'Japanese',
396 lt: 'Lithuanian',
397 //lv: 'Latvian',
398 mk: 'Macedonian',
399 nl: 'Dutch',
400 //'nl-be': 'Dutch (Belgium)',
401 no: 'Norwegian',
402 pl: 'Polish',
403 pt: 'Portuguese',
404 'pt-br': 'Portuguese (Brazil)',
405 //ru: 'Russian',
406 sl: 'Slovenian',
407 sv: 'Swedish',
408 //th: 'Thai',
409 tr: 'Turkish'
410 },
411
412 kvm_vga_drivers: {
413 std: gettext('Standard VGA'),
414 vmware: gettext('VMware compatible'),
415 qxl: 'SPICE',
416 qxl2: 'SPICE dual monitor',
417 qxl3: 'SPICE three monitors',
418 qxl4: 'SPICE four monitors',
419 serial0: gettext('Serial terminal') + ' 0',
420 serial1: gettext('Serial terminal') + ' 1',
421 serial2: gettext('Serial terminal') + ' 2',
422 serial3: gettext('Serial terminal') + ' 3',
423 virtio: 'VirtIO-GPU',
424 none: Proxmox.Utils.noneText
425 },
426
427 render_kvm_language: function (value) {
428 if (!value || value === '__default__') {
429 return Proxmox.Utils.defaultText;
430 }
431 var text = PVE.Utils.kvm_keymaps[value];
432 if (text) {
433 return text + ' (' + value + ')';
434 }
435 return value;
436 },
437
438 kvm_keymap_array: function() {
439 var data = [['__default__', PVE.Utils.render_kvm_language('')]];
440 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
441 data.push([key, PVE.Utils.render_kvm_language(value)]);
442 });
443
444 return data;
445 },
446
447 console_map: {
448 '__default__': Proxmox.Utils.defaultText + ' (xterm.js)',
449 'vv': 'SPICE (remote-viewer)',
450 'html5': 'HTML5 (noVNC)',
451 'xtermjs': 'xterm.js'
452 },
453
454 render_console_viewer: function(value) {
455 value = value || '__default__';
456 if (PVE.Utils.console_map[value]) {
457 return PVE.Utils.console_map[value];
458 }
459 return value;
460 },
461
462 console_viewer_array: function() {
463 return Ext.Array.map(Object.keys(PVE.Utils.console_map), function(v) {
464 return [v, PVE.Utils.render_console_viewer(v)];
465 });
466 },
467
468 render_kvm_vga_driver: function (value) {
469 if (!value) {
470 return Proxmox.Utils.defaultText;
471 }
472 var vga = PVE.Parser.parsePropertyString(value, 'type');
473 var text = PVE.Utils.kvm_vga_drivers[vga.type];
474 if (!vga.type) {
475 text = Proxmox.Utils.defaultText;
476 }
477 if (text) {
478 return text + ' (' + value + ')';
479 }
480 return value;
481 },
482
483 kvm_vga_driver_array: function() {
484 var data = [['__default__', PVE.Utils.render_kvm_vga_driver('')]];
485 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
486 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
487 });
488
489 return data;
490 },
491
492 render_kvm_startup: function(value) {
493 var startup = PVE.Parser.parseStartup(value);
494
495 var res = 'order=';
496 if (startup.order === undefined) {
497 res += 'any';
498 } else {
499 res += startup.order;
500 }
501 if (startup.up !== undefined) {
502 res += ',up=' + startup.up;
503 }
504 if (startup.down !== undefined) {
505 res += ',down=' + startup.down;
506 }
507
508 return res;
509 },
510
511 extractFormActionError: function(action) {
512 var msg;
513 switch (action.failureType) {
514 case Ext.form.action.Action.CLIENT_INVALID:
515 msg = gettext('Form fields may not be submitted with invalid values');
516 break;
517 case Ext.form.action.Action.CONNECT_FAILURE:
518 msg = gettext('Connection error');
519 var resp = action.response;
520 if (resp.status && resp.statusText) {
521 msg += " " + resp.status + ": " + resp.statusText;
522 }
523 break;
524 case Ext.form.action.Action.LOAD_FAILURE:
525 case Ext.form.action.Action.SERVER_INVALID:
526 msg = Proxmox.Utils.extractRequestError(action.result, true);
527 break;
528 }
529 return msg;
530 },
531
532 format_duration_short: function(ut) {
533
534 if (ut < 60) {
535 return ut.toFixed(1) + 's';
536 }
537
538 if (ut < 3600) {
539 var mins = ut / 60;
540 return mins.toFixed(1) + 'm';
541 }
542
543 if (ut < 86400) {
544 var hours = ut / 3600;
545 return hours.toFixed(1) + 'h';
546 }
547
548 var days = ut / 86400;
549 return days.toFixed(1) + 'd';
550 },
551
552 contentTypes: {
553 'images': gettext('Disk image'),
554 'backup': gettext('VZDump backup file'),
555 'vztmpl': gettext('Container template'),
556 'iso': gettext('ISO image'),
557 'rootdir': gettext('Container'),
558 'snippets': gettext('Snippets')
559 },
560
561 volume_is_qemu_backup: function(volid, format) {
562 return format === 'pbs-vm' || volid.match(':backup/vzdump-qemu-');
563 },
564
565 volume_is_lxc_backup: function(volid, format) {
566 return format === 'pbs-ct' || volid.match(':backup/vzdump-(lxc|openvz)-');
567 },
568
569 storageSchema: {
570 dir: {
571 name: Proxmox.Utils.directoryText,
572 ipanel: 'DirInputPanel',
573 faIcon: 'folder'
574 },
575 lvm: {
576 name: 'LVM',
577 ipanel: 'LVMInputPanel',
578 faIcon: 'folder'
579 },
580 lvmthin: {
581 name: 'LVM-Thin',
582 ipanel: 'LvmThinInputPanel',
583 faIcon: 'folder'
584 },
585 nfs: {
586 name: 'NFS',
587 ipanel: 'NFSInputPanel',
588 faIcon: 'building'
589 },
590 cifs: {
591 name: 'CIFS',
592 ipanel: 'CIFSInputPanel',
593 faIcon: 'building'
594 },
595 glusterfs: {
596 name: 'GlusterFS',
597 ipanel: 'GlusterFsInputPanel',
598 faIcon: 'building'
599 },
600 iscsi: {
601 name: 'iSCSI',
602 ipanel: 'IScsiInputPanel',
603 faIcon: 'building'
604 },
605 cephfs: {
606 name: 'CephFS',
607 ipanel: 'CephFSInputPanel',
608 faIcon: 'building'
609 },
610 pvecephfs: {
611 name: 'CephFS (PVE)',
612 ipanel: 'CephFSInputPanel',
613 hideAdd: true,
614 faIcon: 'building'
615 },
616 rbd: {
617 name: 'RBD',
618 ipanel: 'RBDInputPanel',
619 faIcon: 'building'
620 },
621 pveceph: {
622 name: 'RBD (PVE)',
623 ipanel: 'RBDInputPanel',
624 hideAdd: true,
625 faIcon: 'building'
626 },
627 zfs: {
628 name: 'ZFS over iSCSI',
629 ipanel: 'ZFSInputPanel',
630 faIcon: 'building'
631 },
632 zfspool: {
633 name: 'ZFS',
634 ipanel: 'ZFSPoolInputPanel',
635 faIcon: 'folder'
636 },
637 pbs: {
638 name: 'Proxmox Backup Server',
639 //ipanel: '', // TODO
640 hideAdd: true,
641 faIcon: 'database',
642 },
643 drbd: {
644 name: 'DRBD',
645 hideAdd: true,
646 },
647 },
648
649 sdnvnetSchema: {
650 vnet: {
651 name: 'vnet',
652 faIcon: 'folder'
653 },
654 },
655
656 sdnzoneSchema: {
657 zone: {
658 name: 'zone',
659 hideAdd: true
660 },
661 vlan: {
662 name: 'vlan',
663 ipanel: 'VlanInputPanel',
664 faIcon: 'folder'
665 },
666 qinq: {
667 name: 'qinq',
668 ipanel: 'QinQInputPanel',
669 faIcon: 'folder'
670 },
671 vxlan: {
672 name: 'vxlan',
673 ipanel: 'VxlanInputPanel',
674 faIcon: 'folder'
675 },
676 evpn: {
677 name: 'evpn',
678 ipanel: 'EvpnInputPanel',
679 faIcon: 'folder'
680 },
681 },
682
683 sdncontrollerSchema: {
684 controller: {
685 name: 'controller',
686 hideAdd: true
687 },
688 evpn: {
689 name: 'evpn',
690 ipanel: 'EvpnInputPanel',
691 faIcon: 'folder'
692 },
693 },
694
695 format_sdnvnet_type: function(value, md, record) {
696 var schema = PVE.Utils.sdnvnetSchema[value];
697 if (schema) {
698 return schema.name;
699 }
700 return Proxmox.Utils.unknownText;
701 },
702
703 format_sdnzone_type: function(value, md, record) {
704 var schema = PVE.Utils.sdnzoneSchema[value];
705 if (schema) {
706 return schema.name.toUpperCase();
707 }
708 return Proxmox.Utils.unknownText;
709 },
710
711 format_sdncontroller_type: function(value, md, record) {
712 var schema = PVE.Utils.sdncontrollerSchema[value];
713 if (schema) {
714 return schema.name;
715 }
716 return Proxmox.Utils.unknownText;
717 },
718
719 format_storage_type: function(value, md, record) {
720 if (value === 'rbd') {
721 value = (!record || record.get('monhost') ? 'rbd' : 'pveceph');
722 } else if (value === 'cephfs') {
723 value = (!record || record.get('monhost') ? 'cephfs' : 'pvecephfs');
724 }
725
726 var schema = PVE.Utils.storageSchema[value];
727 if (schema) {
728 return schema.name;
729 }
730 return Proxmox.Utils.unknownText;
731 },
732
733 format_ha: function(value) {
734 var text = Proxmox.Utils.noneText;
735
736 if (value.managed) {
737 text = value.state || Proxmox.Utils.noneText;
738
739 text += ', ' + Proxmox.Utils.groupText + ': ';
740 text += value.group || Proxmox.Utils.noneText;
741 }
742
743 return text;
744 },
745
746 format_content_types: function(value) {
747 return value.split(',').sort().map(function(ct) {
748 return PVE.Utils.contentTypes[ct] || ct;
749 }).join(', ');
750 },
751
752 render_storage_content: function(value, metaData, record) {
753 var data = record.data;
754 if (Ext.isNumber(data.channel) &&
755 Ext.isNumber(data.id) &&
756 Ext.isNumber(data.lun)) {
757 return "CH " +
758 Ext.String.leftPad(data.channel,2, '0') +
759 " ID " + data.id + " LUN " + data.lun;
760 }
761 return data.volid.replace(/^.*?:(.*?\/)?/,'');
762 },
763
764 render_serverity: function (value) {
765 return PVE.Utils.log_severity_hash[value] || value;
766 },
767
768 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
769
770 if (!(record.data.uptime && Ext.isNumeric(value))) {
771 return '';
772 }
773
774 var maxcpu = record.data.maxcpu || 1;
775
776 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
777 return '';
778 }
779
780 var per = value * 100;
781
782 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
783 },
784
785 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
786 /*jslint confusion: true */
787
788 if (!Ext.isNumeric(value)) {
789 return '';
790 }
791
792 return Proxmox.Utils.format_size(value);
793 },
794
795 render_bandwidth: function(value) {
796 if (!Ext.isNumeric(value)) {
797 return '';
798 }
799
800 return Proxmox.Utils.format_size(value) + '/s';
801 },
802
803 render_timestamp_human_readable: function(value) {
804 return Ext.Date.format(new Date(value * 1000), 'l d F Y H:i:s');
805 },
806
807 render_duration: function(value) {
808 if (value === undefined) {
809 return '-';
810 }
811 return PVE.Utils.format_duration_short(value);
812 },
813
814 calculate_mem_usage: function(data) {
815 if (!Ext.isNumeric(data.mem) ||
816 data.maxmem === 0 ||
817 data.uptime < 1) {
818 return -1;
819 }
820
821 return (data.mem / data.maxmem);
822 },
823
824 render_mem_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
825 if (!Ext.isNumeric(value) || value === -1) {
826 return '';
827 }
828 if (value > 1 ) {
829 // we got no percentage but bytes
830 var mem = value;
831 var maxmem = record.data.maxmem;
832 if (!record.data.uptime ||
833 maxmem === 0 ||
834 !Ext.isNumeric(mem)) {
835 return '';
836 }
837
838 return ((mem*100)/maxmem).toFixed(1) + " %";
839 }
840 return (value*100).toFixed(1) + " %";
841 },
842
843 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
844
845 var mem = value;
846 var maxmem = record.data.maxmem;
847
848 if (!record.data.uptime) {
849 return '';
850 }
851
852 if (!(Ext.isNumeric(mem) && maxmem)) {
853 return '';
854 }
855
856 return PVE.Utils.render_size(value);
857 },
858
859 calculate_disk_usage: function(data) {
860
861 if (!Ext.isNumeric(data.disk) ||
862 data.type === 'qemu' ||
863 (data.type === 'lxc' && data.uptime === 0) ||
864 data.maxdisk === 0) {
865 return -1;
866 }
867
868 return (data.disk / data.maxdisk);
869 },
870
871 render_disk_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
872 if (!Ext.isNumeric(value) || value === -1) {
873 return '';
874 }
875
876 return (value * 100).toFixed(1) + " %";
877 },
878
879 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
880
881 var disk = value;
882 var maxdisk = record.data.maxdisk;
883 var type = record.data.type;
884
885 if (!Ext.isNumeric(disk) ||
886 type === 'qemu' ||
887 maxdisk === 0 ||
888 (type === 'lxc' && record.data.uptime === 0)) {
889 return '';
890 }
891
892 return PVE.Utils.render_size(value);
893 },
894
895 get_object_icon_class: function(type, record) {
896 var status = '';
897 var objType = type;
898
899 if (type === 'type') {
900 // for folder view
901 objType = record.groupbyid;
902 } else if (record.template) {
903 // templates
904 objType = 'template';
905 status = type;
906 } else {
907 // everything else
908 status = record.status + ' ha-' + record.hastate;
909 }
910
911 if (record.lock) {
912 status += ' locked lock-' + record.lock;
913 }
914
915 var defaults = PVE.tree.ResourceTree.typeDefaults[objType];
916 if (defaults && defaults.iconCls) {
917 var retVal = defaults.iconCls + ' ' + status;
918 return retVal;
919 }
920
921 return '';
922 },
923
924 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
925
926 var cls = PVE.Utils.get_object_icon_class(value,record.data);
927
928 var fa = '<i class="fa-fw x-grid-icon-custom ' + cls + '"></i> ';
929 return fa + value;
930 },
931
932 render_support_level: function(value, metaData, record) {
933 return PVE.Utils.support_level_hash[value] || '-';
934 },
935
936 render_upid: function(value, metaData, record) {
937 var type = record.data.type;
938 var id = record.data.id;
939
940 return Proxmox.Utils.format_task_description(type, id);
941 },
942
943 /* render functions for new status panel */
944
945 render_usage: function(val) {
946 return (val*100).toFixed(2) + '%';
947 },
948
949 render_cpu_usage: function(val, max) {
950 return Ext.String.format(gettext('{0}% of {1}') +
951 ' ' + gettext('CPU(s)'), (val*100).toFixed(2), max);
952 },
953
954 render_size_usage: function(val, max) {
955 if (max === 0) {
956 return gettext('N/A');
957 }
958 return (val*100/max).toFixed(2) + '% '+ '(' +
959 Ext.String.format(gettext('{0} of {1}'),
960 PVE.Utils.render_size(val), PVE.Utils.render_size(max)) + ')';
961 },
962
963 /* this is different for nodes */
964 render_node_cpu_usage: function(value, record) {
965 return PVE.Utils.render_cpu_usage(value, record.cpus);
966 },
967
968 /* this is different for nodes */
969 render_node_size_usage: function(record) {
970 return PVE.Utils.render_size_usage(record.used, record.total);
971 },
972
973 render_optional_url: function(value) {
974 var match;
975 if (value && (match = value.match(/^https?:\/\//)) !== null) {
976 return '<a target="_blank" href="' + value + '">' + value + '</a>';
977 }
978 return value;
979 },
980
981 render_san: function(value) {
982 var names = [];
983 if (Ext.isArray(value)) {
984 value.forEach(function(val) {
985 if (!Ext.isNumber(val)) {
986 names.push(val);
987 }
988 });
989 return names.join('<br>');
990 }
991 return value;
992 },
993
994 render_full_name: function(firstname, metaData, record) {
995 var first = firstname || '';
996 var last = record.data.lastname || '';
997 return Ext.htmlEncode(first + " " + last);
998 },
999
1000 render_u2f_error: function(error) {
1001 var ErrorNames = {
1002 '1': gettext('Other Error'),
1003 '2': gettext('Bad Request'),
1004 '3': gettext('Configuration Unsupported'),
1005 '4': gettext('Device Ineligible'),
1006 '5': gettext('Timeout')
1007 };
1008 return "U2F Error: " + ErrorNames[error] || Proxmox.Utils.unknownText;
1009 },
1010
1011 windowHostname: function() {
1012 return window.location.hostname.replace(Proxmox.Utils.IP6_bracket_match,
1013 function(m, addr, offset, original) { return addr; });
1014 },
1015
1016 openDefaultConsoleWindow: function(consoles, vmtype, vmid, nodename, vmname, cmd) {
1017 var dv = PVE.Utils.defaultViewer(consoles);
1018 PVE.Utils.openConsoleWindow(dv, vmtype, vmid, nodename, vmname, cmd);
1019 },
1020
1021 openConsoleWindow: function(viewer, vmtype, vmid, nodename, vmname, cmd) {
1022 // kvm, lxc, shell, upgrade
1023
1024 if (vmid == undefined && (vmtype === 'kvm' || vmtype === 'lxc')) {
1025 throw "missing vmid";
1026 }
1027
1028 if (!nodename) {
1029 throw "no nodename specified";
1030 }
1031
1032 if (viewer === 'html5') {
1033 PVE.Utils.openVNCViewer(vmtype, vmid, nodename, vmname, cmd);
1034 } else if (viewer === 'xtermjs') {
1035 Proxmox.Utils.openXtermJsViewer(vmtype, vmid, nodename, vmname, cmd);
1036 } else if (viewer === 'vv') {
1037 var url;
1038 var params = { proxy: PVE.Utils.windowHostname() };
1039 if (vmtype === 'kvm') {
1040 url = '/nodes/' + nodename + '/qemu/' + vmid.toString() + '/spiceproxy';
1041 PVE.Utils.openSpiceViewer(url, params);
1042 } else if (vmtype === 'lxc') {
1043 url = '/nodes/' + nodename + '/lxc/' + vmid.toString() + '/spiceproxy';
1044 PVE.Utils.openSpiceViewer(url, params);
1045 } else if (vmtype === 'shell') {
1046 url = '/nodes/' + nodename + '/spiceshell';
1047 PVE.Utils.openSpiceViewer(url, params);
1048 } else if (vmtype === 'upgrade') {
1049 url = '/nodes/' + nodename + '/spiceshell';
1050 params.upgrade = 1;
1051 PVE.Utils.openSpiceViewer(url, params);
1052 } else if (vmtype === 'cmd') {
1053 url = '/nodes/' + nodename + '/spiceshell';
1054 params.cmd = cmd;
1055 PVE.Utils.openSpiceViewer(url, params);
1056 }
1057 } else {
1058 throw "unknown viewer type";
1059 }
1060 },
1061
1062 defaultViewer: function(consoles) {
1063
1064 var allowSpice, allowXtermjs;
1065
1066 if (consoles === true) {
1067 allowSpice = true;
1068 allowXtermjs = true;
1069 } else if (typeof consoles === 'object') {
1070 allowSpice = consoles.spice;
1071 allowXtermjs = !!consoles.xtermjs;
1072 }
1073 var dv = PVE.VersionInfo.console || 'xtermjs';
1074 if (dv === 'vv' && !allowSpice) {
1075 dv = (allowXtermjs) ? 'xtermjs' : 'html5';
1076 } else if (dv === 'xtermjs' && !allowXtermjs) {
1077 dv = (allowSpice) ? 'vv' : 'html5';
1078 }
1079
1080 return dv;
1081 },
1082
1083 openVNCViewer: function(vmtype, vmid, nodename, vmname, cmd) {
1084 let scaling = 'off';
1085 if (Proxmox.Utils.toolkit !== 'touch') {
1086 var sp = Ext.state.Manager.getProvider();
1087 scaling = sp.get('novnc-scaling', 'off');
1088 }
1089 var url = Ext.Object.toQueryString({
1090 console: vmtype, // kvm, lxc, upgrade or shell
1091 novnc: 1,
1092 vmid: vmid,
1093 vmname: vmname,
1094 node: nodename,
1095 resize: scaling,
1096 cmd: cmd
1097 });
1098 var nw = window.open("?" + url, '_blank', "innerWidth=745,innerheight=427");
1099 if (nw) {
1100 nw.focus();
1101 }
1102 },
1103
1104 openSpiceViewer: function(url, params){
1105
1106 var downloadWithName = function(uri, name) {
1107 var link = Ext.DomHelper.append(document.body, {
1108 tag: 'a',
1109 href: uri,
1110 css : 'display:none;visibility:hidden;height:0px;'
1111 });
1112
1113 // Note: we need to tell android the correct file name extension
1114 // but we do not set 'download' tag for other environments, because
1115 // It can have strange side effects (additional user prompt on firefox)
1116 var andriod = navigator.userAgent.match(/Android/i) ? true : false;
1117 if (andriod) {
1118 link.download = name;
1119 }
1120
1121 if (link.fireEvent) {
1122 link.fireEvent('onclick');
1123 } else {
1124 var evt = document.createEvent("MouseEvents");
1125 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
1126 link.dispatchEvent(evt);
1127 }
1128 };
1129
1130 Proxmox.Utils.API2Request({
1131 url: url,
1132 params: params,
1133 method: 'POST',
1134 failure: function(response, opts){
1135 Ext.Msg.alert('Error', response.htmlStatus);
1136 },
1137 success: function(response, opts){
1138 var raw = "[virt-viewer]\n";
1139 Ext.Object.each(response.result.data, function(k, v) {
1140 raw += k + "=" + v + "\n";
1141 });
1142 var url = 'data:application/x-virt-viewer;charset=UTF-8,' +
1143 encodeURIComponent(raw);
1144
1145 downloadWithName(url, "pve-spice.vv");
1146 }
1147 });
1148 },
1149
1150 openTreeConsole: function(tree, record, item, index, e) {
1151 e.stopEvent();
1152 var nodename = record.data.node;
1153 var vmid = record.data.vmid;
1154 var vmname = record.data.name;
1155 if (record.data.type === 'qemu' && !record.data.template) {
1156 Proxmox.Utils.API2Request({
1157 url: '/nodes/' + nodename + '/qemu/' + vmid + '/status/current',
1158 failure: function(response, opts) {
1159 Ext.Msg.alert('Error', response.htmlStatus);
1160 },
1161 success: function(response, opts) {
1162 let conf = response.result.data;
1163 var consoles = {
1164 spice: !!conf.spice,
1165 xtermjs: !!conf.serial,
1166 };
1167 PVE.Utils.openDefaultConsoleWindow(consoles, 'kvm', vmid, nodename, vmname);
1168 }
1169 });
1170 } else if (record.data.type === 'lxc' && !record.data.template) {
1171 PVE.Utils.openDefaultConsoleWindow(true, 'lxc', vmid, nodename, vmname);
1172 }
1173 },
1174
1175 // test automation helper
1176 call_menu_handler: function(menu, text) {
1177
1178 var list = menu.query('menuitem');
1179
1180 Ext.Array.each(list, function(item) {
1181 if (item.text === text) {
1182 if (item.handler) {
1183 item.handler();
1184 return 1;
1185 } else {
1186 return undefined;
1187 }
1188 }
1189 });
1190 },
1191
1192 createCmdMenu: function(v, record, item, index, event) {
1193 event.stopEvent();
1194 if (!(v instanceof Ext.tree.View)) {
1195 v.select(record);
1196 }
1197 var menu;
1198 var template = !!record.data.template;
1199 var type = record.data.type;
1200
1201 if (template) {
1202 if (type === 'qemu' || type == 'lxc') {
1203 menu = Ext.create('PVE.menu.TemplateMenu', {
1204 pveSelNode: record
1205 });
1206 }
1207 } else if (type === 'qemu' ||
1208 type === 'lxc' ||
1209 type === 'node') {
1210 menu = Ext.create('PVE.' + type + '.CmdMenu', {
1211 pveSelNode: record,
1212 nodename: record.data.node
1213 });
1214 } else {
1215 return;
1216 }
1217
1218 menu.showAt(event.getXY());
1219 return menu;
1220 },
1221
1222 // helper for deleting field which are set to there default values
1223 delete_if_default: function(values, fieldname, default_val, create) {
1224 if (values[fieldname] === '' || values[fieldname] === default_val) {
1225 if (!create) {
1226 if (values['delete']) {
1227 values['delete'] += ',' + fieldname;
1228 } else {
1229 values['delete'] = fieldname;
1230 }
1231 }
1232
1233 delete values[fieldname];
1234 }
1235 },
1236
1237 loadSSHKeyFromFile: function(file, callback) {
1238 // ssh-keygen produces 740 bytes for an average 4096 bit rsa key, with
1239 // a user@host comment, 1420 for 8192 bits; current max is 16kbit
1240 // assume: 740*8 for max. 32kbit (5920 byte file)
1241 // round upwards to nearest nice number => 8192 bytes, leaves lots of comment space
1242 if (file.size > 8192) {
1243 Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size);
1244 return;
1245 }
1246 /*global
1247 FileReader
1248 */
1249 var reader = new FileReader();
1250 reader.onload = function(evt) {
1251 callback(evt.target.result);
1252 };
1253 reader.readAsText(file);
1254 },
1255
1256 diskControllerMaxIDs: {
1257 ide: 4,
1258 sata: 6,
1259 scsi: 31,
1260 virtio: 16,
1261 },
1262
1263 // types is either undefined (all busses), an array of busses, or a single bus
1264 forEachBus: function(types, func) {
1265 var busses = Object.keys(PVE.Utils.diskControllerMaxIDs);
1266 var i, j, count, cont;
1267
1268 if (Ext.isArray(types)) {
1269 busses = types;
1270 } else if (Ext.isDefined(types)) {
1271 busses = [ types ];
1272 }
1273
1274 // check if we only have valid busses
1275 for (i = 0; i < busses.length; i++) {
1276 if (!PVE.Utils.diskControllerMaxIDs[busses[i]]) {
1277 throw "invalid bus: '" + busses[i] + "'";
1278 }
1279 }
1280
1281 for (i = 0; i < busses.length; i++) {
1282 count = PVE.Utils.diskControllerMaxIDs[busses[i]];
1283 for (j = 0; j < count; j++) {
1284 cont = func(busses[i], j);
1285 if (!cont && cont !== undefined) {
1286 return;
1287 }
1288 }
1289 }
1290 },
1291
1292 mp_counts: { mps: 256, unused: 256 },
1293
1294 forEachMP: function(func, includeUnused) {
1295 var i, cont;
1296 for (i = 0; i < PVE.Utils.mp_counts.mps; i++) {
1297 cont = func('mp', i);
1298 if (!cont && cont !== undefined) {
1299 return;
1300 }
1301 }
1302
1303 if (!includeUnused) {
1304 return;
1305 }
1306
1307 for (i = 0; i < PVE.Utils.mp_counts.unused; i++) {
1308 cont = func('unused', i);
1309 if (!cont && cont !== undefined) {
1310 return;
1311 }
1312 }
1313 },
1314
1315 hardware_counts: { net: 32, usb: 5, hostpci: 16, audio: 1, efidisk: 1, serial: 4, rng: 1 },
1316
1317 cleanEmptyObjectKeys: function (obj) {
1318 var propName;
1319 for (propName in obj) {
1320 if (obj.hasOwnProperty(propName)) {
1321 if (obj[propName] === null || obj[propName] === undefined) {
1322 delete obj[propName];
1323 }
1324 }
1325 }
1326 },
1327
1328 handleStoreErrorOrMask: function(me, store, regex, callback) {
1329
1330 me.mon(store, 'load', function (proxy, response, success, operation) {
1331
1332 if (success) {
1333 Proxmox.Utils.setErrorMask(me, false);
1334 return;
1335 }
1336 var msg;
1337
1338 if (operation.error.statusText) {
1339 if (operation.error.statusText.match(regex)) {
1340 callback(me, operation.error);
1341 return;
1342 } else {
1343 msg = operation.error.statusText + ' (' + operation.error.status + ')';
1344 }
1345 } else {
1346 msg = gettext('Connection error');
1347 }
1348 Proxmox.Utils.setErrorMask(me, msg);
1349 });
1350 },
1351
1352 showCephInstallOrMask: function(container, msg, nodename, callback){
1353 var regex = new RegExp("not (installed|initialized)", "i");
1354 if (msg.match(regex)) {
1355 if (Proxmox.UserName === 'root@pam') {
1356 container.el.mask();
1357 if (!container.down('pveCephInstallWindow')){
1358 var isInstalled = msg.match(/not initialized/i) ? true : false;
1359 var win = Ext.create('PVE.ceph.Install', {
1360 nodename: nodename
1361 });
1362 win.getViewModel().set('isInstalled', isInstalled);
1363 container.add(win);
1364 win.show();
1365 callback(win);
1366 }
1367 } else {
1368 container.mask(Ext.String.format(gettext('{0} not installed.') +
1369 ' ' + gettext('Log in as root to install.'), 'Ceph'), ['pve-static-mask']);
1370 }
1371 return true;
1372 } else {
1373 return false;
1374 }
1375 },
1376
1377 propertyStringSet: function(target, source, name, value) {
1378 if (source) {
1379 if (value === undefined) {
1380 target[name] = source;
1381 } else {
1382 target[name] = value;
1383 }
1384 } else {
1385 delete target[name];
1386 }
1387 },
1388
1389 updateColumns: function(container) {
1390 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
1391 let factor;
1392 if (mode !== 'auto') {
1393 factor = parseInt(mode, 10);
1394 if (Number.isNaN(factor)) {
1395 factor = 1;
1396 }
1397 } else {
1398 factor = container.getSize().width < 1400 ? 1 : 2;
1399 }
1400
1401 if (container.oldFactor === factor) {
1402 return;
1403 }
1404
1405 let items = container.query('>'); // direct childs
1406 factor = Math.min(factor, items.length);
1407 container.oldFactor = factor;
1408
1409 items.forEach((item) => {
1410 item.columnWidth = 1 / factor;
1411 });
1412
1413 // we have to update the layout twice, since the first layout change
1414 // can trigger the scrollbar which reduces the amount of space left
1415 container.updateLayout();
1416 container.updateLayout();
1417 },
1418
1419 forEachCorosyncLink: function(nodeinfo, cb) {
1420 let re = /(?:ring|link)(\d+)_addr/;
1421 Ext.iterate(nodeinfo, (prop, val) => {
1422 let match = re.exec(prop);
1423 if (match) {
1424 cb(Number(match[1]), val);
1425 }
1426 });
1427 },
1428},
1429
1430 singleton: true,
1431 constructor: function() {
1432 var me = this;
1433 Ext.apply(me, me.utilities);
1434 }
1435
1436});