1007 Use KDU name and NS id for model names
[osm/N2VC.git] / n2vc / k8s_conn.py
1 ##
2 # Copyright 2019 Telefonica Investigacion y Desarrollo, S.A.U.
3 # This file is part of OSM
4 # All Rights Reserved.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact with: nfvlabs@tid.es
21 ##
22
23 import asyncio
24 from n2vc.loggable import Loggable
25 import abc
26 import time
27
28
29 class K8sConnector(abc.ABC, Loggable):
30
31 """
32 ##################################################################################################
33 ########################################## P U B L I C ###########################################
34 ##################################################################################################
35 """
36
37 def __init__(
38 self,
39 db: object,
40 log: object = None,
41 on_update_db=None
42 ):
43 """
44
45 :param db: database object to write current operation status
46 :param log: logger for tracing
47 :param on_update_db: callback called when k8s connector updates database
48 """
49
50 # parent class
51 Loggable.__init__(self, log=log, log_to_console=True, prefix='\nK8S')
52
53 self.info('Initializing generic K8S connector')
54
55 # the database and update callback
56 self.db = db
57 self.on_update_db = on_update_db
58
59 self.info('K8S generic connector initialized')
60
61 @abc.abstractmethod
62 async def init_env(
63 self,
64 k8s_creds: str,
65 namespace: str = 'kube-system',
66 reuse_cluster_uuid=None
67 ) -> (str, bool):
68 """
69 It prepares a given K8s cluster environment to run Charts or juju Bundles on both sides:
70 client (OSM)
71 server (Tiller/Charm)
72
73 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid '.kube/config'
74 :param namespace: optional namespace to be used for the K8s engine (helm tiller, juju).
75 By default, 'kube-system' will be used
76 :param reuse_cluster_uuid: existing cluster uuid for reuse
77 :return: uuid of the K8s cluster and True if connector has installed some software in the cluster
78 (on error, an exception will be raised)
79 """
80
81 @abc.abstractmethod
82 async def repo_add(
83 self,
84 cluster_uuid: str,
85 name: str,
86 url: str,
87 repo_type: str = 'chart'
88 ):
89 """
90 Add a new repository to OSM database
91
92 :param cluster_uuid: the cluster
93 :param name: name for the repo in OSM
94 :param url: URL of the repo
95 :param repo_type: either "chart" or "bundle"
96 :return: True if successful
97 """
98
99 @abc.abstractmethod
100 async def repo_list(
101 self,
102 cluster_uuid: str
103 ):
104 """
105 Get the list of registered repositories
106
107 :param cluster_uuid: the cluster
108 :return: list of registered repositories: [ (name, url) .... ]
109 """
110
111 @abc.abstractmethod
112 async def repo_remove(
113 self,
114 cluster_uuid: str,
115 name: str
116 ):
117 """
118 Remove a repository from OSM
119
120 :param name: repo name in OSM
121 :param cluster_uuid: the cluster
122 :return: True if successful
123 """
124
125 @abc.abstractmethod
126 async def reset(
127 self,
128 cluster_uuid: str,
129 force: bool = False,
130 uninstall_sw: bool = False
131 ) -> bool:
132 """
133 Uninstalls Tiller/Charm from a known K8s cluster and removes it from the list of known K8s clusters.
134 Intended to be used e.g. when the NS instance is deleted.
135
136 :param cluster_uuid: UUID of a K8s cluster known by OSM.
137 :param force: force deletion, even in case there are deployed releases
138 :param uninstall_sw: flag to indicate that sw uninstallation from software is needed
139 :return: str: kdu_instance generated by helm
140 """
141
142 @abc.abstractmethod
143 async def install(
144 self,
145 cluster_uuid: str,
146 kdu_model: str,
147 atomic: bool = True,
148 timeout: float = 300,
149 params: dict = None,
150 db_dict: dict = None,
151 kdu_name: str = None
152 ):
153 """
154 Deploys of a new KDU instance. It would implicitly rely on the `install` call to deploy the Chart/Bundle
155 properly parametrized (in practice, this call would happen before any _initial-config-primitive_
156 of the VNF is called).
157
158 :param cluster_uuid: UUID of a K8s cluster known by OSM
159 :param kdu_model: chart/bundle:version reference (string), which can be either of these options:
160 - a name of chart/bundle available via the repos known by OSM
161 - a path to a packaged chart/bundle
162 - a path to an unpacked chart/bundle directory or a URL
163 :param atomic: If set, installation process purges chart/bundle on fail, also will wait until
164 all the K8s objects are active
165 :param timeout: Time in seconds to wait for the install of the chart/bundle (defaults to
166 Helm default timeout: 300s)
167 :param params: dictionary of key-value pairs for instantiation parameters (overriding default values)
168 :param dict db_dict: where to write into database when the status changes.
169 It contains a dict with {collection: <str>, filter: {}, path: <str>},
170 e.g. {collection: "nsrs", filter: {_id: <nsd-id>, path: "_admin.deployed.K8S.3"}
171 :param kdu_name: Name of the KDU instance to be installed
172 :return: True if successful
173 """
174
175 @abc.abstractmethod
176 async def upgrade(
177 self,
178 cluster_uuid: str,
179 kdu_instance: str,
180 kdu_model: str = None,
181 atomic: bool = True,
182 timeout: float = 300,
183 params: dict = None,
184 db_dict: dict = None
185 ):
186 """
187 Upgrades an existing KDU instance. It would implicitly use the `upgrade` call over an existing Chart/Bundle.
188 It can be used both to upgrade the chart or to reconfigure it. This would be exposed as Day-2 primitive.
189
190 :param cluster_uuid: UUID of a K8s cluster known by OSM
191 :param kdu_instance: unique name for the KDU instance to be updated
192 :param kdu_model: new chart/bundle:version reference
193 :param atomic: rollback in case of fail and wait for pods and services are available
194 :param timeout: Time in seconds to wait for the install of the chart/bundle (defaults to
195 Helm default timeout: 300s)
196 :param params: new dictionary of key-value pairs for instantiation parameters
197 :param dict db_dict: where to write into database when the status changes.
198 It contains a dict with {collection: <str>, filter: {}, path: <str>},
199 e.g. {collection: "nsrs", filter: {_id: <nsd-id>, path: "_admin.deployed.K8S.3"}
200 :return: reference to the new revision number of the KDU instance
201 """
202
203 @abc.abstractmethod
204 async def rollback(
205 self,
206 cluster_uuid: str,
207 kdu_instance: str,
208 revision=0,
209 db_dict: dict = None
210 ):
211 """
212 Rolls back a previous update of a KDU instance. It would implicitly use the `rollback` call.
213 It can be used both to rollback from a Chart/Bundle version update or from a reconfiguration.
214 This would be exposed as Day-2 primitive.
215
216 :param cluster_uuid: UUID of a K8s cluster known by OSM
217 :param kdu_instance: unique name for the KDU instance
218 :param revision: revision to which revert changes. If omitted, it will revert the last update only
219 :param dict db_dict: where to write into database when the status changes.
220 It contains a dict with {collection: <str>, filter: {}, path: <str>},
221 e.g. {collection: "nsrs", filter: {_id: <nsd-id>, path: "_admin.deployed.K8S.3"}
222 :return:If successful, reference to the current active revision of the KDU instance after the rollback
223 """
224
225 @abc.abstractmethod
226 async def uninstall(
227 self,
228 cluster_uuid: str,
229 kdu_instance: str
230 ):
231 """
232 Removes an existing KDU instance. It would implicitly use the `delete` call (this call would happen
233 after all _terminate-config-primitive_ of the VNF are invoked).
234
235 :param cluster_uuid: UUID of a K8s cluster known by OSM
236 :param kdu_instance: unique name for the KDU instance to be deleted
237 :return: True if successful
238 """
239
240 @abc.abstractmethod
241 async def inspect_kdu(
242 self,
243 kdu_model: str,
244 repo_url: str = None
245 ) -> str:
246 """
247 These calls will retrieve from the Chart/Bundle:
248
249 - The list of configurable values and their defaults (e.g. in Charts, it would retrieve
250 the contents of `values.yaml`).
251 - If available, any embedded help file (e.g. `readme.md`) embedded in the Chart/Bundle.
252
253 :param kdu_model: chart/bundle reference
254 :param repo_url: optional, reposotory URL (None if tar.gz, URl in other cases, even stable URL)
255 :return:
256
257 If successful, it will return the available parameters and their default values as provided by the backend.
258 """
259
260 @abc.abstractmethod
261 async def help_kdu(
262 self,
263 kdu_model: str,
264 repo_url: str = None
265 ) -> str:
266 """
267
268 :param kdu_model: chart/bundle reference
269 :param repo_url: optional, reposotory URL (None if tar.gz, URl in other cases, even stable URL)
270 :return: If successful, it will return the contents of the 'readme.md'
271 """
272
273 @abc.abstractmethod
274 async def status_kdu(
275 self,
276 cluster_uuid: str,
277 kdu_instance: str
278 ) -> str:
279 """
280 This call would retrieve tha current state of a given KDU instance. It would be would allow to retrieve
281 the _composition_ (i.e. K8s objects) and _specific values_ of the configuration parameters applied
282 to a given instance. This call would be based on the `status` call.
283
284 :param cluster_uuid: UUID of a K8s cluster known by OSM
285 :param kdu_instance: unique name for the KDU instance
286 :return: If successful, it will return the following vector of arguments:
287 - K8s `namespace` in the cluster where the KDU lives
288 - `state` of the KDU instance. It can be:
289 - UNKNOWN
290 - DEPLOYED
291 - DELETED
292 - SUPERSEDED
293 - FAILED or
294 - DELETING
295 - List of `resources` (objects) that this release consists of, sorted by kind, and the status of those resources
296 - Last `deployment_time`.
297
298 """
299
300 """
301 ##################################################################################################
302 ########################################## P R I V A T E #########################################
303 ##################################################################################################
304 """
305
306 async def write_app_status_to_db(
307 self,
308 db_dict: dict,
309 status: str,
310 detailed_status: str,
311 operation: str
312 ) -> bool:
313
314 if not self.db:
315 self.warning('No db => No database write')
316 return False
317
318 if not db_dict:
319 self.warning('No db_dict => No database write')
320 return False
321
322 self.debug('status={}'.format(status))
323
324 try:
325
326 the_table = db_dict['collection']
327 the_filter = db_dict['filter']
328 the_path = db_dict['path']
329 if not the_path[-1] == '.':
330 the_path = the_path + '.'
331 update_dict = {
332 the_path + 'operation': operation,
333 the_path + 'status': status,
334 the_path + 'detailed-status': detailed_status,
335 the_path + 'status-time': str(time.time()),
336 }
337
338 self.db.set_one(
339 table=the_table,
340 q_filter=the_filter,
341 update_dict=update_dict,
342 fail_on_empty=True
343 )
344
345 # database callback
346 if self.on_update_db:
347 if asyncio.iscoroutinefunction(self.on_update_db):
348 await self.on_update_db(the_table, the_filter, the_path, update_dict)
349 else:
350 self.on_update_db(the_table, the_filter, the_path, update_dict)
351
352 return True
353
354 except Exception as e:
355 self.info('Exception writing status to database: {}'.format(e))
356 return False