|
| 1 | +from zenlib.util import colorize as c_ |
| 2 | +from zenlib.util import contains, unset |
| 3 | + |
| 4 | +__version__ = "0.1.0" |
| 5 | + |
| 6 | +VM_PRODUCT_NAMES = { |
| 7 | + "Virtual Machine": ["virtio_blk"], |
| 8 | + "Parallels ARM Virtual Machine": ["virtio_blk"], |
| 9 | + "Standard PC (Q35 + ICH9, 2009)": ["virtio_blk"], |
| 10 | +} |
| 11 | + |
| 12 | +VM_VENDOR_NAMES = { |
| 13 | + "Microsoft Corporation": ["hv_storvsc"], |
| 14 | + "VMware, Inc.": ["vmw_pvscsi"], |
| 15 | + "Xen": ["xen_blk"], |
| 16 | + "QEMU": ["virtio_blk"], |
| 17 | + "Parallels International GmbH.": ["virtio_blk"], |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +@contains("hostonly", "hostonly is not enabled, skipping platform detection.", log_level=30) |
| 22 | +def get_platform_info(self): |
| 23 | + """Detects plaform information such as the vendor and product name""" |
| 24 | + with open("/sys/class/dmi/id/product_name", "r") as f: |
| 25 | + self["_dmi_product_name"] = f.read().strip() |
| 26 | + |
| 27 | + with open("/sys/class/dmi/id/sys_vendor", "r") as f: |
| 28 | + self["_dmi_system_vendor"] = f.read().strip() |
| 29 | + |
| 30 | + |
| 31 | +@unset("virtual_machine", "virtual_machine is already set, skipping VM detection.", log_level=10) |
| 32 | +@contains("hostonly", "hostonly is not enabled, skipping VM detection.", log_level=30) |
| 33 | +def autodetect_virtual_machine(self): |
| 34 | + """Detects if the system is running in a virtual machine, adds relevant kernel modules to the list. |
| 35 | + Sets the `virtual_machine` attribute to True if a VM is detected, to be used by other modules. |
| 36 | + """ |
| 37 | + kmods = set() |
| 38 | + kmods.update(VM_PRODUCT_NAMES.get(self["_dmi_product_name"], [])) |
| 39 | + kmods.update(VM_VENDOR_NAMES.get(self["_dmi_system_vendor"], [])) |
| 40 | + |
| 41 | + if kmods: |
| 42 | + self.logger.info( |
| 43 | + f"[{c_(self['_dmi_system_vendor'], color='cyan', bold=True)}]({c_(self['_dmi_product_name'], color='cyan', bright=True)}) Detected VM kmods: {c_((' ').join(kmods), color='magenta', bright=True)}" |
| 44 | + ) |
| 45 | + self["virtual_machine"] = True |
0 commit comments