Code Coverage

Cobertura Coverage Report > osmclient.sol005 >

k8scluster.py

Trend

Classes100%
 
Lines14%
   
Conditionals100%
 

File Coverage summary

NameClassesLinesConditionals
k8scluster.py
100%
1/1
14%
17/118
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
k8scluster.py
14%
17/118
N/A

Source

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 1 """
16 OSM K8s cluster API handling
17 """
18
19 1 from osmclient.common import utils
20 1 from osmclient.common import wait as WaitForStatus
21 1 from osmclient.common.exceptions import NotFound
22 1 from osmclient.common.exceptions import ClientException
23 1 import json
24 1 import logging
25
26
27 1 class K8scluster(object):
28 1     def __init__(self, http=None, client=None):
29 0         self._http = http
30 0         self._client = client
31 0         self._logger = logging.getLogger("osmclient.k8scluster")
32 0         self._apiName = "/admin"
33 0         self._apiVersion = "/v1"
34 0         self._apiResource = "/k8sclusters"
35 0         self._apiBase = "{}{}{}".format(
36             self._apiName, self._apiVersion, self._apiResource
37         )
38
39 1     def _get_vim_account(self, vim_account):
40 0         vim = self._client.vim.get(vim_account)
41 0         if vim is None:
42 0             raise NotFound("cannot find vim account '{}'".format(vim_account))
43 0         return vim
44
45     # K8S '--wait' option
46 1     def _wait(self, id, wait_time, deleteFlag=False):
47 0         self._logger.debug("")
48 0         self._client.get_token()
49         # Endpoint to get operation status
50 0         apiUrlStatus = "{}{}{}".format(
51             self._apiName, self._apiVersion, self._apiResource
52         )
53         # Wait for status for VIM instance creation/deletion
54 0         if isinstance(wait_time, bool):
55 0             wait_time = WaitForStatus.TIMEOUT_VIM_OPERATION
56 0         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 1     def create(self, name, k8s_cluster, wait=False):
66 0         self._client.get_token()
67 0         vim_account = self._get_vim_account(k8s_cluster["vim_account"])
68 0         k8s_cluster["vim_account"] = vim_account["_id"]
69 0         if "vca" in vim_account:
70 0             k8s_cluster["vca_id"] = vim_account["vca"]
71 0         http_code, resp = self._http.post_cmd(
72             endpoint=self._apiBase, postfields_dict=k8s_cluster
73         )
74
75 0         self._logger.debug("HTTP CODE: {}".format(http_code))
76 0         self._logger.debug("RESP: {}".format(resp))
77
78 0         if resp:
79 0             resp = json.loads(resp)
80 0         if not resp or "id" not in resp:
81 0             raise ClientException("unexpected response from server - {}".format(resp))
82 0         if wait:
83             # Wait for status for VIM instance creation
84 0             self._wait(resp.get("id"), wait)
85 0         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 1     def update(self, name, k8s_cluster, wait=False):
96 0         self._client.get_token()
97 0         cluster = self.get(name)
98 0         if "vim_account" in k8s_cluster:
99 0             vim_account = self._get_vim_account(k8s_cluster["vim_account"])
100 0             k8s_cluster["vim_account"] = vim_account["_id"]
101 0             if "vca" in vim_account:
102 0                 k8s_cluster["vca_id"] = vim_account["vca"]
103 0         http_code, resp = self._http.patch_cmd(
104             endpoint="{}/{}".format(self._apiBase, cluster["_id"]),
105             postfields_dict=k8s_cluster,
106         )
107
108 0         if wait:
109 0             wait_id = cluster["_id"]
110 0             self._wait(wait_id, wait)
111
112 0         self._logger.debug("HTTP CODE: {}".format(http_code))
113 0         self._logger.debug("RESP: {}".format(resp))
114
115 0         if http_code in (200, 201, 202, 204):
116 0             print("Updated")
117         else:
118 0             msg = ""
119 0             if resp:
120 0                 try:
121 0                     msg = json.loads(resp)
122 0                 except ValueError:
123 0                     msg = resp
124 0             raise ClientException(
125                 "failed to update K8s cluster {} - {}".format(name, msg)
126             )
127
128 1     def get_id(self, name):
129         """Returns a K8s cluster id from a K8s cluster name"""
130 0         for cluster in self.list():
131 0             if name == cluster["name"]:
132 0                 return cluster["_id"]
133 0         raise NotFound("K8s cluster {} not found".format(name))
134
135 1     def delete(self, name, force=False, wait=False):
136 0         self._client.get_token()
137 0         cluster_id = name
138 0         if not utils.validate_uuid4(name):
139 0             cluster_id = self.get_id(name)
140 0         querystring = ""
141 0         if force:
142 0             querystring = "?FORCE=True"
143 0         http_code, resp = self._http.delete_cmd(
144             "{}/{}{}".format(self._apiBase, cluster_id, querystring)
145         )
146
147 0         self._logger.debug("HTTP CODE: {}".format(http_code))
148 0         self._logger.debug("RESP: {}".format(resp))
149
150 0         if http_code == 202:
151 0             if wait:
152 0                 wait_id = cluster_id
153
154 0                 if resp:
155 0                     resp = json.loads(resp)
156 0                     wait_id = resp.get("id")
157
158 0                 self._wait(wait_id, wait, deleteFlag=True)
159             else:
160 0                 print("Deletion in progress")
161 0         elif http_code == 204:
162 0             print("Deleted")
163         else:
164 0             msg = resp or ""
165             #     if resp:
166             #         try:
167             #             msg = json.loads(resp)
168             #         except ValueError:
169             #             msg = resp
170 0             raise ClientException(
171                 "failed to delete K8s cluster {} - {}".format(name, msg)
172             )
173
174 1     def list(self, filter=None):
175         """Returns a list of K8s clusters"""
176 0         self._client.get_token()
177 0         filter_string = ""
178 0         if filter:
179 0             filter_string = "?{}".format(filter)
180 0         _, resp = self._http.get2_cmd("{}{}".format(self._apiBase, filter_string))
181 0         if resp:
182 0             return json.loads(resp)
183 0         return list()
184
185 1     def get(self, name):
186         """Returns a K8s cluster based on name or id"""
187 0         self._client.get_token()
188 0         cluster_id = name
189 0         if not utils.validate_uuid4(name):
190 0             cluster_id = self.get_id(name)
191 0         try:
192 0             _, resp = self._http.get2_cmd("{}/{}".format(self._apiBase, cluster_id))
193 0             if resp:
194 0                 resp = json.loads(resp)
195 0             if not resp or "_id" not in resp:
196 0                 raise ClientException("failed to get K8s cluster info: {}".format(resp))
197 0             return resp
198 0         except NotFound:
199 0             raise NotFound("K8s cluster {} not found".format(name))