blob: 1818e08557230c6d8238c6a1d16035ba52ab682f [file] [log] [blame]
tiernoc0e42e22018-05-11 11:36:10 +02001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4##
5# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
tiernoc0e42e22018-05-11 11:36:10 +02006#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License. You may obtain
9# a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16# License for the specific language governing permissions and limitations
17# under the License.
18#
tiernoc0e42e22018-05-11 11:36:10 +020019##
20
21"""
22asyncio RO python client to interact with RO-server
23"""
24
25import asyncio
26import aiohttp
tiernoc0e42e22018-05-11 11:36:10 +020027import json
28import yaml
29import logging
tiernoc0e42e22018-05-11 11:36:10 +020030from urllib.parse import quote
31from uuid import UUID
32from copy import deepcopy
33
tierno275411e2018-05-16 14:33:32 +020034__author__ = "Alfonso Tierno"
tiernoc0e42e22018-05-11 11:36:10 +020035__date__ = "$09-Jan-2018 09:09:48$"
tierno275411e2018-05-16 14:33:32 +020036__version__ = "0.1.2"
37version_date = "2018-05-16"
tiernoc0e42e22018-05-11 11:36:10 +020038requests = None
39
tierno750b2452018-05-17 16:39:29 +020040
tiernoc0e42e22018-05-11 11:36:10 +020041class ROClientException(Exception):
42 def __init__(self, message, http_code=400):
tierno750b2452018-05-17 16:39:29 +020043 """Common Exception for all RO client exceptions"""
tiernoc0e42e22018-05-11 11:36:10 +020044 self.http_code = http_code
45 Exception.__init__(self, message)
tiernoc0e42e22018-05-11 11:36:10 +020046
47
48def remove_envelop(item, indata=None):
49 """
50 Obtain the useful data removing the envelop. It goes through the vnfd or nsd catalog and returns the
51 vnfd or nsd content
52 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
53 :param indata: Content to be inspected
54 :return: the useful part of indata (a reference, not a new dictionay)
55 """
56 clean_indata = indata
57 if not indata:
58 return {}
59 if item == "vnfd":
garciadeblas5697b8b2021-03-24 09:17:02 +010060 if clean_indata.get("vnfd:vnfd-catalog"):
61 clean_indata = clean_indata["vnfd:vnfd-catalog"]
62 elif clean_indata.get("vnfd-catalog"):
63 clean_indata = clean_indata["vnfd-catalog"]
64 if clean_indata.get("vnfd"):
65 if (
66 not isinstance(clean_indata["vnfd"], list)
67 or len(clean_indata["vnfd"]) != 1
68 ):
tiernoc0e42e22018-05-11 11:36:10 +020069 raise ROClientException("'vnfd' must be a list only one element")
garciadeblas5697b8b2021-03-24 09:17:02 +010070 clean_indata = clean_indata["vnfd"][0]
tiernoc0e42e22018-05-11 11:36:10 +020071 elif item == "nsd":
garciadeblas5697b8b2021-03-24 09:17:02 +010072 if clean_indata.get("nsd:nsd-catalog"):
73 clean_indata = clean_indata["nsd:nsd-catalog"]
74 elif clean_indata.get("nsd-catalog"):
75 clean_indata = clean_indata["nsd-catalog"]
76 if clean_indata.get("nsd"):
77 if (
78 not isinstance(clean_indata["nsd"], list)
79 or len(clean_indata["nsd"]) != 1
80 ):
tiernoc0e42e22018-05-11 11:36:10 +020081 raise ROClientException("'nsd' must be a list only one element")
garciadeblas5697b8b2021-03-24 09:17:02 +010082 clean_indata = clean_indata["nsd"][0]
tiernoc0e42e22018-05-11 11:36:10 +020083 elif item == "sdn":
84 if len(indata) == 1 and "sdn_controller" in indata:
85 clean_indata = indata["sdn_controller"]
86 elif item == "tenant":
87 if len(indata) == 1 and "tenant" in indata:
88 clean_indata = indata["tenant"]
89 elif item in ("vim", "vim_account", "datacenters"):
90 if len(indata) == 1 and "datacenter" in indata:
91 clean_indata = indata["datacenter"]
tiernoe37b57d2018-12-11 17:22:51 +000092 elif item == "wim":
93 if len(indata) == 1 and "wim" in indata:
94 clean_indata = indata["wim"]
95 elif item == "wim_account":
96 if len(indata) == 1 and "wim_account" in indata:
97 clean_indata = indata["wim_account"]
tiernoc0e42e22018-05-11 11:36:10 +020098 elif item == "ns" or item == "instances":
99 if len(indata) == 1 and "instance" in indata:
100 clean_indata = indata["instance"]
101 else:
Gabriel Cuba4c0e6802023-10-09 13:22:38 -0500102 raise ROClientException("remove_envelop with unknown item {}".format(item))
tiernoc0e42e22018-05-11 11:36:10 +0200103
104 return clean_indata
105
106
107class ROClient:
garciadeblas5697b8b2021-03-24 09:17:02 +0100108 headers_req = {"Accept": "application/yaml", "content-type": "application/yaml"}
109 client_to_RO = {
110 "tenant": "tenants",
111 "vim": "datacenters",
112 "vim_account": "datacenters",
113 "sdn": "sdn_controllers",
114 "vnfd": "vnfs",
115 "nsd": "scenarios",
116 "wim": "wims",
117 "wim_account": "wims",
118 "ns": "instances",
119 }
tiernoc0e42e22018-05-11 11:36:10 +0200120 mandatory_for_create = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100121 "tenant": ("name",),
122 "vnfd": ("name", "id"),
123 "nsd": ("name", "id"),
124 "ns": ("name", "scenario", "datacenter"),
125 "vim": ("name", "vim_url"),
126 "wim": ("name", "wim_url"),
127 "vim_account": (),
128 "wim_account": (),
129 "sdn": ("name", "type"),
tiernoc0e42e22018-05-11 11:36:10 +0200130 }
131 timeout_large = 120
132 timeout_short = 30
133
Gabriel Cubae7898982023-05-11 01:57:21 -0500134 def __init__(self, uri, **kwargs):
tierno69f0d382020-05-07 13:08:09 +0000135 self.uri = uri
tiernoc0e42e22018-05-11 11:36:10 +0200136
137 self.username = kwargs.get("username")
138 self.password = kwargs.get("password")
139 self.tenant_id_name = kwargs.get("tenant")
140 self.tenant = None
141 self.datacenter_id_name = kwargs.get("datacenter")
142 self.datacenter = None
garciadeblas5697b8b2021-03-24 09:17:02 +0100143 logger_name = kwargs.get("logger_name", "lcm.ro")
tiernoc0e42e22018-05-11 11:36:10 +0200144 self.logger = logging.getLogger(logger_name)
145 if kwargs.get("loglevel"):
146 self.logger.setLevel(kwargs["loglevel"])
147 global requests
148 requests = kwargs.get("TODO remove")
149
150 def __getitem__(self, index):
garciadeblas5697b8b2021-03-24 09:17:02 +0100151 if index == "tenant":
tiernoc0e42e22018-05-11 11:36:10 +0200152 return self.tenant_id_name
garciadeblas5697b8b2021-03-24 09:17:02 +0100153 elif index == "datacenter":
tiernoc0e42e22018-05-11 11:36:10 +0200154 return self.datacenter_id_name
garciadeblas5697b8b2021-03-24 09:17:02 +0100155 elif index == "username":
tiernoc0e42e22018-05-11 11:36:10 +0200156 return self.username
garciadeblas5697b8b2021-03-24 09:17:02 +0100157 elif index == "password":
tiernoc0e42e22018-05-11 11:36:10 +0200158 return self.password
garciadeblas5697b8b2021-03-24 09:17:02 +0100159 elif index == "uri":
tierno69f0d382020-05-07 13:08:09 +0000160 return self.uri
tiernoc0e42e22018-05-11 11:36:10 +0200161 else:
tierno750b2452018-05-17 16:39:29 +0200162 raise KeyError("Invalid key '{}'".format(index))
endikac2950402020-09-14 11:20:00 +0200163
tierno750b2452018-05-17 16:39:29 +0200164 def __setitem__(self, index, value):
garciadeblas5697b8b2021-03-24 09:17:02 +0100165 if index == "tenant":
tiernoc0e42e22018-05-11 11:36:10 +0200166 self.tenant_id_name = value
garciadeblas5697b8b2021-03-24 09:17:02 +0100167 elif index == "datacenter" or index == "vim":
tiernoc0e42e22018-05-11 11:36:10 +0200168 self.datacenter_id_name = value
garciadeblas5697b8b2021-03-24 09:17:02 +0100169 elif index == "username":
tiernoc0e42e22018-05-11 11:36:10 +0200170 self.username = value
garciadeblas5697b8b2021-03-24 09:17:02 +0100171 elif index == "password":
tiernoc0e42e22018-05-11 11:36:10 +0200172 self.password = value
garciadeblas5697b8b2021-03-24 09:17:02 +0100173 elif index == "uri":
tierno69f0d382020-05-07 13:08:09 +0000174 self.uri = value
tiernoc0e42e22018-05-11 11:36:10 +0200175 else:
176 raise KeyError("Invalid key '{}'".format(index))
garciadeblas5697b8b2021-03-24 09:17:02 +0100177 self.tenant = None # force to reload tenant with different credentials
tiernoc0e42e22018-05-11 11:36:10 +0200178 self.datacenter = None # force to reload datacenter with different credentials
tierno750b2452018-05-17 16:39:29 +0200179
tiernob5203912020-08-11 11:20:13 +0000180 @staticmethod
181 def _parse(descriptor, descriptor_format, response=False):
garciadeblas5697b8b2021-03-24 09:17:02 +0100182 if (
183 descriptor_format
184 and descriptor_format != "json"
185 and descriptor_format != "yaml"
186 ):
187 raise ROClientException(
188 "'descriptor_format' must be a 'json' or 'yaml' text"
189 )
tiernoc0e42e22018-05-11 11:36:10 +0200190 if descriptor_format != "json":
191 try:
Luisccdc2162022-07-01 14:35:49 +0000192 return yaml.safe_load(descriptor)
tiernoc0e42e22018-05-11 11:36:10 +0200193 except yaml.YAMLError as exc:
194 error_pos = ""
garciadeblas5697b8b2021-03-24 09:17:02 +0100195 if hasattr(exc, "problem_mark"):
tiernoc0e42e22018-05-11 11:36:10 +0200196 mark = exc.problem_mark
garciadeblas5697b8b2021-03-24 09:17:02 +0100197 error_pos = " at line:{} column:{}s".format(
198 mark.line + 1, mark.column + 1
199 )
tiernoc0e42e22018-05-11 11:36:10 +0200200 error_text = "yaml format error" + error_pos
201 elif descriptor_format != "yaml":
202 try:
tierno750b2452018-05-17 16:39:29 +0200203 return json.loads(descriptor)
tiernoc0e42e22018-05-11 11:36:10 +0200204 except Exception as e:
205 if response:
206 error_text = "json format error" + str(e)
207
208 if response:
209 raise ROClientException(error_text)
tierno750b2452018-05-17 16:39:29 +0200210 raise ROClientException(error_text)
tiernob5203912020-08-11 11:20:13 +0000211
212 @staticmethod
213 def _parse_error_yaml(descriptor):
214 json_error = None
215 try:
Luisccdc2162022-07-01 14:35:49 +0000216 json_error = yaml.safe_load(descriptor)
tiernob5203912020-08-11 11:20:13 +0000217 return json_error["error"]["description"]
218 except Exception:
219 return str(json_error or descriptor)
220
221 @staticmethod
222 def _parse_yaml(descriptor, response=False):
tiernoc0e42e22018-05-11 11:36:10 +0200223 try:
Luisccdc2162022-07-01 14:35:49 +0000224 return yaml.safe_load(descriptor)
tiernoc0e42e22018-05-11 11:36:10 +0200225 except yaml.YAMLError as exc:
226 error_pos = ""
garciadeblas5697b8b2021-03-24 09:17:02 +0100227 if hasattr(exc, "problem_mark"):
tiernoc0e42e22018-05-11 11:36:10 +0200228 mark = exc.problem_mark
garciadeblas5697b8b2021-03-24 09:17:02 +0100229 error_pos = " at line:{} column:{}s".format(
230 mark.line + 1, mark.column + 1
231 )
tiernoc0e42e22018-05-11 11:36:10 +0200232 error_text = "yaml format error" + error_pos
233 if response:
234 raise ROClientException(error_text)
tierno750b2452018-05-17 16:39:29 +0200235 raise ROClientException(error_text)
tiernoc0e42e22018-05-11 11:36:10 +0200236
237 @staticmethod
238 def check_if_uuid(uuid_text):
239 """
240 Check if text correspond to an uuid foramt
241 :param uuid_text:
242 :return: True if it is an uuid False if not
243 """
244 try:
245 UUID(uuid_text)
246 return True
tierno98768132018-09-11 12:07:21 +0200247 except Exception:
tiernoc0e42e22018-05-11 11:36:10 +0200248 return False
249
250 @staticmethod
251 def _create_envelop(item, indata=None):
252 """
253 Returns a new dict that incledes indata with the expected envelop
254 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
255 :param indata: Content to be enveloped
256 :return: a new dic with {<envelop>: {indata} } where envelop can be e.g. tenant, datacenter, ...
257 """
258 if item == "vnfd":
garciadeblas5697b8b2021-03-24 09:17:02 +0100259 return {"vnfd-catalog": {"vnfd": [indata]}}
tiernoc0e42e22018-05-11 11:36:10 +0200260 elif item == "nsd":
garciadeblas5697b8b2021-03-24 09:17:02 +0100261 return {"nsd-catalog": {"nsd": [indata]}}
tiernoc0e42e22018-05-11 11:36:10 +0200262 elif item == "tenant":
garciadeblas5697b8b2021-03-24 09:17:02 +0100263 return {"tenant": indata}
tiernoc0e42e22018-05-11 11:36:10 +0200264 elif item in ("vim", "vim_account", "datacenter"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100265 return {"datacenter": indata}
tiernoe37b57d2018-12-11 17:22:51 +0000266 elif item == "wim":
garciadeblas5697b8b2021-03-24 09:17:02 +0100267 return {"wim": indata}
tiernoe37b57d2018-12-11 17:22:51 +0000268 elif item == "wim_account":
garciadeblas5697b8b2021-03-24 09:17:02 +0100269 return {"wim_account": indata}
tiernoc0e42e22018-05-11 11:36:10 +0200270 elif item == "ns" or item == "instances":
garciadeblas5697b8b2021-03-24 09:17:02 +0100271 return {"instance": indata}
tiernoc0e42e22018-05-11 11:36:10 +0200272 elif item == "sdn":
garciadeblas5697b8b2021-03-24 09:17:02 +0100273 return {"sdn_controller": indata}
tiernoc0e42e22018-05-11 11:36:10 +0200274 else:
Gabriel Cuba4c0e6802023-10-09 13:22:38 -0500275 raise ROClientException("remove_envelop with unknown item {}".format(item))
tiernoc0e42e22018-05-11 11:36:10 +0200276
277 @staticmethod
278 def update_descriptor(desc, kwargs):
279 desc = deepcopy(desc) # do not modify original descriptor
280 try:
281 for k, v in kwargs.items():
282 update_content = desc
283 kitem_old = None
284 klist = k.split(".")
285 for kitem in klist:
286 if kitem_old is not None:
287 update_content = update_content[kitem_old]
288 if isinstance(update_content, dict):
289 kitem_old = kitem
290 elif isinstance(update_content, list):
291 kitem_old = int(kitem)
292 else:
293 raise ROClientException(
garciadeblas5697b8b2021-03-24 09:17:02 +0100294 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(
295 k, kitem
296 )
297 )
tiernoc0e42e22018-05-11 11:36:10 +0200298 if v == "__DELETE__":
299 del update_content[kitem_old]
300 else:
301 update_content[kitem_old] = v
302 return desc
303 except KeyError:
304 raise ROClientException(
garciadeblas5697b8b2021-03-24 09:17:02 +0100305 "Invalid query string '{}'. Descriptor does not contain '{}'".format(
306 k, kitem_old
307 )
308 )
tiernoc0e42e22018-05-11 11:36:10 +0200309 except ValueError:
garciadeblas5697b8b2021-03-24 09:17:02 +0100310 raise ROClientException(
311 "Invalid query string '{}'. Expected integer index list instead of '{}'".format(
312 k, kitem
313 )
314 )
tiernoc0e42e22018-05-11 11:36:10 +0200315 except IndexError:
316 raise ROClientException(
garciadeblas5697b8b2021-03-24 09:17:02 +0100317 "Invalid query string '{}'. Index '{}' out of range".format(
318 k, kitem_old
319 )
320 )
tiernoc0e42e22018-05-11 11:36:10 +0200321
cubag3ff23252023-11-29 23:01:21 +0200322 @staticmethod
323 def check_ns_status(ns_descriptor):
324 """
325 Inspect RO instance descriptor and indicates the status
326 :param ns_descriptor: instance descriptor obtained with self.show("ns", )
327 :return: status, message: status can be BUILD,ACTIVE,ERROR, message is a text message
328 """
329 error_list = []
330 total = {"VMs": 0, "networks": 0, "SDN_networks": 0}
331 done = {"VMs": 0, "networks": 0, "SDN_networks": 0}
332
333 def _get_ref(desc):
334 # return an identification for the network or vm. Try vim_id if exist, if not descriptor id for net
335 if desc.get("vim_net_id"):
336 return "'vim-net-id={}'".format(desc["vim_net_id"])
337 elif desc.get("ns_net_osm_id"):
338 return "'nsd-vld-id={}'".format(desc["ns_net_osm_id"])
339 elif desc.get("vnf_net_osm_id"):
340 return "'vnfd-vld-id={}'".format(desc["vnf_net_osm_id"])
341 # for VM
342 elif desc.get("vim_vm_id"):
343 return "'vim-vm-id={}'".format(desc["vim_vm_id"])
344 elif desc.get("vdu_osm_id"):
345 return "'vnfd-vdu-id={}'".format(desc["vdu_osm_id"])
346 else:
347 return ""
348
349 def _get_sdn_ref(sce_net_id):
350 # look for the network associated to the SDN network and obtain the identification
351 net = next(
352 (x for x in ns_descriptor["nets"] if x.get("sce_net_id") == sce_net_id),
353 None,
354 )
355 if not sce_net_id or not net:
356 return ""
357 return _get_ref(net)
358
359 try:
360 total["networks"] = len(ns_descriptor["nets"])
361 for net in ns_descriptor["nets"]:
362 if net["status"] in ("ERROR", "VIM_ERROR"):
363 error_list.append(
364 "Error at VIM network {}: {}".format(
365 _get_ref(net), net["error_msg"]
366 )
367 )
368 elif net["status"] == "ACTIVE":
369 done["networks"] += 1
370
371 total["SDN_networks"] = len(ns_descriptor["sdn_nets"])
372 for sdn_net in ns_descriptor["sdn_nets"]:
373 if sdn_net["status"] in ("ERROR", "VIM_ERROR", "WIM_ERROR"):
374 error_list.append(
375 "Error at SDN network {}: {}".format(
376 _get_sdn_ref(sdn_net.get("sce_net_id")),
377 sdn_net["error_msg"],
378 )
379 )
380 elif sdn_net["status"] == "ACTIVE":
381 done["SDN_networks"] += 1
382
383 for vnf in ns_descriptor["vnfs"]:
384 for vm in vnf["vms"]:
385 total["VMs"] += 1
386 if vm["status"] in ("ERROR", "VIM_ERROR"):
387 error_list.append(
388 "Error at VIM VM {}: {}".format(
389 _get_ref(vm), vm["error_msg"]
390 )
391 )
392 elif vm["status"] == "ACTIVE":
393 done["VMs"] += 1
394 if error_list:
395 # skip errors caused because other dependendent task is on error
396 return "ERROR", "; ".join(
397 [
398 el
399 for el in error_list
400 if "because depends on failed ACTION" not in el
401 ]
402 )
403 if all(total[x] == done[x] for x in total): # DONE == TOTAL for all items
404 return "ACTIVE", str(
405 {x: total[x] for x in total if total[x]}
406 ) # print only those which value is not 0
407 else:
408 return "BUILD", str(
409 {x: "{}/{}".format(done[x], total[x]) for x in total if total[x]}
410 )
411 # print done/total for each item if total is not 0
412 except Exception as e:
413 raise ROClientException(
414 "Unexpected RO ns descriptor. Wrong version? {}".format(e)
415 ) from e
416
417 @staticmethod
418 def check_action_status(action_descriptor):
419 """
420 Inspect RO instance descriptor and indicates the status
421 :param action_descriptor: action instance descriptor obtained with self.show("ns", "action")
422 :return: status, message: status can be BUILD,ACTIVE,ERROR, message is a text message
423 """
424 net_total = 0
425 vm_total = 0
426 net_done = 0
427 vm_done = 0
428 other_total = 0
429 other_done = 0
430
431 for vim_action_set in action_descriptor["actions"]:
432 for vim_action in vim_action_set["vim_wim_actions"]:
433 if vim_action["item"] == "instance_vms":
434 vm_total += 1
435 elif vim_action["item"] == "instance_nets":
436 net_total += 1
437 else:
438 other_total += 1
439 if vim_action["status"] == "FAILED":
440 return "ERROR", vim_action["error_msg"]
441 elif vim_action["status"] in ("DONE", "SUPERSEDED", "FINISHED"):
442 if vim_action["item"] == "instance_vms":
443 vm_done += 1
444 elif vim_action["item"] == "instance_nets":
445 net_done += 1
446 else:
447 other_done += 1
448
449 if net_total == net_done and vm_total == vm_done and other_total == other_done:
450 return "ACTIVE", "VMs {}, networks: {}, other: {} ".format(
451 vm_total, net_total, other_total
452 )
453 else:
454 return "BUILD", "VMs: {}/{}, networks: {}/{}, other: {}/{}".format(
455 vm_done, vm_total, net_done, net_total, other_done, other_total
456 )
457
458 @staticmethod
459 def get_ns_vnf_info(ns_descriptor):
460 """
461 Get a dict with the VIM_id, ip_addresses, mac_addresses of every vnf and vdu
462 :param ns_descriptor: instance descriptor obtained with self.show("ns", )
463 :return: dict with:
464 <member_vnf_index>:
465 ip_address: XXXX,
466 vdur:
467 <vdu_osm_id>:
468 ip_address: XXX
469 vim_id: XXXX
470 interfaces:
471 <name>:
472 ip_address: XXX
473 mac_address: XXX
474 """
475 ns_info = {}
476 for vnf in ns_descriptor["vnfs"]:
477 if not vnf.get("ip_address") and vnf.get("vms"):
478 raise ROClientException(
479 "ns member_vnf_index '{}' has no IP address".format(
480 vnf["member_vnf_index"]
481 ),
482 http_code=409,
483 )
484 vnfr_info = {"ip_address": vnf.get("ip_address"), "vdur": {}}
485 for vm in vnf["vms"]:
486 vdur = {
487 "vim_id": vm.get("vim_vm_id"),
488 "ip_address": vm.get("ip_address"),
489 "interfaces": {},
490 }
491 for iface in vm["interfaces"]:
492 if iface.get("type") == "mgmt" and not iface.get("ip_address"):
493 raise ROClientException(
494 "ns member_vnf_index '{}' vm '{}' management interface '{}' has no IP "
495 "address".format(
496 vnf["member_vnf_index"],
497 vm["vdu_osm_id"],
498 iface["external_name"],
499 ),
500 http_code=409,
501 )
502 vdur["interfaces"][iface["internal_name"]] = {
503 "ip_address": iface.get("ip_address"),
504 "mac_address": iface.get("mac_address"),
505 "vim_id": iface.get("vim_interface_id"),
506 }
507 vnfr_info["vdur"][vm["vdu_osm_id"]] = vdur
508 ns_info[str(vnf["member_vnf_index"])] = vnfr_info
509 return ns_info
510
tiernoc0e42e22018-05-11 11:36:10 +0200511 async def _get_item_uuid(self, session, item, item_id_name, all_tenants=False):
512 if all_tenants:
513 tenant_text = "/any"
514 elif all_tenants is None:
515 tenant_text = ""
516 else:
517 if not self.tenant:
518 await self._get_tenant(session)
519 tenant_text = "/" + self.tenant
520
521 item_id = 0
tierno69f0d382020-05-07 13:08:09 +0000522 url = "{}{}/{}".format(self.uri, tenant_text, item)
tiernoc0e42e22018-05-11 11:36:10 +0200523 if self.check_if_uuid(item_id_name):
524 item_id = item_id_name
525 url += "/" + item_id_name
garciadeblas5697b8b2021-03-24 09:17:02 +0100526 elif (
527 item_id_name and item_id_name.startswith("'") and item_id_name.endswith("'")
528 ):
tiernoc0e42e22018-05-11 11:36:10 +0200529 item_id_name = item_id_name[1:-1]
tierno750b2452018-05-17 16:39:29 +0200530 self.logger.debug("RO GET %s", url)
calvinosanchd5916fd2020-01-09 17:19:53 +0100531 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
532 async with session.get(url, headers=self.headers_req) as response:
533 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100534 self.logger.debug(
535 "GET {} [{}] {}".format(url, response.status, response_text[:100])
536 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100537 if response.status == 404: # NOT_FOUND
garciadeblas5697b8b2021-03-24 09:17:02 +0100538 raise ROClientException(
539 "No {} found with id '{}'".format(item[:-1], item_id_name),
540 http_code=404,
541 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100542 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100543 raise ROClientException(
544 self._parse_error_yaml(response_text), http_code=response.status
545 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100546 content = self._parse_yaml(response_text, response=True)
tiernoc0e42e22018-05-11 11:36:10 +0200547
548 if item_id:
549 return item_id
550 desc = content[item]
Gabriel Cuba4c0e6802023-10-09 13:22:38 -0500551 if not isinstance(desc, list):
552 raise ROClientException(
553 "_get_item_uuid get a non dict with a list inside {}".format(type(desc))
554 )
tiernoc0e42e22018-05-11 11:36:10 +0200555 uuid = None
556 for i in desc:
557 if item_id_name and i["name"] != item_id_name:
558 continue
559 if uuid: # found more than one
560 raise ROClientException(
garciadeblas5697b8b2021-03-24 09:17:02 +0100561 "Found more than one {} with name '{}'. uuid must be used".format(
562 item, item_id_name
563 ),
564 http_code=404,
565 )
tiernoc0e42e22018-05-11 11:36:10 +0200566 uuid = i["uuid"]
567 if not uuid:
garciadeblas5697b8b2021-03-24 09:17:02 +0100568 raise ROClientException(
569 "No {} found with name '{}'".format(item[:-1], item_id_name),
570 http_code=404,
571 )
tiernoc0e42e22018-05-11 11:36:10 +0200572 return uuid
573
cubag3ff23252023-11-29 23:01:21 +0200574 async def _get_item(
575 self,
576 session,
577 item,
578 item_id_name,
579 extra_item=None,
580 extra_item_id=None,
581 all_tenants=False,
582 ):
583 if all_tenants:
584 tenant_text = "/any"
585 elif all_tenants is None:
586 tenant_text = ""
587 else:
588 if not self.tenant:
589 await self._get_tenant(session)
590 tenant_text = "/" + self.tenant
591
592 if self.check_if_uuid(item_id_name):
593 uuid = item_id_name
594 else:
595 # check that exist
596 uuid = await self._get_item_uuid(session, item, item_id_name, all_tenants)
597
598 url = "{}{}/{}/{}".format(self.uri, tenant_text, item, uuid)
599 if extra_item:
600 url += "/" + extra_item
601 if extra_item_id:
602 url += "/" + extra_item_id
603 self.logger.debug("GET %s", url)
604 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
605 async with session.get(url, headers=self.headers_req) as response:
606 response_text = await response.read()
607 self.logger.debug(
608 "GET {} [{}] {}".format(url, response.status, response_text[:100])
609 )
610 if response.status >= 300:
611 raise ROClientException(
612 self._parse_error_yaml(response_text), http_code=response.status
613 )
614
615 return self._parse_yaml(response_text, response=True)
616
tiernoc0e42e22018-05-11 11:36:10 +0200617 async def _get_tenant(self, session):
618 if not self.tenant:
garciadeblas5697b8b2021-03-24 09:17:02 +0100619 self.tenant = await self._get_item_uuid(
620 session, "tenants", self.tenant_id_name, None
621 )
tiernoc0e42e22018-05-11 11:36:10 +0200622 return self.tenant
endikac2950402020-09-14 11:20:00 +0200623
tiernoc0e42e22018-05-11 11:36:10 +0200624 async def _get_datacenter(self, session):
625 if not self.tenant:
626 await self._get_tenant(session)
627 if not self.datacenter:
garciadeblas5697b8b2021-03-24 09:17:02 +0100628 self.datacenter = await self._get_item_uuid(
629 session, "datacenters", self.datacenter_id_name, True
630 )
tiernoc0e42e22018-05-11 11:36:10 +0200631 return self.datacenter
632
garciadeblas5697b8b2021-03-24 09:17:02 +0100633 async def _create_item(
634 self,
635 session,
636 item,
637 descriptor,
638 item_id_name=None,
639 action=None,
640 all_tenants=False,
641 ):
tiernoc0e42e22018-05-11 11:36:10 +0200642 if all_tenants:
643 tenant_text = "/any"
644 elif all_tenants is None:
645 tenant_text = ""
646 else:
647 if not self.tenant:
648 await self._get_tenant(session)
649 tenant_text = "/" + self.tenant
650 payload_req = yaml.safe_dump(descriptor)
tierno750b2452018-05-17 16:39:29 +0200651 # print payload_req
tiernoc0e42e22018-05-11 11:36:10 +0200652
653 api_version_text = ""
654 if item == "vnfs":
655 # assumes version v3 only
656 api_version_text = "/v3"
657 item = "vnfd"
658 elif item == "scenarios":
659 # assumes version v3 only
660 api_version_text = "/v3"
661 item = "nsd"
662
663 if not item_id_name:
tierno750b2452018-05-17 16:39:29 +0200664 uuid = ""
tiernoc0e42e22018-05-11 11:36:10 +0200665 elif self.check_if_uuid(item_id_name):
666 uuid = "/{}".format(item_id_name)
667 else:
668 # check that exist
669 uuid = await self._get_item_uuid(session, item, item_id_name, all_tenants)
670 uuid = "/{}".format(uuid)
671 if not action:
672 action = ""
673 else:
tierno22f4f9c2018-06-11 18:53:39 +0200674 action = "/{}".format(action)
tiernoc0e42e22018-05-11 11:36:10 +0200675
garciadeblas5697b8b2021-03-24 09:17:02 +0100676 url = "{}{apiver}{tenant}/{item}{id}{action}".format(
677 self.uri,
678 apiver=api_version_text,
679 tenant=tenant_text,
680 item=item,
681 id=uuid,
682 action=action,
683 )
tierno750b2452018-05-17 16:39:29 +0200684 self.logger.debug("RO POST %s %s", url, payload_req)
calvinosanchd5916fd2020-01-09 17:19:53 +0100685 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
garciadeblas5697b8b2021-03-24 09:17:02 +0100686 async with session.post(
687 url, headers=self.headers_req, data=payload_req
688 ) as response:
calvinosanchd5916fd2020-01-09 17:19:53 +0100689 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100690 self.logger.debug(
691 "POST {} [{}] {}".format(url, response.status, response_text[:100])
692 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100693 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100694 raise ROClientException(
695 self._parse_error_yaml(response_text), http_code=response.status
696 )
tiernoc0e42e22018-05-11 11:36:10 +0200697
698 return self._parse_yaml(response_text, response=True)
699
700 async def _del_item(self, session, item, item_id_name, all_tenants=False):
701 if all_tenants:
702 tenant_text = "/any"
703 elif all_tenants is None:
704 tenant_text = ""
705 else:
706 if not self.tenant:
707 await self._get_tenant(session)
708 tenant_text = "/" + self.tenant
709 if not self.check_if_uuid(item_id_name):
710 # check that exist
711 _all_tenants = all_tenants
garciadeblas5697b8b2021-03-24 09:17:02 +0100712 if item in ("datacenters", "wims"):
tiernoc0e42e22018-05-11 11:36:10 +0200713 _all_tenants = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100714 uuid = await self._get_item_uuid(
715 session, item, item_id_name, all_tenants=_all_tenants
716 )
tiernoc0e42e22018-05-11 11:36:10 +0200717 else:
718 uuid = item_id_name
tierno750b2452018-05-17 16:39:29 +0200719
tierno69f0d382020-05-07 13:08:09 +0000720 url = "{}{}/{}/{}".format(self.uri, tenant_text, item, uuid)
tiernoc0e42e22018-05-11 11:36:10 +0200721 self.logger.debug("DELETE %s", url)
calvinosanchd5916fd2020-01-09 17:19:53 +0100722 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
723 async with session.delete(url, headers=self.headers_req) as response:
724 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100725 self.logger.debug(
726 "DELETE {} [{}] {}".format(url, response.status, response_text[:100])
727 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100728 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100729 raise ROClientException(
730 self._parse_error_yaml(response_text), http_code=response.status
731 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100732
tiernoc0e42e22018-05-11 11:36:10 +0200733 return self._parse_yaml(response_text, response=True)
734
735 async def _list_item(self, session, item, all_tenants=False, filter_dict=None):
736 if all_tenants:
737 tenant_text = "/any"
738 elif all_tenants is None:
739 tenant_text = ""
740 else:
741 if not self.tenant:
742 await self._get_tenant(session)
743 tenant_text = "/" + self.tenant
tierno750b2452018-05-17 16:39:29 +0200744
tierno69f0d382020-05-07 13:08:09 +0000745 url = "{}{}/{}".format(self.uri, tenant_text, item)
tiernoc0e42e22018-05-11 11:36:10 +0200746 separator = "?"
747 if filter_dict:
748 for k in filter_dict:
tierno750b2452018-05-17 16:39:29 +0200749 url += separator + quote(str(k)) + "=" + quote(str(filter_dict[k]))
tiernoc0e42e22018-05-11 11:36:10 +0200750 separator = "&"
tierno750b2452018-05-17 16:39:29 +0200751 self.logger.debug("RO GET %s", url)
calvinosanchd5916fd2020-01-09 17:19:53 +0100752 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
753 async with session.get(url, headers=self.headers_req) as response:
754 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100755 self.logger.debug(
756 "GET {} [{}] {}".format(url, response.status, response_text[:100])
757 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100758 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100759 raise ROClientException(
760 self._parse_error_yaml(response_text), http_code=response.status
761 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100762
tiernoc0e42e22018-05-11 11:36:10 +0200763 return self._parse_yaml(response_text, response=True)
764
765 async def _edit_item(self, session, item, item_id, descriptor, all_tenants=False):
766 if all_tenants:
767 tenant_text = "/any"
768 elif all_tenants is None:
769 tenant_text = ""
770 else:
771 if not self.tenant:
772 await self._get_tenant(session)
773 tenant_text = "/" + self.tenant
774
775 payload_req = yaml.safe_dump(descriptor)
endikac2950402020-09-14 11:20:00 +0200776
tierno750b2452018-05-17 16:39:29 +0200777 # print payload_req
tierno69f0d382020-05-07 13:08:09 +0000778 url = "{}{}/{}/{}".format(self.uri, tenant_text, item, item_id)
tierno750b2452018-05-17 16:39:29 +0200779 self.logger.debug("RO PUT %s %s", url, payload_req)
calvinosanchd5916fd2020-01-09 17:19:53 +0100780 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
garciadeblas5697b8b2021-03-24 09:17:02 +0100781 async with session.put(
782 url, headers=self.headers_req, data=payload_req
783 ) as response:
calvinosanchd5916fd2020-01-09 17:19:53 +0100784 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100785 self.logger.debug(
786 "PUT {} [{}] {}".format(url, response.status, response_text[:100])
787 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100788 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100789 raise ROClientException(
790 self._parse_error_yaml(response_text), http_code=response.status
791 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100792
tiernoc0e42e22018-05-11 11:36:10 +0200793 return self._parse_yaml(response_text, response=True)
794
tierno22f4f9c2018-06-11 18:53:39 +0200795 async def get_version(self):
796 """
797 Obtain RO server version.
798 :return: a list with integers ["major", "minor", "release"]. Raises ROClientException on Error,
799 """
800 try:
tiernoc231a872020-01-21 08:49:05 +0000801 response_text = ""
bravof922c4172020-11-24 21:21:43 -0300802 async with aiohttp.ClientSession() as session:
tierno69f0d382020-05-07 13:08:09 +0000803 url = "{}/version".format(self.uri)
tierno22f4f9c2018-06-11 18:53:39 +0200804 self.logger.debug("RO GET %s", url)
calvinosanchd5916fd2020-01-09 17:19:53 +0100805 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
806 async with session.get(url, headers=self.headers_req) as response:
807 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100808 self.logger.debug(
809 "GET {} [{}] {}".format(
810 url, response.status, response_text[:100]
811 )
812 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100813 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100814 raise ROClientException(
815 self._parse_error_yaml(response_text),
816 http_code=response.status,
817 )
calvinosanchd5916fd2020-01-09 17:19:53 +0100818
tierno22f4f9c2018-06-11 18:53:39 +0200819 for word in str(response_text).split(" "):
820 if "." in word:
821 version_text, _, _ = word.partition("-")
tierno8069ce52019-08-28 15:34:33 +0000822 return version_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100823 raise ROClientException(
824 "Got invalid version text: '{}'".format(response_text),
825 http_code=500,
826 )
calvinosanch30ccee32020-01-13 12:01:36 +0100827 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tierno22f4f9c2018-06-11 18:53:39 +0200828 raise ROClientException(e, http_code=504)
829 except asyncio.TimeoutError:
830 raise ROClientException("Timeout", http_code=504)
831 except Exception as e:
Gabriel Cubae7898982023-05-11 01:57:21 -0500832 self.logger.critical(
833 "Got invalid version text: '{}'; causing exception {}".format(
834 response_text, str(e)
835 )
836 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100837 raise ROClientException(
838 "Got invalid version text: '{}'; causing exception {}".format(
839 response_text, e
840 ),
841 http_code=500,
842 )
tierno22f4f9c2018-06-11 18:53:39 +0200843
tiernoc0e42e22018-05-11 11:36:10 +0200844 async def get_list(self, item, all_tenants=False, filter_by=None):
845 """
bravof922c4172020-11-24 21:21:43 -0300846 List of items filtered by the contents in the dictionary "filter_by".
tiernoc0e42e22018-05-11 11:36:10 +0200847 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
848 :param all_tenants: True if not filtering by tenant. Only allowed for admin
849 :param filter_by: dictionary with filtering
850 :return: a list of dict. It can be empty. Raises ROClientException on Error,
851 """
852 try:
853 if item not in self.client_to_RO:
854 raise ROClientException("Invalid item {}".format(item))
garciadeblas5697b8b2021-03-24 09:17:02 +0100855 if item == "tenant":
tiernoc0e42e22018-05-11 11:36:10 +0200856 all_tenants = None
Gabriel Cubae7898982023-05-11 01:57:21 -0500857 async with aiohttp.ClientSession() as session:
garciadeblas5697b8b2021-03-24 09:17:02 +0100858 content = await self._list_item(
859 session,
860 self.client_to_RO[item],
861 all_tenants=all_tenants,
862 filter_dict=filter_by,
863 )
tiernoc0e42e22018-05-11 11:36:10 +0200864 if isinstance(content, dict):
865 if len(content) == 1:
866 for _, v in content.items():
867 return v
868 return content.values()[0]
869 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100870 raise ROClientException(
871 "Output not a list neither dict with len equal 1", http_code=500
872 )
tiernoc0e42e22018-05-11 11:36:10 +0200873 return content
calvinosanch30ccee32020-01-13 12:01:36 +0100874 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tiernoc0e42e22018-05-11 11:36:10 +0200875 raise ROClientException(e, http_code=504)
tierno22f4f9c2018-06-11 18:53:39 +0200876 except asyncio.TimeoutError:
877 raise ROClientException("Timeout", http_code=504)
tiernoc0e42e22018-05-11 11:36:10 +0200878
cubag3ff23252023-11-29 23:01:21 +0200879 async def show(
880 self,
881 item,
882 item_id_name=None,
883 extra_item=None,
884 extra_item_id=None,
885 all_tenants=False,
886 ):
887 """
888 Obtain the information of an item from its id or name
889 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
890 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
891 :param extra_item: if supplied, it is used to add to the URL.
892 Can be 'action' if item='ns'; 'networks' or'images' if item='vim'
893 :param extra_item_id: if supplied, it is used get details of a concrete extra_item.
894 :param all_tenants: True if not filtering by tenant. Only allowed for admin
895 :return: dictionary with the information or raises ROClientException on Error, NotFound, found several
896 """
897 try:
898 if item not in self.client_to_RO:
899 raise ROClientException("Invalid item {}".format(item))
900 if item == "tenant":
901 all_tenants = None
902 elif item == "vim":
903 all_tenants = True
904 elif item == "vim_account":
905 all_tenants = False
906
907 async with aiohttp.ClientSession() as session:
908 content = await self._get_item(
909 session,
910 self.client_to_RO[item],
911 item_id_name,
912 extra_item=extra_item,
913 extra_item_id=extra_item_id,
914 all_tenants=all_tenants,
915 )
916 return remove_envelop(item, content)
917 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
918 raise ROClientException(e, http_code=504)
919 except asyncio.TimeoutError:
920 raise ROClientException("Timeout", http_code=504)
921
tiernoc0e42e22018-05-11 11:36:10 +0200922 async def delete(self, item, item_id_name=None, all_tenants=False):
923 """
924 Delete the information of an item from its id or name
925 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
926 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
927 :param all_tenants: True if not filtering by tenant. Only allowed for admin
928 :return: dictionary with the information or raises ROClientException on Error, NotFound, found several
929 """
930 try:
931 if item not in self.client_to_RO:
932 raise ROClientException("Invalid item {}".format(item))
garciadeblas5697b8b2021-03-24 09:17:02 +0100933 if item in ("tenant", "vim", "wim"):
tiernoc0e42e22018-05-11 11:36:10 +0200934 all_tenants = None
935
Gabriel Cubae7898982023-05-11 01:57:21 -0500936 async with aiohttp.ClientSession() as session:
garciadeblas5697b8b2021-03-24 09:17:02 +0100937 result = await self._del_item(
938 session,
939 self.client_to_RO[item],
940 item_id_name,
941 all_tenants=all_tenants,
942 )
tiernofa66d152018-08-28 10:13:45 +0000943 # in case of ns delete, get the action_id embeded in text
944 if item == "ns" and result.get("result"):
945 _, _, action_id = result["result"].partition("action_id=")
946 action_id, _, _ = action_id.partition(" ")
947 if action_id:
948 result["action_id"] = action_id
949 return result
calvinosanch30ccee32020-01-13 12:01:36 +0100950 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tiernoc0e42e22018-05-11 11:36:10 +0200951 raise ROClientException(e, http_code=504)
tierno22f4f9c2018-06-11 18:53:39 +0200952 except asyncio.TimeoutError:
953 raise ROClientException("Timeout", http_code=504)
tiernoc0e42e22018-05-11 11:36:10 +0200954
garciadeblas5697b8b2021-03-24 09:17:02 +0100955 async def edit(
956 self, item, item_id_name, descriptor=None, descriptor_format=None, **kwargs
957 ):
958 """Edit an item
tiernoc0e42e22018-05-11 11:36:10 +0200959 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns', 'vim'
tierno22f4f9c2018-06-11 18:53:39 +0200960 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
tiernoc0e42e22018-05-11 11:36:10 +0200961 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
962 :param descriptor_format: Can be 'json' or 'yaml'
963 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
964 keys can be a dot separated list to specify elements inside dict
965 :return: dictionary with the information or raises ROClientException on Error
966 """
967 try:
968 if isinstance(descriptor, str):
969 descriptor = self._parse(descriptor, descriptor_format)
970 elif descriptor:
971 pass
972 else:
973 descriptor = {}
974
975 if item not in self.client_to_RO:
976 raise ROClientException("Invalid item {}".format(item))
977 desc = remove_envelop(item, descriptor)
978
979 # Override descriptor with kwargs
980 if kwargs:
981 desc = self.update_descriptor(desc, kwargs)
982 all_tenants = False
garciadeblas5697b8b2021-03-24 09:17:02 +0100983 if item in ("tenant", "vim"):
tiernoc0e42e22018-05-11 11:36:10 +0200984 all_tenants = None
985
986 create_desc = self._create_envelop(item, desc)
987
Gabriel Cubae7898982023-05-11 01:57:21 -0500988 async with aiohttp.ClientSession() as session:
tiernoc0e42e22018-05-11 11:36:10 +0200989 _all_tenants = all_tenants
garciadeblas5697b8b2021-03-24 09:17:02 +0100990 if item == "vim":
tiernoc0e42e22018-05-11 11:36:10 +0200991 _all_tenants = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100992 item_id = await self._get_item_uuid(
993 session,
994 self.client_to_RO[item],
995 item_id_name,
996 all_tenants=_all_tenants,
997 )
998 if item == "vim":
tiernofe1c37f2018-05-17 22:58:04 +0200999 _all_tenants = None
tiernoc0e42e22018-05-11 11:36:10 +02001000 # await self._get_tenant(session)
garciadeblas5697b8b2021-03-24 09:17:02 +01001001 outdata = await self._edit_item(
1002 session,
1003 self.client_to_RO[item],
1004 item_id,
1005 create_desc,
1006 all_tenants=_all_tenants,
1007 )
tiernoc0e42e22018-05-11 11:36:10 +02001008 return remove_envelop(item, outdata)
calvinosanch30ccee32020-01-13 12:01:36 +01001009 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tiernoc0e42e22018-05-11 11:36:10 +02001010 raise ROClientException(e, http_code=504)
tierno22f4f9c2018-06-11 18:53:39 +02001011 except asyncio.TimeoutError:
1012 raise ROClientException("Timeout", http_code=504)
tiernoc0e42e22018-05-11 11:36:10 +02001013
1014 async def create(self, item, descriptor=None, descriptor_format=None, **kwargs):
1015 """
1016 Creates an item from its descriptor
1017 :param item: can be 'tenant', 'vnfd', 'nsd', 'ns', 'vim', 'vim_account', 'sdn'
1018 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
1019 :param descriptor_format: Can be 'json' or 'yaml'
1020 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
1021 keys can be a dot separated list to specify elements inside dict
1022 :return: dictionary with the information or raises ROClientException on Error
1023 """
1024 try:
1025 if isinstance(descriptor, str):
1026 descriptor = self._parse(descriptor, descriptor_format)
1027 elif descriptor:
1028 pass
1029 else:
1030 descriptor = {}
1031
1032 if item not in self.client_to_RO:
1033 raise ROClientException("Invalid item {}".format(item))
1034 desc = remove_envelop(item, descriptor)
1035
1036 # Override descriptor with kwargs
1037 if kwargs:
1038 desc = self.update_descriptor(desc, kwargs)
1039
1040 for mandatory in self.mandatory_for_create[item]:
1041 if mandatory not in desc:
garciadeblas5697b8b2021-03-24 09:17:02 +01001042 raise ROClientException(
1043 "'{}' is mandatory parameter for {}".format(mandatory, item)
1044 )
tiernoc0e42e22018-05-11 11:36:10 +02001045
1046 all_tenants = False
garciadeblas5697b8b2021-03-24 09:17:02 +01001047 if item in ("tenant", "vim", "wim"):
tiernoc0e42e22018-05-11 11:36:10 +02001048 all_tenants = None
1049
1050 create_desc = self._create_envelop(item, desc)
1051
Gabriel Cubae7898982023-05-11 01:57:21 -05001052 async with aiohttp.ClientSession() as session:
garciadeblas5697b8b2021-03-24 09:17:02 +01001053 outdata = await self._create_item(
1054 session,
1055 self.client_to_RO[item],
1056 create_desc,
1057 all_tenants=all_tenants,
1058 )
tiernoc0e42e22018-05-11 11:36:10 +02001059 return remove_envelop(item, outdata)
calvinosanch30ccee32020-01-13 12:01:36 +01001060 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tiernoc0e42e22018-05-11 11:36:10 +02001061 raise ROClientException(e, http_code=504)
tierno22f4f9c2018-06-11 18:53:39 +02001062 except asyncio.TimeoutError:
1063 raise ROClientException("Timeout", http_code=504)
1064
cubag3ff23252023-11-29 23:01:21 +02001065 async def create_action(
1066 self, item, item_id_name, descriptor=None, descriptor_format=None, **kwargs
1067 ):
1068 """
1069 Performs an action over an item
1070 :param item: can be 'tenant', 'vnfd', 'nsd', 'ns', 'vim', 'vim_account', 'sdn'
1071 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
1072 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
1073 :param descriptor_format: Can be 'json' or 'yaml'
1074 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
1075 keys can be a dot separated list to specify elements inside dict
1076 :return: dictionary with the information or raises ROClientException on Error
1077 """
1078 try:
1079 if isinstance(descriptor, str):
1080 descriptor = self._parse(descriptor, descriptor_format)
1081 elif descriptor:
1082 pass
1083 else:
1084 descriptor = {}
1085
1086 if item not in self.client_to_RO:
1087 raise ROClientException("Invalid item {}".format(item))
1088 desc = remove_envelop(item, descriptor)
1089
1090 # Override descriptor with kwargs
1091 if kwargs:
1092 desc = self.update_descriptor(desc, kwargs)
1093
1094 all_tenants = False
1095 if item in ("tenant", "vim"):
1096 all_tenants = None
1097
1098 action = None
1099 if item == "vims":
1100 action = "sdn_mapping"
1101 elif item in ("vim_account", "ns"):
1102 action = "action"
1103
1104 # create_desc = self._create_envelop(item, desc)
1105 create_desc = desc
1106
1107 async with aiohttp.ClientSession() as session:
1108 _all_tenants = all_tenants
1109 if item == "vim":
1110 _all_tenants = True
1111 # item_id = await self._get_item_uuid(session, self.client_to_RO[item], item_id_name,
1112 # all_tenants=_all_tenants)
1113 outdata = await self._create_item(
1114 session,
1115 self.client_to_RO[item],
1116 create_desc,
1117 item_id_name=item_id_name, # item_id_name=item_id
1118 action=action,
1119 all_tenants=_all_tenants,
1120 )
1121 return remove_envelop(item, outdata)
1122 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
1123 raise ROClientException(e, http_code=504)
1124 except asyncio.TimeoutError:
1125 raise ROClientException("Timeout", http_code=504)
1126
garciadeblas5697b8b2021-03-24 09:17:02 +01001127 async def attach(
1128 self, item, item_id_name=None, descriptor=None, descriptor_format=None, **kwargs
1129 ):
tiernoe37b57d2018-12-11 17:22:51 +00001130 """
1131 Attach a datacenter or wim to a tenant, creating a vim_account, wim_account
1132 :param item: can be vim_account or wim_account
1133 :param item_id_name: id or name of the datacenter, wim
1134 :param descriptor:
1135 :param descriptor_format:
1136 :param kwargs:
1137 :return:
1138 """
tierno22f4f9c2018-06-11 18:53:39 +02001139 try:
1140 if isinstance(descriptor, str):
1141 descriptor = self._parse(descriptor, descriptor_format)
1142 elif descriptor:
1143 pass
1144 else:
1145 descriptor = {}
tiernoe37b57d2018-12-11 17:22:51 +00001146
1147 desc = remove_envelop(item, descriptor)
tiernoc0e42e22018-05-11 11:36:10 +02001148
tierno22f4f9c2018-06-11 18:53:39 +02001149 # # check that exist
1150 # uuid = self._get_item_uuid(session, "datacenters", uuid_name, all_tenants=True)
1151 # tenant_text = "/" + self._get_tenant()
1152 if kwargs:
1153 desc = self.update_descriptor(desc, kwargs)
tiernoc0e42e22018-05-11 11:36:10 +02001154
tiernoe37b57d2018-12-11 17:22:51 +00001155 if item == "vim_account":
1156 if not desc.get("vim_tenant_name") and not desc.get("vim_tenant_id"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001157 raise ROClientException(
1158 "Wrong descriptor. At least vim_tenant_name or vim_tenant_id must be "
1159 "provided"
1160 )
tiernoe37b57d2018-12-11 17:22:51 +00001161 elif item != "wim_account":
garciadeblas5697b8b2021-03-24 09:17:02 +01001162 raise ROClientException(
1163 "Attach with unknown item {}. Must be 'vim_account' or 'wim_account'".format(
1164 item
1165 )
1166 )
tiernoe37b57d2018-12-11 17:22:51 +00001167 create_desc = self._create_envelop(item, desc)
tierno22f4f9c2018-06-11 18:53:39 +02001168 payload_req = yaml.safe_dump(create_desc)
Gabriel Cubae7898982023-05-11 01:57:21 -05001169 async with aiohttp.ClientSession() as session:
tierno22f4f9c2018-06-11 18:53:39 +02001170 # check that exist
garciadeblas5697b8b2021-03-24 09:17:02 +01001171 item_id = await self._get_item_uuid(
1172 session, self.client_to_RO[item], item_id_name, all_tenants=True
1173 )
tierno22f4f9c2018-06-11 18:53:39 +02001174 await self._get_tenant(session)
tiernoc0e42e22018-05-11 11:36:10 +02001175
garciadeblas5697b8b2021-03-24 09:17:02 +01001176 url = "{}/{tenant}/{item}/{item_id}".format(
1177 self.uri,
1178 tenant=self.tenant,
1179 item=self.client_to_RO[item],
1180 item_id=item_id,
1181 )
tierno22f4f9c2018-06-11 18:53:39 +02001182 self.logger.debug("RO POST %s %s", url, payload_req)
calvinosanchd5916fd2020-01-09 17:19:53 +01001183 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
garciadeblas5697b8b2021-03-24 09:17:02 +01001184 async with session.post(
1185 url, headers=self.headers_req, data=payload_req
1186 ) as response:
calvinosanchd5916fd2020-01-09 17:19:53 +01001187 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +01001188 self.logger.debug(
1189 "POST {} [{}] {}".format(
1190 url, response.status, response_text[:100]
1191 )
1192 )
calvinosanchd5916fd2020-01-09 17:19:53 +01001193 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +01001194 raise ROClientException(
1195 self._parse_error_yaml(response_text),
1196 http_code=response.status,
1197 )
tiernoc0e42e22018-05-11 11:36:10 +02001198
tierno22f4f9c2018-06-11 18:53:39 +02001199 response_desc = self._parse_yaml(response_text, response=True)
tiernoe37b57d2018-12-11 17:22:51 +00001200 desc = remove_envelop(item, response_desc)
tierno22f4f9c2018-06-11 18:53:39 +02001201 return desc
calvinosanch30ccee32020-01-13 12:01:36 +01001202 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tierno22f4f9c2018-06-11 18:53:39 +02001203 raise ROClientException(e, http_code=504)
1204 except asyncio.TimeoutError:
1205 raise ROClientException("Timeout", http_code=504)
tiernoc0e42e22018-05-11 11:36:10 +02001206
tiernoe37b57d2018-12-11 17:22:51 +00001207 async def detach(self, item, item_id_name=None):
tierno750b2452018-05-17 16:39:29 +02001208 # TODO replace the code with delete_item(vim_account,...)
tierno22f4f9c2018-06-11 18:53:39 +02001209 try:
Gabriel Cubae7898982023-05-11 01:57:21 -05001210 async with aiohttp.ClientSession() as session:
tierno22f4f9c2018-06-11 18:53:39 +02001211 # check that exist
garciadeblas5697b8b2021-03-24 09:17:02 +01001212 item_id = await self._get_item_uuid(
1213 session, self.client_to_RO[item], item_id_name, all_tenants=False
1214 )
tierno22f4f9c2018-06-11 18:53:39 +02001215 tenant = await self._get_tenant(session)
tiernoc0e42e22018-05-11 11:36:10 +02001216
garciadeblas5697b8b2021-03-24 09:17:02 +01001217 url = "{}/{tenant}/{item}/{datacenter}".format(
1218 self.uri,
1219 tenant=tenant,
1220 item=self.client_to_RO[item],
1221 datacenter=item_id,
1222 )
tierno22f4f9c2018-06-11 18:53:39 +02001223 self.logger.debug("RO DELETE %s", url)
endikac2950402020-09-14 11:20:00 +02001224
calvinosanchd5916fd2020-01-09 17:19:53 +01001225 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
1226 async with session.delete(url, headers=self.headers_req) as response:
1227 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +01001228 self.logger.debug(
1229 "DELETE {} [{}] {}".format(
1230 url, response.status, response_text[:100]
1231 )
1232 )
calvinosanchd5916fd2020-01-09 17:19:53 +01001233 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +01001234 raise ROClientException(
1235 self._parse_error_yaml(response_text),
1236 http_code=response.status,
1237 )
endikac2950402020-09-14 11:20:00 +02001238
tierno22f4f9c2018-06-11 18:53:39 +02001239 response_desc = self._parse_yaml(response_text, response=True)
tiernoe37b57d2018-12-11 17:22:51 +00001240 desc = remove_envelop(item, response_desc)
tierno22f4f9c2018-06-11 18:53:39 +02001241 return desc
calvinosanch30ccee32020-01-13 12:01:36 +01001242 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
tierno22f4f9c2018-06-11 18:53:39 +02001243 raise ROClientException(e, http_code=504)
1244 except asyncio.TimeoutError:
1245 raise ROClientException("Timeout", http_code=504)
cubag3ff23252023-11-29 23:01:21 +02001246
1247 # TODO convert to asyncio
1248 # DATACENTERS
1249
1250 def edit_datacenter(
1251 self,
1252 uuid=None,
1253 name=None,
1254 descriptor=None,
1255 descriptor_format=None,
1256 all_tenants=False,
1257 **kwargs
1258 ):
1259 """Edit the parameters of a datacenter
1260 Params: must supply a descriptor or/and a parameter to change
1261 uuid or/and name. If only name is supplied, there must be only one or an exception is raised
1262 descriptor: with format {'datacenter':{params to change info}}
1263 must be a dictionary or a json/yaml text.
1264 parameters to change can be supplyied by the descriptor or as parameters:
1265 new_name: the datacenter name
1266 vim_url: the datacenter URL
1267 vim_url_admin: the datacenter URL for administrative issues
1268 vim_type: the datacenter type, can be openstack or openvim.
1269 public: boolean, available to other tenants
1270 description: datacenter description
1271 Return: Raises an exception on error, not found or found several
1272 Obtain a dictionary with format {'datacenter':{new_datacenter_info}}
1273 """
1274
1275 if isinstance(descriptor, str):
1276 descriptor = self._parse(descriptor, descriptor_format)
1277 elif descriptor:
1278 pass
1279 elif kwargs:
1280 descriptor = {"datacenter": {}}
1281 else:
1282 raise ROClientException("Missing descriptor")
1283
1284 if "datacenter" not in descriptor or len(descriptor) != 1:
1285 raise ROClientException(
1286 "Descriptor must contain only one 'datacenter' field"
1287 )
1288 for param in kwargs:
1289 if param == "new_name":
1290 descriptor["datacenter"]["name"] = kwargs[param]
1291 else:
1292 descriptor["datacenter"][param] = kwargs[param]
1293 return self._edit_item("datacenters", descriptor, uuid, name, all_tenants=None)
1294
1295 def edit_scenario(
1296 self,
1297 uuid=None,
1298 name=None,
1299 descriptor=None,
1300 descriptor_format=None,
1301 all_tenants=False,
1302 **kwargs
1303 ):
1304 """Edit the parameters of a scenario
1305 Params: must supply a descriptor or/and a parameters to change
1306 uuid or/and name. If only name is supplied, there must be only one or an exception is raised
1307 descriptor: with format {'scenario':{params to change info}}
1308 must be a dictionary or a json/yaml text.
1309 parameters to change can be supplyied by the descriptor or as parameters:
1310 new_name: the scenario name
1311 public: boolean, available to other tenants
1312 description: scenario description
1313 tenant_id. Propietary tenant
1314 Return: Raises an exception on error, not found or found several
1315 Obtain a dictionary with format {'scenario':{new_scenario_info}}
1316 """
1317
1318 if isinstance(descriptor, str):
1319 descriptor = self._parse(descriptor, descriptor_format)
1320 elif descriptor:
1321 pass
1322 elif kwargs:
1323 descriptor = {"scenario": {}}
1324 else:
1325 raise ROClientException("Missing descriptor")
1326
1327 if "scenario" not in descriptor or len(descriptor) > 2:
1328 raise ROClientException("Descriptor must contain only one 'scenario' field")
1329 for param in kwargs:
1330 if param == "new_name":
1331 descriptor["scenario"]["name"] = kwargs[param]
1332 else:
1333 descriptor["scenario"][param] = kwargs[param]
1334 return self._edit_item("scenarios", descriptor, uuid, name, all_tenants=None)
1335
1336 # VIM ACTIONS
1337 def vim_action(self, action, item, uuid=None, all_tenants=False, **kwargs):
1338 """Perform an action over a vim
1339 Params:
1340 action: can be 'list', 'get'/'show', 'delete' or 'create'
1341 item: can be 'tenants' or 'networks'
1342 uuid: uuid of the tenant/net to show or to delete. Ignore otherwise
1343 other parameters:
1344 datacenter_name, datacenter_id: datacenters to act on, if missing uses classes store datacenter
1345 descriptor, descriptor_format: descriptor needed on creation, can be a dict or a yaml/json str
1346 must be a dictionary or a json/yaml text.
1347 name: for created tenant/net Overwrite descriptor name if any
1348 description: tenant descriptor. Overwrite descriptor description if any
1349
1350 Return: Raises an exception on error
1351 Obtain a dictionary with format {'tenant':{new_tenant_info}}
1352 """
1353 session = None # TODO remove when changed to asyncio
1354 if item not in ("tenants", "networks", "images"):
1355 raise ROClientException(
1356 "Unknown value for item '{}', must be 'tenants', 'nets' or "
1357 "images".format(str(item))
1358 )
1359
1360 image_actions = ["list", "get", "show", "delete"]
1361 if item == "images" and action not in image_actions:
1362 raise ROClientException(
1363 "Only available actions for item '{}' are {}\n"
1364 "Requested action was '{}'".format(
1365 item, ", ".join(image_actions), action
1366 )
1367 )
1368 if all_tenants:
1369 tenant_text = "/any"
1370 else:
1371 tenant_text = "/" + self._get_tenant(session)
1372
1373 if "datacenter_id" in kwargs or "datacenter_name" in kwargs:
1374 datacenter = self._get_item_uuid(
1375 session,
1376 "datacenters",
1377 kwargs.get("datacenter"),
1378 all_tenants=all_tenants,
1379 )
1380 else:
1381 datacenter = self._get_datacenter(session)
1382
1383 if action == "list":
1384 url = "{}{}/vim/{}/{}".format(self.uri, tenant_text, datacenter, item)
1385 self.logger.debug("GET %s", url)
1386 mano_response = requests.get(url, headers=self.headers_req)
1387 self.logger.debug("RO response: %s", mano_response.text)
1388 content = self._parse_yaml(mano_response.text, response=True)
1389 if mano_response.status_code == 200:
1390 return content
1391 else:
1392 raise ROClientException(str(content), http_code=mano_response.status)
1393 elif action == "get" or action == "show":
1394 url = "{}{}/vim/{}/{}/{}".format(
1395 self.uri, tenant_text, datacenter, item, uuid
1396 )
1397 self.logger.debug("GET %s", url)
1398 mano_response = requests.get(url, headers=self.headers_req)
1399 self.logger.debug("RO response: %s", mano_response.text)
1400 content = self._parse_yaml(mano_response.text, response=True)
1401 if mano_response.status_code == 200:
1402 return content
1403 else:
1404 raise ROClientException(str(content), http_code=mano_response.status)
1405 elif action == "delete":
1406 url = "{}{}/vim/{}/{}/{}".format(
1407 self.uri, tenant_text, datacenter, item, uuid
1408 )
1409 self.logger.debug("DELETE %s", url)
1410 mano_response = requests.delete(url, headers=self.headers_req)
1411 self.logger.debug("RO response: %s", mano_response.text)
1412 content = self._parse_yaml(mano_response.text, response=True)
1413 if mano_response.status_code == 200:
1414 return content
1415 else:
1416 raise ROClientException(str(content), http_code=mano_response.status)
1417 elif action == "create":
1418 if "descriptor" in kwargs:
1419 if isinstance(kwargs["descriptor"], str):
1420 descriptor = self._parse(
1421 kwargs["descriptor"], kwargs.get("descriptor_format")
1422 )
1423 else:
1424 descriptor = kwargs["descriptor"]
1425 elif "name" in kwargs:
1426 descriptor = {item[:-1]: {"name": kwargs["name"]}}
1427 else:
1428 raise ROClientException("Missing descriptor")
1429
1430 if item[:-1] not in descriptor or len(descriptor) != 1:
1431 raise ROClientException(
1432 "Descriptor must contain only one 'tenant' field"
1433 )
1434 if "name" in kwargs:
1435 descriptor[item[:-1]]["name"] = kwargs["name"]
1436 if "description" in kwargs:
1437 descriptor[item[:-1]]["description"] = kwargs["description"]
1438 payload_req = yaml.safe_dump(descriptor)
1439 # print payload_req
1440 url = "{}{}/vim/{}/{}".format(self.uri, tenant_text, datacenter, item)
1441 self.logger.debug("RO POST %s %s", url, payload_req)
1442 mano_response = requests.post(
1443 url, headers=self.headers_req, data=payload_req
1444 )
1445 self.logger.debug("RO response: %s", mano_response.text)
1446 content = self._parse_yaml(mano_response.text, response=True)
1447 if mano_response.status_code == 200:
1448 return content
1449 else:
1450 raise ROClientException(str(content), http_code=mano_response.status)
1451 else:
1452 raise ROClientException("Unknown value for action '{}".format(str(action)))