| David Garcia | 78b6e6d | 2022-04-29 05:50:46 +0200 | [diff] [blame] | 1 | # Copyright 2022 Canonical Ltd. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 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 | from typing import Any, Dict, List, Optional |
| 16 | from pydantic import BaseModel, validator |
| 17 | |
| 18 | |
| 19 | def _get_ip_from_service(service: Dict[str, Any]) -> List[str]: |
| 20 | return ( |
| 21 | [service["cluster_ip"]] |
| 22 | if service["type"] == "ClusterIP" |
| 23 | else service["external_ip"] |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | class K8sConfigV0(BaseModel): |
| 28 | services: List[Dict] |
| 29 | |
| 30 | @validator("services") |
| Gabriel Cuba | 411af2e | 2023-01-06 17:23:22 -0500 | [diff] [blame] | 31 | @classmethod |
| David Garcia | 78b6e6d | 2022-04-29 05:50:46 +0200 | [diff] [blame] | 32 | def parse_services(cls, services: Dict[str, Any]): |
| 33 | return { |
| 34 | service["name"]: { |
| 35 | "type": service["type"], |
| 36 | "ip": _get_ip_from_service(service), |
| 37 | "ports": { |
| 38 | port["name"]: { |
| 39 | "port": port["port"], |
| 40 | "protocol": port["protocol"], |
| 41 | } |
| 42 | for port in service["ports"] |
| 43 | }, |
| 44 | } |
| 45 | for service in services |
| 46 | } |
| 47 | |
| 48 | |
| 49 | class OsmConfigV0(BaseModel): |
| 50 | k8s: Optional[K8sConfigV0] |
| 51 | |
| 52 | |
| 53 | class OsmConfig(BaseModel): |
| 54 | v0: OsmConfigV0 |
| 55 | |
| 56 | |
| 57 | class OsmConfigBuilder: |
| 58 | def __init__(self, k8s: Dict[str, Any] = {}) -> None: |
| 59 | self._k8s = k8s |
| 60 | self._configs = {} |
| 61 | if k8s: |
| 62 | self._configs["k8s"] = k8s |
| 63 | |
| 64 | def build(self) -> Dict[str, Any]: |
| 65 | return OsmConfig(v0=OsmConfigV0(**self._configs)).dict() |