示例#1
0
def build_client(module):
    """Build a DRAC client instance.

    :param module: The AnsibleModule instance
    :returns: dracclient.client.DRACClient instance
    """
    return drac.DRACClient(module.params['address'], module.params['username'],
                           module.params['password'])
示例#2
0
    def calculate_hostos_cpus(self, number_of_host_os_cpu):
        try:
            global HOST_OS_CPUS, VCPUS, TOTAL_CPUS
            cpu_count_list = []
            for node in ConfigOvercloud.nodes:
                # for every compute node get the corresponding drac credentials
                # to fetch the cpu details
                node_uuid = node.uuid
                node_details = ConfigOvercloud.ironic_client.node.get(
                    node_uuid)
                node_type = node_details.properties['capabilities'].split(
                    ',')[0].split(':')[1]
                if 'compute' not in node_type:
                    # filter for getting compute node
                    continue
                drac_ip, drac_user, drac_password = \
                    ConfigOvercloud.get_drac_credential.get_drac_creds(
                        ConfigOvercloud.ironic_client, node_uuid)
                stor = client.DRACClient(drac_ip, drac_user, drac_password)
                # cpu socket information for every compute node
                sockets = stor.list_cpus()
                cpu_count = 0
                for socket in sockets:
                    if socket.ht_enabled:
                        cpu_count += socket.cores * 2
                    else:
                        raise Exception("Hyperthreading is not enabled in " +
                                        str(node_uuid))
                cpu_count_list.append(cpu_count)

            min_cpu_count = min(cpu_count_list)
            if min_cpu_count not in [40, 48, 56, 64, 72, 128]:
                raise Exception("The number of vCPUs, as specified in the"
                                " reference architecture, must be one of"
                                " [40, 48, 56, 64, 72, 128]"
                                " but number of vCPUs are " +
                                str(min_cpu_count))
            number_of_host_os_cpu = int(number_of_host_os_cpu)
            logger.info("host_os_cpus {}".format(
                cpu_siblings.sibling_info[min_cpu_count][number_of_host_os_cpu]
                ["host_os_cpu"]))
            logger.info(
                "vcpus {}".format(cpu_siblings.sibling_info[min_cpu_count]
                                  [number_of_host_os_cpu]["vcpu_pin_set"]))
            siblings_info = cpu_siblings.sibling_info[min_cpu_count][
                number_of_host_os_cpu]
            HOST_OS_CPUS = siblings_info["host_os_cpu"]
            VCPUS = siblings_info["vcpu_pin_set"]
            TOTAL_CPUS = min_cpu_count
        except Exception as error:
            message = "Exception {}: {}".format(
                type(error).__name__, str(error))
            raise Exception("Failed to calculate "
                            "Numa Vcpu list {}".format(message))
示例#3
0
 def check_ht_status(self, node):
     drac_ip, drac_user, drac_password = \
         CredentialHelper.get_drac_creds(self.ironic, node)
     stor = drac_client.DRACClient(drac_ip, drac_user, drac_password)
     # cpu socket information for every compute node
     sockets = stor.list_cpus()
     for socket in sockets:
         if not socket.ht_enabled:
             raise Exception("Hyperthreading is not enabled in " +
                             str(node))
     print "Hyperthreading enabled on %s" % node
     return True
示例#4
0
 def check_ht_status(self, node,
                     instackenv_file=Constants.INSTACKENV_FILENAME):
     drac_ip, drac_user, drac_password = \
         CredentialHelper.get_drac_creds(self.ironic, node, instackenv_file)
     stor = drac_client.DRACClient(drac_ip, drac_user, drac_password)
     # cpu socket information for every compute node
     sockets = stor.list_cpus()
     for socket in sockets:
         if not socket.ht_enabled:
             raise Exception("Hyperthreading is not enabled in "
                             + str(node))
     logger.debug("Hyperthreading enabled on %s" % node)
     return True
示例#5
0
def main():
    parser = argparse.ArgumentParser(
        description="Queries an iDRAC to determine if it is ready to process "
        "commands.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    ArgHelper.add_ip_service_tag(parser)
    ArgHelper.add_instack_arg(parser)
    LoggingHelper.add_argument(parser)

    args = parser.parse_args()

    LoggingHelper.configure_logging(args.logging_level)

    ip_service_tag = args.ip_service_tag
    node_definition = args.node_definition

    return_code = 0

    try:
        node = CredentialHelper.get_node_from_instack(ip_service_tag,
                                                      node_definition)
        if not node:
            raise ValueError("Unable to find {} in {}".format(
                ip_service_tag, node_definition))
        drac_ip = node["pm_addr"]
        drac_user = node["pm_user"]
        drac_password = node["pm_password"]

        drac_client = client.DRACClient(drac_ip, drac_user, drac_password)

        ready = drac_client.is_idrac_ready()

        if ready:
            LOG.info("iDRAC is ready")
        else:
            return_code = 1
            LOG.info("iDRAC is NOT ready")
    except:  # noqa: E501
        LOG.exception("An exception occurred:")
        return_code = 2

    sys.exit(return_code)
示例#6
0
import os
import subprocess
from dracclient import client
import logging
import urllib3
import datetime

urllib3.disable_warnings()

logging.basicConfig(filename='/home/ubuntu/onoff.log', level=logging.INFO)
six_ten = 'ip'
seven_ten = 'ip'
sixten = client.DRACClient(six_ten, 'user', 'password')
seventen = client.DRACClient(seven_ten, 'user', 'password')


def check_server(server):
    test = server.get_power_state()
    if test == 'POWER_ON':
        logging.info("Servers are powered on")
        return True
    elif test == 'POWER_OFF':
        logging.info("Servers are powered off")
        return False


current_hour = datetime.datetime.now().hour
current_min = datetime.datetime.now().minute
logging.info("The Time is " + str(current_hour) + ":" + str(current_min))
if current_hour == 0 and current_min == 30:
    if check_server(sixten) == True:
示例#7
0
def config_idrac(instack_lock,
                 ip_service_tag,
                 node_definition=Constants.INSTACKENV_FILENAME,
                 model_properties=Constants.MODEL_PROPERTIES_FILENAME,
                 pxe_nic=None,
                 password=None,
                 skip_nic_config=False):
    node = CredentialHelper.get_node_from_instack(ip_service_tag,
                                                  node_definition)
    if not node:
        raise ValueError("Unable to find {} in {}".format(
            ip_service_tag, node_definition))
    drac_ip = node["pm_addr"]
    drac_user = node["pm_user"]
    drac_password = node["pm_password"]
    ironic_driver = node["pm_type"]

    if ironic_driver != "pxe_drac":
        LOG.info("{} is using the {} driver.  No iDRAC configuration is "
                 "possible.".format(ip_service_tag, ironic_driver))

        if pxe_nic:
            LOG.warn("Ignoring specified PXE NIC ({})".format(pxe_nic))

        if password:
            LOG.warn("Ignoring specified password")

        return

    drac_client = client.DRACClient(drac_ip, drac_user, drac_password)

    reset_idrac(drac_client, ip_service_tag)

    # Clear out any pending jobs in the job queue and fix the condition where
    # there are no pending jobs, but the iDRAC thinks there are
    clear_job_queue(drac_client, ip_service_tag)
    if skip_nic_config:
        target_boot_mode = BootModeHelper.get_boot_mode(drac_client)
    elif BootModeHelper.is_boot_order_flexibly_programmable(drac_client):
        target_boot_mode = boot_mode_helper.DRAC_BOOT_MODE_UEFI
    else:
        target_boot_mode = boot_mode_helper.DRAC_BOOT_MODE_BIOS

    config_boot_mode(drac_client, ip_service_tag, node, target_boot_mode)

    job_ids = list()
    reboot_required = False

    pxe_nic_fqdd = get_pxe_nic_fqdd(pxe_nic, model_properties, drac_client)

    if skip_nic_config:
        provisioning_mac = get_nic_mac_address(drac_client, pxe_nic_fqdd)
        LOG.info("Skipping NIC configuration")
    else:
        # Configure the NIC port to PXE boot or not
        reboot_required_nic, nic_job_ids, provisioning_mac = \
            configure_nics_boot_settings(drac_client,
                                         ip_service_tag,
                                         pxe_nic_fqdd,
                                         node,
                                         target_boot_mode)

        reboot_required = reboot_required or reboot_required_nic
        if nic_job_ids:
            job_ids.extend(nic_job_ids)

    # Do initial idrac configuration
    reboot_required_idrac, idrac_job_id = config_idrac_settings(
        drac_client, ip_service_tag, password, node)
    reboot_required = reboot_required or reboot_required_idrac
    if idrac_job_id:
        job_ids.append(idrac_job_id)

    # If we need to reboot, then add a job for it
    if reboot_required:
        LOG.info("Rebooting {} to apply configuration".format(ip_service_tag))

        job_id = drac_client.create_reboot_job()
        job_ids.append(job_id)

    success = True
    if job_ids:
        drac_client.schedule_job_execution(job_ids, start_time='TIME_NOW')

        LOG.info("Waiting for iDRAC configuration to complete on {}".format(
            ip_service_tag))
        LOG.info("Do not unplug {}".format(ip_service_tag))

        # If the user set the password, then we need to change creds
        if password:
            new_drac_client = client.DRACClient(drac_ip, drac_user, password)

            # Try every 10 seconds over 2 minutes to connect with the new creds
            password_changed = False
            retries = 12
            while not password_changed and retries > 0:
                try:
                    LOG.debug("Attempting to access the iDRAC on {} with the "
                              "new password".format(ip_service_tag))
                    new_drac_client.is_idrac_ready()
                    password_changed = True
                except exceptions.WSManInvalidResponse as ex:
                    if "unauthorized" in ex.message.lower():
                        LOG.debug(
                            "Got an unauthorized exception on {}, so "
                            "sleeping and trying again".format(ip_service_tag))
                        retries -= 1
                        if retries > 0:
                            sleep(10)
                    else:
                        raise

            # If the new creds were successful then use them.  If they were not
            # successful then assume the attempt to change the password failed
            # and stick with the original creds
            if password_changed:
                LOG.debug(
                    "Successfully changed the password on {}.  "
                    "Switching to the new password".format(ip_service_tag))
                drac_client = new_drac_client
            else:
                success = False
                LOG.warn("Failed to change the password on {}".format(
                    ip_service_tag))

        all_jobs_succeeded = wait_for_jobs_to_complete(job_ids, drac_client,
                                                       ip_service_tag)

        if not all_jobs_succeeded:
            success = False

    if success and target_boot_mode == boot_mode_helper.DRAC_BOOT_MODE_BIOS:
        success = config_hard_disk_drive_boot_sequence(drac_client,
                                                       ip_service_tag)

    # We always want to update the password for the node in the instack file
    # if the user requested a password change and the iDRAC config job was
    # successful regardless of if the other jobs succeeded or not.
    new_password = None
    if password:
        job_status = drac_client.get_job(idrac_job_id).status

        if JobHelper.job_succeeded(job_status):
            new_password = password

    if new_password is not None or \
        "provisioning_mac" not in node or \
        ("provisioning_mac" in node and
         node["provisioning_mac"] != provisioning_mac):

        # Synchronize to prevent thread collisions while saving the instack
        # file
        if instack_lock is not None:
            LOG.debug("Acquiring the lock")
            instack_lock.acquire()
        try:
            if instack_lock is not None:
                LOG.debug("Clearing and reloading instack")
                # Force a reload of the instack file
                CredentialHelper.clear_instack_cache()
                node = CredentialHelper.get_node_from_instack(
                    ip_service_tag, node_definition)
            if new_password is not None:
                node["pm_password"] = new_password

            node["provisioning_mac"] = provisioning_mac

            LOG.debug("Saving instack")
            CredentialHelper.save_instack(node_definition)
        finally:
            if instack_lock is not None:
                LOG.debug("Releasing the lock")
                instack_lock.release()

    if success:
        LOG.info("Completed configuration of the iDRAC on {}".format(
            ip_service_tag))
    else:
        raise RuntimeError("An error occurred while configuring the iDRAC "
                           "on {}".format(drac_ip))
示例#8
0
def scan_one(scan_info):
    LOG.set_idrac_ip_address(scan_info.ip_address)

    # Create client for managing a server's resources through its iDRAC.
    # It interacts with the iDRAC using the Distributed Management Task
    # Force, Inc.'s (DMTF) Web Services for Management (WS-Man)
    # protocol. See the DMTF's "Web Services for Management
    # (WS-Management) Specification"
    # (http://www.dmtf.org/sites/default/files/standards/documents/DSP0226_1.2.0.pdf).
    drac_client = client.DRACClient(scan_info.ip_address,
                                                  scan_info.user_name,
                                                  scan_info.password)

    # Initialize the values of the attributes.
    pm_address = scan_info.ip_address
    pm_password = scan_info.password
    pm_type = OSPD_NODE_TEMPLATE_VALUE_PM_TYPE_PXE_IDRAC
    pm_user = scan_info.user_name
    model = ''
    service_tag = ''

    try:
        # Determine if the IP address is a WS-Man endpoint and an iDRAC.
        # If it is not, return None so that no entry is created for it
        # in the node definition template.
        if not is_idrac(drac_client):
            LOG.info('IP address is not an iDRAC')
            return None

        model = drac_client.get_system().model
        service_tag = drac_client.get_system().service_tag
    except dracclient.exceptions.WSManInvalidResponse:
        # Most likely the user credentials are unauthorized.

        # Log an error level message, along with the exception, because
        # this is something that should be addressed and infrequently
        # encountered.
        LOG.exception('Could not determine if IP address is an iDRAC')

        # Create an entry in the node definition template for this IP
        # address that provides information about what needs to be
        # fixed.
        pm_user += ' '
        pm_user += OSPD_NODE_TEMPLATE_VALUE_USER_INTERVENTION_REQUIRED

        pm_password += ' '
        pm_password += OSPD_NODE_TEMPLATE_VALUE_USER_INTERVENTION_REQUIRED
    except Exception:
        # Handle all other exceptions so that the remaining addresses
        # can be scanned.

        # Log an error level message, along with the exception, because
        # this is something that should be addressed and infrequently
        # encountered.
        LOG.exception('Unexpected exception encountered while determining if'
                      ' IP address is an iDRAC')

        # Create an entry in the node definition template for this IP
        # address that provides information about what needs to be
        # fixed.
        pm_address += ' '
        pm_address += OSPD_NODE_TEMPLATE_VALUE_USER_INTERVENTION_REQUIRED

    kwargs = {
        OSPD_NODE_TEMPLATE_ATTRIBUTE_PM_ADDR: pm_address,
        OSPD_NODE_TEMPLATE_ATTRIBUTE_PM_PASSWORD: pm_password,
        OSPD_NODE_TEMPLATE_ATTRIBUTE_PM_TYPE: pm_type,
        OSPD_NODE_TEMPLATE_ATTRIBUTE_PM_USER: pm_user,
        NODE_TEMPLATE_ATTRIBUTE_MODEL: model,
        NODE_TEMPLATE_ATTRIBUTE_SERVICE_TAG: service_tag
    }
    return NodeInfo(**kwargs)
示例#9
0
from dracclient import client
import urllib3
urllib3.disable_warnings()

sixten = client.DRACClient('ip', 'user', 'password')
seventen = client.DRACClient('ip', 'user', 'password')

print("Turning on Servers")
sixten.set_power_state("POWER_ON")
seventen.set_power_state("POWER_ON")