| David Garcia | 673401c | 2020-07-02 13:56:58 +0200 | [diff] [blame] | 1 | # Copyright 2020 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 kubernetes import client, config |
| 16 | from kubernetes.client.rest import ApiException |
| 17 | import logging |
| 18 | |
| 19 | |
| 20 | class Kubectl: |
| 21 | def __init__(self, config_file=None): |
| 22 | config.load_kube_config(config_file=config_file) |
| 23 | self.logger = logging.getLogger("Kubectl") |
| 24 | |
| 25 | def get_services(self, field_selector=None, label_selector=None): |
| 26 | kwargs = {} |
| 27 | if field_selector: |
| 28 | kwargs["field_selector"] = field_selector |
| 29 | if label_selector: |
| 30 | kwargs["label_selector"] = label_selector |
| 31 | |
| 32 | try: |
| 33 | v1 = client.CoreV1Api() |
| 34 | result = v1.list_service_for_all_namespaces(**kwargs) |
| 35 | return [ |
| 36 | { |
| 37 | "name": i.metadata.name, |
| 38 | "cluster_ip": i.spec.cluster_ip, |
| 39 | "type": i.spec.type, |
| David Garcia | 70c5f3a | 2020-07-16 17:53:20 +0200 | [diff] [blame] | 40 | "ports": [ |
| 41 | { |
| 42 | "name": p.name, |
| 43 | "node_port": p.node_port, |
| 44 | "port": p.port, |
| 45 | "protocol": p.protocol, |
| 46 | "target_port": p.target_port, |
| 47 | } |
| 48 | for p in i.spec.ports |
| David Garcia | 20806a4 | 2020-07-22 13:17:56 +0200 | [diff] [blame] | 49 | ] |
| 50 | if i.spec.ports |
| 51 | else [], |
| David Garcia | 673401c | 2020-07-02 13:56:58 +0200 | [diff] [blame] | 52 | "external_ip": [i.ip for i in i.status.load_balancer.ingress] |
| 53 | if i.status.load_balancer.ingress |
| 54 | else None, |
| 55 | } |
| 56 | for i in result.items |
| 57 | ] |
| 58 | except ApiException as e: |
| 59 | self.logger.error("Error calling get services: {}".format(e)) |
| 60 | raise e |