-
- # TODO convert to asyncio
- # DATACENTERS
-
- def edit_datacenter(
- self,
- uuid=None,
- name=None,
- descriptor=None,
- descriptor_format=None,
- all_tenants=False,
- **kwargs
- ):
- """Edit the parameters of a datacenter
- Params: must supply a descriptor or/and a parameter to change
- uuid or/and name. If only name is supplied, there must be only one or an exception is raised
- descriptor: with format {'datacenter':{params to change info}}
- must be a dictionary or a json/yaml text.
- parameters to change can be supplyied by the descriptor or as parameters:
- new_name: the datacenter name
- vim_url: the datacenter URL
- vim_url_admin: the datacenter URL for administrative issues
- vim_type: the datacenter type, can be openstack or openvim.
- public: boolean, available to other tenants
- description: datacenter description
- Return: Raises an exception on error, not found or found several
- Obtain a dictionary with format {'datacenter':{new_datacenter_info}}
- """
-
- if isinstance(descriptor, str):
- descriptor = self.parse(descriptor, descriptor_format)
- elif descriptor:
- pass
- elif kwargs:
- descriptor = {"datacenter": {}}
- else:
- raise ROClientException("Missing descriptor")
-
- if "datacenter" not in descriptor or len(descriptor) != 1:
- raise ROClientException(
- "Descriptor must contain only one 'datacenter' field"
- )
- for param in kwargs:
- if param == "new_name":
- descriptor["datacenter"]["name"] = kwargs[param]
- else:
- descriptor["datacenter"][param] = kwargs[param]
- return self._edit_item("datacenters", descriptor, uuid, name, all_tenants=None)
-
- def edit_scenario(
- self,
- uuid=None,
- name=None,
- descriptor=None,
- descriptor_format=None,
- all_tenants=False,
- **kwargs
- ):
- """Edit the parameters of a scenario
- Params: must supply a descriptor or/and a parameters to change
- uuid or/and name. If only name is supplied, there must be only one or an exception is raised
- descriptor: with format {'scenario':{params to change info}}
- must be a dictionary or a json/yaml text.
- parameters to change can be supplyied by the descriptor or as parameters:
- new_name: the scenario name
- public: boolean, available to other tenants
- description: scenario description
- tenant_id. Propietary tenant
- Return: Raises an exception on error, not found or found several
- Obtain a dictionary with format {'scenario':{new_scenario_info}}
- """
-
- if isinstance(descriptor, str):
- descriptor = self.parse(descriptor, descriptor_format)
- elif descriptor:
- pass
- elif kwargs:
- descriptor = {"scenario": {}}
- else:
- raise ROClientException("Missing descriptor")
-
- if "scenario" not in descriptor or len(descriptor) > 2:
- raise ROClientException("Descriptor must contain only one 'scenario' field")
- for param in kwargs:
- if param == "new_name":
- descriptor["scenario"]["name"] = kwargs[param]
- else:
- descriptor["scenario"][param] = kwargs[param]
- return self._edit_item("scenarios", descriptor, uuid, name, all_tenants=None)
-
- # VIM ACTIONS
- def vim_action(self, action, item, uuid=None, all_tenants=False, **kwargs):
- """Perform an action over a vim
- Params:
- action: can be 'list', 'get'/'show', 'delete' or 'create'
- item: can be 'tenants' or 'networks'
- uuid: uuid of the tenant/net to show or to delete. Ignore otherwise
- other parameters:
- datacenter_name, datacenter_id: datacenters to act on, if missing uses classes store datacenter
- descriptor, descriptor_format: descriptor needed on creation, can be a dict or a yaml/json str
- must be a dictionary or a json/yaml text.
- name: for created tenant/net Overwrite descriptor name if any
- description: tenant descriptor. Overwrite descriptor description if any
-
- Return: Raises an exception on error
- Obtain a dictionary with format {'tenant':{new_tenant_info}}
- """
- session = None # TODO remove when changed to asyncio
- if item not in ("tenants", "networks", "images"):
- raise ROClientException(
- "Unknown value for item '{}', must be 'tenants', 'nets' or "
- "images".format(str(item))
- )
-
- image_actions = ["list", "get", "show", "delete"]
- if item == "images" and action not in image_actions:
- raise ROClientException(
- "Only available actions for item '{}' are {}\n"
- "Requested action was '{}'".format(
- item, ", ".join(image_actions), action
- )
- )
- if all_tenants:
- tenant_text = "/any"
- else:
- tenant_text = "/" + self._get_tenant()
-
- if "datacenter_id" in kwargs or "datacenter_name" in kwargs:
- datacenter = self._get_item_uuid(
- session,
- "datacenters",
- kwargs.get("datacenter"),
- all_tenants=all_tenants,
- )
- else:
- datacenter = self.get_datacenter(session)
-
- if action == "list":
- url = "{}{}/vim/{}/{}".format(self.uri, tenant_text, datacenter, item)
- self.logger.debug("GET %s", url)
- mano_response = requests.get(url, headers=self.headers_req)
- self.logger.debug("RO response: %s", mano_response.text)
- content = self._parse_yaml(mano_response.text, response=True)
- if mano_response.status_code == 200:
- return content
- else:
- raise ROClientException(str(content), http_code=mano_response.status)
- elif action == "get" or action == "show":
- url = "{}{}/vim/{}/{}/{}".format(
- self.uri, tenant_text, datacenter, item, uuid
- )
- self.logger.debug("GET %s", url)
- mano_response = requests.get(url, headers=self.headers_req)
- self.logger.debug("RO response: %s", mano_response.text)
- content = self._parse_yaml(mano_response.text, response=True)
- if mano_response.status_code == 200:
- return content
- else:
- raise ROClientException(str(content), http_code=mano_response.status)
- elif action == "delete":
- url = "{}{}/vim/{}/{}/{}".format(
- self.uri, tenant_text, datacenter, item, uuid
- )
- self.logger.debug("DELETE %s", url)
- mano_response = requests.delete(url, headers=self.headers_req)
- self.logger.debug("RO response: %s", mano_response.text)
- content = self._parse_yaml(mano_response.text, response=True)
- if mano_response.status_code == 200:
- return content
- else:
- raise ROClientException(str(content), http_code=mano_response.status)
- elif action == "create":
- if "descriptor" in kwargs:
- if isinstance(kwargs["descriptor"], str):
- descriptor = self._parse(
- kwargs["descriptor"], kwargs.get("descriptor_format")
- )
- else:
- descriptor = kwargs["descriptor"]
- elif "name" in kwargs:
- descriptor = {item[:-1]: {"name": kwargs["name"]}}
- else:
- raise ROClientException("Missing descriptor")
-
- if item[:-1] not in descriptor or len(descriptor) != 1:
- raise ROClientException(
- "Descriptor must contain only one 'tenant' field"
- )
- if "name" in kwargs:
- descriptor[item[:-1]]["name"] = kwargs["name"]
- if "description" in kwargs:
- descriptor[item[:-1]]["description"] = kwargs["description"]
- payload_req = yaml.safe_dump(descriptor)
- # print payload_req
- url = "{}{}/vim/{}/{}".format(self.uri, tenant_text, datacenter, item)
- self.logger.debug("RO POST %s %s", url, payload_req)
- mano_response = requests.post(
- url, headers=self.headers_req, data=payload_req
- )
- self.logger.debug("RO response: %s", mano_response.text)
- content = self._parse_yaml(mano_response.text, response=True)
- if mano_response.status_code == 200:
- return content
- else:
- raise ROClientException(str(content), http_code=mano_response.status)
- else:
- raise ROClientException("Unknown value for action '{}".format(str(action)))
-
-
-if __name__ == "__main__":
- RO_URL = "http://localhost:9090/openmano"
- TEST_TENANT = "myTenant"
- TEST_VIM1 = "myvim"
- TEST_URL1 = "https://localhost:5000/v1"
- TEST_TYPE1 = "openstack"
- TEST_CONFIG1 = {"use_floating_ip": True}
- TEST_VIM2 = "myvim2"
- TEST_URL2 = "https://localhost:5000/v2"
- TEST_TYPE2 = "openvim"
- TEST_CONFIG2 = {"config2": "config2", "config3": True}
-
- streamformat = "%(asctime)s %(name)s %(levelname)s: %(message)s"
- logging.basicConfig(format=streamformat)
- logger = logging.getLogger("ROClient")
-
- tenant_id = None
- vim_id = False
- loop = asyncio.get_event_loop()
- myClient = ROClient(uri=RO_URL, loop=loop, loglevel="DEBUG")
- try:
- # test tenant
- content = loop.run_until_complete(myClient.get_list("tenant"))
- print("tenants", content)
- content = loop.run_until_complete(myClient.create("tenant", name=TEST_TENANT))
- tenant_id = True
- content = loop.run_until_complete(myClient.show("tenant", TEST_TENANT))
- print("tenant", TEST_TENANT, content)
- content = loop.run_until_complete(
- myClient.edit("tenant", TEST_TENANT, description="another description")
- )
- content = loop.run_until_complete(myClient.show("tenant", TEST_TENANT))
- print("tenant edited", TEST_TENANT, content)
- myClient["tenant"] = TEST_TENANT
-
- # test VIM
- content = loop.run_until_complete(
- myClient.create(
- "vim",
- name=TEST_VIM1,
- type=TEST_TYPE1,
- vim_url=TEST_URL1,
- config=TEST_CONFIG1,
- )
- )
- vim_id = True
- content = loop.run_until_complete(myClient.get_list("vim"))
- print("vim", content)
- content = loop.run_until_complete(myClient.show("vim", TEST_VIM1))
- print("vim", TEST_VIM1, content)
- content = loop.run_until_complete(
- myClient.edit(
- "vim",
- TEST_VIM1,
- description="another description",
- name=TEST_VIM2,
- type=TEST_TYPE2,
- vim_url=TEST_URL2,
- config=TEST_CONFIG2,
- )
- )
- content = loop.run_until_complete(myClient.show("vim", TEST_VIM2))
- print("vim edited", TEST_VIM2, content)
-
- # test VIM_ACCOUNT
- content = loop.run_until_complete(
- myClient.attach_datacenter(
- TEST_VIM2,
- vim_username="user",
- vim_password="pass",
- vim_tenant_name="vimtenant1",
- config=TEST_CONFIG1,
- )
- )
- vim_id = True
- content = loop.run_until_complete(myClient.get_list("vim_account"))
- print("vim_account", content)
- content = loop.run_until_complete(myClient.show("vim_account", TEST_VIM2))
- print("vim_account", TEST_VIM2, content)
- content = loop.run_until_complete(
- myClient.edit(
- "vim_account",
- TEST_VIM2,
- vim_username="user2",
- vim_password="pass2",
- vim_tenant_name="vimtenant2",
- config=TEST_CONFIG2,
- )
- )
- content = loop.run_until_complete(myClient.show("vim_account", TEST_VIM2))
- print("vim_account edited", TEST_VIM2, content)
-
- myClient["vim"] = TEST_VIM2
-
- except Exception as e:
- logger.error("Error {}".format(e), exc_info=True)
-
- for item in (
- ("vim_account", TEST_VIM1),
- ("vim", TEST_VIM1),
- ("vim_account", TEST_VIM2),
- ("vim", TEST_VIM2),
- ("tenant", TEST_TENANT),
- ):
- try:
- content = loop.run_until_complete(myClient.delete(item[0], item[1]))
- print("{} {} deleted; {}".format(item[0], item[1], content))
- except Exception as e:
- if e.http_code == 404:
- print("{} {} not present or already deleted".format(item[0], item[1]))
- else:
- logger.error("Error {}".format(e), exc_info=True)
-
- loop.close()