Wei-Yu Chen | ad55cb8 | 2022-02-15 20:07:01 +0800 | [diff] [blame] | 1 | #! /usr/bin/env python3 |
Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 2 | |
Wei-Yu Chen | ad55cb8 | 2022-02-15 20:07:01 +0800 | [diff] [blame] | 3 | # SPDX-FileCopyrightText: 2020 The Magma Authors. |
| 4 | # SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org> |
| 5 | # |
| 6 | # SPDX-License-Identifier: BSD-3-Clause |
Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 7 | |
| 8 | from datetime import datetime |
| 9 | |
| 10 | import dateutil.parser |
| 11 | import docker |
| 12 | from common.health.entities import Errors, ServiceHealth, Version |
| 13 | from common.health.health_service import GenericHealthChecker |
| 14 | |
| 15 | |
| 16 | class DockerHealthChecker(GenericHealthChecker): |
| 17 | |
| 18 | def get_error_summary(self, service_names): |
| 19 | res = {} |
| 20 | for service_name in service_names: |
| 21 | client = docker.from_env() |
| 22 | container = client.containers.get(service_name) |
| 23 | |
| 24 | res[service_name] = Errors(log_level='-', error_count=0) |
| 25 | for line in container.logs().decode('utf-8').split('\n'): |
| 26 | if service_name not in line: |
| 27 | continue |
| 28 | # Reset the counter for restart/start |
| 29 | if 'Starting {}...'.format(service_name) in line: |
| 30 | res[service_name].error_count = 0 |
| 31 | elif 'ERROR' in line: |
| 32 | res[service_name].error_count += 1 |
| 33 | return res |
| 34 | |
| 35 | def get_magma_services_summary(self): |
| 36 | services_health_summary = [] |
| 37 | client = docker.from_env() |
| 38 | |
| 39 | for container in client.containers.list(): |
| 40 | service_start_time = dateutil.parser.parse( |
| 41 | container.attrs['State']['StartedAt'], |
| 42 | ) |
| 43 | current_time = datetime.now(service_start_time.tzinfo) |
| 44 | time_running = current_time - service_start_time |
| 45 | services_health_summary.append( |
| 46 | ServiceHealth( |
| 47 | service_name=container.name, |
| 48 | active_state=container.status, |
| 49 | sub_state=container.status, |
| 50 | time_running=str(time_running).split('.', 1)[0], |
| 51 | errors=self.get_error_summary([container.name])[ |
| 52 | container.name |
| 53 | ], |
| 54 | ), |
| 55 | ) |
| 56 | return services_health_summary |
| 57 | |
| 58 | def get_magma_version(self): |
| 59 | client = docker.from_env() |
| 60 | container = client.containers.get('magmad') |
| 61 | |
| 62 | return Version( |
| 63 | version_code=container.attrs['Config']['Image'], |
| 64 | last_update_time='-', |
| 65 | ) |