84ce7aa151e67a61e852ede2b60040d97d6bf161
2 # -*- coding: utf-8 -*-
5 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
6 # This file is part of openmano
9 # Licensed under the Apache License, Version 2.0 (the "License"); you may
10 # not use this file except in compliance with the License. You may obtain
11 # a copy of the License at
13 # http://www.apache.org/licenses/LICENSE-2.0
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 # License for the specific language governing permissions and limitations
21 # For those usages not covered by the Apache License, Version 2.0 please
22 # contact with: nfvlabs@tid.es
26 asyncio RO python client to interact with RO-server
36 from urllib
.parse
import quote
39 __author__
= "Alfonso Tierno, Pablo Montes"
40 __date__
= "$09-Jan-2018 09:09:48$"
41 __version__
= "0.1.0-r470"
42 version_date
= "Jan 2018"
45 class ROClientException(Exception):
46 def __init__(self
, message
, http_code
=400):
47 self
.http_code
= http_code
48 Exception.__init
__(self
, message
)
49 """Common Exception for all openmano client exceptions"""
52 def remove_envelop(item
, indata
=None):
54 Obtain the useful data removing the envelop. It goes through the vnfd or nsd catalog and returns the
56 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
57 :param indata: Content to be inspected
58 :return: the useful part of indata (a reference, not a new dictionay) plus boolean indicating if it was enveloped
65 if clean_indata
.get('vnfd:vnfd-catalog'):
67 clean_indata
= clean_indata
['vnfd:vnfd-catalog']
68 elif clean_indata
.get('vnfd-catalog'):
70 clean_indata
= clean_indata
['vnfd-catalog']
71 if clean_indata
.get('vnfd'):
72 if not isinstance(clean_indata
['vnfd'], list) or len(clean_indata
['vnfd']) != 1:
73 raise ROClientException("'vnfd' must be a list only one element")
74 clean_indata
= clean_indata
['vnfd'][0]
76 if clean_indata
.get('nsd:nsd-catalog'):
78 clean_indata
= clean_indata
['nsd:nsd-catalog']
79 elif clean_indata
.get('nsd-catalog'):
81 clean_indata
= clean_indata
['nsd-catalog']
82 if clean_indata
.get('nsd'):
83 if not isinstance(clean_indata
['nsd'], list) or len(clean_indata
['nsd']) != 1:
84 raise ROClientException("'nsd' must be a list only one element")
85 clean_indata
= clean_indata
['nsd'][0]
86 elif item
== "tenant":
87 if len(indata
) == 1 and "tenant" in indata
:
89 clean_indata
= indata
["tenant"]
90 elif item
== "vim" or item
== "datacenter":
91 if len(indata
) == 1 and "datacenter" in indata
:
93 clean_indata
= indata
["datacenter"]
94 elif item
== "ns" or item
== "instances":
95 if len(indata
) == 1 and "instance" in indata
:
97 clean_indata
= indata
["instance"]
99 assert False, "remove_envelop with unknown item {}".format(item
)
101 return clean_indata
, enveloped
105 headers_req
= {'Accept': 'application/yaml', 'content-type': 'application/yaml'}
106 client_to_RO
= {'tenant': 'tenants', 'vim': 'datacenters', 'vnfd': 'vnfs', 'nsd': 'scenarios',
108 mandatory_for_create
= {
109 'tenant': ("name", ),
110 'vim': ("name", "vim_url"),
111 'vnfd': ("name", "id", "connection-point", "vdu"),
112 'nsd': ("name", "id", "constituent-vnfd"),
113 'ns': ("name", "scenario", "datacenter"),
118 def __init__(self
, loop
, endpoint_url
, **kwargs
):
120 self
.endpoint_url
= endpoint_url
122 self
.username
= kwargs
.get("username")
123 self
.password
= kwargs
.get("password")
124 self
.tenant_id_name
= kwargs
.get("tenant")
126 self
.datacenter_id_name
= kwargs
.get("datacenter")
127 self
.datacenter
= None
128 self
.logger
= logging
.getLogger(kwargs
.get('logger', 'ROClient'))
129 if kwargs
.get("debug"):
130 self
.logger
.setLevel(logging
.DEBUG
)
132 requests
= kwargs
.get("TODO remove")
134 def __getitem__(self
, index
):
135 if index
== 'tenant':
136 return self
.tenant_id_name
137 elif index
== 'datacenter':
138 return self
.datacenter_id_name
139 elif index
== 'username':
141 elif index
== 'password':
143 elif index
== 'endpoint_url':
144 return self
.endpoint_url
146 raise KeyError("Invalid key '%s'" %str
(index
))
148 def __setitem__(self
,index
, value
):
149 if index
== 'tenant':
150 self
.tenant_id_name
= value
151 elif index
== 'datacenter':
152 self
.datacenter_id_name
= value
153 elif index
== 'username':
154 self
.username
= value
155 elif index
== 'password':
156 self
.password
= value
157 elif index
== 'endpoint_url':
158 self
.endpoint_url
= value
160 raise KeyError("Invalid key '{}'".format(index
))
161 self
.tenant
= None # force to reload tenant with different credentials
162 self
.datacenter
= None # force to reload datacenter with different credentials
164 def _parse(self
, descriptor
, descriptor_format
, response
=False):
166 if descriptor_format
and descriptor_format
!= "json" and descriptor_format
!= "yaml":
167 raise ROClientException("'descriptor_format' must be a 'json' or 'yaml' text")
168 if descriptor_format
!= "json":
170 return yaml
.load(descriptor
)
171 except yaml
.YAMLError
as exc
:
173 if hasattr(exc
, 'problem_mark'):
174 mark
= exc
.problem_mark
175 error_pos
= " at line:{} column:{}s".format(mark
.line
+1, mark
.column
+1)
176 error_text
= "yaml format error" + error_pos
177 elif descriptor_format
!= "yaml":
179 return json
.loads(descriptor
)
180 except Exception as e
:
182 error_text
= "json format error" + str(e
)
185 raise ROClientException(error_text
)
186 raise ROClientException(error_text
)
188 def _parse_yaml(self
, descriptor
, response
=False):
190 return yaml
.load(descriptor
)
191 except yaml
.YAMLError
as exc
:
193 if hasattr(exc
, 'problem_mark'):
194 mark
= exc
.problem_mark
195 error_pos
= " at line:{} column:{}s".format(mark
.line
+1, mark
.column
+1)
196 error_text
= "yaml format error" + error_pos
198 raise ROClientException(error_text
)
199 raise ROClientException(error_text
)
202 def check_if_uuid(uuid_text
):
204 Check if text correspond to an uuid foramt
206 :return: True if it is an uuid False if not
211 except (ValueError, TypeError):
215 def _create_envelop(item
, indata
=None):
217 Returns a new dict that incledes indata with the expected envelop
218 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
219 :param indata: Content to be enveloped
220 :return: a new dic with {<envelop>: {indata} } where envelop can be e.g. tenant, datacenter, ...
223 return {'vnfd-catalog': {'vnfd': [indata
]}}
225 return {'nsd-catalog': {'nsd': [indata
]}}
226 elif item
== "tenant":
227 return {'tenant': indata
}
228 elif item
== "vim" or item
== "datacenter":
229 return {'datacenter': indata
}
230 elif item
== "ns" or item
== "instances":
231 return {'instance': indata
}
233 assert False, "_create_envelop with unknown item {}".format(item
)
236 def check_ns_status(ns_descriptor
):
238 Inspect RO instance descriptor and indicates the status
239 :param ns_descriptor: instance descriptor obtained with self.show("ns", )
240 :return: status, message: status can be BUILD,ACTIVE,ERROR, message is a text message
247 for net
in ns_descriptor
["nets"]:
249 if net
["status"] == "ERROR":
250 return "ERROR", net
["error_msg"]
251 elif net
["status"] == "ACTIVE":
253 for vnf
in ns_descriptor
["vnfs"]:
254 for vm
in vnf
["vms"]:
256 if vm
["status"] == "ERROR":
257 return "ERROR", vm
["error_msg"]
258 elif vm
["status"] == "ACTIVE":
261 if net_total
== net_done
and vm_total
== vm_done
:
262 return "ACTIVE", "VMs {}, networks: {}".format(vm_total
, net_total
)
264 return "BUILD", "VMs: {}/{}, networks: {}/{}".format(vm_done
, vm_total
, net_done
, net_total
)
267 def get_ns_vnf_ip(ns_descriptor
):
269 Get a dict with the IPs of every vnf.
270 :param ns_descriptor: instance descriptor obtained with self.show("ns", )
271 :return: dict iwth key member_vnf_index, value ip_address
274 for vnf
in ns_descriptor
["vnfs"]:
275 ns_ip
[vnf
["member_vnf_index"]] = vnf
["ip_address"]
277 # vnf[mgmt_access]: '{interface_id: cf3cbf00-385c-49b4-9a3f-b400b7b15dc6, vm_id: d0dd22a9-91ef-46f1-8e8f-8cf4b2d5b2d7}'
281 async def get_list(self
, item
, all_tenants
=False, filter_by
=None):
283 Obtain a list of items filtering by the specigy filter_by.
284 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
285 :param all_tenants: True if not filtering by tenant. Only allowed for admin
286 :param filter_by: dictionary with filtering
287 :return: a list of dict. It can be empty. Raises ROClientException on Error,
289 if item
not in self
.client_to_RO
:
290 raise ROClientException("Invalid item {}".format(item
))
293 with aiohttp
.ClientSession(loop
=self
.loop
) as session
:
294 content
= await self
._list
_item
(session
, self
.client_to_RO
[item
], all_tenants
=all_tenants
,
295 filter_dict
=filter_by
)
296 if isinstance(content
, dict):
297 if len(content
) == 1:
298 return content
.values()[0]
300 raise ROClientException("Output not a list neither dict with len equal 1", http_code
=500)
303 async def _get_item_uuid(self
, session
, item
, item_id_name
, all_tenants
=False):
306 elif all_tenants
is None:
310 await self
._get
_tenant
(session
)
311 tenant_text
= "/" + self
.tenant
314 url
= "{}{}/{}".format(self
.endpoint_url
, tenant_text
, item
)
315 if self
.check_if_uuid(item_id_name
):
316 item_id
= item_id_name
317 url
+= "/" + item_id_name
318 elif item_id_name
and item_id_name
.startswith("'") and item_id_name
.endswith("'"):
319 item_id_name
= item_id_name
[1:-1]
320 self
.logger
.debug("openmano GET %s", url
)
321 with aiohttp
.Timeout(self
.timeout_short
):
322 async with session
.get(url
, headers
=self
.headers_req
) as response
:
323 response_text
= await response
.read()
324 self
.logger
.debug("GET {} [{}] {}".format(url
, response
.status
, response_text
[:100]))
325 if response
.status
== 404: # NOT_FOUND
326 raise ROClientException("No {} found with id '{}'".format(item
[:-1], item_id_name
),
328 if response
.status
>= 300:
329 raise ROClientException(response_text
, http_code
=response
.status
)
330 content
= self
._parse
_yaml
(response_text
, response
=True)
335 assert isinstance(desc
, list), "_get_item_uuid get a non dict with a list inside {}".format(type(desc
))
338 if item_id_name
and i
["name"] != item_id_name
:
340 if uuid
: # found more than one
341 raise ROClientException(
342 "Found more than one {} with name '{}'. uuid must be used".format(item
, item_id_name
),
346 raise ROClientException("No {} found with name '{}'".format(item
[:-1], item_id_name
), http_code
=404)
349 async def _get_item(self
, session
, item
, item_id_name
, all_tenants
=False):
352 elif all_tenants
is None:
356 await self
._get
_tenant
(session
)
357 tenant_text
= "/" + self
.tenant
359 if self
.check_if_uuid(item_id_name
):
363 uuid
= self
._get
_item
_uuid
(session
, item
, item_id_name
, all_tenants
)
365 url
= "{}{}/{}/{}".format(self
.endpoint_url
, tenant_text
, item
, uuid
)
366 self
.logger
.debug("GET %s", url
)
367 with aiohttp
.Timeout(self
.timeout_short
):
368 async with session
.get(url
, headers
=self
.headers_req
) as response
:
369 response_text
= await response
.read()
370 self
.logger
.debug("GET {} [{}] {}".format(url
, response
.status
, response_text
[:100]))
371 if response
.status
>= 300:
372 raise ROClientException(response_text
, http_code
=response
.status
)
374 return self
._parse
_yaml
(response_text
, response
=True)
376 async def _get_tenant(self
, session
):
378 self
.tenant
= await self
._get
_item
_uuid
(session
, "tenants", self
.tenant_id_name
, None)
381 async def _get_datacenter(self
, session
):
383 await self
._get
_tenant
(session
)
384 if not self
.datacenter
:
385 self
.datacenter
= await self
._get
_item
_uuid
(session
, "datacenters", self
.datacenter_id_name
, True)
386 return self
.datacenter
388 async def _create_item(self
, session
, item
, descriptor
, all_tenants
=False):
391 elif all_tenants
is None:
395 await self
._get
_tenant
(session
)
396 tenant_text
= "/" + self
.tenant
397 payload_req
= yaml
.safe_dump(descriptor
)
399 api_version_text
= ""
401 # assumes version v3 only
402 api_version_text
= "/v3"
404 elif item
== "scenarios":
405 # assumes version v3 only
406 api_version_text
= "/v3"
411 url
= "{}{apiver}{tenant}/{item}".format(self
.endpoint_url
, apiver
=api_version_text
, tenant
=tenant_text
,
413 self
.logger
.debug("openmano POST %s %s", url
, payload_req
)
414 with aiohttp
.Timeout(self
.timeout_large
):
415 async with session
.post(url
, headers
=self
.headers_req
, data
=payload_req
) as response
:
416 response_text
= await response
.read()
417 self
.logger
.debug("POST {} [{}] {}".format(url
, response
.status
, response_text
[:100]))
418 if response
.status
>= 300:
419 raise ROClientException(response_text
, http_code
=response
.status
)
421 response_desc
= self
._parse
_yaml
(response_text
, response
=True)
422 desc
, _
= remove_envelop(item
, response_desc
)
425 async def _del_item(self
, session
, item
, item_id_name
, all_tenants
=False):
428 elif all_tenants
is None:
432 await self
._get
_tenant
(session
)
433 tenant_text
= "/" + self
.tenant
434 if not self
.check_if_uuid(item_id_name
):
436 uuid
= await self
._get
_item
_uuid
(session
, item
, item_id_name
, all_tenants
)
440 url
= "{}{}/{}/{}".format(self
.endpoint_url
, tenant_text
, item
, uuid
)
441 self
.logger
.debug("DELETE %s", url
)
442 with aiohttp
.Timeout(self
.timeout_short
):
443 async with session
.delete(url
, headers
=self
.headers_req
) as response
:
444 response_text
= await response
.read()
445 self
.logger
.debug("DELETE {} [{}] {}".format(url
, response
.status
, response_text
[:100]))
446 if response
.status
>= 300:
447 raise ROClientException(response_text
, http_code
=response
.status
)
448 return self
._parse
_yaml
(response_text
, response
=True)
450 async def _list_item(self
, session
, item
, all_tenants
=False, filter_dict
=None):
453 elif all_tenants
is None:
457 await self
._get
_tenant
(session
)
458 tenant_text
= "/" + self
.tenant
460 url
= "{}{}/{}".format(self
.endpoint_url
, tenant_text
, item
)
463 for k
in filter_dict
:
464 url
+= separator
+ quote(str(k
)) + "=" + quote(str(filter_dict
[k
]))
466 self
.logger
.debug("openmano GET %s", url
)
467 with aiohttp
.Timeout(self
.timeout_short
):
468 async with session
.get(url
, headers
=self
.headers_req
) as response
:
469 response_text
= await response
.read()
470 self
.logger
.debug("GET {} [{}] {}".format(url
, response
.status
, response_text
[:100]))
471 if response
.status
>= 300:
472 raise ROClientException(response_text
, http_code
=response
.status
)
473 return self
._parse
_yaml
(response_text
, response
=True)
475 async def _edit_item(self
, session
, item
, descriptor
, item_id_name
, all_tenants
=False):
478 elif all_tenants
is None:
482 await self
._get
_tenant
(session
)
483 tenant_text
= "/" + self
.tenant
487 uuid
= self
._get
_item
_uuid
(session
, "tenants", item_id_name
, all_tenants
)
489 payload_req
= yaml
.safe_dump(descriptor
)
493 url
= "{}{}/{}/{}".format(self
.endpoint_url
, tenant_text
, item
, uuid
)
494 self
.logger
.debug("openmano PUT %s %s", url
, payload_req
)
495 with aiohttp
.Timeout(self
.timeout_large
):
496 async with session
.put(url
, headers
=self
.headers_req
, data
=payload_req
) as response
:
497 response_text
= await response
.read()
498 self
.logger
.debug("PUT {} [{}] {}".format(url
, response
.status
, response_text
[:100]))
499 if response
.status
>= 300:
500 raise ROClientException(response_text
, http_code
=response
.status
)
501 return self
._parse
_yaml
(response_text
, response
=True)
503 async def show(self
, item
, item_id_name
=None, all_tenants
=False):
505 Obtain the information of an item from its id or name
506 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
507 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
508 :param all_tenants: True if not filtering by tenant. Only allowed for admin
509 :return: dictionary with the information or raises ROClientException on Error, NotFound, found several
511 if item
not in self
.client_to_RO
:
512 raise ROClientException("Invalid item {}".format(item
))
516 with aiohttp
.ClientSession(loop
=self
.loop
) as session
:
517 content
= await self
._get
_item
(session
, self
.client_to_RO
[item
], item_id_name
, all_tenants
=all_tenants
)
518 if len(content
) == 1:
519 return content
.values()[0]
523 async def delete(self
, item
, item_id_name
=None, all_tenants
=False):
525 Delete the information of an item from its id or name
526 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
527 :param item_id_name: RO id or name of the item. Raise and exception if more than one found
528 :param all_tenants: True if not filtering by tenant. Only allowed for admin
529 :return: dictionary with the information or raises ROClientException on Error, NotFound, found several
531 if item
not in self
.client_to_RO
:
532 raise ROClientException("Invalid item {}".format(item
))
536 with aiohttp
.ClientSession(loop
=self
.loop
) as session
:
539 item_id
= await self
._get
_item
_uuid
(session
, "datacenters", item_id_name
, all_tenants
=True)
541 return await self
._del
_item
(session
, self
.client_to_RO
[item
], item_id_name
, all_tenants
=all_tenants
)
543 async def create(self
, item
, descriptor
=None, descriptor_format
=None, **kwargs
):
545 Creates an item from its descriptor
546 :param item: can be 'tenant', 'vim', 'vnfd', 'nsd', 'ns'
547 :param descriptor: can be a dict, or a yaml/json text. Autodetect unless descriptor_format is provided
548 :param descriptor_format: Can be 'json' or 'yaml'
549 :param kwargs: Overrides descriptor with values as name, description, vim_url, vim_url_admin, vim_type
550 keys can be a dot separated list to specify elements inside dict
551 :return: dictionary with the information or raises ROClientException on Error
553 if isinstance(descriptor
, str):
554 descriptor
= self
._parse
(descriptor
, descriptor_format
)
560 if item
not in self
.client_to_RO
:
561 raise ROClientException("Invalid item {}".format(item
))
562 desc
, enveloped
= remove_envelop(item
, descriptor
)
564 # Override descriptor with kwargs
567 for k
, v
in kwargs
.items():
568 update_content
= desc
572 if kitem_old
is not None:
573 update_content
= update_content
[kitem_old
]
574 if isinstance(update_content
, dict):
576 elif isinstance(update_content
, list):
577 kitem_old
= int(kitem
)
579 raise ROClientException(
580 "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k
, kitem
))
581 update_content
[kitem_old
] = v
583 raise ROClientException(
584 "Invalid query string '{}'. Descriptor does not contain '{}'".format(k
, kitem_old
))
586 raise ROClientException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
589 raise ROClientException(
590 "Invalid query string '{}'. Index '{}' out of range".format(k
, kitem_old
))
592 for mandatory
in self
.mandatory_for_create
[item
]:
593 if mandatory
not in desc
:
594 raise ROClientException("'{}' is mandatory parameter for {}".format(mandatory
, item
))
597 if item
in ('tenant', 'vim'):
601 create_desc
= self
._create
_envelop
(item
, desc
)
603 create_desc
= descriptor
605 with aiohttp
.ClientSession(loop
=self
.loop
) as session
:
606 return await self
._create
_item
(session
, self
.client_to_RO
[item
], create_desc
, all_tenants
)
608 def edit_tenant(self
, uuid
=None, name
=None, descriptor
=None, descriptor_format
=None, new_name
=None, new_description
=None):
609 """Edit the parameters of a tenant
610 Params: must supply a descriptor or/and a new_name or new_description
611 uuid or/and name. If only name is supplied, there must be only one or an exception is raised
612 descriptor: with format {'tenant':{params to change info}}
613 must be a dictionary or a json/yaml text.
614 name: the tenant name. Overwrite descriptor name if any
615 description: tenant descriptor.. Overwrite descriptor description if any
616 Return: Raises an exception on error, not found or found several
617 Obtain a dictionary with format {'tenant':{newtenant_info}}
620 if isinstance(descriptor
, str):
621 descriptor
= self
.parse(descriptor
, descriptor_format
)
624 elif new_name
or new_description
:
625 descriptor
={"tenant": {}}
627 raise ROClientException("Missing descriptor")
629 if 'tenant' not in descriptor
or len(descriptor
)!=1:
630 raise ROClientException("Descriptor must contain only one 'tenant' field")
632 descriptor
['tenant']['name'] = new_name
634 descriptor
['tenant']['description'] = new_description
636 return self
._edit
_item
("tenants", descriptor
, uuid
, name
, all_tenants
=None)
640 def edit_datacenter(self
, uuid
=None, name
=None, descriptor
=None, descriptor_format
=None, all_tenants
=False, **kwargs
):
641 """Edit the parameters of a datacenter
642 Params: must supply a descriptor or/and a parameter to change
643 uuid or/and name. If only name is supplied, there must be only one or an exception is raised
644 descriptor: with format {'datacenter':{params to change info}}
645 must be a dictionary or a json/yaml text.
646 parameters to change can be supplyied by the descriptor or as parameters:
647 new_name: the datacenter name
648 vim_url: the datacenter URL
649 vim_url_admin: the datacenter URL for administrative issues
650 vim_type: the datacenter type, can be openstack or openvim.
651 public: boolean, available to other tenants
652 description: datacenter description
653 Return: Raises an exception on error, not found or found several
654 Obtain a dictionary with format {'datacenter':{new_datacenter_info}}
657 if isinstance(descriptor
, str):
658 descriptor
= self
.parse(descriptor
, descriptor_format
)
662 descriptor
={"datacenter": {}}
664 raise ROClientException("Missing descriptor")
666 if 'datacenter' not in descriptor
or len(descriptor
)!=1:
667 raise ROClientException("Descriptor must contain only one 'datacenter' field")
669 if param
=='new_name':
670 descriptor
['datacenter']['name'] = kwargs
[param
]
672 descriptor
['datacenter'][param
] = kwargs
[param
]
673 return self
._edit
_item
("datacenters", descriptor
, uuid
, name
, all_tenants
=None)
675 def attach_datacenter(self
, uuid_name
=None, descriptor
=None, descriptor_format
=None, vim_user
=None, vim_password
=None, vim_tenant_name
=None, vim_tenant_id
=None):
677 uuid
= self
._get
_item
_uuid
(session
, "datacenters", uuid_name
, all_tenants
=True)
678 tenant_text
= "/"+self
._get
_tenant
()
680 if isinstance(descriptor
, str):
681 descriptor
= self
.parse(descriptor
, descriptor_format
)
684 elif vim_user
or vim_password
or vim_tenant_name
or vim_tenant_id
:
685 descriptor
={"datacenter": {}}
687 raise ROClientException("Missing descriptor or params")
689 if vim_user
or vim_password
or vim_tenant_name
or vim_tenant_id
:
693 descriptor
['datacenter']['vim_user'] = vim_user
695 descriptor
['datacenter']['vim_password'] = vim_password
697 descriptor
['datacenter']['vim_tenant_name'] = vim_tenant_name
699 descriptor
['datacenter']['vim_tenant'] = vim_tenant_id
700 except (KeyError, TypeError) as e
:
701 if str(e
)=='datacenter': error_pos
= "missing field 'datacenter'"
702 else: error_pos
="wrong format"
703 raise ROClientException("Wrong datacenter descriptor: " + error_pos
)
705 payload_req
= yaml
.safe_dump(descriptor
)
707 url
= "{}{}/datacenters/{}".format(self
.endpoint_url
, tenant_text
, uuid
)
708 self
.logger
.debug("openmano POST %s %s", url
, payload_req
)
709 mano_response
= requests
.post(url
, headers
= self
.headers_req
, data
=payload_req
)
710 self
.logger
.debug("openmano response: %s", mano_response
.text
)
712 content
= self
._parse
_yaml
(mano_response
.text
, response
=True)
713 if mano_response
.status_code
==200:
716 raise ROClientException(str(content
), http_code
=mano_response
.status
)
718 def detach_datacenter(self
, uuid_name
=None):
721 uuid
= self
._get
_item
_uuid
(session
, "datacenters", uuid_name
, all_tenants
=False)
722 tenant_text
= "/"+self
._get
_tenant
()
723 url
= "{}{}/datacenters/{}".format(self
.endpoint_url
, tenant_text
, uuid
)
724 self
.logger
.debug("openmano DELETE %s", url
)
725 mano_response
= requests
.delete(url
, headers
= self
.headers_req
)
726 self
.logger
.debug("openmano response: %s", mano_response
.text
)
728 content
= self
._parse
_yaml
(mano_response
.text
, response
=True)
729 if mano_response
.status_code
==200:
732 raise ROClientException(str(content
), http_code
=mano_response
.status
)
736 def edit_scenario(self
, uuid
=None, name
=None, descriptor
=None, descriptor_format
=None, all_tenants
=False, **kwargs
):
737 """Edit the parameters of a scenario
738 Params: must supply a descriptor or/and a parameters to change
739 uuid or/and name. If only name is supplied, there must be only one or an exception is raised
740 descriptor: with format {'scenario':{params to change info}}
741 must be a dictionary or a json/yaml text.
742 parameters to change can be supplyied by the descriptor or as parameters:
743 new_name: the scenario name
744 public: boolean, available to other tenants
745 description: scenario description
746 tenant_id. Propietary tenant
747 Return: Raises an exception on error, not found or found several
748 Obtain a dictionary with format {'scenario':{new_scenario_info}}
751 if isinstance(descriptor
, str):
752 descriptor
= self
.parse(descriptor
, descriptor_format
)
756 descriptor
={"scenario": {}}
758 raise ROClientException("Missing descriptor")
760 if 'scenario' not in descriptor
or len(descriptor
)>2:
761 raise ROClientException("Descriptor must contain only one 'scenario' field")
763 if param
=='new_name':
764 descriptor
['scenario']['name'] = kwargs
[param
]
766 descriptor
['scenario'][param
] = kwargs
[param
]
767 return self
._edit
_item
("scenarios", descriptor
, uuid
, name
, all_tenants
=None)
770 def vim_action(self
, action
, item
, uuid
=None, all_tenants
=False, **kwargs
):
771 """Perform an action over a vim
773 action: can be 'list', 'get'/'show', 'delete' or 'create'
774 item: can be 'tenants' or 'networks'
775 uuid: uuid of the tenant/net to show or to delete. Ignore otherwise
777 datacenter_name, datacenter_id: datacenters to act on, if missing uses classes store datacenter
778 descriptor, descriptor_format: descriptor needed on creation, can be a dict or a yaml/json str
779 must be a dictionary or a json/yaml text.
780 name: for created tenant/net Overwrite descriptor name if any
781 description: tenant descriptor. Overwrite descriptor description if any
783 Return: Raises an exception on error
784 Obtain a dictionary with format {'tenant':{new_tenant_info}}
786 if item
not in ("tenants", "networks", "images"):
787 raise ROClientException("Unknown value for item '{}', must be 'tenants', 'nets' or "
788 "images".format(str(item
)))
790 image_actions
= ['list','get','show','delete']
791 if item
== "images" and action
not in image_actions
:
792 raise ROClientException("Only available actions for item '{}' are {}\n"
793 "Requested action was '{}'".format(item
, ', '.join(image_actions
), action
))
797 tenant_text
= "/"+self
._get
_tenant
()
799 if "datacenter_id" in kwargs
or "datacenter_name" in kwargs
:
800 datacenter
= self
._get
_item
_uuid
(session
, "datacenters", kwargs
.get("datacenter"), all_tenants
=all_tenants
)
802 datacenter
= self
.get_datacenter(session
)
805 url
= "{}{}/vim/{}/{}".format(self
.endpoint_url
, tenant_text
, datacenter
, item
)
806 self
.logger
.debug("GET %s", url
)
807 mano_response
= requests
.get(url
, headers
=self
.headers_req
)
808 self
.logger
.debug("openmano response: %s", mano_response
.text
)
809 content
= self
._parse
_yaml
(mano_response
.text
, response
=True)
810 if mano_response
.status_code
==200:
813 raise ROClientException(str(content
), http_code
=mano_response
.status
)
814 elif action
=="get" or action
=="show":
815 url
= "{}{}/vim/{}/{}/{}".format(self
.endpoint_url
, tenant_text
, datacenter
, item
, uuid
)
816 self
.logger
.debug("GET %s", url
)
817 mano_response
= requests
.get(url
, headers
=self
.headers_req
)
818 self
.logger
.debug("openmano response: %s", mano_response
.text
)
819 content
= self
._parse
_yaml
(mano_response
.text
, response
=True)
820 if mano_response
.status_code
==200:
823 raise ROClientException(str(content
), http_code
=mano_response
.status
)
824 elif action
=="delete":
825 url
= "{}{}/vim/{}/{}/{}".format(self
.endpoint_url
, tenant_text
, datacenter
, item
, uuid
)
826 self
.logger
.debug("DELETE %s", url
)
827 mano_response
= requests
.delete(url
, headers
=self
.headers_req
)
828 self
.logger
.debug("openmano response: %s", mano_response
.text
)
829 content
= self
._parse
_yaml
(mano_response
.text
, response
=True)
830 if mano_response
.status_code
==200:
833 raise ROClientException(str(content
), http_code
=mano_response
.status
)
834 elif action
=="create":
835 if "descriptor" in kwargs
:
836 if isinstance(kwargs
["descriptor"], str):
837 descriptor
= self
._parse
(kwargs
["descriptor"], kwargs
.get("descriptor_format") )
839 descriptor
= kwargs
["descriptor"]
840 elif "name" in kwargs
:
841 descriptor
={item
[:-1]: {"name": kwargs
["name"]}}
843 raise ROClientException("Missing descriptor")
845 if item
[:-1] not in descriptor
or len(descriptor
)!=1:
846 raise ROClientException("Descriptor must contain only one 'tenant' field")
848 descriptor
[ item
[:-1] ]['name'] = kwargs
["name"]
849 if "description" in kwargs
:
850 descriptor
[ item
[:-1] ]['description'] = kwargs
["description"]
851 payload_req
= yaml
.safe_dump(descriptor
)
853 url
= "{}{}/vim/{}/{}".format(self
.endpoint_url
, tenant_text
, datacenter
, item
)
854 self
.logger
.debug("openmano POST %s %s", url
, payload_req
)
855 mano_response
= requests
.post(url
, headers
= self
.headers_req
, data
=payload_req
)
856 self
.logger
.debug("openmano response: %s", mano_response
.text
)
857 content
= self
._parse
_yaml
(mano_response
.text
, response
=True)
858 if mano_response
.status_code
==200:
861 raise ROClientException(str(content
), http_code
=mano_response
.status
)
863 raise ROClientException("Unknown value for action '{}".format(str(action
)))
866 if __name__
== '__main__':
867 RO_URL
= "http://localhost:9090/openmano"
868 RO_TENANT
= "2c94f639-cefc-4f3a-a8f9-bbab0471946a"
869 RO_VIM
= "3e70deb6-aea1-11e7-af13-080027429aaf"
871 streamformat
= "%(asctime)s %(name)s %(levelname)s: %(message)s"
872 logging
.basicConfig(format
=streamformat
)
874 loop
= asyncio
.get_event_loop()
875 myClient
= ROClient(endpoint_url
=RO_URL
, loop
=loop
, tenant_id
=RO_TENANT
, datacenter_id
=RO_VIM
, debug
=True)
876 content
= loop
.run_until_complete(myClient
.list_tenants())