0acccc4a97cd95d0afc8136992c9f44ee40c5b62
[osm/LCM.git] / osm_lcm / ng_ro.py
1 #!/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 """
22 asyncio RO python client to interact with New Generation RO server
23 """
24
25 import asyncio
26 import aiohttp
27 import yaml
28 import logging
29
30 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com"
31 __date__ = "$09-Jan-2018 09:09:48$"
32 __version__ = "0.1.2"
33 version_date = "2020-05-08"
34
35
36 class 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
43 class NgRoClient:
44 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 }
56 mandatory_for_create = {
57 "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"),
66 }
67 timeout_large = 120
68 timeout_short = 30
69
70 def __init__(self, loop, uri, **kwargs):
71 self.loop = loop
72 self.endpoint_url = uri
73 if not self.endpoint_url.endswith("/"):
74 self.endpoint_url += "/"
75 if not self.endpoint_url.startswith("http"):
76 self.endpoint_url = "http://" + self.endpoint_url
77
78 self.username = kwargs.get("username")
79 self.password = kwargs.get("password")
80 self.tenant_id_name = kwargs.get("tenant")
81 self.tenant = None
82 self.datacenter_id_name = kwargs.get("datacenter")
83 self.datacenter = None
84 logger_name = kwargs.get("logger_name", "lcm.ro")
85 self.logger = logging.getLogger(logger_name)
86 if kwargs.get("loglevel"):
87 self.logger.setLevel(kwargs["loglevel"])
88
89 async def deploy(self, nsr_id, target):
90 """
91 Performs an action over an item
92 :param item: can be 'tenant', 'vnfd', 'nsd', 'ns', 'vim', 'vim_account', 'sdn'
93 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
94 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
95 :param descriptor_format: Can be 'json' or 'yaml'
96 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
97 keys can be a dot separated list to specify elements inside dict
98 :return: dictionary with the information or raises NgRoException on Error
99 """
100 try:
101 if isinstance(target, str):
102 target = self._parse_yaml(target)
103 payload_req = yaml.safe_dump(target)
104
105 url = "{}/ns/v1/deploy/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
106 async with aiohttp.ClientSession(loop=self.loop) as session:
107 self.logger.debug("NG-RO POST %s %s", url, payload_req)
108 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
109 async with session.post(
110 url, headers=self.headers_req, data=payload_req
111 ) as response:
112 response_text = await response.read()
113 self.logger.debug(
114 "POST {} [{}] {}".format(
115 url, response.status, response_text[:100]
116 )
117 )
118 if response.status >= 300:
119 raise NgRoException(response_text, http_code=response.status)
120 return self._parse_yaml(response_text, response=True)
121 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
122 raise NgRoException(e, http_code=504)
123 except asyncio.TimeoutError:
124 raise NgRoException("Timeout", http_code=504)
125
126 async def migrate(self, nsr_id, target):
127 """
128 Performs migration of VNFs
129 :param nsr_id: NS Instance Id
130 :param target: payload data for migrate operation
131 :return: dictionary with the information or raises NgRoException on Error
132 """
133 try:
134 if isinstance(target, str):
135 target = self._parse_yaml(target)
136 payload_req = yaml.safe_dump(target)
137
138 url = "{}/ns/v1/migrate/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
139 async with aiohttp.ClientSession(loop=self.loop) as session:
140 self.logger.debug("NG-RO POST %s %s", url, payload_req)
141 # timeout = aiohttp.ClientTimeout(total=self.timeout_large)
142 async with session.post(
143 url, headers=self.headers_req, data=payload_req
144 ) as response:
145 response_text = await response.read()
146 self.logger.debug(
147 "POST {} [{}] {}".format(
148 url, response.status, response_text[:100]
149 )
150 )
151 if response.status >= 300:
152 raise NgRoException(response_text, http_code=response.status)
153 return self._parse_yaml(response_text, response=True)
154 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
155 raise NgRoException(e, http_code=504)
156 except asyncio.TimeoutError:
157 raise NgRoException("Timeout", http_code=504)
158
159 async def status(self, nsr_id, action_id):
160 try:
161 url = "{}/ns/v1/deploy/{nsr_id}/{action_id}".format(
162 self.endpoint_url, nsr_id=nsr_id, action_id=action_id
163 )
164 async with aiohttp.ClientSession(loop=self.loop) as session:
165 self.logger.debug("GET %s", url)
166 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
167 async with session.get(url, headers=self.headers_req) as response:
168 response_text = await response.read()
169 self.logger.debug(
170 "GET {} [{}] {}".format(
171 url, response.status, response_text[:100]
172 )
173 )
174 if response.status >= 300:
175 raise NgRoException(response_text, http_code=response.status)
176 return self._parse_yaml(response_text, response=True)
177
178 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
179 raise NgRoException(e, http_code=504)
180 except asyncio.TimeoutError:
181 raise NgRoException("Timeout", http_code=504)
182
183 async def delete(self, nsr_id):
184 try:
185 url = "{}/ns/v1/deploy/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
186 async with aiohttp.ClientSession(loop=self.loop) as session:
187 self.logger.debug("DELETE %s", url)
188 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
189 async with session.delete(url, headers=self.headers_req) as response:
190 self.logger.debug("DELETE {} [{}]".format(url, response.status))
191 if response.status >= 300:
192 raise NgRoException(
193 "Delete {}".format(nsr_id), http_code=response.status
194 )
195 return
196
197 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
198 raise NgRoException(e, http_code=504)
199 except asyncio.TimeoutError:
200 raise NgRoException("Timeout", http_code=504)
201
202 async def get_version(self):
203 """
204 Obtain RO server version.
205 :return: a list with integers ["major", "minor", "release"]. Raises NgRoException on Error,
206 """
207 try:
208 response_text = ""
209 async with aiohttp.ClientSession(loop=self.loop) as session:
210 url = "{}/version".format(self.endpoint_url)
211 self.logger.debug("RO GET %s", url)
212 # timeout = aiohttp.ClientTimeout(total=self.timeout_short)
213 async with session.get(url, headers=self.headers_req) as response:
214 response_text = await response.read()
215 self.logger.debug(
216 "GET {} [{}] {}".format(
217 url, response.status, response_text[:100]
218 )
219 )
220 if response.status >= 300:
221 raise NgRoException(response_text, http_code=response.status)
222
223 for word in str(response_text).split(" "):
224 if "." in word:
225 version_text, _, _ = word.partition("-")
226 return version_text
227 raise NgRoException(
228 "Got invalid version text: '{}'".format(response_text),
229 http_code=500,
230 )
231 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
232 raise NgRoException(e, http_code=504)
233 except asyncio.TimeoutError:
234 raise NgRoException("Timeout", http_code=504)
235 except Exception as e:
236 raise NgRoException(
237 "Got invalid version text: '{}'; causing exception {}".format(
238 response_text, e
239 ),
240 http_code=500,
241 )
242
243 async def recreate(self, nsr_id, target):
244 """
245 Performs an action over an item
246 :param item: can be 'tenant', 'vnfd', 'nsd', 'ns', 'vim', 'vim_account', 'sdn'
247 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
248 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
249 :param descriptor_format: Can be 'json' or 'yaml'
250 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
251 keys can be a dot separated list to specify elements inside dict
252 :return: dictionary with the information or raises NgRoException on Error
253 """
254 try:
255 if isinstance(target, str):
256 target = self._parse_yaml(target)
257 payload_req = yaml.safe_dump(target)
258
259 url = "{}/ns/v1/recreate/{nsr_id}".format(self.endpoint_url, nsr_id=nsr_id)
260 async with aiohttp.ClientSession(loop=self.loop) as session:
261 self.logger.debug("NG-RO POST %s %s", url, payload_req)
262 async with session.post(
263 url, headers=self.headers_req, data=payload_req
264 ) as response:
265 response_text = await response.read()
266 self.logger.debug(
267 "POST {} [{}] {}".format(
268 url, response.status, response_text[:100]
269 )
270 )
271 if response.status >= 300:
272 raise NgRoException(response_text, http_code=response.status)
273 return self._parse_yaml(response_text, response=True)
274 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
275 raise NgRoException(e, http_code=504)
276 except asyncio.TimeoutError:
277 raise NgRoException("Timeout", http_code=504)
278
279 async def recreate_status(self, nsr_id, action_id):
280 try:
281 url = "{}/ns/v1/recreate/{nsr_id}/{action_id}".format(
282 self.endpoint_url, nsr_id=nsr_id, action_id=action_id
283 )
284 async with aiohttp.ClientSession(loop=self.loop) as session:
285 self.logger.debug("GET %s", url)
286 async with session.get(url, headers=self.headers_req) as response:
287 response_text = await response.read()
288 self.logger.debug(
289 "GET {} [{}] {}".format(
290 url, response.status, response_text[:100]
291 )
292 )
293 if response.status >= 300:
294 raise NgRoException(response_text, http_code=response.status)
295 return self._parse_yaml(response_text, response=True)
296
297 except (aiohttp.ClientOSError, aiohttp.ClientError) as e:
298 raise NgRoException(e, http_code=504)
299 except asyncio.TimeoutError:
300 raise NgRoException("Timeout", http_code=504)
301
302 @staticmethod
303 def _parse_yaml(descriptor, response=False):
304 try:
305 return yaml.safe_load(descriptor)
306 except yaml.YAMLError as exc:
307 error_pos = ""
308 if hasattr(exc, "problem_mark"):
309 mark = exc.problem_mark
310 error_pos = " at line:{} column:{}s".format(
311 mark.line + 1, mark.column + 1
312 )
313 error_text = "yaml format error" + error_pos
314 if response:
315 raise NgRoException("reponse with " + error_text)
316 raise NgRoException(error_text)