387bcd573bbf89c1f6a74504d7bd2b8d1d3a64a7
[osm/osmclient.git] / 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 """
18 OSM ns API handling
19 """
20
21 from osmclient.common import utils
22 from osmclient.common.exceptions import ClientException
23 from osmclient.common.exceptions import NotFound
24 import yaml
25 import json
26
27
28 class Ns(object):
29
30 def __init__(self, http=None, client=None):
31 self._http = http
32 self._client = client
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)
38
39 def list(self, filter=None):
40 """Returns a list of NS
41 """
42 filter_string = ''
43 if filter:
44 filter_string = '?{}'.format(filter)
45 resp = self._http.get_cmd('{}{}'.format(self._apiBase,filter_string))
46 if resp:
47 return resp
48 return list()
49
50 def get(self, name):
51 """Returns an NS based on name or id
52 """
53 if utils.validate_uuid4(name):
54 for ns in self.list():
55 if name == ns['_id']:
56 return ns
57 else:
58 for ns in self.list():
59 if name == ns['name']:
60 return ns
61 raise NotFound("ns {} not found".format(name))
62
63 def get_individual(self, name):
64 ns_id = name
65 if not utils.validate_uuid4(name):
66 for ns in self.list():
67 if name == ns['name']:
68 ns_id = ns['_id']
69 break
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)
73 if resp:
74 return resp
75 raise NotFound("ns {} not found".format(name))
76
77 def delete(self, name, force=False):
78 ns = self.get(name)
79 querystring = ''
80 if force:
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)
86 if http_code == 202:
87 print('Deletion in progress')
88 elif http_code == 204:
89 print('Deleted')
90 else:
91 msg = ""
92 if resp:
93 try:
94 msg = json.loads(resp)
95 except ValueError:
96 msg = resp
97 raise ClientException("failed to delete ns {} - {}".format(name, msg))
98
99 def create(self, nsd_name, nsr_name, account, config=None,
100 ssh_keys=None, description='default description',
101 admin_status='ENABLED'):
102
103 nsd = self._client.nsd.get(nsd_name)
104
105 vim_account_id = {}
106
107 def get_vim_account_id(vim_account):
108 if vim_account_id.get(vim_account):
109 return vim_account_id[vim_account]
110
111 vim = self._client.vim.get(vim_account)
112 if vim is None:
113 raise NotFound("cannot find vim account '{}'".format(vim_account))
114 vim_account_id[vim_account] = vim['_id']
115 return vim['_id']
116
117 ns = {}
118 ns['nsdId'] = nsd['_id']
119 ns['nsName'] = nsr_name
120 ns['nsDescription'] = description
121 ns['vimAccountId'] = get_vim_account_id(account)
122 #ns['userdata'] = {}
123 #ns['userdata']['key1']='value1'
124 #ns['userdata']['key2']='value2'
125
126 if ssh_keys is not None:
127 ns['ssh_keys'] = []
128 for pubkeyfile in ssh_keys.split(','):
129 with open(pubkeyfile, 'r') as f:
130 ns['ssh_keys'].append(f.read())
131 if config:
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"))
148
149 ns["vnf"] = ns_config["vnf"]
150
151 #print yaml.safe_dump(ns)
152 try:
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,
162 postfields_dict=ns)
163 #print 'HTTP CODE: {}'.format(http_code)
164 #print 'RESP: {}'.format(resp)
165 if http_code in (200, 201, 202, 204):
166 if resp:
167 resp = json.loads(resp)
168 if not resp or 'id' not in resp:
169 raise ClientException('unexpected response from server - {} '.format(
170 resp))
171 return resp['id']
172 else:
173 msg = ""
174 if resp:
175 try:
176 msg = json.loads(resp)
177 except ValueError:
178 msg = resp
179 raise ClientException(msg)
180 except ClientException as exc:
181 message="failed to create ns: {} nsd: {}\nerror:\n{}".format(
182 nsr_name,
183 nsd_name,
184 exc.message)
185 raise ClientException(message)
186
187 def list_op(self, name, filter=None):
188 """Returns the list of operations of a NS
189 """
190 ns = self.get(name)
191 try:
192 self._apiResource = '/ns_lcm_op_occs'
193 self._apiBase = '{}{}{}'.format(self._apiName,
194 self._apiVersion, self._apiResource)
195 filter_string = ''
196 if filter:
197 filter_string = '&{}'.format(filter)
198 http_code, resp = self._http.get2_cmd('{}?nsInstanceId={}'.format(
199 self._apiBase, ns['_id'],
200 filter_string) )
201 #print 'HTTP CODE: {}'.format(http_code)
202 #print 'RESP: {}'.format(resp)
203 if http_code == 200:
204 if resp:
205 resp = json.loads(resp)
206 return resp
207 else:
208 raise ClientException('unexpected response from server')
209 else:
210 msg = ""
211 if resp:
212 try:
213 resp = json.loads(resp)
214 msg = resp['detail']
215 except ValueError:
216 msg = resp
217 raise ClientException(msg)
218 except ClientException as exc:
219 message="failed to get operation list of NS {}:\nerror:\n{}".format(
220 name,
221 exc.message)
222 raise ClientException(message)
223
224 def get_op(self, operationId):
225 """Returns the status of an operation
226 """
227 try:
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)
234 if http_code == 200:
235 if resp:
236 resp = json.loads(resp)
237 return resp
238 else:
239 raise ClientException('unexpected response from server')
240 else:
241 msg = ""
242 if resp:
243 try:
244 resp = json.loads(resp)
245 msg = resp['detail']
246 except ValueError:
247 msg = resp
248 raise ClientException(msg)
249 except ClientException as exc:
250 message="failed to get status of operation {}:\nerror:\n{}".format(
251 operationId,
252 exc.message)
253 raise ClientException(message)
254
255 def exec_op(self, name, op_name, op_data=None):
256 """Executes an operation on a NS
257 """
258 ns = self.get(name)
259 try:
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):
270 if resp:
271 resp = json.loads(resp)
272 if not resp or 'id' not in resp:
273 raise ClientException('unexpected response from server - {}'.format(
274 resp))
275 print(resp['id'])
276 else:
277 msg = ""
278 if resp:
279 try:
280 msg = json.loads(resp)
281 except ValueError:
282 msg = resp
283 raise ClientException(msg)
284 except ClientException as exc:
285 message="failed to exec operation {}:\nerror:\n{}".format(
286 name,
287 exc.message)
288 raise ClientException(message)
289
290 def create_alarm(self, alarm):
291 data = {}
292 data["create_alarm_request"] = {}
293 data["create_alarm_request"]["alarm_create_request"] = alarm
294 try:
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')
302 else:
303 msg = ""
304 if resp:
305 try:
306 msg = json.loads(resp)
307 except ValueError:
308 msg = resp
309 raise ClientException('error: code: {}, resp: {}'.format(
310 http_code, msg))
311 except ClientException as exc:
312 message="failed to create alarm: alarm {}\n{}".format(
313 alarm,
314 exc.message)
315 raise ClientException(message)
316
317 def delete_alarm(self, name):
318 data = {}
319 data["delete_alarm_request"] = {}
320 data["delete_alarm_request"]["alarm_delete_request"] = {}
321 data["delete_alarm_request"]["alarm_delete_request"]["alarm_uuid"] = name
322 try:
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')
330 else:
331 msg = ""
332 if resp:
333 try:
334 msg = json.loads(resp)
335 except ValueError:
336 msg = resp
337 raise ClientException('error: code: {}, resp: {}'.format(
338 http_code, msg))
339 except ClientException as exc:
340 message="failed to delete alarm: alarm {}\n{}".format(
341 name,
342 exc.message)
343 raise ClientException(message)
344
345 def export_metric(self, metric):
346 data = {}
347 data["read_metric_data_request"] = metric
348 try:
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'
356 else:
357 msg = ""
358 if resp:
359 try:
360 msg = json.loads(resp)
361 except ValueError:
362 msg = resp
363 raise ClientException('error: code: {}, resp: {}'.format(
364 http_code, msg))
365 except ClientException as exc:
366 message="failed to export metric: metric {}\n{}".format(
367 metric,
368 exc.message)
369 raise ClientException(message)
370
371 def get_field(self, ns_name, field):
372 nsr = self.get(ns_name)
373 if nsr is None:
374 raise NotFound("failed to retrieve ns {}".format(ns_name))
375
376 if field in nsr:
377 return nsr[field]
378
379 raise NotFound("failed to find {} in ns {}".format(field, ns_name))