Goal: Dynamically add USB devices to running LXC instances using PyLxd library. Essentially, I want to pair an LXC container to a particular USB controller and whenever a device is added or removed from that controller, my script needs to update the container config to add or remove that device.
I have an LXC container running an Ubuntu 20.04 image on an Ubuntu 20.04 host. Using the built in LXC commands, I can add a USB device to a container and see it in the container, interact with it, etc. like so:
lxc config device add ubuc1 phone unix-char source=/dev/bus/usb/007/002
Where ubuc1
is my container name, phone
is the name I give the device, and source
describes where on the host the device is located.
I can verify that works by running ADB in my container and interacting with the device (I am using an Android phone to test this).
Likewise, I can remove a device:
lxc config device remove ubuc1 phone
I would like to automate this with a Python script, so I installed the PyLxd library and followed the documentation found here to add devices to a running instance. Here is my code attempting to do that:
from pylxd import Client
client = Client()
container = client.instances.get('ubuc1')
devStr = '/dev/bus/usb/007/002'
container.devices = { 'phone': {'source': devStr, 'type': 'unix-char' } }
container.save
Problem: If I attempt to print the device list from within my script after adding it, then I can see the device I added listed. However, if I try to read the device list from outside the script, for example using:
lxc config show ubuc1
I get an empty list. Additionally, I cannot see the device from within the container shell nor can ADB see the device inside the container. Essentially, my change only seems to affect the instance inside the Python script while I expect it to save the config to the LXD daemon and have the change be available no matter where or how I try and access the container.
What I've tried: I have tried punching in those Python command directly in a Python session with the same results. I have also tried putting the contents of devStr
directly in the container.devices
line and it did not change the outcome. I've used 2 different phones, 2 different USB controllers and 2 different containers and this problem arises in all cases. Additionally, I have tried to shut down and restart the container after adding the device to it with no luck.