Exemplo n.º 1
0
    def get_request_result_raw(self):
        """Request vRa to get the status of a specific request based on the status_url
        
        Returns:
            dict: vRa raw data
        """

        try:
            req = self.config.session.get(f"{self.status_url}/resources",
                                          verify=self.config.verify,
                                          timeout=self.config.timeout)
            req.raise_for_status()
            data = json.loads(req.text)
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(f'vRa request exception : {e}')
        except Exception as e:
            raise VraSdkMainRequestException(
                f'Unmanaged error requesting vRa: {e}')

        if data.get("content"):
            return data['content'][0]
        else:
            try:
                req = self.config.session.get(
                    f"{self.status_url}/forms/details",
                    verify=self.config.verify,
                    timeout=self.config.timeout)
                req.raise_for_status()
            except requests.exceptions.RequestException as e:
                raise VraSdkRequestException(f'vRa request exception : {e}')
            except Exception as e:
                raise VraSdkMainRequestException(
                    f'Unmanaged error requesting vRa: {e}')
            data = json.loads(req.text)
            return data
Exemplo n.º 2
0
    def get_catalog(self):
        """Get the catalog item list from the vRa infrastructure
        
        Returns:
            dict: map of catalog item to vRa id
        """

        catalog = {}
        try:
            req = self.config.session.get(
                f"https://{self.config.vcac_server}/catalog-service/api/consumer/entitledCatalogItems?limit=9999",
                verify=self.config.verify,
                timeout=self.config.timeout)
            req.raise_for_status()
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(
                f'Error during retrieving catalog item: {e}')
        except Exception as e:
            raise VraSdkMainException(
                f'Unmanaged error during catalog retrieving: {e}')

        try:
            for elt in json.loads(req.text)['content']:
                catalog[elt['catalogItem']['name']] = elt['catalogItem']['id']
        except Exception as e:
            raise VraSdkMainException(
                f'Error updating the catalog attribute {e}')

        return catalog
Exemplo n.º 3
0
    def delete_token(self):
        """Delete vRa token
        
        Raises:
            VraSdkRequestException: [description]
            VraSdkAuthenticateException: [description]
        
        Returns:
            bolean: True if the token has been succesfully deleted, False there's already no token
        """

        try:
            if not self.token: return False
            req = self.config.session.delete(
                f"https://{self.config.vcac_server}/identity/api/tokens/{self.token}",
                verify=self.config.verify,
                headers=self.config.session.headers,
                timeout=self.config.timeout)
            req.raise_for_status()
            self.token = None
            self.config.session.headers.update({
                'content-type': 'application/json',
                'Accept': 'application/json',
                'Authorization': ''
            })
            return True
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(
                f"Error during request to get vRa token: {e}")
        except Exception as e:
            raise VraSdkAuthenticateException(
                f"Unmanaged error during token retrieving: {e}")
Exemplo n.º 4
0
 def execute_request(self):
     """Execute the request against the vRa infrastructure
     
     Returns:
         requests.Request: request object
     """
     try:
         req = self.config.session.post(
             f"https://{self.config.vcac_server}/catalog-service/api/consumer/requests",
             data=json.dumps(self.customized),
             verify=self.config.verify,
             timeout=self.config.timeout)
         req.raise_for_status()
     except requests.exceptions.RequestException as e:
         raise VraSdkRequestException(f'vRa request exception : {e}')
     except Exception as e:
         raise VraSdkPayloadException(
             f'Unmanaged error requesting vRa: {e}')
Exemplo n.º 5
0
    def get_status(self):
        """Use the status_url attribute to get the status of the request against the vRa infrastructure
        
        Returns:
            dict: vRa status state
        """

        try:
            req = self.config.session.get(self.status_url,
                                          verify=self.config.verify,
                                          timeout=self.config.timeout)
            res = json.loads(req.text)['state']
            return res
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(
                f'Error requesting status url {self.status_url}: {e}')
        except Exception as e:
            raise VraSdkMainRequestException(
                f'Unmanaged error requesting status url {self.status_url}: {e}'
            )
Exemplo n.º 6
0
    def get_token(self, login, password):
        """Get authentication token against vRa infrastructure
        
        Args:
            login (string): vRa login
            password (string): vRa password
        
        Raises:
            VraSdkRequestException: Raised if any Requests error
            VraSdkAuthenticateException: Raised for unmanged error. Mostly for raise_for_status 4xx or 5xx errors
        
        Returns:
            string: vRa token
        """

        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        payload = {
            'username': login,
            'password': password,
            'tenant': self.tenant
        }

        try:
            req = self.config.session.post(
                f"https://{self.config.vcac_server}/identity/api/tokens",
                json=payload,
                verify=self.config.verify,
                headers=headers,
                timeout=self.config.timeout)
            req.raise_for_status()
            return json.loads(req.text)['id']
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(
                f"Error during request to get vRa token: {e}")
        except Exception as e:
            raise VraSdkAuthenticateException(
                f"Unmanaged error during token retrieving: {e}")
Exemplo n.º 7
0
    def get_template(self, catalog_item_id):
        """Get payload template for catalog item request against vRa infrastructure
        
        Args:
            catalog_item_id (string): id of the catalog item
        
        Returns:
            dict: payload of the request to perform to request the specified catalog item
        """

        try:
            req = self.config.session.get(
                f"https://{self.config.vcac_server}/catalog-service/api/consumer/entitledCatalogItems/{catalog_item_id}/requests/template",
                verify=self.config.verify,
                timeout=self.config.timeout)
            req.raise_for_status()
            return json.loads(req.text)
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(f'vRa request exception : {e}')
        except Exception as e:
            raise VraSdkPayloadException(
                f'Unmanaged error requesting vRa: {e}')
Exemplo n.º 8
0
    def get_template(self, resource_id, resource_action_id):
        """Get payload template for resource action request against vRa infrastructure
        
        Args:
            resource_id (string): id of the resource to perform the action on
            resource_action_id (string): id of the action to perform
        
        Returns:
            dict: payload of the request to perform to request the specified action on the specified resource
        """

        try:
            req = self.config.session.get(
                f"https://{self.config.vcac_server}/catalog-service/api/consumer/resources/{resource_id}/actions/{resource_action_id}/requests/template",
                verify=self.config.verify,
                timeout=self.config.timeout)
            req.raise_for_status()
            return json.loads(req.text)
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(f'vRa request exception : {e}')
        except Exception as e:
            raise VraSdkPayloadException(
                f'Unmanaged error requesting vRa: {e}')
Exemplo n.º 9
0
    def get_bg_id(self, business_group, force_refresh=False):
        """get business group id against vRa infrastructure
        
        Args:
            business_group (string): business group name
            force_refresh (bool, optional): Defaults to False. force the refresh of the business group id
        
        """

        if not self.business_group_id or force_refresh:
            try:
                req = self.config.session.get(
                    f"https://{self.config.vcac_server}/catalog-service/api/consumer/entitledCatalogItems?limit=998",
                    verify=self.config.verify,
                    timeout=self.config.timeout)
                req.raise_for_status()
                response = json.loads(req.text)
            except requests.exceptions.RequestException as e:
                raise VraSdkRequestException(
                    f"Error getting business group id for bg {self.business_group}: {e}"
                )
            except Exception as e:
                raise VraSdkMainException(e)

            if 'content' in response:
                for catalog_item in response['content']:
                    for elt in catalog_item['entitledOrganizations']:
                        if elt["subtenantLabel"] == business_group:
                            return elt['subtenantRef']
                raise VraSdkMainException(
                    f'No entitlement for the account {self.authentication_object.login} in business group {business_group}'
                )
            else:
                raise VraSdkMainException(
                    f'Unable get bg id list. No entitled catalog item for account {self.authentication_object.login}'
                )
Exemplo n.º 10
0
    def get_object_raw(self,
                       object_type,
                       key,
                       value,
                       limit,
                       page,
                       full=False,
                       resource_type=None):
        """Get raw catalog resource information from vRa infrastructure
        
        Args:
            object_type (string): type of vRa resource to get data on
            key (string): field to search for
            value (string): value of the field
            limit (int): maximum result per page
            page (int): page to get from result.
            full (bool): If True return the full result
            resource_type (string, optional): Defaults to None. Only used for get_raw_definitions()
        
        Returns:
            dict: raw vRa data
        """

        #url_array = [f"limit={str(limit)}",f'page={str(page)}']
        url_array = ["limit=" + str(limit), "page=" + str(page)]
        filters = self.format_filters(object_type, key, value, resource_type)
        if filters:
            url_array.append(filters)
        amp = "&"
        url = f"https://{self.config.vcac_server}/catalog-service/api/consumer/resources/?{amp.join(url_array)}"
        try:
            req = self.config.session.get(url,
                                          verify=self.config.verify,
                                          timeout=self.config.timeout)
            req.raise_for_status()
        except requests.exceptions.RequestException as e:
            raise VraSdkRequestException(f'vRa request exception : {e}')
        except Exception as e:
            raise VraSdkMainRequestException(
                f'Unmanaged error requesting vRa: {e}')

        res = req.json()

        if (not object_type and resource_type) or full:
            ids = []
            if key != 'id':
                for elt in res["content"]:
                    ids.append(elt["id"])
            else:
                ids.append(value)

            result = []
            for id in ids:
                url = f"https://{self.config.vcac_server}/catalog-service/api/consumer/resources/{id}"
                try:
                    req = self.config.session.get(url,
                                                  verify=self.config.verify,
                                                  timeout=self.config.timeout)
                    req.raise_for_status()
                except requests.exceptions.RequestException as e:
                    raise VraSdkRequestException(
                        f'vRa request exception : {e}')
                except Exception as e:
                    raise VraSdkMainRequestException(
                        f'Unmanaged error requesting vRa: {e}')

                res = req.json()
                result.append(res)
            return result
        else:
            return res['content'] if 'content' in res else []