Exemple #1
0
    def build(self,
              package_folder,
              skip_validation=False,
              skip_charm_build=False):
        """
            **Creates a .tar.gz file given a package_folder**

            :params:
                - package_folder: is the name of the folder to be packaged
                - skip_validation: is the flag to validate or not the descriptors on the folder before build

            :returns: message result for the build process
        """
        self._logger.debug("")
        package_folder = package_folder.rstrip('/')
        if not os.path.exists("{}".format(package_folder)):
            return "Fail, package is not in the specified path"
        if not skip_validation:
            print('Validating package {}'.format(package_folder))
            results = self.validate(package_folder, recursive=False)
            if results:
                for result in results:
                    if result["valid"] != "OK":
                        raise ClientException(
                            "There was an error validating the file {} with error: {}"
                            .format(result["path"], result["error"]))
                print('Validation OK')
            else:
                raise ClientException(
                    "No descriptor file found in: {}".format(package_folder))
        charm_list = self.build_all_charms(package_folder, skip_charm_build)
        return self.build_tarfile(package_folder, charm_list)
Exemple #2
0
 def create(self, pdu, update_endpoint=None):
     headers = self._client._headers
     headers['Content-Type'] = 'application/yaml'
     http_header = [
         '{}: {}'.format(key, val) for (key, val) in list(headers.items())
     ]
     self._http.set_http_header(http_header)
     if update_endpoint:
         http_code, resp = self._http.put_cmd(endpoint=update_endpoint,
                                              postfields_dict=pdu)
     else:
         endpoint = self._apiBase
         #endpoint = '{}{}'.format(self._apiBase,ow_string)
         http_code, resp = self._http.post_cmd(endpoint=endpoint,
                                               postfields_dict=pdu)
     #print 'HTTP CODE: {}'.format(http_code)
     #print 'RESP: {}'.format(resp)
     if http_code in (200, 201, 202, 204):
         if resp:
             resp = json.loads(resp)
         if not resp or 'id' not in resp:
             raise ClientException(
                 'unexpected response from server: '.format(resp))
         print(resp['id'])
     else:
         msg = "Error {}".format(http_code)
         if resp:
             try:
                 msg = "{} - {}".format(msg, json.loads(resp))
             except ValueError:
                 msg = "{} - {}".format(msg, resp)
         raise ClientException(
             "failed to create/update pdu - {}".format(msg))
Exemple #3
0
 def update(self, project, project_changes):
     """Updates an OSM project identified by name
     """
     proj = self.get(project)
     http_code, resp = self._http.put_cmd(endpoint='{}/{}'.format(
         self._apiBase, proj['_id']),
                                          postfields_dict=project_changes)
     # print('HTTP CODE: {}'.format(http_code))
     # print('RESP: {}'.format(resp))
     if http_code in (200, 201, 202):
         if resp:
             resp = json.loads(resp)
         if not resp or 'id' not in resp:
             raise ClientException(
                 'unexpected response from server - {}'.format(resp))
         print(resp['id'])
     elif http_code == 204:
         print("Updated")
     else:
         msg = ""
         if resp:
             try:
                 msg = json.loads(resp)
             except ValueError:
                 msg = resp
         raise ClientException("failed to update project {} - {}".format(
             project, msg))
Exemple #4
0
 def list_op(self, name, filter=None):
     """Returns the list of operations of a NSI
     """
     nsi = self.get(name)
     try:
         self._apiResource = '/nsi_lcm_op_occs'
         self._apiBase = '{}{}{}'.format(self._apiName, self._apiVersion,
                                         self._apiResource)
         filter_string = ''
         if filter:
             filter_string = '&{}'.format(filter)
         http_code, resp = self._http.get2_cmd(
             '{}?netsliceInstanceId={}'.format(self._apiBase, nsi['_id'],
                                               filter_string))
         #print 'HTTP CODE: {}'.format(http_code)
         #print 'RESP: {}'.format(resp)
         if http_code == 200:
             if resp:
                 resp = json.loads(resp)
                 return resp
             else:
                 raise ClientException('unexpected response from server')
         else:
             msg = ""
             if resp:
                 try:
                     resp = json.loads(resp)
                     msg = resp['detail']
                 except ValueError:
                     msg = resp
             raise ClientException(msg)
     except ClientException as exc:
         message = "failed to get operation list of NSI {}:\nerror:\n{}".format(
             name, exc.message)
         raise ClientException(message)
Exemple #5
0
 def scale_vnf(self, ns_name, vnf_name, scaling_group, scale_in, scale_out, wait=False, timeout=None):
     """Scales a VNF by adding/removing VDUs
     """
     self._logger.debug("")
     self._client.get_token()
     try:
         op_data={}
         op_data["scaleType"] = "SCALE_VNF"
         op_data["scaleVnfData"] = {}
         if scale_in and not scale_out:
             op_data["scaleVnfData"]["scaleVnfType"] = "SCALE_IN"
         elif not scale_in and scale_out:
             op_data["scaleVnfData"]["scaleVnfType"] = "SCALE_OUT"
         else:
             raise ClientException("you must set either 'scale_in' or 'scale_out'")
         op_data["scaleVnfData"]["scaleByStepData"] = {
             "member-vnf-index": vnf_name,
             "scaling-group-descriptor": scaling_group,
         }
         if timeout:
             op_data["timeout_ns_scale"] = timeout
         op_id = self.exec_op(ns_name, op_name='scale', op_data=op_data, wait=wait)
         print(str(op_id))
     except ClientException as exc:
         message="failed to scale vnf {} of ns {}:\nerror:\n{}".format(
                 vnf_name, ns_name, str(exc))
         raise ClientException(message)
Exemple #6
0
    def delete(self, ns_name, wait=True):
        vnfs = self.get_field(ns_name, 'constituent-vnfr-ref')

        resp = self._terminate(ns_name)
        if 'success' not in resp:
            raise ClientException("failed to delete ns {}".format(ns_name))

        # helper method to check if pkg exists
        def check_not_exists(func):
            try:
                func()
                return False
            except NotFound:
                return True

        for vnf in vnfs:
            if (not utils.wait_for_value(
                lambda:
                check_not_exists(lambda:
                                 self._client.vnf.get(vnf['vnfr-id'])))):
                raise ClientException(
                    "vnf {} failed to delete".format(vnf['vnfr-id']))
        if not utils.wait_for_value(lambda:
                                    check_not_exists(lambda:
                                                     self.get(ns_name))):
            raise ClientException("ns {} failed to delete".format(ns_name))
Exemple #7
0
 def get_op(self, operationId):
     """Returns the status of an operation
     """
     try:
         self._apiResource = '/nsi_lcm_op_occs'
         self._apiBase = '{}{}{}'.format(self._apiName, self._apiVersion,
                                         self._apiResource)
         http_code, resp = self._http.get2_cmd('{}/{}'.format(
             self._apiBase, operationId))
         #print 'HTTP CODE: {}'.format(http_code)
         #print 'RESP: {}'.format(resp)
         if http_code == 200:
             if resp:
                 resp = json.loads(resp)
                 return resp
             else:
                 raise ClientException('unexpected response from server')
         else:
             msg = ""
             if resp:
                 try:
                     resp = json.loads(resp)
                     msg = resp['detail']
                 except ValueError:
                     msg = resp
             raise ClientException(msg)
     except ClientException as exc:
         message = "failed to get status of operation {}:\nerror:\n{}".format(
             operationId, exc.message)
         raise ClientException(message)
Exemple #8
0
    def get_pkg(self, pkgtype, name, repo, filter, version):
        """
            Returns the filename of the PKG downloaded to disk
        """
        self._logger.debug("")
        self._client.get_token()
        f = None
        f_name = None
        # Get OSM registered repository list
        pkgs = self.pkg_list(pkgtype, filter, repo)
        for pkg in pkgs:
            if pkg.get('repository') == repo and pkg.get('name') == name:
                if 'latest' in version:
                    if not pkg.get('latest'):
                        continue
                    else:
                        version = pkg.get('version')
                if pkg.get('version') == version:
                    r = requests.get('{}{}'.format(pkg.get('repourl'),
                                                   pkg.get('location')),
                                     stream=True)
                    if r.status_code != 200:
                        raise ClientException("Package not found")

                    with tempfile.NamedTemporaryFile(delete=False) as f:
                        f.write(r.raw.read())
                        f_name = f.name
                    if not f_name:
                        raise ClientException(
                            "{} {} not found at repo {}".format(
                                pkgtype, name, repo))
        return f_name
Exemple #9
0
 def exec_op(self, name, op_name, op_data=None):
     """Executes an operation on a NSI
     """
     nsi = self.get(name)
     try:
         self._apiResource = '/netslice_instances'
         self._apiBase = '{}{}{}'.format(self._apiName, self._apiVersion,
                                         self._apiResource)
         endpoint = '{}/{}/{}'.format(self._apiBase, nsi['_id'], op_name)
         #print 'OP_NAME: {}'.format(op_name)
         #print 'OP_DATA: {}'.format(json.dumps(op_data))
         http_code, resp = self._http.post_cmd(endpoint=endpoint,
                                               postfields_dict=op_data)
         #print 'HTTP CODE: {}'.format(http_code)
         #print 'RESP: {}'.format(resp)
         if http_code in (200, 201, 202, 204):
             if resp:
                 resp = json.loads(resp)
             if not resp or 'id' not in resp:
                 raise ClientException(
                     'unexpected response from server - {}'.format(resp))
             print(resp['id'])
         else:
             msg = ""
             if resp:
                 try:
                     msg = json.loads(resp)
                 except ValueError:
                     msg = resp
             raise ClientException(msg)
     except ClientException as exc:
         message = "failed to exec operation {}:\nerror:\n{}".format(
             name, exc.message)
         raise ClientException(message)
Exemple #10
0
 def get_op(self, operationId):
     """Returns the status of an operation
     """
     self._logger.debug("")
     self._client.get_token()
     try:
         self._apiResource = '/ns_lcm_op_occs'
         self._apiBase = '{}{}{}'.format(self._apiName, self._apiVersion,
                                         self._apiResource)
         http_code, resp = self._http.get2_cmd('{}/{}'.format(
             self._apiBase, operationId))
         #print('HTTP CODE: {}'.format(http_code))
         #print('RESP: {}'.format(resp))
         if http_code == 200:
             if resp:
                 resp = json.loads(resp)
                 return resp
             else:
                 raise ClientException('unexpected response from server')
         else:
             msg = resp or ""
             #    if resp:
             #        try:
             #            resp = json.loads(resp)
             #            msg = resp['detail']
             #        except ValueError:
             #            msg = resp
             raise ClientException(msg)
     except ClientException as exc:
         message = "failed to get status of operation {}:\nerror:\n{}".format(
             operationId, str(exc))
         raise ClientException(message)
Exemple #11
0
 def delete_alarm(self, name):
     data = {}
     data["delete_alarm_request"] = {}
     data["delete_alarm_request"]["alarm_delete_request"] = {}
     data["delete_alarm_request"]["alarm_delete_request"][
         "alarm_uuid"] = name
     try:
         http_code, resp = self._http.post_cmd(
             endpoint='/test/message/alarm_request', postfields_dict=data)
         #print 'HTTP CODE: {}'.format(http_code)
         #print 'RESP: {}'.format(resp)
         if http_code in (200, 201, 202, 204):
             #resp = json.loads(resp)
             print('Alarm deleted')
         else:
             msg = ""
             if resp:
                 try:
                     msg = json.loads(resp)
                 except ValueError:
                     msg = resp
             raise ClientException('error: code: {}, resp: {}'.format(
                 http_code, msg))
     except ClientException as exc:
         message = "failed to delete alarm: alarm {}\n{}".format(
             name, exc.message)
         raise ClientException(message)
Exemple #12
0
 def create(self, filename, overwrite=None, update_endpoint=None):
     mime_type = magic.from_file(filename, mime=True)
     if mime_type is None:
         raise ClientException(
             "failed to guess MIME type for file '{}'".format(filename))
     headers = self._client._headers
     headers['Content-Filename'] = basename(filename)
     if mime_type in ['application/yaml', 'text/plain', 'application/json']:
         headers['Content-Type'] = 'text/plain'
     elif mime_type in ['application/gzip', 'application/x-gzip']:
         headers['Content-Type'] = 'application/gzip'
         #headers['Content-Type'] = 'application/binary'
         # Next three lines are to be removed in next version
         #headers['Content-Filename'] = basename(filename)
         #file_size = stat(filename).st_size
         #headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
     else:
         raise ClientException(
             "Unexpected MIME type for file {}: MIME type {}".format(
                 filename, mime_type))
     headers["Content-File-MD5"] = utils.md5(filename)
     http_header = [
         '{}: {}'.format(key, val) for (key, val) in list(headers.items())
     ]
     self._http.set_http_header(http_header)
     if update_endpoint:
         http_code, resp = self._http.put_cmd(endpoint=update_endpoint,
                                              filename=filename)
     else:
         ow_string = ''
         if overwrite:
             ow_string = '?{}'.format(overwrite)
         self._apiResource = '/vnf_packages_content'
         self._apiBase = '{}{}{}'.format(self._apiName, self._apiVersion,
                                         self._apiResource)
         endpoint = '{}{}'.format(self._apiBase, ow_string)
         http_code, resp = self._http.post_cmd(endpoint=endpoint,
                                               filename=filename)
     #print 'HTTP CODE: {}'.format(http_code)
     #print 'RESP: {}'.format(resp)
     if http_code in (200, 201, 202):
         if resp:
             resp = json.loads(resp)
         if not resp or 'id' not in resp:
             raise ClientException(
                 'unexpected response from server: '.format(resp))
         return resp['id']
     elif http_code == 204:
         print('Updated')
     else:
         msg = "Error {}".format(http_code)
         if resp:
             try:
                 msg = "{} - {}".format(msg, json.loads(resp))
             except ValueError:
                 msg = "{} - {}".format(msg, resp)
         raise ClientException(
             "failed to create/update vnfd - {}".format(msg))
Exemple #13
0
    def wait_for_upload(self, filename):
        """wait(block) for an upload to succeed.
           The filename passed is assumed to be a descriptor tarball.
        """
        pkg_type = utils.get_key_val_from_pkg(filename)

        if pkg_type is None:
            raise ClientException("Cannot determine package type")

        if not self._wait_for_package(pkg_type):
            raise ClientException(
                "package {} failed to upload".format(filename))
Exemple #14
0
    def create(self,
               name,
               vim_access,
               sdn_controller=None,
               sdn_port_mapping=None,
               wait=False):
        if 'vim-type' not in vim_access:
            #'openstack' not in vim_access['vim-type']):
            raise Exception("vim type not provided")

        vim_account = {}
        vim_account['name'] = name
        vim_account = self.update_vim_account_dict(vim_account, vim_access)

        vim_config = {}
        if 'config' in vim_access and vim_access['config'] is not None:
            vim_config = yaml.safe_load(vim_access['config'])
        if sdn_controller:
            sdnc = self._client.sdnc.get(sdn_controller)
            vim_config['sdn-controller'] = sdnc['_id']
        if sdn_port_mapping:
            with open(sdn_port_mapping, 'r') as f:
                vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
        if vim_config:
            vim_account['config'] = vim_config
            #vim_account['config'] = json.dumps(vim_config)

        http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
                                              postfields_dict=vim_account)
        #print 'HTTP CODE: {}'.format(http_code)
        #print 'RESP: {}'.format(resp)
        if http_code in (200, 201, 202, 204):
            if resp:
                resp = json.loads(resp)
            if not resp or 'id' not in resp:
                raise ClientException(
                    'unexpected response from server - {}'.format(resp))
            if wait:
                # Wait for status for VIM instance creation
                self._wait(resp.get('id'))
            print(resp['id'])
        else:
            msg = ""
            if resp:
                try:
                    msg = json.loads(resp)
                except ValueError:
                    msg = resp
            raise ClientException("failed to create vim {} - {}".format(
                name, msg))
Exemple #15
0
 def update(self,
            vim_name,
            vim_account,
            sdn_controller,
            sdn_port_mapping,
            wait=False):
     vim = self.get(vim_name)
     vim_id_for_wait = self._get_id_for_wait(vim_name)
     vim_config = {}
     if 'config' in vim_account:
         if vim_account.get('config') == "" and (sdn_controller
                                                 or sdn_port_mapping):
             raise ClientException(
                 "clearing config is incompatible with updating SDN info")
         if vim_account.get('config') == "":
             vim_config = None
         else:
             vim_config = yaml.safe_load(vim_account['config'])
     if sdn_controller:
         sdnc = self._client.sdnc.get(sdn_controller)
         vim_config['sdn-controller'] = sdnc['_id']
     if sdn_port_mapping:
         with open(sdn_port_mapping, 'r') as f:
             vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
     vim_account['config'] = vim_config
     #vim_account['config'] = json.dumps(vim_config)
     http_code, resp = self._http.put_cmd(endpoint='{}/{}'.format(
         self._apiBase, vim['_id']),
                                          postfields_dict=vim_account)
     # print 'HTTP CODE: {}'.format(http_code)
     # print 'RESP: {}'.format(resp)
     if http_code in (200, 201, 202, 204):
         if wait:
             # In this case, 'resp' always returns None, so 'resp['id']' cannot be used.
             # Use the previously obtained id instead.
             wait_id = vim_id_for_wait
             # Wait for status for VI instance update
             self._wait(wait_id)
         else:
             pass
     else:
         msg = ""
         if resp:
             try:
                 msg = json.loads(resp)
             except ValueError:
                 msg = resp
         raise ClientException("failed to update vim {} - {}".format(
             vim_name, msg))
Exemple #16
0
 def delete(self, name, force=False):
     self._client.get_token()
     repo_id = name
     if not utils.validate_uuid4(name):
         repo_id = self.get_id(name)
     querystring = ''
     if force:
         querystring = '?FORCE=True'
     http_code, resp = self._http.delete_cmd('{}/{}{}'.format(
         self._apiBase, repo_id, querystring))
     #print 'HTTP CODE: {}'.format(http_code)
     #print 'RESP: {}'.format(resp)
     if http_code == 202:
         print('Deletion in progress')
     elif http_code == 204:
         print('Deleted')
     else:
         msg = resp or ""
         # if resp:
         #     try:
         #         msg = json.loads(resp)
         #     except ValueError:
         #         msg = resp
         raise ClientException("failed to delete repo {} - {}".format(
             name, msg))
Exemple #17
0
 def delete(self, name, force=False, wait=False):
     nsi = self.get(name)
     querystring = ''
     if force:
         querystring = '?FORCE=True'
     http_code, resp = self._http.delete_cmd('{}/{}{}'.format(
         self._apiBase, nsi['_id'], querystring))
     # print 'HTTP CODE: {}'.format(http_code)
     # print 'RESP: {}'.format(resp)
     if http_code == 202:
         if wait and resp:
             resp = json.loads(resp)
             # Wait for status for NSI instance deletion
             # For the 'delete' operation, '_id' is used
             self._wait(resp.get('_id'), deleteFlag=True)
         else:
             print('Deletion in progress')
     elif http_code == 204:
         print('Deleted')
     else:
         msg = ""
         if resp:
             try:
                 msg = json.loads(resp)
             except ValueError:
                 msg = resp
         raise ClientException("failed to delete nsi {} - {}".format(
             name, msg))
Exemple #18
0
    def pkg_get(self, pkgtype, name, repo, version, filter):

        pkg_name = self.get_pkg(pkgtype, name, repo, filter, version)
        if not pkg_name:
            raise ClientException('Package not found')
        folder, descriptor = self.zip_extraction(pkg_name)
        with open(descriptor) as pkg:
            pkg_descriptor = yaml.safe_load(pkg)
        rmtree(folder, ignore_errors=False)
        if ((pkgtype == 'vnf' and (pkg_descriptor.get('vnfd')
                                   or pkg_descriptor.get('vnfd:vnfd_catalog')))
                or (pkgtype == 'ns' and
                    (pkg_descriptor.get('nsd')
                     or pkg_descriptor.get('nsd:nsd_catalog')))):
            raise ClientException('Wrong Package type')
        return pkg_descriptor
Exemple #19
0
    def delete(self, name, force=False):
        """
        Deletes an OSM role identified by name.

        :param name:
        :param force:
        :raises ClientException: when fails to delete a role.
        """
        role = self.get(name)
        querystring = ''
        if force:
            querystring = '?FORCE=True'
        http_code, resp = self._http.delete_cmd('{}/{}{}'.format(
            self._apiBase, role['_id'], querystring))
        # print('HTTP CODE: {}'.format(http_code))
        # print('RESP: {}'.format(resp))
        if http_code == 202:
            print('Deletion in progress')
        elif http_code == 204:
            print('Deleted')
        elif resp and 'result' in resp:
            print('Deleted')
        else:
            msg = ""
            if resp:
                try:
                    msg = json.loads(resp)
                except ValueError:
                    msg = resp
            raise ClientException("Failed to delete role {} - {}".format(
                name, msg))
Exemple #20
0
 def create(self, pdu, update_endpoint=None):
     self._logger.debug("")
     self._client.get_token()
     headers = self._client._headers
     headers['Content-Type'] = 'application/yaml'
     http_header = [
         '{}: {}'.format(key, val) for (key, val) in list(headers.items())
     ]
     self._http.set_http_header(http_header)
     if update_endpoint:
         http_code, resp = self._http.put_cmd(endpoint=update_endpoint,
                                              postfields_dict=pdu)
     else:
         endpoint = self._apiBase
         #endpoint = '{}{}'.format(self._apiBase,ow_string)
         http_code, resp = self._http.post_cmd(endpoint=endpoint,
                                               postfields_dict=pdu)
     #print('HTTP CODE: {}'.format(http_code))
     #print('RESP: {}'.format(resp))
     #if http_code in (200, 201, 202, 204):
     if resp:
         resp = json.loads(resp)
     if not resp or 'id' not in resp:
         raise ClientException(
             'unexpected response from server: {}'.format(resp))
     print(resp['id'])
Exemple #21
0
 def scale_vnf(self,
               ns_name,
               vnf_name,
               scaling_group,
               scale_in,
               scale_out,
               wait=False):
     """Scales a VNF by adding/removing VDUs
     """
     try:
         op_data = {}
         op_data["scaleType"] = "SCALE_VNF"
         op_data["scaleVnfData"] = {}
         if scale_in:
             op_data["scaleVnfData"]["scaleVnfType"] = "SCALE_IN"
         else:
             op_data["scaleVnfData"]["scaleVnfType"] = "SCALE_OUT"
         op_data["scaleVnfData"]["scaleByStepData"] = {
             "member-vnf-index": vnf_name,
             "scaling-group-descriptor": scaling_group,
         }
         self.exec_op(ns_name, op_name='scale', op_data=op_data, wait=wait)
     except ClientException as exc:
         message = "failed to scale vnf {} of ns {}:\nerror:\n{}".format(
             vnf_name, ns_name, exc.message)
         raise ClientException(message)
Exemple #22
0
 def delete(self, name, force=False):
     """Deletes an existing OSM user identified by name
     """
     self._logger.debug("")
     self._client.get_token()
     user = self.get(name)
     querystring = ''
     if force:
         querystring = '?FORCE=True'
     http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
                                      user['_id'], querystring), skip_query_admin=True)
     #print('HTTP CODE: {}'.format(http_code))
     #print('RESP: {}'.format(resp))
     if http_code == 202:
         print('Deletion in progress')
     elif http_code == 204:
         print('Deleted')
     elif resp and 'result' in resp:
         print('Deleted')
     else:
         msg = resp or ""
         # if resp:
         #     try:
         #         msg = json.loads(resp)
         #     except ValueError:
         #         msg = resp
         raise ClientException("failed to delete user {} - {}".format(name, msg))
Exemple #23
0
 def delete(self, name, force=False, wait=False):
     self._logger.debug("")
     self._client.get_token()
     sdn_controller = self.get(name)
     sdnc_id_for_wait = self._get_id_for_wait(name)
     querystring = ''
     if force:
         querystring = '?FORCE=True'
     http_code, resp = self._http.delete_cmd('{}/{}{}'.format(
         self._apiBase, sdn_controller['_id'], querystring))
     # print('HTTP CODE: {}'.format(http_code))
     # print('RESP: {}'.format(resp))
     if http_code == 202:
         if wait:
             # Wait for status for SDNC instance deletion
             self._wait(sdnc_id_for_wait, wait, deleteFlag=True)
         else:
             print('Deletion in progress')
     elif http_code == 204:
         print('Deleted')
     elif resp and 'result' in resp:
         print('Deleted')
     else:
         msg = resp or ""
         # if resp:
         #     try:
         #         msg = json.loads(resp)
         #     except ValueError:
         #         msg = resp
         raise ClientException(
             "failed to delete SDN controller {} - {}".format(name, msg))
Exemple #24
0
 def delete(self, vnfd_name):
     vnfd = self.get(vnfd_name)
     resp = self._http.delete_cmd(
         'api/running/{}vnfd-catalog/vnfd/{}'.format(
             self._client.so_rbac_project_path, vnfd['id']))
     if 'success' not in resp:
         raise ClientException("failed to delete vnfd {}".format(vnfd_name))
Exemple #25
0
    def create(self, name, wim_input, wim_port_mapping=None, wait=False):
        self._logger.debug("")
        self._client.get_token()
        if 'wim_type' not in wim_input:
            raise Exception("wim type not provided")

        wim_account = wim_input
        wim_account["name"] = name

        wim_config = {}
        if 'config' in wim_input and wim_input['config'] is not None:
            wim_config = yaml.safe_load(wim_input['config'])
        if wim_port_mapping:
            with open(wim_port_mapping, 'r') as f:
                wim_config['wim_port_mapping'] = yaml.safe_load(f.read())
        if wim_config:
            wim_account['config'] = wim_config
            #wim_account['config'] = json.dumps(wim_config)

        http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
                                              postfields_dict=wim_account)
        #print('HTTP CODE: {}'.format(http_code))
        #print('RESP: {}'.format(resp))
        #if http_code in (200, 201, 202, 204):
        if resp:
            resp = json.loads(resp)
        if not resp or 'id' not in resp:
            raise ClientException(
                'unexpected response from server - {}'.format(resp))
        if wait:
            # Wait for status for WIM instance creation
            self._wait(resp.get('id'), wait)
        print(resp['id'])
Exemple #26
0
 def _detach(self, vim_name):
     tenant_name = 'osm'
     tenant = self._get_ro_tenant()
     if tenant is None:
         raise ClientException("tenant {} not found".format(tenant_name))
     return self._ro_http.delete_cmd('openmano/{}/datacenters/{}'.format(
         tenant["uuid"], vim_name))
Exemple #27
0
 def export_metric(self, metric):
     self._logger.debug("")
     self._client.get_token()
     data = {}
     data["read_metric_data_request"] = metric
     try:
         http_code, resp = self._http.post_cmd(
             endpoint='/test/message/metric_request', postfields_dict=data)
         #print('HTTP CODE: {}'.format(http_code))
         #print('RESP: {}'.format(resp))
         # if http_code in (200, 201, 202, 204):
         #    resp = json.loads(resp)
         return 'Metric exported'
         #else:
         #    msg = ""
         #    if resp:
         #        try:
         #            msg = json.loads(resp)
         #        except ValueError:
         #            msg = resp
         #    raise ClientException('error: code: {}, resp: {}'.format(
         #                          http_code, msg))
     except ClientException as exc:
         message = "failed to export metric: metric {}\n{}".format(
             metric, str(exc))
         raise ClientException(message)
Exemple #28
0
 def delete_alarm(self, name):
     self._logger.debug("")
     self._client.get_token()
     data = {}
     data["delete_alarm_request"] = {}
     data["delete_alarm_request"]["alarm_delete_request"] = {}
     data["delete_alarm_request"]["alarm_delete_request"][
         "alarm_uuid"] = name
     try:
         http_code, resp = self._http.post_cmd(
             endpoint='/test/message/alarm_request', postfields_dict=data)
         #print('HTTP CODE: {}'.format(http_code))
         #print('RESP: {}'.format(resp))
         # if http_code in (200, 201, 202, 204):
         #    resp = json.loads(resp)
         print('Alarm deleted')
         #else:
         #    msg = ""
         #    if resp:
         #        try:
         #            msg = json.loads(resp)
         #        except ValueError:
         #            msg = resp
         #    raise ClientException('error: code: {}, resp: {}'.format(
         #                          http_code, msg))
     except ClientException as exc:
         message = "failed to delete alarm: alarm {}\n{}".format(
             name, str(exc))
         raise ClientException(message)
Exemple #29
0
    def create(self, name, vim_access):
        vim_account = {}
        vim_account['datacenter'] = {}

        # currently assumes vim_acc
        if ('vim-type' not in vim_access):
            #'openstack' not in vim_access['vim-type']):
            raise Exception("vim type not provided")

        vim_account['datacenter']['name'] = name
        vim_account['datacenter']['type'] = vim_access['vim-type']

        vim_config = {}
        if 'config' in vim_access and vim_access['config'] is not None:
            vim_config = yaml.safe_load(vim_access['config'])

        if vim_config:
            vim_account['datacenter']['config'] = vim_config

        vim_account = self.update_vim_account_dict(vim_account, vim_access,
                                                   vim_config)

        resp = self._ro_http.post_cmd('openmano/datacenters', vim_account)
        if resp and 'error' in resp:
            raise ClientException("failed to create vim")
        else:
            self._attach(name, vim_account)
            self._update_ro_accounts()
Exemple #30
0
 def update(self, wim_name, wim_account, wim_port_mapping=None, wait=False):
     self._logger.debug("")
     self._client.get_token()
     wim = self.get(wim_name)
     wim_id_for_wait = self._get_id_for_wait(wim_name)
     wim_config = {}
     if 'config' in wim_account:
         if wim_account.get('config') == "" and (wim_port_mapping):
             raise ClientException(
                 "clearing config is incompatible with updating SDN info")
         if wim_account.get('config') == "":
             wim_config = None
         else:
             wim_config = yaml.safe_load(wim_account['config'])
     if wim_port_mapping:
         with open(wim_port_mapping, 'r') as f:
             wim_config['wim_port_mapping'] = yaml.safe_load(f.read())
     wim_account['config'] = wim_config
     #wim_account['config'] = json.dumps(wim_config)
     http_code, resp = self._http.patch_cmd(endpoint='{}/{}'.format(
         self._apiBase, wim['_id']),
                                            postfields_dict=wim_account)
     #print('HTTP CODE: {}'.format(http_code))
     #print('RESP: {}'.format(resp))
     #if http_code in (200, 201, 202, 204):
     if wait:
         # In this case, 'resp' always returns None, so 'resp['id']' cannot be used.
         # Use the previously obtained id instead.
         wait_id = wim_id_for_wait
         # Wait for status for WIM instance update
         self._wait(wait_id, wait)