Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | """ |
| 4 | Copyright 2020 The Magma Authors. |
| 5 | |
| 6 | This source code is licensed under the BSD-style license found in the |
| 7 | LICENSE file in the root directory of this source tree. |
| 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 | |
| 16 | from datetime import datetime |
| 17 | |
| 18 | import dateutil.parser |
| 19 | import docker |
| 20 | from common.health.entities import Errors, ServiceHealth, Version |
| 21 | from common.health.health_service import GenericHealthChecker |
| 22 | |
| 23 | |
| 24 | class 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 | ) |