blob: 8570d524ba6b70a328d5a5ad2bf625f8615527f6 [file] [log] [blame]
tierno69f0d382020-05-07 13:08:09 +00001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4##
5# Copyright 2020 Telefónica Investigación y Desarrollo, S.A.U.
6#
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#
19##
20
21"""
22asyncio RO python client to interact with New Generation RO server
23"""
24
25import asyncio
26import aiohttp
27import yaml
28import logging
29
30__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com"
31__date__ = "$09-Jan-2018 09:09:48$"
32__version__ = "0.1.2"
33version_date = "2020-05-08"
34
35
36class NgRoException(Exception):
37 def __init__(self, message, http_code=400):
38 """Common Exception for all RO client exceptions"""
39 self.http_code = http_code
40 Exception.__init__(self, message)
41
42
43class NgRoClient:
garciadeblas5697b8b2021-03-24 09:17:02 +010044 headers_req = {"Accept": "application/yaml", "content-type": "application/yaml"}
45 client_to_RO = {
46 "tenant": "tenants",
47 "vim": "datacenters",
48 "vim_account": "datacenters",
49 "sdn": "sdn_controllers",
50 "vnfd": "vnfs",
51 "nsd": "scenarios",
52 "wim": "wims",
53 "wim_account": "wims",
54 "ns": "instances",
55 }
tierno69f0d382020-05-07 13:08:09 +000056 mandatory_for_create = {
garciadeblas5697b8b2021-03-24 09:17:02 +010057 "tenant": ("name",),
58 "vnfd": ("name", "id"),
59 "nsd": ("name", "id"),
60 "ns": ("name", "scenario", "datacenter"),
61 "vim": ("name", "vim_url"),
62 "wim": ("name", "wim_url"),
63 "vim_account": (),
64 "wim_account": (),
65 "sdn": ("name", "type"),
tierno69f0d382020-05-07 13:08:09 +000066 }
67 timeout_large = 120
68 timeout_short = 30
69
Gabriel Cubae7898982023-05-11 01:57:21 -050070 def __init__(self, uri, **kwargs):
tierno69f0d382020-05-07 13:08:09 +000071 self.endpoint_url = uri
72 if not self.endpoint_url.endswith("/"):
73 self.endpoint_url += "/"
74 if not self.endpoint_url.startswith("http"):
75 self.endpoint_url = "http://" + self.endpoint_url
76
77 self.username = kwargs.get("username")
78 self.password = kwargs.get("password")
79 self.tenant_id_name = kwargs.get("tenant")
80 self.tenant = None
81 self.datacenter_id_name = kwargs.get("datacenter")
82 self.datacenter = None
garciadeblas5697b8b2021-03-24 09:17:02 +010083 logger_name = kwargs.get("logger_name", "lcm.ro")
tierno69f0d382020-05-07 13:08:09 +000084 self.logger = logging.getLogger(logger_name)
85 if kwargs.get("loglevel"):
86 self.logger.setLevel(kwargs["loglevel"])
87
88 async def deploy(self, nsr_id, target):
89 """
90 Performs an action over an item
91 :param item: can be 'tenant', 'vnfd', 'nsd', 'ns', 'vim', 'vim_account', 'sdn'
92 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
93 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
94 :param descriptor_format: Can be 'json' or 'yaml'
95 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
96 keys can be a dot separated list to specify elements inside dict
97 :return: dictionary with the information or raises NgRoException on Error
98 """
99 try:
100 if isinstance(target, str):
101 target = self._parse_yaml(target)
102 payload_req = yaml.safe_dump(target)
103
104 url = "{}/ns/v1/deploy/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
Gabriel Cubae7898982023-05-11 01:57:21 -0500105 async with aiohttp.ClientSession() as session:
tierno69f0d382020-05-07 13:08:09 +0000106 self.logger.debug("NG-RO POST %s %s", url, payload_req)
107 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
garciadeblas5697b8b2021-03-24 09:17:02 +0100108 async with session.post(
109 url, headers=self.headers_req, data=payload_req
110 ) as response:
tierno69f0d382020-05-07 13:08:09 +0000111 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100112 self.logger.debug(
113 "POST {} [{}] {}".format(
114 url, response.status, response_text[:100]
115 )
116 )
tierno69f0d382020-05-07 13:08:09 +0000117 if response.status >= 300:
118 raise NgRoException(response_text, http_code=response.status)
119 return self._parse_yaml(response_text, response=True)
120 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
121 raise NgRoException(e, http_code=504)
122 except asyncio.TimeoutError:
123 raise NgRoException("Timeout", http_code=504)
124
elumalai80bcf1c2022-04-28 18:05:01 +0530125 async def migrate(self, nsr_id, target):
126 """
127 Performs migration of VNFs
128 :param nsr_id: NS Instance Id
129 :param target: payload data for migrate operation
130 :return: dictionary with the information or raises NgRoException on Error
131 """
132 try:
133 if isinstance(target, str):
134 target = self._parse_yaml(target)
135 payload_req = yaml.safe_dump(target)
136
137 url = "{}/ns/v1/migrate/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
Gabriel Cubae7898982023-05-11 01:57:21 -0500138 async with aiohttp.ClientSession() as session:
elumalai80bcf1c2022-04-28 18:05:01 +0530139 self.logger.debug("NG-RO POST %s %s", url, payload_req)
140 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
141 async with session.post(
142 url, headers=self.headers_req, data=payload_req
143 ) as response:
144 response_text = await response.read()
145 self.logger.debug(
146 "POST {} [{}] {}".format(
147 url, response.status, response_text[:100]
148 )
149 )
150 if response.status >= 300:
151 raise NgRoException(response_text, http_code=response.status)
152 return self._parse_yaml(response_text, response=True)
153 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
154 raise NgRoException(e, http_code=504)
155 except asyncio.TimeoutError:
156 raise NgRoException("Timeout", http_code=504)
157
k4.rahulb827de92022-05-02 16:35:02 +0000158 async def operate(self, nsr_id, target, operation_type):
159 """
160 Performs start/stop/rebuil of VNFs
161 :param nsr_id: NS Instance Id
162 :param target: payload data for migrate operation
163 :param operation_type: start/stop/rebuil of VNFs
164 :return: dictionary with the information or raises NgRoException on Error
165 """
166 try:
167 if isinstance(target, str):
168 target = self._parse_yaml(target)
169 payload_req = yaml.safe_dump(target)
170
171 url = "{}/ns/v1/{operation_type}/{nsr_id}".format(
172 self.endpoint_url, operation_type=operation_type, nsr_id=nsr_id
173 )
Gabriel Cubae7898982023-05-11 01:57:21 -0500174 async with aiohttp.ClientSession() as session:
k4.rahulb827de92022-05-02 16:35:02 +0000175 self.logger.debug("NG-RO POST %s %s", url, payload_req)
176 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
177 async with session.post(
178 url, headers=self.headers_req, data=payload_req
179 ) as response:
180 response_text = await response.read()
181 self.logger.debug(
182 "POST {} [{}] {}".format(
183 url, response.status, response_text[:100]
184 )
185 )
186 if response.status >= 300:
187 raise NgRoException(response_text, http_code=response.status)
188 return self._parse_yaml(response_text, response=True)
189 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
190 raise NgRoException(e, http_code=504)
191 except asyncio.TimeoutError:
192 raise NgRoException("Timeout", http_code=504)
193
tierno69f0d382020-05-07 13:08:09 +0000194 async def status(self, nsr_id, action_id):
195 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100196 url = "{}/ns/v1/deploy/{nsr_id}/{action_id}".format(
197 self.endpoint_url, nsr_id=nsr_id, action_id=action_id
198 )
Gabriel Cubae7898982023-05-11 01:57:21 -0500199 async with aiohttp.ClientSession() as session:
tierno69f0d382020-05-07 13:08:09 +0000200 self.logger.debug("GET %s", url)
201 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
202 async with session.get(url, headers=self.headers_req) as response:
203 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100204 self.logger.debug(
205 "GET {} [{}] {}".format(
206 url, response.status, response_text[:100]
207 )
208 )
Isabel Lloret23aea8e2025-04-25 11:27:11 +0200209 self.logger.debug("Get response text: %s", response_text)
210 if response.status >= 300:
211 raise NgRoException(response_text, http_code=response.status)
212 return self._parse_yaml(response_text, response=True)
213
214 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
215 raise NgRoException(e, http_code=504)
216 except asyncio.TimeoutError:
217 raise NgRoException("Timeout", http_code=504)
218
219 async def get_action_vim_info(self, nsr_id, action_id):
220 try:
221 url = "{}/ns/v1/deploy/{nsr_id}/{action_id}/viminfo".format(
222 self.endpoint_url, nsr_id=nsr_id, action_id=action_id
223 )
224 async with aiohttp.ClientSession() as session:
225 self.logger.debug("GET %s", url)
226 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
227 async with session.get(url, headers=self.headers_req) as response:
228 response_text = await response.read()
229 self.logger.debug(
230 "GET {} [{}] {}".format(
231 url, response.status, response_text[:100]
232 )
233 )
234 self.logger.debug("Get response text: %s", response_text)
tierno69f0d382020-05-07 13:08:09 +0000235 if response.status >= 300:
236 raise NgRoException(response_text, http_code=response.status)
237 return self._parse_yaml(response_text, response=True)
238
239 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
240 raise NgRoException(e, http_code=504)
241 except asyncio.TimeoutError:
242 raise NgRoException("Timeout", http_code=504)
243
244 async def delete(self, nsr_id):
245 try:
246 url = "{}/ns/v1/deploy/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
Gabriel Cubae7898982023-05-11 01:57:21 -0500247 async with aiohttp.ClientSession() as session:
tierno69f0d382020-05-07 13:08:09 +0000248 self.logger.debug("DELETE %s", url)
249 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
250 async with session.delete(url, headers=self.headers_req) as response:
251 self.logger.debug("DELETE {} [{}]".format(url, response.status))
252 if response.status >= 300:
garciadeblas5697b8b2021-03-24 09:17:02 +0100253 raise NgRoException(
254 "Delete {}".format(nsr_id), http_code=response.status
255 )
tierno69f0d382020-05-07 13:08:09 +0000256 return
257
258 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
259 raise NgRoException(e, http_code=504)
260 except asyncio.TimeoutError:
261 raise NgRoException("Timeout", http_code=504)
262
263 async def get_version(self):
264 """
265 Obtain RO server version.
266 :return: a list with integers ["major", "minor", "release"]. Raises NgRoException on Error,
267 """
268 try:
269 response_text = ""
Gabriel Cubae7898982023-05-11 01:57:21 -0500270 async with aiohttp.ClientSession() as session:
tierno69f0d382020-05-07 13:08:09 +0000271 url = "{}/version".format(self.endpoint_url)
272 self.logger.debug("RO GET %s", url)
273 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
274 async with session.get(url, headers=self.headers_req) as response:
275 response_text = await response.read()
garciadeblas5697b8b2021-03-24 09:17:02 +0100276 self.logger.debug(
277 "GET {} [{}] {}".format(
278 url, response.status, response_text[:100]
279 )
280 )
tierno69f0d382020-05-07 13:08:09 +0000281 if response.status >= 300:
282 raise NgRoException(response_text, http_code=response.status)
283
284 for word in str(response_text).split(" "):
285 if "." in word:
286 version_text, _, _ = word.partition("-")
287 return version_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100288 raise NgRoException(
289 "Got invalid version text: '{}'".format(response_text),
290 http_code=500,
291 )
tierno69f0d382020-05-07 13:08:09 +0000292 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
293 raise NgRoException(e, http_code=504)
294 except asyncio.TimeoutError:
295 raise NgRoException("Timeout", http_code=504)
296 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100297 raise NgRoException(
298 "Got invalid version text: '{}'; causing exception {}".format(
299 response_text, e
300 ),
301 http_code=500,
302 )
tierno69f0d382020-05-07 13:08:09 +0000303
garciadeblas07f4e4c2022-06-09 09:42:58 +0200304 async def recreate(self, nsr_id, target):
305 """
306 Performs an action over an item
307 :param item: can be 'tenant', 'vnfd', 'nsd', 'ns', 'vim', 'vim_account', 'sdn'
308 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
309 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
310 :param descriptor_format: Can be 'json' or 'yaml'
311 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
312 keys can be a dot separated list to specify elements inside dict
313 :return: dictionary with the information or raises NgRoException on Error
314 """
315 try:
316 if isinstance(target, str):
317 target = self._parse_yaml(target)
318 payload_req = yaml.safe_dump(target)
319
320 url = "{}/ns/v1/recreate/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
Gabriel Cubae7898982023-05-11 01:57:21 -0500321 async with aiohttp.ClientSession() as session:
garciadeblas07f4e4c2022-06-09 09:42:58 +0200322 self.logger.debug("NG-RO POST %s %s", url, payload_req)
323 async with session.post(
324 url, headers=self.headers_req, data=payload_req
325 ) as response:
326 response_text = await response.read()
327 self.logger.debug(
328 "POST {} [{}] {}".format(
329 url, response.status, response_text[:100]
330 )
331 )
332 if response.status >= 300:
333 raise NgRoException(response_text, http_code=response.status)
334 return self._parse_yaml(response_text, response=True)
335 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
336 raise NgRoException(e, http_code=504)
337 except asyncio.TimeoutError:
338 raise NgRoException("Timeout", http_code=504)
339
340 async def recreate_status(self, nsr_id, action_id):
341 try:
342 url = "{}/ns/v1/recreate/{nsr_id}/{action_id}".format(
343 self.endpoint_url, nsr_id=nsr_id, action_id=action_id
344 )
Gabriel Cubae7898982023-05-11 01:57:21 -0500345 async with aiohttp.ClientSession() as session:
garciadeblas07f4e4c2022-06-09 09:42:58 +0200346 self.logger.debug("GET %s", url)
347 async with session.get(url, headers=self.headers_req) as response:
348 response_text = await response.read()
349 self.logger.debug(
350 "GET {} [{}] {}".format(
351 url, response.status, response_text[:100]
352 )
353 )
354 if response.status >= 300:
355 raise NgRoException(response_text, http_code=response.status)
356 return self._parse_yaml(response_text, response=True)
357
358 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
359 raise NgRoException(e, http_code=504)
360 except asyncio.TimeoutError:
361 raise NgRoException("Timeout", http_code=504)
362
govindarajul4ff4b512022-05-02 20:02:41 +0530363 async def vertical_scale(self, nsr_id, target):
364 """
365 Performs migration of VNFs
366 :param nsr_id: NS Instance Id
367 :param target: payload data for migrate operation
368 :return: dictionary with the information or raises NgRoException on Error
369 """
370 try:
371 if isinstance(target, str):
372 target = self._parse_yaml(target)
373 payload_req = yaml.safe_dump(target)
374
preethika.p28b0bf82022-09-23 07:36:28 +0000375 url = "{}/ns/v1/verticalscale/{nsr_id}".format(
376 self.endpoint_url, nsr_id=nsr_id
377 )
Gabriel Cubae7898982023-05-11 01:57:21 -0500378 async with aiohttp.ClientSession() as session:
govindarajul4ff4b512022-05-02 20:02:41 +0530379 self.logger.debug("NG-RO POST %s %s", url, payload_req)
380 async with session.post(
381 url, headers=self.headers_req, data=payload_req
382 ) as response:
383 response_text = await response.read()
384 self.logger.debug(
385 "POST {} [{}] {}".format(
386 url, response.status, response_text[:100]
387 )
388 )
389 if response.status >= 300:
390 raise NgRoException(response_text, http_code=response.status)
391 return self._parse_yaml(response_text, response=True)
392 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
393 raise NgRoException(e, http_code=504)
394 except asyncio.TimeoutError:
395 raise NgRoException("Timeout", http_code=504)
396
tierno69f0d382020-05-07 13:08:09 +0000397 @staticmethod
398 def _parse_yaml(descriptor, response=False):
399 try:
400 return yaml.safe_load(descriptor)
401 except yaml.YAMLError as exc:
402 error_pos = ""
garciadeblas5697b8b2021-03-24 09:17:02 +0100403 if hasattr(exc, "problem_mark"):
tierno69f0d382020-05-07 13:08:09 +0000404 mark = exc.problem_mark
garciadeblas5697b8b2021-03-24 09:17:02 +0100405 error_pos = " at line:{} column:{}s".format(
406 mark.line + 1, mark.column + 1
407 )
tierno69f0d382020-05-07 13:08:09 +0000408 error_text = "yaml format error" + error_pos
409 if response:
410 raise NgRoException("reponse with " + error_text)
411 raise NgRoException(error_text)