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
21 from osmclient
.common
import utils
22 from osmclient
.common
.exceptions
import ClientException
23 from osmclient
.common
.exceptions
import NotFound
30 def __init__(self
, http
=None, client
=None):
33 self
._apiName
= '/nslcm'
34 self
._apiVersion
= '/v1'
35 self
._apiResource
= '/ns_instances_content'
36 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
37 self
._apiVersion
, self
._apiResource
)
39 def list(self
, filter=None):
40 """Returns a list of NS
44 filter_string
= '?{}'.format(filter)
45 resp
= self
._http
.get_cmd('{}{}'.format(self
._apiBase
,filter_string
))
51 """Returns an NS based on name or id
53 if utils
.validate_uuid4(name
):
54 for ns
in self
.list():
58 for ns
in self
.list():
59 if name
== ns
['name']:
61 raise NotFound("ns {} not found".format(name
))
63 def get_individual(self
, name
):
65 if not utils
.validate_uuid4(name
):
66 for ns
in self
.list():
67 if name
== ns
['name']:
70 resp
= self
._http
.get_cmd('{}/{}'.format(self
._apiBase
, ns_id
))
71 #resp = self._http.get_cmd('{}/{}/nsd_content'.format(self._apiBase, ns_id))
72 #print yaml.safe_dump(resp)
75 raise NotFound("ns {} not found".format(name
))
77 def delete(self
, name
, force
=False):
81 querystring
= '?FORCE=True'
82 http_code
, resp
= self
._http
.delete_cmd('{}/{}{}'.format(self
._apiBase
,
83 ns
['_id'], querystring
))
84 #print 'HTTP CODE: {}'.format(http_code)
85 #print 'RESP: {}'.format(resp)
87 print('Deletion in progress')
88 elif http_code
== 204:
94 msg
= json
.loads(resp
)
97 raise ClientException("failed to delete ns {} - {}".format(name
, msg
))
99 def create(self
, nsd_name
, nsr_name
, account
, config
=None,
100 ssh_keys
=None, description
='default description',
101 admin_status
='ENABLED'):
103 nsd
= self
._client
.nsd
.get(nsd_name
)
107 def get_vim_account_id(vim_account
):
108 if vim_account_id
.get(vim_account
):
109 return vim_account_id
[vim_account
]
111 vim
= self
._client
.vim
.get(vim_account
)
113 raise NotFound("cannot find vim account '{}'".format(vim_account
))
114 vim_account_id
[vim_account
] = vim
['_id']
118 ns
['nsdId'] = nsd
['_id']
119 ns
['nsName'] = nsr_name
120 ns
['nsDescription'] = description
121 ns
['vimAccountId'] = get_vim_account_id(account
)
123 #ns['userdata']['key1']='value1'
124 #ns['userdata']['key2']='value2'
126 if ssh_keys
is not None:
128 for pubkeyfile
in ssh_keys
.split(','):
129 with
open(pubkeyfile
, 'r') as f
:
130 ns
['ssh_keys'].append(f
.read())
132 ns_config
= yaml
.load(config
)
133 if "vim-network-name" in ns_config
:
134 ns_config
["vld"] = ns_config
.pop("vim-network-name")
135 if "vld" in ns_config
:
136 for vld
in ns_config
["vld"]:
137 if vld
.get("vim-network-name"):
138 if isinstance(vld
["vim-network-name"], dict):
139 vim_network_name_dict
= {}
140 for vim_account
, vim_net
in list(vld
["vim-network-name"].items()):
141 vim_network_name_dict
[get_vim_account_id(vim_account
)] = vim_net
142 vld
["vim-network-name"] = vim_network_name_dict
143 ns
["vld"] = ns_config
["vld"]
144 if "vnf" in ns_config
:
145 for vnf
in ns_config
["vnf"]:
146 if vnf
.get("vim_account"):
147 vnf
["vimAccountId"] = get_vim_account_id(vnf
.pop("vim_account"))
149 ns
["vnf"] = ns_config
["vnf"]
151 #print yaml.safe_dump(ns)
153 self
._apiResource
= '/ns_instances_content'
154 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
155 self
._apiVersion
, self
._apiResource
)
156 headers
= self
._client
._headers
157 headers
['Content-Type'] = 'application/yaml'
158 http_header
= ['{}: {}'.format(key
,val
)
159 for (key
,val
) in list(headers
.items())]
160 self
._http
.set_http_header(http_header
)
161 http_code
, resp
= self
._http
.post_cmd(endpoint
=self
._apiBase
,
163 #print 'HTTP CODE: {}'.format(http_code)
164 #print 'RESP: {}'.format(resp)
165 if http_code
in (200, 201, 202, 204):
167 resp
= json
.loads(resp
)
168 if not resp
or 'id' not in resp
:
169 raise ClientException('unexpected response from server - {} '.format(
176 msg
= json
.loads(resp
)
179 raise ClientException(msg
)
180 except ClientException
as exc
:
181 message
="failed to create ns: {} nsd: {}\nerror:\n{}".format(
185 raise ClientException(message
)
187 def list_op(self
, name
, filter=None):
188 """Returns the list of operations of a NS
192 self
._apiResource
= '/ns_lcm_op_occs'
193 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
194 self
._apiVersion
, self
._apiResource
)
197 filter_string
= '&{}'.format(filter)
198 http_code
, resp
= self
._http
.get2_cmd('{}?nsInstanceId={}'.format(
199 self
._apiBase
, ns
['_id'],
201 #print 'HTTP CODE: {}'.format(http_code)
202 #print 'RESP: {}'.format(resp)
205 resp
= json
.loads(resp
)
208 raise ClientException('unexpected response from server')
213 resp
= json
.loads(resp
)
217 raise ClientException(msg
)
218 except ClientException
as exc
:
219 message
="failed to get operation list of NS {}:\nerror:\n{}".format(
222 raise ClientException(message
)
224 def get_op(self
, operationId
):
225 """Returns the status of an operation
228 self
._apiResource
= '/ns_lcm_op_occs'
229 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
230 self
._apiVersion
, self
._apiResource
)
231 http_code
, resp
= self
._http
.get2_cmd('{}/{}'.format(self
._apiBase
, operationId
))
232 #print 'HTTP CODE: {}'.format(http_code)
233 #print 'RESP: {}'.format(resp)
236 resp
= json
.loads(resp
)
239 raise ClientException('unexpected response from server')
244 resp
= json
.loads(resp
)
248 raise ClientException(msg
)
249 except ClientException
as exc
:
250 message
="failed to get status of operation {}:\nerror:\n{}".format(
253 raise ClientException(message
)
255 def exec_op(self
, name
, op_name
, op_data
=None):
256 """Executes an operation on a NS
260 self
._apiResource
= '/ns_instances'
261 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
262 self
._apiVersion
, self
._apiResource
)
263 endpoint
= '{}/{}/{}'.format(self
._apiBase
, ns
['_id'], op_name
)
264 #print 'OP_NAME: {}'.format(op_name)
265 #print 'OP_DATA: {}'.format(json.dumps(op_data))
266 http_code
, resp
= self
._http
.post_cmd(endpoint
=endpoint
, postfields_dict
=op_data
)
267 #print 'HTTP CODE: {}'.format(http_code)
268 #print 'RESP: {}'.format(resp)
269 if http_code
in (200, 201, 202, 204):
271 resp
= json
.loads(resp
)
272 if not resp
or 'id' not in resp
:
273 raise ClientException('unexpected response from server - {}'.format(
280 msg
= json
.loads(resp
)
283 raise ClientException(msg
)
284 except ClientException
as exc
:
285 message
="failed to exec operation {}:\nerror:\n{}".format(
288 raise ClientException(message
)
290 def create_alarm(self
, alarm
):
292 data
["create_alarm_request"] = {}
293 data
["create_alarm_request"]["alarm_create_request"] = alarm
295 http_code
, resp
= self
._http
.post_cmd(endpoint
='/test/message/alarm_request',
296 postfields_dict
=data
)
297 #print 'HTTP CODE: {}'.format(http_code)
298 #print 'RESP: {}'.format(resp)
299 if http_code
in (200, 201, 202, 204):
300 #resp = json.loads(resp)
301 print('Alarm created')
306 msg
= json
.loads(resp
)
309 raise ClientException('error: code: {}, resp: {}'.format(
311 except ClientException
as exc
:
312 message
="failed to create alarm: alarm {}\n{}".format(
315 raise ClientException(message
)
317 def delete_alarm(self
, name
):
319 data
["delete_alarm_request"] = {}
320 data
["delete_alarm_request"]["alarm_delete_request"] = {}
321 data
["delete_alarm_request"]["alarm_delete_request"]["alarm_uuid"] = name
323 http_code
, resp
= self
._http
.post_cmd(endpoint
='/test/message/alarm_request',
324 postfields_dict
=data
)
325 #print 'HTTP CODE: {}'.format(http_code)
326 #print 'RESP: {}'.format(resp)
327 if http_code
in (200, 201, 202, 204):
328 #resp = json.loads(resp)
329 print('Alarm deleted')
334 msg
= json
.loads(resp
)
337 raise ClientException('error: code: {}, resp: {}'.format(
339 except ClientException
as exc
:
340 message
="failed to delete alarm: alarm {}\n{}".format(
343 raise ClientException(message
)
345 def export_metric(self
, metric
):
347 data
["read_metric_data_request"] = metric
349 http_code
, resp
= self
._http
.post_cmd(endpoint
='/test/message/metric_request',
350 postfields_dict
=data
)
351 #print 'HTTP CODE: {}'.format(http_code)
352 #print 'RESP: {}'.format(resp)
353 if http_code
in (200, 201, 202, 204):
354 #resp = json.loads(resp)
355 return 'Metric exported'
360 msg
= json
.loads(resp
)
363 raise ClientException('error: code: {}, resp: {}'.format(
365 except ClientException
as exc
:
366 message
="failed to export metric: metric {}\n{}".format(
369 raise ClientException(message
)
371 def get_field(self
, ns_name
, field
):
372 nsr
= self
.get(ns_name
)
374 raise NotFound("failed to retrieve ns {}".format(ns_name
))
379 raise NotFound("failed to find {} in ns {}".format(field
, ns_name
))