Debian Codegraph @

agents/kubevirt/fence_kubevirt.py

raw symbols SCIP
1 #!@PYTHON@ -tt
2
3 import sys
4 import logging
5 import atexit
6 sys.path.append("@FENCEAGENTSLIBDIR@")
7 from fencing import *
8 from fencing import fail, fail_usage, run_delay, EC_STATUS, EC_FETCH_VM_UUID
9
10 try:
11 from kubernetes.client.exceptions import ApiException
12 except ImportError:
13 try:
14 from kubernetes.client.rest import ApiException
15 except ImportError:
16 logging.error("Couldn\'t import kubernetes.client.exceptions.ApiException or kubernetes.client.rest.ApiException - not found or not accessible")
17
18 def _get_namespace(options):
19 from kubernetes import config
20
21 ns = options.get("--namespace")
22 if ns is None:
23 ns = config.kube_config.list_kube_config_contexts()[1]['context']['namespace']
24
25 return ns
26
27 def get_nodes_list(conn, options):
28 logging.debug("Starting list/monitor operation")
29 result = {}
30 try:
31 apiversion = options.get("--apiversion")
32 namespace = _get_namespace(options)
33 include_uninitialized = True
34 vm_api = conn.resources.get(api_version=apiversion, kind='VirtualMachine')
35 vm_list = vm_api.get(namespace=namespace)
36 for vm in vm_list.items:
37 result[vm.metadata.name] = ("", None)
38 except Exception as e:
39 logging.error("Exception when calling VirtualMachine list: %s", e)
40 return result
41
42 def get_power_status(conn, options):
43 logging.debug("Starting get status operation")
44 try:
45 apiversion = options.get("--apiversion")
46 namespace = _get_namespace(options)
47 name = options.get("--plug")
48 vmi_api = conn.resources.get(api_version=apiversion,
49 kind='VirtualMachineInstance')
50 vmi = vmi_api.get(name=name, namespace=namespace)
51 return translate_status(vmi.status.phase)
52 except ApiException as e:
53 if e.status == 404:
54 try:
55 vm_api = conn.resources.get(api_version=apiversion, kind='VirtualMachine')
56 vm = vm_api.get(name=name, namespace=namespace)
57 except ApiException as e:
58 logging.error("VM %s doesn't exist", name)
59 fail(EC_FETCH_VM_UUID)
60 return "off"
61 logging.error("Failed to get power status, with API Exception: %s", e)
62 fail(EC_STATUS)
63 except Exception as e:
64 logging.error("Failed to get power status, with Exception: %s", e)
65 fail(EC_STATUS)
66
67 def translate_status(instance_status):
68 if instance_status == "Running":
69 return "on"
70 return "unknown"
71
72 def set_power_status(conn, options):
73 logging.debug("Starting set status operation")
74 try:
75 apiversion= options.get("--apiversion")
76 namespace = _get_namespace(options)
77 name = options.get("--plug")
78 action = 'start' if options["--action"] == "on" else 'stop'
79 virtctl_vm_action(conn, action, namespace, name, apiversion)
80 except Exception as e:
81 logging.error("Failed to set power status, with Exception: %s", e)
82 fail(EC_STATUS)
83
84 def define_new_opts():
85 all_opt["namespace"] = {
86 "getopt" : ":",
87 "longopt" : "namespace",
88 "help" : "--namespace=[namespace] Namespace of the KubeVirt machine",
89 "shortdesc" : "Namespace of the KubeVirt machine.",
90 "required" : "0",
91 "order" : 2
92 }
93 all_opt["kubeconfig"] = {
94 "getopt" : ":",
95 "longopt" : "kubeconfig",
96 "help" : "--kubeconfig=[kubeconfig] Kubeconfig file path",
97 "shortdesc": "Kubeconfig file path",
98 "required": "0",
99 "order": 4
100 }
101 all_opt["apiversion"] = {
102 "getopt" : ":",
103 "longopt" : "apiversion",
104 "help" : "--apiversion=[apiversion] Version of the KubeVirt API",
105 "shortdesc" : "Version of the KubeVirt API.",
106 "required" : "0",
107 "default" : "kubevirt.io/v1",
108 "order" : 5
109 }
110
111 def virtctl_vm_action(conn, action, namespace, name, apiversion):
112 path = '/apis/subresources.{api_version}/namespaces/{namespace}/virtualmachines/{name}/{action}'
113 path = path.format(api_version=apiversion, namespace=namespace, name=name, action=action)
114 return conn.request('put', path, header_params={'accept': '*/*'}, body={'gracePeriod': 0} if action == 'stop' else None)
115
116 # Main agent method
117 def main():
118 conn = None
119
120 device_opt = ["port", "namespace", "kubeconfig", "ssl_insecure", "no_password", "apiversion"]
121
122 atexit.register(atexit_handler)
123 define_new_opts()
124
125 all_opt["power_timeout"]["default"] = "40"
126
127 options = check_input(device_opt, process_input(device_opt))
128
129 docs = {}
130 docs["shortdesc"] = "Fence agent for KubeVirt"
131 docs["longdesc"] = "fence_kubevirt is a Power Fencing agent for KubeVirt."
132 docs["vendorurl"] = "https://kubevirt.io/"
133 show_docs(options, docs)
134
135 run_delay(options)
136
137 # Disable insecure-certificate-warning message
138 if "--ssl-insecure" in options:
139 import urllib3
140 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
141
142 try:
143 from kubernetes import config
144 from openshift.dynamic import DynamicClient
145 kubeconfig = options.get('--kubeconfig')
146 k8s_client = config.new_client_from_config(config_file=kubeconfig)
147 conn = DynamicClient(k8s_client)
148 except ImportError:
149 logging.error("Couldn\'t import kubernetes.config or "
150 "openshift.dynamic.DynamicClient - not found or not accessible")
151
152 # Operate the fencing device
153 result = fence_action(conn, options, set_power_status, get_power_status, get_nodes_list)
154 sys.exit(result)
155
156 if __name__ == "__main__":
157 main()