Skip to content
Snippets Groups Projects
Commit 7eb461b3 authored by Rastislav Krutak's avatar Rastislav Krutak
Browse files

feat: print_docker_versions.py, run_version_script.py scripts

closes(PRX-99)
parent 12f25c68
No related branches found
No related tags found
1 merge request!23feat: print_docker_versions.py, run_version_script.py scripts
Pipeline #244905 passed
......@@ -25,3 +25,20 @@ All nagios scripts are located under `nagios` directory.
- Params:
- 1 - url to a page which prints a time when expires the metadata closest to expiration
### print_docker_versions.py
- This script collects system info, docker engine info and the versions of running containers and then prints it to the stdout in the JSON format
- A python [docker library](https://pypi.org/project/docker/) is needed to run the script
- Options:
- -e,--exclude NAMES - space delimited string of container names to exclude from the listing
### run_version_script.py
- This scripts runs the print_docker_version.py script on the given machines. The collected versions are then printed as a MD table to the stdout
- Options:
- -e,--exclude NAMES - space delimited string of container names to exclude from the listing
- Params:
- 1... - machines to run the script on in the form of user@adress, the user needs root privileges to execute the script
#!/usr/bin/env python3
import multiprocessing
import os
import re
import json
import docker
import argparse
import platform
output = {
"cpu_count": "",
"memory": "",
"os_version": "",
"kernel_version": "",
"docker_version": "",
"containerd_version": "",
"containers": {},
}
parser = argparse.ArgumentParser()
parser.add_argument(
"-e", "--exclude", type=str, help="Space delimited list of containers to exclude"
)
args = parser.parse_args()
exc_containers = args.exclude.split(" ") if args.exclude is not None else []
output["cpu_count"] = str(multiprocessing.cpu_count())
mem_bytes = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
if mem_bytes > 1:
output["memory"] = str(round(mem_bytes / (1024.0**3), 2)) + "GiB"
name = ""
maj_version = ""
with open("/etc/os-release") as file:
contents = file.read()
match = re.search(r"NAME=\"(.*)\"", contents)
if match is not None:
name = match.group(1)
match = re.search(r"VERSION_ID=\"(.*)\"", contents)
if match is not None:
maj_version = match.group(1).split(".")[0]
if name.startswith("Debian"):
name = name.split(" ")[0]
output["os_version"] = name + " " + maj_version
output["kernel_version"] = platform.release()
client = docker.from_env()
if client is not None:
version_info = client.version()
docker_ver_filter = list(
filter(lambda x: x["Name"] == "Engine", version_info["Components"])
)
output["docker_version"] = (
docker_ver_filter[0]["Version"] if len(docker_ver_filter) > 0 else ""
)
containerd_ver_filter = list(
filter(lambda x: x["Name"] == "containerd", version_info["Components"])
)
containerd_version = (
containerd_ver_filter[0]["Version"] if len(containerd_ver_filter) > 0 else ""
)
if len(containerd_version) > 0 and containerd_version[0] == "v":
containerd_version = containerd_version[1:]
output["containerd_version"] = containerd_version
containers = client.containers.list()
containers = list(filter(lambda x: x.name not in exc_containers, containers))
for container in containers:
container_image = container.image.tags[0] if container.image.tags else ""
output["containers"][container.name] = container_image.split(":")[-1]
print(json.dumps(output))
#!/usr/bin/env python3
import asyncio
import json
import asyncssh
import argparse
def jsons_to_dictionary(jsons, hosts):
versions_dicts = list(map(lambda x: json.loads(x), jsons))
ret_dict = {"hosts": hosts}
for i in range(len(versions_dicts)):
versions_dicts[i].update(versions_dicts[i]["containers"])
versions_dicts[i].pop("containers")
for key, val in versions_dicts[i].items():
if key in ret_dict:
ret_dict[key].append(val)
else:
ret_dict[key] = ["-" for _ in range(i)] + [val]
for key, val in ret_dict.items():
if len(val) < i + 1:
ret_dict[key].append("-")
return ret_dict
def dict_to_md_table(dictionary):
keys = list(dictionary.keys())
values = list(dictionary.values())
lengths = [
max(max(map(lambda x: len(x), value)), len(str(key)))
for key, value in dictionary.items()
]
keys[0] = ""
print(
"| "
+ " | ".join([f"{key:<{length}}" for key, length in zip(keys, lengths)])
+ " |"
)
print(
"| " + " | ".join([f"{':-:':<{lengths[i]}}" for i in range(len(keys))]) + " |"
)
for i in range(len(values[0])):
print(
"| "
+ " | ".join(
[f"{str(value[i]):<{length}}" for length, value in zip(lengths, values)]
)
+ " |"
)
async def run_script(user, host):
try:
async with asyncssh.connect(host, username=user) as conn:
await asyncssh.scp("print_docker_versions.py", (conn, "/tmp/"))
return (
await conn.run(
'python3 /tmp/print_docker_versions.py -e "' + exc_containers + '"',
),
host,
)
except Exception as e:
return e, host
async def collect_info(hosts):
tasks = (run_script(host[0], host[1]) for host in hosts)
results = await asyncio.gather(*tasks, return_exceptions=True)
stdouts = []
hosts = []
for result, host in results:
if isinstance(result, Exception):
print("Connecting to host %s failed: %s" % (host, str(result)))
elif result.exit_status != 0:
print(
"Running script on %s exited with status %s:"
% (host, result.exit_status)
)
print(result.stderr, end="")
else:
stdouts.append(result.stdout)
hosts.append(host)
if len(stdouts) > 0 and len(hosts) > 0:
dict_to_md_table(jsons_to_dictionary(stdouts, hosts))
parser = argparse.ArgumentParser()
parser.add_argument(
"-e", "--exclude", type=str, help="Space delimited list of containers to exclude"
)
parser.add_argument("machines", nargs="+", help="Machines to collect the info from")
args = parser.parse_args()
exc_containers = args.exclude if args.exclude is not None else ""
machines = list(map(lambda x: x.split("@"), args.machines))
asyncio.run(collect_info(machines))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment