canonical / operator-libs-linux

Linux helper libraries for the operator framework
Apache License 2.0
11 stars 37 forks source link

[Systemd] support detection of virt substrate #127

Open phvalguima opened 1 month ago

phvalguima commented 1 month ago

Can we add support for systemd-detect-virt on our systemd lib?

That is important, e.g. when we want to use sysctl lib and some of the options may be applicable, but others cannot.

Proposal:

import subprocess

...

def running_as_vm():
    try:
        return subprocess.run(["systemd-detect-virt", "--vm"]).returncode == 0
    except FileNotFoundError:
        # No systemd! Either this is a docker container OR a very old distro
        return False

def running_as_lxc():
    try:
        return subprocess.run(["systemd-detect-virt", "--container"]).returncode == 0
    except FileNotFoundError:
        # No systemd! Either this is a docker container OR a very old distro
        return False

def running_as_container():
    try:
        return subprocess.run(["systemd-detect-virt", "--container"]).returncode == 0
    except FileNotFoundError:
        return True
NucciTheBoss commented 1 month ago

@phvalguima not sure if this is similar to what you're looking for, but HPC does have a library for detecting if your machine charm is currently running within a container: https://github.com/charmed-hpc/hpc-libs/blob/main/lib/charms/hpc_libs/v0/is_container.py

We kept it systemd agnostic however - e.g. didn't include it in the systemd charm library - as some of our routines/applications won't work if inside an LXD container but aren't managed directly by systemd.