Wei-Yu Chen | ad55cb8 | 2022-02-15 20:07:01 +0800 | [diff] [blame] | 1 | # SPDX-FileCopyrightText: 2020 The Magma Authors. |
| 2 | # SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org> |
| 3 | # |
| 4 | # SPDX-License-Identifier: BSD-3-Clause |
Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 5 | |
| 6 | from common.redis.client import get_default_client |
| 7 | from common.redis.containers import RedisFlatDict |
| 8 | from common.redis.serializers import ( |
| 9 | RedisSerde, |
| 10 | get_proto_deserializer, |
| 11 | get_proto_serializer, |
| 12 | ) |
| 13 | from orc8r.protos.service_status_pb2 import ServiceExitStatus |
| 14 | |
| 15 | |
| 16 | class ServiceStateWrapper: |
| 17 | """ |
| 18 | Class wraps ServiceState interactions with redis |
| 19 | """ |
| 20 | |
| 21 | # Unique typename for Redis key |
| 22 | REDIS_VALUE_TYPE = "systemd_status" |
| 23 | |
| 24 | def __init__(self): |
| 25 | serde = RedisSerde( |
| 26 | self.REDIS_VALUE_TYPE, |
| 27 | get_proto_serializer(), |
| 28 | get_proto_deserializer(ServiceExitStatus), |
| 29 | ) |
| 30 | self._flat_dict = RedisFlatDict(get_default_client(), serde) |
| 31 | |
| 32 | def update_service_status( |
| 33 | self, service_name: str, |
| 34 | service_status: ServiceExitStatus, |
| 35 | ) -> None: |
| 36 | """ |
| 37 | Update the service exit status for a given service |
| 38 | """ |
| 39 | |
| 40 | if service_name in self._flat_dict: |
| 41 | current_service_status = self._flat_dict[service_name] |
| 42 | else: |
| 43 | current_service_status = ServiceExitStatus() |
| 44 | |
| 45 | if service_status.latest_service_result == \ |
| 46 | ServiceExitStatus.ServiceResult.Value("SUCCESS"): |
| 47 | service_status.num_clean_exits = \ |
| 48 | current_service_status.num_clean_exits + 1 |
| 49 | service_status.num_fail_exits = \ |
| 50 | current_service_status.num_fail_exits |
| 51 | else: |
| 52 | service_status.num_fail_exits = \ |
| 53 | current_service_status.num_fail_exits + 1 |
| 54 | service_status.num_clean_exits = \ |
| 55 | current_service_status.num_clean_exits |
| 56 | self._flat_dict[service_name] = service_status |
| 57 | |
| 58 | def get_service_status(self, service_name: str) -> ServiceExitStatus: |
| 59 | """ |
| 60 | Get the service status protobuf for a given service |
| 61 | @returns ServiceStatus protobuf object |
| 62 | """ |
| 63 | return self._flat_dict[service_name] |
| 64 | |
| 65 | def get_all_services_status(self) -> [str, ServiceExitStatus]: |
| 66 | """ |
| 67 | Get a dict of service name to service status |
| 68 | @return dict of service_name to service map |
| 69 | """ |
| 70 | service_status = {} |
| 71 | for k, v in self._flat_dict.items(): |
| 72 | service_status[k] = v |
| 73 | return service_status |
| 74 | |
| 75 | def cleanup_service_status(self) -> None: |
| 76 | """ |
| 77 | Cleanup service status for all services in redis, mostly using for |
| 78 | testing |
| 79 | """ |
| 80 | self._flat_dict.clear() |