]> git.proxmox.com Git - pve-manager.git/blob - www/manager6/Utils.js
7bf3955a19dc66b1442a0225991b5561e0ddc5b2
[pve-manager.git] / www / manager6 / Utils.js
1 Ext.ns('PVE');
2
3 console.log("Starting Proxmox VE Manager");
4
5 Ext.Ajax.defaultHeaders = {
6 'Accept': 'application/json',
7 };
8
9 Ext.define('PVE.Utils', {
10 utilities: {
11
12 // this singleton contains miscellaneous utilities
13
14 toolkit: undefined, // (extjs|touch), set inside Toolkit.js
15
16 bus_match: /^(ide|sata|virtio|scsi)(\d+)$/,
17
18 log_severity_hash: {
19 0: "panic",
20 1: "alert",
21 2: "critical",
22 3: "error",
23 4: "warning",
24 5: "notice",
25 6: "info",
26 7: "debug",
27 },
28
29 support_level_hash: {
30 'c': gettext('Community'),
31 'b': gettext('Basic'),
32 's': gettext('Standard'),
33 'p': gettext('Premium'),
34 },
35
36 noSubKeyHtml: 'You do not have a valid subscription for this server. Please visit '
37 +'<a target="_blank" href="https://www.proxmox.com/products/proxmox-ve/subscription-service-plans">'
38 +'www.proxmox.com</a> to get a list of available options.',
39
40 kvm_ostypes: {
41 'Linux': [
42 { desc: '6.x - 2.6 Kernel', val: 'l26' },
43 { desc: '2.4 Kernel', val: 'l24' },
44 ],
45 'Microsoft Windows': [
46 { desc: '11/2022', val: 'win11' },
47 { desc: '10/2016/2019', val: 'win10' },
48 { desc: '8.x/2012/2012r2', val: 'win8' },
49 { desc: '7/2008r2', val: 'win7' },
50 { desc: 'Vista/2008', val: 'w2k8' },
51 { desc: 'XP/2003', val: 'wxp' },
52 { desc: '2000', val: 'w2k' },
53 ],
54 'Solaris Kernel': [
55 { desc: '-', val: 'solaris' },
56 ],
57 'Other': [
58 { desc: '-', val: 'other' },
59 ],
60 },
61
62 is_windows: function(ostype) {
63 for (let entry of PVE.Utils.kvm_ostypes['Microsoft Windows']) {
64 if (entry.val === ostype) {
65 return true;
66 }
67 }
68 return false;
69 },
70
71 get_health_icon: function(state, circle) {
72 if (circle === undefined) {
73 circle = false;
74 }
75
76 if (state === undefined) {
77 state = 'uknown';
78 }
79
80 var icon = 'faded fa-question';
81 switch (state) {
82 case 'good':
83 icon = 'good fa-check';
84 break;
85 case 'upgrade':
86 icon = 'warning fa-upload';
87 break;
88 case 'old':
89 icon = 'warning fa-refresh';
90 break;
91 case 'warning':
92 icon = 'warning fa-exclamation';
93 break;
94 case 'critical':
95 icon = 'critical fa-times';
96 break;
97 default: break;
98 }
99
100 if (circle) {
101 icon += '-circle';
102 }
103
104 return icon;
105 },
106
107 parse_ceph_version: function(service) {
108 if (service.ceph_version_short) {
109 return service.ceph_version_short;
110 }
111
112 if (service.ceph_version) {
113 var match = service.ceph_version.match(/version (\d+(\.\d+)*)/);
114 if (match) {
115 return match[1];
116 }
117 }
118
119 return undefined;
120 },
121
122 compare_ceph_versions: function(a, b) {
123 let avers = [];
124 let bvers = [];
125
126 if (a === b) {
127 return 0;
128 }
129
130 if (Ext.isArray(a)) {
131 avers = a.slice(); // copy array
132 } else {
133 avers = a.toString().split('.');
134 }
135
136 if (Ext.isArray(b)) {
137 bvers = b.slice(); // copy array
138 } else {
139 bvers = b.toString().split('.');
140 }
141
142 for (;;) {
143 let av = avers.shift();
144 let bv = bvers.shift();
145
146 if (av === undefined && bv === undefined) {
147 return 0;
148 } else if (av === undefined) {
149 return -1;
150 } else if (bv === undefined) {
151 return 1;
152 } else {
153 let diff = parseInt(av, 10) - parseInt(bv, 10);
154 if (diff !== 0) return diff;
155 // else we need to look at the next parts
156 }
157 }
158 },
159
160 get_ceph_icon_html: function(health, fw) {
161 var state = PVE.Utils.map_ceph_health[health];
162 var cls = PVE.Utils.get_health_icon(state);
163 if (fw) {
164 cls += ' fa-fw';
165 }
166 return "<i class='fa " + cls + "'></i> ";
167 },
168
169 map_ceph_health: {
170 'HEALTH_OK': 'good',
171 'HEALTH_UPGRADE': 'upgrade',
172 'HEALTH_OLD': 'old',
173 'HEALTH_WARN': 'warning',
174 'HEALTH_ERR': 'critical',
175 },
176
177 render_sdn_pending: function(rec, value, key, index) {
178 if (rec.data.state === undefined || rec.data.state === null) {
179 return value;
180 }
181
182 if (rec.data.state === 'deleted') {
183 if (value === undefined) {
184 return ' ';
185 } else {
186 return '<div style="text-decoration: line-through;">'+ value +'</div>';
187 }
188 } else if (rec.data.pending[key] !== undefined && rec.data.pending[key] !== null) {
189 if (rec.data.pending[key] === 'deleted') {
190 return ' ';
191 } else {
192 return rec.data.pending[key];
193 }
194 }
195 return value;
196 },
197
198 render_sdn_pending_state: function(rec, value) {
199 if (value === undefined || value === null) {
200 return ' ';
201 }
202
203 let icon = `<i class="fa fa-fw fa-refresh warning"></i>`;
204
205 if (value === 'deleted') {
206 return '<span>' + icon + value + '</span>';
207 }
208
209 let tip = gettext('Pending Changes') + ': <br>';
210
211 for (const [key, keyvalue] of Object.entries(rec.data.pending)) {
212 if ((rec.data[key] !== undefined && rec.data.pending[key] !== rec.data[key]) ||
213 rec.data[key] === undefined
214 ) {
215 tip += `${key}: ${keyvalue} <br>`;
216 }
217 }
218 return '<span data-qtip="' + tip + '">'+ icon + value + '</span>';
219 },
220
221 render_ceph_health: function(healthObj) {
222 var state = {
223 iconCls: PVE.Utils.get_health_icon(),
224 text: '',
225 };
226
227 if (!healthObj || !healthObj.status) {
228 return state;
229 }
230
231 var health = PVE.Utils.map_ceph_health[healthObj.status];
232
233 state.iconCls = PVE.Utils.get_health_icon(health, true);
234 state.text = healthObj.status;
235
236 return state;
237 },
238
239 render_zfs_health: function(value) {
240 if (typeof value === 'undefined') {
241 return "";
242 }
243 var iconCls = 'question-circle';
244 switch (value) {
245 case 'AVAIL':
246 case 'ONLINE':
247 iconCls = 'check-circle good';
248 break;
249 case 'REMOVED':
250 case 'DEGRADED':
251 iconCls = 'exclamation-circle warning';
252 break;
253 case 'UNAVAIL':
254 case 'FAULTED':
255 case 'OFFLINE':
256 iconCls = 'times-circle critical';
257 break;
258 default: //unknown
259 }
260
261 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
262 },
263
264 render_pbs_fingerprint: fp => fp.substring(0, 23),
265
266 render_backup_encryption: function(v, meta, record) {
267 if (!v) {
268 return gettext('No');
269 }
270
271 let tip = '';
272 if (v.match(/^[a-fA-F0-9]{2}:/)) { // fingerprint
273 tip = `Key fingerprint ${PVE.Utils.render_pbs_fingerprint(v)}`;
274 }
275 let icon = `<i class="fa fa-fw fa-lock good"></i>`;
276 return `<span data-qtip="${tip}">${icon} ${gettext('Encrypted')}</span>`;
277 },
278
279 render_backup_verification: function(v, meta, record) {
280 let i = (cls, txt) => `<i class="fa fa-fw fa-${cls}"></i> ${txt}`;
281 if (v === undefined || v === null) {
282 return i('question-circle-o warning', gettext('None'));
283 }
284 let tip = "";
285 let txt = gettext('Failed');
286 let iconCls = 'times critical';
287 if (v.state === 'ok') {
288 txt = gettext('OK');
289 iconCls = 'check good';
290 let now = Date.now() / 1000;
291 let task = Proxmox.Utils.parse_task_upid(v.upid);
292 let verify_time = Proxmox.Utils.render_timestamp(task.starttime);
293 tip = `Last verify task started on ${verify_time}`;
294 if (now - v.starttime > 30 * 24 * 60 * 60) {
295 tip = `Last verify task over 30 days ago: ${verify_time}`;
296 iconCls = 'check warning';
297 }
298 }
299 return `<span data-qtip="${tip}"> ${i(iconCls, txt)} </span>`;
300 },
301
302 render_backup_status: function(value, meta, record) {
303 if (typeof value === 'undefined') {
304 return "";
305 }
306
307 let iconCls = 'check-circle good';
308 let text = gettext('Yes');
309
310 if (!PVE.Parser.parseBoolean(value.toString())) {
311 iconCls = 'times-circle critical';
312
313 text = gettext('No');
314
315 let reason = record.get('reason');
316 if (typeof reason !== 'undefined') {
317 if (reason in PVE.Utils.backup_reasons_table) {
318 reason = PVE.Utils.backup_reasons_table[record.get('reason')];
319 }
320 text = `${text} - ${reason}`;
321 }
322 }
323
324 return `<i class="fa fa-${iconCls}"></i> ${text}`;
325 },
326
327 render_backup_days_of_week: function(val) {
328 var dows = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
329 var selected = [];
330 var cur = -1;
331 val.split(',').forEach(function(day) {
332 cur++;
333 var dow = (dows.indexOf(day)+6)%7;
334 if (cur === dow) {
335 if (selected.length === 0 || selected[selected.length-1] === 0) {
336 selected.push(1);
337 } else {
338 selected[selected.length-1]++;
339 }
340 } else {
341 while (cur < dow) {
342 cur++;
343 selected.push(0);
344 }
345 selected.push(1);
346 }
347 });
348
349 cur = -1;
350 var days = [];
351 selected.forEach(function(item) {
352 cur++;
353 if (item > 2) {
354 days.push(Ext.Date.dayNames[cur+1] + '-' + Ext.Date.dayNames[(cur+item)%7]);
355 cur += item-1;
356 } else if (item === 2) {
357 days.push(Ext.Date.dayNames[cur+1]);
358 days.push(Ext.Date.dayNames[(cur+2)%7]);
359 cur++;
360 } else if (item === 1) {
361 days.push(Ext.Date.dayNames[(cur+1)%7]);
362 }
363 });
364 return days.join(', ');
365 },
366
367 render_backup_selection: function(value, metaData, record) {
368 let allExceptText = gettext('All except {0}');
369 let allText = '-- ' + gettext('All') + ' --';
370 if (record.data.all) {
371 if (record.data.exclude) {
372 return Ext.String.format(allExceptText, record.data.exclude);
373 }
374 return allText;
375 }
376 if (record.data.vmid) {
377 return record.data.vmid;
378 }
379
380 if (record.data.pool) {
381 return "Pool '"+ record.data.pool + "'";
382 }
383
384 return "-";
385 },
386
387 backup_reasons_table: {
388 'backup=yes': gettext('Enabled'),
389 'backup=no': gettext('Disabled'),
390 'enabled': gettext('Enabled'),
391 'disabled': gettext('Disabled'),
392 'not a volume': gettext('Not a volume'),
393 'efidisk but no OMVF BIOS': gettext('EFI Disk without OMVF BIOS'),
394 },
395
396 renderNotFound: what => Ext.String.format(gettext("No {0} found"), what),
397
398 get_kvm_osinfo: function(value) {
399 var info = { base: 'Other' }; // default
400 if (value) {
401 Ext.each(Object.keys(PVE.Utils.kvm_ostypes), function(k) {
402 Ext.each(PVE.Utils.kvm_ostypes[k], function(e) {
403 if (e.val === value) {
404 info = { desc: e.desc, base: k };
405 }
406 });
407 });
408 }
409 return info;
410 },
411
412 render_kvm_ostype: function(value) {
413 var osinfo = PVE.Utils.get_kvm_osinfo(value);
414 if (osinfo.desc && osinfo.desc !== '-') {
415 return osinfo.base + ' ' + osinfo.desc;
416 } else {
417 return osinfo.base;
418 }
419 },
420
421 render_hotplug_features: function(value) {
422 var fa = [];
423
424 if (!value || value === '0') {
425 return gettext('Disabled');
426 }
427
428 if (value === '1') {
429 value = 'disk,network,usb';
430 }
431
432 Ext.each(value.split(','), function(el) {
433 if (el === 'disk') {
434 fa.push(gettext('Disk'));
435 } else if (el === 'network') {
436 fa.push(gettext('Network'));
437 } else if (el === 'usb') {
438 fa.push('USB');
439 } else if (el === 'memory') {
440 fa.push(gettext('Memory'));
441 } else if (el === 'cpu') {
442 fa.push(gettext('CPU'));
443 } else {
444 fa.push(el);
445 }
446 });
447
448 return fa.join(', ');
449 },
450
451 render_localtime: function(value) {
452 if (value === '__default__') {
453 return Proxmox.Utils.defaultText + ' (' + gettext('Enabled for Windows') + ')';
454 }
455 return Proxmox.Utils.format_boolean(value);
456 },
457
458 render_qga_features: function(config) {
459 if (!config) {
460 return Proxmox.Utils.defaultText + ' (' + Proxmox.Utils.disabledText + ')';
461 }
462 let qga = PVE.Parser.parsePropertyString(config, 'enabled');
463 if (!PVE.Parser.parseBoolean(qga.enabled)) {
464 return Proxmox.Utils.disabledText;
465 }
466 delete qga.enabled;
467
468 let agentstring = Proxmox.Utils.enabledText;
469
470 for (const [key, value] of Object.entries(qga)) {
471 let displayText = Proxmox.Utils.disabledText;
472 if (key === 'type') {
473 let map = {
474 isa: "ISA",
475 virtio: "VirtIO",
476 };
477 displayText = map[value] || Proxmox.Utils.unknownText;
478 } else if (PVE.Parser.parseBoolean(value)) {
479 displayText = Proxmox.Utils.enabledText;
480 }
481 agentstring += `, ${key}: ${displayText}`;
482 }
483
484 return agentstring;
485 },
486
487 render_qemu_machine: function(value) {
488 return value || Proxmox.Utils.defaultText + ' (i440fx)';
489 },
490
491 render_qemu_bios: function(value) {
492 if (!value) {
493 return Proxmox.Utils.defaultText + ' (SeaBIOS)';
494 } else if (value === 'seabios') {
495 return "SeaBIOS";
496 } else if (value === 'ovmf') {
497 return "OVMF (UEFI)";
498 } else {
499 return value;
500 }
501 },
502
503 render_dc_ha_opts: function(value) {
504 if (!value) {
505 return Proxmox.Utils.defaultText;
506 } else {
507 return PVE.Parser.printPropertyString(value);
508 }
509 },
510 render_as_property_string: v => !v ? Proxmox.Utils.defaultText : PVE.Parser.printPropertyString(v),
511
512 render_scsihw: function(value) {
513 if (!value || value === '__default__') {
514 return Proxmox.Utils.defaultText + ' (LSI 53C895A)';
515 } else if (value === 'lsi') {
516 return 'LSI 53C895A';
517 } else if (value === 'lsi53c810') {
518 return 'LSI 53C810';
519 } else if (value === 'megasas') {
520 return 'MegaRAID SAS 8708EM2';
521 } else if (value === 'virtio-scsi-pci') {
522 return 'VirtIO SCSI';
523 } else if (value === 'virtio-scsi-single') {
524 return 'VirtIO SCSI single';
525 } else if (value === 'pvscsi') {
526 return 'VMware PVSCSI';
527 } else {
528 return value;
529 }
530 },
531
532 render_spice_enhancements: function(values) {
533 let props = PVE.Parser.parsePropertyString(values);
534 if (Ext.Object.isEmpty(props)) {
535 return Proxmox.Utils.noneText;
536 }
537
538 let output = [];
539 if (PVE.Parser.parseBoolean(props.foldersharing)) {
540 output.push('Folder Sharing: ' + gettext('Enabled'));
541 }
542 if (props.videostreaming === 'all' || props.videostreaming === 'filter') {
543 output.push('Video Streaming: ' + props.videostreaming);
544 }
545 return output.join(', ');
546 },
547
548 // fixme: auto-generate this
549 // for now, please keep in sync with PVE::Tools::kvmkeymaps
550 kvm_keymaps: {
551 '__default__': Proxmox.Utils.defaultText,
552 //ar: 'Arabic',
553 da: 'Danish',
554 de: 'German',
555 'de-ch': 'German (Swiss)',
556 'en-gb': 'English (UK)',
557 'en-us': 'English (USA)',
558 es: 'Spanish',
559 //et: 'Estonia',
560 fi: 'Finnish',
561 //fo: 'Faroe Islands',
562 fr: 'French',
563 'fr-be': 'French (Belgium)',
564 'fr-ca': 'French (Canada)',
565 'fr-ch': 'French (Swiss)',
566 //hr: 'Croatia',
567 hu: 'Hungarian',
568 is: 'Icelandic',
569 it: 'Italian',
570 ja: 'Japanese',
571 lt: 'Lithuanian',
572 //lv: 'Latvian',
573 mk: 'Macedonian',
574 nl: 'Dutch',
575 //'nl-be': 'Dutch (Belgium)',
576 no: 'Norwegian',
577 pl: 'Polish',
578 pt: 'Portuguese',
579 'pt-br': 'Portuguese (Brazil)',
580 //ru: 'Russian',
581 sl: 'Slovenian',
582 sv: 'Swedish',
583 //th: 'Thai',
584 tr: 'Turkish',
585 },
586
587 kvm_vga_drivers: {
588 '__default__': Proxmox.Utils.defaultText,
589 std: gettext('Standard VGA'),
590 vmware: gettext('VMware compatible'),
591 qxl: 'SPICE',
592 qxl2: 'SPICE dual monitor',
593 qxl3: 'SPICE three monitors',
594 qxl4: 'SPICE four monitors',
595 serial0: gettext('Serial terminal') + ' 0',
596 serial1: gettext('Serial terminal') + ' 1',
597 serial2: gettext('Serial terminal') + ' 2',
598 serial3: gettext('Serial terminal') + ' 3',
599 virtio: 'VirtIO-GPU',
600 'virtio-gl': 'VirGL GPU',
601 none: Proxmox.Utils.noneText,
602 },
603
604 render_kvm_language: function(value) {
605 if (!value || value === '__default__') {
606 return Proxmox.Utils.defaultText;
607 }
608 let text = PVE.Utils.kvm_keymaps[value];
609 return text ? `${text} (${value})` : value;
610 },
611
612 console_map: {
613 '__default__': Proxmox.Utils.defaultText + ' (xterm.js)',
614 'vv': 'SPICE (remote-viewer)',
615 'html5': 'HTML5 (noVNC)',
616 'xtermjs': 'xterm.js',
617 },
618
619 render_console_viewer: function(value) {
620 value = value || '__default__';
621 return PVE.Utils.console_map[value] || value;
622 },
623
624 render_kvm_vga_driver: function(value) {
625 if (!value) {
626 return Proxmox.Utils.defaultText;
627 }
628 let vga = PVE.Parser.parsePropertyString(value, 'type');
629 let text = PVE.Utils.kvm_vga_drivers[vga.type];
630 if (!vga.type) {
631 text = Proxmox.Utils.defaultText;
632 }
633 return text ? `${text} (${value})` : value;
634 },
635
636 render_kvm_startup: function(value) {
637 var startup = PVE.Parser.parseStartup(value);
638
639 var res = 'order=';
640 if (startup.order === undefined) {
641 res += 'any';
642 } else {
643 res += startup.order;
644 }
645 if (startup.up !== undefined) {
646 res += ',up=' + startup.up;
647 }
648 if (startup.down !== undefined) {
649 res += ',down=' + startup.down;
650 }
651
652 return res;
653 },
654
655 extractFormActionError: function(action) {
656 var msg;
657 switch (action.failureType) {
658 case Ext.form.action.Action.CLIENT_INVALID:
659 msg = gettext('Form fields may not be submitted with invalid values');
660 break;
661 case Ext.form.action.Action.CONNECT_FAILURE:
662 msg = gettext('Connection error');
663 var resp = action.response;
664 if (resp.status && resp.statusText) {
665 msg += " " + resp.status + ": " + resp.statusText;
666 }
667 break;
668 case Ext.form.action.Action.LOAD_FAILURE:
669 case Ext.form.action.Action.SERVER_INVALID:
670 msg = Proxmox.Utils.extractRequestError(action.result, true);
671 break;
672 }
673 return msg;
674 },
675
676 contentTypes: {
677 'images': gettext('Disk image'),
678 'backup': gettext('VZDump backup file'),
679 'vztmpl': gettext('Container template'),
680 'iso': gettext('ISO image'),
681 'rootdir': gettext('Container'),
682 'snippets': gettext('Snippets'),
683 },
684
685 volume_is_qemu_backup: function(volid, format) {
686 return format === 'pbs-vm' || volid.match(':backup/vzdump-qemu-');
687 },
688
689 volume_is_lxc_backup: function(volid, format) {
690 return format === 'pbs-ct' || volid.match(':backup/vzdump-(lxc|openvz)-');
691 },
692
693 authSchema: {
694 ad: {
695 name: gettext('Active Directory Server'),
696 ipanel: 'pveAuthADPanel',
697 syncipanel: 'pveAuthLDAPSyncPanel',
698 add: true,
699 tfa: true,
700 pwchange: true,
701 },
702 ldap: {
703 name: gettext('LDAP Server'),
704 ipanel: 'pveAuthLDAPPanel',
705 syncipanel: 'pveAuthLDAPSyncPanel',
706 add: true,
707 tfa: true,
708 pwchange: true,
709 },
710 openid: {
711 name: gettext('OpenID Connect Server'),
712 ipanel: 'pveAuthOpenIDPanel',
713 add: true,
714 tfa: false,
715 pwchange: false,
716 iconCls: 'pmx-itype-icon-openid-logo',
717 },
718 pam: {
719 name: 'Linux PAM',
720 ipanel: 'pveAuthBasePanel',
721 add: false,
722 tfa: true,
723 pwchange: true,
724 },
725 pve: {
726 name: 'Proxmox VE authentication server',
727 ipanel: 'pveAuthBasePanel',
728 add: false,
729 tfa: true,
730 pwchange: true,
731 },
732 },
733
734 storageSchema: {
735 dir: {
736 name: Proxmox.Utils.directoryText,
737 ipanel: 'DirInputPanel',
738 faIcon: 'folder',
739 backups: true,
740 },
741 lvm: {
742 name: 'LVM',
743 ipanel: 'LVMInputPanel',
744 faIcon: 'folder',
745 backups: false,
746 },
747 lvmthin: {
748 name: 'LVM-Thin',
749 ipanel: 'LvmThinInputPanel',
750 faIcon: 'folder',
751 backups: false,
752 },
753 btrfs: {
754 name: 'BTRFS',
755 ipanel: 'BTRFSInputPanel',
756 faIcon: 'folder',
757 backups: true,
758 },
759 nfs: {
760 name: 'NFS',
761 ipanel: 'NFSInputPanel',
762 faIcon: 'building',
763 backups: true,
764 },
765 cifs: {
766 name: 'SMB/CIFS',
767 ipanel: 'CIFSInputPanel',
768 faIcon: 'building',
769 backups: true,
770 },
771 glusterfs: {
772 name: 'GlusterFS',
773 ipanel: 'GlusterFsInputPanel',
774 faIcon: 'building',
775 backups: true,
776 },
777 iscsi: {
778 name: 'iSCSI',
779 ipanel: 'IScsiInputPanel',
780 faIcon: 'building',
781 backups: false,
782 },
783 cephfs: {
784 name: 'CephFS',
785 ipanel: 'CephFSInputPanel',
786 faIcon: 'building',
787 backups: true,
788 },
789 pvecephfs: {
790 name: 'CephFS (PVE)',
791 ipanel: 'CephFSInputPanel',
792 hideAdd: true,
793 faIcon: 'building',
794 backups: true,
795 },
796 rbd: {
797 name: 'RBD',
798 ipanel: 'RBDInputPanel',
799 faIcon: 'building',
800 backups: false,
801 },
802 pveceph: {
803 name: 'RBD (PVE)',
804 ipanel: 'RBDInputPanel',
805 hideAdd: true,
806 faIcon: 'building',
807 backups: false,
808 },
809 zfs: {
810 name: 'ZFS over iSCSI',
811 ipanel: 'ZFSInputPanel',
812 faIcon: 'building',
813 backups: false,
814 },
815 zfspool: {
816 name: 'ZFS',
817 ipanel: 'ZFSPoolInputPanel',
818 faIcon: 'folder',
819 backups: false,
820 },
821 pbs: {
822 name: 'Proxmox Backup Server',
823 ipanel: 'PBSInputPanel',
824 faIcon: 'floppy-o',
825 backups: true,
826 },
827 drbd: {
828 name: 'DRBD',
829 hideAdd: true,
830 backups: false,
831 },
832 },
833
834 sdnvnetSchema: {
835 vnet: {
836 name: 'vnet',
837 faIcon: 'folder',
838 },
839 },
840
841 sdnzoneSchema: {
842 zone: {
843 name: 'zone',
844 hideAdd: true,
845 },
846 simple: {
847 name: 'Simple',
848 ipanel: 'SimpleInputPanel',
849 faIcon: 'th',
850 },
851 vlan: {
852 name: 'VLAN',
853 ipanel: 'VlanInputPanel',
854 faIcon: 'th',
855 },
856 qinq: {
857 name: 'QinQ',
858 ipanel: 'QinQInputPanel',
859 faIcon: 'th',
860 },
861 vxlan: {
862 name: 'VXLAN',
863 ipanel: 'VxlanInputPanel',
864 faIcon: 'th',
865 },
866 evpn: {
867 name: 'EVPN',
868 ipanel: 'EvpnInputPanel',
869 faIcon: 'th',
870 },
871 },
872
873 sdncontrollerSchema: {
874 controller: {
875 name: 'controller',
876 hideAdd: true,
877 },
878 evpn: {
879 name: 'evpn',
880 ipanel: 'EvpnInputPanel',
881 faIcon: 'crosshairs',
882 },
883 bgp: {
884 name: 'bgp',
885 ipanel: 'BgpInputPanel',
886 faIcon: 'crosshairs',
887 },
888 },
889
890 sdnipamSchema: {
891 ipam: {
892 name: 'ipam',
893 hideAdd: true,
894 },
895 pve: {
896 name: 'PVE',
897 ipanel: 'PVEIpamInputPanel',
898 faIcon: 'th',
899 hideAdd: true,
900 },
901 netbox: {
902 name: 'Netbox',
903 ipanel: 'NetboxInputPanel',
904 faIcon: 'th',
905 },
906 phpipam: {
907 name: 'PhpIpam',
908 ipanel: 'PhpIpamInputPanel',
909 faIcon: 'th',
910 },
911 },
912
913 sdndnsSchema: {
914 dns: {
915 name: 'dns',
916 hideAdd: true,
917 },
918 powerdns: {
919 name: 'powerdns',
920 ipanel: 'PowerdnsInputPanel',
921 faIcon: 'th',
922 },
923 },
924
925 format_sdnvnet_type: function(value, md, record) {
926 var schema = PVE.Utils.sdnvnetSchema[value];
927 if (schema) {
928 return schema.name;
929 }
930 return Proxmox.Utils.unknownText;
931 },
932
933 format_sdnzone_type: function(value, md, record) {
934 var schema = PVE.Utils.sdnzoneSchema[value];
935 if (schema) {
936 return schema.name;
937 }
938 return Proxmox.Utils.unknownText;
939 },
940
941 format_sdncontroller_type: function(value, md, record) {
942 var schema = PVE.Utils.sdncontrollerSchema[value];
943 if (schema) {
944 return schema.name;
945 }
946 return Proxmox.Utils.unknownText;
947 },
948
949 format_sdnipam_type: function(value, md, record) {
950 var schema = PVE.Utils.sdnipamSchema[value];
951 if (schema) {
952 return schema.name;
953 }
954 return Proxmox.Utils.unknownText;
955 },
956
957 format_sdndns_type: function(value, md, record) {
958 var schema = PVE.Utils.sdndnsSchema[value];
959 if (schema) {
960 return schema.name;
961 }
962 return Proxmox.Utils.unknownText;
963 },
964
965 format_storage_type: function(value, md, record) {
966 if (value === 'rbd') {
967 value = !record || record.get('monhost') ? 'rbd' : 'pveceph';
968 } else if (value === 'cephfs') {
969 value = !record || record.get('monhost') ? 'cephfs' : 'pvecephfs';
970 }
971
972 let schema = PVE.Utils.storageSchema[value];
973 return schema?.name ?? value;
974 },
975
976 format_ha: function(value) {
977 var text = Proxmox.Utils.noneText;
978
979 if (value.managed) {
980 text = value.state || Proxmox.Utils.noneText;
981
982 text += ', ' + Proxmox.Utils.groupText + ': ';
983 text += value.group || Proxmox.Utils.noneText;
984 }
985
986 return text;
987 },
988
989 format_content_types: function(value) {
990 return value.split(',').sort().map(function(ct) {
991 return PVE.Utils.contentTypes[ct] || ct;
992 }).join(', ');
993 },
994
995 render_storage_content: function(value, metaData, record) {
996 var data = record.data;
997 if (Ext.isNumber(data.channel) &&
998 Ext.isNumber(data.id) &&
999 Ext.isNumber(data.lun)) {
1000 return "CH " +
1001 Ext.String.leftPad(data.channel, 2, '0') +
1002 " ID " + data.id + " LUN " + data.lun;
1003 }
1004 return data.volid.replace(/^.*?:(.*?\/)?/, '');
1005 },
1006
1007 render_serverity: function(value) {
1008 return PVE.Utils.log_severity_hash[value] || value;
1009 },
1010
1011 calculate_hostcpu: function(data) {
1012 if (!(data.uptime && Ext.isNumeric(data.cpu))) {
1013 return -1;
1014 }
1015
1016 if (data.type !== 'qemu' && data.type !== 'lxc') {
1017 return -1;
1018 }
1019
1020 var index = PVE.data.ResourceStore.findExact('id', 'node/' + data.node);
1021 var node = PVE.data.ResourceStore.getAt(index);
1022 if (!Ext.isDefined(node) || node === null) {
1023 return -1;
1024 }
1025 var maxcpu = node.data.maxcpu || 1;
1026
1027 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
1028 return -1;
1029 }
1030
1031 return (data.cpu/maxcpu) * data.maxcpu;
1032 },
1033
1034 render_hostcpu: function(value, metaData, record, rowIndex, colIndex, store) {
1035 if (!(record.data.uptime && Ext.isNumeric(record.data.cpu))) {
1036 return '';
1037 }
1038
1039 if (record.data.type !== 'qemu' && record.data.type !== 'lxc') {
1040 return '';
1041 }
1042
1043 var index = PVE.data.ResourceStore.findExact('id', 'node/' + record.data.node);
1044 var node = PVE.data.ResourceStore.getAt(index);
1045 if (!Ext.isDefined(node) || node === null) {
1046 return '';
1047 }
1048 var maxcpu = node.data.maxcpu || 1;
1049
1050 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
1051 return '';
1052 }
1053
1054 var per = (record.data.cpu/maxcpu) * record.data.maxcpu * 100;
1055
1056 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
1057 },
1058
1059 render_bandwidth: function(value) {
1060 if (!Ext.isNumeric(value)) {
1061 return '';
1062 }
1063
1064 return Proxmox.Utils.format_size(value) + '/s';
1065 },
1066
1067 render_timestamp_human_readable: function(value) {
1068 return Ext.Date.format(new Date(value * 1000), 'l d F Y H:i:s');
1069 },
1070
1071 // render a timestamp or pending
1072 render_next_event: function(value) {
1073 if (!value) {
1074 return '-';
1075 }
1076 let now = new Date(), next = new Date(value * 1000);
1077 if (next < now) {
1078 return gettext('pending');
1079 }
1080 return Proxmox.Utils.render_timestamp(value);
1081 },
1082
1083 calculate_mem_usage: function(data) {
1084 if (!Ext.isNumeric(data.mem) ||
1085 data.maxmem === 0 ||
1086 data.uptime < 1) {
1087 return -1;
1088 }
1089
1090 return data.mem / data.maxmem;
1091 },
1092
1093 calculate_hostmem_usage: function(data) {
1094 if (data.type !== 'qemu' && data.type !== 'lxc') {
1095 return -1;
1096 }
1097
1098 var index = PVE.data.ResourceStore.findExact('id', 'node/' + data.node);
1099 var node = PVE.data.ResourceStore.getAt(index);
1100
1101 if (!Ext.isDefined(node) || node === null) {
1102 return -1;
1103 }
1104 var maxmem = node.data.maxmem || 0;
1105
1106 if (!Ext.isNumeric(data.mem) ||
1107 maxmem === 0 ||
1108 data.uptime < 1) {
1109 return -1;
1110 }
1111
1112 return data.mem / maxmem;
1113 },
1114
1115 render_mem_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
1116 if (!Ext.isNumeric(value) || value === -1) {
1117 return '';
1118 }
1119 if (value > 1) {
1120 // we got no percentage but bytes
1121 var mem = value;
1122 var maxmem = record.data.maxmem;
1123 if (!record.data.uptime ||
1124 maxmem === 0 ||
1125 !Ext.isNumeric(mem)) {
1126 return '';
1127 }
1128
1129 return (mem*100/maxmem).toFixed(1) + " %";
1130 }
1131 return (value*100).toFixed(1) + " %";
1132 },
1133
1134 render_hostmem_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
1135 if (!Ext.isNumeric(record.data.mem) || value === -1) {
1136 return '';
1137 }
1138
1139 if (record.data.type !== 'qemu' && record.data.type !== 'lxc') {
1140 return '';
1141 }
1142
1143 var index = PVE.data.ResourceStore.findExact('id', 'node/' + record.data.node);
1144 var node = PVE.data.ResourceStore.getAt(index);
1145 var maxmem = node.data.maxmem || 0;
1146
1147 if (record.data.mem > 1) {
1148 // we got no percentage but bytes
1149 var mem = record.data.mem;
1150 if (!record.data.uptime ||
1151 maxmem === 0 ||
1152 !Ext.isNumeric(mem)) {
1153 return '';
1154 }
1155
1156 return ((mem*100)/maxmem).toFixed(1) + " %";
1157 }
1158 return (value*100).toFixed(1) + " %";
1159 },
1160
1161 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
1162 var mem = value;
1163 var maxmem = record.data.maxmem;
1164
1165 if (!record.data.uptime) {
1166 return '';
1167 }
1168
1169 if (!(Ext.isNumeric(mem) && maxmem)) {
1170 return '';
1171 }
1172
1173 return Proxmox.Utils.render_size(value);
1174 },
1175
1176 calculate_disk_usage: function(data) {
1177 if (!Ext.isNumeric(data.disk) ||
1178 ((data.type === 'qemu' || data.type === 'lxc') && data.uptime === 0) ||
1179 data.maxdisk === 0
1180 ) {
1181 return -1;
1182 }
1183
1184 return data.disk / data.maxdisk;
1185 },
1186
1187 render_disk_usage_percent: function(value, metaData, record, rowIndex, colIndex, store) {
1188 if (!Ext.isNumeric(value) || value === -1) {
1189 return '';
1190 }
1191
1192 return (value * 100).toFixed(1) + " %";
1193 },
1194
1195 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
1196 var disk = value;
1197 var maxdisk = record.data.maxdisk;
1198 var type = record.data.type;
1199
1200 if (!Ext.isNumeric(disk) ||
1201 maxdisk === 0 ||
1202 ((type === 'qemu' || type === 'lxc') && record.data.uptime === 0)
1203 ) {
1204 return '';
1205 }
1206
1207 return Proxmox.Utils.render_size(value);
1208 },
1209
1210 get_object_icon_class: function(type, record) {
1211 var status = '';
1212 var objType = type;
1213
1214 if (type === 'type') {
1215 // for folder view
1216 objType = record.groupbyid;
1217 } else if (record.template) {
1218 // templates
1219 objType = 'template';
1220 status = type;
1221 } else {
1222 // everything else
1223 status = record.status + ' ha-' + record.hastate;
1224 }
1225
1226 if (record.lock) {
1227 status += ' locked lock-' + record.lock;
1228 }
1229
1230 var defaults = PVE.tree.ResourceTree.typeDefaults[objType];
1231 if (defaults && defaults.iconCls) {
1232 var retVal = defaults.iconCls + ' ' + status;
1233 return retVal;
1234 }
1235
1236 return '';
1237 },
1238
1239 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
1240 var cls = PVE.Utils.get_object_icon_class(value, record.data);
1241
1242 var fa = '<i class="fa-fw x-grid-icon-custom ' + cls + '"></i> ';
1243 return fa + value;
1244 },
1245
1246 render_support_level: function(value, metaData, record) {
1247 return PVE.Utils.support_level_hash[value] || '-';
1248 },
1249
1250 render_upid: function(value, metaData, record) {
1251 var type = record.data.type;
1252 var id = record.data.id;
1253
1254 return Proxmox.Utils.format_task_description(type, id);
1255 },
1256
1257 render_optional_url: function(value) {
1258 if (value && value.match(/^https?:\/\//)) {
1259 return '<a target="_blank" href="' + value + '">' + value + '</a>';
1260 }
1261 return value;
1262 },
1263
1264 render_san: function(value) {
1265 var names = [];
1266 if (Ext.isArray(value)) {
1267 value.forEach(function(val) {
1268 if (!Ext.isNumber(val)) {
1269 names.push(val);
1270 }
1271 });
1272 return names.join('<br>');
1273 }
1274 return value;
1275 },
1276
1277 render_full_name: function(firstname, metaData, record) {
1278 var first = firstname || '';
1279 var last = record.data.lastname || '';
1280 return Ext.htmlEncode(first + " " + last);
1281 },
1282
1283 windowHostname: function() {
1284 return window.location.hostname.replace(Proxmox.Utils.IP6_bracket_match,
1285 function(m, addr, offset, original) { return addr; });
1286 },
1287
1288 openDefaultConsoleWindow: function(consoles, consoleType, vmid, nodename, vmname, cmd) {
1289 var dv = PVE.Utils.defaultViewer(consoles, consoleType);
1290 PVE.Utils.openConsoleWindow(dv, consoleType, vmid, nodename, vmname, cmd);
1291 },
1292
1293 openConsoleWindow: function(viewer, consoleType, vmid, nodename, vmname, cmd) {
1294 if (vmid === undefined && (consoleType === 'kvm' || consoleType === 'lxc')) {
1295 throw "missing vmid";
1296 }
1297 if (!nodename) {
1298 throw "no nodename specified";
1299 }
1300
1301 if (viewer === 'html5') {
1302 PVE.Utils.openVNCViewer(consoleType, vmid, nodename, vmname, cmd);
1303 } else if (viewer === 'xtermjs') {
1304 Proxmox.Utils.openXtermJsViewer(consoleType, vmid, nodename, vmname, cmd);
1305 } else if (viewer === 'vv') {
1306 let url = '/nodes/' + nodename + '/spiceshell';
1307 let params = {
1308 proxy: PVE.Utils.windowHostname(),
1309 };
1310 if (consoleType === 'kvm') {
1311 url = '/nodes/' + nodename + '/qemu/' + vmid.toString() + '/spiceproxy';
1312 } else if (consoleType === 'lxc') {
1313 url = '/nodes/' + nodename + '/lxc/' + vmid.toString() + '/spiceproxy';
1314 } else if (consoleType === 'upgrade') {
1315 params.cmd = 'upgrade';
1316 } else if (consoleType === 'cmd') {
1317 params.cmd = cmd;
1318 } else if (consoleType !== 'shell') {
1319 throw `unknown spice viewer type '${consoleType}'`;
1320 }
1321 PVE.Utils.openSpiceViewer(url, params);
1322 } else {
1323 throw `unknown viewer type '${viewer}'`;
1324 }
1325 },
1326
1327 defaultViewer: function(consoles, type) {
1328 var allowSpice, allowXtermjs;
1329
1330 if (consoles === true) {
1331 allowSpice = true;
1332 allowXtermjs = true;
1333 } else if (typeof consoles === 'object') {
1334 allowSpice = consoles.spice;
1335 allowXtermjs = !!consoles.xtermjs;
1336 }
1337 let dv = PVE.UIOptions.options.console || (type === 'kvm' ? 'vv' : 'xtermjs');
1338 if (dv === 'vv' && !allowSpice) {
1339 dv = allowXtermjs ? 'xtermjs' : 'html5';
1340 } else if (dv === 'xtermjs' && !allowXtermjs) {
1341 dv = allowSpice ? 'vv' : 'html5';
1342 }
1343
1344 return dv;
1345 },
1346
1347 openVNCViewer: function(vmtype, vmid, nodename, vmname, cmd) {
1348 let scaling = 'off';
1349 if (Proxmox.Utils.toolkit !== 'touch') {
1350 var sp = Ext.state.Manager.getProvider();
1351 scaling = sp.get('novnc-scaling', 'off');
1352 }
1353 var url = Ext.Object.toQueryString({
1354 console: vmtype, // kvm, lxc, upgrade or shell
1355 novnc: 1,
1356 vmid: vmid,
1357 vmname: vmname,
1358 node: nodename,
1359 resize: scaling,
1360 cmd: cmd,
1361 });
1362 var nw = window.open("?" + url, '_blank', "innerWidth=745,innerheight=427");
1363 if (nw) {
1364 nw.focus();
1365 }
1366 },
1367
1368 openSpiceViewer: function(url, params) {
1369 var downloadWithName = function(uri, name) {
1370 var link = Ext.DomHelper.append(document.body, {
1371 tag: 'a',
1372 href: uri,
1373 css: 'display:none;visibility:hidden;height:0px;',
1374 });
1375
1376 // Note: we need to tell Android and Chrome the correct file name extension
1377 // but we do not set 'download' tag for other environments, because
1378 // It can have strange side effects (additional user prompt on firefox)
1379 if (navigator.userAgent.match(/Android|Chrome/i)) {
1380 link.download = name;
1381 }
1382
1383 if (link.fireEvent) {
1384 link.fireEvent('onclick');
1385 } else {
1386 let evt = document.createEvent("MouseEvents");
1387 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
1388 link.dispatchEvent(evt);
1389 }
1390 };
1391
1392 Proxmox.Utils.API2Request({
1393 url: url,
1394 params: params,
1395 method: 'POST',
1396 failure: function(response, opts) {
1397 Ext.Msg.alert('Error', response.htmlStatus);
1398 },
1399 success: function(response, opts) {
1400 let cfg = response.result.data;
1401 let raw = Object.entries(cfg).reduce((acc, [k, v]) => acc + `${k}=${v}\n`, "[virt-viewer]\n");
1402 let spiceDownload = 'data:application/x-virt-viewer;charset=UTF-8,' + encodeURIComponent(raw);
1403 downloadWithName(spiceDownload, "pve-spice.vv");
1404 },
1405 });
1406 },
1407
1408 openTreeConsole: function(tree, record, item, index, e) {
1409 e.stopEvent();
1410 let nodename = record.data.node;
1411 let vmid = record.data.vmid;
1412 let vmname = record.data.name;
1413 if (record.data.type === 'qemu' && !record.data.template) {
1414 Proxmox.Utils.API2Request({
1415 url: `/nodes/${nodename}/qemu/${vmid}/status/current`,
1416 failure: response => Ext.Msg.alert('Error', response.htmlStatus),
1417 success: function(response, opts) {
1418 let conf = response.result.data;
1419 let consoles = {
1420 spice: !!conf.spice,
1421 xtermjs: !!conf.serial,
1422 };
1423 PVE.Utils.openDefaultConsoleWindow(consoles, 'kvm', vmid, nodename, vmname);
1424 },
1425 });
1426 } else if (record.data.type === 'lxc' && !record.data.template) {
1427 PVE.Utils.openDefaultConsoleWindow(true, 'lxc', vmid, nodename, vmname);
1428 }
1429 },
1430
1431 // test automation helper
1432 call_menu_handler: function(menu, text) {
1433 let item = menu.query('menuitem').find(el => el.text === text);
1434 if (item && item.handler) {
1435 item.handler();
1436 }
1437 },
1438
1439 createCmdMenu: function(v, record, item, index, event) {
1440 event.stopEvent();
1441 if (!(v instanceof Ext.tree.View)) {
1442 v.select(record);
1443 }
1444 let menu;
1445 let type = record.data.type;
1446
1447 if (record.data.template) {
1448 if (type === 'qemu' || type === 'lxc') {
1449 menu = Ext.create('PVE.menu.TemplateMenu', {
1450 pveSelNode: record,
1451 });
1452 }
1453 } else if (type === 'qemu' || type === 'lxc' || type === 'node') {
1454 menu = Ext.create('PVE.' + type + '.CmdMenu', {
1455 pveSelNode: record,
1456 nodename: record.data.node,
1457 });
1458 } else {
1459 return undefined;
1460 }
1461
1462 menu.showAt(event.getXY());
1463 return menu;
1464 },
1465
1466 // helper for deleting field which are set to there default values
1467 delete_if_default: function(values, fieldname, default_val, create) {
1468 if (values[fieldname] === '' || values[fieldname] === default_val) {
1469 if (!create) {
1470 if (values.delete) {
1471 if (Ext.isArray(values.delete)) {
1472 values.delete.push(fieldname);
1473 } else {
1474 values.delete += ',' + fieldname;
1475 }
1476 } else {
1477 values.delete = fieldname;
1478 }
1479 }
1480
1481 delete values[fieldname];
1482 }
1483 },
1484
1485 loadSSHKeyFromFile: function(file, callback) {
1486 // ssh-keygen produces ~ 740 bytes for a 4096 bit RSA key, current max is 16 kbit, so assume:
1487 // 740 * 8 for max. 32kbit (5920 bytes), round upwards to 8192 bytes, leaves lots of comment space
1488 PVE.Utils.loadFile(file, callback, 8192);
1489 },
1490
1491 loadFile: function(file, callback, maxSize) {
1492 maxSize = maxSize || 32 * 1024;
1493 if (file.size > maxSize) {
1494 Ext.Msg.alert(gettext('Error'), `${gettext("Invalid file size")}: ${file.size} > ${maxSize}`);
1495 return;
1496 }
1497 let reader = new FileReader();
1498 reader.onload = evt => callback(evt.target.result);
1499 reader.readAsText(file);
1500 },
1501
1502 loadTextFromFile: function(file, callback, maxBytes) {
1503 let maxSize = maxBytes || 8192;
1504 if (file.size > maxSize) {
1505 Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size);
1506 return;
1507 }
1508 let reader = new FileReader();
1509 reader.onload = evt => callback(evt.target.result);
1510 reader.readAsText(file);
1511 },
1512
1513 diskControllerMaxIDs: {
1514 ide: 4,
1515 sata: 6,
1516 scsi: 31,
1517 virtio: 16,
1518 unused: 256,
1519 },
1520
1521 // types is either undefined (all busses), an array of busses, or a single bus
1522 forEachBus: function(types, func) {
1523 let busses = Object.keys(PVE.Utils.diskControllerMaxIDs);
1524
1525 if (Ext.isArray(types)) {
1526 busses = types;
1527 } else if (Ext.isDefined(types)) {
1528 busses = [types];
1529 }
1530
1531 // check if we only have valid busses
1532 for (let i = 0; i < busses.length; i++) {
1533 if (!PVE.Utils.diskControllerMaxIDs[busses[i]]) {
1534 throw "invalid bus: '" + busses[i] + "'";
1535 }
1536 }
1537
1538 for (let i = 0; i < busses.length; i++) {
1539 let count = PVE.Utils.diskControllerMaxIDs[busses[i]];
1540 for (let j = 0; j < count; j++) {
1541 let cont = func(busses[i], j);
1542 if (!cont && cont !== undefined) {
1543 return;
1544 }
1545 }
1546 }
1547 },
1548
1549 mp_counts: {
1550 mp: 256,
1551 unused: 256,
1552 },
1553
1554 forEachMP: function(func, includeUnused) {
1555 for (let i = 0; i < PVE.Utils.mp_counts.mp; i++) {
1556 let cont = func('mp', i);
1557 if (!cont && cont !== undefined) {
1558 return;
1559 }
1560 }
1561
1562 if (!includeUnused) {
1563 return;
1564 }
1565
1566 for (let i = 0; i < PVE.Utils.mp_counts.unused; i++) {
1567 let cont = func('unused', i);
1568 if (!cont && cont !== undefined) {
1569 return;
1570 }
1571 }
1572 },
1573
1574 hardware_counts: {
1575 net: 32,
1576 usb: 14,
1577 usb_old: 5,
1578 hostpci: 16,
1579 audio: 1,
1580 efidisk: 1,
1581 serial: 4,
1582 rng: 1,
1583 tpmstate: 1,
1584 },
1585
1586 // we can have usb6 and up only for specific machine/ostypes
1587 get_max_usb_count: function(ostype, machine) {
1588 if (!ostype) {
1589 return PVE.Utils.hardware_counts.usb_old;
1590 }
1591
1592 let match = /-(\d+).(\d+)/.exec(machine ?? '');
1593 if (!match || PVE.Utils.qemu_min_version([match[1], match[2]], [7, 1])) {
1594 if (ostype === 'l26') {
1595 return PVE.Utils.hardware_counts.usb;
1596 }
1597 let os_match = /^win(\d+)$/.exec(ostype);
1598 if (os_match && os_match[1] > 7) {
1599 return PVE.Utils.hardware_counts.usb;
1600 }
1601 }
1602
1603 return PVE.Utils.hardware_counts.usb_old;
1604 },
1605
1606 // parameters are expected to be arrays, e.g. [7,1], [4,0,1]
1607 // returns true if toCheck is equal or greater than minVersion
1608 qemu_min_version: function(toCheck, minVersion) {
1609 let i;
1610 for (i = 0; i < toCheck.length && i < minVersion.length; i++) {
1611 if (toCheck[i] < minVersion[i]) {
1612 return false;
1613 }
1614 }
1615
1616 if (minVersion.length > toCheck.length) {
1617 for (; i < minVersion.length; i++) {
1618 if (minVersion[i] !== 0) {
1619 return false;
1620 }
1621 }
1622 }
1623
1624 return true;
1625 },
1626
1627 cleanEmptyObjectKeys: function(obj) {
1628 for (const propName of Object.keys(obj)) {
1629 if (obj[propName] === null || obj[propName] === undefined) {
1630 delete obj[propName];
1631 }
1632 }
1633 },
1634
1635 acmedomain_count: 5,
1636
1637 add_domain_to_acme: function(acme, domain) {
1638 if (acme.domains === undefined) {
1639 acme.domains = [domain];
1640 } else {
1641 acme.domains.push(domain);
1642 acme.domains = acme.domains.filter((value, index, self) => self.indexOf(value) === index);
1643 }
1644 return acme;
1645 },
1646
1647 remove_domain_from_acme: function(acme, domain) {
1648 if (acme.domains !== undefined) {
1649 acme.domains = acme
1650 .domains
1651 .filter((value, index, self) => self.indexOf(value) === index && value !== domain);
1652 }
1653 return acme;
1654 },
1655
1656 handleStoreErrorOrMask: function(view, store, regex, callback) {
1657 view.mon(store, 'load', function(proxy, response, success, operation) {
1658 if (success) {
1659 Proxmox.Utils.setErrorMask(view, false);
1660 return;
1661 }
1662 let msg;
1663 if (operation.error.statusText) {
1664 if (operation.error.statusText.match(regex)) {
1665 callback(view, operation.error);
1666 return;
1667 } else {
1668 msg = operation.error.statusText + ' (' + operation.error.status + ')';
1669 }
1670 } else {
1671 msg = gettext('Connection error');
1672 }
1673 Proxmox.Utils.setErrorMask(view, msg);
1674 });
1675 },
1676
1677 showCephInstallOrMask: function(container, msg, nodename, callback) {
1678 if (msg.match(/not (installed|initialized)/i)) {
1679 if (Proxmox.UserName === 'root@pam') {
1680 container.el.mask();
1681 if (!container.down('pveCephInstallWindow')) {
1682 var isInstalled = !!msg.match(/not initialized/i);
1683 var win = Ext.create('PVE.ceph.Install', {
1684 nodename: nodename,
1685 });
1686 win.getViewModel().set('isInstalled', isInstalled);
1687 container.add(win);
1688 win.show();
1689 callback(win);
1690 }
1691 } else {
1692 container.mask(Ext.String.format(gettext('{0} not installed.') +
1693 ' ' + gettext('Log in as root to install.'), 'Ceph'), ['pve-static-mask']);
1694 }
1695 return true;
1696 } else {
1697 return false;
1698 }
1699 },
1700
1701 monitor_ceph_installed: function(view, rstore, nodename, maskOwnerCt) {
1702 PVE.Utils.handleStoreErrorOrMask(
1703 view,
1704 rstore,
1705 /not (installed|initialized)/i,
1706 (_, error) => {
1707 nodename = nodename || 'localhost';
1708 let maskTarget = maskOwnerCt ? view.ownerCt : view;
1709 rstore.stopUpdate();
1710 PVE.Utils.showCephInstallOrMask(maskTarget, error.statusText, nodename, win => {
1711 view.mon(win, 'cephInstallWindowClosed', () => rstore.startUpdate());
1712 });
1713 },
1714 );
1715 },
1716
1717
1718 propertyStringSet: function(target, source, name, value) {
1719 if (source) {
1720 if (value === undefined) {
1721 target[name] = source;
1722 } else {
1723 target[name] = value;
1724 }
1725 } else {
1726 delete target[name];
1727 }
1728 },
1729
1730 forEachCorosyncLink: function(nodeinfo, cb) {
1731 let re = /(?:ring|link)(\d+)_addr/;
1732 Ext.iterate(nodeinfo, (prop, val) => {
1733 let match = re.exec(prop);
1734 if (match) {
1735 cb(Number(match[1]), val);
1736 }
1737 });
1738 },
1739
1740 cpu_vendor_map: {
1741 'default': 'QEMU',
1742 'AuthenticAMD': 'AMD',
1743 'GenuineIntel': 'Intel',
1744 },
1745
1746 cpu_vendor_order: {
1747 "AMD": 1,
1748 "Intel": 2,
1749 "QEMU": 3,
1750 "Host": 4,
1751 "_default_": 5, // includes custom models
1752 },
1753
1754 verify_ip64_address_list: function(value, with_suffix) {
1755 for (let addr of value.split(/[ ,;]+/)) {
1756 if (addr === '') {
1757 continue;
1758 }
1759
1760 if (with_suffix) {
1761 let parts = addr.split('%');
1762 addr = parts[0];
1763
1764 if (parts.length > 2) {
1765 return false;
1766 }
1767
1768 if (parts.length > 1 && !addr.startsWith('fe80:')) {
1769 return false;
1770 }
1771 }
1772
1773 if (!Proxmox.Utils.IP64_match.test(addr)) {
1774 return false;
1775 }
1776 }
1777
1778 return true;
1779 },
1780
1781 sortByPreviousUsage: function(vmconfig, controllerList) {
1782 if (!controllerList) {
1783 controllerList = ['ide', 'virtio', 'scsi', 'sata'];
1784 }
1785 let usedControllers = {};
1786 for (const type of Object.keys(PVE.Utils.diskControllerMaxIDs)) {
1787 usedControllers[type] = 0;
1788 }
1789
1790 for (const property of Object.keys(vmconfig)) {
1791 if (property.match(PVE.Utils.bus_match) && !vmconfig[property].match(/media=cdrom/)) {
1792 const foundController = property.match(PVE.Utils.bus_match)[1];
1793 usedControllers[foundController]++;
1794 }
1795 }
1796
1797 let sortPriority = PVE.qemu.OSDefaults.getDefaults(vmconfig.ostype).busPriority;
1798
1799 let sortedList = Ext.clone(controllerList);
1800 sortedList.sort(function(a, b) {
1801 if (usedControllers[b] === usedControllers[a]) {
1802 return sortPriority[b] - sortPriority[a];
1803 }
1804 return usedControllers[b] - usedControllers[a];
1805 });
1806
1807 return sortedList;
1808 },
1809
1810 nextFreeDisk: function(controllers, config) {
1811 for (const controller of controllers) {
1812 for (let i = 0; i < PVE.Utils.diskControllerMaxIDs[controller]; i++) {
1813 let confid = controller + i.toString();
1814 if (!Ext.isDefined(config[confid])) {
1815 return {
1816 controller,
1817 id: i,
1818 confid,
1819 };
1820 }
1821 }
1822 }
1823
1824 return undefined;
1825 },
1826
1827 nextFreeMP: function(type, config) {
1828 for (let i = 0; i < PVE.Utils.mp_counts[type]; i++) {
1829 let confid = `${type}${i}`;
1830 if (!Ext.isDefined(config[confid])) {
1831 return {
1832 type,
1833 id: i,
1834 confid,
1835 };
1836 }
1837 }
1838
1839 return undefined;
1840 },
1841
1842 escapeNotesTemplate: function(value) {
1843 let replace = {
1844 '\\': '\\\\',
1845 '\n': '\\n',
1846 };
1847 return value.replace(/(\\|[\n])/g, match => replace[match]);
1848 },
1849
1850 unEscapeNotesTemplate: function(value) {
1851 let replace = {
1852 '\\\\': '\\',
1853 '\\n': '\n',
1854 };
1855 return value.replace(/(\\\\|\\n)/g, match => replace[match]);
1856 },
1857
1858 notesTemplateVars: ['cluster', 'guestname', 'node', 'vmid'],
1859
1860 renderTags: function(tagstext, overrides) {
1861 let text = '';
1862 if (tagstext) {
1863 let tags = (tagstext.split(/[,; ]/) || []).filter(t => !!t);
1864 if (PVE.UIOptions.shouldSortTags()) {
1865 tags = tags.sort((a, b) => {
1866 let alc = a.toLowerCase();
1867 let blc = b.toLowerCase();
1868 return alc < blc ? -1 : blc < alc ? 1 : a.localeCompare(b);
1869 });
1870 }
1871 text += ' ';
1872 tags.forEach((tag) => {
1873 text += Proxmox.Utils.getTagElement(tag, overrides);
1874 });
1875 }
1876 return text;
1877 },
1878
1879 tagCharRegex: /^[a-z0-9+_.-]+$/i,
1880
1881 verificationStateOrder: {
1882 'failed': 0,
1883 'none': 1,
1884 'ok': 2,
1885 '__default__': 3,
1886 },
1887 },
1888
1889 singleton: true,
1890 constructor: function() {
1891 var me = this;
1892 Ext.apply(me, me.utilities);
1893
1894 Proxmox.Utils.override_task_descriptions({
1895 acmedeactivate: ['ACME Account', gettext('Deactivate')],
1896 acmenewcert: ['SRV', gettext('Order Certificate')],
1897 acmerefresh: ['ACME Account', gettext('Refresh')],
1898 acmeregister: ['ACME Account', gettext('Register')],
1899 acmerenew: ['SRV', gettext('Renew Certificate')],
1900 acmerevoke: ['SRV', gettext('Revoke Certificate')],
1901 acmeupdate: ['ACME Account', gettext('Update')],
1902 'auth-realm-sync': [gettext('Realm'), gettext('Sync')],
1903 'auth-realm-sync-test': [gettext('Realm'), gettext('Sync Preview')],
1904 cephcreatemds: ['Ceph Metadata Server', gettext('Create')],
1905 cephcreatemgr: ['Ceph Manager', gettext('Create')],
1906 cephcreatemon: ['Ceph Monitor', gettext('Create')],
1907 cephcreateosd: ['Ceph OSD', gettext('Create')],
1908 cephcreatepool: ['Ceph Pool', gettext('Create')],
1909 cephdestroymds: ['Ceph Metadata Server', gettext('Destroy')],
1910 cephdestroymgr: ['Ceph Manager', gettext('Destroy')],
1911 cephdestroymon: ['Ceph Monitor', gettext('Destroy')],
1912 cephdestroyosd: ['Ceph OSD', gettext('Destroy')],
1913 cephdestroypool: ['Ceph Pool', gettext('Destroy')],
1914 cephdestroyfs: ['CephFS', gettext('Destroy')],
1915 cephfscreate: ['CephFS', gettext('Create')],
1916 cephsetpool: ['Ceph Pool', gettext('Edit')],
1917 cephsetflags: ['', gettext('Change global Ceph flags')],
1918 clustercreate: ['', gettext('Create Cluster')],
1919 clusterjoin: ['', gettext('Join Cluster')],
1920 dircreate: [gettext('Directory Storage'), gettext('Create')],
1921 dirremove: [gettext('Directory'), gettext('Remove')],
1922 download: [gettext('File'), gettext('Download')],
1923 hamigrate: ['HA', gettext('Migrate')],
1924 hashutdown: ['HA', gettext('Shutdown')],
1925 hastart: ['HA', gettext('Start')],
1926 hastop: ['HA', gettext('Stop')],
1927 imgcopy: ['', gettext('Copy data')],
1928 imgdel: ['', gettext('Erase data')],
1929 lvmcreate: [gettext('LVM Storage'), gettext('Create')],
1930 lvmremove: ['Volume Group', gettext('Remove')],
1931 lvmthincreate: [gettext('LVM-Thin Storage'), gettext('Create')],
1932 lvmthinremove: ['Thinpool', gettext('Remove')],
1933 migrateall: ['', gettext('Migrate all VMs and Containers')],
1934 'move_volume': ['CT', gettext('Move Volume')],
1935 'pbs-download': ['VM/CT', gettext('File Restore Download')],
1936 pull_file: ['CT', gettext('Pull file')],
1937 push_file: ['CT', gettext('Push file')],
1938 qmclone: ['VM', gettext('Clone')],
1939 qmconfig: ['VM', gettext('Configure')],
1940 qmcreate: ['VM', gettext('Create')],
1941 qmdelsnapshot: ['VM', gettext('Delete Snapshot')],
1942 qmdestroy: ['VM', gettext('Destroy')],
1943 qmigrate: ['VM', gettext('Migrate')],
1944 qmmove: ['VM', gettext('Move disk')],
1945 qmpause: ['VM', gettext('Pause')],
1946 qmreboot: ['VM', gettext('Reboot')],
1947 qmreset: ['VM', gettext('Reset')],
1948 qmrestore: ['VM', gettext('Restore')],
1949 qmresume: ['VM', gettext('Resume')],
1950 qmrollback: ['VM', gettext('Rollback')],
1951 qmshutdown: ['VM', gettext('Shutdown')],
1952 qmsnapshot: ['VM', gettext('Snapshot')],
1953 qmstart: ['VM', gettext('Start')],
1954 qmstop: ['VM', gettext('Stop')],
1955 qmsuspend: ['VM', gettext('Hibernate')],
1956 qmtemplate: ['VM', gettext('Convert to template')],
1957 spiceproxy: ['VM/CT', gettext('Console') + ' (Spice)'],
1958 spiceshell: ['', gettext('Shell') + ' (Spice)'],
1959 startall: ['', gettext('Start all VMs and Containers')],
1960 stopall: ['', gettext('Stop all VMs and Containers')],
1961 unknownimgdel: ['', gettext('Destroy image from unknown guest')],
1962 wipedisk: ['Device', gettext('Wipe Disk')],
1963 vncproxy: ['VM/CT', gettext('Console')],
1964 vncshell: ['', gettext('Shell')],
1965 vzclone: ['CT', gettext('Clone')],
1966 vzcreate: ['CT', gettext('Create')],
1967 vzdelsnapshot: ['CT', gettext('Delete Snapshot')],
1968 vzdestroy: ['CT', gettext('Destroy')],
1969 vzdump: (type, id) => id ? `VM/CT ${id} - ${gettext('Backup')}` : gettext('Backup Job'),
1970 vzmigrate: ['CT', gettext('Migrate')],
1971 vzmount: ['CT', gettext('Mount')],
1972 vzreboot: ['CT', gettext('Reboot')],
1973 vzrestore: ['CT', gettext('Restore')],
1974 vzresume: ['CT', gettext('Resume')],
1975 vzrollback: ['CT', gettext('Rollback')],
1976 vzshutdown: ['CT', gettext('Shutdown')],
1977 vzsnapshot: ['CT', gettext('Snapshot')],
1978 vzstart: ['CT', gettext('Start')],
1979 vzstop: ['CT', gettext('Stop')],
1980 vzsuspend: ['CT', gettext('Suspend')],
1981 vztemplate: ['CT', gettext('Convert to template')],
1982 vzumount: ['CT', gettext('Unmount')],
1983 zfscreate: [gettext('ZFS Storage'), gettext('Create')],
1984 zfsremove: ['ZFS Pool', gettext('Remove')],
1985 });
1986 },
1987
1988 });