set vm ram in GB instead of MB in gui

nd6376

New Member
Feb 4, 2025
6
1
3
is it possible to input the ram of a vm in the "create VM" gui in GB increments on top of entering the exact MB required?

eg, 8GB instead of 8192MB via a dropbox for MB, GB, TB

1783558022894.png
 
Last edited:
  • Like
Reactions: EllerholdAG
But honestly I dont know any guest OS that runs fine on sub 1 GB RAM - but that may be my shortcoming.
I have some VMs with 512 MiB...768 MiB:
Code:
 $ lsb_release -a; free
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 13 (trixie)
Release:        13
Codename:       trixie
              gesamt       benutzt     frei      gemns.  Puffer/Cache verfĂĽgbar
Speicher:     475560      280936       19584         296      187844      194624
Swap:         808956       17256      791700

This is just a specific jumphost, no "real" services. And it still works with 384 MiB too... :-)
 
Should have been more precise.
I think it should be done like php.ini settings (and many other software) uses these settings.

344M
5G
1T

Right know, I have to calculate "hmm... 1GB is 1024MB. So that means * 2 * 2 = 4096 gives me a 4GB machine.
Instead of just inserting "4G".

Just like I would not use docker deploy.resources.limits set to 4096M but 4G instead.
 
Last edited:
  • Like
Reactions: nd6376
Right know, I have to calculate "hmm... 1GB is 1024MB. So that means * 2 * 2 = 4096 gives me a 4GB machine.
After a few decades you know them by heart or are just a nerd how can simple calculate them in the head.

But honestly I dont know any guest OS that runs fine on sub 1 GB RAM - but that may be my shortcoming.
Windows? No .... but I have hundreds of Linux VMs running with such a low memory amount. If you're e.g. just running VPNs or do some kind of network routing, it's totally fine. I had to increase it over the years from 128M to kno 384 MB with Debian Trixie, yet you cannot install it with such low memory footprint, but it'll run without swap flawlessly.
 
I have many CTs, Some running with less than 128MB RAM.
Cool! That's (of course) the positive aspect of containers.

Unfortunately I do not like them - my virtual assets are VMs. (Actually ~97 percent of them.)
 
  • Like
Reactions: Johannes S
i made a script that adds in the changes for both the LXC and VM creations and then "edit" menus after.

if anyone wants to review or modify it feel free.

pve-unit-dropdown-patch-updated.sh :


Bash:
#!/bin/bash
cat > /usr/local/share/pve-unit-dropdown.js <<'EOF'
/* pve-unit-dropdown:begin v1 */
(function () {
    if (typeof Ext === 'undefined' || !Ext.form || !Ext.form.field || !Ext.form.field.Number) {
        return;
    }

    // [unit, size in base units]; base is MiB for memory/swap and GiB for disks
    const UNITS = {
        MiB: [['MiB', 1], ['GiB', 1024], ['TiB', 1024 * 1024]],
        GiB: [['GiB', 1], ['TiB', 1024]],
    };

    function attach(field, baseUnit) {
        if (!field || field.pveUnitAttached || !field.isFormField) {
            return;
        }
        field.pveUnitAttached = true;

        const units = UNITS[baseUnit];
        const factors = {};
        units.forEach((u) => { factors[u[0]] = u[1]; });

        const intBase = field.allowDecimals === false;
        const prec = field.decimalPrecision > 0 ? field.decimalPrecision : 3;
        const origStep = field.step || 1;
        const baseLabel = String(field.fieldLabel || '').replace(/\s*\([^()]*\)\s*$/, '');

        field.pveUnit = baseUnit;
        const factor = () => factors[field.pveUnit];
        const show = (v) => String(parseFloat((v / factor()).toFixed(6)));

        // typing decimals (1.5 GiB) must be possible: rebuild the key mask
        if (intBase) {
            field.allowDecimals = true;
            field.setMinValue(field.minValue);
        }

        // value stays in base units everywhere; only the text is scaled
        field.rawToValue = function (raw) {
            const n = parseFloat(String(raw).replace(this.decimalSeparator, '.'));
            if (isNaN(n)) {
                return raw || null;
            }
            const base = n * factor();
            return intBase ? Math.round(base) : parseFloat(base.toFixed(prec));
        };

        field.valueToRaw = function (value) {
            const n = typeof value === 'number'
                ? value
                : parseFloat(String(value).replace(this.decimalSeparator, '.'));
            if (isNaN(n)) {
                return '';
            }
            return show(n).replace('.', this.decimalSeparator);
        };

        field.getSubmitValue = function () {
            const v = this.getValue();
            return v === null || v === undefined ? '' : String(v);
        };

        field.getErrors = function (value) {
            const me = this;
            value = arguments.length > 0 ? value : me.processRawValue(me.getRawValue());
            const errors = Ext.form.field.Text.prototype.getErrors.call(me, value);
            if (value.length < 1) {
                return errors;
            }
            const s = String(value).replace(me.decimalSeparator, '.');
            if (isNaN(s)) {
                errors.push(Ext.String.format(me.nanText, s));
                return errors;
            }
            const num = me.rawToValue(value);
            const disp = (v) => `${show(v)} ${me.pveUnit}`;
            if (me.minValue === 0 && num < 0) {
                errors.push(me.negativeText);
            } else if (num < me.minValue) {
                errors.push(Ext.String.format(me.minText, disp(me.minValue)));
            }
            if (num > me.maxValue) {
                errors.push(Ext.String.format(me.maxText, disp(me.maxValue)));
            }
            return errors;
        };

        const syncStep = () => {
            field.step = factor() > 1 ? factor() : origStep;
        };

        const renderLabel = () => {
            if (!field.rendered || !field.labelTextEl) {
                return;
            }
            const style = 'cursor:pointer;text-decoration:underline dotted;';
            field.labelTextEl.dom.innerHTML =
                `${Ext.String.htmlEncode(baseLabel)} (<a href="#" class="pve-unit-sel" ` +
                `style="${style}">${field.pveUnit} &#9662;</a>)${field.labelSeparator || ''}`;
        };

        const setUnit = (unit) => {
            if (unit === field.pveUnit) {
                return;
            }
            const cur = field.getValue(); // base units, using the old unit
            field.pveUnit = unit;
            syncStep();
            renderLabel();
            if (typeof cur === 'number') {
                field.setRawValue(field.valueToRaw(cur));
            }
            field.validate();
        };

        const showMenu = (anchor) => {
            if (!field.pveUnitMenu) {
                field.pveUnitMenu = Ext.create('Ext.menu.Menu', {
                    items: units.map((u) => ({
                        text: u[0],
                        checked: false,
                        group: `pveunit-${field.id}`,
                        handler: () => setUnit(u[0]),
                    })),
                });
                field.on('destroy', () => field.pveUnitMenu.destroy());
            }
            field.pveUnitMenu.items.each((item) => {
                item.setChecked(item.text === field.pveUnit, true);
            });
            const xy = anchor.getXY();
            field.pveUnitMenu.showAt(xy[0], xy[1] + anchor.getHeight());
        };

        field.on('afterrender', () => {
            renderLabel();
            if (field.labelEl) {
                field.labelEl.on('click', (e) => {
                    const t = e.getTarget('.pve-unit-sel');
                    if (!t) {
                        return;
                    }
                    e.preventDefault();
                    if (!field.disabled && !field.readOnly) {
                        showMenu(Ext.get(t));
                    }
                });
            }
        });
    }

    function hook(name, fn) {
        const cls = Ext.ClassManager.get(name);
        if (!cls) {
            console.warn(`pve-unit-dropdown: class ${name} not found`);
            return;
        }
        const orig = cls.prototype.initComponent;
        Ext.override(cls, {
            initComponent: function () {
                orig.apply(this, arguments);
                try {
                    fn(this);
                } catch (e) {
                    console.warn('pve-unit-dropdown:', e);
                }
            },
        });
    }

    hook('PVE.form.MemoryField', (f) => attach(f, 'MiB'));
    hook('PVE.lxc.MemoryInputPanel', (p) => {
        ['memory', 'swap'].forEach((n) => attach(p.down(`field[name=${n}]`), 'MiB'));
    });
    hook('PVE.form.DiskStorageSelector', (p) => attach(p.getComponent('disksize'), 'GiB'));
})();
/* pve-unit-dropdown:end */
EOF

cat > /usr/local/sbin/pve-unit-patch.sh <<'SH'
#!/bin/bash
F=/usr/share/pve-manager/js/pvemanagerlib.js
JS=/usr/local/share/pve-unit-dropdown.js
[ -f "$JS" ] || exit 0
grep -q 'pve-unit-dropdown:begin' "$F" && exit 0
for c in PVE.form.MemoryField PVE.lxc.MemoryInputPanel PVE.form.DiskStorageSelector; do
  grep -q "Ext.define('$c'" "$F" || { echo "pve-unit-patch: $c not found, not patching" >&2; exit 0; }
done
v=$(dpkg-query -W -f='${Version}' pve-manager)
cp -n "$F" "/root/pvemanagerlib.js.orig-$v"
printf '\n' >> "$F"
cat "$JS" >> "$F"
systemctl restart pveproxy.service
echo "pve-unit-patch: applied"
exit 0
SH
chmod +x /usr/local/sbin/pve-unit-patch.sh

echo 'DPkg::Post-Invoke { "/usr/local/sbin/pve-unit-patch.sh || true"; };' > /etc/apt/apt.conf.d/99-pve-unit-patch
apt-get check && /usr/local/sbin/pve-unit-patch.sh


it has worked for me across many pve-manager updates, it just requires a hard-refresh of the WebGUI to load the updated JavaScript.
 
Last edited: