]> git.proxmox.com Git - pve-manager.git/blobdiff - www/manager6/Utils.js
ui: eslint auto-fixes
[pve-manager.git] / www / manager6 / Utils.js
index e927a2fd7d0f3e9dd3050860b67096af7244edef..df2f9631164a5deb1617231df4cf27d85d1982e2 100644 (file)
@@ -1,12 +1,5 @@
 Ext.ns('PVE');
 
-// avoid errors related to Accessible Rich Internet Applications
-// (access for people with disabilities)
-// TODO reenable after all components are upgraded
-Ext.enableAria = false;
-Ext.enableAriaButtons = false;
-Ext.enableAriaPanels = false;
-
 console.log("Starting Proxmox VE Manager");
 
 Ext.Ajax.defaultHeaders = {
@@ -20,7 +13,7 @@ Ext.define('PVE.Utils', {
 
     toolkit: undefined, // (extjs|touch), set inside Toolkit.js
 
-    bus_match: /^(ide|sata|virtio|scsi)\d+$/,
+    bus_match: /^(ide|sata|virtio|scsi)(\d+)$/,
 
     log_severity_hash: {
        0: "panic",
@@ -50,6 +43,7 @@ Ext.define('PVE.Utils', {
            { desc: '2.4 Kernel', val: 'l24' },
        ],
        'Microsoft Windows': [
+           { desc: '11/2022', val: 'win11' },
            { desc: '10/2016/2019', val: 'win10' },
            { desc: '8.x/2012/2012r2', val: 'win8' },
            { desc: '7/2008r2', val: 'win7' },
@@ -511,13 +505,10 @@ Ext.define('PVE.Utils', {
            return PVE.Parser.printPropertyString(value);
        }
     },
-    render_as_property_string: function(value) {
-       return !value ? Proxmox.Utils.defaultText
-           : PVE.Parser.printPropertyString(value);
-    },
+    render_as_property_string: v => !v ? Proxmox.Utils.defaultText : PVE.Parser.printPropertyString(v),
 
     render_scsihw: function(value) {
-       if (!value) {
+       if (!value || value === '__default__') {
            return Proxmox.Utils.defaultText + ' (LSI 53C895A)';
        } else if (value === 'lsi') {
            return 'LSI 53C895A';
@@ -555,6 +546,7 @@ Ext.define('PVE.Utils', {
     // fixme: auto-generate this
     // for now, please keep in sync with PVE::Tools::kvmkeymaps
     kvm_keymaps: {
+       '__default__': Proxmox.Utils.defaultText,
        //ar: 'Arabic',
        da: 'Danish',
        de: 'German',
@@ -591,6 +583,7 @@ Ext.define('PVE.Utils', {
     },
 
     kvm_vga_drivers: {
+       '__default__': Proxmox.Utils.defaultText,
        std: gettext('Standard VGA'),
        vmware: gettext('VMware compatible'),
        qxl: 'SPICE',
@@ -602,6 +595,7 @@ Ext.define('PVE.Utils', {
        serial2: gettext('Serial terminal') + ' 2',
        serial3: gettext('Serial terminal') + ' 3',
        virtio: 'VirtIO-GPU',
+       'virtio-gl': 'VirGL GPU',
        none: Proxmox.Utils.noneText,
     },
 
@@ -609,20 +603,8 @@ Ext.define('PVE.Utils', {
        if (!value || value === '__default__') {
            return Proxmox.Utils.defaultText;
        }
-       var text = PVE.Utils.kvm_keymaps[value];
-       if (text) {
-           return text + ' (' + value + ')';
-       }
-       return value;
-    },
-
-    kvm_keymap_array: function() {
-       var data = [['__default__', PVE.Utils.render_kvm_language('')]];
-       Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
-           data.push([key, PVE.Utils.render_kvm_language(value)]);
-       });
-
-       return data;
+       let text = PVE.Utils.kvm_keymaps[value];
+       return text ? `${text} (${value})` : value;
     },
 
     console_map: {
@@ -634,40 +616,19 @@ Ext.define('PVE.Utils', {
 
     render_console_viewer: function(value) {
        value = value || '__default__';
-       if (PVE.Utils.console_map[value]) {
-           return PVE.Utils.console_map[value];
-       }
-       return value;
-    },
-
-    console_viewer_array: function() {
-       return Ext.Array.map(Object.keys(PVE.Utils.console_map), function(v) {
-           return [v, PVE.Utils.render_console_viewer(v)];
-       });
+       return PVE.Utils.console_map[value] || value;
     },
 
     render_kvm_vga_driver: function(value) {
        if (!value) {
            return Proxmox.Utils.defaultText;
        }
-       var vga = PVE.Parser.parsePropertyString(value, 'type');
-       var text = PVE.Utils.kvm_vga_drivers[vga.type];
+       let vga = PVE.Parser.parsePropertyString(value, 'type');
+       let text = PVE.Utils.kvm_vga_drivers[vga.type];
        if (!vga.type) {
            text = Proxmox.Utils.defaultText;
        }
-       if (text) {
-           return text + ' (' + value + ')';
-       }
-       return value;
-    },
-
-    kvm_vga_driver_array: function() {
-       var data = [['__default__', PVE.Utils.render_kvm_vga_driver('')]];
-       Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
-           data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
-       });
-
-       return data;
+       return text ? `${text} (${value})` : value;
     },
 
     render_kvm_startup: function(value) {
@@ -733,22 +694,38 @@ Ext.define('PVE.Utils', {
            ipanel: 'pveAuthADPanel',
            syncipanel: 'pveAuthLDAPSyncPanel',
            add: true,
+           tfa: true,
+           pwchange: true,
        },
        ldap: {
            name: gettext('LDAP Server'),
            ipanel: 'pveAuthLDAPPanel',
            syncipanel: 'pveAuthLDAPSyncPanel',
            add: true,
+           tfa: true,
+           pwchange: true,
+       },
+       openid: {
+           name: gettext('OpenID Connect Server'),
+           ipanel: 'pveAuthOpenIDPanel',
+           add: true,
+           tfa: false,
+           pwchange: false,
+           iconCls: 'pmx-itype-icon-openid-logo',
        },
        pam: {
            name: 'Linux PAM',
            ipanel: 'pveAuthBasePanel',
            add: false,
+           tfa: true,
+           pwchange: true,
        },
        pve: {
            name: 'Proxmox VE authentication server',
            ipanel: 'pveAuthBasePanel',
            add: false,
+           tfa: true,
+           pwchange: true,
        },
     },
 
@@ -771,6 +748,12 @@ Ext.define('PVE.Utils', {
            faIcon: 'folder',
            backups: false,
        },
+       btrfs: {
+           name: 'BTRFS',
+           ipanel: 'BTRFSInputPanel',
+           faIcon: 'folder',
+           backups: true,
+       },
        nfs: {
            name: 'NFS',
            ipanel: 'NFSInputPanel',
@@ -778,7 +761,7 @@ Ext.define('PVE.Utils', {
            backups: true,
        },
        cifs: {
-           name: 'CIFS',
+           name: 'SMB/CIFS',
            ipanel: 'CIFSInputPanel',
            faIcon: 'building',
            backups: true,
@@ -984,11 +967,8 @@ Ext.define('PVE.Utils', {
            value = !record || record.get('monhost') ? 'cephfs' : 'pvecephfs';
        }
 
-       var schema = PVE.Utils.storageSchema[value];
-       if (schema) {
-           return schema.name;
-       }
-       return Proxmox.Utils.unknownText;
+       let schema = PVE.Utils.storageSchema[value];
+       return schema?.name ?? value;
     },
 
     format_ha: function(value) {
@@ -1086,6 +1066,18 @@ Ext.define('PVE.Utils', {
        return Ext.Date.format(new Date(value * 1000), 'l d F Y H:i:s');
     },
 
+    // render a timestamp or pending
+    render_next_event: function(value) {
+       if (!value) {
+           return '-';
+       }
+       let now = new Date(), next = new Date(value * 1000);
+       if (next < now) {
+           return gettext('pending');
+       }
+       return Proxmox.Utils.render_timestamp(value);
+    },
+
     calculate_mem_usage: function(data) {
        if (!Ext.isNumeric(data.mem) ||
            data.maxmem === 0 ||
@@ -1286,17 +1278,6 @@ Ext.define('PVE.Utils', {
        return Ext.htmlEncode(first + " " + last);
     },
 
-    render_u2f_error: function(error) {
-       var ErrorNames = {
-           '1': gettext('Other Error'),
-           '2': gettext('Bad Request'),
-           '3': gettext('Configuration Unsupported'),
-           '4': gettext('Device Ineligible'),
-           '5': gettext('Timeout'),
-       };
-       return "U2F Error: " + ErrorNames[error] || Proxmox.Utils.unknownText;
-    },
-
     windowHostname: function() {
        return window.location.hostname.replace(Proxmox.Utils.IP6_bracket_match,
             function(m, addr, offset, original) { return addr; });
@@ -1351,7 +1332,7 @@ Ext.define('PVE.Utils', {
            allowSpice = consoles.spice;
            allowXtermjs = !!consoles.xtermjs;
        }
-       let dv = PVE.VersionInfo.console || (type === 'kvm' ? 'vv' : 'xtermjs');
+       let dv = PVE.UIOptions.console || (type === 'kvm' ? 'vv' : 'xtermjs');
        if (dv === 'vv' && !allowSpice) {
            dv = allowXtermjs ? 'xtermjs' : 'html5';
        } else if (dv === 'xtermjs' && !allowXtermjs) {
@@ -1500,18 +1481,19 @@ Ext.define('PVE.Utils', {
     },
 
     loadSSHKeyFromFile: function(file, callback) {
-       // ssh-keygen produces 740 bytes for an average 4096 bit rsa key, with
-       // a user@host comment, 1420 for 8192 bits; current max is 16kbit
-       // assume: 740*8 for max. 32kbit (5920 byte file)
-       // round upwards to nearest nice number => 8192 bytes, leaves lots of comment space
-       if (file.size > 8192) {
-           Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size);
+       // ssh-keygen produces ~ 740 bytes for a 4096 bit RSA key,  current max is 16 kbit, so assume:
+       // 740 * 8 for max. 32kbit (5920 bytes), round upwards to 8192 bytes, leaves lots of comment space
+       PVE.Utils.loadFile(file, callback, 8192);
+    },
+
+    loadFile: function(file, callback, maxSize) {
+       maxSize = maxSize || 32 * 1024;
+       if (file.size > maxSize) {
+           Ext.Msg.alert(gettext('Error'), `${gettext("Invalid file size")}: ${file.size} > ${maxSize}`);
            return;
        }
        let reader = new FileReader();
-       reader.onload = function(evt) {
-           callback(evt.target.result);
-       };
+       reader.onload = evt => callback(evt.target.result);
        reader.readAsText(file);
     },
 
@@ -1531,6 +1513,7 @@ Ext.define('PVE.Utils', {
        sata: 6,
        scsi: 31,
        virtio: 16,
+       unused: 256,
     },
 
     // types is either undefined (all busses), an array of busses, or a single bus
@@ -1562,12 +1545,12 @@ Ext.define('PVE.Utils', {
     },
 
     mp_counts: {
-       mps: 256,
+       mp: 256,
        unused: 256,
     },
 
     forEachMP: function(func, includeUnused) {
-       for (let i = 0; i < PVE.Utils.mp_counts.mps; i++) {
+       for (let i = 0; i < PVE.Utils.mp_counts.mp; i++) {
            let cont = func('mp', i);
            if (!cont && cont !== undefined) {
                return;
@@ -1586,7 +1569,58 @@ Ext.define('PVE.Utils', {
        }
     },
 
-    hardware_counts: { net: 32, usb: 5, hostpci: 16, audio: 1, efidisk: 1, serial: 4, rng: 1 },
+    hardware_counts: {
+       net: 32,
+       usb: 14,
+       usb_old: 5,
+       hostpci: 16,
+       audio: 1,
+       efidisk: 1,
+       serial: 4,
+       rng: 1,
+       tpmstate: 1,
+    },
+
+    // we can have usb6 and up only for specific machine/ostypes
+    get_max_usb_count: function(ostype, machine) {
+       if (!ostype) {
+           return PVE.Utils.hardware_counts.usb_old;
+       }
+
+       let match = /-(\d+).(\d+)/.exec(machine ?? '');
+       if (!match || PVE.Utils.qemu_min_version([match[1], match[2]], [7, 1])) {
+           if (ostype === 'l26') {
+               return PVE.Utils.hardware_counts.usb;
+           }
+           let os_match = /^win(\d+)$/.exec(ostype);
+           if (os_match && os_match[1] > 7) {
+               return PVE.Utils.hardware_counts.usb;
+           }
+       }
+
+       return PVE.Utils.hardware_counts.usb_old;
+    },
+
+    // parameters are expected to be arrays, e.g. [7,1], [4,0,1]
+    // returns true if toCheck is equal or greater than minVersion
+    qemu_min_version: function(toCheck, minVersion) {
+       let i;
+       for (i = 0; i < toCheck.length && i < minVersion.length; i++) {
+           if (toCheck[i] < minVersion[i]) {
+               return false;
+           }
+       }
+
+       if (minVersion.length > toCheck.length) {
+           for (; i < minVersion.length; i++) {
+               if (minVersion[i] !== 0) {
+                   return false;
+               }
+           }
+       }
+
+       return true;
+    },
 
     cleanEmptyObjectKeys: function(obj) {
        for (const propName of Object.keys(obj)) {
@@ -1741,6 +1775,191 @@ Ext.define('PVE.Utils', {
 
        return true;
     },
+
+    sortByPreviousUsage: function(vmconfig, controllerList) {
+       if (!controllerList) {
+           controllerList = ['ide', 'virtio', 'scsi', 'sata'];
+       }
+       let usedControllers = {};
+       for (const type of Object.keys(PVE.Utils.diskControllerMaxIDs)) {
+           usedControllers[type] = 0;
+       }
+
+       for (const property of Object.keys(vmconfig)) {
+           if (property.match(PVE.Utils.bus_match) && !vmconfig[property].match(/media=cdrom/)) {
+               const foundController = property.match(PVE.Utils.bus_match)[1];
+               usedControllers[foundController]++;
+           }
+       }
+
+       let sortPriority = PVE.qemu.OSDefaults.getDefaults(vmconfig.ostype).busPriority;
+
+       let sortedList = Ext.clone(controllerList);
+       sortedList.sort(function(a, b) {
+           if (usedControllers[b] === usedControllers[a]) {
+               return sortPriority[b] - sortPriority[a];
+           }
+           return usedControllers[b] - usedControllers[a];
+       });
+
+       return sortedList;
+    },
+
+    nextFreeDisk: function(controllers, config) {
+       for (const controller of controllers) {
+           for (let i = 0; i < PVE.Utils.diskControllerMaxIDs[controller]; i++) {
+               let confid = controller + i.toString();
+               if (!Ext.isDefined(config[confid])) {
+                   return {
+                       controller,
+                       id: i,
+                       confid,
+                   };
+               }
+           }
+       }
+
+       return undefined;
+    },
+
+    nextFreeMP: function(type, config) {
+       for (let i = 0; i < PVE.Utils.mp_counts[type]; i++) {
+           let confid = `${type}${i}`;
+           if (!Ext.isDefined(config[confid])) {
+               return {
+                   type,
+                   id: i,
+                   confid,
+               };
+           }
+       }
+
+       return undefined;
+    },
+
+    escapeNotesTemplate: function(value) {
+       let replace = {
+           '\\': '\\\\',
+           '\n': '\\n',
+       };
+       return value.replace(/(\\|[\n])/g, match => replace[match]);
+    },
+
+    unEscapeNotesTemplate: function(value) {
+       let replace = {
+           '\\\\': '\\',
+           '\\n': '\n',
+       };
+       return value.replace(/(\\\\|\\n)/g, match => replace[match]);
+    },
+
+    notesTemplateVars: ['cluster', 'guestname', 'node', 'vmid'],
+
+    updateUIOptions: function() {
+       Proxmox.Utils.API2Request({
+           url: '/cluster/options',
+           method: 'GET',
+           success: function(response) {
+               PVE.UIOptions = {
+                   'allowed-tags': [],
+               };
+               for (const option of ['allowed-tags', 'console', 'tag-style']) {
+                   PVE.UIOptions[option] = response?.result?.data?.[option];
+               }
+
+               PVE.Utils.updateTagList(PVE.UIOptions['allowed-tags']);
+               PVE.Utils.updateTagSettings(PVE.UIOptions?.['tag-style']);
+           },
+       });
+    },
+
+    tagList: [],
+
+    updateTagList: function(tags) {
+       PVE.Utils.tagList = [...new Set([...tags])].sort();
+    },
+
+    parseTagOverrides: function(overrides) {
+       let colors = {};
+       (overrides || "").split(';').forEach(color => {
+           if (!color) {
+               return;
+           }
+           let [tag, color_hex, font_hex] = color.split(':');
+           let r = parseInt(color_hex.slice(0, 2), 16);
+           let g = parseInt(color_hex.slice(2, 4), 16);
+           let b = parseInt(color_hex.slice(4, 6), 16);
+           colors[tag] = [r, g, b];
+           if (font_hex) {
+               colors[tag].push(parseInt(font_hex.slice(0, 2), 16));
+               colors[tag].push(parseInt(font_hex.slice(2, 4), 16));
+               colors[tag].push(parseInt(font_hex.slice(4, 6), 16));
+           }
+       });
+       return colors;
+    },
+
+    tagOverrides: {},
+
+    updateTagOverrides: function(colors) {
+       let sp = Ext.state.Manager.getProvider();
+       let color_state = sp.get('colors', '');
+       let browser_colors = PVE.Utils.parseTagOverrides(color_state);
+       PVE.Utils.tagOverrides = Ext.apply({}, browser_colors, colors);
+    },
+
+    updateTagSettings: function(style) {
+       let overrides = style?.['color-map'];
+       PVE.Utils.updateTagOverrides(PVE.Utils.parseTagOverrides(overrides ?? ""));
+
+       let shape = style?.shape ?? 'circle';
+       if (shape === '__default__') {
+           style = 'circle';
+       }
+
+       Ext.ComponentQuery.query('pveResourceTree')[0].setUserCls(`proxmox-tags-${shape}`);
+       PVE.data.ResourceStore.fireEvent('load');
+       Ext.GlobalEvents.fireEvent('loadedUiOptions');
+    },
+
+    tagTreeStyles: {
+       '__default__': `${Proxmox.Utils.defaultText} (${gettext('Cirlce')})`,
+       'full': gettext('Full'),
+       'circle': gettext('Circle'),
+       'dense': gettext('Dense'),
+       'none': Proxmox.Utils.NoneText,
+    },
+
+    tagOrderOptions: {
+       '__default__': `${Proxmox.Utils.defaultText} (${gettext('Alphabetical')})`,
+       'config': gettext('Configuration'),
+       'alphabetical': gettext('Alphabetical'),
+    },
+
+    renderTags: function(tagstext, overrides) {
+       let text = '';
+       if (tagstext) {
+           let tags = (tagstext.split(/[,; ]/) || []).filter(t => !!t);
+           if (PVE.Utils.shouldSortTags()) {
+               tags = tags.sort((a, b) => {
+                   let alc = a.toLowerCase();
+                   let blc = b.toLowerCase();
+                   return alc < blc ? -1 : blc < alc ? 1 : a.localeCompare(b);
+               });
+           }
+           text += ' ';
+           tags.forEach((tag) => {
+               text += Proxmox.Utils.getTagElement(tag, overrides);
+           });
+       }
+       return text;
+    },
+
+    shouldSortTags: function() {
+       return !(PVE.UIOptions?.['tag-style']?.ordering === 'config');
+    },
+
+    tagCharRegex: /^[a-z0-9+_.-]+$/i,
 },
 
     singleton: true,
@@ -1768,6 +1987,7 @@ Ext.define('PVE.Utils', {
            cephdestroymon: ['Ceph Monitor', gettext('Destroy')],
            cephdestroyosd: ['Ceph OSD', gettext('Destroy')],
            cephdestroypool: ['Ceph Pool', gettext('Destroy')],
+           cephdestroyfs: ['CephFS', gettext('Destroy')],
            cephfscreate: ['CephFS', gettext('Create')],
            cephsetpool: ['Ceph Pool', gettext('Edit')],
            cephsetflags: ['', gettext('Change global Ceph flags')],
@@ -1775,7 +1995,7 @@ Ext.define('PVE.Utils', {
            clusterjoin: ['', gettext('Join Cluster')],
            dircreate: [gettext('Directory Storage'), gettext('Create')],
            dirremove: [gettext('Directory'), gettext('Remove')],
-           download: ['', gettext('Download')],
+           download: [gettext('File'), gettext('Download')],
            hamigrate: ['HA', gettext('Migrate')],
            hashutdown: ['HA', gettext('Shutdown')],
            hastart: ['HA', gettext('Start')],
@@ -1783,7 +2003,9 @@ Ext.define('PVE.Utils', {
            imgcopy: ['', gettext('Copy data')],
            imgdel: ['', gettext('Erase data')],
            lvmcreate: [gettext('LVM Storage'), gettext('Create')],
+           lvmremove: ['Volume Group', gettext('Remove')],
            lvmthincreate: [gettext('LVM-Thin Storage'), gettext('Create')],
+           lvmthinremove: ['Thinpool', gettext('Remove')],
            migrateall: ['', gettext('Migrate all VMs and Containers')],
            'move_volume': ['CT', gettext('Move Volume')],
            'pbs-download': ['VM/CT', gettext('File Restore Download')],
@@ -1813,6 +2035,7 @@ Ext.define('PVE.Utils', {
            startall: ['', gettext('Start all VMs and Containers')],
            stopall: ['', gettext('Stop all VMs and Containers')],
            unknownimgdel: ['', gettext('Destroy image from unknown guest')],
+           wipedisk: ['Device', gettext('Wipe Disk')],
            vncproxy: ['VM/CT', gettext('Console')],
            vncshell: ['', gettext('Shell')],
            vzclone: ['CT', gettext('Clone')],
@@ -1834,6 +2057,7 @@ Ext.define('PVE.Utils', {
            vztemplate: ['CT', gettext('Convert to template')],
            vzumount: ['CT', gettext('Unmount')],
            zfscreate: [gettext('ZFS Storage'), gettext('Create')],
+           zfsremove: ['ZFS Pool', gettext('Remove')],
        });
     },