Skip to content

Commit f1cce24

Browse files
[DPE-5588] Create architecture helpers lib (#560)
1 parent 5fefa33 commit f1cce24

File tree

2 files changed

+138
-0
lines changed

2 files changed

+138
-0
lines changed

lib/charms/mysql/v0/architecture.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Copyright 2024 Canonical Ltd.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Library to provide hardware architecture checks for VMs and K8s charms.
16+
17+
The WrongArchitectureWarningCharm class is designed to be used alongside
18+
the is-wrong-architecture helper function, as follows:
19+
20+
```python
21+
import sys
22+
23+
from ops import main
24+
from charms.mysql.v0.architecture import WrongArchitectureWarningCharm, is_wrong_architecture
25+
26+
if __name__ == "__main__":
27+
if is_wrong_architecture():
28+
main(WrongArchitectureWarningCharm)
29+
```
30+
"""
31+
32+
import logging
33+
import os
34+
import pathlib
35+
import platform
36+
import sys
37+
38+
import yaml
39+
from ops import BlockedStatus, CharmBase
40+
41+
# The unique Charmhub library identifier, never change it
42+
LIBID = "827e04542dba4c2a93bdc70ae40afdb1"
43+
LIBAPI = 0
44+
LIBPATCH = 1
45+
46+
PYDEPS = ["ops>=2.0.0", "pyyaml>=5.0"]
47+
48+
49+
logger = logging.getLogger(__name__)
50+
51+
52+
class WrongArchitectureWarningCharm(CharmBase):
53+
"""A fake charm class that only signals a wrong architecture deploy."""
54+
55+
def __init__(self, *args):
56+
super().__init__(*args)
57+
58+
hw_arch = platform.machine()
59+
self.unit.status = BlockedStatus(f"Error: Charm incompatible with {hw_arch} architecture")
60+
sys.exit(0)
61+
62+
63+
def is_wrong_architecture() -> bool:
64+
"""Checks if charm was deployed on wrong architecture."""
65+
manifest_path = pathlib.Path(os.environ["CHARM_DIR"], "manifest.yaml")
66+
67+
if not manifest_path.exists():
68+
logger.error("Cannot check architecture: manifest file not found in %s", manifest_path)
69+
return False
70+
71+
manifest = yaml.safe_load(manifest_path.read_text())
72+
73+
manifest_archs = []
74+
for base in manifest["bases"]:
75+
base_archs = base.get("architectures", [])
76+
manifest_archs.extend(base_archs)
77+
78+
hardware_arch = platform.machine()
79+
if ("amd64" in manifest_archs and hardware_arch == "x86_64") or (
80+
"arm64" in manifest_archs and hardware_arch == "aarch64"
81+
):
82+
logger.debug("Charm architecture matches")
83+
return False
84+
85+
logger.error("Charm architecture does not match")
86+
return True

tests/unit/test_architecture.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/usr/bin/env python3
2+
# Copyright 2024 Canonical Ltd.
3+
# See LICENSE file for licensing details.
4+
5+
from unittest.mock import patch
6+
7+
from charms.mysql.v0.architecture import is_wrong_architecture
8+
9+
TEST_MANIFEST = """
10+
bases:
11+
- architectures:
12+
- {arch}
13+
channel: '22.04'
14+
name: ubuntu
15+
"""
16+
17+
18+
def test_wrong_architecture_file_not_found():
19+
"""Tests if the function returns False when the charm file doesn't exist."""
20+
with (
21+
patch("os.environ", return_value={"CHARM_DIR": "/tmp"}),
22+
patch("pathlib.Path.exists", return_value=False),
23+
):
24+
assert not is_wrong_architecture()
25+
26+
27+
def test_wrong_architecture_amd64():
28+
"""Tests if the function correctly identifies arch when charm is AMD."""
29+
with (
30+
patch("os.environ", return_value={"CHARM_DIR": "/tmp"}),
31+
patch("pathlib.Path.exists", return_value=True),
32+
patch("pathlib.Path.read_text", return_value=TEST_MANIFEST.format(arch="amd64")),
33+
patch("platform.machine") as machine,
34+
):
35+
machine.return_value = "x86_64"
36+
assert not is_wrong_architecture()
37+
machine.return_value = "aarch64"
38+
assert is_wrong_architecture()
39+
40+
41+
def test_wrong_architecture_arm64():
42+
"""Tests if the function correctly identifies arch when charm is ARM."""
43+
with (
44+
patch("os.environ", return_value={"CHARM_DIR": "/tmp"}),
45+
patch("pathlib.Path.exists", return_value=True),
46+
patch("pathlib.Path.read_text", return_value=TEST_MANIFEST.format(arch="arm64")),
47+
patch("platform.machine") as machine,
48+
):
49+
machine.return_value = "x86_64"
50+
assert is_wrong_architecture()
51+
machine.return_value = "aarch64"
52+
assert not is_wrong_architecture()

0 commit comments

Comments
 (0)