blob: 70a728ab1df9ccc2c7c84d95093f5a118fabc437 [file] [log] [blame]
Wei-Yu Chen49950b92021-11-08 19:19:18 +08001#!/usr/bin/env python3
2
3"""
4Copyright 2020 The Magma Authors.
5
6This source code is licensed under the BSD-style license found in the
7LICENSE file in the root directory of this source tree.
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14"""
15
16from datetime import datetime
17
18import dateutil.parser
19import docker
20from common.health.entities import Errors, ServiceHealth, Version
21from common.health.health_service import GenericHealthChecker
22
23
24class DockerHealthChecker(GenericHealthChecker):
25
26 def get_error_summary(self, service_names):
27 res = {}
28 for service_name in service_names:
29 client = docker.from_env()
30 container = client.containers.get(service_name)
31
32 res[service_name] = Errors(log_level='-', error_count=0)
33 for line in container.logs().decode('utf-8').split('\n'):
34 if service_name not in line:
35 continue
36 # Reset the counter for restart/start
37 if 'Starting {}...'.format(service_name) in line:
38 res[service_name].error_count = 0
39 elif 'ERROR' in line:
40 res[service_name].error_count += 1
41 return res
42
43 def get_magma_services_summary(self):
44 services_health_summary = []
45 client = docker.from_env()
46
47 for container in client.containers.list():
48 service_start_time = dateutil.parser.parse(
49 container.attrs['State']['StartedAt'],
50 )
51 current_time = datetime.now(service_start_time.tzinfo)
52 time_running = current_time - service_start_time
53 services_health_summary.append(
54 ServiceHealth(
55 service_name=container.name,
56 active_state=container.status,
57 sub_state=container.status,
58 time_running=str(time_running).split('.', 1)[0],
59 errors=self.get_error_summary([container.name])[
60 container.name
61 ],
62 ),
63 )
64 return services_health_summary
65
66 def get_magma_version(self):
67 client = docker.from_env()
68 container = client.containers.get('magmad')
69
70 return Version(
71 version_code=container.attrs['Config']['Image'],
72 last_update_time='-',
73 )