def ethernetinterface_actions(self, parameters):
    try:
        a_name = ''

        if 'action' in parameters.keys():
            a_name = parameters['action']

        if a_name == 'static':
            res = set_static_interface(parameters["ifname"],
                                       parameters["address"],
                                       parameters["subnetmask"],
                                       parameters["gateway"])
            return ethernet_actions_results(res)
        elif a_name == 'dhcp':
            res = set_dhcp_interface(parameters["ifname"])
            return ethernet_actions_results(res)
        elif a_name == 'enable':
            res = enable_network_interface(parameters["ifname"])
            return ethernet_actions_results(res)
        elif a_name == 'disable':
            res = disable_network_interface(parameters["ifname"])
            return ethernet_actions_results(res)
        else:
            return set_failure_dict('Action command is not correct',
                                    completion_code.failure)
    except Exception, e:
        ocslog.log_exception()
        return set_failure_dict(('Exception:', e), completion_code.failure)
def call_network_command(command):
    try:
        process = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
        output, error_msg = process.communicate()
        completion_status = process.wait()
        
        return {'status_code' : completion_status, 'stdout' : output, 'stderr': error_msg}       
    
    except Exception, e:
        ocslog.log_exception()
        return {'status_code' : -1, 'stdout' : output, 'stderr' : e}        
def rackmanager_parse_set_commands(command_args):
    """
    Set commands for rack manager
        ocscli set rackmanager <command> <parameters>
        
        Command options:
            "LEDOn",
            "LEDOff",
            "RelayOn",
            "RelayOff",
            "TFTPStart",
            "TFTPStop",
            "TFTPGet",
            "TFTPPut",
            "TFTPDelete",
            "NFSStart",
            "NFSStop",
            "FwUpdate",
            "ClearLog",
            "SessionKill",
            "Time"
    """
    
    try:
        parser = ArgumentParser(prog = 'set manager', description = "Manager set commands")
        
        subparser = parser.add_subparsers(title = "Commands", metavar = '', dest = 'command')
        
        rackmanager_setcommand_options(subparser)
        
        args = parse_args_retain_case(parser, command_args)
        
        set_rm_cmd = repr(pre_settings.command_name_enum.set_rm_state)
        
        if pre_settings.is_set_rm_call == True:
            ocsaudit_log_command("", cmd_type.type_set, cmd_interface.interface_ocscli, 
                                 "manager " + str(args.command), " ".join(command_args[1:]))
            rackmanager_setcommands(args)
        else:
            permission = pre_settings.pre_check_manager(set_rm_cmd, 0) 
            if (permission == False):
                return
            else:
                ocsaudit_log_command("", cmd_type.type_set, cmd_interface.interface_ocscli, 
                                     "manager " + str(args.command), " ".join(command_args[1:]))
                rackmanager_setcommands(args)     
        
    except Exception, e:
        ocslog.log_exception()
        print "rackmanager_parse_set_commands - Exception: {0}".format(e) 
def powerport_set_system_reset(port_id, action_type, port_type):
    """ Turn power port on/off through GPIO shared library
    """

    try:
        gpio_binary = get_gpio_library()

        action = 1
        output = ''
        j = c_int()

        if (port_id < 1) or (port_id > 48):
            return set_failure_dict(
                "Invalid port-id {0}. Expected {1, 48}".format(port_id),
                completion_code.failure)

        if action_type.lower() == 'on':
            action = 1
        else:
            action = 0

        if port_type.lower() == "pdu":
            output = gpio_binary.ocs_port_control(port_id, action)

        elif port_type.lower() == "relay":
            output = gpio_binary.ocs_port_relay(port_id, action, byref(j))

        if (output == 0):
            return set_success_dict()
        else:
            #log_err
            return set_failure_dict(
                ("Failed to reset system using GPIO Library: {0}".format(
                    output)), completion_code.failure)

    except Exception, e:
        ocslog.log_exception()
        return set_failure_dict(
            "powerport_set_system_reset - Exception: {0}".format(e),
            completion_code.failure)
    def get_all_port_link_state(self):
        """
        Get the link state for all switch ports.
        
        Parameters:
            None.
            
        Return:
            A dictionary containing the link state for each port.  The dictionary keys are integer
            port numbers, and the values are a link state enumeration.
        """

        link = {}
        try:
            xml = self.get_all_port_802_3_settings()
            ports = xml.findall("./Entry")

            for i in ports:
                name = get_xml_string_value(i, "interfaceName",
                                            "port interface name")
                port = re.match("gi(\d+)", name)
                if (not port):
                    continue

                port = int(port.group(1))
                link[port] = get_xml_port_link_state(i)

            link = set_success_dict(link)

        except CalledProcessError as error:
            ocslog.log_exception()
            link = set_failure_dict(error.output.strip())

        except Exception as error:
            ocslog.log_exception()
            link = set_failure_dict(
                "get_all_port_link_state() Exception: {0}".format(error))

        return link
Exemple #6
0
def get_op_mode():
    """
    Get the operational mode of the rack manager.
    
    :return The rack manager mode.
    """

    try:
        precheck_binary = get_precheck_library()

        i = c_int()
        output = precheck_binary.get_rm_mode(byref(i))

        if (output == 0):
            manager_mode = rm_mode(i.value)
        else:
            manager_mode = rm_mode_enum.unknown_rm_mode

    except:
        ocslog.log_exception()
        manager_mode = rm_mode_enum.unknown_rm_mode

    return manager_mode
def run_pre_check(func, *args, **kwargs):
    """
    Execute a pre-check call for the request.  This call will only return if the pre-check was
    successful.  Otherwise, an exception will be thrown.
    
    :param func: The pre-check call to execute.
    :param args: Arguments that will be passed to the pre-check call.
    :param kwargs: Arguments that will be passed to the pre-check call.
    """

    try:
        output = func(*args, **kwargs)
        code = get_pre_check_status_code(output)
        if (code != 200):
            result = {}
            append_response_information(result, output)
            raise_status_response(code, result)

    except (HTTPResponse, HTTPError):
        raise

    except:
        ocslog.log_exception()
        raise HTTPError(status=500)
def validate_user (username, password):
    """
    Authenticate the user login credentials.
    
    :param username: The user name.
    :parem password: The password for the user.
    
    :return True if the user credentials have been authenticated.
    """
    
    try:
        auth_binary = get_authentication_library ()
            
        usr = c_char_p (username)
        psw = c_char_p (password)            
        auth = auth_binary.verify_authentication (usr, psw)  
    
        if auth == 0:
            return True
        else:
            return False
    except:
        ocslog.log_exception ()
        return False
def process_command(command):
    """
    Extract the command parameters and execute the command.
    
    :param command: The command being executed.
    """

    try:
        handler = COMMANDS.get(command.lower(), None)
        if (not handler):
            raise HTTPError(status=404)

        parameters = {}
        for name, value in request.query.iteritems():
            parameters[name.lower()] = value.lower()

        execute = handler(parameters)
        execute.pre_check()

        if (pre_check.get_mode() != rm_mode_enum.rowmanager):
            result = execute.get_response()
        else:
            result = execute.get_row_manager()
        result = result.format()[0]

        response.content_type = "application/xml"
        response.status = 200
        response.body = [ElementTree.tostring(result)]
        return response

    except (HTTPResponse, HTTPError):
        raise

    except:
        ocslog.log_exception()
        raise HTTPError(status=500)
Exemple #10
0
def server_start_serial_session(system_id, force = False):
    try:
        if(force == True):
            server_stop_serial_session(system_id)
              
        serverhost = get_hostname_by_serverid(system_id)
                
        if(serverhost == -1):
            return set_failure_dict("Failed to get hostname for server: {0}".format(system_id))
        
        username, password = get_server_access(1)
        
        if username is None:
            return set_failure_dict("Failed to get username for server: {0}".format(system_id))                   
                                    
        sshserverParams = '%s@%s' % (username, serverhost)
        sshpassParams = '-p%s' % (password)
        
        subprocess.check_call(["sshpass", sshpassParams, "ssh", "-o", "UserKnownHostsFile=/dev/null", "-o", 
                               "StrictHostKeyChecking=no", "-o", "LogLevel=ERROR", sshserverParams], stderr = subprocess.STDOUT)
                        
    except Exception, e: 
        ocslog.log_exception ()
        return (set_failure_dict("start_serial_session failed to connect.", completion_code.failure))
def route_system_request(system, path=""):
    view_helper.run_pre_check(pre_check.pre_check_blade_availability, system)

    ctrl = ""
    try:
        ctrl = controls.bladeinfo_lib.get_server_control_interface(system)[2]

    except Exception as error:
        ocslog.log_exception()
        return view_helper.return_status_response(
            500, "Failed to discover system control interface.")

    if (ctrl == "REST"):
        if (request.method == "GET"):
            view_helper.run_pre_check(pre_check.pre_check_function_call,
                                      command_name_enum.get_blade_state)
        else:
            view_helper.run_pre_check(pre_check.pre_check_function_call,
                                      command_name_enum.set_blade_config)

        try:
            return controls.restcmd_library.send_redfish_request(
                serverid=int(system),
                uri=request.path,
                method=request.method,
                data=request.body.read())

        except controls.restcmd_library.rest_http_error as error:
            ocslog.log_exception()
            raise HTTPError(status=error.status_code)

        except Exception as error:
            ocslog.log_exception()
            return view_helper.return_status_response(
                500, "Failed to query system REST interface.")
    else:
        route = redfish.systems_app.match(request.environ)
        return route[0].call(**route[1])
Exemple #12
0
def system_rackmanager_display(parameters):
    try:
        action_name = ''
        reset_type = ''
        boardname = ''
        server = ''
        manager = ''
        power = ''
        memory = ''
        sensor = ''
        rm_mode = ''
        port_id = -1
        starttime = -1
        endtime = -1
        startid = -1
        endid = -1 
        component = -1
        loglevel = -1
        deviceid = -1
        
        if 'action' in parameters.keys():
            action_name = parameters["action"]
            
        if 'starttime' in parameters.keys():
            starttime = parameters["starttime"]
        
        if 'endtime' in parameters.keys():
            endtime = parameters["endtime"]
            
        if 'startid' in parameters.keys():
            startid = parameters["startid"]
            
        if 'endid' in parameters.keys():
            endid = parameters["endid"]
            
        if 'component' in parameters.keys():
            component = parameters["component"]
            
        if 'loglevel' in parameters.keys():
            loglevel = parameters["loglevel"]
            
        if 'deviceid' in parameters.keys():
            deviceid = parameters["deviceid"]
            
        if 'port_id' in parameters.keys():
            port_id = int(parameters["port_id"])
        
        if 'boardname' in parameters.keys():
            boardname = parameters["boardname"]
        
        if 'server' in parameters.keys():
            server = parameters["server"]
        
        if 'manager' in parameters.keys():
            manager = parameters["manager"]
        
        if 'power' in parameters.keys():
            power = parameters["power"]
            
        if 'sensor' in parameters.keys():
            sensor = parameters["sensor"]
            
        if 'memory' in parameters.keys():
            memory = parameters["memory"]
            
        if 'rm_mode' in parameters.keys():
            rm_mode = parameters["rm_mode"]
            
        if action_name == 'info':
            if server == True and manager == False and power == False:
                result = server_info(rm_mode,True)
            elif server == False and manager == True and power == False:
                result = manager_info()
            elif server == False and manager == False and power == True:  
                result =   get_power_supply_objects()            
            else:
                result = get_rack_manager_info(rm_mode)
        elif action_name == 'health':
            if server == True and memory == False and power == False and sensor == False:
                result = server_info(rm_mode, False)
            elif server == False and memory == True and power == False and sensor == False:
                result = get_memory_details() 
            elif server == False and memory == False and power == True and sensor == False:  
                result =   get_power_supply_objects()
            elif server == False and memory == False and power == False and sensor == True:  
                result = get_sensor_objects_with_units()          
            else:
                result = get_rm_health(rm_mode)
        elif action_name == "relay":
            result = powerport_get_port_status(port_id, 'relay')      
        elif action_name == 'led':
            result = get_rack_manager_attention_led_status()
        elif action_name == 'version':
            result = get_ocsfwversion()
        elif action_name == "fru":
            result = read_fru(boardname)
        elif action_name == "type":
            result = show_rack_manager_type()
        elif action_name == "tftpstatus":
            result = manager_tftp_server_status()
        elif action_name == "tftplist":
            result = manager_tftp_server_listfiles()
        elif action_name == "nfsstatus":
            result = manager_nfs_server_status()
        elif action_name == "sessionlist":        
            result = manager_session_list()
        elif action_name == 'port':        
            if port_id == 0:
                result = powerport_get_all_port_status()
            else:
                result = powerport_get_port_status(port_id, 'pdu')            
        elif action_name == 'ntpstatus':
            result = get_rack_manager_ntp_status ()
        elif action_name == 'ntpserver':
            result = get_rack_manager_ntp_server ()
        elif action_name == 'itpstatus':
            result = get_rack_manager_itp_status ()
        elif action_name == 'log':
            result = get_rack_manager_log(telemetry_log_path, True, starttime, endtime, 
                                          startid, endid, loglevel, component, deviceid, port_id)
        elif action_name == 'inventory':
            result = manager_inventory(rm_mode)
        elif action_name == 'throttlelocal':
            result = get_manager_throttle_local_bypass ()
            if (result[completion_code.cc_key] == completion_code.success):
                result.update (get_manager_throttle_output_enable ())
        elif action_name == 'throttlerow':
            result = get_row_throttle_bypass ()
            if (result[completion_code.cc_key] == completion_code.success):
                result.update (get_row_throttle_output_enable ())
        elif action_name == 'bootstrap': # Row Manager bootstrap command
            result = powerport_get_row_boot_strap(port_id)
        elif action_name == "time":
            result = show_rack_manager_time()
        elif action_name == "scandevice":
            result = get_rack_manager_scandevice()
        elif action_name == "fwupdatestatus":
            result = show_rack_manager_fwupdate_status()
        elif action_name == "fwupdatelist":
            result = show_rack_manager_fwupdate_list()
        else:
            return set_failure_dict("Display command not implemented: {0}".format(action_name), completion_code.failure)
        
    except Exception, e:
        ocslog.log_exception()
        return set_failure_dict("system_rackmanager_display - Exception: {0}".format(e), completion_code.failure)