Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add is_container charm library #9

Merged
merged 4 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions lib/charms/hpc_libs/v0/is_container.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Copyright 2024 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Detect if machine is a container instance.

Even though Juju supports using LXD containers as the backing cloud for
deploying charmed operators, not all HPC applications work within system containers,
and some need additional configuration. This simple charm library provides utilities
for identifying the virtualization runtime for a charmed operator.

### Example Usage:

```python3
from charms.hpc_libs.v0.is_container import is_container

class ApplicationCharm(CharmBase):

def __init__(self, *args):
super().__init__(*args)

self.framework.observe(self.on.install, self._on_install)

def _on_install(self, _: InstallEvent) -> None:
if is_container():
self.unit.status = BlockedStatus("app does not support container runtime")

# Proceed with installation.
...
```
"""

import shutil
import subprocess

# The unique Charmhub library identifier, never change it
LIBID = "eb95ad73da1941c0af186ee670f96507"

# Increment this major API version when introducing breaking changes
LIBAPI = 0

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 1


class UnknownVirtStateError(Exception):
"""Raise error if unknown virtualization state is returned."""

@property
def message(self) -> str:
"""Return message passed as argument to exception."""
return self.args[0]


def is_container() -> bool:
"""Detect if the machine is a container instance.

Raises:
DetectVirtNotFoundError: Raised if `systemd-detect-virt` is not found on machine.
"""
if shutil.which("systemd-detect-virt") is None:
raise UnknownVirtStateError(
(
"executable `systemd-detect-virt` not found. "
+ "cannot determine if machine is a container instance"
)
)

result = subprocess.run(["systemd-detect-virt", "--container"])
return result.returncode == 0
10 changes: 10 additions & 0 deletions tests/integration/is_container/test_is_container.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.

from lib.charms.hpc_libs.v0.is_container import is_container


def test_is_container() -> None:
"""Test that `is_container` properly detects the system container."""
assert is_container() is True
11 changes: 10 additions & 1 deletion tests/integration/test_hpc_libs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ acts:
path: dev-requirements.txt
- host-path: tests/integration/slurm_ops
path: slurm_ops
- host-path: tests/integration/is_container
path: is_container
scenes:
- name: "Install dependencies in a virtual environment"
run: |
Expand All @@ -34,10 +36,17 @@ acts:
apt install -y python3-venv python3-yaml
python3 -m venv venv --system-site-packages
venv/bin/python3 -m pip install -r dev-requirements.txt
- name: "Run integration tests with pytest"
- name: "Run `slurm_ops` integration tests"
run: |
venv/bin/python3 -m pytest -v \
-s \
--tb native \
--log-cli-level=INFO \
slurm_ops
- name: "Run `is_container` integration tests"
run: |
venv/bin/python3 -m pytest -v \
-s \
--tb native \
--log-cli-level=INFO \
is_container
40 changes: 40 additions & 0 deletions tests/unit/test_is_container.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.

"""Test `is_container` library."""

from unittest import TestCase
from unittest.mock import patch

from charms.hpc_libs.v0.is_container import UnknownVirtStateError, is_container


@patch("charms.hpc_libs.v0.is_container.shutil.which", return_value="/usr/bin/systemd-detect-virt")
@patch("charms.hpc_libs.v0.is_container.subprocess.run")
class TestIsContainer(TestCase):

def test_inside_container(self, run, _) -> None:
"""Test that `is_container` returns True when inside a container."""
run.return_value.returncode = 0
self.assertTrue(is_container())

def test_inside_virtual_machine(self, run, _) -> None:
"""Test that `is_container` returns False when inside a virtual machine."""
run.return_value.returncode = 1
self.assertFalse(is_container())

def test_detect_virt_not_found(self, _, which) -> None:
"""Test that correct error is thrown if `systemd-detect-virt` is not found."""
which.return_value = None

try:
is_container()
except UnknownVirtStateError as e:
self.assertEqual(
e.message,
(
"executable `systemd-detect-virt` not found. "
+ "cannot determine if machine is a container instance"
),
)