Python logging.config.read() Examples

The following are 19 code examples of logging.config.read(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module logging.config , or try the search function .
Example #1
Source File: pyepm.py    From pyepm with MIT License 6 votes vote down vote up
def create_config(parser):
    options = parse_arguments(parser)

    # 1) read the default config at "~/.pyepm"
    config = c.read_config()

    # 2) read config from file
    cfg_fn = getattr(options, 'config')
    if cfg_fn:
        if not os.path.exists(cfg_fn):
            c.read_config(cfg_fn)  # creates default
        config.read(cfg_fn)

    # 3) apply cmd line options to config
    for section in config.sections():
        for a, v in config.items(section):
            if getattr(options, a, None) is not None:
                config.set(section, a, getattr(options, a))

    # set config_dir
    config_dir.set(config.get('misc', 'config_dir'))

    return config 
Example #2
Source File: config.py    From oneview-redfish-toolkit with Apache License 2.0 6 votes vote down vote up
def load_conf_file(conf_file):
    """Loads and parses conf file

        Loads and parses the module conf file

        Args:
            conf_file: string with the conf file name

        Returns:
            ConfigParser object with conf_file configs
    """

    if not os.path.isfile(conf_file):
        raise OneViewRedfishResourceNotFoundException(
            "File {} not found.".format(conf_file)
        )

    config = configparser.ConfigParser()
    config.optionxform = str
    try:
        config.read(conf_file)
    except Exception:
        raise

    return config 
Example #3
Source File: server_mgr_mon_base_plugin.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def handle_inventory_trigger(self, action=None, servers=None):
        self._smgr_log.log(self._smgr_log.INFO, "Inventory of added servers will not be read.")
        return "Inventory Parameters haven't been configured.\n" \
               "Reset the configuration correctly and restart Server Manager.\n" 
Example #4
Source File: util.py    From Adminset_Zabbix with Apache License 2.0 5 votes vote down vote up
def get_config(service_conf, section=''):
    config = ConfigParser.ConfigParser()
    config.read(service_conf)

    conf_items = dict(config.items('common')) if config.has_section('common') else {}
    if section and config.has_section(section):
       conf_items.update(config.items(section))
    return conf_items 
Example #5
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_enroll_token():
    config = configparser.ConfigParser()
    config.read(INI_PATH)
    return config['DEFAULT'].get('enroll_token') 
Example #6
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_ini_log_file():
    config = configparser.ConfigParser()
    config.read(INI_PATH)
    return config['DEFAULT'].get('log_file') 
Example #7
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_fallback_token():
    config = configparser.ConfigParser()
    config.read(INI_PATH)
    return config['DEFAULT'].get('fallback_token') 
Example #8
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def try_enroll_in_operation_mode(device_id, dev):
    enroll_token = get_enroll_token()
    if enroll_token is None:
        return
    logger.info("Enroll token found. Trying to automatically enroll the node.")

    setup_endpoints(dev)
    response = mtls_request('get', 'claimed', dev=dev, requester_name="Get Node Claim Info")
    if response is None or not response.ok:
        logger.error('Did not manage to get claim info from the server.')
        return
    logger.debug("[RECEIVED] Get Node Claim Info: {}".format(response))
    claim_info = response.json()
    if claim_info['claimed']:
        logger.info('The node is already claimed. No enrolling required.')
    else:
        claim_token = claim_info['claim_token']
        if not enroll_device(enroll_token, claim_token, device_id):
            logger.error('Node enrolling failed. Will try next time.')
            return

    logger.info("Update config...")
    config = configparser.ConfigParser()
    config.read(INI_PATH)
    config.remove_option('DEFAULT', 'enroll_token')
    with open(INI_PATH, 'w') as configfile:
        config.write(configfile)
    os.chmod(INI_PATH, 0o600) 
Example #9
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_device_id(dev=False):
    """
    Returns the WoTT Device ID (i.e. fqdn) by reading the first subject from
    the certificate on disk.
    """

    can_read_cert()

    with open(CLIENT_CERT_PATH, 'r') as f:
        cert = x509.load_pem_x509_certificate(
            f.read().encode(), default_backend()
        )

    return cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value 
Example #10
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_certificate_expiration_date():
    """
    Returns the expiration date of the certificate.
    """

    can_read_cert()

    with open(CLIENT_CERT_PATH, 'r') as f:
        cert = x509.load_pem_x509_certificate(
            f.read().encode(), default_backend()
        )

    return cert.not_valid_after.replace(tzinfo=pytz.utc) 
Example #11
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def can_read_cert():
    if not os.access(CLIENT_CERT_PATH, os.R_OK):
        logger.error('Permission denied when trying to read the certificate file.')
        exit(1)

    if not os.access(CLIENT_KEY_PATH, os.R_OK):
        logger.error('Permission denied when trying to read the key file.')
        exit(1) 
Example #12
Source File: data.py    From Faraday-Software with GNU General Public License v3.0 5 votes vote down vote up
def configureData(args, dataConfigPath):
    '''
    Configure Data configuration file from command line

    :param args: argparse arguments
    :param dataConfigPath: Path to data.ini file
    :return: None
    '''

    config = ConfigParser.RawConfigParser()
    config.read(os.path.join(path, "data.ini"))

    if args.flaskhost is not None:
        config.set('FLASK', 'HOST', args.flaskhost)
    if args.flaskport is not None:
        config.set('FLASK', 'PORT', args.flaskport)
    if args.proxyhost is not None:
        config.set('PROXY', 'HOST', args.proxyhost)
    if args.proxyport is not None:
        config.set('PROXY', 'PORT', args.proxyport)

    with open(dataConfigPath, 'wb') as configfile:
        config.write(configfile)


# Now act upon the command line arguments
# Initialize and configure Data 
Example #13
Source File: server_mgr_mon_base_plugin.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def parse_inventory_args(self, args_str, args, sm_args, _rev_tags_dict, base_obj):
        config = ConfigParser.SafeConfigParser()
        config.read([args.config_file])
        try:
            if dict(config.items("INVENTORY")).keys():
                # Handle parsing for monitoring
                inventory_args = self.parse_args(args_str, "INVENTORY")
                if inventory_args:
                    self._smgr_log.log(self._smgr_log.DEBUG, "Inventory arguments read from config.")
                    self.inventory_args = inventory_args
                else:
                    self._smgr_log.log(self._smgr_log.DEBUG, "No inventory configuration set.")
            else:
                self._smgr_log.log(self._smgr_log.DEBUG, "No inventory configuration set.")
        except ConfigParser.NoSectionError:
            self._smgr_log.log(self._smgr_log.DEBUG, "No inventory configuration set.")

        if self.inventory_args:
            try:
                if self.inventory_args.inventory_plugin:
                    module_components = str(self.inventory_args.inventory_plugin).split('.')
                    inventory_module = __import__(str(module_components[0]))
                    inventory_class = getattr(inventory_module, module_components[1])
                    if sm_args.collectors:
                        self.server_inventory_obj = inventory_class(sm_args.listen_ip_addr, sm_args.listen_port,
                                                                    sm_args.http_introspect_port, _rev_tags_dict)
                        self.inventory_config_set = True
                else:
                    self._smgr_log.log(self._smgr_log.ERROR,
                                       "Iventory API misconfigured, inventory aborted")
                    self.server_inventory_obj = base_obj
            except ImportError:
                self._smgr_log.log(self._smgr_log.ERROR,
                                   "Configured modules are missing. Server Manager will quit now.")
                raise ImportError
        else:
            self.server_inventory_obj = base_obj
        return self.server_inventory_obj 
Example #14
Source File: server_mgr_mon_base_plugin.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def parse_monitoring_args(self, args_str, args, sm_args, _rev_tags_dict, base_obj):
        config = ConfigParser.SafeConfigParser()
        config.read([args.config_file])
        try:
            if dict(config.items("MONITORING")).keys():
                # Handle parsing for monitoring
                monitoring_args = self.parse_args(args_str, "MONITORING")
                if monitoring_args:
                    self._smgr_log.log(self._smgr_log.DEBUG, "Monitoring arguments read from config.")
                    self.monitoring_args = monitoring_args
                else:
                    self._smgr_log.log(self._smgr_log.DEBUG, "No monitoring configuration set.")
            else:
                self._smgr_log.log(self._smgr_log.DEBUG, "No monitoring configuration set.")
        except ConfigParser.NoSectionError:
            self._smgr_log.log(self._smgr_log.DEBUG, "No monitoring configuration set.")
        if self.monitoring_args:
            try:
                if self.monitoring_args.monitoring_plugin:
                    module_components = str(self.monitoring_args.monitoring_plugin).split('.')
                    monitoring_module = __import__(str(module_components[0]))
                    monitoring_class = getattr(monitoring_module, module_components[1])
                    if sm_args.collectors:
                        self.server_monitoring_obj = monitoring_class(1, self.monitoring_args.monitoring_frequency,
                                                                      sm_args.listen_ip_addr,
                                                                      sm_args.listen_port, sm_args.collectors,
                                                                      sm_args.http_introspect_port, _rev_tags_dict)
                        self.monitoring_config_set = True
                else:
                    self._smgr_log.log(self._smgr_log.ERROR,
                                       "Analytics IP and Monitoring API misconfigured, monitoring aborted")
                    self.server_monitoring_obj = base_obj
            except ImportError as ie:
                self._smgr_log.log(self._smgr_log.ERROR,
                                   "Configured modules are missing. Server Manager will quit now.")
                self._smgr_log.log(self._smgr_log.ERROR, "Error: " + str(ie))
                raise ImportError
        else:
            self.server_monitoring_obj = base_obj
        return self.server_monitoring_obj 
Example #15
Source File: common.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_restful_params(urlstring):
    """Returns a dictionary of paired RESTful URI parameters"""
    parsed_path = urllib.parse.urlsplit(urlstring.strip("/"))
    query_params = urllib.parse.parse_qsl(parsed_path.query)
    path_tokens = parsed_path.path.split('/')

    # If first token is API version, ensure it isn't obsolete
    api_version = API_VERSION
    if len(path_tokens[0]) == 2 and path_tokens[0][0] == 'v':
        # Require latest API version
        if path_tokens[0][1] != API_VERSION:
            return None
        api_version = path_tokens.pop(0)

    path_params = list_to_dict(path_tokens)
    path_params["api_version"] = api_version
    path_params.update(query_params)
    return path_params

# this doesn't currently work
# if LOAD_TEST:
#     config = ConfigParser.RawConfigParser()
#     config.read(CONFIG_FILE)
#     TEST_CREATE_DEEP_QUOTE_DELAY = config.getfloat('general', 'test_deep_quote_delay')
#     TEST_CREATE_QUOTE_DELAY = config.getfloat('general','test_quote_delay')

# NOTE These are still used by platform init in dev in eclipse mode 
Example #16
Source File: common.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_config():
    global _CURRENT_CONFIG
    if _CURRENT_CONFIG is None:
        # read the config file
        _CURRENT_CONFIG = configparser.ConfigParser()
        _CURRENT_CONFIG.read(CONFIG_FILE)
    return _CURRENT_CONFIG 
Example #17
Source File: server_mgr_mon_base_plugin.py    From contrail-server-manager with Apache License 2.0 4 votes vote down vote up
def parse_args(self, args_str, section):
        # Source any specified config/ini file
        # Turn off help, so we print all options in response to -h
        conf_parser = argparse.ArgumentParser(add_help=False)

        conf_parser.add_argument(
            "-c", "--config_file",
            help="Specify config file with the parameter values.",
            metavar="FILE")
        args, remaining_argv = conf_parser.parse_known_args(args_str)

        if args.config_file:
            config_file = args.config_file
        else:
            config_file = _DEF_SMGR_CFG_FILE
        config = ConfigParser.SafeConfigParser()
        config.read([config_file])
        parser = argparse.ArgumentParser(
            # Inherit options from config_parser
            # parents=[conf_parser],
            # print script description with -h/--help
            description=__doc__,
            # Don't mess with format of description
            formatter_class=argparse.RawDescriptionHelpFormatter,
        )
        if section == "MONITORING":
            for key in dict(config.items("MONITORING")).keys():
                if key in self.MonitoringCfg.keys():
                    self.MonitoringCfg[key] = dict(config.items("MONITORING"))[key]
                else:
                    self._smgr_log.log(self._smgr_log.DEBUG, "Configuration set for invalid parameter: %s" % key)
            self._smgr_log.log(self._smgr_log.DEBUG,
                               "Arguments read from monitoring config file %s" % self.MonitoringCfg)
            parser.set_defaults(**self.MonitoringCfg)
        elif section == "INVENTORY":
            for key in dict(config.items("INVENTORY")).keys():
                if key in self.InventoryCfg.keys():
                    self.InventoryCfg[key] = dict(config.items("INVENTORY"))[key]
                else:
                    self._smgr_log.log(self._smgr_log.DEBUG, "Configuration set for invalid parameter: %s" % key)
            self._smgr_log.log(self._smgr_log.DEBUG,
                               "Arguments read from inventory config file %s" % self.InventoryCfg)
            parser.set_defaults(**self.InventoryCfg)
        return parser.parse_args(remaining_argv) 
Example #18
Source File: config.py    From oneview-redfish-toolkit with Apache License 2.0 4 votes vote down vote up
def load_config(conf_file):
    """Loads redfish.conf file

        Loads and parsers the system conf file into config global var
        Loads json schemas into schemas_dict global var
        Established a connection with OneView and sets in as ov_conn
        global var

        Args:
            conf_file: string with the conf file name

        Returns:
            None

        Exception:
            HPOneViewException:
                - if fails to connect to oneview
    """

    config = load_conf_file(conf_file)
    globals()['config'] = config

    # Config file read set global vars
    # Setting ov_config
    # ov_config = dict(config.items('oneview_config'))
    # ov_config['credentials'] = dict(config.items('credentials'))
    # ov_config['api_version'] = API_VERSION
    # globals()['ov_config'] = ov_config

    util.load_event_service_info()

    # Load schemas | Store schemas
    try:
        for ip_oneview in get_oneview_multiple_ips():
            connection.check_oneview_availability(ip_oneview)

        registry_dict = load_registry(
            get_registry_path(),
            schemas.REGISTRY)
        globals()['registry_dict'] = registry_dict

        load_schemas(get_schemas_path())
    except Exception as e:
        raise OneViewRedfishException(
            'Failed to connect to OneView: {}'.format(e)
        ) 
Example #19
Source File: simpleui.py    From Faraday-Software with GNU General Public License v3.0 4 votes vote down vote up
def configureSimpleUI(args):
    '''
    Configure SimpleUI configuration file from command line

    :param args: argparse arguments
    :return: None
    '''

    config = ConfigParser.RawConfigParser()
    config.read(os.path.join(faradayHelper.path, configFile))

    if args.callsign is not None:
        config.set('SIMPLEUI', 'CALLSIGN', args.callsign)
    if args.nodeid is not None:
        config.set('SIMPLEUI', 'NODEID', args.nodeid)
    if args.cmdlocalcallsign is not None:
        config.set('SIMPLEUI', 'LOCALCALLSIGN', args.cmdlocalcallsign)
    if args.cmdlocalnodeid is not None:
        config.set('SIMPLEUI', 'LOCALNODEID', args.cmdlocalnodeid)
    if args.cmdremotecallsign is not None:
        config.set('SIMPLEUI', 'REMOTECALLSIGN', args.cmdremotecallsign)
    if args.cmdremotenodeid is not None:
        config.set('SIMPLEUI', 'REMOTENODEID', args.cmdremotenodeid)
    if args.flaskhost is not None:
        config.set('FLASK', 'HOST', args.flaskhost)
    if args.flaskport is not None:
        config.set('FLASK', 'PORT', args.flaskport)
    if args.proxyhost is not None:
        config.set('PROXY', 'HOST', args.proxyhost)
    if args.proxyport is not None:
        config.set('PROXY', 'PORT', args.proxyport)
    if args.telemetryhost is not None:
        config.set('TELEMETRY', 'HOST', args.telemetryhost)
    if args.telemetryport is not None:
        config.set('TELEMETRY', 'PORT', args.telemetryport)

    filename = os.path.join(faradayHelper.path, configFile)
    with open(filename, 'wb') as configfile:
        config.write(configfile)


# Now act upon the command line arguments
# Initialize and configure SimpleUI