OCI containers and Python

I’ve recently pushed Python bindings to the crun git repo. Handling JSON data is extremely easy in Python and makes it a great candidate to quickly customize the container configuration and launch it. Keep in mind that crun is only an OCI runtime for running a container, it doesn’t take care of pulling and storing images. You’ll need a different tool for that.

For more details, this is the commit that adds the Python bindings: https://github.com/giuseppe/crun/commit/a2b5faf88a4abde241ad813afdf6688e38fb7ca2

By default the Python bindings are not built, you’ll need to specify –with-python-bindings to the configure script to build them.

Once you have the Python bindings, a simple script can be used to customize and launch a container:

import python_crun
import json

# the spec() function generates a default configuration for
# running the OCI container, parse directly the JSON. 
spec = json.loads(python_crun.spec())

# Let's change the rootfs of the container to point to the correct
# path.  This is where the image is exploded on disk.
spec['root']['path'] = '/home/gscrivano/example-container/rootfs'

# We don't want the container to do much, just greet us
spec['process']['args'] = ['/bin/echo', 'hello from a container']

# From the customized configuration, we create the OCI container.
ctr = python_crun.load_from_memory(json.dumps(spec))

# The context says what ID the container will have, and optionally allows
# to tweak other settings as well such as the state root, using systemd
# for the cgroups
ctx = python_crun.make_context("test-container")

# We don't want to print any warning.

# And finally run the container
python_crun.run(ctx, ctr)

Store it in a launch_container.py file.

Now, from the crun build root directory:

# PYTHONPATH=.libs python ./launch_container.py
hello from a container

Leave a Reply

Your email address will not be published. Required fields are marked *