Skip to content

Commit

Permalink
initial code for QM python api
Browse files Browse the repository at this point in the history
Signed-off-by: Douglas Schilling Landgraf <[email protected]>
  • Loading branch information
dougsland committed Jan 1, 2025
1 parent ef5463d commit d92d3af
Show file tree
Hide file tree
Showing 3 changed files with 236 additions and 0 deletions.
71 changes: 71 additions & 0 deletions api/python/qm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
For now just create a dir in the python latest version in your system.

1. Create a dir in the python site-packages for QM

```console
sudo mkdir -p /usr/lib/python3.13/site-packages/qm/
```

2. Copy library to it site-library for the specific user, in the case
bellow will be available only for root user.

```console
sudo cp __init__.py /usr/lib/python3.13/site-packages/qm/
```

3. Test it

Source code:

```python
from qm import QM

def main():
# Initialize the QM class
qm_manager = QM()

# Example: Start a container named 'qm'
container_name = "qm"
if qm_manager.start_container(container_name):
print(f"Container '{container_name}' started successfully.")
else:
print(f"Failed to start container '{container_name}'.")

# Example: Check the status of the container
status = qm_manager.container_status(container_name)
#print(f"Status of container '{container_name}': {status}")
print(f"Status of container {status}")

# Example: Count the number of running containers
running_count = qm_manager.count_running_containers()
print(f"Number of running containers: {running_count}")

# Example: Stop the container
if qm_manager.stop_container(container_name):
print(f"Container '{container_name}' stopped successfully.")
else:
print(f"Failed to stop container '{container_name}'.")

# Example: Check if the QM service is installed
if qm_manager.is_qm_service_installed():
print("QM service is installed.")
else:
print("QM service is not installed.")

# Example: Check if the QM service is running
if qm_manager.is_qm_service_running():
print("QM service is running.")
else:
print("QM service is not running.")

if __name__ == "__main__":
main()
```

Testing:

```console
$ sudo ./reading_information
QM service is installed.
QM service is running.
```
110 changes: 110 additions & 0 deletions api/python/qm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# 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.

import subprocess
import json

class QM:
"""
A class to manage containers inside the "qm" Podman container.
"""

def __init__(self, qm_container_name="qm"):
"""
Initialize the QM class with the name of the main Podman container.
Args:
qm_container_name (str): The name of the container running QM. Defaults to "qm".
"""
self.qm_container_name = qm_container_name

def execute_command(self, command):
"""
Executes a generic command inside the QM container.
Args:
command (list): The command to execute inside the QM container as a list of strings.
Returns:
str: The output of the executed command.
"""
full_command = ["podman", "exec", self.qm_container_name] + command
try:
result = subprocess.run(
full_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
return result.stdout.decode("utf-8").strip()
except subprocess.CalledProcessError as e:
return f"Error: {e.stderr.decode('utf-8').strip()}"

def start_container(self, name):
command = ["podman", "start", name]
output = self.execute_command(command)
return "started" in output.lower()

def stop_container(self, name):
command = ["podman", "stop", name]
output = self.execute_command(command)
return "stopped" in output.lower()

def container_status(self, name):
"""
Checks the status of a container inside the QM container.
Args:
name (str): The name of the container to check.
Returns:
str: The status of the container (e.g., "running", "stopped").
"""
command = ["podman", "inspect", "--format", "{{json .State}}", name]
output = self.execute_command(command)

if "Error" in output:
return output

try:
state = json.loads(output)
return state.get("Status", "unknown")
except json.JSONDecodeError:
return "unknown"

def count_running_containers(self):
"""
Counts the number of running containers inside the QM container.
Returns:
int: The number of running containers.
"""
command = ["podman", "ps", "--filter", "status=running", "--format", "{{.ID}}"]
output = self.execute_command(command)
if "Error" in output:
return 0
return len(output.splitlines()) if output else 0

def is_qm_service_installed(self):
try:
result = subprocess.run(
["rpm", "-q", "qm"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
return result.returncode == 0
except subprocess.CalledProcessError:
return False

def is_qm_service_running(self):
try:
result = subprocess.run(
["systemctl", "is-active", "qm"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
return result.stdout.decode("utf-8").strip() == "active"
except subprocess.CalledProcessError:
return False
55 changes: 55 additions & 0 deletions api/python/qm/examples/reading_information
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python
# 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.

from qm import QM

def main():
# Initialize the QM class
qm_manager = QM()

# Example: Start a container named 'qm'
container_name = "qm"
if qm_manager.start_container(container_name):
print(f"Container '{container_name}' started successfully.")
else:
print(f"Failed to start container '{container_name}'.")

# Example: Check the status of the container
status = qm_manager.container_status(container_name)
#print(f"Status of container '{container_name}': {status}")
print(f"Status of container {status}")

# Example: Count the number of running containers
running_count = qm_manager.count_running_containers()
print(f"Number of running containers: {running_count}")

# Example: Stop the container
if qm_manager.stop_container(container_name):
print(f"Container '{container_name}' stopped successfully.")
else:
print(f"Failed to stop container '{container_name}'.")

# Example: Check if the QM service is installed
if qm_manager.is_qm_service_installed():
print("QM service is installed.")
else:
print("QM service is not installed.")

# Example: Check if the QM service is running
if qm_manager.is_qm_service_running():
print("QM service is running.")
else:
print("QM service is not running.")

if __name__ == "__main__":
main()

0 comments on commit d92d3af

Please sign in to comment.