class CertificateAuthority(object):
    """
    Certificate Authority API client.
    """

    URI = '/rest/certificates/ca'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get(self):
        """
        Retrieves the certificate of the internal CA in the form of a string.

        Returns:
            str: The Internal CA Certificate.
        """
        return self._client.get(self.URI)

    def get_crl(self):
        """
        Retrieves the contents of the CRL file maintained by the internal CA; in Base-64 encoded format, in the form
        of a string.

        Returns:
            str: The Certificate Revocation List
        """
        crl_url = self.URI + "/crl"
        return self._client.get(crl_url)

    def delete(self, alias_name, timeout=-1):
        """
        Revokes a certificate signed by the internal CA. If client certificate to be revoked is RabbitMQ_readonly,
        then the internal CA root certificate, RabbitMQ client certificate and RabbitMQ server certificate will be
        regenerated. This will invalidate the previous version of RabbitMQ client certificate and the RabbitMQ server
        will be restarted to read the latest certificates.

        Args:
            alias_name (str): Alias name.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.
        """
        uri = self.URI + "/" + alias_name
        return self._client.delete(uri, timeout=timeout)
Beispiel #2
0
class ServerHardwareTypes(object):
    """
    The server hardware types resource is a representation/abstraction of a physical server managed by the appliance.
    It defines capabilities and settings that can be used in a server profile.

    """
    URI = '/rest/server-hardware-types'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets the list of server hardware type resources defined on the appliance.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of server hardware types.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets the server hardware type resource with the specified ID or URI.

        Args:
            id_or_uri: Can be either the server hardware type ID or URI.

        Returns:
            dict: The logical interconnect group.
        """
        return self._client.get(id_or_uri)

    def update(self, resource, uri=None, timeout=-1):
        """
        Updates one or more attributes for a server hardware type resource.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated server hardware type.

        """
        return self._client.update(resource, uri, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Removes the server hardware type with the specified URI. A server hardware type cannot be deleted if it
        is associated with a server hardware or server profile resource.

        Args:
            resource (dict): object to delete
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates whether the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all server hardware types that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of server hardware types.
        """
        return self._client.get_by(field, value)
class GoldenImages(object):
    URI = '/rest/golden-images'

    def __init__(self, con):
        self._client = ResourceClient(con, self.URI)
        self._task_monitor = TaskMonitor(con)
        self.__default_values = {
            'type': 'GoldenImage',
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Retrieves a list of Golden Image resources as per the specified parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Golden Images.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def create(self, resource, timeout=-1):
        """
        Creates a Golden Image resource from the deployed OS Volume as per the attributes specified.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Golden Image created.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def upload(self, file_path, golden_image_info):
        """
        Adds a Golden Image resource from the file that is uploaded from a local drive. Only the .zip format file can
        be used for the upload.

        Args:
            file_path (str): File name to upload.
            golden_image_info (dict): Golden Image information.

        Returns:
            dict: Golden Image.
        """
        uri = "{0}?name={1}&description={2}".format(self.URI,
                                                    quote(golden_image_info.get('name', '')),
                                                    quote(golden_image_info.get('description', '')))

        return self._client.upload(file_path, uri)

    def download_archive(self, id_or_uri, file_path):
        """
        Download the details of the Golden Image capture logs, which has been archived based on the specific attribute
        ID.

        Args:
            id_or_uri: ID or URI of the Golden Image.
            file_path (str): File name to save the archive.

        Returns:
            bool: Success.
        """
        uri = self.URI + "/archive/" + extract_id_from_uri(id_or_uri)
        return self._client.download(uri, file_path)

    def download(self, id_or_uri, file_path):
        """
        Downloads the content of the selected Golden Image as per the specified attributes.

        Args:
            id_or_uri: ID or URI of the Golden Image.
            file_path(str): Destination file path.

        Returns:
            bool: Successfully downloaded.
        """
        uri = self.URI + "/download/" + extract_id_from_uri(id_or_uri)
        return self._client.download(uri, file_path)

    def get(self, id_or_uri):
        """
        Retrieves the overview details of the selected Golden Image as per the specified attributes.

        Args:
            id_or_uri: ID or URI of the Golden Image.

        Returns:
            dict: The Golden Image.
        """
        return self._client.get(id_or_uri)

    def update(self, resource, timeout=-1):
        """
        Updates the properties of the Golden Image.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Updated resource.

        """
        return self._client.update(resource, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes the Golden Image specified.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all Golden Images that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Golden Images.
        """
        return self._client.get_by(field, value)
class IdPoolsRanges(object):
    """
    Base class for Id Pools Ranges API client.

    Has common function used by: vMAC, vSN, vWWN
    """

    def __init__(self, type, con):

        uri = ""
        if type == 'vmac':
            uri = '/rest/id-pools/vmac/ranges'
        elif type == 'vsn':
            uri = '/rest/id-pools/vsn/ranges'
        elif type == 'vwwn':
            uri = '/rest/id-pools/vwwn/ranges'
        else:
            raise HPOneViewValueError("Invalid type: {0}, types allowed: vmac, vsn, vwwn, ".format(type))

        self._client = ResourceClient(con, uri)

    def create(self, resource, timeout=-1):
        """
        Creates range.

        Args:
            resource (dict): Object to create
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created range.
        """
        return self._client.create(resource, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets range.

        Using the allocator and collector associated with the range, IDs may be allocated from or collected back to the
        range.

        Args:
            id_or_uri: Can be either the range ID or URI.

        Returns:
            dict: Range
        """
        return self._client.get(id_or_uri)

    def enable(self, information, id_or_uri, timeout=-1):
        """
        Enables or disables a range.

        Args:
            information (dict): Information to update.
            id_or_uri: ID or URI of range.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """

        uri = self._client.build_uri(id_or_uri)

        return self._client.update(information, uri, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes range.

        Args:
            resource (dict):
                Object to delete
            force (bool):
                If set to true, the operation completes despite any problems with
                network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_allocated_fragments(self, id_or_uri, count=-1, start=0):
        """
        Gets all fragments that have been allocated in range.

        Args:
            id_or_uri:
                ID or URI of range.
            count:
                 The number of resources to return. A count of -1 requests all items. The actual number of items in
                 the response may differ from the requested count if the sum of start and count exceed the total number
                 of items.
            start:
                The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                first available item.

        Returns:
            list: A list with the allocated fragements.
        """
        uri = self._client.build_uri(id_or_uri) + "/allocated-fragments?start={0}&count={1}".format(start, count)
        return self._client.get_collection(uri)

    def allocate(self, information, id_or_uri, timeout=-1):
        """
        Allocates a set of IDs from range.

        The allocator returned contains the list of IDs successfully allocated.

        Args:
            information (dict):
                Information to update. Can result in system specified IDs or the system reserving user-specified IDs.
            id_or_uri:
                ID or URI of vSN range.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Allocator
        """
        uri = self._client.build_uri(id_or_uri) + "/allocator"

        return self._client.update(information, uri, timeout=timeout)

    def collect(self, information, id_or_uri, timeout=-1):
        """
        Collects a set of IDs back to range.

        The collector returned contains the list of IDs successfully collected.

        Args:
            information (dict):
                The list of IDs to be collected
            id_or_uri:
                ID or URI of range
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Collector containing list of collected IDs successfully collected.
        """
        uri = self._client.build_uri(id_or_uri) + "/collector"

        return self._client.update(information, uri, timeout=timeout)

    def get_free_fragments(self, id_or_uri, count=-1, start=0):
        """
        Gets all free fragments in a vSN range.

        Args:
            id_or_uri:
                ID or URI of range.
            count:
                 The number of resources to return. A count of -1 requests all items. The actual number of items in
                 the response may differ from the requested count if the sum of start and count exceed the total number
                 of items.
            start:
                The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                first available item.

        Returns:
            list: A list with the free fragments.
        """
        uri = self._client.build_uri(id_or_uri) + "/free-fragments?start={0}&count={1}".format(start, count)
        return self._client.get_collection(uri)
Beispiel #5
0
class Volumes(object):
    URI = '/rest/storage-volumes'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__snapshot_default_values = {
            "type": "Snapshot"
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of managed volumes. The collection is based on optional
        sorting and filtering, and constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets the managed volume.

        Args:
            id_or_uri: Could be either the volume id or the volume uri.

        Returns: Managed volume.
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Get all managed volumes that matches the given filter.
        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates or adds a volume.

        It's possible to create the volume in 6 different ways:

          It's possible to create the volume in 6 different ways:

          1) Common = Storage System + Storage Pool
          2) Template = Storage Volume Template
          3) Common with snapshots = Storage System + Storage Pool + Snapshot Pool
          4) Management = Storage System + wwn
          5) Management by name = Storage System + Storage System Volume Name
          6) Snapshot = Snapshot Pool + Storage Pool + Snapshot.

          NOTE: The 4) and 5) are for adding a volume for management, it do not create new volumes.

        Args:
            resource: dict object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created or added resource.
        """
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, force=False, timeout=-1):
        """
        Updates properties of a volume.

        Reverts a volume to the specified snapshot.

        Args:
            resource: dict object to update
            force:
                If set to true the operation completes despite any problems with network connectivity or errors on
                the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns: Updated resource.
        """
        return self._client.update(resource, timeout=timeout, force=force)

    def delete(self, resource, force=False, export_only=False, timeout=-1):
        """
        Deletes a managed volume.

        Args:
            resource: dict object to delete
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.
            export_only:
                By default, volumes will be deleted from OneView and storage system.
                To delete the volume only from OneView, you must set its value to True.
                Setting its value to False has the same behaviour as the default behaviour.

        Returns:
            bool: indicating if the volume was successfully deleted.
        """
        custom_headers = {"exportOnly": export_only}
        return self._client.delete(resource, force=force, timeout=timeout, custom_headers=custom_headers)

    def __build_volume_snapshot_uri(self, volume_id_or_uri=None, snapshot_id_or_uri=None):
        if snapshot_id_or_uri and "/" in snapshot_id_or_uri:
            return snapshot_id_or_uri
        else:
            if not volume_id_or_uri:
                raise ValueError(INVALID_VOLUME_URI)
            volume_uri = self._client.build_uri(volume_id_or_uri)
            return volume_uri + "/snapshots/" + str(snapshot_id_or_uri or '')

    def get_snapshots(self, volume_id_or_uri, start=0, count=-1, filter='', sort=''):
        """
        Gets all snapshots of a volume. Returns a list of snapshots based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of snapshots
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri)

    def create_snapshot(self, volume_id_or_uri, snapshot, timeout=-1):
        """
        Creates a snapshot for the volume specified
        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri
            snapshot (dict): Object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage Volume

        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        data = self.__snapshot_default_values.copy()
        data.update(snapshot)
        return self._client.create(data, uri=uri, timeout=timeout)

    def get_snapshot(self, snapshot_id_or_uri, volume_id_or_uri=None):
        """
        Gets a snapshot of a volume
        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri. It is optional if is passed a snapshot uri,
                but required if passed a snapshot id
            snapshot_id_or_uri:
                Could be either the snapshot id or the snapshot uri

        Returns:
            dict: The snapshot
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri, snapshot_id_or_uri)
        return self._client.get(uri)

    def delete_snapshot(self, resource, force=False, timeout=-1):
        """
        Deletes a snapshot from OneView and storage system.

        Args:
            resource (dict): object to remove
            force (bool):
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Details of associated volume

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_snapshot_by(self, volume_id_or_uri, field, value):
        """
        Get all snapshots that match the filter
        The search is case insensitive

        Args:
            volume_id_or_uri: Could be either the volume id or the volume uri
            field: field name to filter
            value: value to filter

        Returns:
            list: snapshots

        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_by(field, value, uri=uri)
class ServerHardware(object):
    """
    The server hardware resource is a representation of a physical server.
    The server hardware resource provides methods for server management tasks such
    as applying a profile, importing a server and managing an iLO.

    """
    URI = '/rest/server-hardware'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_utilization(self, id_or_uri, fields=None, filter=None, refresh=False, view=None):
        """
        Retrieves historical utilization data for the specified resource, metrics, and time span.

        Args:
            id_or_uri: Resource identification or URI.
            fields:
                Name of the metrics to be retrieved in the format METRIC[,METRIC]...

                If unspecified, all metrics supported are returned.

                Server hardware supports the following utilization metrics:

                    AmbientTemperature
                        Inlet air temperature in degrees Celsius during this sample interval.
                    AveragePower
                        Average power consumption in Watts during this sample interval.
                    PeakPower
                        Peak power consumption in Watts during this sample interval.
                    PowerCap
                        Dynamic power cap setting on the server hardware in Watts during this sample interval.
                    CpuUtilization
                        CPU utilization of all CPUs in percent during this sample interval.
                    CpuAverageFreq
                        Average CPU frequency in Mhz during this sample interval.

            filter (list or str):
                Provides an expression of the requested time range of data. One condition (startDate/endDate) is
                specified per filter specification as described below. The condition must be specified via the
                equals (=) operator.

                startDate
                    Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is
                    determined by the endDate minus 24 hours.
                endDate
                    End date of requested starting time range in ISO 8601 format. When omitted, the endDate includes
                    the latest data sample available.

                If an excessive number of samples would otherwise be returned, the results will be segmented. The
                caller is responsible for comparing the returned sliceStartTime with the requested startTime in the
                response. If the sliceStartTime is greater than the oldestSampleTime and the requested start time,
                the caller is responsible for repeating the request with endTime set to sliceStartTime to obtain the
                next segment. This process is repeated until the full data set is retrieved.

                If the resource has no data, the UtilizationData is still returned, but will contain no samples and
                sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set
                appropriately (null if no data is available). If the filter just does not happen to overlap the data
                that a resource does have, then the metric history service will return null sample values for any
                missing samples.

            refresh:
                Specifies that, if necessary, an additional request will be queued to obtain the most recent
                utilization data from the iLO. The response will not include any refreshed data. To track the
                availability of the newly collected data, monitor the TaskResource identified by the refreshTaskUri
                property in the response. If null, no refresh was queued.

            view:
                Specifies the resolution interval length of the samples to be retrieved. This is reflected in the
                resolution in the returned response. Utilization data is automatically purged to stay within storage
                space constraints. See the following supported views.

                native
                    Resolution of the samples returned will be one sample for each 5-minute time period. This is the
                    default view and matches the resolution of the data returned by the iLO. Samples at this resolution
                    are retained up to one year.
                hour
                    Resolution of the samples returned will be one sample for each 60-minute time period. Samples are
                    calculated by averaging the available 5-minute data samples that occurred within the hour, except
                    for PeakPower, which is calculated by reporting the peak observed 5-minute sample value data during
                    the hour. Samples at this resolution are retained up to three years.
                day
                    Resolution of the samples returned will be one sample for each 24-hour time period. One day is a
                    24-hour period that starts at midnight GMT, regardless of the time zone in which the appliance or
                    client is located. Samples are calculated by averaging the available 5-minute data samples that
                    occurred during the day, except for PeakPower, which is calculated by reporting the peak observed
                    5-minute sample value data during the day. Samples at this resolution are retained up to three
                    years.

        Returns:
            dict
        """

        return self._client.get_utilization(id_or_uri, fields=fields, filter=filter, refresh=refresh, view=view)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of server hardware resources. Returns a list of resources based on optional sorting and filtering,
        and constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of server hardware resources.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def add(self, information, timeout=-1):
        """
        Adds a rackmount server for management by the appliance. This API initiates the asynchronous addition of
        supported server models.

        Note: Servers in an enclosure are added by adding the enclosure resource. This is
        only supported on appliances that support rackmounted servers.

        Args:
            information (dict): Object to create
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created rackmount server.
        """
        return self._client.create(information, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets a server hardware resource by ID or by URI.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            dict: The server hardware resource
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Gets all server hardware that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            dict
        """
        return self._client.get_by(field, value)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes the rackserver with the specified URI.
        Note: This operation is only supported on appliances that support rackmounted servers.

        Args:
            resource (dict):
                Object to delete.
            force (bool):
                If set to true, the operation completes despite any problems with
                network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates whether the resource was successfully removed.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_bios(self, id_or_uri):
        """
        Gets the list of BIOS/UEFI values currently set on the physical server.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            dict: Dictionary of BIOS/UEFI values.
        """
        uri = self._client.build_uri(id_or_uri) + "/bios"
        return self._client.get(uri)

    def get_environmental_configuration(self, id_or_uri):
        """
        Gets the settings that describe the environmental configuration (supported feature set, calibrated minimum and
        maximum power, location and dimensions, etc.) of the server hardware resource.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            dict: Environmental configuration settings.
        """
        uri = self._client.build_uri(id_or_uri) + "/environmentalConfiguration"
        return self._client.get(uri)

    def update_environmental_configuration(self, configuration, id_or_uri, timeout=-1):
        """
        Sets the calibrated max power of an unmanaged or unsupported server hardware resource.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.
            configuration (dict): Environmental configuration.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Environmental configuration settings.
        """
        uri = self._client.build_uri(id_or_uri) + "/environmentalConfiguration"
        return self._client.update(configuration, uri, timeout=timeout)

    def get_ilo_sso_url(self, id_or_uri):
        """
        Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is
        unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.
        This is not supported on G7/iLO3 or earlier servers.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            URL
        """
        uri = self._client.build_uri(id_or_uri) + "/iloSsoUrl"
        return self._client.get(uri)

    def get_all_firmwares(self, filter='', start=0, count=-1, query='', sort=''):
        """
        Gets a list of firmware inventory across all servers. To filter the returned data, specify a filter
        expression to select a particular server model, component name, and/or component firmware version.

        Note:
            This method is available for API version 300 or later.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            query:
                A general query string to narrow the list of resources returned. The default is no query; all resources
                are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: List of firmware inventory.
        """
        uri = self.URI + "/*/firmware"
        return self._client.get_all(start, count, filter, query, sort, '', '', uri)

    def get_firmware(self, id_or_uri):
        """
        Get the firmware inventory of a server.

        Note:
            This method is available for API version 300 or later.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            dict: Server Hardware firmware.
        """
        uri = self._client.build_uri(id_or_uri) + "/firmware"
        return self._client.get(uri)

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Performs a specific patch operation for the given server. If the server supports the particular operation,
        the operation is performed and a response is returned to the caller with the results.

        Args:
            id_or_uri: Can be either the resource ID or the resource URI.
            operation: Patch operation
            path: Path
            value: Value
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        return self._client.patch(id_or_uri, operation, path, value, timeout=timeout)

    def get_java_remote_console_url(self, id_or_uri):
        """
        Generates a Single Sign-On (SSO) session for the iLO Java Applet console and returns the URL to launch it.
        If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the iLO Java Applet
        will prompt for credentials. This is not supported on G7/iLO3 or earlier servers.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            URL
        """
        uri = self._client.build_uri(id_or_uri) + "/javaRemoteConsoleUrl"
        return self._client.get(uri)

    def update_mp_firware_version(self, id_or_uri, timeout=-1):
        """
        Updates the iLO firmware on a physical server to a minimum ILO firmware version required by OneView to
        manage the server.

        Args:
            id_or_uri:
                Can be either the server hardware resource ID or URI.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.
        Returns:
            Resource
        """
        uri = self._client.build_uri(id_or_uri) + "/mpFirmwareVersion"
        return self._client.update_with_zero_body(uri, timeout)

    def update_power_state(self, configuration, id_or_uri, timeout=-1):
        """
        Refreshes the server hardware to fix configuration issues.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.
            configuration (dict): Power state configuration.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            Resource
        """
        uri = self._client.build_uri(id_or_uri) + "/powerState"
        return self._client.update(configuration, uri, timeout=timeout)

    def refresh_state(self, configuration, id_or_uri, timeout=-1):
        """
        Refreshes the server hardware to fix configuration issues.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.
            configuration: Refresh state configuration.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            Resource
        """
        uri = self._client.build_uri(id_or_uri) + "/refreshState"
        return self._client.update(configuration, uri=uri, timeout=timeout)

    def get_remote_console_url(self, id_or_uri):
        """
        Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application (IRC) and returns the
        URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the
        IRC application will prompt for credentials. Use of this URL requires a previous installation of the iLO IRC and
        is supported only on Windows clients.

        Args:
            id_or_uri: Can be either the server hardware resource ID or URI.

        Returns:
            URL
        """
        uri = self._client.build_uri(id_or_uri) + "/remoteConsoleUrl"
        return self._client.get(uri)
Beispiel #7
0
class Volumes(object):
    """
    Volumes API client.

    """

    URI = '/rest/storage-volumes'

    DEFAULT_VALUES_SNAPSHOT = {
        '200': {"type": "Snapshot"},
        '300': {"type": "Snapshot"},
        '500': {}
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of managed volumes. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets the managed volume.

        Args:
            id_or_uri: Can be either the volume ID or the volume URI.

        Returns:
            Managed volume.
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Gets all managed volumes that matches the given filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates or adds a volume.

        There are six different methods to create the volume:

          1) Common = Storage System + Storage Pool
          2) Template = Storage Volume Template
          3) Common with snapshots = Storage System + Storage Pool + Snapshot Pool
          4) Management = Storage System + wwn
          5) Management by name = Storage System + Storage System Volume Name
          6) Snapshot = Snapshot Pool + Storage Pool + Snapshot.

          NOTE: Use numbers 4 and 5 to add a volume for management; it does not create new volumes.

        Args:
            resource (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created or added resource.
        """
        return self._client.create(resource, timeout=timeout)

    def add_from_existing(self, resource, timeout=-1):
        """
        Adds a volume that already exists in the Storage system

        Args:
            resource (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Added resource.
        """
        uri = self.URI + "/from-existing"
        return self._client.create(resource, uri=uri, timeout=timeout)

    def create_from_snapshot(self, data, timeout=-1):
        """
        Creates a new volume on the storage system from a snapshot of a volume.
        A volume template must also be specified when creating a volume from a snapshot.

        The global setting "StorageVolumeTemplateRequired" controls whether or
        not root volume templates can be used to provision volumes.
        The value of this setting defaults to "false".
        If the value is set to "true", then only templates with an "isRoot" value of "false"
        can be used to provision a volume.

        Args:
            data (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created data.
        """
        uri = self.URI + "/from-snapshot"
        return self._client.create(data, uri=uri, timeout=timeout)

    def update(self, resource, force=False, timeout=-1):
        """
        Updates properties of a volume.

        Reverts a volume to the specified snapshot.

        Args:
            resource (dict): Object to update.
            force:
                If set to true, the operation completes despite any problems with network connectivity or errors on
                the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            Updated resource.
        """
        return self._client.update(resource, timeout=timeout, force=force)

    def delete(self, resource, force=False, export_only=None, suppress_device_updates=None, timeout=-1):
        """
        Deletes a managed volume.

        Args:
            resource (dict):
                Object to delete.
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.
            export_only:
                Valid prior to API500. By default, volumes will be deleted from OneView, and storage system.
                To delete the volume from OneView only, you must set its value to True.
                Setting its value to False has the same behavior as the default behavior.
            suppress_device_updates:
                Valid API500 onwards. By default, volumes will be deleted from OneView, and storage system.
                To delete the volume from OneView only, you must set its value to True.
                Setting its value to False has the same behavior as the default behavior.

        Returns:
            bool: Indicates if the volume was successfully deleted.
        """
        custom_headers = {'If-Match': '*'}
        if 'uri' in resource:
            uri = resource['uri']
        else:
            uri = self._client.build_uri(resource)
        if suppress_device_updates:
            uri += '?suppressDeviceUpdates=true'
        if export_only:
            custom_headers['exportOnly'] = True
        return self._client.delete(uri, force=force, timeout=timeout, custom_headers=custom_headers)

    def __build_volume_snapshot_uri(self, volume_id_or_uri=None, snapshot_id_or_uri=None):
        if snapshot_id_or_uri and "/" in snapshot_id_or_uri:
            return snapshot_id_or_uri
        else:
            if not volume_id_or_uri:
                raise ValueError(INVALID_VOLUME_URI)
            volume_uri = self._client.build_uri(volume_id_or_uri)
            return volume_uri + "/snapshots/" + str(snapshot_id_or_uri or '')

    def get_snapshots(self, volume_id_or_uri, start=0, count=-1, filter='', sort=''):
        """
        Gets all snapshots of a volume. Returns a list of snapshots based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            volume_id_or_uri:
                Can be either the volume id or the volume uri.
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of snapshots.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri)

    def create_snapshot(self, volume_id_or_uri, snapshot, timeout=-1):
        """
        Creates a snapshot for the specified volume.

        Args:
            volume_id_or_uri:
                Can be either the volume ID or the volume URI.
            snapshot (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage volume.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)

        return self._client.create(snapshot, uri=uri, timeout=timeout, default_values=self.DEFAULT_VALUES_SNAPSHOT)

    def get_snapshot(self, snapshot_id_or_uri, volume_id_or_uri=None):
        """
        Gets a snapshot of a volume.

        Args:
            volume_id_or_uri:
                Can be either the volume ID or the volume URI. It is optional if it is passed a snapshot URI,
                but required if it passed a snapshot ID.
            snapshot_id_or_uri:
                Can be either the snapshot ID or the snapshot URI.

        Returns:
            dict: The snapshot.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri, snapshot_id_or_uri)
        return self._client.get(uri)

    def delete_snapshot(self, resource, force=False, timeout=-1):
        """
        Deletes a snapshot from OneView and the storage system.

        Args:
            resource (dict): Object to remove.
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Details of associated volume.

        """
        headers = {'If-Match': '*'}
        return self._client.delete(resource, force=force, timeout=timeout, custom_headers=headers)

    def get_snapshot_by(self, volume_id_or_uri, field, value):
        """
        Gets all snapshots that match the filter.

        The search is case-insensitive.

        Args:
            volume_id_or_uri: Can be either the volume id or the volume uri.
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: Snapshots
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_by(field, value, uri=uri)

    def get_extra_managed_storage_volume_paths(self, start=0, count=-1, filter='', sort=''):
        """
        Gets the list of extra managed storage volume paths.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of extra managed storage volume paths.
        """
        uri = self.URI + '/repair?alertFixType=ExtraManagedStorageVolumePaths'
        return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri)

    def repair(self, volume_id_or_uri, timeout=-1):
        """
        Removes extra presentations from a specified volume on the storage system.

        Args:
            volume_id_or_uri:
                Can be either the volume id or the volume uri.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage volume.
        """
        data = {
            "type": "ExtraManagedStorageVolumePaths",
            "resourceUri": self._client.build_uri(volume_id_or_uri)
        }
        custom_headers = {'Accept-Language': 'en_US'}
        uri = self.URI + '/repair'
        return self._client.create(data, uri=uri, timeout=timeout, custom_headers=custom_headers)

    def get_attachable_volumes(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets the volumes that are connected on the specified networks based on the storage system port's expected
        network connectivity.

        A volume is attachable if it satisfies either of the following conditions:
            * The volume is shareable.
            * The volume not shareable and not attached.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            query:
                A general query string to narrow the list of resources returned. The default
                is no query; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of attachable volumes that the appliance manages.
        """
        uri = self.URI + '/attachable-volumes'
        return self._client.get_all(start, count, filter=filter, query=query, sort=sort, uri=uri)
class IdPoolsRanges(object):

    def __init__(self, uri, con):
        self._connection = con
        self._client = ResourceClient(con, uri)

    def create(self, resource, timeout=-1):
        """
        Creates range.

        A range can be one of two types based upon the range category specified: Generated or Custom. The Generated
        range type automatically assigns start and end addresses to the range. The Custom range type requires a start
        address to be specified. The end address may also be specified but is optional.

        Args:
            resource (dict): Object to create
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Created range.
        """
        return self._client.create(resource, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets range.

        Using the allocator and collector associated with the range, IDs may be allocated from or collected back to the
        range.

        Args:
            id_or_uri: Could be either the range id or uri.

        Returns:
            dict: Range
        """
        return self._client.get(id_or_uri)

    def enable(self, information, id_or_uri, timeout=-1):
        """
        Enables or disables a range.

        Args:
            information (dict): Information to update.
            id_or_uri: Id or uri of range.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """

        uri = self._client.build_uri(id_or_uri)

        return self._client.update(information, uri, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes range.

        Args:
            resource (dict):
                Object to delete
            force (bool):
                If set to true the operation completes despite any problems with
                network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_allocated_fragments(self, id_or_uri, count=-1, start=0):
        """
        Gets all fragments that have been allocated in range.

        Args:
            id_or_uri:
                Id or uri of range
            count:
                 The number of resources to return. A count of -1 requests all the items. The actual number of items in
                 the response may differ from the requested count if the sum of start and count exceed the total number
                 of items.
            start:
                The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                first available item.

        Returns:
            list: A list with IDs.
        """
        uri = self._client.build_uri(id_or_uri) + \
            "/allocated-fragments?start={0}&count={1}".format(start, count)
        return self._client.get(uri)

    def allocate(self, information, id_or_uri, timeout=-1):
        """
        Allocates a set of IDs from range.

        The allocator returned contains the list of IDs successfully allocated.

        Args:
            information (dict):
                Information to update. Can result in system specified IDs or the system reserving user-specified IDs.
            id_or_uri:
                id or uri of vSN range.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Allocator
        """
        uri = self._client.build_uri(id_or_uri) + "/allocator"

        return self._client.update(information, uri, timeout=timeout)

    def collect(self, information, id_or_uri, timeout=-1):
        """
        Collects a set of IDs back to range.

        The collector returned contains the list of IDs successfully collected.

        Args:
            information (dict):
                The list of IDs to be collected
            id_or_uri:
                Id or uri of range
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: collector containing list of collected IDs successfully collected.
        """
        uri = self._client.build_uri(id_or_uri) + "/collector"

        return self._client.update(information, uri, timeout=timeout)

    def get_free_fragments(self, id_or_uri, count=-1, start=0):
        """
        Gets all the free fragments in a vSN range.

        Args:
            id_or_uri:
                Id or uri of range
            count:
                 The number of resources to return. A count of -1 requests all the items. The actual number of items in
                 the response may differ from the requested count if the sum of start and count exceed the total number
                 of items.
            start:
                The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                first available item.

        Returns:
            The list of IDs.
        """
        uri = self._client.build_uri(
            id_or_uri) + "/free-fragments?start={0}&count={1}".format(start, count)
        return self._client.get(uri)
class EthernetNetworks(object):
    """
    Ethernet Networks API client.

    """
    URI = '/rest/ethernet-networks'

    DEFAULT_VALUES = {
        '200': {"type": "ethernet-networkV3"},
        '300': {"type": "ethernet-networkV300"}
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Ethernet networks. The collection is based on optional sorting and filtering
        and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of ethernet networks.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes an Ethernet network.

        Any deployed connections that are using the network are placed in the 'Failed' state.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets the Ethernet network.

        Args:
            id_or_uri: ID or URI of Ethernet network.

        Returns:
            dict: The ethernet network.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Creates an Ethernet network.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created resource.

        """
        return self._client.create(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)

    def create_bulk(self, resource, timeout=-1):
        """
        Creates bulk Ethernet networks.

        Args:
            resource (dict): Specifications to create in bulk.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            list: List of created Ethernet Networks.

        """
        data = {"type": "bulk-ethernet-network"}
        data.update(resource)
        uri = self.URI + '/bulk'
        self._client.create(data, uri=uri, timeout=timeout)

        return self.get_range(resource['namePrefix'], resource['vlanIdRange'])

    def get_range(self, name_prefix, vlan_id_range):
        """
        Gets a list of Ethernet Networks that match the 'given name_prefix' and the 'vlan_id_range'.

        Examples:
            >>> enet.get_range('Enet_name', '1-2,5')
                # The result contains the ethernet network with names:
                ['Enet_name_1', 'Enet_name_2', 'Enet_name_5']

            >>> enet.get_range('Enet_name', '2')
                # The result contains the ethernet network with names:
                ['Enet_name_1', 'Enet_name_2']

        Args:
            name_prefix: The Ethernet Network prefix
            vlan_id_range: A combination of values or ranges to be retrieved. For example, '1-10,50,51,500-700'.

        Returns:
            list: A list of Ethernet Networks.

        """
        filter = '"\'name\' matches \'{}\_%\'"'.format(name_prefix)
        ethernet_networks = self.get_all(filter=filter, sort='vlanId:ascending')

        vlan_ids = self.dissociate_values_or_ranges(vlan_id_range)

        for net in ethernet_networks[:]:
            if int(net['vlanId']) not in vlan_ids:
                ethernet_networks.remove(net)
        return ethernet_networks

    def dissociate_values_or_ranges(self, vlan_id_range):
        """
        Build a list of vlan ids given a combination of ranges and/or values

        Examples:
            >>> enet.dissociate_values_or_ranges('1-2,5')
                [1, 2, 5]

            >>> enet.dissociate_values_or_ranges('5')
                [1, 2, 3, 4, 5]

            >>> enet.dissociate_values_or_ranges('4-5,7-8')
                [4, 5, 7, 8]

        Args:
            vlan_id_range: A combination of values or ranges. For example, '1-10,50,51,500-700'.

        Returns:
            list: vlan ids
        """
        values_or_ranges = vlan_id_range.split(',')
        vlan_ids = []
        # The expected result is different if the vlan_id_range contains only one value
        if len(values_or_ranges) == 1 and '-' not in values_or_ranges[0]:
            vlan_ids = list(range(1, int(values_or_ranges[0]) + 1))
        else:
            for value_or_range in values_or_ranges:
                value_or_range.strip()
                if '-' not in value_or_range:
                    vlan_ids.append(int(value_or_range))
                else:
                    start, end = value_or_range.split('-')
                    range_ids = range(int(start), int(end) + 1)
                    vlan_ids.extend(range_ids)

        return vlan_ids

    def update(self, resource, timeout=-1):
        """
        Updates an Ethernet network.

        Args:
            resource: dict object to update
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns: Updated resource.

        """
        return self._client.update(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)

    def get_by(self, field, value):
        """
        Gets all Ethernet networks that match the filter.
        The search is case-insensitive.

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of ethernet networks.
        """
        return self._client.get_by(field, value)

    def get_associated_profiles(self, id_or_uri):
        """
        Gets the URIs of profiles which are using an Ethernet network.

        Args:
            id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            list: URIs of the associated profiles.

        """
        uri = self._client.build_uri(id_or_uri) + "/associatedProfiles"
        return self._client.get(uri)

    def get_associated_uplink_groups(self, id_or_uri):
        """
        Gets the uplink sets which are using an Ethernet network.

        Args:
            id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            list: URIs of the associated uplink sets.

        """
        uri = self._client.build_uri(id_or_uri) + "/associatedUplinkGroups"
        return self._client.get(uri)
class StorageSystems(object):
    """
    Storage Systems API client.

    """
    URI = '/rest/storage-systems'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets information about all managed storage systems. Filtering and sorting are supported with the retrieval of
        managed storage systems. The following storage system attributes can be used with filtering and sorting
        operation: name, model, serialNumber, firmware, status, managedDomain, and state.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of all managed storage systems.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def add(self, resource, timeout=-1):
        """
        Adds a storage system for management by the appliance. The storage system resource created will be in a
        Connected state and will not yet be available for further operations. Users are required to perform a PUT API
        on the storage system resource to complete the management of the storage system resource. An asynchronous task
        will be created as a result of this API call to discover available domains, target ports, and storage pools.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created storage system.
        """
        return self._client.create(resource, timeout=timeout)

    def get_host_types(self):
        """
        Gets the list of supported host types.

        Returns:
            list: Host types.
        """
        uri = self.URI + "/host-types"
        return self._client.get(uri)

    def get_storage_pools(self, id_or_uri):
        """
        Gets a list of Storage pools. Returns a list of storage pools belonging to the storage system referred by the
        Path property {ID} parameter or URI.

        Args:
            id_or_uri: Can be either the storage system ID (serial number) or the storage system URI.
        Returns:
            dict: Host types.
        """
        uri = self._client.build_uri(id_or_uri) + "/storage-pools"
        return self._client.get(uri)

    def get(self, id_or_uri):
        """
        Gets the specified storage system resource by ID or by URI.

        Args:
            id_or_uri: Can be either the storage system id or the storage system uri.

        Returns:
            dict: The storage system.
        """
        return self._client.get(id_or_uri)

    def update(self, resource, timeout=-1):
        """
        Updates the storage system. To complete the addition of a storage system for management by the appliance,
        this must be called after create() of a storage system.

        Args:
            resource (dict):
                Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated storage system.
        """
        return self._client.update(resource, timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes the storage system from OneView.

        Args:
            resource (dict):
                Object to delete
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Details of associated resource.
        """
        headers = {'If-Match': '*'}
        return self._client.delete(resource, force=force, timeout=timeout, custom_headers=headers)

    def get_managed_ports(self, id_or_uri, port_id_or_uri=''):
        """
        Gets all ports or a specific managed target port for the specified storage system.

        Args:
            id_or_uri: Can be either the storage system id or the storage system uri.
            port_id_or_uri: Can be either the port id or the port uri.

        Returns:
            dict: Managed ports.
        """
        if port_id_or_uri:
            uri = self._client.build_uri(port_id_or_uri)
            if "/managedPorts" not in uri:
                uri = self._client.build_uri(id_or_uri) + "/managedPorts" + "/" + port_id_or_uri

        else:
            uri = self._client.build_uri(id_or_uri) + "/managedPorts"

        return self._client.get_collection(uri)

    def get_by(self, field, value):
        """
        Gets all storage systems that match the filter.

        The search is case-insensitive.

        Args:
            Field: field name to filter.
            Value: value to filter.

        Returns:
            list: A list of storage systems.
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Retrieves a resource by its name.

        Args:
            name: Resource name.

        Returns:
            dict
        """
        return self._client.get_by_name(name=name)

    def get_by_ip_hostname(self, ip_hostname):
        """
        Retrieve a storage system by its IP.

        Works only with API version <= 300.

        Args:
            ip_hostname: Storage system IP or hostname.

        Returns:
            dict
        """
        resources = self._client.get_all()

        resources_filtered = [x for x in resources if x['credentials']['ip_hostname'] == ip_hostname]

        if resources_filtered:
            return resources_filtered[0]
        else:
            return None

    def get_by_hostname(self, hostname):
        """
        Retrieve a storage system by its hostname.

        Works only in API500 onwards.

        Args:
            hostname: Storage system hostname.

        Returns:
            dict
        """
        resources = self._client.get_all()

        resources_filtered = [x for x in resources if x['hostname'] == hostname]

        if resources_filtered:
            return resources_filtered[0]
        else:
            return None

    def get_reachable_ports(self, id_or_uri, start=0, count=-1, filter='', query='', sort='', networks=[]):
        """
        Gets the storage ports that are connected on the specified networks
        based on the storage system port's expected network connectivity.

        Returns:
            list: Reachable Storage Port List.
        """
        uri = self._client.build_uri(id_or_uri) + "/reachable-ports"

        if networks:
            elements = "\'"
            for n in networks:
                elements += n + ','
            elements = elements[:-1] + "\'"
            uri = uri + "?networks=" + elements

        return self._client.get(self._client.build_query_uri(start=start, count=count, filter=filter, query=query,
                                                             sort=sort, uri=uri))

    def get_templates(self, id_or_uri, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a list of volume templates. Returns a list of storage templates belonging to the storage system.

        Returns:
            list: Storage Template List.
        """
        uri = self._client.build_uri(id_or_uri) + "/templates"
        return self._client.get(self._client.build_query_uri(start=start, count=count, filter=filter,
                                                             query=query, sort=sort, uri=uri))
class ServerProfiles(object):
    URI = '/rest/server-profiles'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            'type': 'ServerProfileV5'
        }

    def create(self, resource, timeout=-1):
        """
        Creates a server profile using the information provided in the resource parameter. Connection requests can be
        one of the following types - port auto, auto and explicit. An explicit request is where the request includes
        the adapter, port and flexNic. An auto request is where none of the three are specified and a port auto
        request is where just the adapter and port are specified.

        Args:
            resource (dict): Object to create.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created server profile.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(resource=data, timeout=timeout)

    def update(self, resource, id_or_uri):
        """
        Allows a server profile object to have its configuration modified. These modifications can be as simple as a
        name or description change or much more complex changes around the assigned server and networking configuration.
        It should be noted that selection of a virtual or physical MAC or Serial Number is not mutable once a profile
        has been created, and attempts to change those elements will not be applied to the target profile. Connection
        requests can be one of the following types - port Auto, auto and explicit. An explicit request is where the
        request portId parameter includes the adapter, port and flexNic. An auto request is where portId is set to
        "Auto" and a port auto request is where just the portId parameter includes just the adapter and port.

        Args:
            id_or_uri: Could be either the server profile id or the server profile uri.
            resource (dict): Object to update.

        Returns:
            dict: The server profile resource.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(resource=data, uri=id_or_uri)

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Performs a specific patch operation for the given server profile.

        The supported operation is:
            Update the server profile from the server profile template.
                Operation: replace | Path: /templateCompliance | Value: Compliant

        Args:
            id_or_uri:
                Could be either the server profile id or the server profile uri
            operation:
                The type of operation: one of "add", "copy", "move", "remove", "replace", or "test".
            path:
                The JSON path the operation is to use. The exact meaning depends on the type of operation.
            value:
                The value to add or replace for "add" and "replace" operations, or the value to compare against
                for a "test" operation. Not used by "copy", "move", or "remove".

        Returns:
            dict: Server profile resource.
        """
        return self._client.patch(id_or_uri, operation, path, value, timeout)

    def delete(self, resource, timeout=-1):
        """
        Deletes a server profile object from the appliance based on its server profile UUID.

        Args:
            resource (dict): Object to delete.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the server profile was successfully deleted.
        """
        return self._client.delete(resource=resource, timeout=timeout)

    def delete_all(self, filter, timeout=-1, force=False):
        """
        Deletes all Server Profile objects from the appliance that match the provided filter. Filters are supported
        for the following profile attributes only - name, description, serialnumber, uuid, mactype, wwntype,
        serialnumbertype, status and state.

        Examples:
            >>> server_profile_client.delete_all(filter="name='Exchange Server'")
            # Remove all profiles that match the name "Exchange Server"

            >>> server_profile_client.delete_all(filter="name matches'%25Database%25'")
            # Remove all profiles that have the word "Database" in its name

        The filter function here operates very similar to the function defined for GET Server Profiles. It allows
        for both actual and partial matches of data in the profile. Any requests that wish to use a wildcard match
        must include a %25 as illustrated in the example. This is how that character is encoded for transmission to
        the appliance.

        Args:
            filter (dict): Object to delete.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the server profile was successfully deleted.
        """
        return self._client.delete_all(filter=filter, force=force, timeout=timeout)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of server profile based on optional sorting and filtering, and constrained by start and
        count parameters.
        Gets a list of server profiles based on optional sorting and filtering, and constrained by start and count
        parameters. Providing a -1 for the count parameter will restrict the result set size to 64 server profiles.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return.
                Providing a -1 for the count parameter will restrict the result set size to 64 server profile
                templates. The maximum number of profile templates is restricted to 256, i.e., if user requests more
                than 256, this will be internally limited to 256.
                The actual number of items in the response may differ from the
                requested count if the sum of start and count exceed the total number of items, or if returning the
                requested number of items would take too long.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
                Filters are supported for the name, description, serialNumber, uuid, affinity, macType, wwnType,
                serialNumberType, serverProfileTemplateUri, templateCompliance, status and state attributes.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of server profiles.
        """
        return self._client.get_all(start=start, count=count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Retrieves a server profile managed by the appliance by ID or by uri.

        Args:
            id_or_uri: Could be either the server profile resource id or uri.

        Returns:
            dict: The server profile resource.
        """
        return self._client.get(id_or_uri=id_or_uri)

    def get_by(self, field, value):
        """
        Get all server profile that matches a specified filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of server profiles.
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Gets a server profile by name.

        Args:
            name: Name of the server profile.

        Returns:
            dict: The server profile resource.
        """
        return self._client.get_by_name(name)

    def get_schema(self):
        """
        Generates the ServerProfile schema.

        Returns:
            dict: The server profile schema.
        """
        return self._client.get_schema()

    def get_compliance_preview(self, id_or_uri):
        """
        Gets the preview of manual and automatic updates required to make the server profile
        consistent with its template.

        Args:
            id_or_uri: Could be either the server profile resource id or uri.

        Returns:
            dict: Server profile compliance preview.
        """
        uri = self._client.build_uri(id_or_uri) + '/compliance-preview'
        return self._client.get(uri)

    def get_profile_ports(self, **kwargs):
        """
        Retrieves the port model associated with a server or server hardware type and enclosure group.

        Args:
            enclosureGroupUri (str):
                The URI of the enclosure group associated with the resource.
            serverHardwareTypeUri (str):
                The URI of the server hardware type associated with the resource.
            serverHardwareUri (str):
                The URI of the server hardware associated with the resource.

        Returns:
            dict: Profile port.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/profile-ports')
        return self._client.get(uri)

    def get_messages(self, id_or_uri):
        """
        Retrieve the error or status messages associated with the specified profile.

        Args:
            id_or_uri: Could be either the server profile resource id or uri.

        Returns:
            dict: Server Profile Health.
        """
        uri = self._client.build_uri(id_or_uri) + '/messages'
        return self._client.get(uri)

    def get_transformation(self, id_or_uri, **kwargs):
        """
        Transforms an existing profile by supplying a new server hardware type and/or enclosure group. A profile
        will be returned with a new configuration based on the capabilities of the supplied server hardware type
        and/or enclosure group. All deployed connections will have their port assignment set to 'Auto'.
        Re-selection of the server hardware may also be required. The new profile can subsequently be used for update
        the server profile but is not guaranteed to pass validation. Any incompatibilities will be flagged when the
        transformed server profile is submitted.

        Args:
            id_or_uri:
                Could be either the server profile resource id or uri.
            enclosureGroupUri (str):
                The URI of the enclosure group associated with the resource.
            serverHardwareTypeUri (str):
                The URI of the server hardware type associated with the resource.
            serverHardwareUri (str):
                The URI of the server hardware associated with the resource.

        Returns:
            dict: Server Profile.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/transformation', id_or_uri)
        return self._client.get(uri)

    def get_available_networks(self, **kwargs):
        """
        Retrieves the list of Ethernet networks, Fibre Channel networks and network sets that are available to a
        server profile along with their respective ports.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           functionType (str):
               The FunctionType (Ethernet or FibreChannel) to filter the list of networks returned.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           serverHardwareUri (str):
               The URI of the server hardware associated with the resource.
           view (str):
               Return a specific subset of the attributes of the resource or collection, by specifying the name of a
               predefined view. The default view is expand - show all attributes of the resource and all elements of
               collections of resources.

               Values:
                   Ethernet
                       Specifies that the connection is to an Ethernet network or a network set.
                   FibreChannel
                       Specifies that the connection is to a Fibre Channel network.

        Returns:
            list: Available networks.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-networks')
        return self._client.get(uri)

    def get_available_servers(self, **kwargs):
        """
        Retrieves the list of available servers.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           profileUri (str):
               The URI of the server profile resource.

        Returns:
            list: Available servers.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-servers')
        return self._client.get(uri)

    def get_available_storage_system(self, **kwargs):
        """
        Retrieve a specific storage system and its associated volumes that are available to the server profile based
        on the given server hardware type and enclosure group.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           storageSystemId (str):
               The storage system ID associated with the resource.

        Returns:
            dict: Available storage system.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-storage-system')
        return self._client.get(uri)

    def get_available_storage_systems(self, start=0, count=-1, filter='', sort='', **kwargs):
        """
        Retrieves the list of the storage systems and their associated volumes that are available to the server profile
        based on the given server hardware type and enclosure group.

        Args:
           count:
               The number of resources to return. A count of -1 requests all the items. The actual number of items in
               the response may differ from the requested count if the sum of start and count exceed the total
               number of items.
           start:
               The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
               first available item.
           filter:
               A general filter/query string to narrow the list of items returned. The default is no filter - all
               resources are returned.
           sort:
               The sort order of the returned data set. By default, the sort order is based on create time, with the
               oldest entry first.
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.

        Returns:
            list: Available storage systems.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-storage-systems')
        return self._client.get_all(start=start, count=count, filter=filter, sort=sort, uri=uri)

    def get_available_targets(self, **kwargs):
        """
        Retrieves a list of the target servers and empty device bays that are available for assignment to the server
        profile.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           profileUri (str):
               The URI of the server profile associated with the resource

        Returns:
            list: List of available servers and bays.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-targets')
        return self._client.get(uri)

    def __build_uri_with_query_string(self, kwargs, sufix_path, id_or_uri=None):
        uri = self.URI
        if id_or_uri:
            uri = self._client.build_uri(id_or_uri)

        query_string = '&'.join('{}={}'.format(key, kwargs[key]) for key in sorted(kwargs))
        return uri + sufix_path + '?' + query_string
class UplinkSets(object):
    URI = '/rest/uplink-sets'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self._ethernet_network = EthernetNetworks(con)
        self.__default_values = {
            "type": "uplink-setV3",
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated list of uplink sets based on optional sorting and filtering, and constrained by start and
        count parameters.
        Filters can be used in the URL to control the number of uplink sets that are returned.
        With no filters specified, the API returns all uplink sets.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of uplink sets.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets an uplink set with the specified ID
        Args:
            id_or_uri:
                Could be either the uplink set id or the uplink set uri

        Returns:
            dict: The uplink set
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Get all uplink sets that match the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: Uplink sets

        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates an uplink set.

        Args:
            resource: dict object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Created resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates an uplink set.

        Args:
            resource (dict): Resource to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Updated resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes an uplink set. If the uplink set was carrying a Fibre Channel (FC) network, any connections which are
        deployed and using the FC network will be placed into a 'Failed' state.

        Args:
            resource: Resource to delete or the resource ID
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

            Returns:
                bool: True if successfully deleted

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_ethernet_networks(self, id_or_uri):
        """
        Gets a list of associated ethernet networks of an uplink set
        Args:
            id_or_uri:
                Could be either the uplink set id or the uplink set uri

        Returns:
            list: Associated ethernet networks
        """
        uplink = self.get(id_or_uri)
        network_uris = uplink.get('networkUris')
        networks = []
        if network_uris:
            for uri in network_uris:
                networks.append(self._ethernet_network.get(uri))
        return networks

    def add_ethernet_networks(self, id_or_uri, ethernet_id_or_uris):
        """
        Adds existing ethernet networks to an uplink set
        Args:
            id_or_uri:
                Could be either the uplink set id or the uplink set uri
            ethernet_id_or_uris:
                Could be either one or more ethernet network id or ethernet network uri

        Returns:
            dict: The updated uplink set
        """
        return self.__set_ethernet_uris(id_or_uri, ethernet_id_or_uris, operation="add")

    def remove_ethernet_networks(self, id_or_uri, ethernet_id_or_uris):
        """
        Remove existing ethernet networks of an uplink set
        Args:
            id_or_uri:
                Could be either the uplink set id or the uplink set uri
            ethernet_id_or_uris:
                Could be either one or more ethernet network id or ethernet network uri

        Returns:
            dict: The updated uplink set
        """
        return self.__set_ethernet_uris(id_or_uri, ethernet_id_or_uris, operation="remove")

    def __set_ethernet_uris(self, id_or_uri, ethernet_id_or_uris, operation="add"):
        if not isinstance(ethernet_id_or_uris, list):
            ethernet_id_or_uris = [ethernet_id_or_uris]

        uplink = self.get(id_or_uri)

        associated_enets = uplink.get('networkUris', [])

        for i, enet in enumerate(ethernet_id_or_uris):
            ethernet_id_or_uris[i] = enet if '/' in enet else self._ethernet_network.URI + '/' + enet

        if operation == "remove":
            enets_to_update = sorted(list(set(associated_enets) - set(ethernet_id_or_uris)))
        elif operation == "add":
            enets_to_update = sorted(list(set(associated_enets).union(set(ethernet_id_or_uris))))
        else:
            raise ValueError("Value {} is not supported as operation. The supported values are: ['add', 'remove']")

        if set(enets_to_update) != set(associated_enets):
            uplink['networkUris'] = enets_to_update
            return self.update(uplink)
        else:
            return uplink
Beispiel #13
0
class Racks(object):
    URI = '/rest/racks'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a set of rack resources according to the specified parameters. Filters can be used to get a specific set
        of racks. With no filters specified, the API returns a potentially paginated list of all the racks
        subject to start/count/sort parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items, or
                if returning the requested number of items would take too long.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default
                 is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns: list of racks
        """
        return self._client.get_all(start, count, filter=filter, sort=sort, query=query)

    def get(self, id_or_uri):
        """
        Gets a rack with the specified ID or URI
        Args:
            id_or_uri:
                Could be either the rack id or the rack uri

        Returns:
            dict: The rack
        """
        return self._client.get(id_or_uri)

    def get_device_topology(self, id_or_uri):
        """
        Retrieves the topology information for the rack resource specified by id or uri.

        Args:
            id_or_uri: Could be either the resource id or the resource uri

        Return:
            dict: device topology
        """
        uri = self._client.build_uri(id_or_uri) + "/deviceTopology"
        return self._client.get(uri)

    def get_by(self, field, value):
        """
        Get all racks that match the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            dict: rack

        """
        return self._client.get_by(field, value)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes the specified rack.

        Args:
            resource: dict object to remove
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Result status

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def add(self, information, timeout=-1):
        """
        Adds a rack resource based upon the attributes specified. All attributes without default values must be
        specified in the POST body. The response contains the rack resource as added to the appliance with default and
        assigned properties expanded. The id and uri are assigned by the management appliance and are used to uniquely
        identify this particular resource.

        Args:
            resource: rack information
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: added rack.

        """
        return self._client.create(information, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the specified rack resource. The properties that are omitted (not included as part of the request body)
        are reset to their respective default values. The id and uuid properties are required and cannot be changed.
        To update existing racks first perform a get() request to retrieve the current properties, update the desired
        properties, and then update() the request body containing the new representation of the resource.
        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated rack

        """
        return self._client.update(resource, timeout=timeout)
class ApplianceDeviceSNMPv3Users(object):
    """
    ApplianceDeviceSNMPv3Users API client [Available only since API 600].

    As part of SNMPv3 trap forwarding support, the appliance provides APIs for creating User-based Security Model (USM) and forwarding destinations.
    The following protocols are supported while defining USM.

    Authentication protocols: MD5 / SHA1 / SHA256 / SHA384 / SHA512
    Privacy protocols: AES / DES
    The security levels supported while defining USM are None, Authentication only and both Authentication and Privacy.

    """
    URI = '/rest/appliance/snmpv3-trap-forwarding/users'

    def __init__(self, con):
        self._client = ResourceClient(con, self.URI)

    def create(self, resource, timeout=-1):
        """
        Creates a new SNMPv3 user.
        This user will be used for sending the SNMPv3 trap to the associated destinations.
        One user can be assigned to multiple destinations.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.

        """
        return self._client.create(resource, timeout=timeout)

    def get(self, id_or_uri):
        """
        Returns the SNMPv3 user with the specified ID, if it exists.

        Args:
            id_or_uri: ID or URI of SNMPv3 user.

        Returns:
            dict: Appliance SNMPv3 user.
        """
        return self._client.get(id_or_uri)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Lists all SNMPv3 Users.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of SNMPv3 Users.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets all SNMPv3 users that match the filter.
        The search is case-insensitive.

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of SNMPv3 Users.
        """
        return self._client.get_by(field, value)

    def delete_all(self, filter=None, timeout=-1):
        """
        Delete an SNMPv3 User based on User name specified in filter. The user will be deleted only if it has no associated destinations.

        Args:
            username: ID or URI of SNMPv3 user.
            filter: A general filter/query string to narrow the list of items returned.
                    The default is no filter - all resources are returned.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete_all(filter=filter, timeout=timeout)

    def delete(self, id_or_uri, timeout=-1):
        """
        Delete an SNMPv3 User based on User Id specified in {Id}.
        The user will be deleted only if it has no associated destinations.

        Args:
            id_or_uri: dict object to delete
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(id_or_uri, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates SNMPv3 User based on User Id as specified in {Id}

        Args:
            resource: dict object with changes.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Updated appliance SNMPv3 user.
        """
        return self._client.update(resource, timeout=timeout)
class PowerDevices(object):
    URI = '/rest/power-devices'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a set of power delivery device resources according to the specified parameters. Filters can be used to get
        a specific set of power delivery devices. With no filters specified, the API returns a potentially paginated
        list of all the power delivery device resources subject to start/count/sort parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default
                 is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
             list of power devices
        """
        return self._client.get_all(start, count, filter=filter, sort=sort, query=query)

    def get(self, id_or_uri):
        """
        Gets a single power delivery device resource based upon its uri or id.

        Args:
            id_or_uri:
                Could be either the power device id or the uri

        Returns:
            dict: The power device
        """
        return self._client.get(id_or_uri)

    def add(self, information, timeout=-1):
        """
        Adds a power delivery device resource based upon the attributes specified. Use this method to create a
        representation of power delivery devices that provide power to other resources but cannot otherwise be
        discovered by the management appliance.

        Args:
            information:
                power device information
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: added power device.
        """
        return self._client.create(information, timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Deletes the set of power-devices according to the specified parameters. A filter is required to identify the
        set of resources to be deleted.

        Args:
            resource: dict object to remove
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
             bool: operation success
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def add_ipdu(self, information, timeout=-1):
        """
        Add an HP iPDU and bring all components under management by discovery of its management module. Bring the
        management module under exclusive management by the appliance, configure any management or data collection
        settings, and create a private set of administrative credentials to enable ongoing communication and management
        of the iPDU. Use "force" to claim the device, even if claimed by another management appliance

        Args:
            resource: power device information
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: added power device.
        """
        uri = self.URI + "/discover"
        return self._client.create(information, uri=uri, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the resource for the specified {id}. The properties that are omitted (not included as part of the the
        request body) are reset to their respective default values. The id and uuid properties are required and cannot
        be changed.

        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated power device
        """
        return self._client.update(resource, timeout=timeout)

    def get_power_state(self, id_or_uri):
        """
        Gets the power state (on, off or unknown) of the specified power delivery device that supports power control.
        The device must be an HP Intelligent Outlet.

        Args:
            id_or_uri:
                Could be either the power device id or the uri

        Returns:
            str: The power state
        """
        uri = self._client.build_uri(id_or_uri) + "/powerState"
        return self._client.get(uri)

    def update_power_state(self, id_or_uri, power_state):
        """
        Sets the power state of the specified power delivery device. The device must be an HP Intelligent Outlet.

        Args:
            id_or_uri:
                Could be either the power device id or the uri
            power_state:
                {"powerState":"On|Off"}

        Returns:
            str: The power state
        """
        uri = self._client.build_uri(id_or_uri) + "/powerState"
        return self._client.update(power_state, uri)

    def update_refresh_state(self, id_or_uri, refresh_state_data):
        """
        Refreshes a given intelligent power delivery device.

        Args:
            id_or_uri:
                Could be either the power device id or the uri
            refresh_state_data:
                Power device refresh request

        Returns:
            str: The power state
        """
        uri = self._client.build_uri(id_or_uri) + "/refreshState"
        return self._client.update(refresh_state_data, uri=uri)

    def remove_synchronous(self, resource, force=False, timeout=-1):
        """
        Deletes the resource specified by {id} synchronously.

        Args:
            resource: dict object to remove
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: operation success
        """
        uri = self._client.build_uri(resource['uri']) + "/synchronous"
        remove_resource = {'uri': uri}
        return self._client.delete(remove_resource, force=force, timeout=timeout)

    def get_uid_state(self, id_or_uri):
        """
        Retrieves the unit identification (UID) state (on, off, unknown) of the specified power outlet or extension bar
        resource. The device must be an HP iPDU component with a locator light (HP Intelligent Load Segment,
        HP AC Module, HP Intelligent Outlet Bar, or HP Intelligent Outlet).

        Args:
            id_or_uri:
                Could be either the power device id or the uri

        Returns:
            str: unit identification (UID) state
        """
        uri = self._client.build_uri(id_or_uri) + "/uidState"
        return self._client.get(uri)

    def update_uid_state(self, id_or_uri, refresh_state_data):
        """
        Sets the unit identification (UID) light state of the specified power delivery device. The device must be an
        HP iPDU component with a locator light (HP Intelligent Load Segment, HP AC Module, HP Intelligent Outlet Bar,
        or HP Intelligent Outlet)

        Args:
            id_or_uri:
                Could be either the power device id or the uri
            refresh_state_data:
                Power device refresh request

        Returns:
            str: The UID state
        """
        uri = self._client.build_uri(id_or_uri) + "/uidState"
        return self._client.update(refresh_state_data, uri)

    def get_utilization(self, id_or_uri, fields=None, filter=None, refresh=False, view=None):
        """
        Retrieves historical utilization data for the specified metrics, and time span. The device must be a component
        of an HPE iPDU.

        Args:
            id_or_uri:
                The power device id or the resource uri
            fields:
                Name of the metric(s) to be retrieved in the format METRIC[,METRIC]...If unspecified, all metrics
                supported are returned. Power delivery devices support the following utilization metrics:

                    * AveragePower
                        Average power consumption in Watts during this sample interval.
                    * PeakPower
                        Peak power consumption in Watts during this sample interval.

            filter:
                Filters should be in the format FILTER_NAME=VALUE[,FILTER_NAME=VALUE]...

                E.g.: 'startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z'

                startDate:
                    Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is
                    determined by the endDate minus 24 hours.
                endDate:
                    End date of requested starting time range in ISO 8601 format. When omitted the endDate includes the
                    latest data sample available.

                If an excessive number of samples would otherwise be returned, the results will be segmented. The caller
                is responsible for comparing the returned sliceStartTime with the requested startTime in the response.
                If the sliceStartTime is greater than the oldestSampleTime and the requested start time, the caller is
                responsible for repeating the request with endTime set to sliceStartTime to obtain the next segment.
                This process is repeated until the full data set is retrieved.

                If the resource has no data, the UtilizationData is still returned, but will contain no samples and
                sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set
                appropriately (null if no data is available). If the filter just does not happen to overlap the data
                that a resource does have, then the metric history service will return null sample values for any
                missing samples.

            refresh:
                Specifies that if necessary an additional request will be queued to obtain the most recent utilization
                data from the enclosure. The response will not include any refreshed data. To track the availability
                of the newly collected data, monitor the TaskResource identified by the refreshTaskUri property in
                the response. If null, no refresh was queued.
            view:
                Specifies the resolution interval length of the samples to be retrieved. This is reflected in the
                resolution in the returned response. Utilization data is automatically purged to stay within storage
                space constraints. Supported views are listed below.

                native (DEFAULT)
                    Resolution of the samples returned will be one sample for each 5-minute time period. This is the
                    default view and matches the resolution of the data returned by the enclosure. Samples at this
                    resolution are retained up to one year.
                hour
                    Resolution of the samples returned will be one sample for each 60-minute time period. Samples are
                    calculated by averaging the available 5-minute data samples that occurred within the hour, except
                    for PeakPower which is calculated by reporting the peak observed 5-minute sample value data during
                    the hour. Samples at this resolution are retained up to three years.
                day
                    Resolution of the samples returned will be one sample for each 24-hour time period. One day is a
                    24-hour period that starts at midnight GMT regardless of the time zone in which the appliance or
                    client is located. Samples are calculated by averaging the available 5-minute data samples that
                    occurred during the day, except for PeakPower which is calculated by reporting the peak observed
                    5-minute sample value data during the day. Samples at this resolution are retained up to three
                    years.

        Returns:
            dict: Utilization data
        """

        return self._client.get_utilization(id_or_uri, fields, filter, refresh, view)

    def get_by(self, field, value):
        """
        Get all power devices that match the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            dict: power devices
        """
        return self._client.get_by(field, value)
class FcNetworks(object):
    URI = '/rest/fc-networks'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            'autoLoginRedistribution': False,
            'type': 'fc-networkV2',
            'linkStabilityTime': 30,
            'fabricType': 'FabricAttach',
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Fibre Channel networks. The collection is based on optional
        sorting and filtering, and constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.

                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of Fibre Channel networks.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a Fibre Channel network.
        Any deployed connections that are using the network are placed in the 'Failed' state.

        Args:
            resource: dict object to delete
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id):
        """
        Gets the Fibre Channel network with the specified ID.

        Args:
            id: ID of Fibre Channel network.

        Returns:
            dict: The Fibre Channel network.
        """
        return self._client.get(id)

    def create(self, resource, timeout=-1):
        """
        Creates a Fibre Channel network.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a Fibre Channel network.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Updated resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def get_by(self, field, value):
        """
        Get all Fibre Channel networks that matches the filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Fibre Channel networks.
        """
        return self._client.get_by(field, value)
Beispiel #17
0
class ServerProfileTemplate(object):
    URI = '/rest/server-profile-templates'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {'type': 'ServerProfileTemplateV1'}

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of server profile templates based on optional sorting and filtering and is constrained by start and
        count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return.
                Providing a -1 for the count parameter will restrict the result set size to 64 server profile
                templates. The maximum number of profile templates is restricted to 256, that is, if user requests more
                than 256, this will be internally limited to 256.
                The actual number of items in the response might differ from the
                requested count if the sum of start and count exceeds the total number of items, or if returning the
                requested number of items would take too long.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The default is no filter; all
                resources are returned.
                Filters are supported for the name, description, affinity, macType, wwnType, serialNumberType, status,
                serverHardwareTypeUri, enclosureGroupUri, and firmware.firmwareBaselineUri attributes.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of server profile templates.

        """
        return self._client.get_all(start=start,
                                    count=count,
                                    filter=filter,
                                    sort=sort)

    def get(self, id_or_uri):
        """
        Gets a server profile template resource by ID or by URI.

        Args:
            id_or_uri: Can be either the server profile template resource ID or URI.

        Returns:
            dict: The server profile template resource.
        """
        return self._client.get(id_or_uri=id_or_uri)

    def get_by(self, field, value):
        """
        Gets all server profile templates that match a specified filter.
        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of server profile templates.
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Gets a server profile template by name.

        Args:
            name: Name of the server profile template.

        Returns:
            dict: The server profile template resource.
        """
        return self._client.get_by_name(name)

    def create(self, resource, timeout=-1):
        """
        Creates a server profile template.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(resource=data, timeout=timeout)

    def update(self, resource, id_or_uri):
        """
        Allows a server profile template object to have its configuration modified. These modifications can be as
        simple as a name or description change or much more complex changes around the networking configuration.

        Args:
            id_or_uri: Can be either the template id or the template uri.
            resource (dict): Object to update.

        Returns:
            dict: The server profile template resource.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(resource=data, uri=id_or_uri)

    def delete(self, resource, timeout=-1):
        """
        Deletes a server profile template object from the appliance based on its profile template UUID.

        Args:
            resource: Object to delete.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates whether the resource was successfully deleted.
        """
        return self._client.delete(resource=resource, timeout=timeout)

    def get_new_profile(self, id_or_uri):
        """
        A profile object will be returned with the configuration based on this template. Specify the profile name and
        server hardware to assign. If template has any fiber channel connection (which is specified as bootable) but no
        boot target was defined, that connection will be instantiated as a non-bootable connection. So modify that
        connection to change it to bootable and to specify the boot target.

        Args:
            id_or_uri: Can be either the server profile template resource ID or URI.

        Returns:
            dict: The server profile resource.
        """
        uri = self._client.build_uri(id_or_uri) + "/new-profile"
        return self._client.get(id_or_uri=uri)
class StoragePools(object):
    URI = '/rest/storage-pools'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of storage pools. Returns a list of storage pools based on optional sorting and filtering, and
        constrained by start and count parameters. The following storage pool attributes can be used with filtering and
        sorting operation: name, domain, deviceType, deviceSpeed, supportedRAIDLevel, status and state.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of storage pools.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def add(self, resource, timeout=-1):
        """
        Adds storage pool for management by the appliance.

        Args:
            resource (dict):
                Object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Created storage pool

        """
        return self._client.create(resource, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets the specified storage pool resource by ID or by uri.

        Args:
            id_or_uri: Could be either the storage pool id or the storage pool uri.

        Returns:
            dict: The storage pool.
        """
        return self._client.get(id_or_uri)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes an imported storage pool from OneView.

        Args:
            resource (dict):
                Object to remove.
            force (bool):
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Details of associated resource.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_by(self, field, value):
        """
        Get all storage pools that match the filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of storage pools.
        """
        return self._client.get_by(field, value)
Beispiel #19
0
class EthernetNetworks(object):
    URI = '/rest/ethernet-networks'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            "ethernetNetworkType": "Tagged",
            "type": "ethernet-networkV3"
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Ethernet networks. The collection is based on optional sorting and filtering
        and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of ethernet networks.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes an Ethernet network.

        Any deployed connections that are using the network are placed in the 'Failed' state.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets the Ethernet network.

        Args:
            id_or_uri: ID or URI of Ethernet network.

        Returns:
            dict: The ethernet network.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Creates an Ethernet network.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def create_bulk(self, resource, timeout=-1):
        """
        Creates bulk Ethernet networks.

        Args:
            resource (dict): Specifications to create in bulk.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            list: List of created Ethernet Networks.

        """
        data = {"type": "bulk-ethernet-network"}
        data.update(resource)
        uri = self.URI + '/bulk'
        self._client.create(data, uri=uri, timeout=timeout)

        return self.get_range(resource['namePrefix'], resource['vlanIdRange'])

    def get_range(self, name_prefix, vlan_id_range):
        """
        Gets a list of Ethernet Networks that match the 'given name_prefix' and the 'vlan_id_range'.

        Examples:
            >>> enet.get_range('Enet_name', '1-2,5')
                # The result contains the ethernet network with names:
                ['Enet_name_1', 'Enet_name_2', 'Enet_name_5']

            >>> enet.get_range('Enet_name', '2')
                # The result contains the ethernet network with names:
                ['Enet_name_1', 'Enet_name_2']

        Args:
            name_prefix: The Ethernet Network prefix
            vlan_id_range: A combination of values or ranges to be retrieved. For example, '1-10,50,51,500-700'.

        Returns:
            list: A list of Ethernet Networks.

        """
        filter = '"\'name\' matches \'{}\_%\'"'.format(name_prefix)
        ethernet_networks = self.get_all(filter=filter, sort='vlanId:ascending')

        vlan_ids = self.dissociate_values_or_ranges(vlan_id_range)

        for net in ethernet_networks[:]:
            if int(net['vlanId']) not in vlan_ids:
                ethernet_networks.remove(net)
        return ethernet_networks

    def dissociate_values_or_ranges(self, vlan_id_range):
        """
        Build a list of vlan ids given a combination of ranges and/or values

        Examples:
            >>> enet.dissociate_values_or_ranges('1-2,5')
                [1, 2, 5]

            >>> enet.dissociate_values_or_ranges('5')
                [1, 2, 3, 4, 5]

            >>> enet.dissociate_values_or_ranges('4-5,7-8')
                [4, 5, 7, 8]

        Args:
            vlan_id_range: A combination of values or ranges. For example, '1-10,50,51,500-700'.

        Returns:
            list: vlan ids
        """
        values_or_ranges = vlan_id_range.split(',')
        vlan_ids = []
        # The expected result is different if the vlan_id_range contains only one value
        if len(values_or_ranges) == 1 and '-' not in values_or_ranges[0]:
            vlan_ids = list(range(1, int(values_or_ranges[0]) + 1))
        else:
            for value_or_range in values_or_ranges:
                value_or_range.strip()
                if '-' not in value_or_range:
                    vlan_ids.append(int(value_or_range))
                else:
                    start, end = value_or_range.split('-')
                    range_ids = range(int(start), int(end) + 1)
                    vlan_ids.extend(range_ids)

        return vlan_ids

    def update(self, resource, timeout=-1):
        """
        Updates an Ethernet network.

        Args:
            resource: dict object to update
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns: Updated resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all Ethernet networks that match the filter.
        The search is case-insensitive.

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of ethernet networks.
        """
        return self._client.get_by(field, value)

    def get_associated_profiles(self, id_or_uri):
        """
        Gets the URIs of profiles which are using an Ethernet network.

        Args:
            id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            list: URIs of the associated profiles.

        """
        uri = self._client.build_uri(id_or_uri) + "/associatedProfiles"
        return self._client.get(uri)

    def get_associated_uplink_groups(self, id_or_uri):
        """
        Gets the uplink sets which are using an Ethernet network.

        Args:
            id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            list: URIs of the associated uplink sets.

        """
        uri = self._client.build_uri(id_or_uri) + "/associatedUplinkGroups"
        return self._client.get(uri)
class FirmwareDrivers(object):
    URI = '/rest/firmware-drivers'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Firware Drivers. The collection is based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: list of firmware baseline resources.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to
        filter the list of resources returned.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: List of firmware baseline resources.
        """
        firmwares = self.get_all()
        matches = []
        for item in firmwares:
            if item.get(field) == value:
                matches.append(item)
        return matches

    def get(self, id_or_uri):
        """
        Gets the individual firmware baseline resource for the given URI. Note that the view
        parameter is not currently supported.

        Args:
            id: ID or URI of firmware baseline resource.

        Returns:
            dict: Firmware baseline resource.
        """
        return self._client.get(id_or_uri)

    def delete(self, resource, force=False, timeout=-1):
        """
        Delete the firmware baseline resource with the specified id. If force is set to true, the firmware baseline
        resource will be deleted even if it is assigned to devices.

        Args:
            resource (dict): Object to delete
            force: If set to true the operation completes despite any problems with
                network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)
Beispiel #21
0
class UnmanagedDevices(object):
    URI = '/rest/unmanaged-devices'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a set of unmanaged device resources according to the specified parameters. Filters can be used to get a
        specific set of unmanaged devices. With no filters specified, the API returns a potentially paginated list of
        all the unmanaged device resources subject to start/count/sort parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default
                 is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
             list: Unmanaged Devices
        """
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    query=query)

    def get(self, id_or_uri):
        """
        Gets a single Unmanaged Device resource based upon its uri or id.

        Args:
            id_or_uri:
                Can be either the Unmanaged Device id or the uri

        Returns:
            dict: The Unmanaged Device
        """
        return self._client.get(id_or_uri)

    def add(self, information, timeout=-1):
        """
        Adds an unmanaged device resource based upon the attributes specified. Use this method to create an unmanaged
        device to represent resources that consume space within a rack, or consume power from a power delivery device
        but cannot otherwise be represented by the management appliance.

        Args:
            information:
                Unmanaged Device information
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Added Unmanaged Device
        """
        return self._client.create(information, timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Deletes the resource specified.

        Args:
            resource:
                 Dict object to remove
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                 Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                 in OneView; it just stops waiting for its completion.

        Returns:
             bool: operation success
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def remove_all(self, filter, force=False, timeout=-1):
        """
        Deletes the set of unmanaged-devices according to the specified parameters. A filter is required to identify
        the set of resources to be deleted.

        Args:
            filter:
                 A general filter/query string to narrow the list of items that will be removed.
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                 Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                 in OneView; it just stops waiting for its completion.

        Returns:
             bool: operation success
        """
        return self._client.delete_all(filter=filter,
                                       force=force,
                                       timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the resource for the specified. The properties that are omitted (not included as part of the the
        request body) are reset to their respective default values. The id and uuid properties are required and cannot
        be changed.

        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated Unmanaged Devices
        """
        return self._client.update(resource, timeout=timeout)

    def get_environmental_configuration(self, id_or_uri):
        """
        Returns a description of the environmental configuration (supported feature set, calibrated minimum & maximum
        power, location & dimensions, ...) of the resource.

        Args:
            id_or_uri:
                Can be either the Unmanaged Device id or the uri

        Returns:
            dict:
                EnvironmentalConfiguration
        """
        uri = self._client.build_uri(id_or_uri) + "/environmentalConfiguration"
        return self._client.get(uri)

    def get_by(self, field, value):
        """
        Gets all Unmanaged Devices that match the filter
        The search is case-insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            dict: Unmanaged Devices
        """
        return self._client.get_by(field, value)
class ServerProfileTemplate(object):
    URI = '/rest/server-profile-templates'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            'type': 'ServerProfileTemplateV1'
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of server profile templates based on optional sorting and filtering, and constrained by start and
        count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return.
                Providing a -1 for the count parameter will restrict the result set size to 64 server profile
                templates. The maximum number of profile templates is restricted to 256, i.e., if user requests more
                than 256, this will be internally limited to 256.
                The actual number of items in the response may differ from the
                requested count if the sum of start and count exceed the total number of items, or if returning the
                requested number of items would take too long.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
                Filters are supported for the name, description, affinity, macType, wwnType, serialNumberType, status,
                serverHardwareTypeUri, enclosureGroupUri, firmware.firmwareBaselineUri attributes.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of server profile templates.

        """
        return self._client.get_all(start=start, count=count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a server profile template resource by ID or by uri
        Args:
            id_or_uri: Could be either the server profile template resource id or uri

        Returns:
            dict: The server profile template resource
        """
        return self._client.get(id_or_uri=id_or_uri)

    def get_by(self, field, value):
        """
        Get all server profile templates that matches a specified filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of server profile templates
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Gets a server profile template by name.

        Args:
            name: Name of the server profile template

        Returns:
            dict: The server profile template resource
        """
        return self._client.get_by_name(name)

    def create(self, resource, timeout=-1):
        """
         Creates a server profile template.

        Args:
            resource: dict object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns: Created resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(resource=data, timeout=timeout)

    def update(self, resource, id_or_uri):
        """
        Allows a server profile template object to have its configuration modified. These modifications can be as
        simple as a name or description change or much more complex changes around the networking configuration.
        It should be noted that selection of a virtual or physical MAC or Serial Number type is not mutable once a
        profile template has been created, and attempts to change those elements will not be applied to the target
        profile template. Connection requests can be one of the following types - port Auto, auto and explicit.
        An explicit request is where the request portId parameter includes the adapter, port and flexNic. An auto
        request  is where portId is set to "Auto" and a port auto request is where just the portId parameter includes
        just the adapter and port. The fields listed as required in the Request Body section need to be specified
        only when their associated parent is used.

        Args:
            id_or_uri: Could be either the template id or the template uri
            resource (dict): object to update

        Returns:
            dict: The server profile template resource
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(resource=data, uri=id_or_uri)

    def delete(self, resource, timeout=-1):
        """
        Deletes a server profile template object from the appliance based on its profile template UUID.

        Args:
            resource: dict object to delete
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool:
        """
        return self._client.delete(resource=resource, timeout=timeout)

    def get_new_profile(self, id_or_uri):
        """
         A profile object will be returned with the configuration based on this template. Specify the profile name and
         server hardware to assign. If template has any fibre channel connection which is specified as bootable but no
         boot target was defined, that connection will be instantiated as a non-bootable connection. So modify that
         connection to change it to bootable and to specify the boot target. This profile object can subsequently be
         used for the POST https://{appl}/rest/server-profiles/ API.

        Args:
            id_or_uri: Could be either the server profile template resource id or uri

        Returns:
            dict: The server profile resource
        """
        uri = self._client.build_uri(id_or_uri) + "/new-profile"
        return self._client.get(id_or_uri=uri)
class ServerProfiles(object):
    """
    Server Profile API client.

    """
    URI = '/rest/server-profiles'

    DEFAULT_VALUES = {
        '200': {
            "type": "ServerProfileV5"
        },
        '300': {
            "type": "ServerProfileV6"
        },
        '500': {
            "type": "ServerProfileV7"
        }
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def create(self, resource, timeout=-1):
        """
        Creates a server profile using the information provided in the resource parameter.

        Args:
            resource (dict): Object to create.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created server profile.
        """
        return self._client.create(resource=resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    def update(self, resource, id_or_uri):
        """
        Allows the configuration of a server profile object to be modified.

        Args:
            id_or_uri: Can be either the server profile id or the server profile uri.
            resource (dict): Object to update.

        Returns:
            dict: The server profile resource.
        """
        # Removes related fields to serverHardware in case of unassign
        if resource.get('serverHardwareUri') is None:
            resource.pop('enclosureBay', None)
            resource.pop('enclosureUri', None)
        return self._client.update(resource=resource,
                                   uri=id_or_uri,
                                   default_values=self.DEFAULT_VALUES)

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Performs a specific patch operation for the given server profile.

        The supported operation:
            Updates the server profile from the server profile template.
                Operation: replace | Path: /templateCompliance | Value: Compliant

        Args:
            id_or_uri:
                Can be either the server profile id or the server profile uri
            operation:
                The type of operation: one of "add", "copy", "move", "remove", "replace", or "test".
            path:
                The JSON path the operation is to use. The exact meaning depends on the type of operation.
            value:
                The value to add or replace for "add" and "replace" operations, or the value to compare against
                for a "test" operation. Not used by "copy", "move", or "remove".

        Returns:
            dict: Server profile resource.
        """
        return self._client.patch(id_or_uri, operation, path, value, timeout)

    def delete(self, resource, timeout=-1):
        """
        Deletes a server profile object from the appliance based on its server profile UUID.

        Args:
            resource (dict): Object to delete.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates whether the server profile was successfully deleted.
        """
        return self._client.delete(resource=resource, timeout=timeout)

    def delete_all(self, filter, timeout=-1, force=False):
        """
        Deletes all Server Profile objects from the appliance that match the provided filter.
        Filters are supported only for the following profile attributes:  name, description, serialnumber, uuid,
        mactype, wwntype, serialnumbertype, status, and state.


        Examples:
            >>> server_profile_client.delete_all(filter="name='Exchange Server'")
            # Remove all profiles that match the name "Exchange Server"

            >>> server_profile_client.delete_all(filter="name matches'%25Database%25'")
            # Remove all profiles that have the word "Database" in its name

        The filter function here operates similarly to the function defined for GET Server Profiles. It allows
        for both actual and partial matches of data in the profile. Any requests that use a wildcard match
        must include a %25 as illustrated in the previous example. This is how you encode that character for
        transmission to the appliance.

        Args:
            filter (dict): Object to delete.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates whether the server profile was successfully deleted.
        """
        return self._client.delete_all(filter=filter,
                                       force=force,
                                       timeout=timeout)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of server profiles based on optional sorting and filtering and is constrained by start and
        count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return.
                Providing a -1 for the count parameter will restrict the result set size to 64 server profile
                templates. The maximum number of profile templates is restricted to 256, that is, if user requests more
                than 256, this will be internally limited to 256.
                The actual number of items in the response might differ from the
                requested count if the sum of start and count exceeds the total number of items, or if returning the
                requested number of items would take too long.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
                Filters are supported for the name, description, serialNumber, uuid, affinity, macType, wwnType,
                serialNumberType, serverProfileTemplateUri, templateCompliance, status, and state attributes.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of server profiles.
        """
        return self._client.get_all(start=start,
                                    count=count,
                                    filter=filter,
                                    sort=sort)

    def get(self, id_or_uri):
        """
        Retrieves a server profile managed by the appliance by ID or by URI.

        Args:
            id_or_uri: Can be either the server profile resource ID or URI.

        Returns:
            dict: The server profile resource.
        """
        return self._client.get(id_or_uri=id_or_uri)

    def get_by(self, field, value):
        """
        Gets all server profiles that match a specified filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of server profiles.
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Gets a server profile by name.

        Args:
            name: Name of the server profile.

        Returns:
            dict: The server profile resource.
        """
        return self._client.get_by_name(name)

    def get_schema(self):
        """
        Generates the Server Profile schema.

        Returns:
            dict: The server profile schema.
        """
        return self._client.get_schema()

    def get_compliance_preview(self, id_or_uri):
        """
        Gets the preview of manual and automatic updates required to make the server profile
        consistent with its template.

        Args:
            id_or_uri: Can be either the server profile resource ID or URI.

        Returns:
            dict: Server profile compliance preview.
        """
        uri = self._client.build_uri(id_or_uri) + '/compliance-preview'
        return self._client.get(uri)

    def get_profile_ports(self, **kwargs):
        """
        Retrieves the port model associated with a server or server hardware type and enclosure group.

        Args:
            enclosureGroupUri (str):
                The URI of the enclosure group associated with the resource.
            serverHardwareTypeUri (str):
                The URI of the server hardware type associated with the resource.
            serverHardwareUri (str):
                The URI of the server hardware associated with the resource.

        Returns:
            dict: Profile port.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/profile-ports')
        return self._client.get(uri)

    def get_messages(self, id_or_uri):
        """
        Retrieves the error or status messages associated with the specified profile.

        Args:
            id_or_uri: Can be either the server profile resource ID or URI.

        Returns:
            dict: Server Profile Health.
        """
        uri = self._client.build_uri(id_or_uri) + '/messages'
        return self._client.get(uri)

    def get_transformation(self, id_or_uri, **kwargs):
        """

        Transforms an existing profile by supplying a new server hardware type or enclosure group or both.
        A profile will be returned with a new configuration based on the capabilities of the supplied server hardware
        type or enclosure group or both. The port assignment for all deployed connections will be set to Auto.
        Re-selection of the server hardware may also be required. The new profile can subsequently be used for updating
        the server profile, but passing validation is not guaranteed. Any incompatibilities will be flagged when the
        transformed server profile is submitted.

        Args:
            id_or_uri:
                Can be either the server profile resource ID or URI.
            enclosureGroupUri (str):
                The URI of the enclosure group associated with the resource.
            serverHardwareTypeUri (str):
                The URI of the server hardware type associated with the resource.
            serverHardwareUri (str):
                The URI of the server hardware associated with the resource.

        Returns:
            dict: Server Profile.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/transformation',
                                                 id_or_uri)
        return self._client.get(uri)

    def get_available_networks(self, **kwargs):
        """
        Retrieves the list of Ethernet networks, Fiber Channel networks, and network sets that are available to a
        server profile, along with their respective ports.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           functionType (str):
               The FunctionType (Ethernet or FibreChannel) to filter the list of networks returned.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           serverHardwareUri (str):
               The URI of the server hardware associated with the resource.
           view (str):
               Returns a specific subset of the attributes of the resource or collection, by specifying the name of a
               predefined view. The default view is expand (show all attributes of the resource and all elements of
               collections of resources).

               Values:
                   Ethernet
                       Specifies that the connection is to an Ethernet network or a network set.
                   FibreChannel
                       Specifies that the connection is to a Fibre Channel network.

        Returns:
            list: Available networks.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-networks')
        return self._client.get(uri)

    def get_available_servers(self, **kwargs):
        """
        Retrieves the list of available servers.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           profileUri (str):
               The URI of the server profile resource.

        Returns:
            list: Available servers.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-servers')
        return self._client.get(uri)

    def get_available_storage_system(self, **kwargs):
        """
        Retrieves a specific storage system and its associated volumes available to the server profile based
        on the given server hardware type and enclosure group.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           storageSystemId (str):
               The storage system ID associated with the resource.

        Returns:
            dict: Available storage system.
        """
        uri = self.__build_uri_with_query_string(kwargs,
                                                 '/available-storage-system')
        return self._client.get(uri)

    def get_available_storage_systems(self,
                                      start=0,
                                      count=-1,
                                      filter='',
                                      sort='',
                                      **kwargs):
        """
        Retrieves the list of the storage systems and their associated volumes available to the server profile
        based on the given server hardware type and enclosure group.

        Args:
           count:
               The number of resources to return. A count of -1 requests all items. The actual number of items in
               the response may differ from the requested count if the sum of start and count exceed the total
               number of items.
           start:
               The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
               first available item.
           filter (list or str):
               A general filter/query string to narrow the list of items returned. The default is no filter; all
               resources are returned.
           sort:
               The sort order of the returned data set. By default, the sort order is based on create time, with the
               oldest entry first.
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.

        Returns:
            list: Available storage systems.
        """
        uri = self.__build_uri_with_query_string(kwargs,
                                                 '/available-storage-systems')
        return self._client.get_all(start=start,
                                    count=count,
                                    filter=filter,
                                    sort=sort,
                                    uri=uri)

    def get_available_targets(self, **kwargs):
        """
        Retrieves a list of the target servers and empty device bays that are available for assignment to the server
        profile.

        Args:
           enclosureGroupUri (str):
               The URI of the enclosure group associated with the resource.
           serverHardwareTypeUri (str):
               The URI of the server hardware type associated with the resource.
           profileUri (str):
               The URI of the server profile associated with the resource.

        Returns:
            list: List of available servers and bays.
        """
        uri = self.__build_uri_with_query_string(kwargs, '/available-targets')
        return self._client.get(uri)

    def __build_uri_with_query_string(self,
                                      kwargs,
                                      sufix_path,
                                      id_or_uri=None):
        uri = self.URI
        if id_or_uri:
            uri = self._client.build_uri(id_or_uri)

        query_string = '&'.join('{}={}'.format(key, kwargs[key])
                                for key in sorted(kwargs))
        return uri + sufix_path + '?' + query_string

    def get_new_profile_template(self, id_or_uri):
        """
        Retrieves the profile template for a given server profile.

        Args:
            id_or_uri: Can be either the server profile resource ID or URI.

        Returns:
            dict: Server profile template.
        """
        uri = self._client.build_uri(id_or_uri) + '/new-profile-template'
        return self._client.get(uri)
Beispiel #24
0
class PowerDevices(object):
    URI = '/rest/power-devices'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a set of power delivery device resources according to the specified parameters. Filters can be used to get
        a specific set of power delivery devices. With no filters specified, the API returns a potentially paginated
        list of all the power delivery device resources subject to start/count/sort parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default
                 is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
             list of power devices
        """
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    query=query)

    def get(self, id_or_uri):
        """
        Gets a single power delivery device resource based upon its uri or id.

        Args:
            id_or_uri:
                Can be either the power device id or the uri

        Returns:
            dict: The power device
        """
        return self._client.get(id_or_uri)

    def add(self, information, timeout=-1):
        """
        Adds a power delivery device resource based upon the attributes specified. Use this method to create a
        representation of power delivery devices that provide power to other resources but cannot otherwise be
        discovered by the management appliance.

        Args:
            information:
                power device information
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: added power device.
        """
        return self._client.create(information, timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Deletes the set of power-devices according to the specified parameters. A filter is required to identify the
        set of resources to be deleted.

        Args:
            resource: dict object to remove
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
             bool: operation success
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def add_ipdu(self, information, timeout=-1):
        """
        Add an HP iPDU and bring all components under management by discovery of its management module. Bring the
        management module under exclusive management by the appliance, configure any management or data collection
        settings, and create a private set of administrative credentials to enable ongoing communication and management
        of the iPDU. Use "force" to claim the device, even if claimed by another management appliance

        Args:
            resource: power device information
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: added power device.
        """
        uri = self.URI + "/discover"
        return self._client.create(information, uri=uri, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the resource for the specified {id}. The properties that are omitted (not included as part of the the
        request body) are reset to their respective default values. The id and uuid properties are required and cannot
        be changed.

        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated power device
        """
        return self._client.update(resource, timeout=timeout)

    def get_power_state(self, id_or_uri):
        """
        Gets the power state (on, off or unknown) of the specified power delivery device that supports power control.
        The device must be an HP Intelligent Outlet.

        Args:
            id_or_uri:
                Can be either the power device id or the uri

        Returns:
            str: The power state
        """
        uri = self._client.build_uri(id_or_uri) + "/powerState"
        return self._client.get(uri)

    def update_power_state(self, id_or_uri, power_state):
        """
        Sets the power state of the specified power delivery device. The device must be an HP Intelligent Outlet.

        Args:
            id_or_uri:
                Can be either the power device id or the uri
            power_state:
                {"powerState":"On|Off"}

        Returns:
            str: The power state
        """
        uri = self._client.build_uri(id_or_uri) + "/powerState"
        return self._client.update(power_state, uri)

    def update_refresh_state(self, id_or_uri, refresh_state_data):
        """
        Refreshes a given intelligent power delivery device.

        Args:
            id_or_uri:
                Can be either the power device id or the uri
            refresh_state_data:
                Power device refresh request

        Returns:
            str: The power state
        """
        uri = self._client.build_uri(id_or_uri) + "/refreshState"
        return self._client.update(refresh_state_data, uri=uri)

    def remove_synchronous(self, resource, force=False, timeout=-1):
        """
        Deletes the resource specified by {id} synchronously.

        Args:
            resource: dict object to remove
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: operation success
        """
        uri = self._client.build_uri(resource['uri']) + "/synchronous"
        remove_resource = {'uri': uri}
        return self._client.delete(remove_resource,
                                   force=force,
                                   timeout=timeout)

    def get_uid_state(self, id_or_uri):
        """
        Retrieves the unit identification (UID) state (on, off, unknown) of the specified power outlet or extension bar
        resource. The device must be an HP iPDU component with a locator light (HP Intelligent Load Segment,
        HP AC Module, HP Intelligent Outlet Bar, or HP Intelligent Outlet).

        Args:
            id_or_uri:
                Can be either the power device id or the uri

        Returns:
            str: unit identification (UID) state
        """
        uri = self._client.build_uri(id_or_uri) + "/uidState"
        return self._client.get(uri)

    def update_uid_state(self, id_or_uri, refresh_state_data):
        """
        Sets the unit identification (UID) light state of the specified power delivery device. The device must be an
        HP iPDU component with a locator light (HP Intelligent Load Segment, HP AC Module, HP Intelligent Outlet Bar,
        or HP Intelligent Outlet)

        Args:
            id_or_uri:
                Can be either the power device id or the uri
            refresh_state_data:
                Power device refresh request

        Returns:
            str: The UID state
        """
        uri = self._client.build_uri(id_or_uri) + "/uidState"
        return self._client.update(refresh_state_data, uri)

    def get_utilization(self,
                        id_or_uri,
                        fields=None,
                        filter=None,
                        refresh=False,
                        view=None):
        """
        Retrieves historical utilization data for the specified metrics and time span. The device must be a component
        of an HPE iPDU.

        Args:
            id_or_uri:
                The power device id or the resource uri
            fields:
                Name of the metric(s) to be retrieved in the format METRIC[,METRIC]...If unspecified, all metrics
                supported are returned. Power delivery devices support the following utilization metrics:

                    * AveragePower
                        Average power consumption in Watts during this sample interval.
                    * PeakPower
                        Peak power consumption in Watts during this sample interval.

            filter (list or str):
                Filters should be in the format: FILTER_NAME=VALUE[,FILTER_NAME=VALUE]...

                For Example: 'startDate=2016-05-30T11:20:44.541Z,endDate=2016-05-30T19:20:44.541Z'

                startDate:
                    Start date of requested starting time range in ISO 8601 format. If omitted, the startDate is
                    determined by the endDate minus 24 hours.
                endDate:
                    End date of requested starting time range in ISO 8601 format. When omitted the endDate includes the
                    latest data sample available.

                If an excessive number of samples would otherwise be returned, the results will be segmented. The caller
                is responsible for comparing the returned sliceStartTime with the requested startTime in the response.
                If the sliceStartTime is greater than the oldestSampleTime and the requested start time, the caller is
                responsible for repeating the request with endTime set to sliceStartTime to obtain the next segment.
                This process is repeated until the full data set is retrieved.

                If the resource has no data, the UtilizationData is still returned, but will contain no samples and
                sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set
                appropriately (null if no data is available). If the filter does not happen to overlap the data
                that a resource does have, then the metric history service will return null sample values for any
                missing samples.

            refresh:
                Specifies that if necessary, an additional request will be queued to obtain the most recent utilization
                data from the enclosure. The response will not include any refreshed data. To track the availability
                of the newly collected data, monitor the TaskResource identified by the refreshTaskUri property in
                the response. If null, no refresh was queued.
            view:
                Specifies the resolution interval length of the samples to be retrieved. This is reflected in the
                resolution in the returned response. Utilization data is automatically purged to stay within storage
                space constraints. Supported views are listed below:

                native (DEFAULT)
                    Resolution of the samples returned will be one sample for each 5-minute time period. This is the
                    default view and matches the resolution of the data returned by the enclosure. Samples at this
                    resolution are retained up to one year.
                hour
                    Resolution of the samples returned will be one sample for each 60-minute time period. Samples are
                    calculated by averaging the available 5-minute data samples that occurred within the hour, except
                    for PeakPower which is calculated by reporting the peak observed 5-minute sample value data during
                    the hour. Samples at this resolution are retained up to three years.
                day
                    Resolution of the samples returned will be one sample for each 24-hour time period. One day is a
                    24-hour period that starts at midnight GMT regardless of the time zone in which the appliance or
                    client is located. Samples are calculated by averaging the available 5-minute data samples that
                    occurred during the day, except for PeakPower which is calculated by reporting the peak observed
                    5-minute sample value data during the day. Samples at this resolution are retained up to three
                    years.

        Returns:
            dict: Utilization data
        """

        return self._client.get_utilization(id_or_uri, fields, filter, refresh,
                                            view)

    def get_by(self, field, value):
        """
        Gets all power devices that match the filter
        The search is case-insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            dict: power devices
        """
        return self._client.get_by(field, value)
Beispiel #25
0
class StorageVolumeTemplates(object):
    """
    Storage Volume Templates API client.

    """
    URI = '/rest/storage-volume-templates'

    DEFAULT_VALUES = {
        '200': {
            "type": "StorageVolumeTemplateV3"
        },
        '300': {
            "type": "StorageVolumeTemplateV3"
        }
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of storage volume templates.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of storage volume templates.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def create(self, resource, timeout=-1):
        """
        Creates a new storage volume template.

        Args:
            resource (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created storage volume template.
        """
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.create(resource,
                                   timeout=timeout,
                                   custom_headers=custom_headers,
                                   default_values=self.DEFAULT_VALUES)

    def get(self, id_or_uri):
        """
        Gets the specified storage volume template resource by ID or by URI.

        Args:
            id_or_uri: Can be either the storage volume template ID or the storage volume template URI.

        Returns:
            dict: The storage volume template
        """
        return self._client.get(id_or_uri)

    def get_connectable_volume_templates(self,
                                         start=0,
                                         count=-1,
                                         filter='',
                                         query='',
                                         sort=''):
        """
        Gets the storage volume templates that are available on the specified networks based on the storage system
        port's expected network connectivity. If there are no storage volume templates that meet the specified
        connectivity criteria, an empty collection will be returned.

        Returns:
            list: Storage volume templates.
        """
        uri = self.URI + "/connectable-volume-templates"

        get_uri = self._client.build_query_uri(start=start,
                                               count=count,
                                               filter=filter,
                                               query=query,
                                               sort=sort,
                                               uri=uri)
        return self._client.get(get_uri)

    def get_reachable_volume_templates(self,
                                       start=0,
                                       count=-1,
                                       filter='',
                                       query='',
                                       sort='',
                                       networks=None,
                                       scope_uris='',
                                       private_allowed_only=False):
        """
        Gets the storage templates that are connected on the specified networks based on the storage system
        port's expected network connectivity.

        Returns:
            list: Storage volume templates.
        """
        uri = self.URI + "/reachable-volume-templates"

        uri += "?networks={}&privateAllowedOnly={}".format(
            networks, private_allowed_only)

        get_uri = self._client.build_query_uri(start=start,
                                               count=count,
                                               filter=filter,
                                               query=query,
                                               sort=sort,
                                               uri=uri,
                                               scope_uris=scope_uris)
        return self._client.get(get_uri)

    def get_compatible_systems(self, id_or_uri):
        """
        Retrieves a collection of all storage systems that is applicable to this storage volume template.

        Args:
            id_or_uri:
                Can be either the power device id or the uri

        Returns:
            list: Storage systems.
        """
        uri = self._client.build_uri(id_or_uri) + "/compatible-systems"
        return self._client.get(uri)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes the specified storage volume template.

        Args:
            resource (dict):
                Object to remove.
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.
        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        custom_headers = {'Accept-Language': 'en_US', 'If-Match': '*'}
        return self._client.delete(resource,
                                   force=force,
                                   timeout=timeout,
                                   custom_headers=custom_headers)

    def update(self, resource, timeout=-1):
        """
        Updates a storage volume template.

        Args:
            resource (dict):
                Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated storage volume system
        """
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.update(resource,
                                   timeout=timeout,
                                   custom_headers=custom_headers,
                                   default_values=self.DEFAULT_VALUES)

    def get_by(self, field, value):
        """
        Gets all storage volume templates that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of storage volume templates that match the filter.
        """
        return self._client.get_by(field, value)
class DeploymentPlans(object):
    URI = '/rest/deployment-plans'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            'type': 'OEDeploymentPlan',
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of Deployment Plans resources based on optional sorting and filtering, and constrained by start and
        count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Deployment Plan.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets all Deployment Plans that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Deployment Plans.
        """
        return self._client.get_by(field, value)

    def get(self, id_or_uri):
        """
        Retrieves a specific Deployment Plan resource based on the ID or URI provided.

        Args:
            id_or_uri: ID or URI of the Deployment Plan.

        Returns:
            dict: The Deployment Plan.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Adds a Deployment Plan based on the attributes specified.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Created Deployment plan.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the properties of the Deployment Plan.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Updated Deployment Plan.
        """
        return self._client.update(resource, timeout=timeout)

    def get_osdp(self, id_or_uri):
        """
        Retrieves facts about Server Profiles and Server Profile Templates that are using Deployment Plan based on the ID or URI provided.

        Args:
            id_or_uri: ID or URI of the Deployment Plan.

        Returns:
            dict: Server Profiles and Server Profile Templates
        """
        uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path="osdp")
        return self._client.get(uri)

    def get_usedby(self, id_or_uri):
        """
        Retrieves the OS deployment plan details from OneView for a deployment plan resource based on the ID or URI provided.

        Args:
            id_or_uri: ID or URI of the Deployment Plan.

        Returns:
            dict: The OS Deployment Plan.
        """
        uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path="usedby")
        return self._client.get(uri)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes the Deployment Plan.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)
class Volumes(object):
    """
    Volumes API client.

    """

    URI = '/rest/storage-volumes'

    DEFAULT_VALUES_SNAPSHOT = {
        '200': {"type": "Snapshot"},
        '300': {"type": "Snapshot"},
        '500': {}
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of managed volumes. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets the managed volume.

        Args:
            id_or_uri: Can be either the volume ID or the volume URI.

        Returns:
            Managed volume.
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Gets all managed volumes that matches the given filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates or adds a volume.

        There are six different methods to create the volume:

          1) Common = Storage System + Storage Pool
          2) Template = Storage Volume Template
          3) Common with snapshots = Storage System + Storage Pool + Snapshot Pool
          4) Management = Storage System + wwn
          5) Management by name = Storage System + Storage System Volume Name
          6) Snapshot = Snapshot Pool + Storage Pool + Snapshot.

          NOTE: Use numbers 4 and 5 to add a volume for management; it does not create new volumes.

        Args:
            resource (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created or added resource.
        """
        return self._client.create(resource, timeout=timeout)

    def add_from_existing(self, resource, timeout=-1):
        """
        Adds a volume that already exists in the Storage system

        Args:
            resource (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Added resource.
        """
        uri = self.URI + "/from-existing"
        return self._client.create(resource, uri=uri, timeout=timeout)

    def create_from_snapshot(self, data, timeout=-1):
        """
        Creates a new volume on the storage system from a snapshot of a volume.
        A volume template must also be specified when creating a volume from a snapshot.

        The global setting "StorageVolumeTemplateRequired" controls whether or
        not root volume templates can be used to provision volumes.
        The value of this setting defaults to "false".
        If the value is set to "true", then only templates with an "isRoot" value of "false"
        can be used to provision a volume.

        Args:
            data (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created data.
        """
        uri = self.URI + "/from-snapshot"
        return self._client.create(data, uri=uri, timeout=timeout)

    def update(self, resource, force=False, timeout=-1):
        """
        Updates properties of a volume.

        Reverts a volume to the specified snapshot.

        Args:
            resource (dict): Object to update.
            force:
                If set to true, the operation completes despite any problems with network connectivity or errors on
                the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            Updated resource.
        """
        return self._client.update(resource, timeout=timeout, force=force)

    def delete(self, resource, force=False, export_only=None, suppress_device_updates=None, timeout=-1):
        """
        Deletes a managed volume.

        Args:
            resource (dict):
                Object to delete.
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.
            export_only:
                Valid prior to API500. By default, volumes will be deleted from OneView, and storage system.
                To delete the volume from OneView only, you must set its value to True.
                Setting its value to False has the same behavior as the default behavior.
            suppress_device_updates:
                Valid API500 onwards. By default, volumes will be deleted from OneView, and storage system.
                To delete the volume from OneView only, you must set its value to True.
                Setting its value to False has the same behavior as the default behavior.

        Returns:
            bool: Indicates if the volume was successfully deleted.
        """
        custom_headers = {'If-Match': '*'}
        if 'uri' in resource:
            uri = resource['uri']
        else:
            uri = self._client.build_uri(resource)
        if suppress_device_updates:
            uri += '?suppressDeviceUpdates=true'
        if export_only:
            custom_headers['exportOnly'] = True
        return self._client.delete(uri, force=force, timeout=timeout, custom_headers=custom_headers)

    def __build_volume_snapshot_uri(self, volume_id_or_uri=None, snapshot_id_or_uri=None):
        if snapshot_id_or_uri and "/" in snapshot_id_or_uri:
            return snapshot_id_or_uri
        else:
            if not volume_id_or_uri:
                raise ValueError(INVALID_VOLUME_URI)
            volume_uri = self._client.build_uri(volume_id_or_uri)
            return volume_uri + "/snapshots/" + str(snapshot_id_or_uri or '')

    def get_snapshots(self, volume_id_or_uri, start=0, count=-1, filter='', sort=''):
        """
        Gets all snapshots of a volume. Returns a list of snapshots based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            volume_id_or_uri:
                Can be either the volume id or the volume uri.
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of snapshots.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri)

    def create_snapshot(self, volume_id_or_uri, snapshot, timeout=-1):
        """
        Creates a snapshot for the specified volume.

        Args:
            volume_id_or_uri:
                Can be either the volume ID or the volume URI.
            snapshot (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage volume.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)

        return self._client.create(snapshot, uri=uri, timeout=timeout, default_values=self.DEFAULT_VALUES_SNAPSHOT)

    def get_snapshot(self, snapshot_id_or_uri, volume_id_or_uri=None):
        """
        Gets a snapshot of a volume.

        Args:
            volume_id_or_uri:
                Can be either the volume ID or the volume URI. It is optional if it is passed a snapshot URI,
                but required if it passed a snapshot ID.
            snapshot_id_or_uri:
                Can be either the snapshot ID or the snapshot URI.

        Returns:
            dict: The snapshot.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri, snapshot_id_or_uri)
        return self._client.get(uri)

    def delete_snapshot(self, resource, force=False, timeout=-1):
        """
        Deletes a snapshot from OneView and the storage system.

        Args:
            resource (dict): Object to remove.
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Details of associated volume.

        """
        headers = {'If-Match': '*'}
        return self._client.delete(resource, force=force, timeout=timeout, custom_headers=headers)

    def get_snapshot_by(self, volume_id_or_uri, field, value):
        """
        Gets all snapshots that match the filter.

        The search is case-insensitive.

        Args:
            volume_id_or_uri: Can be either the volume id or the volume uri.
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: Snapshots
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_by(field, value, uri=uri)

    def get_extra_managed_storage_volume_paths(self, start=0, count=-1, filter='', sort=''):
        """
        Gets the list of extra managed storage volume paths.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of extra managed storage volume paths.
        """
        uri = self.URI + '/repair?alertFixType=ExtraManagedStorageVolumePaths'
        return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri)

    def repair(self, volume_id_or_uri, timeout=-1):
        """
        Removes extra presentations from a specified volume on the storage system.

        Args:
            volume_id_or_uri:
                Can be either the volume id or the volume uri.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage volume.
        """
        data = {
            "type": "ExtraManagedStorageVolumePaths",
            "resourceUri": self._client.build_uri(volume_id_or_uri)
        }
        custom_headers = {'Accept-Language': 'en_US'}
        uri = self.URI + '/repair'
        return self._client.create(data, uri=uri, timeout=timeout, custom_headers=custom_headers)

    def get_attachable_volumes(self, start=0, count=-1, filter='', query='', sort='', scope_uris='', connections=''):
        """
        Gets the volumes that are connected on the specified networks based on the storage system port's expected
        network connectivity.

        A volume is attachable if it satisfies either of the following conditions:
            * The volume is shareable.
            * The volume not shareable and not attached.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            query:
                A general query string to narrow the list of resources returned. The default
                is no query; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.
            connections:
                A list of dicts specifics the connections used by the attachable volumes. Needs network uri, initiatoer
                name and optional proxy name
            scope_uris:
                A list specifics the list of scope uris used by the attachable volumed.

        Returns:
            list: A list of attachable volumes that the appliance manages.
        """
        uri = self.URI + '/attachable-volumes'
        if connections:
            uri += str('?' + 'connections=' + connections.__str__())
        return self._client.get_all(start, count, filter=filter, query=query, sort=sort, uri=uri, scope_uris=scope_uris)
class LogicalSwitches(object):
    """
    Logical Switches API client.

    Note:
        This resource is only available on C7000 enclosures.

    """
    URI = '/rest/logical-switches'

    SWITCH_DEFAULT_VALUES = {
        '200': {"type": "logical-switch"},
        '300': {"type": "logical-switchV300"}
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Logical Switches. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Logical Switches.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a Logical Switch.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets the Logical Switch with the specified ID.

        Args:
            id_or_uri: Can be either the Logical Switch ID or URI

        Returns:
            dict: Logical Switch.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Creates a Logical Switch.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.
        """
        self.__set_default_values(resource)
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a Logical Switch.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        self.__set_default_values(resource)
        uri = self._client.build_uri(resource['logicalSwitch']['uri'])
        return self._client.update(resource, uri=uri, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all Logical Switches that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Logical Switches.
        """
        return self._client.get_by(field, value)

    def refresh(self, id_or_uri, timeout=-1):
        """
        The Refresh action reclaims the top-of-rack switches in a logical switch.

        Args:
            id_or_uri:
                Can be either the Logical Switch ID or URI
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: The Logical Switch
        """
        uri = self._client.build_uri(id_or_uri) + "/refresh"
        return self._client.update_with_zero_body(uri, timeout=timeout)

    def __set_default_values(self, resource):
        if 'logicalSwitch' in resource:
            resource['logicalSwitch'] = self._client.merge_default_values(resource['logicalSwitch'],
                                                                          self.SWITCH_DEFAULT_VALUES)
class UnmanagedDevices(object):
    URI = '/rest/unmanaged-devices'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a set of unmanaged device resources according to the specified parameters. Filters can be used to get a
        specific set of unmanaged devices. With no filters specified, the API returns a potentially paginated list of
        all the unmanaged device resources subject to start/count/sort parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default
                 is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
             list: Unmanaged Devices
        """
        return self._client.get_all(start, count, filter=filter, sort=sort, query=query)

    def get(self, id_or_uri):
        """
        Gets a single Unmanaged Device resource based upon its uri or id.

        Args:
            id_or_uri:
                Could be either the Unmanaged Device id or the uri

        Returns:
            dict: The Unmanaged Device
        """
        return self._client.get(id_or_uri)

    def add(self, information, timeout=-1):
        """
        Adds an unmanaged device resource based upon the attributes specified. Use this method to create an unmanaged
        device to represent resources that consume space within a rack, or consume power from a power delivery device
        but cannot otherwise be represented by the management appliance.

        Args:
            information:
                Unmanaged Device information
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Added Unmanaged Device
        """
        return self._client.create(information, timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Deletes the resource specified.

        Args:
            resource:
                 Dict object to remove
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                 Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                 in OneView, just stops waiting for its completion.

        Returns:
             bool: operation success
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def remove_all(self, filter, force=False, timeout=-1):
        """
        Deletes the set of unmanaged-devices according to the specified parameters. A filter is required to identify
        the set of resources to be deleted.

        Args:
            filter:
                 A general filter/query string to narrow the list of items that will be removed.
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                 Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                 in OneView, just stops waiting for its completion.

        Returns:
             bool: operation success
        """
        return self._client.delete_all(filter=filter, force=force, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the resource for the specified. The properties that are omitted (not included as part of the the
        request body) are reset to their respective default values. The id and uuid properties are required and cannot
        be changed.

        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated Unmanaged Devices
        """
        return self._client.update(resource, timeout=timeout)

    def get_environmental_configuration(self, id_or_uri):
        """
        Returns a description of the environmental configuration (supported feature set, calibrated minimum & maximum
        power, location & dimensions, ...) of the resource.

        Args:
            id_or_uri:
                Could be either the Unmanaged Device id or the uri

        Returns:
            dict:
                EnvironmentalConfiguration
        """
        uri = self._client.build_uri(id_or_uri) + "/environmentalConfiguration"
        return self._client.get(uri)

    def get_by(self, field, value):
        """
        Get all Unmanaged Devices that match the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            dict: Unmanaged Devices
        """
        return self._client.get_by(field, value)
Beispiel #30
0
class PlanScripts(object):
    URI = '/rest/plan-scripts'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            'type': 'PlanScript',
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of Plan Scripts based on optional sorting and filtering, and constrained by start and count
        parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Plan Scripts.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a Plan Script object from the appliance based on its Plan Script UUID.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Retrieves the overview details of the selected Plan Script as per the selected attributes.

        Args:
            id_or_uri: ID or URI of the Plan Script.

        Returns:
            dict: The Plan Script.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Adds a Plan Script using the information provided in the request body. The plan type can be one of the
        following types: General, deploy and capture. Note: The OS type for the Plan Script is always assigned
        as "ESXi".

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Created Plan Script.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the properties of the Plan Script.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Updated resource.

        """
        return self._client.update(resource, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all Plan Scripts that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Plan Scripts.
        """
        return self._client.get_by(field, value)

    def retrieve_differences(self, id_or_uri, content, timeout=-1):
        """
        Retrieves the modified contents of the selected Plan Script according to the provided content object, as per
        the selected attributes.

        Args:
            id_or_uri: ID or URI of the Plan Script.
            content (str): Plan Script content.
            timeout:
                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation
                in OneView, it just stops waiting for its completion.

        Returns:
            dict: Script differences.
        """
        uri = self.URI + "/differences/" + extract_id_from_uri(id_or_uri)
        return self._client.create(content, uri=uri, timeout=timeout)

    def get_usedby_and_readonly(self, id):
        """
        Gets the build plans details os teh selected plan script as per the selected attributes.

        Args:
            id: ID of the Plan Script.

        Returns:
            array of build plans
        """
        uri = self.URI + "/" + id + "/usedby/readonly"
        return self._client.get(uri)
class ResourceTest(unittest.TestCase):
    URI = "/rest/testuri"

    def setUp(self):
        super(ResourceTest, self).setUp()
        self.host = '127.0.0.1'
        self.connection = connection(self.host)
        self.resource_client = ResourceClient(self.connection, self.URI)
        self.task = {"task": "task"}
        self.response_body = {"body": "body"}
        self.custom_headers = {'Accept-Language': 'en_US'}

    @mock.patch.object(connection, 'get')
    def test_get_all_called_once(self, mock_get):
        filter = "'name'='OneViewSDK \"Test FC Network'"
        sort = 'name:ascending'
        query = "name NE 'WrongName'"
        view = '"{view-name}"'

        mock_get.return_value = {"members": [{"member": "member"}]}

        result = self.resource_client.get_all(
            1, 500, filter, query, sort, view, 'name,owner,modified')

        uri = '{resource_uri}?start=1' \
              '&count=500' \
              '&filter=%27name%27%3D%27OneViewSDK%20%22Test%20FC%20Network%27' \
              '&query=name%20NE%20%27WrongName%27' \
              '&sort=name%3Aascending' \
              '&view=%22%7Bview-name%7D%22' \
              '&fields=name%2Cowner%2Cmodified'.format(resource_uri=self.URI)

        self.assertEqual([{'member': 'member'}], result)
        mock_get.assert_called_once_with(uri)

    @mock.patch.object(connection, 'get')
    def test_get_all_with_defaults(self, mock_get):
        self.resource_client.get_all()
        uri = "{resource_uri}?start=0&count=-1".format(resource_uri=self.URI)

        mock_get.assert_called_once_with(uri)

    @mock.patch.object(connection, 'get')
    def test_get_all_with_custom_uri(self, mock_get):
        self.resource_client.get_all(uri='/rest/testuri/12467836/subresources')
        uri = "/rest/testuri/12467836/subresources?start=0&count=-1"

        mock_get.assert_called_once_with(uri)

    @mock.patch.object(connection, 'get')
    def test_get_all_with_different_resource_uri_should_fail(self, mock_get):
        try:
            self.resource_client.get_all(uri='/rest/other/resource/12467836/subresources')
        except HPOneViewUnknownType as e:
            self.assertEqual(UNRECOGNIZED_URI, e.args[0])
        else:
            self.fail('Expected Exception was not raised')

    @mock.patch.object(connection, 'get')
    def test_get_all_should_do_multi_requests_when_response_paginated(self, mock_get):
        uri_list = ['/rest/testuri?start=0&count=-1',
                    '/rest/testuri?start=3&count=3',
                    '/rest/testuri?start=6&count=3']

        results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]},
                   {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]},
                   {'nextPageUri': None, 'members': [{'id': '7'}, {'id': '8'}]}]

        mock_get.side_effect = results

        self.resource_client.get_all()

        expected_calls = [call(uri_list[0]), call(uri_list[1]), call(uri_list[2])]
        self.assertEqual(mock_get.call_args_list, expected_calls)

    @mock.patch.object(connection, 'get')
    def test_get_all_with_count_should_do_multi_requests_when_response_paginated(self, mock_get):
        uri_list = ['/rest/testuri?start=0&count=15',
                    '/rest/testuri?start=3&count=3',
                    '/rest/testuri?start=6&count=3']

        results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]},
                   {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]},
                   {'nextPageUri': None, 'members': [{'id': '7'}, {'id': '8'}]}]

        mock_get.side_effect = results

        self.resource_client.get_all(count=15)

        expected_calls = [call(uri_list[0]), call(uri_list[1]), call(uri_list[2])]
        self.assertEqual(mock_get.call_args_list, expected_calls)

    @mock.patch.object(connection, 'get')
    def test_get_all_should_return_all_items_when_response_paginated(self, mock_get):
        uri_list = ['/rest/testuri?start=0&count=-1',
                    '/rest/testuri?start=3&count=3',
                    '/rest/testuri?start=6&count=1']

        results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]},
                   {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]},
                   {'nextPageUri': None, 'members': [{'id': '7'}]}]

        mock_get.side_effect = results

        result = self.resource_client.get_all()

        expected_items = [{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': '4'}, {'id': '5'}, {'id': '6'}, {'id': '7'}]
        self.assertSequenceEqual(result, expected_items)

    @mock.patch.object(connection, 'get')
    def test_get_all_with_count_should_return_all_items_when_response_paginated(self, mock_get):
        uri_list = ['/rest/testuri?start=0&count=15',
                    '/rest/testuri?start=3&count=3',
                    '/rest/testuri?start=6&count=1']

        results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]},
                   {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]},
                   {'nextPageUri': None, 'members': [{'id': '7'}]}]

        mock_get.side_effect = results

        result = self.resource_client.get_all(count=15)

        expected_items = [{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': '4'}, {'id': '5'}, {'id': '6'}, {'id': '7'}]
        self.assertSequenceEqual(result, expected_items)

    @mock.patch.object(connection, 'get')
    def test_get_all_should_return_empty_list_when_response_has_no_items(self, mock_get):
        mock_get.return_value = {'nextPageUri': None, 'members': []}

        result = self.resource_client.get_all()

        self.assertEqual(result, [])

    @mock.patch.object(connection, 'delete')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_delete_by_id_called_once(self, mock_wait4task, mock_delete):
        mock_delete.return_value = self.task, self.response_body
        mock_wait4task.return_value = self.task

        delete_task = self.resource_client.delete('1', force=True, timeout=-1)

        self.assertEqual(self.task, delete_task)
        mock_delete.assert_called_once_with(self.URI + "/1?force=True", custom_headers=None)

    @mock.patch.object(connection, 'delete')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_delete_with_custom_headers(self, mock_wait4task, mock_delete):
        mock_delete.return_value = self.task, self.response_body
        mock_wait4task.return_value = self.task

        self.resource_client.delete('1', custom_headers=self.custom_headers)

        mock_delete.assert_called_once_with(mock.ANY, custom_headers={'Accept-Language': 'en_US'})

    def test_delete_dict_invalid_uri(self):
        dict_to_delete = {"task": "task",
                          "uri": ""}
        try:
            self.resource_client.delete(dict_to_delete, False, -1)
        except HPOneViewUnknownType as e:
            self.assertEqual("Unknown object type", e.args[0])
        else:
            self.fail()

    @mock.patch.object(connection, 'get')
    def test_get_schema_uri(self, mock_get):
        self.resource_client.get_schema()
        mock_get.assert_called_once_with(self.URI + "/schema")

    @mock.patch.object(connection, 'get')
    def test_get_by_id_uri(self, mock_get):
        self.resource_client.get('12345')
        mock_get.assert_called_once_with(self.URI + "/12345")

    @mock.patch.object(ResourceClient, 'get_by')
    def test_get_by_name_with_result(self, mock_get_by):
        mock_get_by.return_value = [{"name": "value"}]
        response = self.resource_client.get_by_name('Resource Name,')
        self.assertEqual(response, {"name": "value"})
        mock_get_by.assert_called_once_with("name", 'Resource Name,')

    @mock.patch.object(ResourceClient, 'get_by')
    def test_get_by_name_without_result(self, mock_get_by):
        mock_get_by.return_value = []
        response = self.resource_client.get_by_name('Resource Name,')
        self.assertIsNone(response)
        mock_get_by.assert_called_once_with("name", 'Resource Name,')

    @mock.patch.object(connection, 'get')
    def test_get_collection_uri(self, mock_get):
        mock_get.return_value = {"members": [{"key": "value"}, {"key": "value"}]}

        self.resource_client.get_collection('12345')

        mock_get.assert_called_once_with(self.URI + "/12345")

    @mock.patch.object(connection, 'get')
    def test_get_collection_with_filter(self, mock_get):
        mock_get.return_value = {}

        self.resource_client.get_collection('12345', 'name=name')

        mock_get.assert_called_once_with(self.URI + "/12345?filter=name%3Dname")

    @mock.patch.object(connection, 'get')
    def test_get_collection_should_return_list(self, mock_get):
        mock_get.return_value = {"members": [{"key": "value"}, {"key": "value"}]}

        collection = self.resource_client.get_collection('12345')

        self.assertEqual(len(collection), 2)

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_by_property(self, mock_get_all):
        self.resource_client.get_by('name', 'MyFibreNetwork')
        mock_get_all.assert_called_once_with(filter="\"'name'='MyFibreNetwork'\"", uri='/rest/testuri')

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_by_property_with_uri(self, mock_get_all):
        self.resource_client.get_by('name', 'MyFibreNetwork', uri='/rest/testuri/5435534/sub')
        mock_get_all.assert_called_once_with(filter="\"'name'='MyFibreNetwork'\"", uri='/rest/testuri/5435534/sub')

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_by_property_with__invalid_uri(self, mock_get_all):
        try:
            self.resource_client.get_by('name', 'MyFibreNetwork', uri='/rest/other/5435534/sub')
        except HPOneViewUnknownType as e:
            self.assertEqual('Unrecognized URI for this resource', e.args[0])
        else:
            self.fail()

    @mock.patch.object(connection, 'put')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_update_with_zero_body_called_once(self, mock_wait4task, mock_update):
        mock_update.return_value = self.task, self.task
        mock_wait4task.return_value = self.task
        self.resource_client.update_with_zero_body('/rest/enclosures/09USE133E5H4/configuration',
                                                   timeout=-1)

        mock_update.assert_called_once_with(
            "/rest/enclosures/09USE133E5H4/configuration", None, custom_headers=None)

    @mock.patch.object(connection, 'put')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_update_with_zero_body_and_custom_headers(self, mock_wait4task, mock_update):
        mock_update.return_value = self.task, self.task
        mock_wait4task.return_value = self.task
        self.resource_client.update_with_zero_body('1', custom_headers=self.custom_headers)

        mock_update.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'})

    @mock.patch.object(connection, 'put')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_update_with_zero_body_return_entity(self, mock_wait4task, mock_put):
        response_body = {"resource_name": "name"}

        mock_put.return_value = self.task, self.task
        mock_wait4task.return_value = response_body

        result = self.resource_client.update_with_zero_body(
            '/rest/enclosures/09USE133E5H4/configuration', timeout=-1)

        self.assertEqual(result, response_body)

    @mock.patch.object(connection, 'put')
    def test_update_with_zero_body_without_task(self, mock_put):
        mock_put.return_value = None, self.response_body

        result = self.resource_client.update_with_zero_body(
            '/rest/enclosures/09USE133E5H4/configuration', timeout=-1)

        self.assertEqual(result, self.response_body)

    @mock.patch.object(connection, 'put')
    def test_update_with_uri_called_once(self, mock_put):
        dict_to_update = {"name": "test"}
        uri = "/rest/resource/test"

        mock_put.return_value = None, self.response_body

        response = self.resource_client.update(dict_to_update, uri=uri)

        self.assertEqual(self.response_body, response)
        mock_put.assert_called_once_with(uri, dict_to_update, custom_headers=None)

    @mock.patch.object(connection, 'put')
    def test_update_with_custom_headers(self, mock_put):
        dict_to_update = {"name": "test"}
        mock_put.return_value = None, self.response_body

        self.resource_client.update(dict_to_update, uri="/path", custom_headers=self.custom_headers)

        mock_put.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'})

    @mock.patch.object(connection, 'put')
    def test_update_with_force(self, mock_put):
        dict_to_update = {"name": "test"}
        uri = "/rest/resource/test"
        mock_put.return_value = None, self.response_body

        self.resource_client.update(dict_to_update, uri=uri, force=True)

        expected_uri = "/rest/resource/test?force=True"
        mock_put.assert_called_once_with(expected_uri, dict_to_update, custom_headers=None)

    @mock.patch.object(connection, 'put')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_update_uri(self, mock_wait4task, mock_update):
        dict_to_update = {"resource_data": "resource_data",
                          "uri": "a_uri"}

        mock_update.return_value = self.task, self.response_body
        mock_wait4task.return_value = self.task
        update_task = self.resource_client.update(dict_to_update, False)

        self.assertEqual(self.task, update_task)
        mock_update.assert_called_once_with("a_uri", dict_to_update, custom_headers=None)

    @mock.patch.object(connection, 'put')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_update_return_entity(self, mock_wait4task, mock_put):
        dict_to_update = {
            "resource_name": "a name",
            "uri": "a_uri",
        }
        mock_put.return_value = self.task, {}
        mock_wait4task.return_value = dict_to_update

        result = self.resource_client.update(dict_to_update, timeout=-1)

        self.assertEqual(result, dict_to_update)

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_create_with_zero_body_called_once(self, mock_wait4task, mock_post):
        mock_post.return_value = self.task, self.task
        mock_wait4task.return_value = self.task
        self.resource_client.create_with_zero_body('/rest/enclosures/09USE133E5H4/configuration',
                                                   timeout=-1)

        mock_post.assert_called_once_with(
            "/rest/enclosures/09USE133E5H4/configuration", None, custom_headers=None)

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_create_with_zero_body_and_custom_headers(self, mock_wait4task, mock_post):
        mock_post.return_value = self.task, self.task
        mock_wait4task.return_value = self.task
        self.resource_client.create_with_zero_body('1', custom_headers=self.custom_headers)

        mock_post.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'})

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_create_with_zero_body_return_entity(self, mock_wait4task, mock_post):
        response_body = {"resource_name": "name"}

        mock_post.return_value = self.task, self.task
        mock_wait4task.return_value = response_body

        result = self.resource_client.create_with_zero_body(
            '/rest/enclosures/09USE133E5H4/configuration', timeout=-1)

        self.assertEqual(result, response_body)

    @mock.patch.object(connection, 'post')
    def test_create_with_zero_body_without_task(self, mock_post):
        mock_post.return_value = None, self.response_body

        result = self.resource_client.create_with_zero_body(
            '/rest/enclosures/09USE133E5H4/configuration', timeout=-1)

        self.assertEqual(result, self.response_body)

    @mock.patch.object(connection, 'post')
    def test_create_uri(self, mock_post):
        dict_to_create = {"resource_name": "a name"}
        mock_post.return_value = {}, {}

        self.resource_client.create(dict_to_create, timeout=-1)

        mock_post.assert_called_once_with(self.URI, dict_to_create, custom_headers=None)

    @mock.patch.object(connection, 'post')
    def test_create_with_custom_headers(self, mock_post):
        dict_to_create = {"resource_name": "a name"}
        mock_post.return_value = {}, {}

        self.resource_client.create(dict_to_create, custom_headers=self.custom_headers)

        mock_post.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'})

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_create_return_entity(self, mock_wait4task, mock_post):
        dict_to_create = {
            "resource_name": "a name",
        }
        created_resource = {
            "resource_id": "123",
            "resource_name": "a name",
        }

        mock_post.return_value = self.task, {}
        mock_wait4task.return_value = created_resource

        result = self.resource_client.create(dict_to_create, -1)

        self.assertEqual(result, created_resource)

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_wait_for_activity_on_create(self, mock_wait4task, mock_post):
        mock_post.return_value = self.task, {}
        mock_wait4task.return_value = self.task

        self.resource_client.create({"test": "test"}, timeout=60)

        mock_wait4task.assert_called_once_with({"task": "task"}, 60)

    @mock.patch.object(connection, 'patch')
    def test_patch_request_when_id_is_provided(self, mock_patch):
        request_body = [{
            'op': 'replace',
            'path': '/name',
            'value': 'new_name',
        }]
        mock_patch.return_value = {}, {}

        self.resource_client.patch(
            '123a53cz', 'replace', '/name', 'new_name', 70)

        mock_patch.assert_called_once_with(
            '/rest/testuri/123a53cz', request_body, custom_headers=None)

    @mock.patch.object(connection, 'patch')
    def test_patch_request_when_uri_is_provided(self, mock_patch):
        request_body = [{
            'op': 'replace',
            'path': '/name',
            'value': 'new_name',
        }]
        mock_patch.return_value = {}, {}

        self.resource_client.patch(
            '/rest/testuri/123a53cz', 'replace', '/name', 'new_name', 60)

        mock_patch.assert_called_once_with(
            '/rest/testuri/123a53cz', request_body, custom_headers=None)

    @mock.patch.object(connection, 'patch')
    def test_patch_with_custom_headers(self, mock_patch):
        mock_patch.return_value = {}, {}

        self.resource_client.patch('/rest/testuri/123', 'operation', '/field', 'value',
                                   custom_headers=self.custom_headers)

        mock_patch.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'})

    @mock.patch.object(connection, 'patch')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_patch_return_entity(self, mock_wait4task, mock_patch):
        entity = {"resource_id": "123a53cz"}
        mock_patch.return_value = self.task, self.task
        mock_wait4task.return_value = entity

        result = self.resource_client.patch(
            '123a53cz', 'replace', '/name', 'new_name', -1)

        self.assertEqual(result, entity)

    @mock.patch.object(connection, 'patch')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_wait_for_activity_on_patch(self, mock_wait4task, mock_patch):
        entity = {"resource_id": "123a53cz"}
        mock_patch.return_value = self.task, self.task
        mock_wait4task.return_value = entity

        self.resource_client.patch(
            '123a53cz', 'replace', '/name', 'new_name', -1)

        mock_wait4task.assert_called_once_with({"task": "task"}, mock.ANY)

    def test_delete_with_none(self):
        try:
            self.resource_client.delete(None)
        except ValueError as e:
            self.assertTrue("Resource" in e.args[0])
        else:
            self.fail()

    @mock.patch.object(connection, 'delete')
    def test_delete_with_dict_uri(self, mock_delete):

        resource = {"uri": "uri"}

        mock_delete.return_value = {}, {}
        delete_result = self.resource_client.delete(resource)

        self.assertTrue(delete_result)
        mock_delete.assert_called_once_with("uri", custom_headers=None)

    def test_delete_with_empty_dict(self):
        try:
            self.resource_client.delete({})
        except ValueError as e:
            self.assertTrue("Resource" in e.args[0])
        else:
            self.fail()

    def test_get_with_none(self):
        try:
            self.resource_client.get(None)
        except ValueError as e:
            self.assertTrue("id" in e.args[0])
        else:
            self.fail()

    def test_get_collection_with_none(self):
        try:
            self.resource_client.get_collection(None)
        except ValueError as e:
            self.assertTrue("id" in e.args[0])
        else:
            self.fail()

    def test_create_with_none(self):
        try:
            self.resource_client.create(None)
        except ValueError as e:
            self.assertTrue("Resource" in e.args[0])
        else:
            self.fail()

    def test_create_with_empty_dict(self):
        try:
            self.resource_client.create({})
        except ValueError as e:
            self.assertTrue("Resource" in e.args[0])
        else:
            self.fail()

    def test_update_with_none(self):
        try:
            self.resource_client.update(None)
        except ValueError as e:
            self.assertTrue("Resource" in e.args[0])
        else:
            self.fail()

    def test_update_with_empty_dict(self):
        try:
            self.resource_client.update({})
        except ValueError as e:
            self.assertTrue("Resource" in e.args[0])
        else:
            self.fail()

    def test_get_by_with_name_none(self):
        try:
            self.resource_client.get_by(None, None)
        except ValueError as e:
            self.assertTrue("field" in e.args[0])
        else:
            self.fail()

    @mock.patch.object(connection, 'get')
    def test_get_with_uri_should_work(self, mock_get):
        mock_get.return_value = {}
        uri = self.URI + "/ad28cf21-8b15-4f92-bdcf-51cb2042db32"
        self.resource_client.get(uri)

        mock_get.assert_called_once_with(uri)

    def test_get_with_uri_with_incompatible_url_shoud_fail(self):
        message = "Unrecognized URI for this resource"
        uri = "/rest/interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32"
        try:
            self.resource_client.get(uri)
        except HPOneViewUnknownType as exception:
            self.assertEqual(message, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")

    def test_get_with_uri_from_another_resource_with_incompatible_url_shoud_fail(self):
        message = "Unrecognized URI for this resource"
        uri = "/rest/interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32"
        fake_resource = FakeResource(None)
        try:
            fake_resource.get_fake(uri)
        except HPOneViewUnknownType as exception:
            self.assertEqual(message, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")

    @mock.patch.object(connection, 'get')
    def test_get_utilization_with_args(self, mock_get):
        self.resource_client.get_utilization('09USE7335NW3', fields='AmbientTemperature,AveragePower,PeakPower',
                                             filter='startDate=2016-05-30T03:29:42.361Z',
                                             refresh=True, view='day')

        expected_uri = '/rest/testuri/09USE7335NW3/utilization' \
                       '?filter=startDate%3D2016-05-30T03%3A29%3A42.361Z' \
                       '&fields=AmbientTemperature%2CAveragePower%2CPeakPower' \
                       '&refresh=true' \
                       '&view=day'

        mock_get.assert_called_once_with(expected_uri)

    @mock.patch.object(connection, 'get')
    def test_get_utilization_with_multiple_filters(self, mock_get):
        self.resource_client.get_utilization(
            '09USE7335NW3',
            fields='AmbientTemperature,AveragePower,PeakPower',
            filter='startDate=2016-05-30T03:29:42.361Z,endDate=2016-05-31T03:29:42.361Z',
            refresh=True, view='day')

        expected_uri = '/rest/testuri/09USE7335NW3/utilization' \
                       '?filter=startDate%3D2016-05-30T03%3A29%3A42.361Z' \
                       '&filter=endDate%3D2016-05-31T03%3A29%3A42.361Z' \
                       '&fields=AmbientTemperature%2CAveragePower%2CPeakPower' \
                       '&refresh=true' \
                       '&view=day'

        mock_get.assert_called_once_with(expected_uri)

    @mock.patch.object(connection, 'get')
    def test_get_utilization_by_id_with_defaults(self, mock_get):
        self.resource_client.get_utilization('09USE7335NW3')

        expected_uri = '/rest/testuri/09USE7335NW3/utilization'

        mock_get.assert_called_once_with(expected_uri)

    @mock.patch.object(connection, 'get')
    def test_get_utilization_by_uri_with_defaults(self, mock_get):
        self.resource_client.get_utilization('/rest/testuri/09USE7335NW3')

        expected_uri = '/rest/testuri/09USE7335NW3/utilization'

        mock_get.assert_called_once_with(expected_uri)

    def test_get_utilization_with_empty(self):

        try:
            self.resource_client.get_utilization('')
        except ValueError as exception:
            self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")

    def test_build_uri_with_id_should_work(self):
        input = '09USE7335NW35'
        expected_output = '/rest/testuri/09USE7335NW35'
        result = self.resource_client.build_uri(input)
        self.assertEqual(expected_output, result)

    def test_build_uri_with_uri_should_work(self):
        input = '/rest/testuri/09USE7335NW3'
        expected_output = '/rest/testuri/09USE7335NW3'
        result = self.resource_client.build_uri(input)
        self.assertEqual(expected_output, result)

    def test_build_uri_with_none_should_raise_exception(self):
        try:
            self.resource_client.build_uri(None)
        except ValueError as exception:
            self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")

    def test_build_uri_with_empty_str_should_raise_exception(self):
        try:
            self.resource_client.build_uri('')
        except ValueError as exception:
            self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")

    def test_build_uri_with_different_resource_uri_should_raise_exception(self):
        try:
            self.resource_client.build_uri(
                '/rest/test/another/resource/uri/09USE7335NW3')
        except HPOneViewUnknownType as exception:
            self.assertEqual(UNRECOGNIZED_URI, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")

    def test_build_uri_with_incomplete_uri_should_raise_exception(self):
        try:
            self.resource_client.build_uri('/rest/')
        except HPOneViewUnknownType as exception:
            self.assertEqual(UNRECOGNIZED_URI, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")
class LogicalInterconnectGroups(object):
    URI = '/rest/logical-interconnect-groups'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of logical interconnect groups based on optional sorting and filtering, and constrained by start
        and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of logical interconnect groups.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a logical interconnect group by ID or by uri
        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: The logical interconnect group
        """
        return self._client.get(id_or_uri)

    def get_default_settings(self):
        """
        Gets the default interconnect settings for a logical interconnect group

        Returns:
            dict:
        """
        uri = self.URI + "/defaultSettings"
        return self._client.get(uri)

    def get_settings(self, id_or_uri):
        """
        Gets the interconnect settings for a logical interconnect group.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict:
        """
        uri = self._client.build_uri(id_or_uri) + "/settings"
        return self._client.get(uri)

    def create(self, resource, timeout=-1):
        """
        Creates a logical interconnect group.
        Args:
            resource (dict): Object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Created logical interconnect group.

        """
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a logical interconnect group.
        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated logical interconnect group.

        """
        return self._client.update(resource, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a logical interconnect group.

        Args:
            resource (dict): object to delete
            force (bool):
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Details of associated resource

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_by(self, field, value):
        """
        Get all Logical interconnect groups that matches the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of Logical interconnect groups.
        """
        return self._client.get_by(field, value)
Beispiel #33
0
class StorageSystems(object):
    URI = '/rest/storage-systems'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets information about all managed storage systems. Filtering and sorting are supported with the retrieval of
        managed storage systems. The following storage system attributes can be used with filtering and sorting
        operation: name, model, serialNumber, firmware, status, managedDomain, and state.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of all managed storage systems.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def add(self, resource, timeout=-1):
        """
        Adds a storage system for management by the appliance. The storage system resource created will be in a
        Connected state and will not yet be available for further operations. Users are required to perform a PUT API
        on the storage system resource to complete the management of the storage system resource. An asynchronous task
        will be created as a result of this API call to discover available domains, target ports, and storage pools.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created storage system.
        """
        return self._client.create(resource, timeout=timeout)

    def get_host_types(self):
        """
        Gets the list of supported host types.

        Returns:
            list: Host types.
        """
        uri = self.URI + "/host-types"
        return self._client.get(uri)

    def get_storage_pools(self, id_or_uri):
        """
        Gets a list of Storage pools. Returns a list of storage pools belonging to the storage system referred by the
        Path property {ID} parameter or URI.

        Args:
            id_or_uri: Can be either the storage system ID (serial number) or the storage system URI.
        Returns:
            dict: Host types.
        """
        uri = self._client.build_uri(id_or_uri) + "/storage-pools"
        return self._client.get(uri)

    def get(self, id_or_uri):
        """
        Gets the specified storage system resource by ID or by URI.

        Args:
            id_or_uri: Can be either the storage system id or the storage system uri.

        Returns:
            dict: The storage system.
        """
        return self._client.get(id_or_uri)

    def update(self, resource, timeout=-1):
        """
        Updates the storage system. To complete the addition of a storage system for management by the appliance,
        this must be called after create() of a storage system.

        Args:
            resource (dict):
                Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated storage system.
        """
        return self._client.update(resource, timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes the storage system from OneView.

        Args:
            resource (dict):
                Object to delete
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Details of associated resource.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_managed_ports(self, id_or_uri, port_id_or_uri=''):
        """
        Gets all ports or a specific managed target port for the specified storage system.

        Args:
            id_or_uri: Can be either the storage system id or the storage system uri.
            port_id_or_uri: Can be either the port id or the port uri.

        Returns:
            dict: Managed ports.
        """
        if port_id_or_uri:
            uri = self._client.build_uri(port_id_or_uri)
            if "/managedPorts" not in uri:
                uri = self._client.build_uri(
                    id_or_uri) + "/managedPorts" + "/" + port_id_or_uri

        else:
            uri = self._client.build_uri(id_or_uri) + "/managedPorts"

        return self._client.get_collection(uri)

    def get_by(self, field, value):
        """
        Gets all storage systems that match the filter.

        The search is case-insensitive.

        Args:
            Field: field name to filter.
            Value: value to filter.

        Returns:
            list: A list of storage systems.
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Retrieves a resource by its name.

        Args:
            name: Resource name.

        Returns:
            dict
        """
        return self._client.get_by_name(name=name)

    def get_by_ip_hostname(self, ip_hostname):
        """
        Retrieve a storage system by its IP.

        Args:
            ip_hostname: Storage system IP or hostname.

        Returns:
            dict
        """
        resources = self._client.get_all()

        resources_filtered = [
            x for x in resources
            if x['credentials']['ip_hostname'] == ip_hostname
        ]

        if resources_filtered:
            return resources_filtered[0]
        else:
            return None
class ServerProfileTemplate(object):
    URI = '/rest/server-profile-templates'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {'type': 'ServerProfileTemplateV1'}

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of server profile templates based on optional sorting and filtering, and constrained by start and
        count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return.
                Providing a -1 for the count parameter will restrict the result set size to 64 server profile
                templates. The maximum number of profile templates is restricted to 256, i.e., if user requests more
                than 256, this will be internally limited to 256.
                The actual number of items in the response may differ from the
                requested count if the sum of start and count exceed the total number of items, or if returning the
                requested number of items would take too long.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
                Filters are supported for the name, description, affinity, macType, wwnType, serialNumberType, status,
                serverHardwareTypeUri, enclosureGroupUri, firmware.firmwareBaselineUri attributes.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of server profile templates.

        """
        return self._client.get_all(start=start,
                                    count=count,
                                    filter=filter,
                                    sort=sort)

    def get(self, id_or_uri):
        """
        Gets a server profile template resource by ID or by uri
        Args:
            id_or_uri: Could be either the server profile template resource id or uri

        Returns:
            dict: The server profile template resource
        """
        return self._client.get(id_or_uri=id_or_uri)

    def get_by(self, field, value):
        """
        Get all server profile templates that matches a specified filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of server profile templates
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Gets a server profile template by name.

        Args:
            name: Name of the server profile template

        Returns:
            dict: The server profile template resource
        """
        return self._client.get_by_name(name)

    def create(self, resource, timeout=-1):
        """
         Creates a server profile template.

        Args:
            resource: dict object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns: Created resource.

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(resource=data, timeout=timeout)

    def update(self, resource, id_or_uri):
        """
        Allows a server profile template object to have its configuration modified. These modifications can be as
        simple as a name or description change or much more complex changes around the networking configuration.
        It should be noted that selection of a virtual or physical MAC or Serial Number type is not mutable once a
        profile template has been created, and attempts to change those elements will not be applied to the target
        profile template. Connection requests can be one of the following types - port Auto, auto and explicit.
        An explicit request is where the request portId parameter includes the adapter, port and flexNic. An auto
        request  is where portId is set to "Auto" and a port auto request is where just the portId parameter includes
        just the adapter and port. The fields listed as required in the Request Body section need to be specified
        only when their associated parent is used.

        Args:
            id_or_uri: Could be either the template id or the template uri
            resource (dict): object to update

        Returns:
            dict: The server profile template resource
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(resource=data, uri=id_or_uri)

    def delete(self, resource, timeout=-1):
        """
        Deletes a server profile template object from the appliance based on its profile template UUID.

        Args:
            resource: dict object to delete
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool:
        """
        return self._client.delete(resource=resource, timeout=timeout)

    def get_new_profile(self, id_or_uri):
        """
         A profile object will be returned with the configuration based on this template. Specify the profile name and
         server hardware to assign. If template has any fibre channel connection which is specified as bootable but no
         boot target was defined, that connection will be instantiated as a non-bootable connection. So modify that
         connection to change it to bootable and to specify the boot target. This profile object can subsequently be
         used for the POST https://{appl}/rest/server-profiles/ API.

        Args:
            id_or_uri: Could be either the server profile template resource id or uri

        Returns:
            dict: The server profile resource
        """
        uri = self._client.build_uri(id_or_uri) + "/new-profile"
        return self._client.get(id_or_uri=uri)
Beispiel #35
0
class LogicalInterconnectGroups(object):
    URI = '/rest/logical-interconnect-groups'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of logical interconnect groups based on optional sorting and filtering and is constrained by start
        and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of logical interconnect groups.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a logical interconnect group by ID or by URI.

        Args:
            id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri.

        Returns:
            dict: The logical interconnect group.
        """
        return self._client.get(id_or_uri)

    def get_default_settings(self):
        """
        Gets the default interconnect settings for a logical interconnect group.

        Returns:
            dict: Interconnect Settings.
        """
        uri = self.URI + "/defaultSettings"
        return self._client.get(uri)

    def get_settings(self, id_or_uri):
        """
        Gets the interconnect settings for a logical interconnect group.

        Args:
            id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri.

        Returns:
            dict: Interconnect Settings.
        """
        uri = self._client.build_uri(id_or_uri) + "/settings"
        return self._client.get(uri)

    def create(self, resource, timeout=-1):
        """
        Creates a logical interconnect group.

        Args:
            resource (dict): Object to create
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created logical interconnect group.

        """
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a logical interconnect group.

        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated logical interconnect group.

        """
        return self._client.update(resource, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a logical interconnect group.

        Args:
            resource (dict): Object to delete.
            force (bool):
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all Logical interconnect groups that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Logical interconnect groups.
        """
        return self._client.get_by(field, value)
Beispiel #36
0
class Licenses(object):
    """
    Licenses. Gets a list of all license resources that are known by the appliance.

    """
    URI = '/rest/licenses'

    DEFAULT_VALUES = {
        '200': {
            'type': 'LicenseList'
        },
        '300': {
            "type": "LicenseList"
        },
        '500': {
            "type": "LicenseListV500"
        },
        '600': {
            "type": "LicenseListV500"
        }
    }

    def __init__(self, con):
        self._client = ResourceClient(con, self.URI)

    def create(self, resource, timeout=-1):
        """
        Add a license to the appliance.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.

        """
        return self._client.create(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    def get_by_id(self, id_or_uri):
        """
        Gets the License with the specified ID.

        Args:
            id_or_uri: ID or URI of License.

        Returns:
            dict: The License.
        """
        return self._client.get(id_or_uri)

    def delete(self, id_or_uri):
        """
        Deletes a License.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(id_or_uri)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets all the licenses loaded on the appliance. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Licenses.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)
class IdPoolsIpv4Subnets(object):
    """
    The ID pools IPv4 subnets resource provides a Client API for managing IPv4 subnets.
    """

    URI = '/rest/id-pools/ipv4/subnets'

    def __init__(self, con):
        self._client = ResourceClient(con, self.URI)

    def create(self, resource, timeout=-1):
        """
        Creates subnet.

        Args:
            resource (dict): Object to create
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created subnet.
        """
        return self._client.create(resource, timeout=timeout)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of IPV4 Subnet resources. Returns a list of resources based on optional sorting and filtering,
        and constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of IPV4 Subnet resources.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets an IPv4 subnet.

        Using the allocator and collector associated with the subnet, IDs may be allocated from or collected back to the
        subnet.

        Args:
            id_or_uri: Can be either the subnet ID or URI.

        Returns:
            dict: IPv4 subnet.
        """
        return self._client.get(id_or_uri)

    def update(self, resource, timeout=-1):
        """
        Update the resource.

        Args:
            resource (dict): Information to update.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """

        return self._client.update(resource, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes the IPv4 subnet.

        Args:
            resource (dict):
                Object to delete
            force (bool):
                If set to true, the operation completes despite any problems with
                network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)
class IdPoolsIpv4Ranges(object):
    """
    The ID pools IPv4 ranges resource provides a Client API for managing IPv4 ranges.
    """
    URI = '/rest/id-pools/ipv4/ranges'

    def __init__(self, con):
        self._client = ResourceClient(con, self.URI)

    def create(self, resource, timeout=-1):
        """
        Creates an IPv4 range.

        Args:
            resource (dict): Object to create
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Created range.
        """
        return self._client.create(resource, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets an IPv4 range by ID or URI.

        Using the allocator and collector associated with the range, IDs may be allocated from or collected back to the
        range.

        Args:
            id_or_uri: Can be either the range ID or URI.

        Returns:
            dict: Range
        """
        return self._client.get(id_or_uri)

    def enable(self, information, id_or_uri, timeout=-1):
        """
        Enables or disables an IPv4 range.

        Args:
            information (dict): Information to update.
            id_or_uri: ID or URI of range.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated IPv4 range.
        """

        uri = self._client.build_uri(id_or_uri)

        return self._client.update(information, uri, timeout=timeout)

    def update(self, information, timeout=-1):
        """
        Edit an IPv4 Range.

        Args:
            information (dict): Information to update.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated IPv4 range.
        """

        return self._client.update(information, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes an IPv4 range.

        Args:
            resource (dict):
                Object to delete
            force (bool):
                If set to true, the operation completes despite any problems with
                network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_allocated_fragments(self, id_or_uri, count=-1, start=0):
        """
        Gets all fragments that have been allocated in range.

        Args:
            id_or_uri:
                ID or URI of range.
            count:
                 The number of resources to return. A count of -1 requests all items. The actual number of items in
                 the response may differ from the requested count if the sum of start and count exceed the total number
                 of items.
            start:
                The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                first available item.

        Returns:
            list: A list with the allocated fragements.
        """
        uri = self._client.build_uri(id_or_uri) + "/allocated-fragments?start={0}&count={1}".format(start, count)
        return self._client.get_collection(uri)

    def get_free_fragments(self, id_or_uri, count=-1, start=0):
        """
        Gets all free fragments in an IPv4 range.

        Args:
            id_or_uri:
                ID or URI of range.
            count:
                 The number of resources to return. A count of -1 requests all items. The actual number of items in
                 the response may differ from the requested count if the sum of start and count exceed the total number
                 of items.
            start:
                The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                first available item.

        Returns:
            list: A list with the free fragments.
        """
        uri = self._client.build_uri(id_or_uri) + "/free-fragments?start={0}&count={1}".format(start, count)
        return self._client.get_collection(uri)
Beispiel #39
0
class LogicalInterconnects(object):

    URI = '/rest/logical-interconnects'
    FIRMWARE_PATH = "/firmware"
    SNMP_CONFIGURATION_PATH = "/snmp-configuration"
    PORT_MONITOR_PATH = "/port-monitor"
    LOCATIONS_PATH = "/locations/interconnects"
    FORWARDING_INFORMATION_PATH = "/forwarding-information-base"
    QOS_AGGREGATED_CONFIGURATION = "/qos-aggregated-configuration"
    locations_uri = "{uri}{locations}".format(uri=URI,
                                              locations=LOCATIONS_PATH)

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of logical interconnects based on optional sorting and filtering, and constrained by start
        and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of logical interconnects.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a logical interconnect by ID or by uri

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri

        Returns:
            dict: The logical interconnect
        """
        return self._client.get(id_or_uri)

    def get_by_name(self, name):
        """
        Gets a logical interconnect by name.

        Args:
            name: Name of the logical interconnect

        Returns: Logical Interconnect
        """
        logical_interconnects = self._client.get_all()
        result = [x for x in logical_interconnects if x['name'] == name]
        return result[0] if result else None

    def update_compliance(self, id_or_uri, timeout=-1):
        """
        Returns logical interconnects to a consistent state. The current logical interconnect state is
        compared to the associated logical interconnect group.

        Any differences identified are corrected, bringing the logical interconnect back to a consistent
        state. Changes are asynchronously applied to all managed interconnects. Note that if the changes detected
        involve differences in the interconnect map between the logical interconnect group and the logical interconnect,
        the process of bringing the logical interconnect back to a consistent state may involve automatically removing
        existing interconnects from management and/or adding new interconnects for management.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/compliance"
        return self._client.update_with_zero_body(uri, timeout=timeout)

    def update_ethernet_settings(self,
                                 id_or_uri,
                                 configuration,
                                 force=False,
                                 timeout=-1):
        """
        Updates the Ethernet interconnect settings for the logical interconnect.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            configuration:  Ethernet interconnect settings.
            force: If set to true the operation completes despite any problems with network connectivity or errors
                on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/ethernetSettings"
        return self._client.update(configuration,
                                   uri=uri,
                                   force=force,
                                   timeout=timeout)

    def update_internal_networks(self,
                                 id_or_uri,
                                 network_uri_list,
                                 force=False,
                                 timeout=-1):
        """
        Updates internal networks on the logical interconnect.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            network_uri_list: List of Ethernet network uris.
            force: If set to true the operation completes despite any problems with network connectivity or errors
                on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/internalNetworks"
        return self._client.update(network_uri_list,
                                   uri=uri,
                                   force=force,
                                   timeout=timeout)

    def get_internal_vlans(self, id_or_uri):
        """
        Gets the internal VLAN IDs for the provisioned networks on a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: Collection of URIs

        """
        uri = self._client.build_uri(id_or_uri) + "/internalVlans"
        return self._client.get_collection(uri)

    def update_settings(self, id_or_uri, settings, force=False, timeout=-1):
        """
        Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously
        applied to all managed interconnects.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            settings: Interconnect settings
            force: If set to true the operation completes despite any problems with network connectivity or errors
                on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        data = settings.copy()
        if 'type' not in data:
            data['type'] = 'InterconnectSettingsV3'
        if 'ethernetSettings' in data and 'type' not in data[
                'ethernetSettings']:
            data['ethernetSettings']['type'] = 'EthernetInterconnectSettingsV3'

        uri = self._client.build_uri(id_or_uri) + "/settings"
        return self._client.update(data, uri=uri, force=force, timeout=timeout)

    def update_configuration(self, id_or_uri, timeout=-1):
        """
        Asynchronously applies or re-applies the logical interconnect configuration to all managed interconnects.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/configuration"
        return self._client.update_with_zero_body(uri=uri, timeout=timeout)

    def get_snmp_configuration(self, id_or_uri):
        """
        Gets the SNMP configuration for a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: SNMP configuration
        """
        uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH
        return self._client.get(uri)

    def update_snmp_configuration(self, id_or_uri, configuration, timeout=-1):
        """
        Updates the SNMP configuration of a logical interconnect. Changes to the SNMP configuration are asynchronously
        applied to all managed interconnects.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri
            configuration: snmp configuration

        Returns:
            dict: snmp configuration
        """
        data = configuration.copy()
        if 'type' not in data:
            data['type'] = 'snmp-configuration'

        uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH
        return self._client.update(data, uri=uri, timeout=timeout)

    def get_unassigned_uplink_ports(self, id_or_uri):
        """
        Gets a collection of uplink ports from the member interconnects which are eligible for assignment to an
        analyzer port. To be eligible a port must be a valid uplink, must not be a member of an existing uplink set
        and must not currently be used for stacking.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: Collection of uplink ports
        """
        uri = self._client.build_uri(
            id_or_uri) + "/unassignedUplinkPortsForPortMonitor"
        return self._client.get_collection(uri)

    def get_port_monitor(self, id_or_uri):
        """
        Gets the port monitor configuration of a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri

        Returns:
            dict: port monitor configuration
        """
        uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH
        return self._client.get(uri)

    def update_port_monitor(self, id_or_uri, resource, timeout=-1):
        """
        Updates the port monitor configuration of a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri
            resource: port monitor configuration

        Returns:
            dict: port monitor configuration
        """
        data = resource.copy()
        if 'type' not in data:
            data['type'] = 'port-monitor'

        uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH
        return self._client.update(data, uri=uri, timeout=timeout)

    def get_telemetry_configuration(self, telemetry_configuration_uri):
        """
        Gets the telemetry configuration of a logical interconnect.

        Args:
            telemetry_configuration_uri: Telemetry Configuration URI

        Returns:
            dict: Telemetry configuration

        """
        return self._client.get(telemetry_configuration_uri)

    def create_interconnect(self, location_entries, timeout=-1):
        """
        Creates an interconnect at the given location.

        WARN: It does not create the LOGICAL INTERCONNECT itself.
        It will fail if no interconnect is already present on the specified position.

        Args:
            location_entries: dictionary with location entries
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Created interconnect.
        """
        return self._client.create(location_entries,
                                   uri=self.locations_uri,
                                   timeout=timeout)

    def delete_interconnect(self, enclosure_uri, bay, timeout=-1):
        """
        Deletes an interconnect from a location.

        WARN: This won't delete the LOGICAL INTERCONNECT itself, and may cause inconsistency between the enclosure
        and Logical Interconnect Group.

        Args:
            enclosure_uri: URI of the Enclosure
            bay: Bay
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: bool: indicating if the interconnect was successfully deleted.
        """
        uri = "{locations_uri}?location=Enclosure:{enclosure_uri},Bay:{bay}".format(
            locations_uri=self.locations_uri,
            enclosure_uri=enclosure_uri,
            bay=bay)
        return self._client.delete(uri, timeout=timeout)

    def get_firmware(self, id_or_uri):
        """
        Gets the installed firmware for a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri

        Returns:
            dict: LIFirmware
        """
        firmware_uri = self.__build_firmware_uri(id_or_uri)
        return self._client.get(firmware_uri)

    def install_firmware(self, firmware_information, id_or_uri):
        """
        Installs firmware to a logical interconnect. The three operations that are supported for the firmware
        update are Stage (uploads firmware to the interconnect), Activate (installs firmware on the interconnect)
        and Update (which does a Stage and Activate in a sequential manner).

        Returns:
            dict:
        """
        firmware_uri = self.__build_firmware_uri(id_or_uri)
        return self._client.update(firmware_information, firmware_uri)

    def get_forwarding_information_base(self, id_or_uri, filter=''):
        """
        Gets the forwarding information base data for a logical interconnect. Maximum of 100 entries is returned.
        Optional filtering criteria may be specified.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.
            filter:
                Filtering criteria may be specified using supported attributes: interconnectUri, macAddress,
                internalVlan, externalVlan, and supported relation = (Equals). macAddress is 12 hexadecimal digits with
                a colon between each pair of digits.(upper or lower case).
                The default is no filter - all resources are returned.

        Returns:
            list: A set of interconnect MAC address entries.
        """
        uri = self._client.build_uri(
            id_or_uri) + self.FORWARDING_INFORMATION_PATH
        return self._client.get_collection(uri, filter=filter)

    def create_forwarding_information_base(self, id_or_uri, timeout=-1):
        """
        Generates the forwarding information base dump file for a logical interconnect.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns: Interconnect Forwarding Information Base DataInfo
        """
        uri = self._client.build_uri(
            id_or_uri) + self.FORWARDING_INFORMATION_PATH
        return self._client.create_with_zero_body(uri=uri, timeout=timeout)

    def get_qos_aggregated_configuration(self, id_or_uri):
        """
        Gets the QoS aggregated configuration for the logical interconnect.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.

        Returns:
            dict: QoS Configuration
        """
        uri = self._client.build_uri(
            id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION
        return self._client.get(uri)

    def update_qos_aggregated_configuration(self,
                                            id_or_uri,
                                            qos_configuration,
                                            timeout=-1):
        """
        Updates the QoS aggregated configuration for the logical interconnect.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.
            qos_configuration:
                QOS configuration.

        Returns:
            dict: Logical Interconnect
        """
        uri = self._client.build_uri(
            id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION
        return self._client.update(qos_configuration, uri=uri, timeout=timeout)

    def __build_firmware_uri(self, id_or_uri):
        return self._client.build_uri(id_or_uri) + self.FIRMWARE_PATH
class ApplianceDeviceSNMPv3Users(object):
    """
    ApplianceDeviceSNMPv3Users API client [Available only since API 600].

    As part of SNMPv3 trap forwarding support, the appliance provides APIs for creating User-based Security Model (USM) and forwarding destinations.
    The following protocols are supported while defining USM.

    Authentication protocols: MD5 / SHA1 / SHA256 / SHA384 / SHA512
    Privacy protocols: AES / DES
    The security levels supported while defining USM are None, Authentication only and both Authentication and Privacy.

    """
    URI = '/rest/appliance/snmpv3-trap-forwarding/users'

    def __init__(self, con):
        self._client = ResourceClient(con, self.URI)

    def create(self, resource, timeout=-1):
        """
        Creates a new SNMPv3 user.
        This user will be used for sending the SNMPv3 trap to the associated destinations.
        One user can be assigned to multiple destinations.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.

        """
        return self._client.create(resource, timeout=timeout)

    def get(self, id_or_uri):
        """
        Returns the SNMPv3 user with the specified ID, if it exists.

        Args:
            id_or_uri: ID or URI of SNMPv3 user.

        Returns:
            dict: Appliance SNMPv3 user.
        """
        return self._client.get(id_or_uri)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Lists all SNMPv3 Users.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of SNMPv3 Users.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets all SNMPv3 users that match the filter.
        The search is case-insensitive.

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of SNMPv3 Users.
        """
        return self._client.get_by(field, value)

    def delete_all(self, filter=None, timeout=-1):
        """
        Delete an SNMPv3 User based on User name specified in filter. The user will be deleted only if it has no associated destinations.

        Args:
            username: ID or URI of SNMPv3 user.
            filter: A general filter/query string to narrow the list of items returned.
                    The default is no filter - all resources are returned.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete_all(filter=filter, timeout=timeout)

    def delete(self, id_or_uri, timeout=-1):
        """
        Delete an SNMPv3 User based on User Id specified in {Id}.
        The user will be deleted only if it has no associated destinations.

        Args:
            id_or_uri: dict object to delete
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(id_or_uri, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates SNMPv3 User based on User Id as specified in {Id}

        Args:
            resource: dict object with changes.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Updated appliance SNMPv3 user.
        """
        return self._client.update(resource, timeout=timeout)
class FcoeNetworks(object):
    """
    FCoE Networks API client.

    """
    URI = '/rest/fcoe-networks'

    DEFAULT_VALUES = {
        '200': {
            "type": "fcoe-network"
        },
        '300': {
            "type": "fcoe-networkV300"
        },
        '500': {
            "type": "fcoe-networkV300"
        }
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of FCoE networks. The collection is based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of FCoE networks.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a FCoE network.

        Args:
            resource(str, dict):
                Accept either the resource id  or the entire resource.
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets a FCoE network.

        Args:
            id_or_uri: ID or URI of FCoE network.

        Returns:
            dict: FCoE network.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Creates FCoE network.

        Args:
            resource (dict): Object to create.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns: Created resource.
        """
        return self._client.create(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    def update(self, resource, timeout=-1):
        """
        Updates a FCoE network.

        Args:
            resource (dict): Resource to update.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        return self._client.update(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    def get_by(self, field, value):
        """
        Gets all FCoE networks that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of FCoE networks.
        """
        return self._client.get_by(field, value)

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Uses the PATCH to update the given resource.

        Only one operation can be performed in each PATCH call.

        Args:
            id_or_uri: Can be either the resource ID or the resource URI.
            operation: Patch operation
            path: Path
            value: Value
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        return self._client.patch(id_or_uri,
                                  operation,
                                  path,
                                  value,
                                  timeout=timeout)
Beispiel #42
0
class Enclosures(object):
    URI = '/rest/enclosures'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Enclosures. The collection is based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of Enclosures.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Get all Enclosures that matches the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            list: A list of Enclosures.
        """
        return self._client.get_by(field, value)

    def add(self, information, timeout=-1):
        """
        Takes information about an enclosure (e.g. IP address, username, password) and uses
        it to claim/configure the enclosure and add its components to the appliance.

        Args:
            resource: enclosure information

        Returns: Enclosure.

        """
        return self._client.create(information, timeout=timeout)

    def get(self, id_or_uri):
        """
        Returns the enclosure with the specified ID, if it exists.
        Args:
            id: ID or URI of Enclosure

        Returns: dict
        """
        return self._client.get(id_or_uri)

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Uses the PATCH to update a resource for a given enclosure.
        Only one operation can be performed in each PATCH call.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            operation: Patch operation
            path: Path
            value: Value
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Updated resource. When blocking=False, returns the task.
        """
        return self._client.patch(id_or_uri,
                                  operation,
                                  path,
                                  value,
                                  timeout=timeout)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes and unconfigures the specified enclosure from the appliance. All components of the enclosure (e.g.
        blades and interconnects) are unconfigured/removed as part of this process.
        If the force option is set to "true" then any errors encountered as part of unconfiguring the enclosure or its
        components are ignored and the enclosure is removed regardless of any errors that occur.

        Args:
            resource: dict object to delete
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Result status

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def update_configuration(self, id_or_uri, timeout=-1):
        """
        Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps
        that were performed as part of the enclosure add. A task is returned to the caller which can be used to
        track the progress of the operation.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Enclosure
        """
        uri = self._client.build_uri(id_or_uri) + "/configuration"
        return self._client.update_with_zero_body(uri, timeout=timeout)

    def get_environmental_configuration(self, id_or_uri):
        """
        Gets the settings that describe the environmental configuration (supported feature set, calibrated minimum &
        maximum power, location & dimensions, ...) of the enclosure resource

        Args:
            id_or_uri: Could be either the resource id or the resource uri

        Return: Settings that describe the environmental configuration
        """
        uri = self._client.build_uri(id_or_uri) + '/environmentalConfiguration'
        return self._client.get(uri)

    def update_environmental_configuration(self,
                                           id_or_uri,
                                           configuration,
                                           timeout=-1):
        """
        Sets the calibrated max power of an unmanaged or unsupported enclosure
        Args:
            id_or_uri: Could be either the resource id or the resource uri
            configuration: Configuration
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Return: Settings that describe the environmental configuration
        """
        uri = self._client.build_uri(id_or_uri) + '/environmentalConfiguration'
        return self._client.update(configuration, uri=uri, timeout=timeout)

    def refresh_state(self, id_or_uri, configuration, timeout=-1):
        """
        Refreshes the enclosure along with all of its components, including interconnects and servers. Any new
        hardware is added and any hardware that is no longer present within the enclosure is removed. The
        "refreshStateConfig" passed in must have the "refreshState" field set to "Refreshing" and optionally
        provide information to re-claim the enclosure (e.g. IP address, user name, password, etc.). A task is
        returned to the caller which can be used to track the progress of the operation.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            configuration: Configuration
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Return: Enclosure
        """
        uri = self._client.build_uri(id_or_uri) + "/refreshState"
        return self._client.update(configuration, uri=uri, timeout=timeout)

    def get_script(self, id_or_uri):
        """
        Gets the script of the enclosure

        Args:
            id_or_uri: Could be either the resource id or the resource uri

        Return: Enclosure script
        """
        uri = self._client.build_uri(id_or_uri) + "/script"
        return self._client.get(uri)

    def get_sso(self, id_or_uri, role):
        """
        Builds the SSO (Single Sign-On) URL parameters for the specified enclosure. This allows the user to
        log in to the enclosure without providing credentials. This API is currently only supported by C7000 enclosures.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            role: Role

        Return: SSO (Single Sign-On) URL parameters
        """
        uri = self._client.build_uri(id_or_uri) + "/sso?role=%s" % role
        return self._client.get(uri)

    def get_utilization(self,
                        id_or_uri,
                        fields=None,
                        filter=None,
                        refresh=False,
                        view=None):
        """
        Retrieves historical utilization data for the specified enclosure, metrics, and time span.

        Args:
            id: Could be either the resource id or the resource uri
            fields:
                 Name of the metric(s) to be retrieved in the format METRIC[,METRIC]... Enclosures support the following
                  utilization metrics:

                AmbientTemperature
                    Inlet air temperature in degrees Celsius during this sample interval.
                AveragePower
                    Average power consumption in Watts during this sample interval.
                PeakPower
                    Peak power consumption in Watts during this sample interval.
                PowerCap
                    Dynamic power cap setting on the server hardware in Watts during this sample interval.
                DeratedCapacity
                    Enclosure dynamic power cap derated capacity setting in Watts during this sample interval.
                RatedCapacity
                    Enclosure dynamic power cap rated capacity setting in Watts during this sample interval.

                If unspecified, all metrics supported are returned.
            filter:
                 Provides an expression of the requested time range of data. One condition (startDate/endDate) is
                  specified per filter specification as described below. The condition must be specified via the
                  equals (=) operator.

                startDate
                    Start date of requested starting time range in ISO 8601 format (2016-05-31T07:20:00.000Z).
                    If omitted, the startDate is determined by the endDate minus 24 hours.
                endDate
                    End date of requested starting time range in ISO 8601 format. When omitted the endDate includes the
                    latest data sample available.

                If an excessive number of samples would otherwise be returned, the results will be segmented. The caller
                is responsible for comparing the returned sliceStartTime with the requested startTime in the response.
                If the sliceStartTime is greater than the oldestSampleTime and the requested start time, the caller is
                responsible for repeating the request with endTime set to sliceStartTime to obtain the next segment.
                This process is repeated until the full data set is retrieved.

                If the resource has no data, the UtilizationData is still returned, but will contain no samples and
                sliceStartTime/sliceEndTime will be equal. oldestSampleTime/newestSampleTime will still be set
                appropriately (null if no data is available). If the filter just does not happen to overlap the data
                that a resource does have, then the metric history service will return null sample values for any
                missing samples.

            refresh:
                 Specifies that if necessary an additional request will be queued to obtain the most recent utilization
                  data from the enclosure. The response will not include any refreshed data. To track the availability
                  of the newly collected data, monitor the TaskResource identified by the refreshTaskUri property in
                  the response. If null, no refresh was queued.
            view:
                 Specifies the resolution interval length of the samples to be retrieved. This is reflected in the
                 resolution in the returned response. Utilization data is automatically purged to stay within storage
                 space constraints. Supported views are listed below.

                native (DEFAULT)
                    Resolution of the samples returned will be one sample for each 5-minute time period. This is the
                    default view and matches the resolution of the data returned by the enclosure. Samples at this
                     resolution are retained up to one year.
                hour
                    Resolution of the samples returned will be one sample for each 60-minute time period. Samples are
                     calculated by averaging the available 5-minute data samples that occurred within the hour, except
                      for PeakPower which is calculated by reporting the peak observed 5-minute sample value data during
                       the hour. Samples at this resolution are retained up to three years.
                day
                    Resolution of the samples returned will be one sample for each 24-hour time period. One day is a
                    24-hour period that starts at midnight GMT regardless of the time zone in which the appliance or
                    client is located. Samples are calculated by averaging the available 5-minute data samples that
                    occurred during the day, except for PeakPower which is calculated by reporting the peak observed
                    5-minute sample value data during the day. Samples at this resolution are retained up to three
                    years.

        Returns: dict

        """

        return self._client.get_utilization(id_or_uri,
                                            fields=fields,
                                            filter=filter,
                                            refresh=refresh,
                                            view=view)
Beispiel #43
0
class Alerts(object):
    URI = '/rest/alerts'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get(self, id_or_uri):
        """
        Retrieve an alert by its URI or ID.

        Args:
            id_or_uri: alert ID or URI.

        Returns:
            dict: The alert.

        """

        alert = self._client.get(id_or_uri)
        return alert

    def get_all(self,
                start=0,
                count=-1,
                filter='',
                query='',
                sort='',
                view=''):
        """
        Gets all the alerts based upon filters provided.

        Args:
            start:
                 The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the
                 first available item.
            count:
                The number of resources to return. A count of -1 requests all items. The actual number of items in
                the response may differ from the requested count if the sum of start and count exceed the total number
                of items.
            filter (list or str):
                 A general filter/query string to narrow the list of items returned. The default is no filter; all
                 resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default is no query (all
                 resources are returned).
            sort:
                The sort order of the returned data set. By default, the sort order is based on create time, with the
                oldest entry first.
            view:
                 Returns a specific subset of the attributes of the resource or collection, by specifying the name of a
                 predefined view. The default view is expand (show all attributes of the resource and all elements of
                 collections of resources).

        Returns:
            list: A list of alerts.
        """
        return self._client.get_all(start=start,
                                    count=count,
                                    filter=filter,
                                    query=query,
                                    sort=sort,
                                    view=view)

    def get_by(self, field, value):
        """
        Gets all alerts that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: List of alerts.

        """
        return self._client.get_by(field, value)

    def delete(self, resource):
        """
        Deletes an alert.

        Args:
            resource: dict object to delete

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource)

    def delete_all(self, filter, timeout=-1):
        """
        Deletes all Alert objects from the appliance that match the provided filter.

        Args:
            filter (list or str):
                 A general filter string to narrow the list of items to delete. The default is no filter; all
                 resources are deleted.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates whether the alerts were successfully deleted.
        """
        return self._client.delete_all(filter=filter, timeout=timeout)

    def update(self, resource, id_or_uri=None, timeout=-1):
        """
        Updates the specified alert resource.

        Args:
            resource (dict): Object to update.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated alert.
        """
        uri = resource.pop('uri', None)
        if not uri:
            if not id_or_uri:
                raise ValueError("URI was not provided")
            uri = self._client.build_uri(id_or_uri)
        return self._client.update(resource=resource, uri=uri, timeout=timeout)

    def delete_alert_change_log(self, id_or_uri):
        """
        Deletes alert change log by alert ID or URI.

        Args:
            id_or_uri: alert ID or URI.
        """
        uri = self.URI + "/AlertChangeLog/" + extract_id_from_uri(id_or_uri)
        resource = {"uri": uri}
        self._client.delete(resource)
class ServerHardwareTypes(object):
    URI = '/rest/server-hardware-types'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Get the list of server hardware type resources defined on the appliance.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of server hardware type.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Get the server hardware type resource with the specified id or uri.

        Args:
            id_or_uri: Could be either the server hardware type id or uri.

        Returns:
            dict: The logical interconnect group.
        """
        return self._client.get(id_or_uri)

    def update(self, resource, uri=None, timeout=-1):
        """
        Updates one or more attributes for a server hardware type resource.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated server hardware type.

        """
        return self._client.update(resource, uri, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Remove the server hardware type with the specified URI. A server hardware type cannot be deleted if it
        is associated with a server hardware or server profile resource.

        Args:
            resource (dict): object to delete
            force (bool):
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_by(self, field, value):
        """
        Get all server hardware types that match the filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of server hardware types.
        """
        return self._client.get_by(field, value)
class Volumes(object):
    URI = '/rest/storage-volumes'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__snapshot_default_values = {"type": "Snapshot"}

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of managed volumes. The collection is based on optional
        sorting and filtering, and constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets the managed volume.

        Args:
            id_or_uri: Could be either the volume id or the volume uri.

        Returns:
            Managed volume.
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Get all managed volumes that matches the given filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of managed volumes.
        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates or adds a volume.

        It's possible to create the volume in 6 different ways:

          1) Common = Storage System + Storage Pool
          2) Template = Storage Volume Template
          3) Common with snapshots = Storage System + Storage Pool + Snapshot Pool
          4) Management = Storage System + wwn
          5) Management by name = Storage System + Storage System Volume Name
          6) Snapshot = Snapshot Pool + Storage Pool + Snapshot.

          NOTE: The 4) and 5) are for adding a volume for management, it do not create new volumes.

        Args:
            resource (dict):
                Object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created or added resource.
        """
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, force=False, timeout=-1):
        """
        Updates properties of a volume.

        Reverts a volume to the specified snapshot.

        Args:
            resource (dict): Object to update.
            force:
                If set to true the operation completes despite any problems with network connectivity or errors on
                the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            Updated resource.
        """
        return self._client.update(resource, timeout=timeout, force=force)

    def delete(self, resource, force=False, export_only=False, timeout=-1):
        """
        Deletes a managed volume.

        Args:
            resource (dict):
                Object to delete.
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.
            export_only:
                By default, volumes will be deleted from OneView and storage system.
                To delete the volume only from OneView, you must set its value to True.
                Setting its value to False has the same behaviour as the default behaviour.

        Returns:
            bool: indicating if the volume was successfully deleted.
        """
        custom_headers = {"exportOnly": export_only}
        return self._client.delete(resource,
                                   force=force,
                                   timeout=timeout,
                                   custom_headers=custom_headers)

    def __build_volume_snapshot_uri(self,
                                    volume_id_or_uri=None,
                                    snapshot_id_or_uri=None):
        if snapshot_id_or_uri and "/" in snapshot_id_or_uri:
            return snapshot_id_or_uri
        else:
            if not volume_id_or_uri:
                raise ValueError(INVALID_VOLUME_URI)
            volume_uri = self._client.build_uri(volume_id_or_uri)
            return volume_uri + "/snapshots/" + str(snapshot_id_or_uri or '')

    def get_snapshots(self,
                      volume_id_or_uri,
                      start=0,
                      count=-1,
                      filter='',
                      sort=''):
        """
        Gets all snapshots of a volume. Returns a list of snapshots based on optional sorting and filtering, and
        constrained by start and count parameters.

        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri.
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of snapshots.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    uri=uri)

    def create_snapshot(self, volume_id_or_uri, snapshot, timeout=-1):
        """
        Creates a snapshot for the volume specified.

        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri
            snapshot (dict):
                Object to create
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage Volume.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        data = self.__snapshot_default_values.copy()
        data.update(snapshot)
        return self._client.create(data, uri=uri, timeout=timeout)

    def get_snapshot(self, snapshot_id_or_uri, volume_id_or_uri=None):
        """
        Gets a snapshot of a volume.

        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri. It is optional if is passed a snapshot uri,
                but required if passed a snapshot id.
            snapshot_id_or_uri:
                Could be either the snapshot id or the snapshot uri.

        Returns:
            dict: The snapshot.
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri,
                                               snapshot_id_or_uri)
        return self._client.get(uri)

    def delete_snapshot(self, resource, force=False, timeout=-1):
        """
        Deletes a snapshot from OneView and storage system.

        Args:
            resource (dict): Object to remove.
            force (bool):
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Details of associated volume.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_snapshot_by(self, volume_id_or_uri, field, value):
        """
        Get all snapshots that match the filter.

        The search is case insensitive.

        Args:
            volume_id_or_uri: Could be either the volume id or the volume uri.
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: Snapshots
        """
        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)
        return self._client.get_by(field, value, uri=uri)

    def get_extra_managed_storage_volume_paths(self,
                                               start=0,
                                               count=-1,
                                               filter='',
                                               sort=''):
        """
        Gets the list of extra managed storage volume paths.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of extra managed storage volume paths.
        """
        uri = self.URI + '/repair?alertFixType=ExtraManagedStorageVolumePaths'
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    uri=uri)

    def repair(self, volume_id_or_uri, timeout=-1):
        """
        Removes extra presentations from a specified volume on the storage system.

        Args:
            volume_id_or_uri:
                Could be either the volume id or the volume uri.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Storage Volume.
        """
        data = {
            "type": "ExtraManagedStorageVolumePaths",
            "resourceUri": self._client.build_uri(volume_id_or_uri)
        }
        custom_headers = {'Accept-Language': 'en_US'}
        uri = self.URI + '/repair'
        return self._client.create(data,
                                   uri=uri,
                                   timeout=timeout,
                                   custom_headers=custom_headers)

    def get_attachable_volumes(self,
                               start=0,
                               count=-1,
                               filter='',
                               query='',
                               sort=''):
        """
        Gets the volumes that are connected on the specified networks based on the storage system port's expected
        network connectivity.

        A volume is attachable if it satisfies either of the following conditions:
            * The volume is shareable
            * The volume not shareable and not attached.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            query:
                A general query string to narrow the list of resources returned. The default
                is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of attachable volumes which are managed by the appliance.
        """
        uri = self.URI + '/attachable-volumes'
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    query=query,
                                    sort=sort,
                                    uri=uri)
class LogicalInterconnects(object):

    URI = '/rest/logical-interconnects'
    FIRMWARE_PATH = "/firmware"
    SNMP_CONFIGURATION_PATH = "/snmp-configuration"
    PORT_MONITOR_PATH = "/port-monitor"
    LOCATIONS_PATH = "/locations/interconnects"
    FORWARDING_INFORMATION_PATH = "/forwarding-information-base"
    QOS_AGGREGATED_CONFIGURATION = "/qos-aggregated-configuration"
    locations_uri = "{uri}{locations}".format(uri=URI, locations=LOCATIONS_PATH)

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of logical interconnects based on optional sorting and filtering, and constrained by start
        and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of logical interconnects.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a logical interconnect by ID or by uri

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri

        Returns:
            dict: The logical interconnect
        """
        return self._client.get(id_or_uri)

    def get_by_name(self, name):
        """
        Gets a logical interconnect by name.

        Args:
            name: Name of the logical interconnect

        Returns: Logical Interconnect
        """
        logical_interconnects = self._client.get_all()
        result = [x for x in logical_interconnects if x['name'] == name]
        return result[0] if result else None

    def update_compliance(self, id_or_uri, timeout=-1):
        """
        Returns logical interconnects to a consistent state. The current logical interconnect state is
        compared to the associated logical interconnect group.

        Any differences identified are corrected, bringing the logical interconnect back to a consistent
        state. Changes are asynchronously applied to all managed interconnects. Note that if the changes detected
        involve differences in the interconnect map between the logical interconnect group and the logical interconnect,
        the process of bringing the logical interconnect back to a consistent state may involve automatically removing
        existing interconnects from management and/or adding new interconnects for management.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/compliance"
        return self._client.update_with_zero_body(uri, timeout=timeout)

    def update_ethernet_settings(self, id_or_uri, configuration, force=False, timeout=-1):
        """
        Updates the Ethernet interconnect settings for the logical interconnect.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            configuration:  Ethernet interconnect settings.
            force: If set to true the operation completes despite any problems with network connectivity or errors
                on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/ethernetSettings"
        return self._client.update(configuration, uri=uri, force=force, timeout=timeout)

    def update_internal_networks(self, id_or_uri, network_uri_list, force=False, timeout=-1):
        """
        Updates internal networks on the logical interconnect.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            network_uri_list: List of Ethernet network uris.
            force: If set to true the operation completes despite any problems with network connectivity or errors
                on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/internalNetworks"
        return self._client.update(network_uri_list, uri=uri, force=force, timeout=timeout)

    def get_internal_vlans(self, id_or_uri):
        """
        Gets the internal VLAN IDs for the provisioned networks on a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: Collection of URIs

        """
        uri = self._client.build_uri(id_or_uri) + "/internalVlans"
        return self._client.get_collection(uri)

    def update_settings(self, id_or_uri, settings, force=False, timeout=-1):
        """
        Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously
        applied to all managed interconnects.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            settings: Interconnect settings
            force: If set to true the operation completes despite any problems with network connectivity or errors
                on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        data = settings.copy()
        if 'type' not in data:
            data['type'] = 'InterconnectSettingsV3'
        if 'ethernetSettings' in data and 'type' not in data['ethernetSettings']:
            data['ethernetSettings']['type'] = 'EthernetInterconnectSettingsV3'

        uri = self._client.build_uri(id_or_uri) + "/settings"
        return self._client.update(data, uri=uri, force=force, timeout=timeout)

    def update_configuration(self, id_or_uri, timeout=-1):
        """
        Asynchronously applies or re-applies the logical interconnect configuration to all managed interconnects.

        Args:
            id_or_uri: Could be either the resource id or the resource uri
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + "/configuration"
        return self._client.update_with_zero_body(uri=uri, timeout=timeout)

    def get_snmp_configuration(self, id_or_uri):
        """
        Gets the SNMP configuration for a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: SNMP configuration
        """
        uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH
        return self._client.get(uri)

    def update_snmp_configuration(self, id_or_uri, configuration, timeout=-1):
        """
        Updates the SNMP configuration of a logical interconnect. Changes to the SNMP configuration are asynchronously
        applied to all managed interconnects.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri
            configuration: snmp configuration

        Returns:
            dict: snmp configuration
        """
        data = configuration.copy()
        if 'type' not in data:
            data['type'] = 'snmp-configuration'

        uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH
        return self._client.update(data, uri=uri, timeout=timeout)

    def get_unassigned_uplink_ports(self, id_or_uri):
        """
        Gets a collection of uplink ports from the member interconnects which are eligible for assignment to an
        analyzer port. To be eligible a port must be a valid uplink, must not be a member of an existing uplink set
        and must not currently be used for stacking.

        Args:
            id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri

        Returns:
            dict: Collection of uplink ports
        """
        uri = self._client.build_uri(id_or_uri) + "/unassignedUplinkPortsForPortMonitor"
        return self._client.get_collection(uri)

    def get_port_monitor(self, id_or_uri):
        """
        Gets the port monitor configuration of a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri

        Returns:
            dict: port monitor configuration
        """
        uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH
        return self._client.get(uri)

    def update_port_monitor(self, id_or_uri, resource, timeout=-1):
        """
        Updates the port monitor configuration of a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri
            resource: port monitor configuration

        Returns:
            dict: port monitor configuration
        """
        data = resource.copy()
        if 'type' not in data:
            data['type'] = 'port-monitor'

        uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH
        return self._client.update(data, uri=uri, timeout=timeout)

    def get_telemetry_configuration(self, telemetry_configuration_uri):
        """
        Gets the telemetry configuration of a logical interconnect.

        Args:
            telemetry_configuration_uri: Telemetry Configuration URI

        Returns:
            dict: Telemetry configuration

        """
        return self._client.get(telemetry_configuration_uri)

    def create_interconnect(self, location_entries, timeout=-1):
        """
        Creates an interconnect at the given location.

        WARN: It does not create the LOGICAL INTERCONNECT itself.
        It will fail if no interconnect is already present on the specified position.

        Args:
            location_entries: dictionary with location entries
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Created interconnect.
        """
        return self._client.create(location_entries, uri=self.locations_uri, timeout=timeout)

    def delete_interconnect(self, enclosure_uri, bay, timeout=-1):
        """
        Deletes an interconnect from a location.

        WARN: This won't delete the LOGICAL INTERCONNECT itself, and may cause inconsistency between the enclosure
        and Logical Interconnect Group.

        Args:
            enclosure_uri: URI of the Enclosure
            bay: Bay
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: bool: indicating if the interconnect was successfully deleted.
        """
        uri = "{path}?location=Enclosure:{enclosure_uri},Bay:{bay}".format(path=self.LOCATIONS_PATH,
                                                                           enclosure_uri=enclosure_uri,
                                                                           bay=bay)
        return self._client.delete(uri, timeout=timeout)

    def get_firmware(self, id_or_uri):
        """
        Gets the installed firmware for a logical interconnect.

        Args:
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri

        Returns:
            dict: LIFirmware
        """
        firmware_uri = self.__build_firmware_uri(id_or_uri)
        return self._client.get(firmware_uri)

    def install_firmware(self, firmware_information, id_or_uri):
        """
        Installs firmware to a logical interconnect. The three operations that are supported for the firmware
        update are Stage (uploads firmware to the interconnect), Activate (installs firmware on the interconnect)
        and Update (which does a Stage and Activate in a sequential manner).

        Returns:
            dict:
        """
        firmware_uri = self.__build_firmware_uri(id_or_uri)
        return self._client.update(firmware_information, firmware_uri)

    def get_forwarding_information_base(self, id_or_uri, filter=''):
        """
        Gets the forwarding information base data for a logical interconnect. Maximum of 100 entries is returned.
        Optional filtering criteria may be specified.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.
            filter:
                Filtering criteria may be specified using supported attributes: interconnectUri, macAddress,
                internalVlan, externalVlan, and supported relation = (Equals). macAddress is 12 hexadecimal digits with
                a colon between each pair of digits.(upper or lower case).
                The default is no filter - all resources are returned.

        Returns:
            list: A set of interconnect MAC address entries.
        """
        uri = self._client.build_uri(id_or_uri) + self.FORWARDING_INFORMATION_PATH
        return self._client.get_collection(uri, filter=filter)

    def create_forwarding_information_base(self, id_or_uri, timeout=-1):
        """
        Generates the forwarding information base dump file for a logical interconnect.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns: Interconnect Forwarding Information Base DataInfo
        """
        uri = self._client.build_uri(id_or_uri) + self.FORWARDING_INFORMATION_PATH
        return self._client.create_with_zero_body(uri=uri, timeout=timeout)

    def get_qos_aggregated_configuration(self, id_or_uri):
        """
        Gets the QoS aggregated configuration for the logical interconnect.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.

        Returns:
            dict: QoS Configuration
        """
        uri = self._client.build_uri(id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION
        return self._client.get(uri)

    def update_qos_aggregated_configuration(self, id_or_uri, qos_configuration, timeout=-1):
        """
        Updates the QoS aggregated configuration for the logical interconnect.

        Args:
            id_or_uri:
                Could be either the logical interconnect id or the logical interconnect uri.
            qos_configuration:
                QOS configuration.

        Returns:
            dict: Logical Interconnect
        """
        uri = self._client.build_uri(id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION
        return self._client.update(qos_configuration, uri=uri, timeout=timeout)

    def __build_firmware_uri(self, id_or_uri):
        return self._client.build_uri(id_or_uri) + self.FIRMWARE_PATH
Beispiel #47
0
class Racks(object):
    URI = '/rest/racks'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', query='', sort=''):
        """
        Gets a set of rack resources according to the specified parameters. Filters can be used to get a specific set
        of racks. With no filters specified, the API returns a potentially paginated list of all the racks
        subject to start/count/sort parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items, or
                if returning the requested number of items would take too long.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            query:
                 A general query string to narrow the list of resources returned. The default
                 is no query - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns: list of racks
        """
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    query=query)

    def get(self, id_or_uri):
        """
        Gets a rack with the specified ID or URI
        Args:
            id_or_uri:
                Could be either the rack id or the rack uri

        Returns:
            dict: The rack
        """
        return self._client.get(id_or_uri)

    def get_device_topology(self, id_or_uri):
        """
        Retrieves the topology information for the rack resource specified by id or uri.

        Args:
            id_or_uri: Could be either the resource id or the resource uri

        Return:
            dict: device topology
        """
        uri = self._client.build_uri(id_or_uri) + "/deviceTopology"
        return self._client.get(uri)

    def get_by(self, field, value):
        """
        Get all racks that match the filter
        The search is case insensitive

        Args:
            field: field name to filter
            value: value to filter

        Returns:
            dict: rack

        """
        return self._client.get_by(field, value)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes the specified rack.

        Args:
            resource: dict object to remove
            force:
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns: Result status

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def add(self, information, timeout=-1):
        """
        Adds a rack resource based upon the attributes specified. All attributes without default values must be
        specified in the POST body. The response contains the rack resource as added to the appliance with default and
        assigned properties expanded. The id and uri are assigned by the management appliance and are used to uniquely
        identify this particular resource.

        Args:
            resource: rack information
            timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: added rack.

        """
        return self._client.create(information, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates the specified rack resource. The properties that are omitted (not included as part of the request body)
        are reset to their respective default values. The id and uuid properties are required and cannot be changed.
        To update existing racks first perform a get() request to retrieve the current properties, update the desired
        properties, and then update() the request body containing the new representation of the resource.
        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated rack

        """
        return self._client.update(resource, timeout=timeout)
Beispiel #48
0
class LogicalSwitches(object):
    URI = '/rest/logical-switches'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Logical Switches. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Logical Switches.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a Logical Switch.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets the Logical Switch with the specified ID.

        Args:
            id_or_uri: Can be either the Logical Switch ID or URI

        Returns:
            dict: Logical Switch.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Creates a Logical Switch.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.
        """
        self.__set_default_values(resource)
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a Logical Switch.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        self.__set_default_values(resource)
        uri = self._client.build_uri(resource['logicalSwitch']['uri'])
        return self._client.update(resource, uri=uri, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all Logical Switches that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Logical Switches.
        """
        return self._client.get_by(field, value)

    def refresh(self, id_or_uri, timeout=-1):
        """
        The Refresh action reclaims the top-of-rack switches in a logical switch.

        Args:
            id_or_uri:
                Can be either the Logical Switch ID or URI
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: The Logical Switch
        """
        uri = self._client.build_uri(id_or_uri) + "/refresh"
        return self._client.update_with_zero_body(uri, timeout=timeout)

    def __set_default_values(self, resource):
        if 'logicalSwitch' in resource and 'type' not in resource['logicalSwitch']:
            resource['logicalSwitch']['type'] = 'logical-switch'
Beispiel #49
0
class Labels(object):
    """
    Labels API client.

    """

    URI = '/rest/labels'
    RESOURCES_PATH = '/resources'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of labels based on optional sorting and filtering and is constrained by start
        and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of labels.
        """
        return self._client.get_all(start=start, count=count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a label by ID or URI.

        Args:
            id_or_uri: Can be either the label ID or the label URI.

        Returns:
            dict: The label.
        """
        return self._client.get(id_or_uri=id_or_uri)

    def get_by_resource(self, resource_uri):
        """
        Gets all the labels for the specified resource

        Args:
            resource_uri: The resource URI

        Returns:
            dict: Resource Labels
        """
        uri = self.URI + self.RESOURCES_PATH + '/' + resource_uri
        return self._client.get(id_or_uri=uri)

    def create(self, resource):
        """
        Set all the labels for a resource.

        Args:
            resource: The object containing the resource URI and a list of labels

        Returns:
            dict: Resource Labels
        """
        uri = self.URI + self.RESOURCES_PATH
        return self._client.create(resource=resource, uri=uri)

    def update(self, resource):
        """
        Set all the labels for a resource.

        Args:
            resource (dict): Object to update.

        Returns:
            dict: Resource Labels
        """
        return self._client.update(resource=resource)

    def delete(self, resource, timeout=-1):
        """
        Delete all the labels for a resource.

        Args:
            resource (dict): Object to delete.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.
        """
        self._client.delete(resource=resource, timeout=timeout)
Beispiel #50
0
class Users(object):
    """
    Users API client.

    """

    URI = '/rest/users'

    DEFAULT_VALUES = {
        '200': {
            'type': 'UserAndRoles'
        },
        '300': {
            'type': 'UserAndRoles'
        },
        '500': {
            'type': 'UserAndRoles'
        }
    }

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of Users. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.

                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Users.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a User.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.

        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def create(self, resource, timeout=-1):
        """
        Creates a User.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Created resource.

        """
        return self._client.create(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    def update(self, resource, timeout=-1):
        """
        Updates a User.

        Args:
            resource (dict): Object to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView, just stop waiting for its completion.

        Returns:
            dict: Updated resource.

        """
        return self._client.update(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES,
                                   uri=self.URI)

    def get_by(self, field, value):
        """
        Gets all Users that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter. Accepted values: 'name', 'userName', 'role'
            value: Value to filter.

        Returns:
            list: A list of Users.
        """
        if field == 'userName' or field == 'name':
            return self._client.get(self.URI + '/' + value)
        elif field == 'role':
            value = value.replace(" ", "%20")
            return self._client.get(self.URI + '/roles/users/' +
                                    value)['members']
        else:
            raise HPOneViewException(
                'Only userName, name and role can be queried for this resource.'
            )

    def validate_user_name(self, user_name, timeout=-1):
        """
        Verifies if a userName is already in use.

        Args:
            user_name:
                The userName to be verified.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns: True if user name is in use, False if it is not.
        """
        uri = self.URI + '/validateLoginName/' + user_name
        return self._client.create_with_zero_body(uri=uri, timeout=timeout)

    def validate_full_name(self, full_name, timeout=-1):
        """
        Verifies if a fullName is already in use.

        Args:
            full_name:
                The fullName to be verified.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns: True if full name is in use, False if it is not.
        """
        uri = self.URI + '/validateUserName/' + full_name
        return self._client.create_with_zero_body(uri=uri, timeout=timeout)
Beispiel #51
0
class UplinkSets(object):
    URI = '/rest/uplink-sets'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self._ethernet_network = EthernetNetworks(con)
        self.__default_values = {
            "type": "uplink-setV3",
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated list of uplink sets based on optional sorting and filtering and is constrained by start and
        count parameters.

        Filters can be used in the URL to control the number of uplink sets that are returned.
        With no filters specified, the API returns all uplink sets.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of uplink sets.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets an uplink set with the specified ID.

        Args:
            id_or_uri: Can be either the uplink set id or the uplink set uri.

        Returns:
            dict: The uplink set.
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Gets all uplink sets that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: Uplink sets

        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates an uplink set.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Created resource.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates an uplink set.

        Args:
            resource (dict): Resource to update.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes an uplink set. If the uplink set was carrying a Fibre Channel (FC) network, any connections which are
        deployed and using the FC network will be placed into a 'Failed' state.

        Args:
            resource: Resource to delete or the resource ID.
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
                OneView, just stops waiting for its completion.

            Returns:
                bool: True if successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get_ethernet_networks(self, id_or_uri):
        """
        Gets a list of associated ethernet networks of an uplink set.

        Args:
            id_or_uri: Can be either the uplink set id or the uplink set uri.

        Returns:
            list: Associated ethernet networks.
        """
        uplink = self.get(id_or_uri)
        network_uris = uplink.get('networkUris')
        networks = []
        if network_uris:
            for uri in network_uris:
                networks.append(self._ethernet_network.get(uri))
        return networks

    def add_ethernet_networks(self, id_or_uri, ethernet_id_or_uris):
        """
        Adds existing ethernet networks to an uplink set.

        Args:
            id_or_uri:
                Can be either the uplink set id or the uplink set uri.
            ethernet_id_or_uris:
                Could be either one or more ethernet network id or ethernet network uri.

        Returns:
            dict: The updated uplink set.
        """
        return self.__set_ethernet_uris(id_or_uri,
                                        ethernet_id_or_uris,
                                        operation="add")

    def remove_ethernet_networks(self, id_or_uri, ethernet_id_or_uris):
        """
        Remove existing ethernet networks of an uplink set.

        Args:
            id_or_uri:
                Can be either the uplink set id or the uplink set uri.
            ethernet_id_or_uris:
                Could be either one or more ethernet network id or ethernet network uri.

        Returns:
            dict: The updated uplink set.
        """
        return self.__set_ethernet_uris(id_or_uri,
                                        ethernet_id_or_uris,
                                        operation="remove")

    def __set_ethernet_uris(self,
                            id_or_uri,
                            ethernet_id_or_uris,
                            operation="add"):
        if not isinstance(ethernet_id_or_uris, list):
            ethernet_id_or_uris = [ethernet_id_or_uris]

        uplink = self.get(id_or_uri)

        associated_enets = uplink.get('networkUris', [])

        for i, enet in enumerate(ethernet_id_or_uris):
            ethernet_id_or_uris[
                i] = enet if '/' in enet else self._ethernet_network.URI + '/' + enet

        if operation == "remove":
            enets_to_update = sorted(
                list(set(associated_enets) - set(ethernet_id_or_uris)))
        elif operation == "add":
            enets_to_update = sorted(
                list(set(associated_enets).union(set(ethernet_id_or_uris))))
        else:
            raise ValueError(
                "Value {} is not supported as operation. The supported values are: ['add', 'remove']"
            )

        if set(enets_to_update) != set(associated_enets):
            uplink['networkUris'] = enets_to_update
            return self.update(uplink)
        else:
            return uplink
Beispiel #52
0
class NetworkSets(object):
    URI = '/rest/network-sets'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            'connectionTemplateUri': None,
            'type': 'network-set',
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of network sets. The collection is based on optional
        sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: A list of Network sets.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a network set.

        Any deployed connections that are using the network are placed in the 'Failed' state.

        Args:
            resource: dict object to delete
            force:
                 If set to true, the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            bool: Indicates if the resource was successfully deleted.
        """
        return self._client.delete(resource, force=force, timeout=timeout)

    def get(self, id_or_uri):
        """
        Gets the network set with the specified ID.

        Args:
            id_or_uri: ID or URI of network set.

        Returns:
            dict: Network set.
        """
        return self._client.get(id_or_uri)

    def create(self, resource, timeout=-1):
        """
        Creates a network set.

        Args:
            resource (dict): Object to create.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns: Created resource.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a network set.

        Args:
            resource (dict): Object to update.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def get_by(self, field, value):
        """
        Gets all network sets that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of Network sets.
        """
        return self._client.get_by(field, value)

    def get_all_without_ethernet(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of network sets without ethernet. The collection is based
        on optional sorting and filtering and is constrained by start and count parameters.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all items.
                The actual number of items in the response might differ from the requested
                count if the sum of start and count exceeds the total number of items.
            filter (list or str):
                A general filter/query string to narrow the list of items returned. The
                default is no filter; all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.

        Returns:
            list: List of network sets, excluding Ethernet networks.
        """
        without_ethernet_client = ResourceClient(
            self._connection, "/rest/network-sets/withoutEthernet")
        return without_ethernet_client.get_all(start,
                                               count,
                                               filter=filter,
                                               sort=sort)

    def get_without_ethernet(self, id_or_uri):
        """
        Gets the network set with the specified ID or URI without ethernet.

        Args:
            id_or_uri: Can be either the Network Set ID or URI.

        Returns:
            dict: Network set excluding Ethernet networks.
        """
        uri = self._client.build_uri(id_or_uri) + "/withoutEthernet"
        return self._client.get(uri)
class StorageVolumeTemplates(object):
    URI = '/rest/storage-volume-templates'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of storage volume templates.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of storage volume templates.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def create(self, resource, timeout=-1):
        """
        Creates a new storage volume template.

        Args:
            resource (dict):
                Object to create.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Created storage volume template.
        """
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.create(resource, timeout=timeout, custom_headers=custom_headers)

    def get(self, id_or_uri):
        """
        Gets the specified storage volume template resource by ID or by uri.

        Args:
            id_or_uri: Could be either the storage volume template id or the storage volume template uri.

        Returns:
            dict: The storage volume template
        """
        return self._client.get(id_or_uri)

    def get_connectable_volume_templates(self):
        """
        Gets the storage volume templates that are available on the specified networks based on the storage system
        port's expected network connectivity. If there are no storage volume templates that meets the specified
        connectivity criteria an empty collection will be returned.

        Returns:
            list: Storage volume templates.
        """
        uri = self.URI + "/connectable-volume-templates"
        return self._client.get(uri)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes the specified storage volume template.

        Args:
            resource (dict):
                Object to remove.
            force (bool):
                 If set to true the operation completes despite any problems with
                 network connectivity or errors on the resource itself. The default is false.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.
        Returns:
            bool: Indicating if the resource was successfully deleted.
        """
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.delete(resource, force=force, timeout=timeout, custom_headers=custom_headers)

    def update(self, resource, timeout=-1):
        """
        Updates a storage volume template.

        Args:
            resource (dict):
                Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated storage volume system
        """
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.update(resource, timeout=timeout, custom_headers=custom_headers)

    def get_by(self, field, value):
        """
        Get all storage volume templates that match the filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of storage volume templates that match the filter.
        """
        return self._client.get_by(field, value)
class EnclosureGroups(object):
    URI = '/rest/enclosure-groups'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {"type": "EnclosureGroupV200"}

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of enclosure groups.

        Args:
            start:
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            count:
                The number of resources to return. A count of -1 requests all the items.
                The actual number of items in the response may differ from the requested
                count if the sum of start and count exceed the total number of items.
            filter:
                A general filter/query string to narrow the list of items returned. The
                default is no filter - all resources are returned.
            sort:
                The sort order of the returned data set. By default, the sort order is based
                on create time, with the oldest entry first.

        Returns:
            list: A list of enclosure groups.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a enclosure group by ID or by uri.

        Args:
            id_or_uri: Could be either the enclosure group id or the enclosure group uri.

        Returns:
            dict: Enclosure Group
        """
        return self._client.get(id_or_uri)

    def get_script(self, id_or_uri):
        """
        Gets the configuration script of the enclosure-group resource with the specified URI.

        Returns:
            dict: Configuration script.
        """

        uri = self._client.build_uri(id_or_uri) + "/script"

        return self._client.get(uri)

    def get_by(self, field, value):
        """
        Get all enclosure groups that matches the filter.

        The search is case insensitive.

        Args:
            field: Field name to filter.
            value: Value to filter.

        Returns:
            list: A list of enclosure groups.
        """
        return self._client.get_by(field, value)

    def create(self, resource, timeout=-1):
        """
        Creates an enclosure group. An interconnect bay mapping must be provided for each
        of the interconnect bays in the enclosure. For this release, the same logical
        interconnect group must be provided for each interconnect bay mapping.

        Args:
            resource (dict): Object to create.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Created enclosure group.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def delete(self, resource, timeout=-1):
        """
        Deletes an enclosure group. An enclosure group cannot be deleted if any enclosures
        are currently part of that enclosure group.

        Args:
            resource (dict): Object to delete.
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            bool: Indicating if the resource was successfully deleted.

        """
        return self._client.delete(resource, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates an enclosure group with new attributes.

        Args:
            resource (dict): Object to update
            timeout:
                Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
                in OneView, just stops waiting for its completion.

        Returns:
            dict: Updated enclosure group

        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def update_script(self, id_or_uri, script_body):
        """
        Updates the configuration script of the enclosure-group with the specified URI.

        Args:
            id_or_uri: Resource id or resource uri.
            script_body:  Configuration script.

        Returns:
            dict: Updated enclosure group.
        """
        uri = self._client.build_uri(id_or_uri) + "/script"

        return self._client.update(script_body, uri=uri)