1 # Copyright 2018 Telefonica
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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
18 OSM NSI (Network Slice Instance) API handling
21 from osmclient
.common
import utils
22 from osmclient
.common
import wait
as WaitForStatus
23 from osmclient
.common
.exceptions
import ClientException
24 from osmclient
.common
.exceptions
import NotFound
32 def __init__(self
, http
=None, client
=None):
35 self
._logger
= logging
.getLogger('osmclient')
36 self
._apiName
= '/nsilcm'
37 self
._apiVersion
= '/v1'
38 self
._apiResource
= '/netslice_instances_content'
39 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
40 self
._apiVersion
, self
._apiResource
)
43 def _wait(self
, id, deleteFlag
=False):
44 self
._logger
.debug("")
45 self
._client
.get_token()
46 # Endpoint to get operation status
47 apiUrlStatus
= '{}{}{}'.format(self
._apiName
, self
._apiVersion
, '/nsi_lcm_op_occs')
48 # Wait for status for NSI instance creation/update/deletion
49 WaitForStatus
.wait_for_status(
52 WaitForStatus
.TIMEOUT_NSI_OPERATION
,
55 deleteFlag
=deleteFlag
)
57 def list(self
, filter=None):
58 """Returns a list of NSI
60 self
._logger
.debug("")
61 self
._client
.get_token()
64 filter_string
= '?{}'.format(filter)
65 _
, resp
= self
._http
.get2_cmd('{}{}'.format(self
._apiBase
,filter_string
))
67 return json
.loads(resp
)
71 """Returns an NSI based on name or id
73 self
._logger
.debug("")
74 self
._client
.get_token()
75 if utils
.validate_uuid4(name
):
76 for nsi
in self
.list():
77 if name
== nsi
['_id']:
80 for nsi
in self
.list():
81 if name
== nsi
['name']:
83 raise NotFound("nsi {} not found".format(name
))
85 def get_individual(self
, name
):
86 self
._logger
.debug("")
88 self
._client
.get_token()
89 if not utils
.validate_uuid4(name
):
90 for nsi
in self
.list():
91 if name
== nsi
['name']:
95 _
, resp
= self
._http
.get2_cmd('{}/{}'.format(self
._apiBase
, nsi_id
))
96 #resp = self._http.get_cmd('{}/{}/nsd_content'.format(self._apiBase, nsi_id))
97 #print(yaml.safe_dump(resp))
99 return json
.loads(resp
)
101 raise NotFound("nsi '{}' not found".format(name
))
102 raise NotFound("nsi {} not found".format(name
))
104 def delete(self
, name
, force
=False, wait
=False):
105 self
._logger
.debug("")
109 querystring
= '?FORCE=True'
110 http_code
, resp
= self
._http
.delete_cmd('{}/{}{}'.format(self
._apiBase
,
111 nsi
['_id'], querystring
))
112 # print('HTTP CODE: {}'.format(http_code))
113 # print('RESP: {}'.format(resp))
116 resp
= json
.loads(resp
)
117 # Wait for status for NSI instance deletion
118 # For the 'delete' operation, '_id' is used
119 self
._wait
(resp
.get('_id'), deleteFlag
=True)
121 print('Deletion in progress')
122 elif http_code
== 204:
128 # msg = json.loads(resp)
131 raise ClientException("failed to delete nsi {} - {}".format(name
, msg
))
133 def create(self
, nst_name
, nsi_name
, account
, config
=None,
134 ssh_keys
=None, description
='default description',
135 admin_status
='ENABLED', wait
=False):
137 self
._logger
.debug("")
138 self
._client
.get_token()
139 nst
= self
._client
.nst
.get(nst_name
)
143 def get_vim_account_id(vim_account
):
144 self
._logger
.debug("")
145 if vim_account_id
.get(vim_account
):
146 return vim_account_id
[vim_account
]
148 vim
= self
._client
.vim
.get(vim_account
)
150 raise NotFound("cannot find vim account '{}'".format(vim_account
))
151 vim_account_id
[vim_account
] = vim
['_id']
155 nsi
['nstId'] = nst
['_id']
156 nsi
['nsiName'] = nsi_name
157 nsi
['nsiDescription'] = description
158 nsi
['vimAccountId'] = get_vim_account_id(account
)
159 #nsi['userdata'] = {}
160 #nsi['userdata']['key1']='value1'
161 #nsi['userdata']['key2']='value2'
163 if ssh_keys
is not None:
164 # ssh_keys is comma separate list
165 # ssh_keys_format = []
166 # for key in ssh_keys.split(','):
167 # ssh_keys_format.append({'key-pair-ref': key})
169 # ns['ssh-authorized-key'] = ssh_keys_format
171 for pubkeyfile
in ssh_keys
.split(','):
172 with
open(pubkeyfile
, 'r') as f
:
173 nsi
['ssh_keys'].append(f
.read())
175 nsi_config
= yaml
.safe_load(config
)
176 if "netslice-vld" in nsi_config
:
177 for vld
in nsi_config
["netslice-vld"]:
178 if vld
.get("vim-network-name"):
179 if isinstance(vld
["vim-network-name"], dict):
180 vim_network_name_dict
= {}
181 for vim_account
, vim_net
in list(vld
["vim-network-name"].items()):
182 vim_network_name_dict
[get_vim_account_id(vim_account
)] = vim_net
183 vld
["vim-network-name"] = vim_network_name_dict
184 nsi
["netslice-vld"] = nsi_config
["netslice-vld"]
185 if "netslice-subnet" in nsi_config
:
186 for nssubnet
in nsi_config
["netslice-subnet"]:
187 if "vld" in nssubnet
:
188 for vld
in nssubnet
["vld"]:
189 if vld
.get("vim-network-name"):
190 if isinstance(vld
["vim-network-name"], dict):
191 vim_network_name_dict
= {}
192 for vim_account
, vim_net
in list(vld
["vim-network-name"].items()):
193 vim_network_name_dict
[get_vim_account_id(vim_account
)] = vim_net
194 vld
["vim-network-name"] = vim_network_name_dict
195 if "vnf" in nssubnet
:
196 for vnf
in nsi_config
["vnf"]:
197 if vnf
.get("vim_account"):
198 vnf
["vimAccountId"] = get_vim_account_id(vnf
.pop("vim_account"))
199 nsi
["netslice-subnet"] = nsi_config
["netslice-subnet"]
201 if "additionalParamsForNsi" in nsi_config
:
202 nsi
["additionalParamsForNsi"] = nsi_config
.pop("additionalParamsForNsi")
203 if not isinstance(nsi
["additionalParamsForNsi"], dict):
204 raise ValueError("Error at --config 'additionalParamsForNsi' must be a dictionary")
205 if "additionalParamsForSubnet" in nsi_config
:
206 nsi
["additionalParamsForSubnet"] = nsi_config
.pop("additionalParamsForSubnet")
207 if not isinstance(nsi
["additionalParamsForSubnet"], list):
208 raise ValueError("Error at --config 'additionalParamsForSubnet' must be a list")
209 for additional_param_subnet
in nsi
["additionalParamsForSubnet"]:
210 if not isinstance(additional_param_subnet
, dict):
211 raise ValueError("Error at --config 'additionalParamsForSubnet' items must be dictionaries")
212 if not additional_param_subnet
.get("id"):
213 raise ValueError("Error at --config 'additionalParamsForSubnet' items must contain subnet 'id'")
214 if not additional_param_subnet
.get("additionalParamsForNs") and\
215 not additional_param_subnet
.get("additionalParamsForVnf"):
216 raise ValueError("Error at --config 'additionalParamsForSubnet' items must contain "
217 "'additionalParamsForNs' and/or 'additionalParamsForVnf'")
218 if "timeout_nsi_deploy" in nsi_config
:
219 nsi
["timeout_nsi_deploy"] = nsi_config
.pop("timeout_nsi_deploy")
221 # print(yaml.safe_dump(nsi))
223 self
._apiResource
= '/netslice_instances_content'
224 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
225 self
._apiVersion
, self
._apiResource
)
226 headers
= self
._client
._headers
227 headers
['Content-Type'] = 'application/yaml'
228 http_header
= ['{}: {}'.format(key
,val
)
229 for (key
,val
) in list(headers
.items())]
230 self
._http
.set_http_header(http_header
)
231 http_code
, resp
= self
._http
.post_cmd(endpoint
=self
._apiBase
,
233 #print('HTTP CODE: {}'.format(http_code))
234 #print('RESP: {}'.format(resp))
235 #if http_code in (200, 201, 202, 204):
237 resp
= json
.loads(resp
)
238 if not resp
or 'id' not in resp
:
239 raise ClientException('unexpected response from server - {} '.format(
242 # Wait for status for NSI instance creation
243 self
._wait
(resp
.get('nsilcmop_id'))
249 # msg = json.loads(resp)
252 # raise ClientException(msg)
253 except ClientException
as exc
:
254 message
="failed to create nsi: {} nst: {}\nerror:\n{}".format(
258 raise ClientException(message
)
260 def list_op(self
, name
, filter=None):
261 """Returns the list of operations of a NSI
263 self
._logger
.debug("")
266 self
._apiResource
= '/nsi_lcm_op_occs'
267 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
268 self
._apiVersion
, self
._apiResource
)
271 filter_string
= '&{}'.format(filter)
272 http_code
, resp
= self
._http
.get2_cmd('{}?netsliceInstanceId={}'.format(
273 self
._apiBase
, nsi
['_id'],
275 #print('HTTP CODE: {}'.format(http_code))
276 #print('RESP: {}'.format(resp))
277 #if http_code == 200:
279 resp
= json
.loads(resp
)
282 raise ClientException('unexpected response from server')
287 # resp = json.loads(resp)
288 # msg = resp['detail']
291 # raise ClientException(msg)
292 except ClientException
as exc
:
293 message
="failed to get operation list of NSI {}:\nerror:\n{}".format(
296 raise ClientException(message
)
298 def get_op(self
, operationId
):
299 """Returns the status of an operation
301 self
._logger
.debug("")
302 self
._client
.get_token()
304 self
._apiResource
= '/nsi_lcm_op_occs'
305 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
306 self
._apiVersion
, self
._apiResource
)
307 http_code
, resp
= self
._http
.get2_cmd('{}/{}'.format(self
._apiBase
, operationId
))
308 #print('HTTP CODE: {}'.format(http_code))
309 #print('RESP: {}'.format(resp))
310 #if http_code == 200:
312 resp
= json
.loads(resp
)
315 raise ClientException('unexpected response from server')
320 # resp = json.loads(resp)
321 # msg = resp['detail']
324 # raise ClientException(msg)
325 except ClientException
as exc
:
326 message
="failed to get status of operation {}:\nerror:\n{}".format(
329 raise ClientException(message
)
331 def exec_op(self
, name
, op_name
, op_data
=None):
332 """Executes an operation on a NSI
334 self
._logger
.debug("")
337 self
._apiResource
= '/netslice_instances'
338 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
339 self
._apiVersion
, self
._apiResource
)
340 endpoint
= '{}/{}/{}'.format(self
._apiBase
, nsi
['_id'], op_name
)
341 #print('OP_NAME: {}'.format(op_name))
342 #print('OP_DATA: {}'.format(json.dumps(op_data)))
343 http_code
, resp
= self
._http
.post_cmd(endpoint
=endpoint
, postfields_dict
=op_data
)
344 #print('HTTP CODE: {}'.format(http_code))
345 #print('RESP: {}'.format(resp))
346 #if http_code in (200, 201, 202, 204):
348 resp
= json
.loads(resp
)
349 if not resp
or 'id' not in resp
:
350 raise ClientException('unexpected response from server - {}'.format(
357 # msg = json.loads(resp)
360 # raise ClientException(msg)
361 except ClientException
as exc
:
362 message
="failed to exec operation {}:\nerror:\n{}".format(
365 raise ClientException(message
)