Ejemplo n.º 1
0
def ntp_servers_clear(handle, ntp_servers=[]):
    """
    Clears the NTP servers provided in the arguments.
    Clears all the NTP servers, only if ntp is disabled.

    Args:
        handle (ImcHandle)
        ntp_servers (list): List of NTP servers in the format
                            ["192.168.1.1", "192.168.1.2"]

    Returns:
        CommNtpProvider object
    """

    mo = _get_mo(handle, dn=NTP_DN)
    args = {}

    if ntp_servers:
        args = {x: "" for x in _NTP_SERVER_LIST
                if getattr(mo, x) in ntp_servers}
    else:
        args = {x: "" for x in _NTP_SERVER_LIST}

    if mo.ntp_enable.lower() in ["yes", "true"] and \
            len(args) == len(_NTP_SERVER_LIST):
        raise ImcOperationError(
            "Clear NTP Servers",
            "Cannot clear all NTP servers when NTP is enabled")

    mo.set_prop_multiple(**args)
    mo.ntp_enable = mo.ntp_enable
    handle.set_mo(mo)
    return handle.query_dn(mo.dn)
Ejemplo n.º 2
0
def ntp_setting_exists(handle, **kwargs):
    """
    Check if the specified NTP settings are already applied
    Args:
        handle (ImcHandle)
        kwargs: key-value paired arguments

    Returns:
        (True, CommNtpProvider) if settings match, (False, None) otherwise
    """

    mo = _get_mo(handle, dn=NTP_DN)
    if mo is None:
        return False, None

    kwargs['ntp_enable'] = "yes"

    if _is_valid_arg("ntp_servers", kwargs):
        args = _get_ntp_servers(kwargs['ntp_servers'])
        del kwargs['ntp_servers']
        kwargs.update(args)

    if not mo.check_prop_match(**kwargs):
        return False, mo

    return True, mo
Ejemplo n.º 3
0
def ntp_servers_modify(handle, ntp_servers=[]):
    """
    Modifies the configured NTP servers
    Args:
        handle (ImcHandle)
        ntp_servers (list): List of dictionaries in the format
                            [{"id": 1, "ip": "192.168.1.1"},
                             {"id": 2, "ip": "192.168.1.2"}]
                            Upto 4 ntp servers can be specified.

    Returns:
        CommNtpProvider object

    Example:
        ntp_servers_modify(handle,
                           ntp_servers = [{"id": 1, "ip": "192.168.1.1"},
                                          {"id": 2, "ip": "192.168.1.2"},
                                          {"id": 3, "ip": ""}]
    """

    # While sending the modified list of servers, it is imperative to send
    # ntp_enable property in the request.
    # Hence, query the MO and reassign the same value to ntp_enable
    mo = _get_mo(handle, dn=NTP_DN)
    mo.ntp_enable = mo.ntp_enable
    _set_ntp_servers(mo, ntp_servers)

    handle.set_mo(mo)
    return handle.query_dn(mo.dn)
Ejemplo n.º 4
0
def ssh_enable(handle, port=None, session_timeout=None, **kwargs):
    """
       Enables ssh Policy and sets the given properties

       Args:
           handle (ImcHandle)
           port (int): Port number used by SSH
           session_timeout (int): No of seconds to wait before the system considers a SSH request to have timed out
           kwargs: key-value paired arguments for future use

       Returns:
           CommSsh object

       Raises:
           ImcOperationError if the CommSsh Mo is not present

       Example:
           ssh_enable(handle, 22, 120)
       """
    from imcsdk.mometa.comm.CommSsh import CommSshConsts

    mo = _get_mo(handle, dn=_SSH_DN)
    params = {
        'admin_state': CommSshConsts.ADMIN_STATE_ENABLED,
        'port': str(port) if port else None,
        'session_timeout': str(session_timeout) if session_timeout else None
    }
    mo.set_prop_multiple(**params)
    mo.set_prop_multiple(**kwargs)
    handle.set_mo(mo)
    return mo
Ejemplo n.º 5
0
def ntp_enable(handle, ntp_servers=[]):
    """
    Enables NTP and configures the NTP servers provided

    Args:
        handle (ImcHandle)
        ntp_servers (list): List of dictionaries in the format
                            [{"id": 1, "ip": "192.168.1.1"},
                             {"id": 2, "ip": "192.168.1.2"}]
                            Upto 4 ntp servers can be specified.

    Returns:
        CommNtpProvider object

    Example:
        ntp_enable(handle,
                   ntp_servers = [{"id": 1, "ip": "192.168.1.1"},
                                  {"id": 2, "ip": "192.168.1.2"}]
    """

    log.warning('IPMI Set SEL Time command will disable if NTP is enabled.')
    mo = _get_mo(handle, dn=NTP_DN)
    mo.ntp_enable = "yes"

    _set_ntp_servers(mo, ntp_servers)
    handle.set_mo(mo)
    return handle.query_dn(mo.dn)
Ejemplo n.º 6
0
def snmp_enable(handle,
                port=None,
                community=None,
                com2_sec=None,
                trap_community=None,
                sys_contact=None,
                sys_location=None,
                engine_id_key=None,
                **kwargs):
    """
    Enables SNMP.

    Args:
        handle (ImcHandle)
        port (int): port on which SNMP agent runs
        community (string): community
        com2_sec (string): "disabled", "limited", "full"
        trap_community(string): community to be used when generating traps
        sys_contact (string): sys_contact
        sys_location (string): sys_location
        engine_id_key (string): engine id key
        kwargs: key-value paired arguments for future use

    Returns:
        CommSnmp: Managed object

    Raises:
        ImcOperationError: If CommSnmp Mo is not present

    Example:
        mo = snmp_enable(handle,
                    community="username",
                    sys_contact="user contact",
                    sys_location="user location")
    """
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts

    mo = _get_mo(handle, dn=SNMP_DN)

    # always reset if any of the community, trap_community, engine_id_key
    # is empty string both in CIMC and in modify request.
    _reset(handle, mo, community, trap_community, engine_id_key)

    params = {
        'admin_state': CommSnmpConsts.ADMIN_STATE_ENABLED,
        'port': str(port) if port is not None else None,
        'community': community,
        'com2_sec': com2_sec,
        'trap_community': trap_community,
        'sys_contact': sys_contact,
        'sys_location': sys_location,
        'engine_id_key': engine_id_key
    }

    mo.set_prop_multiple(**params)
    mo.set_prop_multiple(**kwargs)

    log.debug("Configuring SNMP.")
    return _set_snmp(handle, mo)
Ejemplo n.º 7
0
def is_ntp_enabled(handle):
    """
    Check if NTP is enabled
    Args:
        handle (ImcHandle)

    Returns:
        bool
    """

    mo = _get_mo(handle, dn=NTP_DN)
    return (mo.ntp_enable.lower() in ["true", "yes"])
Ejemplo n.º 8
0
def ldap_certificate_management_exists(handle):
    """
    Checks if LDAP certificate management is enabled

    Args:
        handle (ImcHandle)

    Returns:
        bool
    """
    mo = _get_mo(handle, dn="sys/ldap-ext/ldap-ca-cert-mgmt")
    return mo.binding_certificate.lower() == "enabled"
Ejemplo n.º 9
0
def ldap_certificate_management_disable(handle):
    """
    Disables ldap certificate management

    Args:
        handle (ImcHandle)

    Returns:
        LdapCACertificateManagement object
    """
    mo = _get_mo(handle, dn="sys/ldap-ext/ldap-ca-cert-mgmt")
    mo.binding_certificate = "disabled"
    handle.set_mo(mo)
    return mo
Ejemplo n.º 10
0
def is_ldap_enabled(handle):
    """
    Checks if LDAP is enabled

    Args:
        handle (ImcHandle)

    Returns:
        bool

    Examples:
        is_ldap_enabled(handle)
    """

    mo = _get_mo(handle, dn=LDAP_DN)
    return mo.admin_state.lower() == "enabled"
Ejemplo n.º 11
0
def ntp_disable(handle):
    """
    Disables NTP
    Args:
        handle (ImcHandle)

    Returns:
        CommNtpProvider object
    """

    log.warning(
        'Disabling NTP may cause Cisco IMC to lose timesync with server/s')
    mo = _get_mo(handle, dn=NTP_DN)
    mo.ntp_enable = "no"

    handle.set_mo(mo)
    return mo
Ejemplo n.º 12
0
def smtp_disable(handle):
    """
    Disable SMTP Settings

    Args:
        handle (ImcHandle)

    Raises:
        ImcOperationError

    Returns:
         CommMailAlert object
    """
    mo = _get_mo(handle, dn=_SMTP_DN)
    mo.admin_state = 'disabled'
    handle.set_mo(mo)
    return mo
Ejemplo n.º 13
0
def ldap_disable(handle):
    """
    Disables the ldap settings

    Args:
        handle (ImcHandle)

    Returns:
        AaaLdap Managed Object

    Examples:
        ldap_disable(handle)
    """

    mo = _get_mo(handle, dn=LDAP_DN)
    mo.admin_state = "disabled"
    handle.set_mo(mo)
    return mo
Ejemplo n.º 14
0
def adaptor_unit_get(handle, adaptor_slot, server_id=1, **kwargs):
    """
    This method fetches the adaptorUnit Managed Object for the specified
    adaptor Slot on a server.

    Args:
        handle (ImcHandle)
        adaptor_slot (string): PCI slot number of the adaptor
        server_id (int): Server Id for C3260 platforms
        kwargs: key=value paired arguments

    Returns:
        AdaptorUnit object

    Examples:
        adaptor_unit_get(handle, adaptor_slot=1, server_id=1)
    """
    return _get_mo(handle, dn=_get_adaptor_dn(handle, adaptor_slot, server_id))
Ejemplo n.º 15
0
def snmp_user_delete_all(handle):
    """
    delete all snmp users.

    Args:
        handle (ImcHandle)

    Returns:
        None

    Raises:
        ImcOperationError: If user is not present

    Example:
        snmp_user_delete_all(handle)

    """
    from imcsdk.mometa.comm.CommSnmpUser import CommSnmpUserConsts
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts

    api = 'snmp_user_delete_all'
    parent_mo = _get_mo(handle, dn=SNMP_DN)
    if parent_mo.admin_state != CommSnmpConsts.ADMIN_STATE_ENABLED:
        raise ImcOperationError(api, 'SNMP is not enabled.')

    mos = []
    users = _get_snmp_users(handle)
    for user in users:
        if user.name == "":
            continue
        user.admin_action = CommSnmpUserConsts.ADMIN_ACTION_CLEAR
        mos.append(user)

    # Optimize SNMP transaction performance for CIMC version HP(4.0) and above
    # via setting parameter 'config_change' to 'no-commit'
    mos = snmp_multiple_config_with_configcommit_for_hp_and_above(handle, mos)

    response = handle.set_mos(mos)
    if response:
        process_conf_mos_response(response, api)

    # Optimize SNMP transaction performance for CIMC version HP(4.0) and above
    # via doing explicit commit using newly introduced MO 'CommSnmpConfigCommit'
    snmp_commit_explicitly_for_hp_and_above(handle, SNMP_DN)
Ejemplo n.º 16
0
def _reset(handle, local_mo, community, trap_community, engine_id_key):
    '''
    The following issues exist when server in a factory reset condition, and if
    enabling SNMP with any of the community, trap_community, engine_id_key
    property with value as empty string.

    GP, GPMR1:
    CIMC returns an error - "CIMC may be running any critical operation or in
    error state. Retry after sometime or reboot CIMC if necessary"

    GPMR2, HP:
    CIMC does not return error, but SNMP remains disabled.

    Bug Ids - CSCvf87365, CSCvi17984

    This function sets and unsets the above properties if both new and
    existing value of any of these properties is empty string.
    '''

    import random
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts

    input_params = locals()
    mo = _get_mo(handle, dn=SNMP_DN)

    params = {
        "community": "init",
        "trap_community": "init",
        "engine_id_key": str(random.randint(1, 101))
    }

    reset = False
    for prop, val in params.items():
        if getattr(mo, prop) == "" and input_params[prop] == "":
            log.debug("Reset %s." % prop)
            setattr(mo, prop, val)
            reset = True

    if reset:
        log.debug("Initiating reset.")
        mo.admin_state = CommSnmpConsts.ADMIN_STATE_ENABLED
        _set_snmp(handle, mo)
        log.debug("Ending reset.")
Ejemplo n.º 17
0
def ldap_exists(handle, change_password=False, **kwargs):
    """
    Checks if the specified LDAP settings are already applied

    Args:
        handle (ImcHandle)
        kwargs: Key-Value paired arguments

    Returns:
        (True, AaaLdap) if settings match, else (False, None)

    Examples:
        match, mo = ldap_exists(
                    handle, enabled=True,
                    basedn='DC=LAB,DC=cisco,DC=com',
                    domain='LAB.cisco.com',
                    timeout=20, group_auth=True,
                    bind_dn='CN=administrator,CN=Users,DC=LAB,DC=cisco,DC=com',
                    password='******', ldap_servers=ldap_servers)
    """

    mo = _get_mo(handle, dn=LDAP_DN)
    if mo is None:
        return False, None

    if _is_valid_arg('ldap_servers', kwargs):
        if not _check_ldap_server_match(mo, kwargs.pop('ldap_servers')):
            return False, mo

    if 'password' in kwargs and not change_password:
        kwargs.pop('password', None)

    if 'dns_search_domain' in kwargs and kwargs['dns_search_domain'] == "":
        kwargs.pop('dns_search_domain', None)

    if 'dns_search_forest' in kwargs and kwargs['dns_search_forest'] == "":
        kwargs.pop('dns_search_forest', None)

    kwargs['admin_state'] = 'enabled'
    if not mo.check_prop_match(**kwargs):
        return False, mo

    return True, mo
Ejemplo n.º 18
0
def snmp_exists(handle, **kwargs):
    """
    Checks if snmp is enabled or not

    Args:
        handle (ImcHandle)
        kwargs: Key-Value paired arguments relevant to CommSnmp object

    Returns:
        True/false, CommSnmp MO/None

    Example:
        snmp_exists(handle)
    """
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts

    mo = _get_mo(handle, dn=SNMP_DN)
    kwargs['admin_state'] = CommSnmpConsts.ADMIN_STATE_ENABLED
    return mo.check_prop_match(**kwargs), mo
Ejemplo n.º 19
0
def ldap_certificate_delete(handle):
    """
    Deletes the LDAP CA certificate

    Args:
        handle (ImcHandle)
        user (str): Username for the remote server
        pwd (str): Password for the remote server

    Returns:
        LdapCACertificate object

    Examples:
        ldap_certificate_delete(handle)
    """
    mo = _get_mo(handle, dn='sys/ldap-ext/ldap-ca-cert-mgmt/ldap-ca-cert')
    mo.admin_action = 'delete-ca-certificate'
    handle.set_mo(mo)
    return handle.query_dn(mo.dn)
Ejemplo n.º 20
0
def ldap_certificate_binding_check(handle, user=None, pwd=None, **kwargs):
    """
    Tests the LDAP CA certificate binding

    Args:
        handle (ImcHandle)
        user (str): Username for the remote server
        pwd (str): Password for the remote server

    Returns:
        LdapCACertificate object

    Examples:
        ldap_certificate_binding_check(handle, user='******', pwd='pqrs')
    """
    mo = _get_mo(handle, dn='sys/ldap-ext/ldap-ca-cert-mgmt/ldap-ca-cert')
    params = {'user': user, 'pwd': pwd, 'admin_action': 'test-ldap-binding'}
    mo.set_prop_multiple(**params)
    mo.set_prop_multiple(**kwargs)
    handle.set_mo(mo)
    return handle.query_dn(mo.dn)
Ejemplo n.º 21
0
def smtp_exists(handle, **kwargs):
    """
    Check whether the specified SMTP settings already exist

    Args:
        handle (ImcHandle)
        kwargs: key-value paired arguments

    Returns:
        (True, CommMailAlert) if settings match, (False, None) otherwise
    """
    try:
        mo = _get_mo(handle, dn=_SMTP_DN)
    except:
        return False, None

    kwargs['admin_state'] = 'enabled'

    if not mo.check_prop_match(**kwargs):
        return False, mo
    return True, None
Ejemplo n.º 22
0
def ldap_certificate_export(handle,
                            remote_server,
                            remote_file,
                            user=None,
                            pwd=None,
                            protocol='tftp',
                            **kwargs):
    """
    Export the LDAP CA certificate from the Cisco IMC to a remote location

    Args:
        handle (ImcHandle)
        remote_server (str): Remote Server IP or Hostname
        remote_file (str): Remote file path
        user (str): Username for the remote server
        pwd (str): Password for the remote server
        protocol (str): Protocol for downloading the certificate
                        ['tftp', 'ftp', 'http', 'scp', 'sftp']
        kwargs: Key-Value paired arguments for future use

    Returns:
        ExportLdapCACertificate object

    Examples:
        ldap_certificate_export(handle, user='******', pwd='pqrs',
            remote_server='1.1.1.1', remote_file='/tmp/cert', protocol='scp')
    """
    mo = _get_mo(handle,
                 dn='sys/ldap-ext/ldap-ca-cert-mgmt/ldap-ca-cert-export')
    params = {
        'user': user,
        'pwd': pwd,
        'remote_server': remote_server,
        'remote_file': remote_file,
        'protocol': protocol
    }
    mo.set_prop_multiple(**params)
    mo.set_prop_multiple(**kwargs)
    handle.set_mo(mo)
    return handle.query_dn(mo.dn)
Ejemplo n.º 23
0
def smtp_enable(handle, ip_address=None, port=None, min_severity_level=None,
                from_address=None, **kwargs):
    """
    Enables SMTP Policy and sets the given properties

    Args:
        handle (ImcHandle)
        ip_address (str): Ip Address of the SMTP server
        port (int): Port number of the SMTP server
        min_severity_level (str): Minimum fault severity level
            Valid values: "condition", "critical", "major", "minor", "warning"
        from_address(str): Email id that will be displayed as the source in the mail alert
        kwargs: key-value paired arguments for future use

    Returns:
        CommMailAlert object

    Raises:
        ImcOperationError if the severity level is not correct

    Example:
        smtp_enable(handle, '10.105.110.219', 25, 'minor')
    """
    if min_severity_level and not _is_valid_severity_level(min_severity_level):
        raise ImcOperationError(
            'Configure SMTP Policy',
            'Invalid severity level %s ' % min_severity_level)

    mo = _get_mo(handle, dn=_SMTP_DN)
    params = {
        'admin_state': 'enabled',
        'ip_address': ip_address,
        'port': str(port) if port is not None else None,
        'min_severity_level': min_severity_level,
        'from_address': from_address
    }
    mo.set_prop_multiple(**params)
    mo.set_prop_multiple(**kwargs)
    handle.set_mo(mo)
    return mo
Ejemplo n.º 24
0
def ip_blocking_exists(handle, **kwargs):
    """
    Checks if IP blocking settings match according to the parameters specified.

    Args:
        handle (ImcHandle)
        kwargs: Key-Value paired arguments relevant to IpBlocking object

    Returns:
        (True, IpBlocking object) if exists, else (False, None)

    Examples:
        ip_blocking_exists(handle, fail_count='6',
                           fail_window='120', penalty_time='800')
    """
    mo = IpBlocking(parent_mo_or_dn=_get_mgmt_if_dn(handle))
    mo = _get_mo(handle, dn=mo.dn)

    if mo.check_prop_match(**kwargs):
        return (True, mo)

    return (False, None)
Ejemplo n.º 25
0
def snmp_disable(handle):
    """
    Disables SNMP.

    Args:
        handle (ImcHandle)

    Returns:
        CommSnmp: Managed Object

    Raises:
        ValueError: If CommSnmp Mo is not present

    Example:
        snmp_disable(handle)
    """
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts

    mo = _get_mo(handle, dn=SNMP_DN)
    mo.admin_state = CommSnmpConsts.ADMIN_STATE_DISABLED
    handle.set_mo(mo)
    return mo
Ejemplo n.º 26
0
def ssh_exists(handle, **kwargs):
    """
    Checks if ssh is enabled or not

    Args:
        handle (ImcHandle)
        kwargs: Key-Value paired arguments relevant to CommSsh object

    Returns:
        True/false, CommSsh MO/None

    Example:
        ssh_exists(handle)
    """
    from imcsdk.mometa.comm.CommSsh import CommSshConsts

    try:
        mo = _get_mo(handle, dn=_SSH_DN)
    except:
        return False, None

    kwargs['admin_state'] = CommSshConsts.ADMIN_STATE_ENABLED
    return mo.check_prop_match(**kwargs), mo
Ejemplo n.º 27
0
def ldap_enable(handle,
                basedn=None,
                domain=None,
                encryption=None,
                timeout=None,
                user_search_precedence=None,
                bind_method=None,
                bind_dn=None,
                change_password=False,
                password=None,
                filter=None,
                group_attribute=None,
                attribute=None,
                group_nested_search=None,
                group_auth=None,
                ldap_servers=[],
                locate_directory_using_dns=None,
                dns_domain_source=None,
                dns_search_domain=None,
                dns_search_forest=None,
                **kwargs):
    """
    Configures LDAP

    Args:
        handle (ImcHandle)
        basedn (str): Represents the Base Distinguished Name. Describes where
            to load users and groups from. It must be in the 'dc=domain,dc=com'
            format for Active Directory servers.
        domain (str): The domain that all users must be in.
        encryption (str): "Disabled", "Enabled", "disabled", "enabled"
        timeout (int): [0-180] The number of seconds the Cisco IMC waits until
            the LDAP search operation times out.
        user_search_precedence (str): ['local-user-db', 'ldap-user-db'].
            Preference to search in local user db versus ldap user db
        bind_method (str): ['login-credentials', 'configured-credentials',
            'anonymous']
        bind_dn (str): Represents the distinguished name (DN) of the user. This
            field is applicable only for bind_method='configured-credentials'
        change_password (bool): True if you want to change the user password.
        password (str): The password of the user. This field is applicable only
            for bind_method='configured-credentials'
        filter (str): Represents the filter attribute in the schema on the LDAP
            server.
        attribute (str): Represents the role and locale information. Should
            match the attribute specified on the LDAP server.
        group_attribute (str): Represents the group attribute in the schema on
            the LDAP server.
        group_nested_search (int): Represents the depth of a nested group
            search
        group_auth (str): "disabled" or "enabled". Enables authentication at
            the group level for LDAP users that are not found in the local user
            database.
        ldap_servers (list): Represents the list of preconfigured LDAP server.
                             List of dictionaries in the format:-
                             [{"id": 1, "ip": "192.168.1.1", "port": 300},
                              {"id": 2, "ip": "192.168.1.2", "port": 400}]
        locate_directory_using_dns (str): "yes" or "no"
        dns_domain_source (str): Represents the method to obtain domain name.
            ['extracted-domain', 'configured-domain',
            'extracted-configured-domain']
        dns_search_domain: Domain name to be used for DNS query. Disabled when
            domain_name_source='extracted-domain'
        dns_search_forest: Forest name to used for DNS query. Disabled when
            domain_name_source='extracted-domain'
        kwargs: Key-Value paired arguments. Reserved for future use

    Returns:
        AaaLdap object

    Raises:
        ImcOperationError when AaaLdap object doesn't exist

    Examples:
        ldap_configure(handle,
                       basedn='DC=LAB,DC=cisco,DC=com',
                       domain='LAB.cisco.com',
                       timeout=20, group_auth='enabled',
                       bind_dn='CN=administrator,CN=Users,DC=LAB,DC=cisco,
                       DC=com', password='******', ldap_servers=ldap_servers)
    """

    mo = _get_mo(handle, dn=LDAP_DN)

    params = {
        'admin_state':
        'enabled',
        'basedn':
        basedn,
        'domain':
        domain,
        'encryption':
        encryption,
        'timeout':
        str(timeout) if timeout is not None else None,
        'user_search_precedence':
        user_search_precedence,
        'bind_method':
        bind_method,
        'bind_dn':
        bind_dn,
        'password':
        password if change_password else None,
        'filter':
        filter,
        'attribute':
        attribute,
        'group_attribute':
        group_attribute,
        'group_nested_search':
        str(group_nested_search) if group_nested_search else None,
        'group_auth':
        group_auth,
        'locate_directory_using_dns':
        locate_directory_using_dns,
        'dns_domain_source':
        dns_domain_source,
        'dns_search_domain':
        None if dns_search_domain == "" else
        dns_search_domain,  #IMC XML API issue : CSCvg92190
        'dns_search_forest':
        None if dns_search_forest == "" else dns_search_forest
    }

    mo.set_prop_multiple(**params)

    if ldap_servers:
        _set_ldap_servers(mo, ldap_servers)

    mo.set_prop_multiple(**kwargs)
    handle.set_mo(mo)
    return mo
Ejemplo n.º 28
0
def adaptor_set_all(handle, adaptors=None, server_id=1, **kwargs):
    """
    Example:
        adaptor_set_all(handle,
                        adaptors=[
                            {id: 1,
                            lldp: "enabled",
                            fip_mode: "enabled",
                            port_channel_enable: "enabled",
                            vntag_mode: "enabled",
                            admin_action:None}
                            ]
                        )
    """
    from imcsdk.mometa.adaptor.AdaptorGenProfile import AdaptorGenProfile

    api = 'adaptor_set_all'
    api_error_msg = VicConst.ADAPTOR_ERROR_MSG

    if not adaptors:
        log.debug("No adapters present for configuration")
        return

    # fetch adaptors from end point, adaptor_ep_dict is dict {id, adaptor_mo}
    adaptor_ep_dict = _prepare_ep_adaptor_dict(handle, api_error_msg)

    # validate input and checks if adaptor exists at end point
    for adaptor in adaptors:
        id = adaptor.get('id', None)
        if id is None:
            raise ImcOperationError(api_error_msg,
                                    'Provide adapter slot to configure')

        if id not in adaptor_ep_dict:
            raise ImcOperationError(
                api_error_msg, "Adaptor %s is not present at end point." % id)

    # configure adapter
    mos = []

    restart_server = None
    adaptor_list = []

    #adaptors are the configured adaptors in intersight AdaptorConfiguration Policy
    for adaptor in adaptors:
        id = adaptor['id']
        lldp = adaptor.pop('lldp', None)
        fip_mode = adaptor.pop('fip_mode', None)
        port_channel_enable = adaptor.pop('port_channel_enable', None)
        log.debug("Adapter Config Policy - configured Values")
        log.debug("Port Channel: %s, LLDP Mode: %s, Fip Mode: %s",
                  port_channel_enable, lldp, fip_mode)

        # vntag_mode = adaptor.pop('vntag_mode', None)
        # admin_state = adaptor.pop('admin_state', None)

        mo = adaptor_ep_dict[id]
        adaptor_properties = adaptor_properties_get(handle, id, server_id=1)
        adaptor_list.append(adaptor_properties)
        #port_channel_capable  returns None for < Gen4 adapters and False for Gen4+ unsupported portchannel adapters.
        #Hence a check has to be done for both None and False
        #for backward compatibility in deploying Adapter Configuration Policy.
        if adaptor_properties.port_channel_capable == None or adaptor_properties.port_channel_capable == "False":
            log.debug(
                "Port Channel is not supported for the adapter at slot: %s",
                adaptor_properties.pci_slot)
            port_channel_enable = None

        if adaptor_properties.port_channel_capable == "True" and port_channel_enable == "disabled":
            log.debug(
                "Port Channel is disabled by user for adapter at slot %s. Server restart initiated",
                adaptor_properties.pci_slot)
            restart_server = True

        mo.admin_state = AdaptorUnitConsts.ADMIN_STATE_ADAPTOR_RESET_DEFAULT

        if port_channel_enable == "disabled":
            AdaptorGenProfile(parent_mo_or_dn=mo,
                              lldp=lldp,
                              fip_mode=fip_mode,
                              port_channel_enable="disabled",
                              vntag_mode="disabled")
        else:
            #port_channel_enable value is set to enabled by default.
            # Hence, its not required to send the default value.
            AdaptorGenProfile(parent_mo_or_dn=mo,
                              lldp=lldp,
                              fip_mode=fip_mode,
                              vntag_mode="disabled")

        mos.append(mo)

    response = handle.set_mos(mos)
    ret = []
    if response:
        ret.append(_process_response(response, api, api_error_msg))

    ext_ethif_adaptor_mos = []
    for adaptor in adaptors:
        id = adaptor['id']
        ext_ethifs = adaptor.pop('ext_ethifs', None)
        if ext_ethifs:
            mo = adaptor_ep_dict[id]
            ext_ethif_mos = _ext_ethif_set_all(handle, ext_ethifs, mo)
            ext_ethif_adaptor_mos.extend(ext_ethif_mos)

    if len(ext_ethif_adaptor_mos) > 0:
        response = handle.set_mos(ext_ethif_adaptor_mos)
        if response:
            error_msg = VicConst.DCE_IF_ERROR_MSG
            ret.append(_process_response(response, api, error_msg))

    results = {}
    results["changed"] = True
    results["msg"] = ""
    results["msg_params"] = ret

    #Power Cycle Host for the changes to take effect.
    if restart_server:
        log.debug("Restarting server...")
        server_power_cycle(handle, timeout=180)
        _wait_for_power_state(handle,
                              state="on",
                              timeout=60,
                              interval=5,
                              server_id=1)
        log.debug(
            "Server restarted successfully. Adaptor initialisation check in progress."
        )
        for adaptor in adaptor_list:
            adaptor_initialization_in_progress = True
            wait_count = 0
            while adaptor_initialization_in_progress and wait_count < 5:
                try:
                    adaptor = _get_mo(handle, dn=adaptor.dn)
                    adaptor_initialization_in_progress = False
                    log.debug("Adaptor at slot %s initialisation complete.",
                              adaptor.pci_slot)
                except ImcOperationError:
                    log.debug(
                        "Adaptor at slot %s initialisation in progress. Sleep for 5s.",
                        adaptor.pci_slot)
                    wait_count += 1
                    time.sleep(5)
            if adaptor_initialization_in_progress:
                log.debug(
                    "Adaptor initialisation failure for adaptor at slot %s",
                    adaptor.pci_slot)
                raise ImcOperationError(
                    api_error_msg,
                    "Adaptor %s is not initialised at end point." %
                    adaptor.pci_slot)
        log.debug("Sleeping for 1 minute")
        time.sleep(60)
        log.debug("Returning results")
    return results
Ejemplo n.º 29
0
def snmp_trap_add_all(handle, traps=None):
    """
    Adds snmp trap.

    Args:
        handle (ImcHandle)
        traps (list): list of trap dict
          keys:
            hostname (string): ip address
            admin_state (string): enabled, disabled
            version (string): "v2c", "v3"
            notification_type (string): "informs", "traps"
                Required only for version "v2c" and "v3"
            user (string): send traps for a specific user
            port (int): port

    Returns:
        list: List of CommSnmpTrap Managed Object

    Example:
        snmp_trap_add_all(handle,
                          traps=[{hostname: "10.10.10.10",
                                 port: "162",
                                 version:"v2c",
                                 notification_type:"informs"}]
                         )
    """
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts
    from imcsdk.mometa.comm.CommSnmpTrap import CommSnmpTrap
    from imcsdk.mometa.comm.CommSnmpTrap import CommSnmpTrapConsts

    api = 'snmp_trap_add_all'
    parent_mo = _get_mo(handle, dn=SNMP_DN)
    if parent_mo.admin_state != CommSnmpConsts.ADMIN_STATE_ENABLED:
        raise ImcOperationError(api, 'SNMP is not enabled.')

    dn_to_trap_dict = {}
    mos = []
    id = 0
    for trap in traps:
        hostname = trap.pop('hostname', None)
        _validate_api_prop('hostname', hostname, api)

        version = trap.pop('version', None)
        _validate_api_prop('version', version, api, True, [
            CommSnmpTrapConsts.VERSION_V1, CommSnmpTrapConsts.VERSION_V2C,
            CommSnmpTrapConsts.VERSION_V3
        ])

        notification_type = trap.pop('notification_type', None)
        _validate_api_prop('notification_type', notification_type, api, True, [
            CommSnmpTrapConsts.NOTIFICATION_TYPE_INFORMS,
            CommSnmpTrapConsts.NOTIFICATION_TYPE_TRAPS
        ])

        admin_state = trap.pop('admin_state', 'enabled')
        _validate_api_prop('admin_state', admin_state, api, True, [
            CommSnmpTrapConsts.ADMIN_STATE_ENABLED,
            CommSnmpTrapConsts.ADMIN_STATE_DISABLED
        ])

        user = trap.pop('user', None)
        port = trap.pop('port', None)

        if version == CommSnmpTrapConsts.VERSION_V2C and user:
            user = None
        if version == CommSnmpTrapConsts.VERSION_V3:
            notification_type = CommSnmpTrapConsts.NOTIFICATION_TYPE_TRAPS

        params = {
            'hostname': hostname,
            'version': version,
            'notification_type': notification_type,
            'admin_state': admin_state,
            'port': str(port) if port else None,
            'user': user
        }

        id += 1
        mo = CommSnmpTrap(parent_mo_or_dn=parent_mo, id=str(id))
        mo.set_prop_multiple(**params)
        mos.append(mo)
        dn_to_trap_dict[mo.dn] = mo.hostname

    # Optimize SNMP transaction performance for CIMC version HP(4.0) and above
    # via setting parameter 'config_change' to 'no-commit'
    mos = snmp_multiple_config_with_configcommit_for_hp_and_above(handle, mos)

    response = handle.set_mos(mos)
    if response:
        ret = process_conf_mos_response(response, api, False,
                                        'Create SNMP traps failed',
                                        snmp_traps_callback, dn_to_trap_dict)
        if len(ret) != 0:
            error_msg = 'Create/Update SNMP traps failed:\n'
            for item in ret:
                obj = item["Object"]
                error = item["Error"]
                error = sanitize_message(error)
                error_msg += "[Trap " + obj + "] " + error + "\n"

            raise ImcOperationErrorDetail(api, error_msg, ret)

    # Optimize SNMP transaction performance for CIMC version HP(4.0) and above
    # via doing explicit commit using newly introduced MO 'CommSnmpConfigCommit'
    snmp_commit_explicitly_for_hp_and_above(handle, SNMP_DN)

    results = {}
    results["changed"] = True
    results["msg"] = ""
    results["msg_params"] = ret

    return results
Ejemplo n.º 30
0
def snmp_user_add_all(handle, users=None):
    """
    Adds snmp user.

    Args:
        handle (ImcHandle)
        users (list): list of user dict
          keys:
            name (string): snmp username
            security_level (string): "authpriv", "authnopriv", "noauthnopriv"
            auth (string): "MD5", "SHA"
            auth_pwd (string): password
                for existing user
            privacy (string): "AES", "DES"
            privacy_pwd (string): privacy password
                for existing user
          example:
            [{'name': 'snmpuser',
              'security_level': 'authpriv',
              'auth': 'MD5',
              'auth_pwd': 'password',
              'privacy': 'AES',
              'privacy_pwd': 'password'}
            ]

    Returns:
        list: List of CommSnmpUser Managed Object

    Raises:
        ImcOperationError is maximum number of users already configured

    Example:
        snmp_user_add_all( handle,
                    users = [{'name': 'snmpuser',
                            'security_level': 'authpriv',
                            'auth': 'MD5', 'auth_pwd': 'password',
                            'privacy': 'AES', 'privacy_pwd': 'password'])
    """
    from imcsdk.mometa.comm.CommSnmpUser import CommSnmpUser
    from imcsdk.mometa.comm.CommSnmpUser import CommSnmpUserConsts
    from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts

    api = 'snmp_user_add_all'
    parent_mo = _get_mo(handle, dn=SNMP_DN)
    if parent_mo.admin_state != CommSnmpConsts.ADMIN_STATE_ENABLED:
        raise ImcOperationError(api, 'SNMP is not enabled.')

    dn_to_user_dict = {}
    mos = []
    id = 0
    for user in users:
        name = user.pop('name', None)
        security_level = user.pop('security_level', None)
        _validate_api_prop('name', name, api)
        _validate_api_prop('security_level', security_level, api)

        auth = user.pop('auth', None)
        auth_pwd = user.pop('auth_pwd', None)
        privacy = user.pop('privacy', None)
        privacy_pwd = user.pop('privacy_pwd', None)

        params = {'name': name, 'security_level': security_level}

        if security_level == CommSnmpUserConsts.SECURITY_LEVEL_AUTHNOPRIV:
            _validate_api_prop('auth_pwd', auth_pwd, api)
            params['auth'] = auth
            params['auth_pwd'] = auth_pwd
        elif security_level == CommSnmpUserConsts.SECURITY_LEVEL_AUTHPRIV:
            _validate_api_prop('auth', auth, api, True, ['MD5', 'SHA'])
            _validate_api_prop('auth_pwd', auth_pwd, api)
            _validate_api_prop('privacy', privacy, api, True, ['AES', 'DES'])
            _validate_api_prop('privacy_pwd', privacy_pwd, api)
            params['auth'] = auth
            params['auth_pwd'] = auth_pwd
            params['privacy'] = privacy
            params['privacy_pwd'] = privacy_pwd

        id += 1
        mo = CommSnmpUser(parent_mo_or_dn=parent_mo, id=str(id))
        mo.set_prop_multiple(**params)
        mos.append(mo)
        dn_to_user_dict[mo.dn] = mo.name

    # Optimize SNMP transaction performance for CIMC version HP(4.0) and above
    # via setting parameter 'config_change' to 'no-commit'
    mos = snmp_multiple_config_with_configcommit_for_hp_and_above(handle, mos)

    response = handle.set_mos(mos)
    if response:
        ret = process_conf_mos_response(response, api, False,
                                        'Create SNMP users failed',
                                        snmp_users_callback, dn_to_user_dict)
        if len(ret) != 0:
            error_msg = 'Create/Update SNMP users failed:\n'
            for item in ret:
                obj = item["Object"]
                error = item["Error"]
                error = sanitize_message(error)
                error_msg += "[User " + obj + "] " + error + "\n"

            raise ImcOperationErrorDetail(api, error_msg, ret)

    # Optimize SNMP transaction performance for CIMC version HP(4.0) and above
    # via doing explicit commit using newly introduced MO 'CommSnmpConfigCommit'
    snmp_commit_explicitly_for_hp_and_above(handle, SNMP_DN)

    results = {}
    results["changed"] = True
    results["msg"] = ""
    results["msg_params"] = ret

    return results