Esempio n. 1
0
    def _set_boot_device(self, task, node, device, persistent=False):
        """Set the boot device for a node.

        :param task: a TaskManager instance.
        :param node: The Node.
        :param device: Boot device. One of [net, network, pxe, hd, cd,
            cdrom, dvd, floppy, default, setup, f1]
        :param persistent: Whether to set next-boot, or make the change
            permanent. Default: False.
        :raises: InvalidParameterValue if an invalid boot device is specified
                 or required ipmi credentials are missing.
        :raises: IPMIFailure when the native ipmi call fails.
        """

        if device not in ipmi_command.boot_devices:
            raise exception.InvalidParameterValue(
                _("Invalid boot device %s specified.") % device)
        driver_info = _parse_driver_info(node)
        try:
            ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                                           userid=driver_info['username'],
                                           password=driver_info['password'])
            ipmicmd.set_bootdev(device)
        except pyghmi_exception.IpmiException as e:
            LOG.warning(
                _("IPMI set boot device failed for node %(node_id)s "
                  "with the following error: %(error)s") % {
                      'node_id': driver_info['uuid'],
                      'error': str(e)
                  })
            raise exception.IPMIFailure(cmd=str(e))
Esempio n. 2
0
 def handle_power(self, ip, is_ipmi=False):
     if is_ipmi:
         bmc = ip
     else:
         a = ip.split(".")
         last_ = [str(int(a[-1]) + 100)]
         bmc = ".".join(a[:3] + last_)
     print_normal(
         "[ IPMIINFO ] ipmiip: {}, ipmiuser: {}, ipmipwd: {}".format(
             bmc, self._user, self._pwd))
     try:
         ipmicmd = ipmi_command.Command(bmc=bmc,
                                        userid=self._user,
                                        password=self._pwd)
     except Exception:
         print_error("[ ERROR ] failed: not connect")
         return
     if self._get_power:
         try:
             ret = ipmicmd.get_power()
         except Exception as e:
             print_error("[ ERROR ] failed: {}".format(e))
         else:
             print_ok("[ OK ] power is {}".format(
                 ret.get("powerstate", "unknow")))
     else:
         try:
             ret = ipmicmd.set_power(self._action, wait=5)
         except Exception as e:
             print_error("[ ERROR ] failed: {}".format(e))
         else:
             status = ret.get("powerstate") if ret.get(
                 "powerstate") else ret.get("pendingpowerstate")
             print_ok("[ OK ] power is {}".format(status, "unknow"))
Esempio n. 3
0
def start_ipmi_chassis_uid_control(bmc_ip,
                                   bmc_username,
                                   bmc_password,
                                   uid_status,
                                   uid_duration=None):
    ipmi_chassis_uid_control_data = dict()
    ipmi_chassis_uid_control_data['action'] = 'IPMI - UID Control'

    try:
        connection_object = command.Command(bmc=bmc_ip,
                                            userid=bmc_username,
                                            password=bmc_password)
        if connection_object:
            cmd_results = connection_object.set_identify(on=uid_status,
                                                         duration=uid_duration)

            # The results are always None, so let's expect its none for success too
            if cmd_results is None:
                ipmi_chassis_uid_control_data[
                    'status'] = json_output_success_string
                ipmi_chassis_uid_control_data['data'] = cmd_results

        else:
            ipmi_chassis_uid_control_data['status'] = json_output_failed_string
            ipmi_chassis_uid_control_data[
                'data'] = json_ipmi_failed_connecting_string

        return json.dumps(ipmi_chassis_uid_control_data)

    except Exception as e:
        ipmi_chassis_uid_control_data['status'] = json_output_error_string
        ipmi_chassis_uid_control_data['data'] = "{}".format(e)
        return json.dumps(ipmi_chassis_uid_control_data)
Esempio n. 4
0
def _power_off(driver_info):
    """Turn the power off for this node.

    :param driver_info: the bmc access info for a node.
    :returns: power state POWER_OFF, one of :class:`ironic.common.states`.
    :raises: IPMIFailure when the native ipmi call fails.
    :raises: PowerStateFailure when invalid power state is returned
             from ipmi.
    """

    msg = _("IPMI power off failed for node %(node_id)s with the "
            "following error: %(error)s")
    try:
        ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                                       userid=driver_info['username'],
                                       password=driver_info['password'])
        wait = CONF.ipmi.retry_timeout
        ret = ipmicmd.set_power('off', wait)
    except pyghmi_exception.IpmiException as e:
        error = msg % {'node_id': driver_info['uuid'], 'error': e}
        LOG.error(error)
        raise exception.IPMIFailure(error)

    state = ret.get('powerstate')
    if state == 'off':
        return states.POWER_OFF
    else:
        error = _("bad response: %s") % ret
        LOG.error(msg, {'node_id': driver_info['uuid'], 'error': error})
        raise exception.PowerStateFailure(pstate=states.POWER_OFF)
Esempio n. 5
0
 def open(self) -> None:
     self._logger.debug("Connecting to %s:623 (User: %s, Privlevel: 2)",
                        self._address, self._username)
     self._command = ipmi_cmd.Command(bmc=self._address,
                                      userid=self._username,
                                      password=self._password,
                                      privlevel=2)
Esempio n. 6
0
def _power_status(driver_info):
    """Get the power status for this node.

    :param driver_info: the bmc access info for a node.
    :returns: power state POWER_ON, POWER_OFF or ERROR defined in
             :class:`ironic.common.states`.
    :raises: IPMIFailure when the native ipmi call fails.
    """

    try:
        ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                           userid=driver_info['username'],
                           password=driver_info['password'])
        ret = ipmicmd.get_power()
    except pyghmi_exception.IpmiException as e:
        LOG.warning(_LW("IPMI get power state failed for node %(node_id)s "
                        "with the following error: %(error)s"),
                    {'node_id': driver_info['uuid'], 'error': str(e)})
        raise exception.IPMIFailure(cmd=str(e))

    state = ret.get('powerstate')
    if state == 'on':
        return states.POWER_ON
    elif state == 'off':
        return states.POWER_OFF
    else:
        # NOTE(linggao): Do not throw an exception here because it might
        # return other valid values. It is up to the caller to decide
        # what to do.
        LOG.warning(_LW("IPMI get power state for node %(node_id)s returns the"
                        " following details: %(detail)s"),
                    {'node_id': driver_info['uuid'], 'detail': ret})
        return states.ERROR
Esempio n. 7
0
def _reboot(driver_info):
    """Reboot this node.

    If the power is off, turn it on. If the power is on, reset it.

    :param driver_info: the bmc access info for a node.
    :returns: power state POWER_ON, one of :class:`ironic.common.states`.
    :raises: IPMIFailure when the native ipmi call fails.
    :raises: PowerStateFailure when invalid power state is returned
             from ipmi.
    """

    msg = _LW("IPMI power reboot failed for node %(node_id)s with the "
              "following error: %(error)s")
    try:
        ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                           userid=driver_info['username'],
                           password=driver_info['password'])
        wait = CONF.ipmi.retry_timeout
        ret = ipmicmd.set_power('boot', wait)
    except pyghmi_exception.IpmiException as e:
        LOG.warning(msg % {'node_id': driver_info['uuid'], 'error': str(e)})
        raise exception.IPMIFailure(cmd=str(e))

    state = ret.get('powerstate')
    if state == 'on':
        return states.POWER_ON
    else:
        LOG.warning(msg % {'node_id': driver_info['uuid'], 'error': ret})
        raise exception.PowerStateFailure(pstate=state)
Esempio n. 8
0
 def main(self):
     print colors.bold | "[ IPMIINFO ] ipmiip: {}, ipmiuser: {}, ipmipwd: {}".format(
         self._bmc, self._user, self._pwd)
     try:
         ipmicmd = ipmi_command.Command(bmc=self._bmc,
                                        userid=self._user,
                                        password=self._pwd)
     except Exception:
         print colors.warn | "[ ERROR ] failed: not connect"
         return
     if self.get_power:
         try:
             ret = ipmicmd.get_power()
         except Exception as e:
             print colors.warn | "[ ERROR ] failed: {}".format(e)
         else:
             print colors.green | "[ OK ] power is {}".format(
                 ret.get("powerstate", "unknow"))
     else:
         try:
             ret = ipmicmd.set_power(self._action, wait=10)
         except Exception as e:
             print colors.warn | "[ ERROR ] failed: {}".format(e)
         else:
             status = ret.get("powerstate") if ret.get(
                 "powerstate") else ret.get("pendingpowerstate")
             print colors.green | "[ OK ] power is {}".format(
                 status, "unknow")
Esempio n. 9
0
def start_ipmi_chassis_power_control(bmc_ip, bmc_username, bmc_password, power_status):
    ipmi_chassis_power_on_data = dict()
    ipmi_chassis_power_on_data['action'] = 'IPMI - Chassis Control'

    try:
        connection_object = command.Command(bmc=bmc_ip, userid=bmc_username, password=bmc_password)
        if connection_object:
            cmd_results = connection_object.set_power(power_status)

            if cmd_results and "error" not in cmd_results:
                ipmi_chassis_power_on_data['status'] = json_output_success_string
                ipmi_chassis_power_on_data['data'] = cmd_results

            # Return the error string if found in the results
            elif "error" in cmd_results:
                ipmi_chassis_power_on_data['status'] = json_output_failed_string
                ipmi_chassis_power_on_data['data'] = cmd_results

            else:
                ipmi_chassis_power_on_data['status'] = json_output_failed_string
                ipmi_chassis_power_on_data['data'] = json_ipmi_chassis_power_failed_string

        else:
            ipmi_chassis_power_on_data['status'] = json_output_failed_string
            ipmi_chassis_power_on_data['data'] = json_ipmi_failed_connecting_string

        return json.dumps(ipmi_chassis_power_on_data)

    except Exception as e:
        ipmi_chassis_power_on_data['status'] = json_output_error_string
        ipmi_chassis_power_on_data['data'] = "{}".format(e)
        return json.dumps(ipmi_chassis_power_on_data)
Esempio n. 10
0
def main():
    '''
    Main function
    '''
    args = get_args()

    if args['bootdev'] and args['power']:
        try:
            ipmicmd = command.Command(bmc=args['bmc'],
                                      userid=args['username'],
                                      password=args['password'])
        except gaierror:
            sys.exit('Unable to resolve provided BMC name')
        except pyghmi.exceptions.IpmiException:
            sys.exit('Invalid username or password')
        if args['power'] in ['on', 'reset', 'boot']:
            powerstate = 'on'
        elif args['power'] == 'status':
            power = get_power(ipmicmd)
            sys.exit('Power state: %s' % power)
        else:
            powerstate = 'off'
        bootdev = set_bootdev(ipmicmd, args['bootdev'])
        power = set_power(ipmicmd, args['power'])
        if not (bootdev == args['bootdev'] and power == powerstate):
            sys.exit(
                'There was an error configuring the BMC. Please check connection and try again'
            )
        else:
            print('BMC configured successfully')
            sys.exit()
def start_ipmi_network_eth0info_macaddress(bmc_ip, bmc_username, bmc_password):
    ipmi_network_eth0info_macaddress_data = dict()
    ipmi_network_eth0info_macaddress_data['action'] = 'IPMI - eth0 Network Mac Address'

    try:
        connection_object = command.Command(bmc=bmc_ip, userid=bmc_username, password=bmc_password)

        if connection_object:
            cmd_results = connection_object.raw_command(netfn=0x30, command=0x21, delay_xmit=None, retry=True,
                                                        timeout=None)

            if cmd_results and "error" not in cmd_results:
                mac_address = '{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}:{6:02x}:{7:02x}:{8:02x}:{9:02x}'.format(
                    *bytearray(cmd_results['data']))[12:]
                ipmi_network_eth0info_macaddress_data['status'] = json_output_success_string
                ipmi_network_eth0info_macaddress_data['data'] = mac_address

            # Return the error string if found in the results
            elif "error" in cmd_results:
                ipmi_network_eth0info_macaddress_data['status'] = json_output_failed_string
                ipmi_network_eth0info_macaddress_data['data'] = cmd_results

            else:
                ipmi_network_eth0info_macaddress_data['status'] = json_output_failed_string
                ipmi_network_eth0info_macaddress_data['data'] = json_ipmi_network_failed_string
        else:
            ipmi_network_eth0info_macaddress_data['status'] = json_output_failed_string
            ipmi_network_eth0info_macaddress_data['data'] = json_ipmi_failed_connecting_string

        return json.dumps(ipmi_network_eth0info_macaddress_data)

    except Exception as e:
        ipmi_network_eth0info_macaddress_data['status'] = json_output_error_string
        ipmi_network_eth0info_macaddress_data['data'] = "{}".format(e)
        return json.dumps(ipmi_network_eth0info_macaddress_data)
Esempio n. 12
0
    def set_boot_device(self, task, device, persistent=False):
        """Set the boot device for the task's node.

        Set the boot device to use on next reboot of the node.

        :param task: a task from TaskManager.
        :param device: the boot device, one of
                       :mod:`ironic.common.boot_devices`.
        :param persistent: Boolean value. True if the boot device will
                           persist to all future boots, False if not.
                           Default: False.
        :raises: InvalidParameterValue if an invalid boot device is specified
                 or required ipmi credentials are missing.
        :raises: MissingParameterValue when required ipmi credentials
                 are missing.
        :raises: IPMIFailure on an error from pyghmi.
        """
        if device not in self.get_supported_boot_devices():
            raise exception.InvalidParameterValue(_(
                "Invalid boot device %s specified.") % device)
        driver_info = _parse_driver_info(task.node)
        try:
            ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                               userid=driver_info['username'],
                               password=driver_info['password'])
            bootdev = _BOOT_DEVICES_MAP[device]
            ipmicmd.set_bootdev(bootdev, persist=persistent)
        except pyghmi_exception.IpmiException as e:
            LOG.error(_LE("IPMI set boot device failed for node %(node_id)s "
                          "with the following error: %(error)s"),
                      {'node_id': driver_info['uuid'], 'error': e})
            raise exception.IPMIFailure(cmd=e)
Esempio n. 13
0
 def __init__(self, **kwargs):
     config = _get_config(**kwargs)
     self.o = command.Command(bmc=config['api_host'],
                              userid=config['api_user'],
                              password=config['api_pass'],
                              port=config['api_port'],
                              kg=config['api_kg'])
Esempio n. 14
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            port=dict(default=623, type='int'),
            state=dict(required=True,
                       choices=['on', 'off', 'shutdown', 'reset', 'boot']),
            user=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            key=dict(type='str', no_log=True),
            timeout=dict(default=300, type='int'),
        ),
        supports_check_mode=True,
    )

    if command is None:
        module.fail_json(msg=missing_required_lib('pyghmi'),
                         exception=PYGHMI_IMP_ERR)

    name = module.params['name']
    port = module.params['port']
    user = module.params['user']
    password = module.params['password']
    state = module.params['state']
    timeout = module.params['timeout']

    try:
        if module.params['key']:
            key = binascii.unhexlify(module.params['key'])
        else:
            key = None
    except Exception as e:
        module.fail_json(msg="Unable to convert 'key' from hex string.")

    # --- run command ---
    try:
        ipmi_cmd = command.Command(bmc=name,
                                   userid=user,
                                   password=password,
                                   port=port,
                                   kg=key)
        module.debug('ipmi instantiated - name: "%s"' % name)

        current = ipmi_cmd.get_power()
        if current['powerstate'] != state:
            response = {
                'powerstate': state
            } if module.check_mode else ipmi_cmd.set_power(state, wait=timeout)
            changed = True
        else:
            response = current
            changed = False

        if 'error' in response:
            module.fail_json(msg=response['error'])

        module.exit_json(changed=changed, **response)
    except Exception as e:
        module.fail_json(msg=str(e))
Esempio n. 15
0
 def __init__(self, **kwargs):
     #cache_key = api_host + api_user + str(api_port)
     config = _get_config(**kwargs)
     self.o = command.Command(bmc=config['api_host'],
                              userid=config['api_user'],
                              password=config['api_pass'],
                              port=config['api_port'],
                              kg=config['api_key'])
Esempio n. 16
0
 def __init__(self,
              username=None,
              password=None,
              ip_address=None,
              port=BMC_PORT):
     self.o = command.Command(userid=username,
                              password=password,
                              bmc=ip_address,
                              port=port)
Esempio n. 17
0
 def __init__(self, **kwargs):
     config = _get_config(**kwargs)
     self.o = command.Command(
         bmc=config["api_host"],
         userid=config["api_user"],
         password=config["api_pass"],
         port=config["api_port"],
         kg=config["api_kg"],
     )
Esempio n. 18
0
    def get_boot_device(self, task):
        """Get the current boot device for the task's node.

        Returns the current boot device of the node.

        :param task: a task from TaskManager.
        :raises: MissingParameterValue if required IPMI parameters
            are missing.
        :raises: IPMIFailure on an error from pyghmi.
        :returns: a dictionary containing:

            :boot_device: the boot device, one of
                :mod:`ironic.common.boot_devices` or None if it is unknown.
            :persistent: Whether the boot device will persist to all
                future boots or not, None if it is unknown.

        """
        driver_info = task.node.driver_info
        driver_internal_info = task.node.driver_internal_info
        if (driver_info.get('ipmi_force_boot_device', False)
                and driver_internal_info.get('persistent_boot_device')
                and driver_internal_info.get('is_next_boot_persistent', True)):
            return {
                'boot_device': driver_internal_info['persistent_boot_device'],
                'persistent': True
            }

        driver_info = _parse_driver_info(task.node)
        response = {'boot_device': None}

        try:
            ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                                           userid=driver_info['username'],
                                           password=driver_info['password'])
            ret = ipmicmd.get_bootdev()
            # FIXME(lucasagomes): pyghmi doesn't seem to handle errors
            # consistently, for some errors it raises an exception
            # others it just returns a dictionary with the error.
            if 'error' in ret:
                raise pyghmi_exception.IpmiException(ret['error'])
        except pyghmi_exception.IpmiException as e:
            LOG.error(
                _LE("IPMI get boot device failed for node %(node_id)s "
                    "with the following error: %(error)s"), {
                        'node_id': driver_info['uuid'],
                        'error': e
                    })
            raise exception.IPMIFailure(cmd=e)

        response['persistent'] = ret.get('persistent')
        bootdev = ret.get('bootdev')
        if bootdev:
            response['boot_device'] = next(
                (dev for dev, hdev in _BOOT_DEVICES_MAP.items()
                 if hdev == bootdev), None)
        return response
Esempio n. 19
0
    def imm_connect(self, host, username, password):
        try:
            connection = command.Command(bmc=host,
                                         userid=username,
                                         password=password)
        except pyghmi.exceptions.IpmiException:
            raise exc.AuthException

        assert connection is not None
        self.connection = connection
Esempio n. 20
0
    def _create_ipmi_connection(self):
        # Do not use the (custom) ipaddress for the host. Use the management board
        # address instead
        credentials = self._credentials

        self._logger.debug("Connecting to %s:623 (User: %s, Privlevel: 2)" %
                           (self._ipaddress, credentials["username"]))
        return ipmi_cmd.Command(bmc=self._ipaddress,
                                userid=credentials["username"],
                                password=credentials["password"],
                                privlevel=2)
Esempio n. 21
0
 def _command(self, bmc):
     try:
         self.ipmi_cmd = ipmi_command.Command(
             bmc=bmc['ipv4'],
             userid=bmc['userid'],
             password=bmc['password'])
     except pyghmi_exception.IpmiException as exc:
         self.log.error(
             'IPMI \'Command\' failed - Rack: %s - IP: %s, %s' %
             (bmc['rack_id'], bmc['ipv4'], str(exc)))
         sys.exit(1)
Esempio n. 22
0
    def __init__(self, log, inv_file):
        inv = Inventory(log, inv_file)
        for rack_id, ipv4, _userid, _password in inv.yield_ipmi_access_info():
            ipmi_cmd = ipmi_command.Command(bmc=ipv4,
                                            userid=_userid,
                                            password=_password)

            try:
                inv = ipmi_cmd.get_net_configuration(channel=None,
                                                     gateway_macs=False)
            except pyghmi_exception.IpmiException as error:
                log.error(IPMI_GET_ERR_MSG % (rack_id, ipv4, str(error)))
                sys.exit(1)

            match = re.search('^(.+?)/', inv['ipv4_address'])
            inv_ipv4_address_no_mask = match.group(1)

            # Check that IPMI port is not set to Static
            if inv['ipv4_configuration'] == STATIC:
                try:
                    raise Exception()
                except:
                    log.error(DHCP_ERR_MSG %
                              (STATIC, rack_id, inv_ipv4_address_no_mask,
                               inv['mac_address']))
                    sys.exit(1)

            # Compare ipv4 address on IPMI port versus inventory file
            if inv_ipv4_address_no_mask != ipv4:
                try:
                    raise Exception()
                except:
                    log.error(IPV4_ERR_MSG %
                              (rack_id, inv_ipv4_address_no_mask, ipv4,
                               inv['mac_address']))
                    sys.exit(1)

            # Compare mac address on IPMI port versus inventory file

            try:
                ipmi_cmd.set_net_configuration(
                    ipv4_address=inv['ipv4_address'],
                    ipv4_configuration='Static',
                    ipv4_gateway=inv['ipv4_gateway'],
                    channel=None)
                log.info(IPMI_SET_MSG %
                         (STATIC, rack_id, ipv4, inv['mac_address']))
            except pyghmi_exception.IpmiException as error:
                log.error(
                    IPMI_SET_ERR_MSG %
                    (STATIC, rack_id, ipv4, inv['mac_address'], str(error)))
                sys.exit(1)
Esempio n. 23
0
    def __init__(self, log, inv_file):
        self.inv = Inventory(log, inv_file)
        self.log = log

        for _, _, self.group, self.index, self.node in \
                self.inv.yield_nodes():
            ipmi_cmd = ipmi_command.Command(
                bmc=self.node[self.inv.INV_IPV4_IPMI],
                userid=self.node[self.inv.INV_USERID_IPMI],
                password=self.node[self.inv.INV_PASSWORD_IPMI])

            components = []
            try:
                for desc in ipmi_cmd.get_inventory_descriptions():
                    components.append(desc)
            except ipmi_exc.IpmiException as exc:
                self._log_ipmi_exception(exc)
                continue

            self.comp_name = self.IPMI_SYSTEM_FIRMWARE
            if self.comp_name in components:
                try:
                    self.comp_value = ipmi_cmd.get_inventory_of_component(
                        self.comp_name)
                    self._get_ipmi_architecture()
                    self._get_ipmi_field(self.IPMI_HARDWARE_VERSION)
                except ipmi_exc.IpmiException as exc:
                    self._log_ipmi_exception(exc)

            self.comp_name = self.IPMI_SYSTEM
            if self.comp_name in components:
                try:
                    self.comp_value = ipmi_cmd.get_inventory_of_component(
                        self.comp_name)
                    self._get_ipmi_field(self.IPMI_PRODUCT_NAME)
                    self._get_ipmi_field(self.IPMI_CHASSIS_PART_NUMBER)
                    self._get_ipmi_field(self.IPMI_CHASSIS_SERIAL_NUMBER)
                    self._get_ipmi_field(self.IPMI_MODEL)
                    self._get_ipmi_field(self.IPMI_SERIAL_NUMBER)
                except ipmi_exc.IpmiException as exc:
                    self._log_ipmi_exception(exc)

            self.comp_name = self.IPMI_NODE1
            if self.comp_name in components:
                try:
                    self.comp_value = ipmi_cmd.get_inventory_of_component(
                        self.comp_name)
                    self._get_ipmi_field(self.IPMI_CHASSIS_PART_NUMBER)
                    self._get_ipmi_field(self.IPMI_CHASSIS_SERIAL_NUMBER)
                except ipmi_exc.IpmiException as exc:
                    self._log_ipmi_exception(exc)
Esempio n. 24
0
    def open(self) -> None:
        self._logger.debug(
            "Connecting to %s:623 (User: %s, Privlevel: 2)",
            self.address or "local",
            self.username or "no user",
        )

        # Performance: See header.
        import pyghmi.ipmi.command as ipmi_cmd  # type: ignore[import]
        self._command = ipmi_cmd.Command(
            bmc=self.address,
            userid=self.username,
            password=self.password,
            privlevel=2,
        )
Esempio n. 25
0
 def initialize_ipmi_session(self):
     """ Initialize command object with IPMI details """
     attempts = 0
     while attempts < 5:
         try:
             ipmi_object = command.Command(self.ipmi_ip, self.user_id,
                                           self.password)
         except IpmiException as e:
             print(e.args[0])
             logger.warning(
                 "IPMI command failed, retrying after 15 seconds...")
             sleep(15)
             attempts = attempts + 1
             continue
         return ipmi_object
Esempio n. 26
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            port=dict(default=623, type='int'),
            state=dict(required=True,
                       choices=['on', 'off', 'shutdown', 'reset', 'boot']),
            user=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            timeout=dict(default=300, type='int'),
        ),
        supports_check_mode=True,
    )

    if command is None:
        module.fail_json(msg='the python pyghmi module is required')

    name = module.params['name']
    port = module.params['port']
    user = module.params['user']
    password = module.params['password']
    state = module.params['state']
    timeout = module.params['timeout']

    # --- run command ---
    try:
        ipmi_cmd = command.Command(bmc=name,
                                   userid=user,
                                   password=password,
                                   port=port)
        module.debug('ipmi instantiated - name: "%s"' % name)

        current = ipmi_cmd.get_power()
        if current['powerstate'] != state:
            response = {
                'powerstate': state
            } if module.check_mode else ipmi_cmd.set_power(state, wait=timeout)
            changed = True
        else:
            response = current
            changed = False

        if 'error' in response:
            module.fail_json(msg=response['error'])

        module.exit_json(changed=changed, **response)
    except Exception as e:
        module.fail_json(msg=str(e))
Esempio n. 27
0
 def __init__(self, host_list, interval):
     threading.Thread.__init__(self)
     self.interval = interval  # Polling interval in seconds
     self.server_connection_list = []
     self.failed_connection_list = []
     self.stopped = False
     for host in host_list:
         try:
             ipmi = command.Command(bmc=host.hostname,
                                    userid=host.userid,
                                    password=host.password)
             server_connection = ServerConnection(ipmi, host.unique_id)
             self.server_connection_list.append(server_connection)
             print(host.hostname + " - ipmi connection established")
         except:
             self.failed_connection_list.append(host.unique_id)
             print(host.hostname + " - ipmi connection failed")
Esempio n. 28
0
    def callFunc(req, cmd, retry):
        try:
            retry = retry + 1
            error(req.uuid + ": Retry Attempt - " + str(retry))
            # error(retry)

            cmd = command.Command(bmc=ipmi_host,
                                  userid=ipmi_user,
                                  password=ipmi_pass)
            result = func(req, cmd)
            error(result)
        except IpmiException, e:
            if retry != 60:
                time.sleep(30)
                result = callFunc(req, cmd, retry)
            else:
                result = fail(msg=str(e))
Esempio n. 29
0
def _send_raw(driver_info, raw_bytes):
    """Send raw bytes to the BMC."""
    netfn, command, data = _parse_raw_bytes(raw_bytes)
    LOG.debug("Sending raw bytes %(bytes)s to node %(node_id)s",
              {'bytes': raw_bytes, 'node_id': driver_info['uuid']})
    try:
        ipmicmd = ipmi_command.Command(bmc=driver_info['address'],
                                       userid=driver_info['username'],
                                       password=driver_info['password'])
        ipmicmd.xraw_command(netfn, command, data=data)
    except pyghmi_exception.IpmiException as e:
        msg = (_("IPMI send raw bytes '%(bytes)s' failed for node %(node_id)s"
                 " with the following error: %(error)s") %
               {'bytes': raw_bytes, 'node_id': driver_info['uuid'],
                'error': e})
        LOG.error(msg)
        raise exception.IPMIFailure(msg)
Esempio n. 30
0
def start_ipmi_boot_setnextboot(bmc_ip,
                                bmc_username,
                                bmc_password,
                                boot_option,
                                persist=False,
                                uefiboot=False):
    ipmi_boot_setnextboot_data = dict()
    ipmi_boot_setnextboot_data['action'] = 'IPMI - Configure boot'

    try:
        connection_object = command.Command(bmc=bmc_ip,
                                            userid=bmc_username,
                                            password=bmc_password)

        if connection_object:
            cmd_results = connection_object.set_bootdev(bootdev=boot_option,
                                                        persist=persist,
                                                        uefiboot=uefiboot)

            if cmd_results and "error" not in cmd_results:
                ipmi_boot_setnextboot_data[
                    'status'] = json_output_success_string
                ipmi_boot_setnextboot_data['data'] = cmd_results

            # Return the error string if found in the results
            elif "error" in cmd_results:
                ipmi_boot_setnextboot_data[
                    'status'] = json_output_failed_string
                ipmi_boot_setnextboot_data['data'] = cmd_results
            else:
                ipmi_boot_setnextboot_data[
                    'status'] = json_output_failed_string
                ipmi_boot_setnextboot_data[
                    'data'] = json_ipmi_boot_setnextboot_failed_string
        else:
            ipmi_boot_setnextboot_data['status'] = json_output_failed_string
            ipmi_boot_setnextboot_data[
                'data'] = json_ipmi_failed_connecting_string

        return json.dumps(ipmi_boot_setnextboot_data)

    except Exception as e:
        ipmi_boot_setnextboot_data['status'] = json_output_error_string
        ipmi_boot_setnextboot_data['data'] = "{}".format(e)
        return json.dumps(ipmi_boot_setnextboot_data)