add k8s util functions for compatibility of upstream changes
[bottlenecks.git] / utils / k8s_setup / k8s_utils.py
1 #!/usr/bin/env python
2 ##############################################################################
3 # Copyright (c) 2018 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11 import os
12 import utils.logger as log
13 from kubernetes import client, watch
14
15
16 LOG = log.Logger(__name__).getLogger()
17 INSTALLER_TYPE = os.getenv("INSTALLER_TYPE")
18
19
20 def get_config_path(INSTALLER_TYPE=None, CONFIG_PATH="/tmp/k8s_config"):
21     if INSTALLER_TYPE:
22         CMD = "bash k8s_config_pre.sh -i " + INSTALLER_TYPE + \
23               " -c " + CONFIG_PATH
24         LOG.info("Executing command: " + CMD)
25         CONFIG_PATH = os.popen(CMD)
26     else:
27         if not os.path.exists(CONFIG_PATH):
28             raise Exception("Must at least specify the path \
29 of k8s config!")
30     return CONFIG_PATH
31
32
33 def get_core_api(version='v1'):
34     if version.lower() == 'v1':
35         API = client.CoreV1Api()
36         LOG.info(API)
37     else:
38         raise Exception("Must input a validate verison!")
39     return API
40
41
42 def watch_namespace(namespace, count=3, stop=None, request_timeout=0):
43     w = watch.Watch()
44     LOG.debug("Watch object generated: {}".format(w))
45     LOG.info("Watch stream generated: {}".format(
46              w.stream(namespace, _request_timeout=request_timeout)))
47     for event in w.stream(namespace, _request_timeout=request_timeout):
48         LOG.info("Event: %s %s" %
49                  (event['type'], event['object'].metadata.name))
50         if event['object'].metadata.name == stop:
51             LOG.info("Namesapce successfully added.\n")
52             w.stop()
53         count -= 1
54         if not count:
55             LOG.info("Ended.\n")
56             w.stop()