class InterconnectTypes(object):
    URI = '/rest/interconnect-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 a paginated collection of all interconnect types based on the specified parameters.

        Filters can be used in the URL to control the number of interconnect types that are returned.
        With no filters specified, the API returns all interconnect types.

        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 Interconnect types.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets an interconnect type by ID or by uri.

        Args:
            id_or_uri: Could be either the interconnect type id or the interconnect type uri.

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

    def get_by(self, field, value):
        """
        Get all interconnect 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 Interconnect types.
        """
        return self._client.get_by(field, value)
class ApplianceNodeInformation(object):
    """
    ApplianceNodeInformation API client.

    """
    URI = '/rest/appliance/nodeinfo'

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

    def get_status(self):
        """
        Retrieves node's status information

        Returns:
            dict: Node's status information
        """
        uri = self.URI + '/status'
        return self._client.get(uri)

    def get_version(self):
        """
        Retrieves node's version information

        Returns:
            dict: Node's version information
        """
        uri = self.URI + '/version'
        return self._client.get(uri)
    def get_all_without_ethernet(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of logical downlinks without ethernet. 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:
            dict
        """
        without_ethernet_client = ResourceClient(
            self._connection, "/rest/logical-downlinks/withoutEthernet")
        return without_ethernet_client.get_all(start, count, filter=filter, sort=sort)
Esempio n. 4
0
class Tasks(object):
    URI = '/rest/tasks'

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

    def get(self, id_or_uri):
        """
        Retrieve a task by its uri.

        Args:
            id_or_uri: task id (or uri)

        Returns:
            dict: The task.

        """

        task = self._client.get(id_or_uri)
        return task

    def get_all(self, start=0, count=-1, fields='', filter='', query='', sort='', view=''):
        """
        Gets all the tasks based upon filters provided.

        Note:
            Filters are optional.

        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.
            fields:
                 Specifies which fields should be returned in the result set.
            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.
            view:
                 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.

        Returns:
            list: A list of tasks.
        """
        return self._client.get_all(start=start, count=count, filter=filter, query=query, sort=sort, view=view,
                                    fields=fields)
Esempio n. 5
0
class Roles(object):
    """
    Roles API client.
    """

    URI = '/rest/roles'
    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 roles 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 roles.
        """
        return self._client.get_all(start=start, count=count, filter=filter, sort=sort)

    def get(self, name_or_uri):
        """
        Get the role by its URI or Name.

        Args:
            name_or_uri:
                Can be either the Name or the URI.

        Returns:
            dict: Role
        """
        name_or_uri = quote(name_or_uri)
        return self._client.get(name_or_uri)
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self.__default_values = {
         'connectionTemplateUri': None,
         'type': 'network-set',
     }
class FirmwareBundles(object):
    """
    Firmware Bundles API client.

    """
    URI = '/rest/firmware-bundles'

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

    def upload(self, file_path, timeout=-1):
        """
        Upload an SPP ISO image file or a hotfix file to the appliance.
        The API supports upload of one hotfix at a time into the system.
        For the successful upload of a hotfix, ensure its original name and extension are not altered.

        Args:
            file_path: Full path to firmware.
            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: Information about the updated firmware bundle.
        """
        return self._client.upload(file_path, timeout=timeout)
Esempio n. 8
0
class Endpoints(object):
    URI = '/rest/fc-sans/endpoints'

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

    def get_all(self, start=0, count=-1, query='', sort=''):
        """
        Retrieves the list of endpoints known by 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.
            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: The endpoints known by the appliance.
        """
        return self._client.get_all(start=start, count=count, query=query, sort=sort)
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self._ethernet_network = EthernetNetworks(con)
     self.__default_values = {
         "type": "uplink-setV3",
     }
Esempio n. 10
0
class FakeResource(object):
    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, "/rest/fake/resource")

    def get_fake(self, uri):
        return self._client.get(uri)
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self.__default_values = {
         "ethernetNetworkType": "Tagged",
         "type": "ethernet-networkV3"
     }
Esempio n. 12
0
 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'}
Esempio n. 13
0
 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',
     }
class ApplianceTimeAndLocaleConfiguration(object):
    """
    ApplianceTimeAndLocaleConfiguration API client.

    """
    URI = '/rest/appliance/configuration/time-locale'

    DEFAULT_VALUES = {
        '200': {"type": "TimeAndLocale"},
        '300': {"type": "TimeAndLocale"}
    }

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

    def get(self):
        """
        Gets the appliance time and locale configuration.

        Returns:
            dict: ApplianceTimeAndLocaleConfiguration
        """
        return self._client.get(self.URI)

    def update(self, resource, timeout=-1):
        """
        Updates the appliance time and locale configuration.

        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 appliance time and locale configuration.

        """
        return self._client.create(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)
    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)
class LoginDetails(object):
    """
    list login details.

    """

    URI = '/rest/logindetails'

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

    def get_login_details(self):
        """
        List the login details

        Returns:
            dict: login details.
        """
        return self._client.get(self.URI)
Esempio n. 17
0
class Versions(object):
    """
    Version API client. It indicates the range of API versions supported by the appliance.

    """
    URI = '/rest/version'

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

    def get_version(self):
        """
        Returns the range of possible API versions supported by the appliance.
        The response contains the current version and the minimum version.
        The current version is the recommended version to specify in the REST header.
        The other versions are supported for backward compatibility, but might not support the most current features.

        Returns:
            dict: The minimum and maximum supported API versions.
        """
        version = self._client.get(self.URI)
        return version
Esempio n. 18
0
class StoragePools(object):
    """
    Storage Pools API client.

    """
    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 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 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 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 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: Can 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 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_by(self, field, value):
        """
        Gets 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)
class ServerProfileTemplate(object):
    """
    The server profile template resource provides methods to create, retrieve, modify, and delete server
    profile templates.

    A server profile template serves as a structural reference when creating a server profile.
    All of the configuration constructs of a server profile are present in the server profile template.
    The server profile template serves as the initial and ongoing reference for the structure of a server profile.
    The server profile template defines the centralized source for the configuration of firmware, connections,
    local storage, SAN storage, boot, BIOS, profile affinity and hide unused flexNICs.

    After being created from a server profile template, the server profile continues to maintain an association to its
    server profile template. Any drift in configuration consistency between the server profile template and server
    profile(s) is monitored and made visible on both the server profile template and the associated server profile(s).

    """

    URI = '/rest/server-profile-templates'
    TRANSFORMATION_PATH = "/transformation/?serverHardwareTypeUri={server_hardware_type_uri}" + \
                          "&enclosureGroupUri={enclosure_group_uri}"

    DEFAULT_VALUES = {
        '200': {
            'type': 'ServerProfileTemplateV1'
        },
        '300': {
            'type': 'ServerProfileTemplateV2'
        },
        '500': {
            'type': 'ServerProfileTemplateV3'
        },
        '600': {
            'type': 'ServerProfileTemplateV4'
        }
    }

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

    def get_all(self, start=0, count=-1, filter='', sort='', scope_uris=''):
        """
        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.
            scope_uris: An expression to restrict the resources returned according to the scopes to which they are assigned.

        Returns:
            list: A list of server profile templates.

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

    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, force=True):
        """
        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.
            force: If set to true, the operation will ignore warnings for SAN storage.

        Returns:
            dict: Created resource.

        """
        uri = self.URI + "?force={0}".format(force)
        return self._client.create(resource=resource,
                                   uri=uri,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    def update(self, resource, id_or_uri, force=True):
        """
        Allows a server profile template object to have its configuration modified. These modifications can be as
        simple as a name or description change or 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.
            force: If set to true, the operation will ignore warnings for SAN storage.

        Returns:
            dict: The server profile template resource.
        """
        return self._client.update(resource=resource,
                                   uri=id_or_uri,
                                   default_values=self.DEFAULT_VALUES,
                                   force=force)

    def delete(self, resource, timeout=-1, force=False):
        """
        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.
            force: If set to true, the operation completes despite any problems with network connectivity
                or errors on the resource itself.

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

    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)

    def get_transformation(self, id_or_uri, server_hardware_type_uri,
                           enclosure_group_uri):
        """
        Transforms an existing profile template by supplying a new server hardware type and enclosure group or both.
        A profile template will be returned with a new configuration based on the capabilities of the supplied
        server hardware type and/or enclosure group. All configured connections will have their port assignments
        set to 'Auto.'
        The new profile template can subsequently be used in the update method, but is not guaranteed to pass
        validation. Any incompatibilities will be flagged when the transformed server profile template is submitted.

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

        Args:
            id_or_uri: Can be either the server profile template resource ID or URI.
            server_hardware_type_uri: The URI of the new server hardware type.
            enclosure_group_uri: The URI of the new enclosure group.

        Returns:
            dict: The server profile template resource.
        """
        query_params = self.TRANSFORMATION_PATH.format(**locals())
        uri = self._client.build_uri(id_or_uri) + query_params
        return self._client.get(id_or_uri=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 template along with their respective ports. The scopeUris, serverHardwareTypeUri and
        enclosureGroupUri parameters should be specified to get the available networks for a new server profile template.
        The serverHardwareTypeUri, enclosureGroupUri, and profileTemplateUri should be specified to get available
        networks for an existing server profile template.
        The scopeUris parameter is ignored when the profileTemplateUri is specified.

        Args:
            enclosureGroupUri: The URI of the enclosure group is required when the serverHardwareTypeUri
                specifies a blade server.
            profileTemplateUri: If the URI of the server profile template is provided the list of available
                networks will include only networks that share a scope with the server profile template.
            scopeUris: An expression to restrict the resources returned according to the scopes
                to which they are assigned.
            serverHardwareTypeUri: If the server hardware type specifies a rack server, the list of
                available network includes all networks that are applicable for the specified server hardware type.
                If the server hardware type specifies a blade server, the enclosureGroupUri parameter must be
                specified, and the list of available networks includes all networks that are applicable for the
                specified server hardware type and all empty bays within the enclosure group that can support
                the specified server hardware type.
            view: The FunctionType (Ethernet or FibreChannel) to filter the list of networks returned.

        Returns:
            dict: Dictionary with available networks details.
        """
        query_string = '&'.join('{}={}'.format(key, value)
                                for key, value in kwargs.items() if value)
        uri = self.URI + "{}?{}".format("/available-networks", query_string)

        return self._client.get(id_or_uri=uri)
Esempio n. 20
0
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self._ethernet_network = EthernetNetworks(con)
Esempio n. 21
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 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 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 task completion by default. The timeout does not abort the operation
                in OneView, 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 parameters--id (serial number) or uri. Filters are supported for the following storage pool
        attributes only - name, domain, deviceSpeed, deviceType, supprtedRAIDLevel, status and state.

        Args:
            id_or_uri: Could 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: Could 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 action of adding a storage system for management by the appliance,
        this must be called after create() of a storage system.
        This method can be used to update storage system credentials, storage system attributes or to request a refresh
        of storage system. For updating credentials, users are allowed to update IP/hostname, username, and password.
        To request a refresh of a storage system user must set the "refreshState" attribute to RefreshPending state.
        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 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 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_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: Could be either the storage system id or the storage system uri
            port_id_or_uri: Could 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):
        """
        Get 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):
        """
        Retrieve 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
 def __init__(self, con):
     self._client = ResourceClient(con, self.URI)
class LogicalSwitchGroups(object):
    URI = '/rest/logical-switch-groups'

    def __init__(self, con):
        self._connection = con
        self._client = ResourceClient(con, self.URI)
        self.__default_values = {
            "type": "logical-switch-group"
        }

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of logical switch 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 switch groups.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a logical switch group by ID or by uri.

        Args:
            id_or_uri: Could be either the logical switch group id or the logical switch group uri.

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

    def create(self, resource, timeout=-1):
        """
        Creates a logical switch 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 switch group.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.create(data, timeout=timeout)

    def update(self, resource, timeout=-1):
        """
        Updates a logical switch 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 switch group.
        """
        data = self.__default_values.copy()
        data.update(resource)
        return self._client.update(data, timeout=timeout)

    def delete(self, resource, force=False, timeout=-1):
        """
        Deletes a logical switch 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:
            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 Logical switch 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 switch groups that match the filter.
        """
        return self._client.get_by(field, value)
Esempio n. 24
0
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_custom_uri_and_query_string(self, mock_get):
        self.resource_client.get_all(
            uri='/rest/testuri/12467836/subresources?param=value')

        uri = "/rest/testuri/12467836/subresources?param=value&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_all_called_once(self, mock_wait4task, mock_delete):
        mock_delete.return_value = self.task, self.response_body
        mock_wait4task.return_value = self.task

        filter = "name='Exchange Server'"
        uri = "/rest/testuri?filter=name%3D%27Exchange%20Server%27&force=True"
        self.resource_client.delete_all(filter=filter, force=True, timeout=-1)

        mock_delete.assert_called_once_with(uri)

    @mock.patch.object(connection, 'delete')
    def test_delete_all_should_return_true(self, mock_delete):
        mock_delete.return_value = None, self.response_body

        filter = "name='Exchange Server'"
        result = self.resource_client.delete_all(filter=filter,
                                                 force=True,
                                                 timeout=-1)

        self.assertTrue(result)

    @mock.patch.object(connection, 'delete')
    @mock.patch.object(TaskMonitor, 'wait_for_task')
    def test_delete_all_should_wait_for_task(self, mock_wait4task,
                                             mock_delete):
        mock_delete.return_value = self.task, self.response_body
        mock_wait4task.return_value = self.task

        filter = "name='Exchange Server'"
        delete_task = self.resource_client.delete_all(filter=filter,
                                                      force=True,
                                                      timeout=-1)

        mock_wait4task.assert_called_with(self.task, timeout=-1)
        self.assertEqual(self.task, delete_task)

    @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", {},
            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")

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'get_completed_task')
    def test_create_report_should_do_post_request(self,
                                                  mock_get_completed_task,
                                                  mock_post):
        task_with_output = self.task.copy()
        task_with_output['taskOutput'] = []

        mock_post.return_value = self.task, {}
        mock_get_completed_task.return_value = task_with_output

        self.resource_client.create_report("/rest/path/create-report")

        mock_post.assert_called_once_with("/rest/path/create-report", {})

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'get_completed_task')
    def test_create_report_should_wait_task_completion(self,
                                                       mock_get_completed_task,
                                                       mock_post):
        task_with_output = self.task.copy()
        task_with_output['taskOutput'] = []

        mock_post.return_value = self.task, {}
        mock_get_completed_task.return_value = task_with_output

        self.resource_client.create_report("/rest/path/create-report",
                                           timeout=60)

        mock_get_completed_task.assert_called_once_with({"task": "task"}, 60)

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'get_completed_task')
    def test_create_report_should_return_output_list_when_results(
            self, mock_get_completed_task, mock_post):
        task_output = [{
            "type": "FCIssueResponseV2",
            "created": "2015-03-24T15: 32: 50.889Z"
        }, {
            "type": "FCIssueResponseV2",
            "created": "2015-03-13T14: 10: 50.322Z"
        }]
        task_with_output = self.task.copy()
        task_with_output['taskOutput'] = task_output

        mock_post.return_value = self.task, {}
        mock_get_completed_task.return_value = task_with_output

        result = self.resource_client.create_report("/rest/path/create-report")

        self.assertEqual(result, task_output)

    @mock.patch.object(connection, 'post')
    @mock.patch.object(TaskMonitor, 'get_completed_task')
    def test_create_report_should_return_empty_list_when_output_is_empty(
            self, mock_get_completed_task, mock_post):
        task_with_output = self.task.copy()
        task_with_output['taskOutput'] = []

        mock_post.return_value = self.task, {}
        mock_get_completed_task.return_value = task_with_output

        result = self.resource_client.create_report("/rest/path/create-report")

        self.assertEqual(result, [])

    @mock.patch.object(connection, 'post')
    def test_create_report_should_raise_exception_when_not_task(
            self, mock_post):
        task_with_output = self.task.copy()
        task_with_output['taskOutput'] = []

        mock_post.return_value = None, {}

        try:
            self.resource_client.create_report("/rest/path/create-report")
        except HPOneViewException as exception:
            self.assertEqual(RESOURCE_CLIENT_TASK_EXPECTED, exception.args[0])
        else:
            self.fail("Expected Exception was not raised")
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)
class SasLogicalJbodAttachments(object):
    """
    SAS Logical JBOD Attachments API client.

    Note:
        This resource is only available on HPE Synergy

    """
    URI = '/rest/sas-logical-jbod-attachments'

    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 SAS Logical JBOD Attachments. 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 SAS Logical JBOD Attachments.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets the SAS Logical JBOD Attachment with the specified ID or URI.

        Args:
            id_or_uri: ID or URI of the SAS Logical JBOD Attachment.

        Returns:
            dict: SAS Logical JBOD Attachment
        """
        return self._client.get(id_or_uri)

    def get_by(self, field, value):
        """
        Gets all SAS Logical JBOD Attachments that match the filter.

        The search is case-insensitive.

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

        Returns:
            list: A list of SAS Logical JBOD Attachments.
        """
        return self._client.get_by(field, value)
Esempio n. 27
0
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, "/rest/fake/resource")
Esempio n. 28
0
class EnclosureGroups(object):
    """
    Enclosure Groups API client.

    """
    URI = '/rest/enclosure-groups'

    DEFAULT_VALUES = {
        '200': {
            "type": "EnclosureGroupV200"
        },
        '300': {
            "type": "EnclosureGroupV300"
        }
    }

    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 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 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 enclosure groups.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets an enclosure group by ID or by URI.

        Args:
            id_or_uri: Can 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):
        """
        Gets all enclosure 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 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 for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

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

    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 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, 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 for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated enclosure group

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

    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)
Esempio n. 29
0
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self._provider_client = ResourceClient(con, self.PROVIDER_URI)
Esempio n. 30
0
class SanManagers(object):
    """
    SAN Managers API client.

    """
    URI = '/rest/fc-sans/device-managers'
    PROVIDER_URI = '/rest/fc-sans/providers'

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

    def get_all(self, start=0, count=-1, query='', sort=''):
        """
        Retrieves the list of registered SAN Managers.

        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.
            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 SAN managers.

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

    def get(self, id_or_uri):
        """
        Retrieves a single registered SAN Manager by ID or URI.

        Args:
            id_or_uri: Can be either the SAN Manager resource ID or URI.

        Returns:
            dict: The SAN Manager resource.
        """
        return self._client.get(id_or_uri=id_or_uri)

    def update(self, resource, id_or_uri):
        """
        Updates a registered Device Manager.

        Args:
            resource (dict): Object to update.
            id_or_uri: Can be either the Device manager ID or URI.

        Returns:
            dict: The device manager resource.
        """
        return self._client.update(resource=resource, uri=id_or_uri)

    def add(self, resource, provider_uri_or_id, timeout=-1):
        """
        Adds a Device Manager under the specified provider.

        Args:
            resource (dict): Object to add.
            provider_uri_or_id: ID or URI of provider.
            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 SAN Manager.
        """
        uri = self._provider_client.build_uri(
            provider_uri_or_id) + "/device-managers"
        return self._client.create(resource=resource, uri=uri, timeout=timeout)

    def get_provider_uri(self, provider_display_name):
        """
        Gets uri for a specific provider.

        Args:
            provider_display_name: Display name of the provider.

        Returns:
            uri
        """
        providers = self._provider_client.get_by('displayName',
                                                 provider_display_name)
        return providers[0]['uri'] if providers else None

    def get_default_connection_info(self, provider_name):
        """
        Gets default connection info for a specific provider.

        Args:
            provider_name: Name of the provider.

        Returns:
            dict: Default connection information.
        """
        provider = self._provider_client.get_by_name(provider_name)
        if provider:
            return provider['defaultConnectionInfo']
        else:
            return {}

    def remove(self, resource, timeout=-1):
        """
        Removes a registered SAN Manager.

        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 if the resource was successfully removed.
        """
        return self._client.delete(resource, timeout=timeout)

    def get_by_name(self, name):
        """
        Gets a SAN Manager by name.

        Args:
            name: Name of the SAN Manager

        Returns:
            dict: SAN Manager.
        """
        san_managers = self._client.get_all()
        result = [x for x in san_managers if x['name'] == name]
        return result[0] if result else None

    def get_by_provider_display_name(self, provider_display_name):
        """
        Gets a SAN Manager by provider display name.

        Args:
            provider_display_name: Name of the Provider Display Name

        Returns:
            dict: SAN Manager.
        """
        san_managers = self._client.get_all()
        result = [
            x for x in san_managers
            if x['providerDisplayName'] == provider_display_name
        ]
        return result[0] if result else None
Esempio n. 31
0
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self.__snapshot_default_values = {
         "type": "Snapshot"
     }
class ApplianceDeviceSNMPv3TrapDestinations(object):
    """
    ApplianceDeviceSNMPv3TrapDestinations API client.
    The appliance has the ability to forward events received from monitored or managed server hardware to the specified destinations as SNMPv3 traps.
    """
    URI = '/rest/appliance/snmpv3-trap-forwarding/destinations'

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

    def create(self, resource, timeout=-1):
        """
        Adds the specified trap forwarding destination.
        The trap destination associated with the specified id will be created if trap destination with that id does not exists.
        The id can only be an integer greater than 0.

        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 trap forwarding destination with the specified ID, if it exists.

        Args:
            id_or_uri: ID or URI of SNMPv3 trap destination.

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

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Retrieves all SNMPv3 trap forwarding destinations.

        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 Trap Destionations.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets all SNMPv3 trap forwarding destinations 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 Trap Destionations.
        """
        return self._client.get_by(field, value)

    def delete(self, id_or_uri, timeout=-1):
        """
        Deletes SNMPv3 trap forwarding destination based on {Id} only if no User is assigned to it.

        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 trap forwarding destination based on 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 trap destinations.
        """
        return self._client.update(resource, timeout=timeout)
Esempio n. 33
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)
Esempio n. 34
0
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)
Esempio n. 35
0
class Interconnects(object):
    URI = '/rest/interconnects'

    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 interconnects that includes the ports.
        In order to avoid a timeout on busy systems, the recommended maximum
        value of count is 2.

        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 interconnects.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_statistics(self, id_or_uri, port_name=''):
        """
        Gets the statistics from an interconnect.

        Args:
            interconnect_id: The interconnect id
            port_name (str): A specific port name of an interconnect

        Returns:
             dict: The statistics for the interconnect that matches id
        """
        uri = self._client.build_uri(id_or_uri) + "/statistics"

        if port_name:
            uri = uri + "/" + port_name

        return self._client.get(uri)

    def get_subport_statistics(self, id_or_uri, port_name, subport_number):
        """
        Gets the subport statistics on an interconnect.

        Args:
            interconnect_id: The interconnect id
            port_name (str): A specific port name of an interconnect
            subport_number (int): The subport

        Returns:
             dict: The statistics for the interconnect that matches id, port_name and subport_number
        """
        uri = self._client.build_uri(id_or_uri) + "/statistics/{0}/subport/{1}".format(port_name, subport_number)
        return self._client.get(uri)

    def get_name_servers(self, id_or_uri):
        """
        Gets the named servers for an interconnect.

        Args:
            id_or_uri:  can be either the interconnect id or the interconnect uri

        Returns:
             dict: the name servers for an interconnect.
        """

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

    def get(self, id_or_uri):
        """
        Gets the Interconnect by ID or by uri
        Args:
            id_or_uri: Could be either the interconnect id or the interconnect uri

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

    def get_by(self, field, value):
        """
        Gets all interconnects that matches the filter
        The search is case insensitive

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

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

    def get_by_name(self, name):
        """
        Retrieve an Interconnect by its name

        Args:
            name: Interconnect name

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

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Performs a specific patch operation for the given interconnect.
        There are a limited set of interconnect properties which may be changed.
        They are: 'powerState', 'uidState', 'deviceResetState'.
        If the interconnect supports the operation, the operation is performed and
        a task is returned through which the results are reported.
        Args:
            id_or_uri: Could be either the interconnect id or the interconnect 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
        """
        return self._client.patch(id_or_uri, operation, path, value, timeout)

    def update_port(self, port_information, id_or_uri, timeout=-1):
        """
        Updates an interconnect port.

        Args:
            id_or_uri: Could be either the interconnect id or the interconnect uri
            port_information (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: The interconnect

        """
        uri = self._client.build_uri(id_or_uri) + "/ports"
        return self._client.update(port_information, uri, timeout)

    def update_ports(self, ports, id_or_uri, timeout=-1):
        """
        Updates the interconnect ports.

        Args:
            id_or_uri: Could be either the interconnect id or the interconnect uri
            ports (dict): array of ports 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: The interconnect

        """
        resources = lmap(self.__port_with_default_type, ports)

        uri = self._client.build_uri(id_or_uri) + "/update-ports"
        return self._client.update(resources, uri, timeout)

    def __port_with_default_type(self, port):
        data = dict(type="port")
        data.update(port)
        return data

    def reset_port_protection(self, id_or_uri, timeout=-1):
        """
        Triggers a reset of port protection.
        Cause port protection to be reset on all the interconnects of the logical interconnect that matches ID
        Args:
            id_or_uri: Could be either the interconnect id or the 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:
            dict: The interconnect

        """
        uri = self._client.build_uri(id_or_uri) + "/resetportprotection"
        return self._client.update_with_zero_body(uri, timeout)
Esempio n. 36
0
 def __init__(self, con):
     self._client = ResourceClient(con, self.URI)
     self._task_monitor = TaskMonitor(con)
     self.__default_values = {
         'type': 'GoldenImage',
     }
Esempio n. 37
0
 def __init__(self, con):
     IdPoolsRanges.__init__(self, object, self.URI)
     self._connection = con
     self._client = ResourceClient(con, self.URI)
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self.__default_values = {
         "type": "logical-switch-group"
     }
Esempio n. 39
0
class Enclosures(object):
    """
    Enclosures API client.

    """
    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 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 Enclosures.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets all Enclosures that match 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):
        """
        C7000:
            Takes information about an enclosure (for example: IP address, username, password) and uses
            it to claim/configure the enclosure and add its components to the appliance.

        Synergy:
            Adds a remote enclosure and all the enclosures linked to that enclosure by their frame link
            modules. The remote enclosures' frame link modules must not be claimed by another appliance.
            The IP used must be the frame link module's Link Local IPv6 address.

        Args:
            information: Enclosure information to add.
            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: 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_or_uri: ID or URI of the Enclosure.

        Returns:
            dict: Enclosure.
        """
        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: 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.
        """
        headers = {'If-Match': '*'}
        return self._client.patch(id_or_uri,
                                  operation,
                                  path,
                                  value,
                                  timeout=timeout,
                                  custom_headers=headers)

    def remove(self, resource, force=False, timeout=-1):
        """
        Removes and unconfigures the specified enclosure from the appliance. All components of the enclosure (for
        example: 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 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 removed.
        """
        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.

        Args:
            id_or_uri: Can be either the resource ID or the resource 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:
            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: Can be either the resource ID or the resource URI.

        Returns:
            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: Can be either the resource ID or the resource URI.
            configuration: 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:
            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
        configuration dict must have the "refreshState" field set to "Refreshing" and optionally
        provide information to re-claim the enclosure (for example: IP address, user name, password, etc.).

        Args:
            id_or_uri: Can be either the resource ID or the resource URI.
            configuration: 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:
            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: Can be either the resource ID or the resource URI.

        Returns:
            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: Can be either the resource ID or the resource URI.
            role: Role

        Returns:
            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_or_uri: Can be either the resource ID or the resource URI.
            fields: Name of the metrics to be retrieved in the format METRIC[,METRIC]...

                If unspecified, all metrics supported are returned.

                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.

            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 (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)
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)
Esempio n. 41
0
class UplinkSets(object):
    """
    Uplink Sets API client.

    """
    URI = '/rest/uplink-sets'

    DEFAULT_VALUES = {
        '200': {
            "type": "uplink-setV3"
        },
        '300': {
            "type": "uplink-setV300"
        }
    }

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

    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.
        """
        return self._client.create(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    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.
        """
        return self._client.update(resource,
                                   timeout=timeout,
                                   default_values=self.DEFAULT_VALUES)

    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
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)
Esempio n. 43
0
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
     self.__default_values = {"type": "EnclosureGroupV200"}
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)
class IndexResources(object):
    """
    Index Resources API client.

    """

    URI = '/rest/index/resources'

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

    def get_all(self, category='', count=-1, fields='', filter='', padding=0, query='', reference_uri='',
                sort='', start=0, user_query='', view=''):
        """
        Gets a list of index resources based on optional sorting and filtering and is constrained by start
        and count parameters.

        Args:
            category (str or list):
                 Category of resources. Multiple Category parameters are applied with OR condition.
            count (int):
                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.
            fields (str):
                Specifies which fields should be returned in the result set.
            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.
            padding (int):
                Number of resources to be returned before the reference URI resource.
            query (str):
                 A general query string to narrow the list of resources returned.
                 The default is no query - all resources are returned.
            reference_uri (str):
                Load one page of resources, pagination is applied with reference to referenceUri provided.
            sort (str):
                The sort order of the returned data set. By default, the sort order is based
                on create time with the oldest entry first.
            start (int):
                The first item to return, using 0-based indexing.
                If not specified, the default is 0 - start with the first available item.
            user_query (str):
                Free text Query string to search the resources. This will match the string in any field that is indexed.
            view (str):
                Return a specific subset of the attributes of the resource or collection, by specifying the name of a predefined view.

        Returns:
            list: A list of index resources.
        """
        uri = self.URI + '?'

        uri += self.__list_or_str_to_query(category, 'category')
        uri += self.__list_or_str_to_query(fields, 'fields')
        uri += self.__list_or_str_to_query(filter, 'filter')
        uri += self.__list_or_str_to_query(padding, 'padding')
        uri += self.__list_or_str_to_query(query, 'query')
        uri += self.__list_or_str_to_query(reference_uri, 'referenceUri')
        uri += self.__list_or_str_to_query(sort, 'sort')
        uri += self.__list_or_str_to_query(user_query, 'userQuery')
        uri += self.__list_or_str_to_query(view, 'view')

        uri = uri.replace('?&', '?')

        return self._client.get_all(start=start, count=count, uri=uri)

    def get(self, uri):
        """
        Gets an index resource by URI.

        Args:
            uri: The resource URI.

        Returns:
            dict: The index resource.
        """
        uri = self.URI + uri
        return self._client.get(uri)

    def get_aggregated(self, attribute, category, child_limit=6, filter='', query='', user_query=''):
        """
        Gets a list of index resources based on optional sorting and filtering and is constrained by start
        and count parameters.

        Args:
            attribute (list or str):
                Attribute to pass in as query filter.
            category (str):
                Category of resources. Multiple Category parameters are applied with an OR condition.
            child_limit (int):
                Number of resources to be retrieved. Default=6.
            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 (str):
                A general query string to narrow the list of resources returned.
                The default is no query - all resources are returned.
            user_query (str):
                Free text Query string to search the resources.
                This will match the string in any field that is indexed.

        Returns:
            list: An aggregated list of index resources.
        """
        uri = self.URI + '/aggregated?'

        # Add attribute to query
        uri += self.__list_or_str_to_query(attribute, 'attribute')
        uri += self.__list_or_str_to_query(category, 'category')
        uri += self.__list_or_str_to_query(child_limit, 'childLimit')
        uri += self.__list_or_str_to_query(filter, 'filter')
        uri += self.__list_or_str_to_query(query, 'query')
        uri += self.__list_or_str_to_query(user_query, 'userQuery')

        uri = uri.replace('?&', '?')

        return self._client.get(uri)

    def __list_or_str_to_query(self, list_or_str, field_name):
        formated_query = ''
        if list_or_str:
            if isinstance(list_or_str, list):
                for f in list_or_str:
                    formated_query = formated_query + "&{0}=".format(field_name) + ''.join(quote(str(f)))
            else:
                formated_query = "&{0}=".format(field_name) + str(list_or_str)
        return formated_query
Esempio n. 46
0
class Switches(object):
    """
    Switches API client.

    Note:
        This resource is only available on C7000 enclosures.

    """
    URI = '/rest/switches'

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

    def get_statistics(self, id_or_uri, port_name=''):
        """
        Gets statistics for a switch.

        Args:
            id_or_uri: Can be either the switch id or the switch uri.
            port_name: switch port number (optional)

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

        if port_name:
            uri += "/" + port_name

        return self._client.get(uri)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a list of top of rack switches.

        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 rack switches.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

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

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

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

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

        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_environmental_configuration(self, id_or_uri):
        """
        Gets the environmental configuration for a switch.

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

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

    def get_by(self, field, value):
        """
        Gets all 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 rack switches.
        """
        return self._client.get_by(field, value)

    def update_ports(self, ports, id_or_uri):
        """
        Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are
        supported for update.

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

        Args:
            ports: List of Switch Ports.
            id_or_uri: Can be either the switch id or the switch uri.

        Returns:
            dict: Switch
        """
        ports = merge_default_values(ports, {'type': 'port'})

        uri = self._client.build_uri(id_or_uri) + "/update-ports"
        return self._client.update(uri=uri, resource=ports)

    def patch(self, id_or_uri, operation, path, value, timeout=-1):
        """
        Uses the PATCH to update a resource for a given logical switch.

        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)
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)
Esempio n. 48
0
class FirmwareDrivers(object):
    """
    Firmware Drivers API client.

    """
    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 Firmware 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 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 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.

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

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

    def create(self, resource, timeout=-1):
        """
        Creates a custom SPP (Service Pack for ProLiant) from an existing SPP and one or more hotfixes that have already
        been added to the 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: Created resource.

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

    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 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)
Esempio n. 49
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 OsDeploymentServers(object):
    URI = '/rest/deployment-servers'

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

    def get_all(self,
                start=0,
                count=-1,
                filter='',
                fields='',
                query='',
                sort='',
                view=''):
        """
        Gets a list of Deployment Servers 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.
            fields:
                Specifies which fields should be returned in the result set.
            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:
                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.

        Returns:
             list: Os Deployment Servers
        """
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    query=query,
                                    fields=fields,
                                    view=view)

    def get(self, id_or_uri):
        """
        Get the details of the particular OS Deployment Server based on its URI or ID.

        Args:
            id_or_uri:
                Can be either the Os Deployment Server ID or the URI

        Returns:
            dict: Os Deployment Server
        """
        return self._client.get(id_or_uri)

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

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

        Returns:
            list: Os Deployment Servers
        """
        return self._client.get_by(field, value)

    def get_by_name(self, name):
        """
        Gets the Os Deployment Server by name.

        Args:
            name: Name of the Os Deployment Server

        Returns:
            dict: Os Deployment Server
        """
        os_deployment_server = self.get_by('name', name) or [None]
        return os_deployment_server[0]

    def add(self, resource, timeout=-1):
        """
        Adds a Deployment Server using the information provided in the request body. Note: The type of the Deployment
        Server is always assigned as "Image streamer".

        Args:
            resource (dict):
                Deployment Manager resource.
            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 added resource.
        """
        return self._client.create(resource, timeout=timeout)

    def update(self, resource, force=False, timeout=-1):
        """
        Updates the Deployment Server resource. The properties that are omitted (not included as part
        of the request body) are ignored.

        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, timeout=-1):
        """
        Deletes a Deployment Server object based on its UUID or URI.

        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 volume was successfully deleted.
        """

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

    def get_networks(self):
        """
        Gets a list of all the One View networks.

        Returns:
             list: Networks
        """
        uri = self.URI + '/network'
        return self._client.get(uri)

    def get_appliances(self,
                       start=0,
                       count=-1,
                       filter='',
                       fields='',
                       query='',
                       sort='',
                       view=''):
        """
        Gets a list of all the Image Streamer 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.
            fields:
                Specifies which fields should be returned in the result set.
            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:
                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.

        Returns:
             list: Image Streamer resources associated with the Deployment Servers.
        """
        uri = self.URI + '/image-streamer-appliances'
        return self._client.get_all(start,
                                    count,
                                    filter=filter,
                                    sort=sort,
                                    query=query,
                                    fields=fields,
                                    view=view,
                                    uri=uri)

    def get_appliance(self, id_or_uri, fields=''):
        """
        Gets the particular Image Streamer resource based on its ID or URI.

        Args:
            id_or_uri:
                Can be either the Os Deployment Server ID or the URI
            fields:
                Specifies which fields should be returned in the result.

        Returns:
             dict: Image Streamer resource.
        """
        uri = self.URI + '/image-streamer-appliances/' + extract_id_from_uri(
            id_or_uri)
        if fields:
            uri += '?fields=' + fields

        return self._client.get(uri)

    def get_appliance_by_name(self, appliance_name):
        """
        Gets the particular Image Streamer resource based on its name.

        Args:
            appliance_name:
                The Image Streamer resource name.

        Returns:
             dict: Image Streamer resource.
        """
        appliances = self.get_appliances()

        if appliances:
            for appliance in appliances:
                if appliance['name'] == appliance_name:
                    return appliance
        return None
class StorageVolumeAttachments(object):
    """
    Storage Volume Attachments API client.

    """

    URI = '/rest/storage-volume-attachments'

    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 volume attachment resources.

        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: Volume attachment resources.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_extra_unmanaged_storage_volumes(self, start=0, count=-1, filter='', sort=''):
        """
        Gets the list of extra unmanaged storage volumes.

        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: Extra unmanaged storage volumes.
        """
        uri = self.URI + "/repair?alertFixType=ExtraUnmanagedStorageVolumes"
        return self._client.get_all(start=start, count=count, filter=filter, sort=sort, uri=uri)

    def remove_extra_presentations(self, resource, timeout=-1):
        """
        Removes extra presentations from a specified server profile.

        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: Associated storage attachment resource.
        """
        uri = self.URI + "/repair"
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.create(resource, uri=uri, timeout=timeout, custom_headers=custom_headers)

    def get_paths(self, id_or_uri, path_id_or_uri=''):
        """
        Gets all paths or a specific attachment path for the specified volume attachment.

        Args:
            id_or_uri: Can be either the volume attachment id or the volume attachment uri.
            path_id_or_uri: Can be either the path id or the path uri.

        Returns:
            dict: Paths.
        """
        if path_id_or_uri:
            uri = self._client.build_uri(path_id_or_uri)
            if "/paths" not in uri:
                uri = self._client.build_uri(
                    id_or_uri) + "/paths" + "/" + path_id_or_uri

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

        return self._client.get(uri)

    def get(self, id_or_uri):
        """
        Gets a volume attachment by ID or URI.

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

        Returns:
            dict: volume attachment
        """
        return self._client.get(id_or_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: List of volume attachments.
        """
        return self._client.get_by(field, value)
Esempio n. 52
0
class Tasks(object):
    URI = '/rest/tasks'

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

    def get(self, id_or_uri):
        """
        Retrieve a task by its uri.

        Args:
            id_or_uri: task id (or uri)

        Returns:
            dict: The task.

        """

        task = self._client.get(id_or_uri)
        return task

    def get_all(self,
                start=0,
                count=-1,
                fields='',
                filter='',
                query='',
                sort='',
                view=''):
        """
        Gets all the tasks based upon filters provided.

        Note:
            Filters are optional.

        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.
            fields:
                 Specifies which fields should be returned in the result set.
            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.
            view:
                 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.

        Returns:
            list: A list of tasks.
        """
        return self._client.get_all(start=start,
                                    count=count,
                                    filter=filter,
                                    query=query,
                                    sort=sort,
                                    view=view,
                                    fields=fields)
class Connections(object):
    """
    Connections API client.

    """

    URI = '/rest/connections'

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

    def get_all(self, start=0, count=-1, filter='', sort='', view='', fields=''):
        """
        Gets a paginated collection of connections 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.
            fields:
                Specifies which fields should be returned in the result set.
            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 connections.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort, view=view, fields=fields)

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

        The search is case-insensitive.

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

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

    def get(self, id_or_uri):
        """
        Returns the connection with the specified ID or URI.

        Args:
            id: ID or URI of connection

        Returns:
            dict
        """
        return self._client.get(id_or_uri)
class ApplianceDeviceSNMPv1TrapDestinations(object):
    """
    ApplianceDeviceSNMPv1TrapDestinations API client.
    The appliance has the ability to forward events received from monitored or managed server hardware to the specified destinations as SNMPv1 traps.
    """
    URI = '/rest/appliance/trap-destinations'

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

    def create(self, resource, id=None, timeout=-1):
        """
        Adds the specified trap forwarding destination.
        The trap destination associated with the specified id will be created if trap destination with that id does not exists.
        The id can only be an integer greater than 0.

        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.

        """
        if not id:
            available_id = self.__get_first_available_id()
            uri = '%s/%s' % (self.URI, str(available_id))
        else:
            uri = '%s/%s' % (self.URI, str(id))
        return self._client.create(resource, uri=uri, timeout=timeout)

    def __findFirstMissing(self, array, start, end):
        """
        Find the smallest elements missing in a sorted array.

        Returns:
            int: The smallest element missing.
        """
        if (start > end):
            return end + 1

        if (start != array[start]):
            return start

        mid = int((start + end) / 2)

        if (array[mid] == mid):
            return self.__findFirstMissing(array, mid + 1, end)

        return self.__findFirstMissing(array, start, mid)

    def __get_first_available_id(self):
        """
        Private method to get the first available id.
        The id can only be an integer greater than 0.

        Returns:
            int: The first available id
        """
        traps = self.get_all()
        if traps:
            used_ids = [0]
            for trap in traps:
                used_uris = trap.get('uri')
                used_ids.append(int(used_uris.split('/')[-1]))
            used_ids.sort()
            return self.__findFirstMissing(used_ids, 0, len(used_ids) - 1)
        else:
            return 1

    def get(self, id_or_uri):
        """
        Returns the SNMPv1 trap forwarding destination with the specified ID, if it exists.

        Args:
            id_or_uri: ID or URI of SNMPv1 trap destination.

        Returns:
            dict: Appliance SNMPv1 trap destination.
        """
        return self._client.get(id_or_uri)

    def get_all(self, start=0, count=-1, filter='', sort=''):
        """
        Retrieves all SNMPv1 trap forwarding destinations.

        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 SNMPv1 Trap Destionations.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get_by(self, field, value):
        """
        Gets all SNMPv1 trap forwarding destinations that match the filter.
        The search is case-insensitive.

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

        Returns:
            list: A list of SNMPv1 Trap Destionations.
        """
        return self._client.get_by(field, value)

    def delete(self, id_or_uri, timeout=-1):
        """
        Deletes SNMPv1 trap forwarding destination based on {Id}.

        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 the specified trap forwarding destination.
        The trap destination associated with the specified id will be updated if a trap destination with that id already exists.
        The id can only be an integer greater than 0.

        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 SNMPv1 trap destinations.
        """
        return self._client.update(resource, timeout=timeout)
Esempio n. 55
0
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:
            dict: Details of associated resource

        """
        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 type.
        """
        return self._client.get_by(field, value)
Esempio n. 56
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:
            dict: 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:
            dict: 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:
            dict: 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:
            dict: 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:
            dict: 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:
            dict: 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.

        Warning:
            It does not create the LOGICAL INTERCONNECT itself.
            It will fail if no interconnect is already present on the specified position.

        Args:
            location_entries (dict): 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:
            dict: 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.

        Warning:
            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).

        Args:
            firmware_information: Options to install firmware to a logical interconnect.
            id_or_uri: Could be either the logical interconnect id or the logical interconnect uri.

        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.
            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: 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 LogicalDownlinks(object):
    URI = '/rest/logical-downlinks'

    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 downlinks. 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 logical downlinks.
        """
        return self._client.get_all(start, count, filter=filter, sort=sort)

    def get(self, id_or_uri):
        """
        Gets a logical downlink by ID or by uri.

        Args:
            id_or_uri: Could be either the logical downlink id or the logical downlink uri.

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

    def get_by(self, field, value):
        """
        Get all logical downlinks 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 downlinks.
        """
        return self._client.get_by(field, value)

    def get_all_without_ethernet(self, start=0, count=-1, filter='', sort=''):
        """
        Gets a paginated collection of logical downlinks without ethernet. 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:
            dict
        """
        without_ethernet_client = ResourceClient(
            self._connection, "/rest/logical-downlinks/withoutEthernet")
        return without_ethernet_client.get_all(start, count, filter=filter, sort=sort)

    def get_without_ethernet(self, id):
        """
        Gets the logical downlink with the specified ID without ethernet.

        Args:
            id: ID of logical downlink.

        Returns:
            dict
        """
        uri = "/rest/logical-downlinks/%s/withoutEthernet" % (id)
        return self._client.get(uri)
Esempio n. 58
0
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)
 def __init__(self, con):
     self._connection = con
     self._client = ResourceClient(con, self.URI)
Esempio n. 60
0
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)