Esempio n. 1
0
 def do_set(self,commands):       
     """
     Execute ocscli set commands 
     usage:
         set group command <parameters>
         
     ---------------------------------------
      Supported groups
     ---------------------------------------
          1. network
          2. manager
          3. system
          4. user
          5. switch                                      
     """ 
     
     try:                  
         args = commands.split()
         command_args = args
          
         if len(command_args) == 0:
             ocsshell.do_help(self, "help")
                
         command = args[0].lower()  
         subcommand = ""
         
         if len(args) >1:
             command_args = args[1:]   
             subcommand = args[1].lower()
         
         if command in help_list:
             ocsshell.do_help(self, command)
         elif command == "user":
             user_Actions(command_args)      
         elif command in network_list:
             set_network_interface(command_args)
         elif subcommand == "power" and command in system_list and pre_settings.manager_mode == "ROWMANAGER":
                 return set_failure_dict("System commands not supported on Row-Manager", completion_code.failure)                                            
         elif command in system_list: 
             if pre_settings.manager_mode == "ROWMANAGER":
                 return set_failure_dict("System commands not supported on Row-Manager", completion_code.failure)
             system_set_commands(command_args)
         elif command in manager_list:
             if subcommand == "network":
                 set_network_interface(command_args[1:])
             else:    
                 rackmanager_parse_set_commands(command_args)
         elif command in switch_list:
             switch_set_commands(command_args)
         elif command =="-bash":
             ocsaudit_log_command("", cmd_type.type_shell, cmd_interface.interface_ocscli, 
                          "bash", command_args)
             openCommandShell("bash")
         else:
             ocsprint("Command not supported: %s\n" % command)
             ocsprint("Available categories:\n %s  "% '  \n '.join(map(str,self.groupslist)))
     except:            
         pass    
Esempio n. 2
0
class ocsshell(cmd.Cmd):
    """ OCS Shell Class
    """
    
    commandtypeslist = ['show', 'sh', 'set', 'start', 'stop', 'exit', 'wcscli', 'help']
    groupslist = ['version', 'user', 'network', 'system', 'manager', 'mte', 'switch', 'auxiliary'] 
    startlist = ['serial', 'mte', 'auxiliary']
    stoplist = ['serial', 'mte']   
 
    def __init__(self):
        # Call superclass constructor 
        cmd.Cmd.__init__(self, completekey='tab') 
        
        try:
            # Initialize log
            ocslog.initialize_log(ocslog.loglevel_t_enum.INFO_LEVEL)
            
        except Exception, e:
            print_response(set_failure_dict("Failed to initialize the log: {0}".format(e)))
                 
        #Get group_id
        permission_exitcode = pre_settings.verify_caller_permission() 
        
        if permission_exitcode != 0:
            print_response(set_failure_dict("Failed to verify caller permission, error code: {0}".format(permission_exitcode), 
                                            completion_code.failure))
            sys.exit(permission_exitcode)
               
        #Get mode type
        rm_mode = pre_settings.get_rm_mode()
        
        if rm_mode != 0:
            print_response(set_failure_dict("Failed to get rack manager mode, error code: {0}".format(rm_mode), 
                                            completion_code.failure))
            sys.exit(rm_mode)
            
        # Load configuration settings
        loadconfig.loadconfig()
        
        if len(sys.argv) > 1:
            mycmd = ''
           
            for arg in sys.argv[1:]:
                mycmd = mycmd + arg + " "
            
            mycmd = mycmd + "\n"
            self.cmdqueue.append(mycmd)
            self.cmdqueue.append("exit\n")
            
        # Change default prompt
        if loadconfig.prompt:
            self.changeprompt(loadconfig.prompt)    
Esempio n. 3
0
def apply_ip_address (address = None, mask = None, gateway = None, addr_type = None,
    save_args = True, args = dict ()):
    """
    Helper function to aggregate network device parameters and apply the settings.
    
    :param address: The IP address to assign to the network interface.
    :param mask: The subnet mask.
    :param gateway: A default gateway to set for the system.
    :param addr_type: The type of IP address being assigned.
    :param save_args: A flag indicating if the specified parameters should be saved or if the
    device should be configured.  When configuring the device, any unspecified parameters will be
    extracted from the argument aggreation.
    :param args: The aggregation of network parameters that will be updated when not applying the
    specified parameters.
    
    :return Result information for the configuration request.
    """
    
    result = {}
    
    if (save_args):
        if (address is not None):
            args["ip_address"] = address
        if (mask is not None):
            args["netmask"] = mask
        if (gateway is not None):
            args["gateway"] = gateway
        if (addr_type is not None):
            args["addr_type"] = addr_type
    else:
        if ("addr_type" in args):
            if (args["addr_type"] == enums.AddressOrigin.DHCP):
                if (("ip_address" in args) or ("netmask" in args) or ("gateway" in args)):
                    result = set_failure_dict (
                        "No IP address information can be specified when using DHCP.",
                        completion_code.failure)
                else:
                    result = ethernet_actions_results (
                        controls.manage_network.set_dhcp_interfaces ("eth0"))
            else:
                missing = []
                if ("ip_address" not in args):
                    missing.append ("Address")
                if ("netmask" not in args):
                    missing.append ("SubnetMask")
                if ("gateway" not in args):
                    missing.append ("Gateway")
                    
                if missing:
                    for param in missing:
                        view_helper.append_missing_parameter_error (result, param)
                else:
                    del args["addr_type"]
                    result = ethernet_actions_results (
                        controls.manage_network.set_static_interface ("eth0", **args))
        else:
            view_helper.append_missing_parameter_error (result, "AddressOrigin")
        
    return result
 def get_placeholder_status ():
     """
     Get a status object to act as a place holder for response objects that only have status
     based on their children.
     
     :return The status object.
     """
     
     return request_status (set_failure_dict (""))
Esempio n. 5
0
def get_expander_fru(expander_id):
    result = {}
    fru_name = 'STORAGEENCLOSURE' + str(expander_id)
    try:
        dbusctl = obmc_dbuslib.ObmcRedfishProviders()
        result = dbusctl.get_fru_info(fru_name)

    except Exception, e:
        return set_failure_dict(('Exception:', e), completion_code.failure)
Esempio n. 6
0
def get_id_led_state(expander_id):  #TBD
    result = {}

    try:
        dbusctl = obmc_dbuslib.ObmcRedfishProviders()
        pydata = dbusctl.power_control('state')

    except Exception, e:
        return set_failure_dict(('Exception:', e), completion_code.failure)
Esempio n. 7
0
 def __init__(self):
     # Call superclass constructor 
     cmd.Cmd.__init__(self, completekey='tab') 
     
     try:
         # Initialize log
         ocslog.initialize_log(ocslog.loglevel_t_enum.INFO_LEVEL)
         
     except Exception, e:
         print_response(set_failure_dict("Failed to initialize the log: {0}".format(e)))
Esempio n. 8
0
def get_storage_enclosure_power(expander_id):
    result = {}

    try:
        if (expander_id == 1):
            sensor_table = sensor_expander1_power_table
        elif (expander_id == 2):
            sensor_table = sensor_expander2_power_table
        elif (expander_id == 3):
            sensor_table = sensor_expander3_power_table
        elif (expander_id == 4):
            sensor_table = sensor_expander4_power_table
        else:
            print("Expander ID error!")
            return set_failure_dict(('Exception:', e), completion_code.failure)

        result['SE_ID'] = expander_id
        result['power_consumption'] = 0
        result['sensor_number'] = 0
        result['voltage_value'] = 0
        result['upper_critical_threshold'] = 0
        result['lower_critical_threshold'] = 0

        object = bus.get_object(DBUS_NAME,
                                sensor_table[2])  # HDD_HSC_Power_Out
        interface = dbus.Interface(object, DBUS_INTERFACE)

        scale = interface.Get(SENSOR_HWMON_INTERFACE, 'scale')
        adjust = interface.Get(SENSOR_HWMON_INTERFACE, 'adjust')
        value = interface.Get(SENSOR_VALUE_INTERFACE, 'value')

        result['power_consumption'] = value * math.pow(10, scale) / adjust

        object = bus.get_object(DBUS_NAME, sensor_table[3])  # HDD_HSC_Volt_Out
        interface = dbus.Interface(object, DBUS_INTERFACE)

        result['sensor_number'] = interface.Get(SENSOR_HWMON_INTERFACE,
                                                'sensornumber')

        scale = interface.Get(SENSOR_HWMON_INTERFACE, 'scale')
        value = interface.Get(SENSOR_VALUE_INTERFACE, 'value')

        result['voltage_value'] = value * math.pow(10, scale)

        result['upper_critical_threshold'] = interface.Get(
            SENSOR_THRESHOLD_INTERFACE, 'critical_upper')
        result['lower_critical_threshold'] = interface.Get(
            SENSOR_THRESHOLD_INTERFACE, 'critical_lower')

    except Exception, e:
        print "!!! DBus error !!!\n"
Esempio n. 9
0
def get_storage_enclosure_thermal(expander_id):
    result = {}
    result['SE_ID'] = expander_id
    result['temperatures'] = collections.OrderedDict()

    try:
        if (expander_id == 1):
            sensor_table = sensor_expander1_temperature_table
        elif (expander_id == 2):
            sensor_table = sensor_expander2_temperature_table
        elif (expander_id == 3):
            sensor_table = sensor_expander3_temperature_table
        elif (expander_id == 4):
            sensor_table = sensor_expander4_temperature_table
        else:
            print("Expander ID error!")
            return set_failure_dict(('Exception:', e), completion_code.failure)

        for index in range(0, len(sensor_table)):
            property = {}
            property['sensor_id'] = index + 1
            property['sensor_name'] = get_sensor_name(sensor_table[index])
            property['sensor_number'] = 0
            property['celsius'] = 0
            property['upper_critical_threshold'] = 0

            object = bus.get_object(DBUS_NAME, sensor_table[index])
            interface = dbus.Interface(object, DBUS_INTERFACE)

            properties = interface.GetAll(SENSOR_VALUE_INTERFACE)
            for property_name in properties:
                if property_name == 'value':
                    property['celsius'] = properties['value']

            property['upper_critical_threshold'] = interface.Get(
                SENSOR_THRESHOLD_INTERFACE, 'critical_upper')

            property['sensor_number'] = interface.Get(SENSOR_HWMON_INTERFACE,
                                                      'sensornumber')

            result['temperatures'][str(index)] = property

    except Exception, e:
        print "!!! DBus error !!!\n"
 def get_nic_list (mac):
     """
     Get the list of NIC information objects for the system.
     
     :param mac: The result of the system query for blade NIC information.
     
     :return A list contaning response objects for the NIC information.
     """
     
     nics = []
     if (mac):
         status = request_status (mac)
         nic1 = blade_nic_info (mac)
         nics.append (response_category ("NicInfo", status = status, results = [nic1]))
         
         if (check_success (mac)):
             status = request_status (set_failure_dict ("Not Present", "Success"))
             nic2 = blade_nic_info ()
             nics.append (response_category ("NicInfo", status = status, results = [nic2]))
                 
     return nics
Esempio n. 11
0
def execute_get_request_queries(query_list, init_values=dict()):
    """
    Handler for all get requests to query the system for necessary information.
    
    :param query_list: A list of functions to be called that will provide the information required
    for the request.  Each function is a pair that contains the function to call and dictionary of
    arguments.
    :param init_values: The initial set of response information.
    
    :return A dictionary containing the information for generating the response object.
    """

    result = init_values.copy()
    for query in query_list:
        try:
            query_data = query[0](**query[1])
            view_helper.append_response_information(result, query_data)

        except Exception as error:
            view_helper.append_response_information(
                result, set_failure_dict(str(error), completion_code.failure))

    return view_helper.replace_key_spaces(result)
Esempio n. 12
0
 def do_show(self, commands):       
     """
     Execute ocscli show commands 
     usage:
         show group command <parameters>
         
     --------------------------------------         
      Supported groups
     --------------------------------------
      1. network
      2. manager
      3. system
      4. user
      5. switch
      6. mte
      7. version
     """ 
     
     try:
         args = commands.split()        
         command_args = args
         
         if len(command_args) == 0:
             ocsshell.do_help(self, "help")                           
         
         command = args[0].lower() 
         subcommand = ""
         
         if len(args) > 1:
             command_args = args[1:] 
             subcommand = args[1].lower()
         
         if command in help_list:
             ocsshell.do_help(self, "help") 
         elif command in version_list:
             show_service_version()     
         elif command == "user":
             user_Actions(command_args)   
         elif command in network_list:
             if subcommand == "interface" or subcommand == "route":
                 show_network_properties(command_args)
             elif len(args) == 1:
                 show_all_interfaces()
             else:
                 ocsshell.do_help(self, "network")
         elif subcommand == "power" and command in system_list and pre_settings.manager_mode == "ROWMANAGER":
                 print("System commands are not supported on Row-Manager")
                 return
         elif command in manager_list:
             if subcommand == "network":
                 if len(command_args) == 1:
                     show_all_interfaces()
                 else:
                     show_network_properties(command_args[1:])
             else:
                 rackmanager_parse_show_commands(command_args)   
         elif command == "mte":
             if verify_caller_admin_permission():
                 show_mte()            
             else:
                 print "Access denied"           
         elif command in system_list: 
             if pre_settings.manager_mode == "ROWMANAGER":
                 return set_failure_dict("System commands not supported on Row-Manager", completion_code.failure)
             system_show_commands(command_args)                
         elif command in switch_list:
             switch_show_commands(command_args)
         elif command == "-bash":
             ocsaudit_log_command("", cmd_type.type_shell, cmd_interface.interface_ocscli, 
                          "bash", command_args)
             openCommandShell("bash")
         else:
             ocsprint("Command not supported: %s\n" % command)
             ocsprint("Available categories:\n %s  "% '  \n '.join(map(str,self.groupslist)))
     except:            
         pass    
Esempio n. 13
0
def execute_patch_request_actions(requested, action_map, tree=[]):
    """
    Handler for all patch requests to change system parameters based on received information.

    :param requested: A dictionary that contains the set of system parameters to change.
    :param action_map: A mapping of the function to call for each parameter that can be set.
    Each mapping contains a tuple that has a function pointer, parameter parser, and additional
    arguments that should be passed to the function.
    :param tree: The ancestry of the current set of request properties.

    :return A result dictionary to be used to generate the response.
    """
    result = {}
    if requested is not None:
        for param, value in requested.items():
            if ("@" not in param):
                try:
                    if (hasattr(value, "keys")):
                        parents = list(tree)
                        parents.append(param)

                        action_data = execute_patch_request_actions(value, action_map,
                                                                    tree=parents)
                        view_helper.append_response_information(result, action_data)
                    elif (isinstance(value, list)):
                        for i, entry in enumerate(value):
                            parents = list(tree)
                            parents.append(param)
                            parents.append("[{0}]".format(i))

                            action_data = execute_patch_request_actions(entry, action_map,
                                                                        tree=parents)
                            view_helper.append_response_information(result, action_data)
                            i = i + 1
                    else:
                        action = ""
                        if len(tree):
                            action = "/".join(tree) + "/"
                        action = action + param

                        if (action in action_map):
                            call = action_map[action]
                            args = call[2].copy()
                            try:
                                call[1].parse_parameter(value, args)

                            except TypeError as error:
                                view_helper.append_invalid_property_type(result,
                                                                         action.split("/"))
                                continue

                            except Exception as error:
                                view_helper.append_invalid_property_value(result,
                                                                          action.split("/"), str(error))
                                continue
                            action_data = call[0](**args)
                            view_helper.append_response_information(result, action_data)
                        else:
                            view_helper.append_read_only_property(result, action.split("/"))

                except Exception as error:
                    view_helper.append_response_information(
                        result, set_failure_dict(str(error), completion_code.failure))
    return result