2 ##############################################################################
3 # Copyright (c) 2018 Huawei Technologies Co.,Ltd and others.
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 ##############################################################################
14 import utils.logger as log
15 from kubernetes import client, watch
18 LOG = log.Logger(__name__).getLogger()
19 INSTALLER_TYPE = os.getenv("INSTALLER_TYPE")
20 K8S_UTILS = "/home/opnfv/bottlenecks/utils/k8s_setup"
23 def get_config_path(INSTALLER_TYPE=None, K8S_CONFIG_PATH="/tmp/k8s_config"):
25 CMD = "bash " + K8S_UTILS + "/k8s_config_pre.sh -i " \
27 " -c " + K8S_CONFIG_PATH
28 LOG.info("Executing command: " + CMD)
31 if not os.path.exists(K8S_CONFIG_PATH):
32 raise Exception("Must at least specify the path \
34 return K8S_CONFIG_PATH
37 def get_core_api(version='v1'):
38 if version.lower() == 'v1':
39 API = client.CoreV1Api()
42 raise Exception("Must input a valid verison!")
46 def get_apps_api(version='v1'):
47 if version.lower() == 'v1':
48 API = client.AppsV1Api()
51 raise Exception("Must input a valid verison!")
55 def get_namespace_status(namespace):
56 CMD = ("kubectl get ns | grep %s" % namespace)
57 namespace_existed = commands.getstatusoutput(CMD)
58 return namespace_existed
61 def get_deployment_status(name, namespace):
62 CMD = ("kubectl get deployment --namespace={} | grep {}".format(
64 deployment_existed = commands.getstatusoutput(CMD)
65 return deployment_existed
68 def get_available_pods(name, namespace):
69 CMD = ("kubectl get deployment --namespace={} | grep {}".format(
70 namespace, name) + " | awk '{print $5}'")
71 available_pods = commands.getstatusoutput(CMD)
72 return int(available_pods[1])
75 def watch_namespace(namespace, count=3, stop=None, request_timeout=0):
77 LOG.debug("Watch object generated: {}".format(w))
78 LOG.info("Watch stream generated: {}".format(
79 w.stream(namespace, _request_timeout=request_timeout)))
80 for event in w.stream(namespace, _request_timeout=request_timeout):
81 LOG.info("Event: %s %s" %
82 (event['type'], event['object'].metadata.name))
83 if event['object'].metadata.name == stop:
84 LOG.info("Namesapce successfully added.\n")
92 def write_json(data, file_name):
93 with open(file_name, "a") as f:
94 f.write(json.dumps(data, f))