Code Coverage

Cobertura Coverage Report > osmclient.sol005 >

ns.py

Trend

Classes0%
 
Lines0%
 
Conditionals100%
 

File Coverage summary

NameClassesLinesConditionals
ns.py
0%
0/1
0%
0/296
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
ns.py
0%
0/296
N/A

Source

osmclient/sol005/ns.py
1 # Copyright 2018 Telefonica
2 #
3 # All Rights Reserved.
4 #
5 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
6 #    not use this file except in compliance with the License. You may obtain
7 #    a copy of the License at
8 #
9 #         http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #    Unless required by applicable law or agreed to in writing, software
12 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 #    License for the specific language governing permissions and limitations
15 #    under the License.
16
17 0 """
18 OSM ns API handling
19 """
20
21 0 from osmclient.common import utils
22 0 from osmclient.common import wait as WaitForStatus
23 0 from osmclient.common.exceptions import ClientException
24 0 from osmclient.common.exceptions import NotFound
25 0 import yaml
26 0 import json
27 0 import logging
28
29
30 0 class Ns(object):
31
32 0     def __init__(self, http=None, client=None):
33 0         self._http = http
34 0         self._client = client
35 0         self._logger = logging.getLogger('osmclient')
36 0         self._apiName = '/nslcm'
37 0         self._apiVersion = '/v1'
38 0         self._apiResource = '/ns_instances_content'
39 0         self._apiBase = '{}{}{}'.format(self._apiName,
40                                         self._apiVersion, self._apiResource)
41
42     # NS '--wait' option
43 0     def _wait(self, id, wait_time, deleteFlag=False):
44 0         self._logger.debug("")
45         # Endpoint to get operation status
46 0         apiUrlStatus = '{}{}{}'.format(self._apiName, self._apiVersion, '/ns_lcm_op_occs')
47         # Wait for status for NS instance creation/update/deletion
48 0         if isinstance(wait_time, bool):
49 0             wait_time = WaitForStatus.TIMEOUT_NS_OPERATION
50 0         WaitForStatus.wait_for_status(
51             'NS',
52             str(id),
53             wait_time,
54             apiUrlStatus,
55             self._http.get2_cmd,
56             deleteFlag=deleteFlag)
57
58 0     def list(self, filter=None):
59         """Returns a list of NS
60         """
61 0         self._logger.debug("")
62 0         self._client.get_token()
63 0         filter_string = ''
64 0         if filter:
65 0             filter_string = '?{}'.format(filter)
66 0         _, resp = self._http.get2_cmd('{}{}'.format(self._apiBase,filter_string))
67 0         if resp:
68 0             return json.loads(resp)
69 0         return list()
70
71 0     def get(self, name):
72         """Returns an NS based on name or id
73         """
74 0         self._logger.debug("")
75 0         self._client.get_token()
76 0         if utils.validate_uuid4(name):
77 0             for ns in self.list():
78 0                 if name == ns['_id']:
79 0                     return ns
80         else:
81 0             for ns in self.list():
82 0                 if name == ns['name']:
83 0                     return ns
84 0         raise NotFound("ns '{}' not found".format(name))
85
86 0     def get_individual(self, name):
87 0         self._logger.debug("")
88 0         self._client.get_token()
89 0         ns_id = name
90 0         if not utils.validate_uuid4(name):
91 0             for ns in self.list():
92 0                 if name == ns['name']:
93 0                     ns_id = ns['_id']
94 0                     break
95 0         try:
96 0             _, resp = self._http.get2_cmd('{}/{}'.format(self._apiBase, ns_id))
97             #resp = self._http.get_cmd('{}/{}/nsd_content'.format(self._apiBase, ns_id))
98             #print(yaml.safe_dump(resp))
99 0             if resp:
100 0                 return json.loads(resp)
101 0         except NotFound:
102 0             raise NotFound("ns '{}' not found".format(name))
103 0         raise NotFound("ns '{}' not found".format(name))
104
105 0     def delete(self, name, force=False, config=None, wait=False):
106         """
107         Deletes a Network Service (NS)
108         :param name: name of network service
109         :param force: set force. Direct deletion without cleaning at VIM
110         :param config: parameters of deletion, as:
111              autoremove: Bool (default True)
112              timeout_ns_terminate: int
113              skip_terminate_primitives: Bool (default False) to not exec the terminate primitives
114         :param wait: Make synchronous. Wait until deletion is completed:
115             False to not wait (by default), True to wait a standard time, or int (time to wait)
116         :return: None. Exception if fail
117         """
118 0         self._logger.debug("")
119 0         ns = self.get(name)
120 0         querystring_list = []
121 0         querystring = ''
122 0         if config:
123 0             ns_config = yaml.safe_load(config)
124 0             querystring_list += ["{}={}".format(k, v) for k, v in ns_config.items()]
125 0         if force:
126 0             querystring_list.append('FORCE=True')
127 0         if querystring_list:
128 0             querystring = "?" + "&".join(querystring_list)
129 0         http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
130                                                  ns['_id'], querystring))
131         # TODO change to use a POST self._http.post_cmd('{}/{}/terminate{}'.format(_apiBase, ns['_id'], querystring),
132         #                                               postfields_dict=ns_config)
133         # seting autoremove as True by default
134         # print('HTTP CODE: {}'.format(http_code))
135         # print('RESP: {}'.format(resp))
136 0         if http_code == 202:
137 0             if wait and resp:
138 0                 resp = json.loads(resp)
139                 # For the 'delete' operation, '_id' is used
140 0                 self._wait(resp.get('_id'), wait, deleteFlag=True)
141             else:
142 0                 print('Deletion in progress')
143 0         elif http_code == 204:
144 0             print('Deleted')
145         else:
146 0             msg = resp or ""
147             # if resp:
148             #     try:
149             #         msg = json.loads(resp)
150             #     except ValueError:
151             #         msg = resp
152 0             raise ClientException("failed to delete ns {} - {}".format(name, msg))
153
154 0     def create(self, nsd_name, nsr_name, account, config=None,
155                ssh_keys=None, description='default description',
156                admin_status='ENABLED', wait=False):
157 0         self._logger.debug("")
158 0         self._client.get_token()
159 0         nsd = self._client.nsd.get(nsd_name)
160
161 0         vim_account_id = {}
162 0         wim_account_id = {}
163
164 0         def get_vim_account_id(vim_account):
165 0             self._logger.debug("")
166 0             if vim_account_id.get(vim_account):
167 0                 return vim_account_id[vim_account]
168 0             vim = self._client.vim.get(vim_account)
169 0             if vim is None:
170 0                 raise NotFound("cannot find vim account '{}'".format(vim_account))
171 0             vim_account_id[vim_account] = vim['_id']
172 0             return vim['_id']
173
174 0         def get_wim_account_id(wim_account):
175 0             self._logger.debug("")
176             # wim_account can be False (boolean) to indicate not use wim account
177 0             if not isinstance(wim_account, str):
178 0                 return wim_account
179 0             if wim_account_id.get(wim_account):
180 0                 return wim_account_id[wim_account]
181 0             wim = self._client.wim.get(wim_account)
182 0             if wim is None:
183 0                 raise NotFound("cannot find wim account '{}'".format(wim_account))
184 0             wim_account_id[wim_account] = wim['_id']
185 0             return wim['_id']
186
187 0         ns = {}
188 0         ns['nsdId'] = nsd['_id']
189 0         ns['nsName'] = nsr_name
190 0         ns['nsDescription'] = description
191 0         ns['vimAccountId'] = get_vim_account_id(account)
192         #ns['userdata'] = {}
193         #ns['userdata']['key1']='value1'
194         #ns['userdata']['key2']='value2'
195
196 0         if ssh_keys is not None:
197 0             ns['ssh_keys'] = []
198 0             for pubkeyfile in ssh_keys.split(','):
199 0                 with open(pubkeyfile, 'r') as f:
200 0                     ns['ssh_keys'].append(f.read())
201 0         if config:
202 0             ns_config = yaml.safe_load(config)
203 0             if "vim-network-name" in ns_config:
204 0                 ns_config["vld"] = ns_config.pop("vim-network-name")
205 0             if "vld" in ns_config:
206 0                 if not isinstance(ns_config["vld"], list):
207 0                     raise ClientException("Error at --config 'vld' must be a list of dictionaries")
208 0                 for vld in ns_config["vld"]:
209 0                     if not isinstance(vld, dict):
210 0                         raise ClientException("Error at --config 'vld' must be a list of dictionaries")
211 0                     if vld.get("vim-network-name"):
212 0                         if isinstance(vld["vim-network-name"], dict):
213 0                             vim_network_name_dict = {}
214 0                             for vim_account, vim_net in vld["vim-network-name"].items():
215 0                                 vim_network_name_dict[get_vim_account_id(vim_account)] = vim_net
216 0                             vld["vim-network-name"] = vim_network_name_dict
217 0                     if "wim_account" in vld and vld["wim_account"] is not None:
218 0                         vld["wimAccountId"] = get_wim_account_id(vld.pop("wim_account"))
219 0             if "vnf" in ns_config:
220 0                 for vnf in ns_config["vnf"]:
221 0                     if vnf.get("vim_account"):
222 0                         vnf["vimAccountId"] = get_vim_account_id(vnf.pop("vim_account"))
223
224 0             if "additionalParamsForNs" in ns_config:
225 0                 if not isinstance(ns_config["additionalParamsForNs"], dict):
226 0                     raise ClientException("Error at --config 'additionalParamsForNs' must be a dictionary")
227 0             if "additionalParamsForVnf" in ns_config:
228 0                 if not isinstance(ns_config["additionalParamsForVnf"], list):
229 0                     raise ClientException("Error at --config 'additionalParamsForVnf' must be a list")
230 0                 for additional_param_vnf in ns_config["additionalParamsForVnf"]:
231 0                     if not isinstance(additional_param_vnf, dict):
232 0                         raise ClientException("Error at --config 'additionalParamsForVnf' items must be dictionaries")
233 0                     if not additional_param_vnf.get("member-vnf-index"):
234 0                         raise ClientException("Error at --config 'additionalParamsForVnf' items must contain "
235                                          "'member-vnf-index'")
236 0             if "wim_account" in ns_config:
237 0                 wim_account = ns_config.pop("wim_account")
238 0                 if wim_account is not None:
239 0                     ns['wimAccountId'] = get_wim_account_id(wim_account)
240             # rest of parameters without any transformation or checking
241             # "timeout_ns_deploy"
242             # "placement-engine"
243 0             ns.update(ns_config)
244
245         # print(yaml.safe_dump(ns))
246 0         try:
247 0             self._apiResource = '/ns_instances_content'
248 0             self._apiBase = '{}{}{}'.format(self._apiName,
249                                             self._apiVersion, self._apiResource)
250 0             headers = self._client._headers
251 0             headers['Content-Type'] = 'application/yaml'
252 0             http_header = ['{}: {}'.format(key,val)
253                           for (key,val) in list(headers.items())]
254 0             self._http.set_http_header(http_header)
255 0             http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
256                                    postfields_dict=ns)
257             # print('HTTP CODE: {}'.format(http_code))
258             # print('RESP: {}'.format(resp))
259             #if http_code in (200, 201, 202, 204):
260 0             if resp:
261 0                 resp = json.loads(resp)
262 0             if not resp or 'id' not in resp:
263 0                 raise ClientException('unexpected response from server - {} '.format(
264                                       resp))
265 0             if wait:
266                 # Wait for status for NS instance creation
267 0                 self._wait(resp.get('nslcmop_id'), wait)
268 0             print(resp['id'])
269 0             return resp['id']
270             #else:
271             #    msg = ""
272             #    if resp:
273             #        try:
274             #            msg = json.loads(resp)
275             #        except ValueError:
276             #            msg = resp
277             #    raise ClientException(msg)
278 0         except ClientException as exc:
279 0             message="failed to create ns: {} nsd: {}\nerror:\n{}".format(
280                     nsr_name,
281                     nsd_name,
282                     str(exc))
283 0             raise ClientException(message)
284
285 0     def list_op(self, name, filter=None):
286         """Returns the list of operations of a NS
287         """
288 0         self._logger.debug("")
289 0         ns = self.get(name)
290 0         try:
291 0             self._apiResource = '/ns_lcm_op_occs'
292 0             self._apiBase = '{}{}{}'.format(self._apiName,
293                                       self._apiVersion, self._apiResource)
294 0             filter_string = ''
295 0             if filter:
296 0                  filter_string = '&{}'.format(filter)
297 0             http_code, resp = self._http.get2_cmd('{}?nsInstanceId={}{}'.format(
298                                                        self._apiBase, ns['_id'],
299                                                        filter_string) )
300             #print('HTTP CODE: {}'.format(http_code))
301             #print('RESP: {}'.format(resp))
302 0             if http_code == 200:
303 0                 if resp:
304 0                     resp = json.loads(resp)
305 0                     return resp
306                 else:
307 0                     raise ClientException('unexpected response from server')
308             else:
309 0                 msg = resp or ""
310             #    if resp:
311             #        try:
312             #            resp = json.loads(resp)
313             #            msg = resp['detail']
314             #        except ValueError:
315             #            msg = resp
316 0                 raise ClientException(msg)
317 0         except ClientException as exc:
318 0             message="failed to get operation list of NS {}:\nerror:\n{}".format(
319                     name,
320                     str(exc))
321 0             raise ClientException(message)
322
323 0     def get_op(self, operationId):
324         """Returns the status of an operation
325         """
326 0         self._logger.debug("")
327 0         self._client.get_token()
328 0         try:
329 0             self._apiResource = '/ns_lcm_op_occs'
330 0             self._apiBase = '{}{}{}'.format(self._apiName,
331                                       self._apiVersion, self._apiResource)
332 0             http_code, resp = self._http.get2_cmd('{}/{}'.format(self._apiBase, operationId))
333             #print('HTTP CODE: {}'.format(http_code))
334             #print('RESP: {}'.format(resp))
335 0             if http_code == 200:
336 0                 if resp:
337 0                     resp = json.loads(resp)
338 0                     return resp
339                 else:
340 0                     raise ClientException('unexpected response from server')
341             else:
342 0                 msg = resp or ""
343             #    if resp:
344             #        try:
345             #            resp = json.loads(resp)
346             #            msg = resp['detail']
347             #        except ValueError:
348             #            msg = resp
349 0                 raise ClientException(msg)
350 0         except ClientException as exc:
351 0             message="failed to get status of operation {}:\nerror:\n{}".format(
352                     operationId,
353                     str(exc))
354 0             raise ClientException(message)
355
356 0     def exec_op(self, name, op_name, op_data=None, wait=False, ):
357         """Executes an operation on a NS
358         """
359 0         self._logger.debug("")
360 0         ns = self.get(name)
361 0         try:
362 0             ns = self.get(name)
363 0             self._apiResource = '/ns_instances'
364 0             self._apiBase = '{}{}{}'.format(self._apiName,
365                                             self._apiVersion, self._apiResource)
366 0             endpoint = '{}/{}/{}'.format(self._apiBase, ns['_id'], op_name)
367             #print('OP_NAME: {}'.format(op_name))
368             #print('OP_DATA: {}'.format(json.dumps(op_data)))
369 0             http_code, resp = self._http.post_cmd(endpoint=endpoint, postfields_dict=op_data)
370             #print('HTTP CODE: {}'.format(http_code))
371             #print('RESP: {}'.format(resp))
372             #if http_code in (200, 201, 202, 204):
373 0             if resp:
374 0                 resp = json.loads(resp)
375 0             if not resp or 'id' not in resp:
376 0                 raise ClientException('unexpected response from server - {}'.format(
377                                   resp))
378 0             if wait:
379                 # Wait for status for NS instance action
380                 # For the 'action' operation, 'id' is used
381 0                 self._wait(resp.get('id'), wait)
382 0             return resp['id']
383             #else:
384             #    msg = ""
385             #    if resp:
386             #        try:
387             #            msg = json.loads(resp)
388             #        except ValueError:
389             #            msg = resp
390             #    raise ClientException(msg)
391 0         except ClientException as exc:
392 0             message="failed to exec operation {}:\nerror:\n{}".format(
393                     name,
394                     str(exc))
395 0             raise ClientException(message)
396
397 0     def scale_vnf(self, ns_name, vnf_name, scaling_group, scale_in, scale_out, wait=False, timeout=None):
398         """Scales a VNF by adding/removing VDUs
399         """
400 0         self._logger.debug("")
401 0         self._client.get_token()
402 0         try:
403 0             op_data={}
404 0             op_data["scaleType"] = "SCALE_VNF"
405 0             op_data["scaleVnfData"] = {}
406 0             if scale_in and not scale_out:
407 0                 op_data["scaleVnfData"]["scaleVnfType"] = "SCALE_IN"
408 0             elif not scale_in and scale_out:
409 0                 op_data["scaleVnfData"]["scaleVnfType"] = "SCALE_OUT"
410             else:
411 0                 raise ClientException("you must set either 'scale_in' or 'scale_out'")
412 0             op_data["scaleVnfData"]["scaleByStepData"] = {
413                 "member-vnf-index": vnf_name,
414                 "scaling-group-descriptor": scaling_group,
415             }
416 0             if timeout:
417 0                 op_data["timeout_ns_scale"] = timeout
418 0             op_id = self.exec_op(ns_name, op_name='scale', op_data=op_data, wait=wait)
419 0             print(str(op_id))
420 0         except ClientException as exc:
421 0             message="failed to scale vnf {} of ns {}:\nerror:\n{}".format(
422                     vnf_name, ns_name, str(exc))
423 0             raise ClientException(message)
424
425 0     def create_alarm(self, alarm):
426 0         self._logger.debug("")
427 0         self._client.get_token()
428 0         data = {}
429 0         data["create_alarm_request"] = {}
430 0         data["create_alarm_request"]["alarm_create_request"] = alarm
431 0         try:
432 0             http_code, resp = self._http.post_cmd(endpoint='/test/message/alarm_request',
433                                        postfields_dict=data)
434             #print('HTTP CODE: {}'.format(http_code))
435             #print('RESP: {}'.format(resp))
436             # if http_code in (200, 201, 202, 204):
437             #     resp = json.loads(resp)
438 0             print('Alarm created')
439             #else:
440             #    msg = ""
441             #    if resp:
442             #        try:
443             #            msg = json.loads(resp)
444             #        except ValueError:
445             #            msg = resp
446             #    raise ClientException('error: code: {}, resp: {}'.format(
447             #                          http_code, msg))
448 0         except ClientException as exc:
449 0             message="failed to create alarm: alarm {}\n{}".format(
450                     alarm,
451                     str(exc))
452 0             raise ClientException(message)
453
454 0     def delete_alarm(self, name):
455 0         self._logger.debug("")
456 0         self._client.get_token()
457 0         data = {}
458 0         data["delete_alarm_request"] = {}
459 0         data["delete_alarm_request"]["alarm_delete_request"] = {}
460 0         data["delete_alarm_request"]["alarm_delete_request"]["alarm_uuid"] = name
461 0         try:
462 0             http_code, resp = self._http.post_cmd(endpoint='/test/message/alarm_request',
463                                        postfields_dict=data)
464             #print('HTTP CODE: {}'.format(http_code))
465             #print('RESP: {}'.format(resp))
466             # if http_code in (200, 201, 202, 204):
467             #    resp = json.loads(resp)
468 0             print('Alarm deleted')
469             #else:
470             #    msg = ""
471             #    if resp:
472             #        try:
473             #            msg = json.loads(resp)
474             #        except ValueError:
475             #            msg = resp
476             #    raise ClientException('error: code: {}, resp: {}'.format(
477             #                          http_code, msg))
478 0         except ClientException as exc:
479 0             message="failed to delete alarm: alarm {}\n{}".format(
480                     name,
481                     str(exc))
482 0             raise ClientException(message)
483
484 0     def export_metric(self, metric):
485 0         self._logger.debug("")
486 0         self._client.get_token()
487 0         data = {}
488 0         data["read_metric_data_request"] = metric
489 0         try:
490 0             http_code, resp = self._http.post_cmd(endpoint='/test/message/metric_request',
491                                        postfields_dict=data)
492             #print('HTTP CODE: {}'.format(http_code))
493             #print('RESP: {}'.format(resp))
494             # if http_code in (200, 201, 202, 204):
495             #    resp = json.loads(resp)
496 0             return 'Metric exported'
497             #else:
498             #    msg = ""
499             #    if resp:
500             #        try:
501             #            msg = json.loads(resp)
502             #        except ValueError:
503             #            msg = resp
504             #    raise ClientException('error: code: {}, resp: {}'.format(
505             #                          http_code, msg))
506 0         except ClientException as exc:
507 0             message="failed to export metric: metric {}\n{}".format(
508                     metric,
509                     str(exc))
510 0             raise ClientException(message)
511
512 0     def get_field(self, ns_name, field):
513 0         self._logger.debug("")
514 0         nsr = self.get(ns_name)
515 0         print(yaml.safe_dump(nsr))
516 0         if nsr is None:
517 0             raise NotFound("failed to retrieve ns {}".format(ns_name))
518
519 0         if field in nsr:
520 0             return nsr[field]
521
522 0         raise NotFound("failed to find {} in ns {}".format(field, ns_name))
523