feature: sol004 and sol007
[osm/osmclient.git] / osmclient / sol005 / k8scluster.py
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
12 # under the License.
13 #
14
15 """
16 OSM K8s cluster API handling
17 """
18
19 from osmclient.common import utils
20 from osmclient.common import wait as WaitForStatus
21 from osmclient.common.exceptions import NotFound
22 from osmclient.common.exceptions import ClientException
23 import json
24 import logging
25
26
27 class K8scluster(object):
28 def __init__(self, http=None, client=None):
29 self._http = http
30 self._client = client
31 self._logger = logging.getLogger("osmclient.k8scluster")
32 self._apiName = "/admin"
33 self._apiVersion = "/v1"
34 self._apiResource = "/k8sclusters"
35 self._apiBase = "{}{}{}".format(
36 self._apiName, self._apiVersion, self._apiResource
37 )
38
39 def _get_vim_account(self, vim_account):
40 vim = self._client.vim.get(vim_account)
41 if vim is None:
42 raise NotFound("cannot find vim account '{}'".format(vim_account))
43 return vim
44
45 # K8S '--wait' option
46 def _wait(self, id, wait_time, deleteFlag=False):
47 self._logger.debug("")
48 self._client.get_token()
49 # Endpoint to get operation status
50 apiUrlStatus = "{}{}{}".format(
51 self._apiName, self._apiVersion, self._apiResource
52 )
53 # Wait for status for VIM instance creation/deletion
54 if isinstance(wait_time, bool):
55 wait_time = WaitForStatus.TIMEOUT_VIM_OPERATION
56 WaitForStatus.wait_for_status(
57 "K8S",
58 str(id),
59 wait_time,
60 apiUrlStatus,
61 self._http.get2_cmd,
62 deleteFlag=deleteFlag,
63 )
64
65 def create(self, name, k8s_cluster, wait=False):
66 self._client.get_token()
67 vim_account = self._get_vim_account(k8s_cluster["vim_account"])
68 k8s_cluster["vim_account"] = vim_account["_id"]
69 if "vca" in vim_account:
70 k8s_cluster["vca_id"] = vim_account["vca"]
71 http_code, resp = self._http.post_cmd(
72 endpoint=self._apiBase, postfields_dict=k8s_cluster
73 )
74
75 self._logger.debug("HTTP CODE: {}".format(http_code))
76 self._logger.debug("RESP: {}".format(resp))
77
78 if resp:
79 resp = json.loads(resp)
80 if not resp or "id" not in resp:
81 raise ClientException("unexpected response from server - {}".format(resp))
82 if wait:
83 # Wait for status for VIM instance creation
84 self._wait(resp.get("id"), wait)
85 print(resp["id"])
86 # else:
87 # msg = ""
88 # if resp:
89 # try:
90 # msg = json.loads(resp)
91 # except ValueError:
92 # msg = resp
93 # raise ClientException("failed to add K8s cluster {} - {}".format(name, msg))
94
95 def update(self, name, k8s_cluster, wait=False):
96 self._client.get_token()
97 cluster = self.get(name)
98 if "vim_account" in k8s_cluster:
99 vim_account = self._get_vim_account(k8s_cluster["vim_account"])
100 k8s_cluster["vim_account"] = vim_account["_id"]
101 if "vca" in vim_account:
102 k8s_cluster["vca_id"] = vim_account["vca"]
103 http_code, resp = self._http.patch_cmd(
104 endpoint="{}/{}".format(self._apiBase, cluster["_id"]),
105 postfields_dict=k8s_cluster,
106 )
107
108 if wait:
109 wait_id = cluster["_id"]
110 self._wait(wait_id, wait)
111
112 self._logger.debug("HTTP CODE: {}".format(http_code))
113 self._logger.debug("RESP: {}".format(resp))
114
115 if http_code in (200, 201, 202, 204):
116 print("Updated")
117 else:
118 msg = ""
119 if resp:
120 try:
121 msg = json.loads(resp)
122 except ValueError:
123 msg = resp
124 raise ClientException(
125 "failed to update K8s cluster {} - {}".format(name, msg)
126 )
127
128 def get_id(self, name):
129 """Returns a K8s cluster id from a K8s cluster name"""
130 for cluster in self.list():
131 if name == cluster["name"]:
132 return cluster["_id"]
133 raise NotFound("K8s cluster {} not found".format(name))
134
135 def delete(self, name, force=False, wait=False):
136 self._client.get_token()
137 cluster_id = name
138 if not utils.validate_uuid4(name):
139 cluster_id = self.get_id(name)
140 querystring = ""
141 if force:
142 querystring = "?FORCE=True"
143 http_code, resp = self._http.delete_cmd(
144 "{}/{}{}".format(self._apiBase, cluster_id, querystring)
145 )
146
147 self._logger.debug("HTTP CODE: {}".format(http_code))
148 self._logger.debug("RESP: {}".format(resp))
149
150 if http_code == 202:
151 if wait:
152 wait_id = cluster_id
153
154 if resp:
155 resp = json.loads(resp)
156 wait_id = resp.get("id")
157
158 self._wait(wait_id, wait, deleteFlag=True)
159 else:
160 print("Deletion in progress")
161 elif http_code == 204:
162 print("Deleted")
163 else:
164 msg = resp or ""
165 # if resp:
166 # try:
167 # msg = json.loads(resp)
168 # except ValueError:
169 # msg = resp
170 raise ClientException(
171 "failed to delete K8s cluster {} - {}".format(name, msg)
172 )
173
174 def list(self, filter=None):
175 """Returns a list of K8s clusters"""
176 self._client.get_token()
177 filter_string = ""
178 if filter:
179 filter_string = "?{}".format(filter)
180 _, resp = self._http.get2_cmd("{}{}".format(self._apiBase, filter_string))
181 if resp:
182 return json.loads(resp)
183 return list()
184
185 def get(self, name):
186 """Returns a K8s cluster based on name or id"""
187 self._client.get_token()
188 cluster_id = name
189 if not utils.validate_uuid4(name):
190 cluster_id = self.get_id(name)
191 try:
192 _, resp = self._http.get2_cmd("{}/{}".format(self._apiBase, cluster_id))
193 if resp:
194 resp = json.loads(resp)
195 if not resp or "_id" not in resp:
196 raise ClientException("failed to get K8s cluster info: {}".format(resp))
197 return resp
198 except NotFound:
199 raise NotFound("K8s cluster {} not found".format(name))