def ibmc_outband_fw_update_module(module):
    """
    Function: Outband firmware upgrade
    Args:
        module : information from yml
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2019/10/9 20:30
    """
    with IbmcBaseConnect(module.params, log, report) as ibmc:
        ret = is_support_server(ibmc, SERVERTYPE)
        if ret['result']:
            all_file = (module.params.get("local_file"),
                        module.params.get("remote_file"))
            if all(all_file) or not any(all_file):
                log_error = "Please select an out-of-band firmware upgrade " \
                            "mode from local_file and remote_file."
                set_result(ibmc.log_error, log_error, False, ret)
                return ret
        try:
            local, file, protocol = get_file_name(module)
        except Exception as e:
            log_error = "Update failed! %s" % str(e)
            set_result(ibmc.log_error, log_error, False, ret)
            return ret

        ret = update_fw(ibmc, file, protocol, local)
    return ret
def check_item(ibmc, snmp_info, item, item_dict):
    """
    Function:
        Set SNMP trap resource properties
    Args:
        ibmc : Class that contains basic information about iBMC
        snmp_info : User-set SNMP trap information
        item : Validation item
        item_dict : Value range of item
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         Set SNMP trap resource properties failed!
    Date: 2019/10/12 17:21
    """
    ret = {'result': True, 'msg': ''}
    item_value = snmp_info.get(item)
    if item_value:
        item_value = item_dict.get(str(item_value).lower())
        if item_value in item_dict.values():
            return item_value
        else:
            log_msg = 'The trap version is incorrect, It should be %s' % item_dict
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret
    return ret
Exemplo n.º 3
0
def verify_file_path(ibmc, local_path=None):
    """
    Function:
        verify local file path
    Args:
        ibmc : Class that contains basic information about iBMC
        local_path :Local path for storing files
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    # Initialize return information
    ret = {'result': True, 'msg': ''}

    # Setting the default save path
    if not local_path:
        local_path = os.path.join(IBMC_REPORT_PATH, "download")
        if not os.path.exists(local_path):
            os.makedirs(local_path)

    # Verify the bmc_file and local_path
    if not os.path.exists(local_path):
        log_error = "Download file failed! The local_path %s is incorrect, the path does not exist." \
                    "Please reset it." % local_path
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    ret['msg'] = local_path
    return ret
Exemplo n.º 4
0
def ibmc_profile_import_module(module):
    """
    Function:
        import BIOS, BMC, and RAID Controller Configurations
    Args:
        module  : information from yml
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2019/10/9 20:30
    """
    with IbmcBaseConnect(module.params, log, report) as ibmc:
        ret = is_support_server(ibmc, SERVERTYPE)
        if ret['result']:
            all_file_path = (module.params.get("local_import"),
                             module.params.get("remote_import"))
            if all(all_file_path) or not any(all_file_path):
                log_error = "Profile import failed! Please select a profile " \
                            "import mode from local_import or remote_import."
                set_result(ibmc.log_error, log_error, False, ret)
                return ret

            try:
                local, profile = get_profile_name(ibmc, module)
            except Exception as e:
                log_error = "Profile import failed! %s" % str(e)
                set_result(ibmc.log_error, log_error, False, ret)
                return ret
            command = "import"
            ret = server_profile(ibmc, profile, command, local)
    return ret
def sp_api_set_fw_upgrade(ibmc,
                          image_url,
                          signal_url,
                          image_type="Firmware",
                          parameter="all",
                          upgrade_mode="Auto",
                          active_method="Restart",
                          upgrade_id="1"):
    """
    Function:
        sp api get fw upgrade
    Args:
        ibmc : Class that contains basic information about iBMC
        image_url : Image URI
        signal_url : Signal URI
        image_type : image type
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2019/10/12 17:21
    """
    uri = "%s/SPService/SPFWUpdate/%s/Actions/SPFWUpdate.SimpleUpdate" \
          % (ibmc.manager_uri, upgrade_id)
    token = ibmc.get_token()
    headers = {'content-type': 'application/json', 'X-Auth-Token': token}
    playload = {
        "ImageURI": image_url,
        "SignalURI": signal_url,
        "ImageType": image_type,
        "Parameter": parameter,
        "UpgradeMode": upgrade_mode,
        "ActiveMethod": active_method
    }
    ret = {'result': True, 'msg': ''}
    try:
        r = ibmc.request('POST',
                         resource=uri,
                         headers=headers,
                         data=playload,
                         tmout=10)
        result = r.status_code
        if result == 200:
            ibmc.log_info("sp api set fw upgrade successful!\n")
            ret['result'] = True
            ret['msg'] = 'successful!'
        else:
            log_msg = "set sp_api_set_fw_upgrade error info is: %s \n" % str(
                r.json())
            set_result(ibmc.log_error, log_msg, False, ret)
    except Exception as e:
        log_msg = "set FwUpgrade failed! %s " % str(e)
        set_result(ibmc.log_error, log_msg, False, ret)
    return ret
def update_fw(ibmc, file_path, protocol=None, local=False):
    """
    Function:
        Out_band firmware upgrade
    Args:
        ibmc : Class that contains basic information about iBMC
        file_path : path of the firmware
        protocol : protocol of the file server
        local
    Returns:
        rets : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        update failed
    Date: 10/19/2019
    """
    # Initialize return information
    rets = {'result': True, 'msg': ''}

    # Uploading a Local Firmware Package
    if local:
        upload_file_ret = upload_file(ibmc, file_path)
        if upload_file_ret.get('result') is False:
            return upload_file_ret
        file_name = file_path.split("/")[-1]
        file_path = os.path.join("/tmp/web", file_name)

    if protocol is not None:
        if protocol not in FILE_SERVER:
            log_msg = "The protocol error, please choose from [HTTPS, SCP, SFTP, CIFS, NFS] \n"
            set_result(ibmc.log_error, log_msg, False, rets)
            return rets

    # Sending a Firmware Upgrade Request
    try:
        if protocol:
            ret = update_api(ibmc, file_path, protocol)
        else:
            ret = update_api(ibmc, file_path)
        ibmc.log_info("ret:%s" % (str(ret)))
        code = ret.status_code
        data = ret.json()
        ibmc.log_info("code:%s" % (str(code)))
        if code != 202:
            log_msg = "update failed: %s" % (
                data[u'error'][u'@Message.ExtendedInfo'][0][u'Message'])
            set_result(ibmc.log_error, log_msg, False, rets)
        else:
            wait_task(ibmc, data, file_path, rets)
        return rets

    except Exception as e:
        ibmc.log_error("update failed! exception is: %s" % (str(e)))
        raise
def get_bios_setting_result(ibmc):
    """
    Function:
        Querying the Effective Status of BIOS Settings.
    Args:
        ibmc : Class that contains basic information about iBMC
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    ret = {'result': True, 'msg': ''}
    # Obtain the token information of the iBMC
    token = ibmc.bmc_token

    # URL of the Bios service
    url = ibmc.system_uri + "/Bios/Settings"

    # Initialize headers
    headers = {'X-Auth-Token': token}

    # Initialize payload
    payload = {}

    try:
        # Obtain the BIOS effective status information through the GET method
        request_result = ibmc.request('GET',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=30)
        # Obtain error code
        request_code = request_result.status_code
        if request_code != 200:
            error_msg = "Get BIOS effective status failed! The error code is: %s, " \
                        "The error info is: %s \n" % (
                            str(request_code), str(request_result.json()))
            set_result(ibmc.log_error, error_msg, False, ret)

        else:
            # Parses the response result and obtains the effective status.
            request_result_json = request_result.json()
            effect_status = request_result_json.get('Oem')
            oem_info = ibmc.oem_info
            status = effect_status.get(oem_info).get('EffectiveStatus')
            ret['msg'] = status
    except Exception as e:
        error_msg = "Get BIOS effective status failed! The error info is: %s \n" % str(
            e)
        set_result(ibmc.log_error, error_msg, False, ret)

    return ret
def set_boot_device_request(ibmc, boot_payload):
    """
    Function:
        Send a request to set Boot device
    Args:
        ibmc : Class that contains basic information about iBMC
        boot_payload : User-set boot device information
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         Set boot device info failed!
    Date: 2019/10/23 21:44
    """
    # Initialize return information
    ret = {'result': True, 'msg': ''}
    payload = {"Boot": boot_payload}

    # URL of the system resource
    url = ibmc.system_uri
    # Obtain token
    token = ibmc.bmc_token
    # Obtain etag
    etag = ibmc.get_etag(url)
    # Initialize headers
    headers = {
        'content-type': 'application/json',
        'X-Auth-Token': token,
        'If-Match': etag
    }

    try:
        # Modify boot device by PATCH method
        request_result = ibmc.request('PATCH',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=10)
        # Obtain the error code
        request_code = request_result.status_code
        if request_code == 200:
            log_msg = "Set boot device info successful!"
            set_result(ibmc.log_info, log_msg, True, ret)
        else:
            log_msg = "Set boot device info failed! The error code is: %s . The error info is: %s" % \
                      (str(request_code), str(request_result.json()))
            set_result(ibmc.log_error, log_msg, False, ret)
    except Exception as e:
        ibmc.log_error(
            "Set boot device info failed! The error info is: %s \n" % str(e))
        raise requests.exceptions.RequestException(
            "Set boot device info failed! The error info is: %s" % str(e))
    return ret
def import_profile(ibmc, file_path, local):
    """
    Function:
        Importing BIOS, BMC, and RAID Controller Configurations
    Args:
        ibmc: Class that contains basic information about iBMC
        file_path: Path of the file to be imported
        local: Import from local
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    """
    ret = {'result': True, 'msg': ''}
    save_path, file_name = os.path.split(file_path)
    if local:
        upload_file_ret = upload_file(ibmc, file_path)
        if upload_file_ret.get('result'):
            file_path = os.path.join("/tmp/web", file_name)
        else:
            return upload_file_ret

    oem_info = ibmc.oem_info
    uri = "%s/Actions/Oem/%s/Manager.ImportConfiguration" % (ibmc.manager_uri,
                                                             oem_info)
    token = ibmc.get_token()
    headers = {'Content-Type': 'application/json', 'X-Auth-Token': token}
    payload = {'Type': 'URI', 'Content': file_path}

    try:
        request_result = ibmc.request('POST',
                                      resource=uri,
                                      headers=headers,
                                      data=payload,
                                      tmout=60)
    except Exception as e:
        log_error = "Import server profile failed: %s" % str(e)
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    log_info = "Send request to import profile succeeded, please waitting for task finish."
    ibmc.log_info(log_info)
    request_code = request_result.status_code
    request_json = request_result.json()
    if request_code == 202:
        ret['result'] = True
        ret['msg'] = request_result.json()
    else:
        log_error = "Import server profile failed, The status code is %s. " \
                    "The error info is: %s." % (request_code, str(request_json))
        set_result(ibmc.log_error, log_error, False, ret)

    return ret
Exemplo n.º 10
0
def send_request(ibmc, url, request_method, payload):
    """
    Function:
        Send the request
    Args:
        ibmc : information from yml
        url : user-set request resource
        request_method : user-set request method
        request_body : request body content
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22
    """
    # Initialize return information
    ret = {'result': True, 'msg': ''}
    # Obtain the token information of the iBMC
    token = ibmc.bmc_token

    # Initialize headers
    headers = {'content-type': 'application/json', 'X-Auth-Token': token}
    if request_method == "PATCH":
        e_tag = ibmc.get_etag(url)
        headers['If-Match'] = e_tag
    request_code = None

    # Send request
    try:
        request_result = ibmc.request(request_method,
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=TIME_OUT)
        # Analyze the request result.
        request_code = request_result.status_code
        request_json = request_result.json()
        # Parsing the request result
        if request_code not in STATUS_CODE:
            log_error = "%s request failed! The error code is: %s. The error info is: %s \n" % \
                        (request_method, request_code, str(request_json))
            set_result(ibmc.log_error, log_error, False, ret)
            return ret
        else:
            ret["msg"] = str(request_json)
            return ret

    except Exception as e:
        log_error = "%s request failed! The error code is: %s. The error info is: " \
                    "%s  \n" % (request_method, request_code, e)
        raise requests.exceptions.RequestException(log_error)
def set_snmp_trap_request(ibmc, trap_payload):
    """
    Function:
        Send request for setting SNMP trap
    Args:
        ibmc :   Class that contains basic information about iBMC
        trap_payload : request body
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         Set SNMP trap resource properties failed!
    Date: 2019/10/12 17:21
    """
    ret = {'result': True, 'msg': ''}
    payload = {"SnmpTrapNotification": trap_payload}
    # URL of the SNMP service
    url = ibmc.manager_uri + "/SnmpService"
    # Obtain token
    token = ibmc.bmc_token
    # Obtain etag
    etag = ibmc.get_etag(url)
    # Initialize headers
    headers = {
        'content-type': 'application/json',
        'X-Auth-Token': token,
        'If-Match': etag
    }
    try:
        # Modify SNMP trap resource properties by PATCH method
        request_result = ibmc.request('PATCH',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=30)
        # Obtain the error code
        request_code = request_result.status_code
        if request_code == 200:
            log_msg = "Set SNMP trap resource properties successful!"
            set_result(ibmc.log_info, log_msg, True, ret)
        else:
            log_msg = "Set SNMP trap resource properties failed! " \
                      "The error code is: %s, The error info is: %s." \
                      % (str(request_code), str(request_result.json()))
            set_result(ibmc.log_error, log_msg, False, ret)
    except Exception as e:
        ibmc.log_error("Set SNMP trap resource properties failed! "
                       "The error info is: %s \n" % str(e))
        raise requests.exceptions.RequestException(
            "Set SNMP trap resource properties failed! "
            "The error info is: %s" % str(e))
    return ret
def set_bios_request(ibmc, payload):
    """
    Function:
        send request to set bios configuration
    Args:
        ibmc : Class that contains basic information about iBMC
        payload : request body
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    # Initialize return information
    ret = {'result': True, 'msg': ''}

    # Initialize request information.
    token = ibmc.get_token()
    url = ibmc.system_uri + "/Bios/Settings"
    e_tag = ibmc.get_etag(url)
    headers = {
        'content-type': 'application/json',
        'X-Auth-Token': token,
        'If-Match': e_tag
    }

    # send request to set bios
    try:
        request_result = ibmc.request('PATCH',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=10)
        request_code = request_result.status_code
        if request_code == 200:
            log_msg = "Set BIOS configuration resource info successfully! " \
                      "The setting takes effect after the system is restarted."
            set_result(ibmc.log_info, log_msg, True, ret)
        else:
            log_msg = "Set BIOS configuration resource info failed! " \
                      "The error code is: %s, The error info is: %s." % \
                      (str(request_code), str(request_result.json()))
            set_result(ibmc.log_error, log_msg, False, ret)
    except Exception as e:
        error_msg = "Set BIOS configuration info failed! The error info is: %s \n" % str(
            e)
        ibmc.log_error(error_msg)
        raise requests.exceptions.RequestException(error_msg)

    return ret
def wait_task(ibmc, data, file_path, rets):
    """
    Function:
        Out_band firmware upgrade
    Args:
        ibmc : Class that contains basic information about iBMC
        file_path : path of the firmware
        data : information from request
        rets: result of last step
    Returns:
        None
    Raises:
        None
    Date: 10/19/2019
    """
    task_id = data.get('Id')
    oem_info = ibmc.oem_info
    while 1:
        time.sleep(3)
        ret = ibmc.get_task_info(task_id)

        # Check whether the connection is successful.
        if ret is not None and ret.status_code == 200:
            data = ret.json()
        elif ret is not None:
            ibmc.log_info("code is :%s may be there are disconnect, "
                          "you should wait for a moment!\n" % ret.status_code)
            continue
        else:
            ibmc.log_info("ret is None,may be there are disconnect, "
                          "you should wait for a moment!\n")
            continue

        ret = data[u'TaskState']
        percent = data[u'Oem'][oem_info][u'TaskPercentage']
        percent = percent if percent else 0
        ibmc.log_info("status:%s percent:%s" % (ret, str(percent)))

        # Check the completion status of the current task.
        if ret == 'Running':
            time.sleep(1)
            continue
        elif ret == 'OK' or ret == 'Completed' or percent == '100%':
            log_msg = "update %s successful! \n" % (file_path.split("/")[-1])
            set_result(ibmc.log_info, log_msg, True, rets)
            break
        else:
            reason = data[u'Messages'][u'Message']
            log_msg = " update %s failed! The failed info is %s \n" \
                      % (file_path.split("/")[-1], reason)
            set_result(ibmc.log_error, log_msg, False, rets)
            break
def collect_log_request(ibmc, log_path, url, log_type):
    """
    Function:
        Send request to collect logs
    Args:
        ibmc : Class that contains basic information about iBMC
        log_path : Log file storage path and file name
        url: Redfish API for collect logs
        log_type : Collected log name
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    # Initialize return information
    ret = {'result': True, 'msg': ''}

    # Initialize request information.
    token = ibmc.get_token()
    headers = {'content-type': 'application/json', 'X-Auth-Token': token}
    payload = {"Type": "URI", "Content": log_path}

    # send request to collect logss
    try:
        request_result = ibmc.request('POST',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=TIME_OUT)
        request_code = request_result.status_code
        request_result_json = request_result.json()
    except Exception as e:
        error_msg = "Collect %s logs failed! The error info is: %s \n" \
                    % (log_type, str(e))
        set_result(ibmc.log_error, error_msg, False, ret)
        return ret

    if request_code != 202:
        log_error = "Collect %s logs failed! The error code is: %s, " \
                    "The error info is: %s." \
                    % (log_type, str(request_code), str(request_result_json))
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    task_url = request_result_json.get("@odata.id")
    ibmc.log_info("Collecting %s logs..." % log_type)
    ret = wait_collect(ibmc, task_url, log_type)

    return ret
def check_set_interval(ibmc, min_polling_interval, max_polling_interval):
    """
    Function:
        Verify the validity of the min_polling_interval and max_polling_interval setted by the user.
    Args:
        ibmc : Class that contains basic information about iBMC
        min_polling_interval : User-set min polling interval
        max_polling_interval: User-set max polling interval
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2019/10/12 17:21
    """
    ret = {'result': True, 'msg': ''}

    if min_polling_interval is not None:
        # Verify min_polling_interval is an integer
        if not isinstance(min_polling_interval, int):
            log_msg = 'The min polling interval must be an integer'
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret
        if min_polling_interval < MIN_POLLING_INTERVAL or min_polling_interval > MAX_POLLING_INTERVAL:
            log_msg = 'The min polling interval is incorrect, It should be a integer from %s to %s' % \
                      (str(MIN_POLLING_INTERVAL), str(MAX_POLLING_INTERVAL))
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret

    if max_polling_interval is not None:
        # Verify max_polling_interval is an integer
        if not isinstance(max_polling_interval, int):
            log_msg = 'The max polling interval must be an integer'
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret
        if max_polling_interval < MIN_POLLING_INTERVAL or max_polling_interval > MAX_POLLING_INTERVAL:
            log_msg = 'The max polling interval is incorrect, It should be a integer from %s to %s' % \
                      (str(MIN_POLLING_INTERVAL), str(MAX_POLLING_INTERVAL))
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret

    if (min_polling_interval is not None) and (max_polling_interval
                                               is not None):
        if min_polling_interval > max_polling_interval:
            log_msg = 'The min polling interval cannot be greater than max polling interval'
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret

    return ret
def wait_task(ibmc, data, command, file_path):
    """
    Function:
        Obtaining the File Transfer Result
    Args:
        ibmc: Class that contains basic information about iBMC
        data: Information returned after sending request
        command: Export or import
        file_path: Path to save the file
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    """
    rets = {'result': True, 'msg': ''}
    save_path, file_name = os.path.split(file_path)
    cnt = -1
    task_id = data.get('Id')
    oem_info = ibmc.oem_info

    try:
        for cnt in range(WAIT_TASK_TIME):
            time.sleep(3)
            task_ret = ibmc.get_task_info(task_id)

            if task_ret.status_code != 200:
                ibmc.log_info("code is: %s ,may be there are disconnect, "
                              "you should wait for a moment!" %
                              str(task_ret.status_code))
                continue

            data = task_ret.json()
            ret = data[u'TaskState']
            percent = data[u'Oem'][oem_info][u'TaskPercentage']
            ibmc.log_info("status: %s percent: %s" % (ret, str(percent)))

            if ret == 'Running':
                time.sleep(1)
                continue
            elif ret == 'OK' or ret == 'Completed' or percent == '100%':
                log_msg = "%s: %s successful! " % (command, file_name)
                set_result(ibmc.log_info, log_msg, True, rets)
                return rets
            else:
                log_msg = "%s: %s failed! The error info is %s " % \
                          (command, file_name, str(data['Messages']['Message']))
                set_result(ibmc.log_error, log_msg, False, rets)
                return rets

        if cnt == (WAIT_TASK_TIME - 1):
            log_msg = " %s : %s failed! Get task result timeout " % (command,
                                                                     file_name)
            set_result(ibmc.log_error, log_msg, False, rets)
            return rets

    except Exception as e:
        log_msg = "%s profile exception! %s" % (command, str(e))
        set_result(ibmc.log_error, log_msg, False, rets)

    return rets
def set_ntp_request(ibmc, payload):
    """
    Function:
        set NTP configuration
    Args:
        ibmc : Class that contains basic information about iBMC
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2019/10/12 21:13
    """
    ret = {'result': True, 'msg': ''}
    # URL of the NTP service
    url = ibmc.manager_uri + "/NtpService"
    # Obtain token
    token = ibmc.bmc_token
    # Obtain etag
    etag = ibmc.get_etag(url)
    # Initialize headers
    headers = {
        'content-type': 'application/json',
        'X-Auth-Token': token,
        'If-Match': etag
    }
    try:
        # Modify NTP configuration by PATCH method
        request_result = ibmc.request('PATCH',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=10)
        # Obtain the error code
        request_code = request_result.status_code
        if request_code == 200:
            log_msg = "Set NTP configuration resource info successful!"
            set_result(ibmc.log_info, log_msg, True, ret)
        else:
            log_msg = "Set NTP configuration resource info failed! The error code is: %s, " \
                      "The error info is: %s." % (
                          str(request_code), str(request_result.json()))
            set_result(ibmc.log_error, log_msg, False, ret)
    except Exception as e:
        msg = "Set NTP configuration resource info failed! The error info is: %s" % str(
            e)
        ibmc.log_error(msg)
        raise requests.exceptions.RequestException(msg)
    return ret
def check_status(ibmc):
    """
    Function:
        check ibmc version, power status and sp status
    Args:
        ibmc : Class that contains basic information about iBMC
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2019/10/12 17:21
    """
    rets = {'result': True, 'msg': ''}
    r = ibmc.check_ibmc_version(BMC_EXPECT_VERSION)
    if r is False:
        log_msg = "ibmc version must be %s or above" % BMC_EXPECT_VERSION
        set_result(ibmc.log_error, log_msg, False, rets)
        return rets

    ret = manage_power(ibmc, "PowerOff")
    if ret['result'] is True:
        ibmc.log_info("ForceOff system successfully!")
    else:
        log_msg = "ForceOff  system failed!"
        set_result(ibmc.log_error, log_msg, False, rets)
        return rets
    time.sleep(5)
    for cnt_times in range(WAIT_POWEROFF):
        time.sleep(1)
        ret = get_power_status(ibmc)
        if "off" in ret['msg'].lower():
            break
        if cnt_times == WAIT_POWEROFF - 1:
            ibmc.log_error("power state is still on after 120 s")
    for cnt_times in range(WAIT_POWEROFF):
        time.sleep(1)
        try:
            ret = sp_api_get_status(ibmc)
            if ret is None:
                ibmc.log_error("get sp status return None ")
        except Exception as e:
            ibmc.log_error("get sp status exception exception is :%s" % str(e))
            continue
        if SP_STATUS_POWEROFF in ret:
            break
        if cnt_times == WAIT_POWEROFF - 1:
            ibmc.log_info("sp state is still on after 120 s")
    return rets
Exemplo n.º 19
0
def download_file(ibmc, bmc_file, local_path=None, change_name=True):
    """
    Function:
        download files from /tmp/web/
    Args:
        ibmc : Class that contains basic information about iBMC
        bmc_file : User-specified file to be download
        local_path :Local path for storing files
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    ibmc.log_info("Start to download the files...")
    # Initialize return information
    ret = {'result': True, 'msg': ''}

    # Verify the bmc_file
    if not isinstance(bmc_file, str):
        log_error = "Download file failed! The bmc_file %s is incorrect, the" \
                    " value must be a string. Please reset it." % bmc_file
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    # Verify the local_path
    verify_result = verify_file_path(ibmc, local_path)
    if not verify_result.get('result'):
        return verify_result

    # Set the file name.
    local_path = verify_result.get('msg')
    if change_name:
        date_str = time.strftime("%Y%m%d%H%M%S", time.localtime())
        file_name = '%s_%s_%s' % (str(ibmc.ip), date_str, bmc_file)
    else:
        file_name = bmc_file
    local_file_name = os.path.join(local_path, file_name)

    # Obtaining the download result
    request_result = download_file_request(ibmc, bmc_file, local_file_name)
    if not request_result.get('result'):
        return request_result

    log_msg = "Download file successfully! File saved to %s." % local_file_name
    set_result(ibmc.log_info, log_msg, True, ret)
    return ret
def ibmc_modify_account_module(module):
    """
    Function:

    Args:
              ansible_module       (class):

    Returns:
        ret = {"result": False, "msg": 'not run modify account yet'}
    Raises:
        Exception
    Examples:

    Author: xwh
    Date: 2019/10/9 20:30
    """
    ret = {"result": False, "msg": 'not run modify account yet'}
    with IbmcBaseConnect(module.params, log, report) as ibmc:
        oem_info = ibmc.oem_info
        config_dic = {}
        body_para = {}
        oem_dic = {oem_info: {}}
        if module.params.get("new_account_user"):
            body_para["UserName"] = module.params.get("new_account_user")
        if module.params.get("new_account_pswd"):
            body_para["Password"] = module.params.get("new_account_pswd")
        if module.params.get("roleid"):
            body_para["RoleId"] = module.params.get("roleid")
        if module.params.get("locked") is not None:
            if module.params["locked"] is not False:
                error_msg = "The locked param can not be set to true"
                set_result(ibmc.log_error, error_msg, False, ret)
                return ret
            body_para["Locked"] = module.params["locked"]
        if module.params.get("enable") is not None:
            body_para["Enabled"] = module.params["enable"]
        if module.params.get("account_insecure_prompt_enabled") is not None:
            oem_dic[oem_info]["AccountInsecurePromptEnabled"] = module.params["account_insecure_prompt_enabled"]

        try:
            new_information(ibmc, module, oem_dic)
        except Exception as e:
            set_result(ibmc.log_error, str(e), False, ret)
            return ret
        if oem_dic[oem_info] != {}:
            body_para['Oem'] = oem_dic
        config_dic[module.params["old_account_user"]] = body_para
        ret = modify_account(ibmc, config_dic)
    return ret
def export_profile(ibmc, file_path, local):
    """
    Function:
        Export BIOS, BMC, and RAID Controller Configurations
    Args:
        ibmc: Class that contains basic information about iBMC
        file_path: Path to save the file
        local: Export to local
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    """
    ret = {'result': True, 'msg': ''}
    save_path, file_name = os.path.split(file_path)
    if local:
        file_path = os.path.join("/tmp/web", file_name)

    oem_info = ibmc.oem_info
    uri = "%s/Actions/Oem/%s/Manager.ExportConfiguration" % (ibmc.manager_uri,
                                                             oem_info)
    token = ibmc.get_token()
    headers = {'content-type': 'application/json', 'X-Auth-Token': token}
    payload = {"Type": "URI", "Content": file_path}

    try:
        request_result = ibmc.request('POST',
                                      resource=uri,
                                      headers=headers,
                                      data=payload,
                                      tmout=60)
    except Exception as e:
        log_error = "Export server profile failed: %s" % str(e)
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    request_code = request_result.status_code
    request_json = request_result.json()

    if request_code != 202:
        log_error = "Export profile failed! The status code is %s. " \
                    "The error info is %s" % (request_code, str(request_json))
        set_result(ibmc.log_error, log_error, False, ret)
    else:
        ret['result'] = True
        ret['msg'] = request_json

    return ret
def get_log_id(ibmc):
    """
    Function:
        Indicates the ID of a log file dynamically obtained.
    Args:
        ibmc : Class that contains basic information about iBMC
    Returns:
        ret : a dict of task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2021/6/30 18:04
    """
    ret = {'result': True, 'msg': ''}

    url = "%s/LogServices" % ibmc.system_uri
    # Obtain the token information of the iBMC
    token = ibmc.bmc_token
    # Initialize headers
    headers = {'X-Auth-Token': token}
    # Initialize payload
    payload = {}

    try:
        # Obtain the BIOS resource information through the GET method
        request_result = ibmc.request('GET',
                                      resource=url,
                                      headers=headers,
                                      data=payload,
                                      tmout=30)
        # Obtain error code
        request_code = request_result.status_code
        res_info = request_result.json()
    except Exception as e:
        log_error = "Get log id failed! The error info is %s" % e
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    if request_code != 200:
        log_error = "Get log id failed! The error info is %s" % res_info
        set_result(ibmc.log_error, log_error, False, ret)
    else:
        log_id = res_info.get("Members")[0].get("@odata.id")
        ret["msg"] = log_id
    return ret
Exemplo n.º 23
0
def upload_file(ibmc, file):
    """
    Function:
        Upload files to /bmc/temp
    Args:
        ibmc : Class that contains basic information about iBMC
        file : User-specified file to be transferred
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    ibmc.log_info("Start to upload the files...")

    # Initialize return information
    ret = {'result': True, 'msg': ''}
    if not os.path.isfile(file):
        log_error = "Upload file failed! The file %s is incorrect, " \
                    "please reset it." % file
        set_result(ibmc.log_error, log_error, False, ret)
        return ret
    # Initialize request information
    url = "https://%s/redfish/v1/UpdateService/FirmwareInventory" % ibmc.ip
    token = ibmc.get_token()
    filename = file.split("/")[-1]
    with open(file, 'rb') as f:
        # Large files cannot be directly transferred and need to be encoded.
        m = MultipartEncoder(
            fields={'file': (filename, f, 'multipart/form-data')})
        headers = {'X-Auth-Token': token, 'Content-Type': m.content_type}
        try:
            request_result = ibmc.request('POST',
                                          resource=url,
                                          data=m,
                                          headers=headers,
                                          tmout=600)

        except Exception as e:
            log_error = "Send request to upload the file failed! The error info is: %s \n" % str(
                e)
            set_result(ibmc.log_error, log_error, False, ret)
            return ret

    if request_result.status_code != 202:
        log_error = "Send request to upload the file failed! " \
                    "The error code is: %s, The error info is: %s" \
                    % (str(request_result.status_code), str(request_result.json()))
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    log_msg = "Upload file successfully!"
    set_result(ibmc.log_info, log_msg, True, ret)
    return ret
def set_bios(ibmc, bios_info, immediately):
    """
    Function:
        Set bios
    Args:
        ibmc : Class that contains basic information about iBMC
        bios_info : user set bios information
        immediately : restart the server
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2021/2/22 21:13
    """
    ibmc.log_info("Start to set BIOS configuration resource info...")

    # Initialize return information
    ret = {'result': True, 'msg': ''}

    # Verify the BIOS content set by the user.
    if not isinstance(bios_info, dict):
        log_msg = 'The attributes format is incorrect, ' \
                  'please set it in the set_bios.yml file.'
        set_result(ibmc.log_error, log_msg, False, ret)
        return ret
    if len(bios_info) == 0:
        log_msg = 'The attributes is null, ' \
                  'please set it in the set_bios.yml file'
        set_result(ibmc.log_error, log_msg, False, ret)
        return ret

    # Obtain the request result.
    payload = {"Attributes": bios_info}
    request_result = set_bios_request(ibmc, payload)
    if not request_result.get('result') or not immediately:
        return request_result

    # Restart the server
    restart_result = restart_server(ibmc)
    if not restart_result.get('result'):
        return restart_result

    ret = verify_configuration(ibmc, bios_info)
    return ret
def sp_api_get_fw_info(ibmc):
    """
    Function:
        sp api get fw info
    Args:
        ibmc : Class that contains basic information about iBMC
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2019/10/12 17:21
    """
    ret = {'result': False, 'msg': '', "fwInfo": []}
    uri = "%s/SPService/DeviceInfo" % ibmc.manager_uri
    token = ibmc.get_token()
    headers = {'X-Auth-Token': token}
    playload = {}
    try:
        r = ibmc.request('GET',
                         resource=uri,
                         headers=headers,
                         data=playload,
                         tmout=10)
        result = r.status_code
        if result != 200:
            log_msg = "get FwInfo error info is: %s \n" % str(r.json())
            set_result(ibmc.log_error, log_msg, False, ret)
            return ret
        ibmc.log_info("get FwInfo successful!\n")
        ret['result'] = True
        ret['msg'] = 'successful!'
        # PCIeCards is empty or do not has the key PCIeCards should raise
        if r.json().get("PCIeCards"):
            ret["fwInfo"] = r.json().get("PCIeCards")
        else:
            msg = "get FWInfo failed! do not has keys PCIeCards or PCIeCards is empty; " \
                  "Maybe you should start sp once"
            ibmc.log_error(msg)
            raise Exception(msg)

    except Exception as e:
        ibmc.log_error("get FWInfo failed! %s" % str(e))
        raise
    return ret
Exemplo n.º 26
0
def get_power_status(ibmc):
    """
    Args:
            ibmc            (class):
    Returns:
        None
    Raises:
        Exception
    Examples:
        None
    Author: xwh
    Date: 10/19/2019
    """
    token = ibmc.get_token()
    headers = {'content-type': 'application/json', 'X-Auth-Token': token}
    uri = ibmc.system_uri
    rets = {'result': True, 'msg': ''}
    payload = {}
    try:
        response = ibmc.request("GET",
                                resource=uri,
                                headers=headers,
                                data=payload)
    except Exception as e:
        ibmc.log_error("send get power state  exception; exception is: %s" %
                       (str(e)))
        raise Exception("send get power state  exception; exception is: %s" %
                        (str(e)))
    try:
        if response.status_code == 200:
            data = response.json()
            log_msg = "get system power state successful! power status is :%s" % data[
                u'PowerState']
            set_result(ibmc.log_info, log_msg, True, rets)
            return rets
        else:
            ibmc.log_error(" get system power state failed!")
            raise Exception(
                "get power state failed , error code exception,error code is  %s"
                % str(response.status_code))
    except Exception as e:
        ibmc.log_error("parse response exception %s" % (str(e)))
        raise Exception("parse response exception %s" % (str(e)))
Exemplo n.º 27
0
def check_user_set(ibmc, url, request_method, request_body):
    """
    Function:
        Validity of parameters set by users
    Args:
        ibmc : information from yml
        url : user-set request resource
        request_method : user-set request method
        request_body : user-set request body content
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    """
    # Initialize return information
    ret = {'result': True, 'msg': ''}

    # Verifying Parameters Configured by Users
    if request_method not in REQUEST_METHOD:
        log_error = "The request method is incorrect. " \
                    "Please set it in the common_api.yml file"
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    if request_method in ("GET", "DELETE") and request_body != '{}':
        log_error = "When request_method is 'Get' or 'Delete', request_body must be empty."
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    if not isinstance(request_body, str) or not request_body.startswith("{"):
        log_error = "Incorrect request_body format. Please set it in the common_api.yml file."
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    if not url.startswith("/"):
        log_error = "The url is incorrect. Please set it in the common_api.yml file."
        set_result(ibmc.log_error, log_error, False, ret)
        return ret

    msg = "Check parameter setting successfully!"
    set_result(ibmc.log_info, msg, True, ret)
    return ret
def ibmc_set_request(module):
    """
    Function:
        Set SNMP trap resource properties
    Args:
              module       (class):

    Returns:
        {"result": False, "msg": 'not run set snmp trap yet'}
    Raises:
        None
    Examples:

    Author:
    Date: 2019/12/12 17:33
    """
    ret = {}
    if module.params.get("verify") is False:
        verify = False
    elif module.params.get("verify") is None or module.params.get(
            "verify") == "":
        verify = True
    else:
        if module.params.get("verify") is True and module.params.get(
                "certify"):
            verify = module.params.get("certify")
        else:
            verify = True
    ciphers = module.params.get("ciphers")
    if module.params.get("force_tls1_2") is False:
        force_tls1_2 = False
    else:
        force_tls1_2 = True

    r = set_ssl_cfg(verify, force_tls1_2, ciphers, log)
    if r:
        log_msg = "set verify sucessed"
        set_result(log.info, log_msg, True, ret)
    else:
        log_msg = "set verify failed"
        set_result(log.error, log_msg, False, ret)
    return ret
def prepare_update(ibmc):
    """
    Function:
        set sp and power for update
    Args:
        ibmc : Class that contains basic information about iBMC
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
         None
    Date: 2019/10/12 17:21
    """
    rets = {'result': True, 'msg': ''}
    # start sp to upgrade
    ret = sp_api_set_sp_service(ibmc, sp_enable=True)
    if ret['result'] is True:
        ibmc.log_info("set sp_service successfully!")
    else:
        time.sleep(CHECK_INTERVAL)
        ret = sp_api_set_sp_service(ibmc, sp_enable=True)
        if ret['result'] is True:
            ibmc.log_info("set sp service again successfully!")
        else:
            log_msg = "set sp service again failed!"
            set_result(ibmc.log_error, log_msg, False, rets)
            return rets
    # power on
    ret = manage_power(ibmc, "PowerOn")
    if ret['result'] is True:
        ibmc.log_info("power on system successfully!")
    else:
        log_msg = "power on  system failed!"
        set_result(ibmc.log_error, log_msg, False, rets)
        return rets

    ret = wait_sp_start(ibmc)
    if ret['result'] is False:
        return ret
    return rets
def wait_collect(ibmc, task_url, log_type):
    """
    Function:
        wait task start for
    Args:
        ibmc : Class that contains basic information about iBMC
        task_url : url of task
        log_type : Collected log name
    Returns:
        ret : a dict of task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2019/11/9 18:04
    """
    ret = {'result': True, 'msg': ''}
    # Wait for task start
    time.sleep(START_TIME)

    request_time = GET_RESULT_TIME.get(log_type)
    sleep_time = SLEEP_TIME.get(log_type)
    for loop_time in range(0, request_time):
        # Get task result
        try:
            task_result = get_task_status(ibmc, task_url)
        except Exception as e:
            log_error = "Get task status exception, " \
                        "The error info is: %s, continue..." % str(e)
            set_result(ibmc.log_error, log_error, False, ret)
            return ret

        loop_time += 1
        if task_result[0].find("Successful") != -1:
            log_msg = "Collect %s logs successfully!" % log_type
            set_result(ibmc.log_info, log_msg, True, ret)
            return ret

        elif task_result[-1].find("failed") != -1 or task_result[0].find(
                "Exception") != -1:
            log_error = "Collect %s logs failed! %s" % (log_type,
                                                        task_result[-1])
            set_result(ibmc.log_error, log_error, False, ret)
            return ret
        else:
            time.sleep(sleep_time)
    # Collect time out
    log_msg = "Collect %s logs failed! Collection timed out." % log_type
    set_result(ibmc.log_error, log_msg, False, ret)
    return ret