コード例 #1
0
ファイル: testbuilder_mgmt.py プロジェクト: Tokalabs/tokasdk
def abort_test_suite(toka_api_configuration, topo_name=None, test_suite_name=None):
    """Abort an already running test suite on the Toka controller.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        topo_name (str): Name of the topology that contains the test suite to be aborted.
        test_suite_name (str): Name of the test suite to be aborted.

    Returns:
        bool: True if the test suite was aborted successfully, False otherwise.
    """
    if ( None == toka_api_configuration or 
         None == topo_name or 0 == len(topo_name.strip()) or 
         None == test_suite_name or 0 == len(test_suite_name.strip())):
        print('[testbuilder_mgmt][abort_test_suite] Invalid input '
              'specified. Either the Toka API configuration object or '
              'the topology name is null or empty or the test_suite_name is null or empty. '
              'Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Aborted'
    TOKA_API_RESPONSE_KEY_STATUS = 'status'

    try:
        tuple_user_token = (libsamples.setup.setup_steps
                    .fetch_username_token_from_configuration_object(
                        toka_api_configuration=toka_api_configuration))
        if None == tuple_user_token:
            return False

        toka_topology_api_instance = tokasdk.TestBuilderApi(tokasdk.ApiClient(toka_api_configuration))
        api_v1_response = toka_topology_api_instance.abort_test_suite_v1(
                                                    topology_name=topo_name, 
                                                    suite_name=test_suite_name,
                                                    username=tuple_user_token[0], 
                                                    api_token=tuple_user_token[1])
        if (True == hasattr(api_v1_response, TOKA_API_RESPONSE_KEY_STATUS) and 
            None != api_v1_response.status and 
            -1 != api_v1_response.status.lower().find(TOKA_API_RESPONSE_SUCCESS.lower())):
            # Test suite was aborted uccessfully...
            return True
        else:
            print('[testbuilder_mgmt][abort_test_suite] Failed to '
                    'abort the test suite. Returning failure. '
                    'Error message ' + str(api_v1_response))
            return False
    except ApiException as exc:
        print('[testbuilder_mgmt][abort_test_suite] APIException '
                ' occurred while attempting to abort the test suite. '
                'Returning failure. APIException status- {0}, '
                'reason - {1}, message -{2}, response body - {3}'
                .format(exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[testbuilder_mgmt][abort_test_suite] Exception '
              ' occurred while attempting to abort the test suite. '
              'Returning failure. Exception message - {0}'
              .format(exc.message))
        # traceback.print_exc()            
        return False    
コード例 #2
0
def search_direct_connections(toka_api_configuration, hostname=None):
    """Search for connections in the Toka controller inventory based on the specified filter(s).
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object
        hostname (str, optional): Hostname to be used for searching and filtering 
                                    direct connections. Defaults to None.
    
    Returns:
        list: List of connections matching the specified filters if successful,
              None otherwise
    """
    if None == toka_api_configuration:
        print(
            '[inventory_conn_mgmt][search_direct_connections] Invalid input specified. The '
            'Toka API configuration object is null or empty. Returning failure'
        )
        return None

    TOKA_API_RESPONSE_SUCCESS = 'Success'
    TOKA_API_RESPONSE_KEY_DIRECT_CONN_LIST = 'directConnectionsList'

    try:
        toka_connections_api_instance = tokasdk.ConnectionsApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_connections_api_instance.get_connections_and_filter(
            hostname=hostname)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()
                and None != api_response.additional_details):
            if (TOKA_API_RESPONSE_KEY_DIRECT_CONN_LIST
                    in api_response.additional_details
                    and None != api_response.additional_details[
                        TOKA_API_RESPONSE_KEY_DIRECT_CONN_LIST]):
                # Atleast 1 connection matched the search filter...
                return api_response.additional_details[
                    TOKA_API_RESPONSE_KEY_DIRECT_CONN_LIST]
            else:
                # No connections matched the search filter. Return an empty list
                return []
        else:
            print('[inventory_conn_mgmt][search_direct_connections] Failed to '
                  'retrieve devices. Returniing failure. '
                  'Error message ' + api_response.message)
            return None
    except ApiException as exc:
        print('[inventory_conn_mgmt][search_direct_connections] APIException '
              ' occurred while attempting to add a network device. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message - {2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return None
    except Exception as exc:
        print('[inventory_conn_mgmt][search_direct_connections] Exception '
              ' occurred while attempting to add a network device. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return None
コード例 #3
0
def delete_connection(toka_api_configuration, connection_id):
    """Delete a conenction from the Toka controller inventory.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object
        connection_id (str): Connection id for the connection to be deleted
    
    Returns:
        bool: True if the connection was deleted successfully, False otherwise
    """
    if (None == toka_api_configuration or None == connection_id
            or 0 == len(connection_id.strip())):
        print('[inventory_device_mgmt][delete_connection] Invalid input '
              'specified. Either the Toka API configuration object or '
              'the hostname is null or empty. Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Success'

    try:
        toka_connections_api_instance = tokasdk.ConnectionsApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_connections_api_instance.delete_connection(
            connectionid=connection_id)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()):
            # Connection was deleted successfully...
            return True
        else:
            print('[inventory_device_mgmt][delete_connection] Failed to '
                  'delete the connection. Returniing failure. '
                  'Error message ' + api_response.message)
            return False
    except ApiException as exc:
        print('[inventory_device_mgmt][delete_connection] APIException '
              ' occurred while attempting to delete the connection. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message - {2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[inventory_device_mgmt][delete_connection] Exception '
              ' occurred while attempting to delete the connection. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return False
コード例 #4
0
ファイル: topology_mgmt.py プロジェクト: Tokalabs/tokasdk
def delete_topology(toka_api_configuration, topo_name=None):
    """Delete a topology from the Toka controller.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        topo_name (str): Name of the topology to be deleted.
    
    Returns:
        bool: True if the topology was deleted successfully, False otherwise.
    """
    if (None == toka_api_configuration or None == topo_name
            or 0 == len(topo_name.strip())):
        print('[topology_mgmt][delete_topology] Invalid input '
              'specified. Either the Toka API configuration object or '
              'the topology name is null or empty. Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Success'

    try:
        toka_topology_api_instance = tokasdk.TopologyApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_topology_api_instance.delete_topology(
            topologyname=topo_name)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()):
            # Topology was deleted successfully...
            return True
        else:
            print('[topology_mgmt][delete_topology] Failed to '
                  'delete the topology. Returniing failure. '
                  'Error message ' + str(api_response))
            return False
    except ApiException as exc:
        print('[topology_mgmt][delete_topology] APIException '
              ' occurred while attempting to delete the topology. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message -{2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[topology_mgmt][delete_topology] Exception '
              ' occurred while attempting to delete the topology. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return False
コード例 #5
0
def delete_device(toka_api_configuration, hostname=None):
    """Delete a device from the Toka controller inventory.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        hostname (str): Hostname of the device to be deleted.
    
    Returns:
        bool: True if the device was deleted successfully, False otherwise.
    """
    if (None == toka_api_configuration or None == hostname
            or 0 == len(hostname.strip())):
        print('[inventory_device_mgmt][delete_device] Invalid input '
              'specified. Either the Toka API configuration object or '
              'the hostname is null or empty. Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Success'

    try:
        toka_inv_mgmt_api_instance = tokasdk.InventoryManagementApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_inv_mgmt_api_instance.delete_inventory_device(
            hostname=hostname, delete_from_server=False)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()):
            # Device was deleted successfully...
            return True
        else:
            print('[inventory_device_mgmt][delete_device] Failed to '
                  'delete the device. Returniing failure. '
                  'Error message ' + str(api_response))
            return False
    except ApiException as exc:
        print('[inventory_device_mgmt][delete_device] APIException '
              ' occurred while attempting to delete the device. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message -{2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[inventory_device_mgmt][delete_device] Exception '
              ' occurred while attempting to delete the device. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return False
コード例 #6
0
def add_connection(toka_api_configuration, src_hostname, src_port_id,
                   target_hostname, target_port_id):
    """Connect the specified devices on the specified ports.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object
        src_hostname (str): Hostname of the source device to be connected
        src_port_id (str): Port id of the source device to be connected
        target_hostname (str): Hostname of the target device to be connected
        target_port_id (str): Port id of the target device to be connected
    
    Returns:
        str: connection id of the newly created connection if successful, None otherwise
    """
    if (None == toka_api_configuration or None == src_hostname
            or 0 == len(src_hostname.strip()) or None == src_port_id
            or 0 == len(src_port_id.strip()) or None == target_hostname
            or 0 == len(target_hostname.strip()) or None == target_port_id
            or 0 == len(target_port_id.strip())):
        print('[inventory_conn_mgmt][add_connection] Invalid input specified. '
              'Either the Toka API configuration object or the source '
              'hostname or the source port id or the target hostname '
              'or the target port id is null or empty. Returning failure')
        return None

    TOKA_API_RESPONSE_SUCCESS = 'Success'
    TOKA_API_RESPONSE_KEY_CONN_ID = 'connectionId'

    try:
        add_connection_request = tokasdk.AddConnectionsRequest(
            source_host=src_hostname.strip(),
            target_host=target_hostname.strip(),
            source_port_id=src_port_id.strip(),
            target_port_id=target_port_id.strip())

        toka_connections_api_instance = tokasdk.ConnectionsApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_connections_api_instance.add_connections(
            add_connections_request=add_connection_request)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()
                and TOKA_API_RESPONSE_KEY_CONN_ID
                in api_response.additional_details and None !=
                api_response.additional_details[TOKA_API_RESPONSE_KEY_CONN_ID]
            ):
            # Connection added successfully...
            return api_response.additional_details[
                TOKA_API_RESPONSE_KEY_CONN_ID]
        else:
            print('[inventory_conn_mgmt][add_connection] Failed to '
                  'add the connection. Returniing failure. '
                  'Error message ' + api_response.message)
            return None
    except ApiException as exc:
        print('[inventory_conn_mgmt][add_connection] APIException '
              ' occurred while attempting to add the connection. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message - {2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return None
    except Exception as exc:
        print('[inventory_conn_mgmt][add_connection] Exception '
              ' occurred while attempting to add the connection. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return None
コード例 #7
0
def login(toka_api_configuration, username, password):
    """Log into the Toka controller.

    If the provided username and password combination is valid, then 
    thie function also set the server returned API token in the Toka 
    API configuration object so that all further operations attempted
    using the Toka SDK client will automatically use the API token.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        username (str): Username to be used for login.
        password (str): Password to be used for login.
    
    Returns:
        str: API token if successful, None if failed.
    """
    if (None == toka_api_configuration or None == username
            or 0 == len(username.strip()) or None == password
            or 0 == len(password.strip())):
        print('[setup_steps][login] Invalid input specified. Either the '
              'Toka API configuration object or the username or the '
              'password is null or empty. Returning failure')
        return None

    TOKA_API_REQUEST_HEADER_TOKEN = 'Authorization'
    TOKA_API_RESPONSE_KEY_TOKEN = 'token'
    TOKA_API_RESPONSE_SUCCESS = 'Success'

    try:
        login_request = tokasdk.LoginRequest(username=username.strip(),
                                             password=password.strip())

        # Login to the Toka controller and obtain a valid Toka API token
        toka_login_api_instance = tokasdk.LoginApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_login_api_instance.login(
            login_request=login_request)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()
                and None != api_response.additional_details and
                TOKA_API_RESPONSE_KEY_TOKEN in api_response.additional_details
                and TOKA_API_RESPONSE_KEY_TOKEN in
                api_response.additional_details[TOKA_API_RESPONSE_KEY_TOKEN]):
            # Login succeeded, Set the returned api token as the request header
            toka_api_configuration.api_key[
                TOKA_API_REQUEST_HEADER_TOKEN] = api_response.additional_details[
                    TOKA_API_RESPONSE_KEY_TOKEN][TOKA_API_RESPONSE_KEY_TOKEN]
            return toka_api_configuration.api_key[
                TOKA_API_REQUEST_HEADER_TOKEN]
        else:
            print('[setup_steps][login] Login failed. Returniing failure. '
                  'Login failed message ' + api_response.message)
            return None
    except ApiException as exc:
        print('[setup_steps][login] APIException while attempting to login. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message -{2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return None
    except Exception as exc:
        print('[setup_steps][login] Exception while attempting to login. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return None
コード例 #8
0
ファイル: topology_mgmt.py プロジェクト: Tokalabs/tokasdk
def create_topology(toka_api_configuration,
                    topo_name,
                    list_of_devices_to_add_to_topo,
                    list_of_indirect_connections_to_be_added_to_topo=[]):
    """Create a topology on the Toka controller inventory.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        list_of_devices_to_add_to_topo (list): List of devices to be added to the topology.
        list_of_indirect_connections_to_be_added_to_topo (list): List of indirect connections 
                                                to be added to the topology. Defaults to [].

    Returns:
        bool: True if the topology was created successfully, False otherwise.
    """
    if (None == toka_api_configuration or None == topo_name
            or 0 == len(topo_name.strip())
            or None == list_of_devices_to_add_to_topo
            or False == isinstance(list_of_devices_to_add_to_topo, list)
            or 0 == len(list_of_devices_to_add_to_topo) or False == isinstance(
                list_of_indirect_connections_to_be_added_to_topo, list)):
        print(
            '[topology_mgmt][create_topology] Invalid input specified. Either the '
            'Toka API configuration object or the topology name or the '
            'list of devices to be added to the topology '
            'is null or empty. Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Success'

    try:
        create_topology_request = tokasdk.AddTopologyRequest(
            name=topo_name,
            devices=list_of_devices_to_add_to_topo,
            indirect_connections=
            list_of_indirect_connections_to_be_added_to_topo)
        toka_topology_api_instance = tokasdk.TopologyApi(
            tokasdk.ApiClient(toka_api_configuration))

        api_response = toka_topology_api_instance.add_topology(
            add_topology_request=create_topology_request)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()):
            # Topology was created successfully...
            return True
        else:
            print('[topology_mgmt][create_topology] Failed to '
                  'create the topology. Returniing failure. '
                  'Error message ' + str(api_response))
            return False
    except ApiException as exc:
        print('[topology_mgmt][create_topology] APIException '
              ' occurred while attempting to create topology. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message -{2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[topology_mgmt][create_topology] Exception '
              ' occurred while attempting to create topology. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return False
コード例 #9
0
ファイル: topology_mgmt.py プロジェクト: Tokalabs/tokasdk
def search_topologies(toka_api_configuration,
                      topo_name=None,
                      topo_reservation_status=None):
    """Search for topologies in the Toka controller inventory based on the specified filters.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        topo_name (str, optional): Topology name to be used for searching and filtering topologies. 
                                     Defaults to None.
        topo_reservation_status (str, optional): Topology reservation status to be used for 
                                     searching and filtering topologies. Defaults to None.
    
    Returns:
        list: List of topologies matching the specified filters if successful,
              None otherwise.
    """
    if None == toka_api_configuration:
        print(
            '[topology_mgmt][search_topologies] Invalid input specified. The '
            'Toka API configuration object is null or empty. Returning failure'
        )
        return None

    TOKA_API_RESPONSE_SUCCESS = 'Success'
    TOKA_API_RESPONSE_KEY_TOPOLOGYLIST = 'topologiesList'

    try:
        toka_topology_api_instance = tokasdk.TopologyApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_topology_api_instance.get_topology(
            name=topo_name, reservation_status=topo_reservation_status)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()
                and None != api_response.additional_details):
            if (TOKA_API_RESPONSE_KEY_TOPOLOGYLIST
                    in api_response.additional_details
                    and None != api_response.
                    additional_details[TOKA_API_RESPONSE_KEY_TOPOLOGYLIST]):
                # Atleast 1 topology matched the search filter...
                return api_response.additional_details[
                    TOKA_API_RESPONSE_KEY_TOPOLOGYLIST]
            else:
                # No topologies matched the search filter. Return an empty list
                return []
        else:
            print('[[topology_mgmt][search_topologies] Failed to '
                  'retrieve topologies. Returniing failure. '
                  'Error message ' + str(api_response))
            return None
    except ApiException as exc:
        print('[topology_mgmt][search_topologies] APIException '
              ' occurred while attempting to retrieve topologies. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message - {2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return None
    except Exception as exc:
        print('[topology_mgmt][search_topologies] Exception '
              ' occurred while attempting to retrieve topologies. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return None
コード例 #10
0
ファイル: testbuilder_mgmt.py プロジェクト: Tokalabs/tokasdk
def fetch_test_status(toka_api_configuration, topo_name=None, test_suite_name=None, test_id=None):
    """Retrieve the run status of the test on the Toka controller.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        topo_name (str): Name of the topology that contains the test whose run status is to be retrieved.
        test_suite_name (str): Name of the test suite that contains the test whose run status is to be retrieved.
        test_id (str): Id of the test whose run status is to be retrieved.

    Returns:
        str: Test run status if successful, None otherwise.
    """
    if ( None == toka_api_configuration or None == topo_name or 0 == len(topo_name.strip()) or 
         None == test_suite_name or 0 == len(test_suite_name.strip()) or 
         None == test_id or 0 == len(test_id.strip()) ):
        print('[testbuilder_mgmt][fetch_test_status] Invalid input '
              'specified. Either the Toka API configuration object or '
              'the topology name is null or empty or '
              'the test_suite_name is null or empty. or'
              'the test_id is null or empty. or'
              ' Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Success'    
    TOKA_API_RESPONSE_KEY_STATUS = 'status'
    TOKA_API_RESPONSE_KEY_TEST_STATUS = 'test_case_status'

    try:
        tuple_user_token = (libsamples.setup.setup_steps
                    .fetch_username_token_from_configuration_object(
                        toka_api_configuration=toka_api_configuration))
        if None == tuple_user_token:
            return False
        toka_topology_api_instance = tokasdk.TestBuilderApi(tokasdk.ApiClient(toka_api_configuration))
        api_v1_response = toka_topology_api_instance.get_test_status_v1(
                                                        topology_name=topo_name, 
                                                        suite_name=test_suite_name, 
                                                        testcase_id=test_id, 
                                                        username=tuple_user_token[0], 
                                                        api_token=tuple_user_token[1])
        if (True == hasattr(api_v1_response, TOKA_API_RESPONSE_KEY_STATUS) and 
            None != api_v1_response.status and 
            -1 != api_v1_response.status.lower().find(TOKA_API_RESPONSE_SUCCESS.lower()) and
            True == hasattr(api_v1_response, TOKA_API_RESPONSE_KEY_TEST_STATUS) and 
            None != api_v1_response.test_case_status ):
            # Test run status was retrieved successfully
            return api_v1_response.test_case_status
        else:
            print('[testbuilder_mgmt][fetch_test_status] Failed to '
                    'retrieve the test run status. Returning failure. '
                    'Error message ' + str(api_v1_response))
            return False
    except ApiException as exc:
        print('[testbuilder_mgmt][fetch_test_status] APIException '
                ' occurred while attempting to retrieve the test run status. '
                'Returning failure. APIException status- {0}, '
                'reason - {1}, message -{2}, response body - {3}'
                .format(exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[testbuilder_mgmt][fetch_test_status] Exception '
              ' occurred while attempting to retrieve the test run status. '
              'Returning failure. Exception message - {0}'
              .format(exc.message))
        # traceback.print_exc()            
        return False   
コード例 #11
0
def add_network_device(toka_api_configuration,
                       hostname,
                       device_type='ap',
                       device_asset_id='',
                       device_vendor='',
                       device_ports={}):
    """Add a network device to the Toka controller inventory.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object.
        hostname (str): Hostname of the device to be added.
        device_type (str, optional): Type of device to be added. Defaults to 'ap'.
        device_asset_id (str, optional): Asset id of the device to be added. Defaults to ''.
        device_vendor (str, optional): Vendor of the device to be added. Defaults to ''.
        device_ports (dict, optional): Ports of the device to be added. Defaults to {}.
    
    Returns:
        bool: True if the network device was added successfully, False otherwise.
    """
    if (None == toka_api_configuration or None == hostname
            or 0 == len(hostname.strip()) or None == device_type
            or 0 == len(device_type.strip())):
        print(
            '[inventory_device_mgmt][add_network_device] Invalid input specified. Either the '
            'Toka API configuration object or the hostname or the '
            'device type is null or empty. Returning failure')
        return False

    TOKA_API_RESPONSE_SUCCESS = 'Success'

    try:
        add_network_device_request = tokasdk.AddNetworkDeviceRequest(
            hostname=hostname,
            device_type=device_type,
            physical_port_connections=device_ports,
            asset_id=device_asset_id,
            vendor=device_vendor)

        toka_inv_mgmt_api_instance = tokasdk.InventoryManagementApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_inv_mgmt_api_instance.add_network_device(
            add_network_device_request=add_network_device_request)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()):
            # Device was added successfully...
            return True
        else:
            print('[inventory_device_mgmt][add_network_device] Failed to '
                  'add the network device. Returniing failure. '
                  'Error message ' + str(api_response))
            return False
    except ApiException as exc:
        print('[inventory_device_mgmt][add_network_device] APIException '
              ' occurred while attempting to add a network device. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message -{2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return False
    except Exception as exc:
        print('[inventory_device_mgmt][add_network_device] Exception '
              ' occurred while attempting to add a network device. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return False
コード例 #12
0
def search_devices(toka_api_configuration,
                   hostname=None,
                   device_type=None,
                   device_reservation_status=None):
    """Search for devices in the Toka controller inventory based on the specified filters.
    
    Args:
        toka_api_configuration (tokasdk.Configuration): Toka SDK configuration object
        hostname (str, optional): Hostname to be used for searching and filtering devices. 
                                     Defaults to None.
        device_type (str, optional): Device type to be used for searching and filtering devices. 
                                     Defaults to None.
        device_reservation_status (str, optional): Device reservation status to be used for 
                                     searching and filtering devices. Defaults to None.
    
    Returns:
        list: List of devices matching the specified filters if successful,
              None otherwise.
    """
    if None == toka_api_configuration:
        print(
            '[inventory_device_mgmt][search_devices] Invalid input specified. The '
            'Toka API configuration object is null or empty. Returning failure'
        )
        return None

    TOKA_API_RESPONSE_SUCCESS = 'Success'
    TOKA_API_RESPONSE_KEY_DEVICELIST = 'devicesList'

    try:
        toka_inv_mgmt_api_instance = tokasdk.InventoryManagementApi(
            tokasdk.ApiClient(toka_api_configuration))
        api_response = toka_inv_mgmt_api_instance.get_inventory_devices(
            hostname=hostname,
            device_type=device_type,
            reservation_status=device_reservation_status)

        if (None != api_response.status and TOKA_API_RESPONSE_SUCCESS.lower()
                == api_response.status.lower()
                and None != api_response.additional_details):
            if (TOKA_API_RESPONSE_KEY_DEVICELIST
                    in api_response.additional_details
                    and None != api_response.
                    additional_details[TOKA_API_RESPONSE_KEY_DEVICELIST]):
                # Atleast 1 device matched the search filter...
                return api_response.additional_details[
                    TOKA_API_RESPONSE_KEY_DEVICELIST]
            else:
                # No devices matched the search filter. Return an empty list
                return []
        else:
            print('[inventory_device_mgmt][search_devices] Failed to '
                  'retrieve devices. Returniing failure. '
                  'Error message ' + str(api_response))
            return None
    except ApiException as exc:
        print('[inventory_device_mgmt][add_network_device] APIException '
              ' occurred while attempting to retrieve devices. '
              'Returning failure. APIException status- {0}, '
              'reason - {1}, message - {2}, response body - {3}'.format(
                  exc.status, exc.reason, exc.message, exc.body))
        return None
    except Exception as exc:
        print('[inventory_device_mgmt][add_network_device] Exception '
              ' occurred while attempting to retrieve devices. '
              'Returning failure. Exception message - {0}'.format(exc.message))
        # traceback.print_exc()
        return None