update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / models / openmano / python / rift / openmano / openmano_client.py
index bd34be1..248c7ff 100755 (executable)
@@ -92,11 +92,148 @@ class OpenmanoHttpAPI(object):
 
         return None
 
+    def vnfs(self):
+        url = "http://{host}:{port}/openmano/{tenant}/vnfs".format(
+            host=self._host,
+            port=self._port,
+            tenant=self._tenant
+            )
+        resp = self._session.get(url, headers={'content-type': 'application/json'})
+        
+        try:
+            resp.raise_for_status()
+        except requests.exceptions.HTTPError as e:
+            raise InstanceStatusError(e)
+
+        return resp.json()
+
+    def vnf(self, vnf_id):
+        vnf_uuid = None
+        try:
+            vnfs = self.vnfs()
+            for vnf in vnfs["vnfs"]:
+                # Rift vnf ID gets mapped to osm_id in OpenMano
+                if vnf_id == vnf["osm_id"]:
+                    vnf_uuid = vnf["uuid"]
+                    break
+        except Exception as e:
+            raise e    
+
+        if not vnf_uuid:
+            return None
+        else:
+            url = "http://{host}:{port}/openmano/{tenant}/vnfs/{uuid}".format(
+                host=self._host,
+                port=self._port,
+                tenant=self._tenant,
+                uuid=vnf_uuid
+                )
+            resp = self._session.get(url, headers={'content-type': 'application/json'})
+        
+            try:
+                resp.raise_for_status()
+            except requests.exceptions.HTTPError as e:
+                raise InstanceStatusError(e)
+
+            return resp.json()['vnf']
+
+    def scenarios(self):
+        url = "http://{host}:{port}/openmano/{tenant}/scenarios".format(
+            host=self._host,
+            port=self._port,
+            tenant=self._tenant
+            )
+        resp = self._session.get(url, headers={'content-type': 'application/json'})
+        
+        try:
+            resp.raise_for_status()
+        except requests.exceptions.HTTPError as e:
+            raise InstanceStatusError(e)
+
+        return resp.json()
+
+    def scenario(self, scenario_id):
+        scenario_uuid = None
+        try:
+            scenarios = self.scenarios()
+            for scenario in scenarios["scenarios"]:
+                # Rift NS ID gets mapped to osm_id in OpenMano
+                if scenario_id == scenario["osm_id"]:
+                    scenario_uuid = scenario["uuid"]
+                    break
+        except Exception as e:
+            raise e    
+
+        if not scenario_uuid:
+            return None
+        else:
+            url = "http://{host}:{port}/openmano/{tenant}/scenarios/{uuid}".format(
+                host=self._host,
+                port=self._port,
+                tenant=self._tenant,
+                uuid=scenario_uuid
+                )
+            resp = self._session.get(url, headers={'content-type': 'application/json'})
+        
+            try:
+                resp.raise_for_status()
+            except requests.exceptions.HTTPError as e:
+                raise InstanceStatusError(e)
+
+            return resp.json()['scenario']
+
+    def post_vnfd_v3(self, vnfd_body):
+        # Check if the VNF is present at the RO
+        vnf_rift_id = vnfd_body["vnfd:vnfd-catalog"]["vnfd"][0]["id"]
+        vnf_check = self.vnf(vnf_rift_id)
+        
+        if not vnf_check:  
+            url = "http://{host}:{port}/openmano/v3/{tenant}/vnfd".format(
+                host=self._host,
+                port=self._port,
+                tenant=self._tenant
+                )
+            payload_data = json.dumps(vnfd_body)
+            resp = self._session.post(url, headers={'content-type': 'application/json'},
+                                        data=payload_data)
+            try:
+                resp.raise_for_status()
+            except requests.exceptions.HTTPError as e:
+                raise InstanceStatusError(e)
+
+            return resp.json()['vnfd'][0]
+
+        else:
+            return vnf_check
+
+    def post_nsd_v3(self, nsd_body):
+        # Check if the NS (Scenario) is present at the RO
+        scenario_rift_id = nsd_body["nsd:nsd-catalog"]["nsd"][0]["id"]
+        scenario_check = self.scenario(scenario_rift_id)
+
+        if not scenario_check:   
+            url = "http://{host}:{port}/openmano/v3/{tenant}/nsd".format(
+                host=self._host,
+                port=self._port,
+                tenant=self._tenant
+                )
+            payload_data = json.dumps(nsd_body)
+            resp = self._session.post(url, headers={'content-type': 'application/json'},
+                                        data=payload_data)
+            try:
+                resp.raise_for_status()
+            except requests.exceptions.HTTPError as e:
+                raise InstanceStatusError(e)
+
+            return resp.json()['nsd'][0]
+        else:
+            return scenario_check        
+
 
 class OpenmanoCliAPI(object):
     """ This class implements the necessary funtionality to interact with  """
 
-    CMD_TIMEOUT = 30
+    CMD_TIMEOUT = 120
 
     def __init__(self, log, host, port, tenant):
         self._log = log
@@ -143,8 +280,8 @@ class OpenmanoCliAPI(object):
 
         if proc.returncode != 0:
             self._log.error(
-                    "Openmano command failed (rc=%s) with stdout: %s",
-                    proc.returncode, stdout
+                    "Openmano command %s failed (rc=%s) with stdout: %s",
+                    cmd_args[1], proc.returncode, stdout
                     )
             raise OpenmanoCommandFailed(stdout)
 
@@ -198,6 +335,7 @@ class OpenmanoCliAPI(object):
             output_lines = self._openmano_cmd(
                     ["vnf-list"],
                     )
+
         except OpenmanoCommandFailed as e:
             self._log.warning("Vnf listing returned an error: %s", str(e))
             return {}
@@ -206,8 +344,9 @@ class OpenmanoCliAPI(object):
         for line in output_lines:
             line = line.strip()
             uuid, name = line.split(" ", 1)
-            name_uuid_map[name] = uuid
+            name_uuid_map[name.strip()] = uuid.strip()
 
+        self._log.debug("VNF list: {}".format(name_uuid_map))
         return name_uuid_map
 
     def ns_create(self, ns_yaml_str, name=None):
@@ -249,8 +388,9 @@ class OpenmanoCliAPI(object):
         for line in output_lines:
             line = line.strip()
             uuid, name = line.split(" ", 1)
-            name_uuid_map[name] = uuid
+            name_uuid_map[name.strip()] = uuid.strip()
 
+        self._log.debug("Scenario list: {}".format(name_uuid_map))
         return name_uuid_map
 
     def ns_delete(self, ns_uuid):
@@ -282,8 +422,9 @@ class OpenmanoCliAPI(object):
         for line in output_lines:
             line = line.strip()
             uuid, name = line.split(" ", 1)
-            name_uuid_map[name] = uuid
+            name_uuid_map[name.strip()] = uuid.strip()
 
+        self._log.debug("Instance Scenario list: {}".format(name_uuid_map))
         return name_uuid_map
 
     def ns_instance_scenario_create(self, instance_yaml_str):
@@ -309,6 +450,44 @@ class OpenmanoCliAPI(object):
 
         return uuid
 
+
+    def ns_vim_network_create(self, net_create_yaml_str,datacenter_name):
+        """ Create a Openmano VIM network from input YAML string """
+
+        self._log.debug("Creating VIM network instance: %s, DC %s", net_create_yaml_str,datacenter_name)
+
+        with tempfile.NamedTemporaryFile() as net_create_file_hdl:
+            net_create_file_hdl.write(net_create_yaml_str.encode())
+            net_create_file_hdl.flush()
+
+            try:
+                output_lines = self._openmano_cmd(
+                        ["vim-net-create","--datacenter", datacenter_name, net_create_file_hdl.name],
+                        expected_lines=1
+                        )
+            except OpenmanoCommandFailed as e:
+                raise
+
+        uuid, _ = output_lines[0].split(" ", 1)
+
+        self._log.info("VIM Networks created in DC %s with ID: %s", datacenter_name, uuid)
+
+        return uuid
+
+    def ns_vim_network_delete(self, network_name,datacenter_name):
+        """ Delete a Openmano VIM network with given name """
+
+        self._log.debug("Deleting VIM network instance: %s, DC %s", network_name,datacenter_name)
+        try:
+            output_lines = self._openmano_cmd(
+                    ["vim-net-delete","--datacenter", datacenter_name, network_name],
+                    expected_lines=1
+                    )
+        except OpenmanoCommandFailed as e:
+            raise
+        self._log.info("VIM Network deleted in DC %s with name: %s", datacenter_name, network_name)
+
+
     def ns_instantiate(self, scenario_name, instance_name, datacenter_name=None):
         self._log.info(
                 "Instantiating NS %s using instance name %s",
@@ -428,6 +607,10 @@ def parse_args(argv=sys.argv[1:]):
             type=valid_uuid,
             )
 
+    _ = subparsers.add_parser(
+            'vnf-list',
+            help="List all the openmano VNFs in the catalog",
+            )
 
     ns_create_parser = subparsers.add_parser(
             'scenario-create',
@@ -449,6 +632,10 @@ def parse_args(argv=sys.argv[1:]):
             type=valid_uuid,
             )
 
+    _ = subparsers.add_parser(
+            'scenario-list',
+            help="List all the openmano scenarios in the catalog",
+            )
 
     ns_instance_create_parser = subparsers.add_parser(
             'scenario-deploy',
@@ -474,8 +661,14 @@ def parse_args(argv=sys.argv[1:]):
             )
 
 
+    _ = subparsers.add_parser(
+            'instance-scenario-list',
+            help="List all the openmano scenario instances in the catalog",
+            )
+
     _ = subparsers.add_parser(
             'datacenter-list',
+            help="List all the openmano datacenters",
             )
 
     args = parser.parse_args(argv)
@@ -500,18 +693,30 @@ def main():
     elif args.command == "vnf-delete":
         openmano_cli.vnf_delete(args.uuid)
 
+    elif args.command == "vnf-list":
+        for uuid, name in openmano_cli.vnf_list().items():
+            print("{} {}".format(uuid, name))
+
     elif args.command == "scenario-create":
         openmano_cli.ns_create(args.file.read())
 
     elif args.command == "scenario-delete":
         openmano_cli.ns_delete(args.uuid)
 
+    elif args.command == "scenario-list":
+        for uuid, name in openmano_cli.ns_list().items():
+            print("{} {}".format(uuid, name))
+
     elif args.command == "scenario-deploy":
         openmano_cli.ns_instantiate(args.scenario_name, args.instance_name)
 
     elif args.command == "instance-scenario-delete":
         openmano_cli.ns_terminate(args.instance_name)
 
+    elif args.command == "instance-scenario-list":
+        for uuid, name in openmano_cli.ns_instance_list().items():
+            print("{} {}".format(uuid, name))
+
     elif args.command == "datacenter-list":
         for uuid, name in openmano_cli.datacenter_list():
             print("{} {}".format(uuid, name))