Feature 10908 pass over upgrade request to Libjuju
[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 abc
24 import asyncio
25 from typing import Union
26 import time
27
28 from n2vc.loggable import Loggable
29
30
31 class K8sConnector(abc.ABC, Loggable):
32 """
33 ####################################################################################
34 ################################### P U B L I C ####################################
35 ####################################################################################
36 """
37
38 @staticmethod
39 def generate_kdu_instance_name(**kwargs):
40 raise NotImplementedError("Method not implemented")
41
42 def __init__(self, db: object, log: object = None, on_update_db=None):
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.log.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.log.info('K8S generic connector initialized')
60
61 @abc.abstractmethod
62 async def init_env(
63 self, k8s_creds: str, namespace: str = "kube-system", reuse_cluster_uuid=None
64 ) -> (str, bool):
65 """
66 It prepares a given K8s cluster environment to run Charts or juju Bundles on
67 both sides:
68 client (OSM)
69 server (Tiller/Charm)
70
71 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid
72 '.kube/config'
73 :param namespace: optional namespace to be used for the K8s engine (helm
74 tiller, juju). By default, 'kube-system' will be used
75 :param reuse_cluster_uuid: existing cluster uuid for reuse
76 :return: uuid of the K8s cluster and True if connector has installed some
77 software in the cluster (on error, an exception will be raised)
78 """
79
80 @abc.abstractmethod
81 async def repo_add(
82 self,
83 cluster_uuid: str,
84 name: str,
85 url: str,
86 repo_type: str = "chart",
87 cert: str = None,
88 user: str = None,
89 password: str = None,
90 ):
91 """
92 Add a new repository to OSM database
93
94 :param cluster_uuid: the cluster
95 :param name: name for the repo in OSM
96 :param url: URL of the repo
97 :param repo_type: either "chart" or "bundle"
98 :return: True if successful
99 """
100
101 @abc.abstractmethod
102 async def repo_list(self, cluster_uuid: str):
103 """
104 Get the list of registered repositories
105
106 :param cluster_uuid: the cluster
107 :return: list of registered repositories: [ (name, url) .... ]
108 """
109
110 @abc.abstractmethod
111 async def repo_remove(self, cluster_uuid: str, name: str):
112 """
113 Remove a repository from OSM
114
115 :param name: repo name in OSM
116 :param cluster_uuid: the cluster
117 :return: True if successful
118 """
119
120 @abc.abstractmethod
121 async def synchronize_repos(self, cluster_uuid: str, name: str):
122 """
123 Synchronizes the list of repositories created in the cluster with
124 the repositories added by the NBI
125
126 :param cluster_uuid: the cluster
127 :return: List of repositories deleted from the cluster and dictionary with
128 repos added
129 """
130
131 @abc.abstractmethod
132 async def reset(
133 self, cluster_uuid: str, force: bool = False, uninstall_sw: bool = False
134 ) -> bool:
135 """
136 Uninstalls Tiller/Charm from a known K8s cluster and removes it from the list
137 of known K8s clusters. Intended to be used e.g. when the NS instance is deleted.
138
139 :param cluster_uuid: UUID of a K8s cluster known by OSM.
140 :param force: force deletion, even in case there are deployed releases
141 :param uninstall_sw: flag to indicate that sw uninstallation from software is
142 needed
143 :return: str: kdu_instance generated by helm
144 """
145
146 @abc.abstractmethod
147 async def install(
148 self,
149 cluster_uuid: str,
150 kdu_model: str,
151 kdu_instance: str,
152 atomic: bool = True,
153 timeout: float = 300,
154 params: dict = None,
155 db_dict: dict = None,
156 kdu_name: str = None,
157 namespace: str = None,
158 ):
159 """
160 Deploys of a new KDU instance. It would implicitly rely on the `install` call
161 to deploy the Chart/Bundle properly parametrized (in practice, this call would
162 happen before any _initial-config-primitive_of the VNF is called).
163
164 :param cluster_uuid: UUID of a K8s cluster known by OSM
165 :param kdu_model: chart/bundle:version reference (string), which can be either
166 of these options:
167 - a name of chart/bundle available via the repos known by OSM
168 - a path to a packaged chart/bundle
169 - a path to an unpacked chart/bundle directory or a URL
170 :param kdu_instance: Kdu instance name
171 :param atomic: If set, installation process purges chart/bundle on fail, also
172 will wait until all the K8s objects are active
173 :param timeout: Time in seconds to wait for the install of the chart/bundle
174 (defaults to Helm default timeout: 300s)
175 :param params: dictionary of key-value pairs for instantiation parameters
176 (overriding default values)
177 :param dict db_dict: where to write into database when the status changes.
178 It contains a dict with {collection: <str>, filter: {},
179 path: <str>},
180 e.g. {collection: "nsrs", filter:
181 {_id: <nsd-id>, path: "_admin.deployed.K8S.3"}
182 :param kdu_name: Name of the KDU instance to be installed
183 :param namespace: K8s namespace to use for the KDU instance
184 :return: True if successful
185 """
186
187 @abc.abstractmethod
188 async def upgrade(
189 self,
190 cluster_uuid: str,
191 kdu_instance: str,
192 kdu_model: str = None,
193 atomic: bool = True,
194 timeout: float = 300,
195 params: dict = None,
196 db_dict: dict = None,
197 ):
198 """
199 Upgrades an existing KDU instance. It would implicitly use the `upgrade` call
200 over an existing Chart/Bundle. It can be used both to upgrade the chart or to
201 reconfigure it. This would be exposed as Day-2 primitive.
202
203 :param cluster_uuid: UUID of a K8s cluster known by OSM
204 :param kdu_instance: unique name for the KDU instance to be updated
205 :param kdu_model: new chart/bundle:version reference
206 :param atomic: rollback in case of fail and wait for pods and services are
207 available
208 :param timeout: Time in seconds to wait for the install of the chart/bundle
209 (defaults to Helm default timeout: 300s)
210 :param params: new dictionary of key-value pairs for instantiation parameters
211 :param dict db_dict: where to write into database when the status changes.
212 It contains a dict with {collection: <str>, filter: {},
213 path: <str>},
214 e.g. {collection: "nsrs", filter:
215 {_id: <nsd-id>, path: "_admin.deployed.K8S.3"}
216 :return: reference to the new revision number of the KDU instance
217 """
218
219 @abc.abstractmethod
220 async def scale(
221 self,
222 kdu_instance: str,
223 scale: int,
224 resource_name: str,
225 total_timeout: float = 1800,
226 cluster_uuid: str = None,
227 kdu_model: str = None,
228 atomic: bool = True,
229 db_dict: dict = None,
230 **kwargs,
231 ) -> bool:
232 """Scale a resource in a KDU instance.
233
234 Args:
235 kdu_instance: KDU instance name
236 scale: Scale to which to set the resource
237 resource_name: Resource name
238 total_timeout: The time, in seconds, to wait for the install
239 to finish
240 cluster_uuid: The UUID of the cluster
241 kdu_model: The chart/bundle reference
242 atomic: if set, upgrade process rolls back changes made in case of failed upgrade.
243 The --wait flag will be set automatically if --atomic is used
244 db_dict: Dictionary for any additional data
245 kwargs: Additional parameters
246 vca_id (str): VCA ID
247
248 Returns:
249 True if successful, False otherwise
250 """
251
252 @abc.abstractmethod
253 async def get_scale_count(
254 self,
255 resource_name: str,
256 kdu_instance: str,
257 cluster_uuid: str,
258 kdu_model: str,
259 timeout: float = 300,
260 **kwargs,
261 ) -> int:
262 """Get a resource scale count in a KDU instance.
263
264 Args:
265 resource_name: Resource name
266 kdu_instance: KDU instance name
267 cluster_uuid: The UUID of the cluster
268 kdu_model: chart/bundle reference
269 timeout: The time, in seconds, to wait
270 kwargs: Additional parameters
271
272 Returns:
273 Resource instance count
274 """
275
276 @abc.abstractmethod
277 async def rollback(
278 self, cluster_uuid: str, kdu_instance: str, revision=0, db_dict: dict = None
279 ):
280 """
281 Rolls back a previous update of a KDU instance. It would implicitly use the
282 `rollback` call. It can be used both to rollback from a Chart/Bundle version
283 update or from a reconfiguration. This would be exposed as Day-2 primitive.
284
285 :param cluster_uuid: UUID of a K8s cluster known by OSM
286 :param kdu_instance: unique name for the KDU instance
287 :param revision: revision to which revert changes. If omitted, it will revert
288 the last update only
289 :param dict db_dict: where to write into database when the status changes.
290 It contains a dict with {collection: <str>, filter: {},
291 path: <str>},
292 e.g. {collection: "nsrs", filter:
293 {_id: <nsd-id>, path: "_admin.deployed.K8S.3"}
294 :return:If successful, reference to the current active revision of the KDU
295 instance after the rollback
296 """
297
298 @abc.abstractmethod
299 async def uninstall(self, cluster_uuid: str, kdu_instance: str):
300 """
301 Removes an existing KDU instance. It would implicitly use the `delete` call
302 (this call would happen after all _terminate-config-primitive_ of the VNF are
303 invoked).
304
305 :param cluster_uuid: UUID of a K8s cluster known by OSM
306 :param kdu_instance: unique name for the KDU instance to be deleted
307 :return: True if successful
308 """
309
310 @abc.abstractmethod
311 async def exec_primitive(
312 self,
313 cluster_uuid: str = None,
314 kdu_instance: str = None,
315 primitive_name: str = None,
316 timeout: float = 300,
317 params: dict = None,
318 db_dict: dict = None,
319 ) -> str:
320 """Exec primitive (Juju action)
321
322 :param cluster_uuid str: The UUID of the cluster
323 :param kdu_instance str: The unique name of the KDU instance
324 :param primitive_name: Name of action that will be executed
325 :param timeout: Timeout for action execution
326 :param params: Dictionary of all the parameters needed for the action
327 :db_dict: Dictionary for any additional data
328
329 :return: Returns the output of the action
330 """
331
332 @abc.abstractmethod
333 async def upgrade_charm(
334 self,
335 ee_id: str = None,
336 path: str = None,
337 charm_id: str = None,
338 charm_type: str = None,
339 timeout: float = None,
340 ) -> str:
341 """This method upgrade charms in VNFs
342
343 Args:
344 ee_id: Execution environment id
345 path: Local path to the charm
346 charm_id: charm-id
347 charm_type: Charm type can be lxc-proxy-charm, native-charm or k8s-proxy-charm
348 timeout: (Float) Timeout for the ns update operation
349
350 Returns:
351 The output of the update operation if status equals to "completed"
352 """
353
354 @abc.abstractmethod
355 async def inspect_kdu(self, kdu_model: str, repo_url: str = None) -> str:
356 """
357 These calls will retrieve from the Chart/Bundle:
358
359 - The list of configurable values and their defaults (e.g. in Charts,
360 it would retrieve the contents of `values.yaml`).
361 - If available, any embedded help file (e.g. `readme.md`) embedded in the
362 Chart/Bundle.
363
364 :param kdu_model: chart/bundle reference
365 :param repo_url: optional, reposotory URL (None if tar.gz, URl in other cases,
366 even stable URL)
367 :return:
368
369 If successful, it will return the available parameters and their default values
370 as provided by the backend.
371 """
372
373 @abc.abstractmethod
374 async def help_kdu(self, kdu_model: str, repo_url: str = None) -> str:
375 """
376
377 :param kdu_model: chart/bundle reference
378 :param repo_url: optional, reposotory URL (None if tar.gz, URl in other cases,
379 even stable URL)
380 :return: If successful, it will return the contents of the 'readme.md'
381 """
382
383 @abc.abstractmethod
384 async def status_kdu(
385 self, cluster_uuid: str, kdu_instance: str, yaml_format: str
386 ) -> Union[str, dict]:
387 """
388 This call would retrieve tha current state of a given KDU instance. It would be
389 would allow to retrieve the _composition_ (i.e. K8s objects) and _specific
390 values_ of the configuration parameters applied to a given instance. This call
391 would be based on the `status` call.
392
393 :param cluster_uuid: UUID of a K8s cluster known by OSM
394 :param kdu_instance: unique name for the KDU instance
395 :param yaml_format: if the return shall be returned as an YAML string or as a
396 dictionary
397 :return: If successful, it will return the following vector of arguments:
398 - K8s `namespace` in the cluster where the KDU lives
399 - `state` of the KDU instance. It can be:
400 - UNKNOWN
401 - DEPLOYED
402 - DELETED
403 - SUPERSEDED
404 - FAILED or
405 - DELETING
406 - List of `resources` (objects) that this release consists of, sorted by kind,
407 and the status of those resources
408 - Last `deployment_time`.
409
410 """
411
412 @abc.abstractmethod
413 async def get_services(
414 self, cluster_uuid: str, kdu_instance: str, namespace: str
415 ) -> list:
416 """
417 Returns a list of services defined for the specified kdu instance.
418
419 :param cluster_uuid: UUID of a K8s cluster known by OSM
420 :param kdu_instance: unique name for the KDU instance
421 :param namespace: K8s namespace used by the KDU instance
422 :return: If successful, it will return a list of services, Each service
423 can have the following data:
424 - `name` of the service
425 - `type` type of service in the k8 cluster
426 - `ports` List of ports offered by the service, for each port includes at least
427 name, port, protocol
428 - `cluster_ip` Internal ip to be used inside k8s cluster
429 - `external_ip` List of external ips (in case they are available)
430 """
431
432 @abc.abstractmethod
433 async def get_service(
434 self, cluster_uuid: str, service_name: str, namespace: str = None
435 ) -> object:
436 """
437 Obtains the data of the specified service in the k8cluster.
438
439 :param cluster_uuid: UUID of a K8s cluster known by OSM
440 :param service_name: name of the K8s service in the specified namespace
441 :param namespace: K8s namespace used by the KDU instance
442 :return: If successful, it will return a list of services, Each service can have
443 the following data:
444 - `name` of the service
445 - `type` type of service in the k8 cluster
446 - `ports` List of ports offered by the service, for each port includes at least
447 name, port, protocol
448 - `cluster_ip` Internal ip to be used inside k8s cluster
449 - `external_ip` List of external ips (in case they are available)
450 """
451
452 """
453 ####################################################################################
454 ################################### P R I V A T E ##################################
455 ####################################################################################
456 """
457
458 async def write_app_status_to_db(
459 self, db_dict: dict, status: str, detailed_status: str, operation: str
460 ) -> bool:
461
462 if not self.db:
463 self.warning("No db => No database write")
464 return False
465
466 if not db_dict:
467 self.warning("No db_dict => No database write")
468 return False
469
470 self.log.debug("status={}".format(status))
471
472 try:
473
474 the_table = db_dict["collection"]
475 the_filter = db_dict["filter"]
476 the_path = db_dict["path"]
477 if not the_path[-1] == ".":
478 the_path = the_path + "."
479 update_dict = {
480 the_path + "operation": operation,
481 the_path + "status": status,
482 the_path + "detailed-status": detailed_status,
483 the_path + "status-time": str(time.time()),
484 }
485
486 self.db.set_one(
487 table=the_table,
488 q_filter=the_filter,
489 update_dict=update_dict,
490 fail_on_empty=True,
491 )
492
493 # database callback
494 if self.on_update_db:
495 if asyncio.iscoroutinefunction(self.on_update_db):
496 await self.on_update_db(
497 the_table, the_filter, the_path, update_dict
498 )
499 else:
500 self.on_update_db(the_table, the_filter, the_path, update_dict)
501
502 return True
503
504 except Exception as e:
505 self.log.info("Exception writing status to database: {}".format(e))
506 return False