Example #1
0
    def get_config(self):
        config = ConfigParser.ConfigParser()
        config.read(NICOCOMMENT_CONFIG)
        mail = config.get("nicoalert", "mail")
        password = config.get("nicoalert", "password")

        return mail, password
Example #2
0
	def __init__(self, path):
		config = configparser.ConfigParser(interpolation=None)
		config.read(path)

		fallback = None
		if "DEFAULT" in config:
			if "fallback" in config["DEFAULT"]:
				fallback_path = os.path.join(
					os.path.dirname(path),
					config["DEFAULT"]["fallback"]
				)
				fallback = configparser.ConfigParser()
				fallback.read(fallback_path)
		self.smtp = SmtpConfig(Config.get_params(config, fallback, "SMTP"))
		self.bug_report = BugReportConfig(Config.get_params(config, fallback, "BUG_REPORT"))
		self.parser = ParserConfig(Config.get_params(config, fallback, "PARSER"))
		self.www = WwwConfig(Config.get_params(config, fallback, "WWW"))

		self.version = subprocess.check_output(
			"git log | "
			"head -n 1 | "
			"cut -f 2 -d ' '",
			shell=True
		).decode().strip()

		cfg_basename = os.path.basename(path)
		m = const.CONFIG_REGEXP.match(cfg_basename)
		if m is None:
			raise ValueError("Config basename {basename} doesn't match CONFIG_REGEXP".format(
				basename=cfg_basename
			))
		self.working_mode = WorkingMode(m.group("mode"))
def main():
    args = parse_args()

    logging.config.fileConfig(args.config[0])

    config = MyConfigParser(allow_no_value=True)
    config.read(args.config[0])

    update_config(config, args)

    signal.signal(signal.SIGTERM, sigterm_handler)

    if config.getboolean('general', 'daemon'):
        daemonize(config.get('general', 'logfile'))

    write_pidfile(config.get('general', 'pidfile'))

    try:
        run_workers(config)
    except (KeyboardInterrupt, SystemExit):
        sys.exit(2)
    except Exception as e:
        logger.exception("%s %s", type(e).__name__, str(e))
        sys.exit(1)

    logger.info("Leave main")
    return 0
Example #4
0
def load_configuration(configuration_file):
    config = ConfigParser.ConfigParser()
    config.read(configuration_file)

    section = 'news'
    source_screen_names = config.get(section, 'source_screen_names').split(',')
    polling_interval = int(config.get(section, 'polling_interval'))

    last_names = unicode(config.get(section, 'last_names'), 'utf-8').split(',')
    first_names = unicode(config.get(section, 'first_names'), 'utf-8').split(',')

    if len(last_names) != len(first_names):
        raise Exception(u"invalid name parameter length.")

    names = []
    for index in xrange(len(last_names)):
        names.append((last_names[index], first_names[index]))

    consumer_key = config.get(section, 'consumer_key')
    consumer_key = config.get(section, 'consumer_key')
    consumer_secret = config.get(section, 'consumer_secret')
    access_key = config.get(section, 'access_key')
    access_secret = config.get(section, 'access_secret')

    dry_run = config.getboolean(section, 'dry_run')

    return (source_screen_names, polling_interval, names,
            consumer_key, consumer_secret, access_key, access_secret, dry_run)
Example #5
0
def main():
    parser = OptionParser('usage: %prog [options] task')
    parser.add_option("-f", "--config-file", dest='config_file',
        help="Configuration file")
    options, args = parser.parse_args()

    if not (options.config_file):
        parser.error("Please specify a configuration file.")

    logging.config.fileConfig(options.config_file)
    config = ConfigParser()
    config.read(options.config_file)

    session = get_session(config)
    today = date.today()

    entries = session.query(TimeEntry).filter(
        not_(TimeEntry.task.like('Aura %'))).filter(
        or_(TimeEntry.comment == None, TimeEntry.comment == '')).filter(
        TimeEntry.start_dt >= today).filter(
        TimeEntry.start_dt <= (today + timedelta(days=1)))

    grouped_entries = group_entries(entries)

    if grouped_entries:
        print 'Following Non-Aura entries require annotations:'
        print_alerts(session, grouped_entries)
        email_offenders(session, grouped_entries)
Example #6
0
def launch(hardware):
    from hedgehog.server.hardware.simulated import SimulatedHardwareAdapter
    simulator = hardware == SimulatedHardwareAdapter

    args = parse_args(simulator)

    if args.logging_conf:
        logging.config.fileConfig(args.logging_conf)

    if simulator and args.simulate_sensors:
        _hardware = hardware

        def hardware(*args, **kwargs):
            return _hardware(*args, simulate_sensors=True, **kwargs)

    config = configparser.ConfigParser()
    config.read(args.config_file)

    if args.scan_config and os.path.isfile(args.scan_config_file):
        scan_config = configparser.ConfigParser()
        scan_config.read(args.scan_config_file)

        apply_scan_config(config, scan_config)

        with open(args.config_file, mode='w') as f:
            config.write(f)

    port = args.port or config.getint('default', 'port', fallback=0)

    with suppress(KeyboardInterrupt):
        start(hardware, port)
    def parse_args(self, args_str):
        # 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])
        for key in dict(config.items("MONITORING")).keys():
            if key in self.MonitoringCfg.keys():
                self.MonitoringCfg[key] = dict(config.items("MONITORING"))[key]
            else:
                self.log(self.DEBUG, "Configuration set for invalid parameter: %s" % key)

        self.log(self.DEBUG, "Arguments read form monitoring config file %s" % self.MonitoringCfg)
        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,
        )
        parser.set_defaults(**self.MonitoringCfg)
        self._collectors_ip = self.MonitoringCfg['collectors']
        return parser.parse_args(remaining_argv)
Example #8
0
def main():
    #signal.signal(signal.SIGINT, lambda : sys.exit(0))
    #signal.signal(signal.SIGTERM, lambda : sys.exit(0))

    logging.config.fileConfig("../conf/seed_log.conf")
    conf = dict(address="localhost", port=10010, db_name="news_crawler")
    queue_service = BlockingQueueService(100)
    handler = SeedHandler(queue_service)
    scheduler = SeedScheduler('background', handler, conf)
    scheduler.start()

    reactor = HttpReactor()
    config = ConfigParser.ConfigParser()
    config.read('../conf/url_dedup.conf')
    hubserver = HubServer(reactor, queue_service, config)
    t = threading.Thread(target=hubserver.start)
    t.daemon = True
    t.start()

    url = "http://roll.news.sina.com.cn/s/channel.php?ch=01#col=89&spec=&type=&ch=01&k=&offset_page=0&offset_num=0&num=60&asc=&page=1"
    url = "http://www.163.com/"
    for _ in xrange(2):
        queue_service.put(SeedTask(url), 1)
    hubserver.process_task(url)
    reactor.run()
Example #9
0
 def __init__(self, config_file):
     print "Using config file '%s'" % config_file
     # init python logging
     logging.config.fileConfig(config_file)
     # create a logger
     self._log = logging.getLogger("moniteur")
     # Load the config file
     config = ConfigParser.SafeConfigParser()
     config.read(config_file)
     # store settings
     self.settings = dict(config.items("moniteur"))
     self._log.info("Settings: %s" % self.settings)
     
     # Load the notifier configuration
     notifier_file = self.settings['notifier_config']
     self._log.debug("Loading notifier definition from '%s'" % notifier_file)
     if not os.access(notifier_file, os.R_OK):
         m = "Unable to load tests configuration file: '%s'" %  notifier_file
         self._log.error(m)
         raise Exception(m)
     notifier_config = ConfigParser.SafeConfigParser()
     notifier_config.read(notifier_file)
     
     self._notifier = Notifier(self.settings, notifier_config)
     
     # Init thread
     threading.Thread.__init__(self)
def load_config(app):
    ''' Reads the config file and loads configuration properties
    into the Flask app.
    :param app: The Flask app object.
    '''

    # Get the path to the application directory,
    # that's where the config file resides.
    par_dir = os.path.join(__file__, os.pardir)
    par_dir_abs_path = os.path.abspath(par_dir)
    app_dir = os.path.dirname(par_dir_abs_path)

    # Read config file
    # FIXME: Use the "common pattern" described in "Configuring from Files":
    # http://flask.pocoo.org/docs/config/
    config = ConfigParser.RawConfigParser()
    config_filepath = app_dir + '/config.cfg'
    config.read(config_filepath)

    # Set up config properties
    app.config['SERVER_PORT'] = config.get('Application', 'SERVER_PORT')
    app.config['BASE_PATH'] = config.get('Application', 'BASE_PATH')

    app.config['API_ELECTION_RESULTS'] = config.get('Api', 'ELECTION_RESULTS')

    # Logging path might be relative or starts from the root.
    # If it's relative then be sure to prepend the path with
    # the application's root directory path.
    log_path = config.get('Logging', 'PATH')
    if log_path.startswith('/'):
        app.config['LOG_PATH'] = log_path
    else:
        app.config['LOG_PATH'] = app_dir + '/' + log_path

    app.config['LOG_LEVEL'] = config.get('Logging', 'LEVEL').upper()
def get_config(config_file=None, server=None):
    logger.info("Getting config from config file %s" % config_file)
    if config_file is None:
        config_file = '/home/minecraft/minecraft/pyredstone.cfg'
    if not os.path.exists(config_file):
        raise IOError("Could not open config file")
    config = ConfigParser.ConfigParser()
    config.read(config_file)

    if server is None:
        try:
            sections = config.sections()
            logger.debug(sections)
            if len(sections) < 1:
                raise SyntaxError("No sections found in config file")
            elif len(sections) > 1:
                logger.warning("More than one server found, no server specified. Using first server.")
            server = sections[0]
        except ConfigParser.Error as e:
            logger.exception("Could not get sections")
    if not config.has_section(server):
        raise SyntaxError("Server section '%s' of config file does not exist. Cannot continue." % (server, ))

    # Now we have a config file and a section.
    data = {}
    try:
        # Take each item in the config file section and dump into a dict
        for item in config.items(server):
            data[item[0]] = item[1]
        logger.info("Config data: %s" % str(data))
    except ConfigParser.Error as e:
        raise SyntaxError("Config file is improperly formated")
    return data
Example #12
0
def WakeUp():
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")

    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return

    config.read(configFilename)
    wake = int(config.get("WakeOnLan", "wake"))
    if wake == 0: # just return if we don't need to wake anything.
        return
    Logger.info("Loading WakeOnLan config from %s", configFilename)
    config.get("WakeOnLan", "host")
    host = config.get("WakeOnLan", "host")
    port = int(config.get("WakeOnLan", "port"))
    mac = config.get("WakeOnLan", "mac")

    i=1
    while TestCon(host, port) == "Down" and i < 4:
        Logger.info("Sending WakeOnLan Magic Packet for mac: %s", mac)
        WakeOnLan(mac)
        time.sleep(20)
        i=i+1

    if TestCon(host,port) == "Down": # final check.
        Logger.warning("System with mac: %s has not woken after 3 attempts. Continuing with the rest of the script.", mac)
    else:
        Logger.info("System with mac: %s has been woken. Continuing with the rest of the script.", mac)
def get_parameters():
    current_directory = os.path.dirname(os.path.realpath(__file__))
    import ConfigParser
    config = ConfigParser.ConfigParser()
    config.read(os.path.join(current_directory, "configuration.ini"))

    return config
Example #14
0
    def readConfig(self, config_file="config.cfg"):
        """Carga la configuracuion"""
        try:
            config = ConfigParser.ConfigParser()
            config.read([RUTA_CONFIGURACION])
            # Paths
            self.accesslog = config.get("Paths", "accesslog")
            self.accessloghistoricos = config.get("Paths",
                    "accesslog_historicos")
            # lista
            self.ipallowed = config.get("Paths",
                    "ipallowed").strip().split(",")
            # lista
            self.dnsallowed = config.get("Paths",
                    "dnsallowed").strip().split(",")
            self.rta_ip_baneados = config.get("Paths", "ip_baneados").strip()
            self.rta_dns_baneadas = config.get("Paths", "dns_baneadas").strip()

            self.dbfile = config.get("Paths", "dbfile")
            self.logconfig = config.get("Paths", "logconfig", "")
            # Settings
            self.escanearhistoricos = config.get("Settings",
                    "escanear_historicos")

            # Times
            self.register_interval = int(config.get("Times",
                "intervalo_de_registro"))
            self.max_inactivity = int(config.get("Times",
                "tiempo_inactividad_usuario"))
        except:
            sys.stderr.write("No fue posible leer archivo de configuracion {}"
                .format(config_file))
            raise
Example #15
0
    def main(cls):
        """Dispatcher entry point."""

        options = parse_cmdline({"pidfile": cls.pidfile})

        # configure logging
        logging.config.fileConfig(options.config,
                                  disable_existing_loggers=False)

        config = ConfigParser()
        config.read(options.config)

        daemon_obj = cls(config)

        context = daemon.DaemonContext()

        context.pidfile = PidFile(options.pidfile)
        if options.foreground:
            context.detach_process = False
            context.stdout = sys.stdout
            context.stderr = sys.stdout

        context.signal_map = {
            signal.SIGTERM: daemon_obj.cleanup,
            signal.SIGHUP: daemon_obj.cleanup
        }

        with context:
            daemon_obj.run()
Example #16
0
def _main():
    config = ConfigParser.ConfigParser({'server_password': None})
    config.read(sys.argv[1])
    setup_logging(config)

    fp = config.get('ircbot', 'channel_config')
    if fp:
        fp = os.path.expanduser(fp)
        if not os.path.exists(fp):
            raise Exception("Unable to read layout config file at %s" % fp)
    else:
        raise Exception("Channel Config must be specified in config file.")

    channel_config = ChannelConfig(yaml.load(open(fp)))

    bot = GerritBot(channel_config.channels,
                    config.get('ircbot', 'nick'),
                    config.get('ircbot', 'pass'),
                    config.get('ircbot', 'server'),
                    config.getint('ircbot', 'port'),
                    config.get('ircbot', 'server_password'))
    g = Gerrit(bot,
               channel_config,
               config.get('gerrit', 'host'),
               config.get('gerrit', 'user'),
               config.getint('gerrit', 'port'),
               config.get('gerrit', 'key'))
    g.start()
    bot.start()
Example #17
0
def run():
    import sys
    if len(sys.argv) < 2:
        filename = "/etc/keyserver-ng/config.ini"
    else:
        filename = sys.argv[1]
    config = configparser.ConfigParser()
    config.read(filename)
    log_cfg = config["logging"]
    LOGGING["handlers"]["file"]["level"] = log_cfg["level"]
    LOGGING["handlers"]["file"]["filename"] = log_cfg["file"]
    LOGGING["handlers"]["file"]["maxBytes"] = int(log_cfg["rotate_bytes"])
    LOGGING["handlers"]["console"]["level"] = log_cfg["console_level"]
    if not config.getboolean("logging", "log_console"):
        LOGGING["loggers"][""]["handlers"] = ["file"]

    logging.config.dictConfig(LOGGING)

    db_module = importlib.import_module(config["database"]["module"])
    db = db_module.DB(**config["database"])
    server = hkp.Server(db)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(
            server.start(loop,
                         host=config["keyserver"]["listen_addr"],
                         port=config["keyserver"]["listen_port"],
                         )
    )
    loop.run_forever()
Example #18
0
def get_setting(setting, default=None):
    config = configparser.SafeConfigParser()
    try:
        config.read(CONFIG_FILE)
        return config.get('transfers', setting)
    except Exception:
        return default
Example #19
0
 def _loadConfig(self):
     def writeDefaultConfig(config):
         config.add_section('STORAGE')
         storageConfig                   = config['STORAGE']
         storageConfig['data_path']      = 'data/storage/'
         config.add_section('SCHEDULER')
         config.add_section('TASK_MANAGER')
         config.add_section('INTERFACE')
         config.add_section('CONTRACTOR')
         config.add_section('ENTITY_MANAGER')
         interfaceConfig                 = config['INTERFACE']
         interfaceConfig['xmlrpc_server_addr'] = 'localhost'
         interfaceConfig['xmlrpc_server_port'] = '8000' 
         config.add_section('LOGGING')
         loggingConfig                   = config['LOGGING']
         loggingConfig['file']           = CONFIG_PATH + '/logging.conf'
         
         if not os.path.exists(CONFIG_PATH):
             os.makedirs(CONFIG_PATH)        
         
         with open(CONFIG_FILE,'w') as configFile:        
             config.write(configFile)
     
     self._config  = configparser.ConfigParser()
     config = self._config     
     config.read(CONFIG_FILE)
     self._corelogger.info('load configuration')
     if len(config.sections()) < 1:
         self._corelogger.info('write default configuration to file')
         writeDefaultConfig(config)            
     logging.config.fileConfig(config['LOGGING']['file'])
Example #20
0
    def get_configparser_config(self, *args, **kwargs):

        # change it to take filename with path
        self.filename = kwargs.get('filename', None)
        self.use_override = kwargs.get('use_override', False)
        self.use_full_path = kwargs.get('use_full_path', False)
        self.section = kwargs.get('section', None)

        try:
            if not self.default_config_file:
                default_config_file = os.path.join(__file__[:__file__.rfind('lib')], 'config', self.filename)
            conf_file = None
            # override
            if self.use_override and os.path.exists(os.path.join(os.getenv("HOME"), 'config', self.filename)):
                conf_file = os.path.join(os.getenv("HOME"), 'config', self.filename)
            elif self.use_full_path and os.path.exists(self.filename):
                conf_file = self.filename
            elif default_config_file is not None and os.path.exists(default_config_file):
                conf_file = default_config_file
            if conf_file is not None:
                config = ConfigParser.SafeConfigParser()
                config.read(self.propertiesFile)
                propertiesDict = dict(config._sections[self.section], raw=True)
            return propertiesDict
        except:
            print "Error loading configparser config: ", sys.exc_info()[0]
            raise
Example #21
0
def converto_to_ascii(nzbName, dirName):
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")
    if not os.path.isfile(configFilename):
        Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
        return nzbName, dirName
    config.read(configFilename)
    ascii_convert = int(config.get("ASCII", "convert"))
    if ascii_convert == 0 or os.name == 'nt': # just return if we don't want to convert or on windows os and "\" is replaced!.
        return nzbName, dirName
    
    nzbName2 = str(nzbName.decode('ascii', 'replace').replace(u'\ufffd', '_'))
    dirName2 = str(dirName.decode('ascii', 'replace').replace(u'\ufffd', '_'))
    if dirName != dirName2:
        Logger.info("Renaming directory:%s  to: %s.", dirName, dirName2)
        shutil.move(dirName, dirName2)
    for dirpath, dirnames, filesnames in os.walk(dirName2):
        for filename in filesnames:
            filename2 = str(filename.decode('ascii', 'replace').replace(u'\ufffd', '_'))
            if filename != filename2:
                Logger.info("Renaming file:%s  to: %s.", filename, filename2)
                shutil.move(filename, filename2)
    nzbName = nzbName2
    dirName = dirName2
    return nzbName, dirName
def set_config(options, verbosity=0, database=None):
    """Read configuration options from file, merge them with command line
    options.

    :Parameters:
        - 'options': command line options.
        - 'verbosity': verbosity level, int.
        - 'database': output database name.

    :Return:
        - 'verbosity': verbosity level, int.
        - 'database': output database name, string.
    """
    try:
        if options.config:
            config = ConfigParser.ConfigParser()
            config.read(options.config)
            verbosity = config.get('task1', 'verbosity')
            database = config.get('base', 'database')

        if options.verbose:
            verbosity = int(options.verbose)
        if options.database:
            database = options.database

        return verbosity, database

    except (ConfigParser.Error, Exception) as err:
        raise MyError('Configuration error: %s' % err)
def initialise():
	logging.config.fileConfig(path + '/logging.cfg')
	logging.debug('> Start: initialise()')
	global config
	config = ConfigParser.ConfigParser()
	config.read(path + '/camera.cfg')
	logging.debug('> End: initialise()')
Example #24
0
def merge_configs(files):
    """merge into a single one multiple config files
    :param files:
    """

    config = ConfigParser.SafeConfigParser()
    config.read(files)
    try:
        try:
            master = config.get('logging', 'master')
            try:
                list_file = ConfigFileList.from_configobj(config)
                list_file.extend(files)
                list_file.append_master(master)
            except ConfigParser.NoOptionError:
                list_file = ConfigFileList(list(files))
                list_file.append_master(master)
        except ConfigParser.NoOptionError:
            try:
                list_file = ConfigFileList.from_configobj(config)
                list_file.extend(files)
            except ConfigParser.NoOptionError:
                list_file = files
        config = ConfigParser.SafeConfigParser()
        config.read(list_file)
    except ConfigParser.NoSectionError:
        pass

    return config
Example #25
0
    def load_ini(self, config_path, defaults=None):
        """Set options from config.ini file in given home_dir

        Parameters:
            config_path:
                directory or file name of the config file.
                If config_path is a directory name, use default
                base name of the config file
            defaults:
                optional dictionary of defaults for ConfigParser

        Note: if home_dir does not contain config.ini file,
        no error is raised.  Config will be reset to defaults.

        """
        if os.path.isdir(config_path):
            home_dir = config_path
            config_path = os.path.join(config_path, self.INI_FILE)
        else:
            home_dir = os.path.dirname(config_path)
        # parse the file
        config_defaults = {"HOME": home_dir}
        if defaults:
            config_defaults.update(defaults)
        config = ConfigParser.ConfigParser(config_defaults)
        config.read([config_path])
        # .ini file loaded ok.
        self.HOME = home_dir
        self.filepath = config_path
        self._adjust_options(config)
        # set the options, starting from HOME
        self.reset()
        for option in self.items():
            option.load_ini(config)
Example #26
0
def configure(conf_fn="conf/feedspool.conf"):
    """Read in the config file and initialize a few things."""
    global config, log, main_log, db_uri, so_conn, db_conn, plugin_manager
    
    # Read in config file
    config = ConfigParser()
    config.read(conf_fn)

    # Set up logging
    logging.config.fileConfig(conf_fn)
    log      = logging.getLogger("%s"%__name__)
    main_log = logging.getLogger("")

    # Set up some app-wide settings & instances
    data_root = alt('data', 'root', 'data')

    # HACK: Coerce HTTPCache to stuff things away in our data directory
    import httpcache
    httpcache.cacheSubDir__ = os.path.join(data_root, "httpcache")
    if not os.path.exists(httpcache.cacheSubDir__):
        os.mkdir(httpcache.cacheSubDir__)

    # Load up plugins
    plugins_root = alt('global', 'plugins', 'plugins')
    plugin_manager = PluginManager(plugins_root)

    log.debug("Configuration complete.")
Example #27
0
def openLogConfig(fileName):
    config = ConfigParser.RawConfigParser()
    try:
      config.read(fileName)
    except:
      pass
    return config
Example #28
0
def load_config(config_file):
    logging.config.fileConfig(config_file, disable_existing_loggers=False)

    config = ConfigParser.RawConfigParser()
    config.read([config_file])

    return config
def main():
    home = os.path.dirname(os.path.abspath(__file__))
    os.chdir(home)

    config = ConfigParser.RawConfigParser()
    config.read('application.conf')
    out_dir = config.get('application', 'out_dir')
    timeout = float(config.get('application', 'timeout'))
    boxes = json.loads(config.get('application', 'boxes_json'))

    logging.config.fileConfig('logging.conf')

    setup_encoding()

    for box in boxes:
        host = box['host']
        username = box['username']
        password = box['password']

        try:
            logging.info('Processing %s', host)
            api = connect(host=host, username=username, password=password, timeout=timeout)
            entries = api(cmd='/ip/arp/print')
            api.close()
            data = set([(entry['mac-address'], entry['interface']) for entry in entries if 'mac-address' in entry])
            file_name = datetime.now().strftime('%Y%m%d%H%M%S') + '-' + host + '.gz'
            file_path = os.path.join(out_dir, file_name)
            with gzip.open(file_path, 'wb') as file:
                for obj in data:
                    file.write(' '.join(obj) + '\n')
            logging.info('%s done', host)
        except:
            _, exc_value, _ = sys.exc_info()
            logging.error(exc_value)
Example #30
0
def main():
    home_dir = os.path.expanduser('~')
    program_dir = os.path.abspath(os.path.join(home_dir, '.dbackups'))
    db_config_file = os.path.join(program_dir, 'databases.ini')

    if not os.path.isdir(os.path.join(BASE_DIR, '../logs')):
        os.mkdir(os.path.join(BASE_DIR, '../logs'))

    if not os.path.isfile(db_config_file):
        print('Config File not found. {}'.format(db_config_file))
        sys.exit(1)

    #logging_config = resource_filename(__name__, '../config/logging.ini')
    #logging.config.fileConfig(logging_config)

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-6s line %(lineno)-4s %(message)s')

    args = parser.parse_args()
    pprint(args)
    config = ConfigParser.ConfigParser()
    config.read(db_config_file)

    logging.debug(config.sections())

    if not config.has_section(args.database):
        logging.info('DB alias not found in the config file {} -> [{}]'.format(db_config_file, args.database))
        sys.exit(1)
    else:
        logging.info('Found the DB settings in the config file. Continuing.')
        db_type = config.get(args.database, 'db_type')
        db_host = config.get(args.database, 'db_host')
        db_user = config.get(args.database, 'db_user')
        db_pass = config.get(args.database, 'db_pass')
        db_port = config.get(args.database, 'db_port')
        db_name = config.get(args.database, 'db_name')

    db_object = get_database_object(db_type, db_host, db_name, db_user, db_pass, db_port)
    logging.debug('DB object created: {}'.format(db_object))

    if args.command == 'backup':
        logging.info('Chose to backup {}'.format(db_object.db_host))
        logging.info('Dump file: [{}]'.format(db_object.dump_file_name))
        db_object.dump()
        logging.info('Dumping DB finished.')
        if args.upload_url:
            print('Uploading to the desired URL: {}'.format(args.upload_url))
            upload_http_put(db_object.dump_file, args.upload_url)

    if args.command == 'clone':
        logging.info('Going to clone_to from one DB to another.')
        dev_db = get_database_object(db_type, args.dev_host, args.dev_name, args.dev_user, args.dev_pass,
                                     args.dev_port)
        db_object.clone_to(dev_db, args.latest_local)

    if args.command == 'clean':
        logging.info('Cleaning the dumps directory to make room for more dumps.')
        file_list = cleanup_backups.find_files_for_delete(db_object.get_dump_dir(), db_object.db_host,
                                                          db_object.db_name)
        cleanup_backups.delete_file_list(file_list)
Example #31
0
    def get_config(self):
        config = ConfigParser.ConfigParser()
        config.read(NICOBBS_CONFIG)
        if config.get("nicobbs", "dry_run").lower() == "true":
            dry_run = True
        else:
            dry_run = False
        mail = config.get("nicobbs", "mail")
        password = config.get("nicobbs", "password")
        database_name = config.get("nicobbs", "database_name")
        target_community = config.get("nicobbs", "target_community")
        ng_words = config.get("nicobbs", "ng_words")
        if ng_words == '':
            ng_words = []
        else:
            ng_words = ng_words.split(',')

        self.logger.debug(
            "dry_run: %s mail: %s password: *** "
            "database_name: %s target_community: %s ng_words: %s" %
            (dry_run, mail, database_name, target_community, ng_words))

        return (dry_run, mail, password, database_name, target_community,
                ng_words)
Example #32
0
def resetParameters():
    logger.info("   Resetting parameters...")
    config = ConfigParser.SafeConfigParser()
    config.optionxform = str
    config.read(sololink_conf)

    serial_dev = config_get(config, config_dev_name)
    if serial_dev is None:
        return

    serial_flow = config_getbool(config, config_flow_name, True)

    serial_baud = config_getint(config, config_baud_name)
    if serial_baud is None:
        return

    m = mavutil.mavlink_connection(serial_dev, baud=serial_baud)
    m.set_rtscts(serial_flow)

    m.mav.param_set_send(m.target_system, m.target_component, 'SYSID_SW_MREV',
                         0, 0)
    time.sleep(5)
    m.close()
    return
Example #33
0
def create_tty_mavlink(serial_baud=None):
    config = ConfigParser.SafeConfigParser()
    config.optionxform = str
    config.read(sololink_conf)

    serial_dev = config_get(config, config_dev_name)
    if serial_dev is None:
        logger.error("reading %s from %s", config_dev_name, sololink_conf)
        return None
    logger.debug("%s = %s", config_dev_name, serial_dev)

    serial_flow = config_getbool(config, config_flow_name, True)
    logger.debug("%s = %s", config_flow_name, serial_flow)

    if serial_baud is None:
        serial_baud = config_getint(config, config_baud_name)
        if serial_baud is None:
            logger.error("reading %s from %s", config_baud_name, sololink_conf)
            return None
        logger.debug("%s = %d", config_baud_name, serial_baud)

    m = mavutil.mavlink_connection(serial_dev, baud=serial_baud)
    m.set_rtscts(serial_flow)
    return m
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 #35
0
def WakeUp():
    config = ConfigParser.ConfigParser()
    configFilename = os.path.join(os.path.dirname(sys.argv[0]),
                                  "autoProcessMedia.cfg")

    if not os.path.isfile(configFilename):
        Logger.error(
            "You need an autoProcessMedia.cfg file - did you rename and edit the .sample?"
        )
        return

    config.read(configFilename)
    wake = int(config.get("WakeOnLan", "wake"))
    if wake == 0:  # just return if we don't need to wake anything.
        return
    Logger.info("Loading WakeOnLan config from %s", configFilename)
    config.get("WakeOnLan", "host")
    host = config.get("WakeOnLan", "host")
    port = int(config.get("WakeOnLan", "port"))
    mac = config.get("WakeOnLan", "mac")

    i = 1
    while TestCon(host, port) == "Down" and i < 4:
        Logger.info("Sending WakeOnLan Magic Packet for mac: %s", mac)
        WakeOnLan(mac)
        time.sleep(20)
        i = i + 1

    if TestCon(host, port) == "Down":  # final check.
        Logger.warning(
            "System with mac: %s has not woken after 3 attempts. Continuing with the rest of the script.",
            mac)
    else:
        Logger.info(
            "System with mac: %s has been woken. Continuing with the rest of the script.",
            mac)
Example #36
0
def unsubscribe():
    try:
        app_id = request.json['app_id']
        sub_info, target = subinfo.get_subinfo(app_id)
        if sub_info is None or target is None:
            err_str = "No subscription exists with app id: " + app_id + "\n"
            logging.error("* No subscription exists with app id:%s ", app_id)
            return err_str
        else:
            ''' Flag to Update pipeling cfg file '''
            config = ConfigParser.ConfigParser()
            config.read('pub_sub.conf')
            if config.get('RABBITMQ', 'UpdateConfMgmt') == "True":
                update_pipeline_conf(sub_info, target, app_id, "DEL")
            else:
                logging.warning(
                    "Update Conf Mgmt flag is disabled,enable the flag to  update Conf Mgmt"
                )
            #update_pipeline_conf(sub_info,target,"DEL")
            subinfo.delete_subinfo(app_id)
    except Exception as e:
        logging.error("* %s", e.__str__())
        return e.__str__()
    return "UnSubscrition is sucessful! \n"
Example #37
0
def readIniFile():
    config = ConfigParser.ConfigParser()
    config.read('conf.ini')
    if (config.has_option('def', 'mode')):
        global mode
        mode = config.get('def', 'mode')
    if (config.has_option('def', 'auth')):
        global auth
        auth = config.get('def', 'auth')
    if (config.has_option('def', 'logpath')):
        global logpath
        logpath = config.get('def', 'logpath')
    if (config.has_option('def', 'webpath')):
        global webpath
        webpath = config.get('def', 'webpath')
    if (config.has_option('def', 'keypath')):
        global keypath
        keypath = config.get('def', 'keypath')
    if (config.has_option('def', 'certpath')):
        global certpath
        certpath = config.get('def', 'certpath')
    if (config.has_option('def', 'passpath')):
        global passpath
        passpath = config.get('def', 'passpath')
Example #38
0
    def __init__(self, config_filename):
        config = configparser.ConfigParser()
        config.read(config_filename)

        self.filename = config_filename
        self.latitude = self.parse_range_str(config['RANGES']['latitude'])
        self.longitude = self.parse_range_str(config['RANGES']['longitude'])
        self.count = self.parse_range_str(config['RANGES']['count'])
        self.area = self.parse_range_str(config['RANGES']['area'])
        self.distance = self.parse_range_str(config['RANGES']['distance'])
        self.ratio = self.parse_range_str(config['RANGES']['ratio'])
        self.dissolve = self.parse_range_str(config['RANGES']['dissolve'])

        self.bins_count = self.parse_range_str(
            config['HISTOGRAMS']['bins_count'])
        self.bins_count_text = self.create_bins_text(self.bins_count)

        self.bins_ratio = self.parse_range_str(
            config['HISTOGRAMS']['bins_ratio'])
        self.bins_ratio_text = self.create_bins_text(self.bins_ratio)

        absolute_folder = config['SIBLING_DATA']['folder']
        folder_details = fu.FileOpen(absolute_folder)
        self.sibling_data_folder = folder_details.folder
Example #39
0
def status(update: Update, context: CallbackContext) -> None:
    config = configparser.ConfigParser()
    config.read('settings.ini')

    WHITE_LIST = config['Telegram']['white_list'].split(',')
    if str(update.message.chat_id) not in WHITE_LIST:
        logger.warning(f'Unknown user {update.message.chat_id}')
        update.message.reply_html(
            f"We are under ban from Clubhouse. Check https://www.reddit.com/r/ClubhouseApp/comments/lqi79i/recording_clubhouse_crash_course/")
        return
    logger.debug(f'STATUS from {update.message.chat_id}')
    act_rec = TASKS.count_documents({'status': 'DOWNLOADING'})
    in_queue = QUEUE.count_documents({})

    act_tasks = '\n'.join(
        ['{}: {} /kill_{}'.format(task['topic'], datetime.now(timezone.utc) - task['dt'], task['pid']) for task in
         TASKS.find({'status': 'DOWNLOADING'})])
    future_tasks = '\n'.join([str(task['time_start'] - datetime.now(timezone.utc)) for task in QUEUE.find()])

    update.message.reply_html(f'<b>Recording:</b> {act_rec}\n'
                              f'{act_tasks}\n'
                              f'<b>Waiting in queue:</b> {in_queue}\n'
                              f'{future_tasks}'
                              )
    def __init__(self, debug=False, env='dev'):
        config = configparser.ConfigParser()
        config.read('config/' + env + '_config.ini')

        logging.config.dictConfig(yaml.load(open('config/logging.conf', 'r')))
        self.logger = logging.getLogger(__name__)

        self.grouper_wsuri = config['ENV'][
            'grouper_wsURI']  # Grouper WS URI and credentials
        self.grouper_username = config['ENV']['username']
        self.grouper_pwd = config['ENV']['password']
        self.stem = config['ENV']['attributes_stem']

        self.active_attrDefName = config['attributes'][
            'active_attrDefName'].split(",")  # A list of active attributes
        self.debug = config['debug']  # Debugging mode on/off.
        self.groupname = ''  # Current group name

        if self.debug:
            httplib2.debuglevel = 1

        self.http = httplib2.Http('.cache')
        self.http.add_credentials(name=self.grouper_username,
                                  password=self.grouper_pwd)
Example #41
0
def main():
    """
    Purge old paste.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--conf', help='paulla.paste conf file')

    args = parser.parse_args()

    config = ConfigParser.RawConfigParser()
    config.read(args.conf)

    logging.config.fileConfig(args.conf)
    logger = logging.getLogger('purge')

    server = couchdbkit.Server(config.get('app:main', 'couchdb.url'))
    db = server.get_or_create_db(config.get('app:main', 'couchdb.db'))
    Paste.set_db(db)

    oldPastes = Paste.view('old/all').all()

    for paste in oldPastes:
        logger.info("deleting %s", paste._id)
        paste.delete()
Example #42
0
def load_config():
    """
    Carrega configuração
    :return:
    """
    #print(environment)

    config = ConfigParser.ConfigParser()
    here = os.path.abspath(os.path.dirname(__file__))
    config_file = os.path.join(here, '../' + environment + '.ini')
    config.read(config_file)

    # Parâmetros globais de configuração
    nltk.data.path.append(config.get('nltk', 'data_dir'))
    nlpnet.set_data_dir(config.get('nlpnet', 'data_dir'))

    # Logging
    logging.config.fileConfig(config_file)

    # Cache configurations
    cache_opts = {
        'cache.regions':
        config.get('lbsociam', 'cache.regions'),
        'cache.type':
        config.get('lbsociam', 'cache.type'),
        'cache.short_term.expire':
        config.get('lbsociam', 'cache.short_term.expire'),
        'cache.default_term.expire':
        config.get('lbsociam', 'cache.default_term.expire'),
        'cache.long_term.expire':
        config.get('lbsociam', 'cache.long_term.expire')
    }

    cache = CacheManager(**parse_cache_config_options(cache_opts))

    return config
Example #43
0
def _get_config(group, key, default=None):
    """ Retrieves configuration parameters from config.ini 

    Keyword arguments:
    group -- Parent group
    key -- Key to retrieve from group
    """
    v = None
    booleankeys = ['remotes', 'backup_sourced_before_save']
    config = ConfigParser()
    config.read(_get_path_user() + 'config.ini')
    try:
        if key in booleankeys:
            v = config.getboolean(group, key)
        else:
            v = config.get(group, key)
    except:
        if default:
            return default
        else:
            raise
    if not v and default:
        return default
    return v
Example #44
0
    def __init__(self, config_file):
        """
        Initialize the configutation object loading the given
        configuration file
        """
        dict.__init__(self)

        # Parse configuration file
        config = ConfigParser.ConfigParser()
        if (config_file is None or len(config.read(config_file)) == 0):
            self.fg_config_messages += (
                "[WARNING]: Couldn't find configuration file '%s'; "
                " default options will be used\n" % config_file)
        else:
            # Store configuration file name
            self.config_file = config_file

        # Load configuration
        for section in self.defaults.keys():
            for conf_name in self.defaults[section].keys():
                def_value = self.defaults[section][conf_name]
                try:
                    self[conf_name] = config.get(section, conf_name)
                except ConfigParser.Error:
                    self[conf_name] = def_value
                    self.fg_config_messages +=\
                        ("[WARNING]:Couldn't find option '%s' "
                         "in section '%s'; "
                         "using default value '%s'\n"
                         % (conf_name, section, def_value))
                # The use of environment varialbes override any default or
                # configuration setting present in the configuration file
                try:
                    env_value = os.environ[conf_name.upper()]
                    self.fg_config_messages += \
                        ("Environment bypass of '%s': '%s' <- '%s'\n" %
                         (conf_name, self[conf_name], env_value))
                    self[conf_name] = env_value
                except KeyError:
                    # Corresponding environment variable not exists
                    pass
        # Logging
        logging.config.fileConfig(self['fgapisrv_logcfg'])
        # Show configuration in Msg variable
        if self['fgapisrv_debug']:
            self.fg_config_messages += self.show_conf()
            logging.debug("Initialized configuration object")
            logging.debug("Messages: %s" % self.fg_config_messages)
Example #45
0
def setup_logging(default_level=logging.WARNING):
    """Setup logging configuration

    """
    log = logging.getLogger(__name__)
    fullPath = findLiotaConfigFullPath().get_liota_fullpath()
    if fullPath != '':
        config = ConfigParser.RawConfigParser()
        try:
            if config.read(fullPath) != []:
                # now use json file for logging settings
                try:
                    log_cfg = config.get('LOG_CFG', 'json_path')
                except ConfigParser.ParsingError, err:
                    print 'Could not parse:', err
            else:
                raise IOError('Cannot open configuration file ' + fullPath)
Example #46
0
def readConst(section, file):
    config = configparser.ConfigParser()
    filePath = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                            '../Utilities/' + file + '.ini')
    variable = config.read(filePath)
    if variable:
        dictionary = {}
        try:
            options = config.options(section)
        except configparser.NoSectionError:
            Logger.logr.error("Section " + section + " does not exist in " +
                              filePath)
        else:
            for option in options:
                dictionary[option] = config.get(section, option)
            return dictionary
    else:
        Logger.logr.info("File " + file +
                         ".ini doesn't exist under provided path:" + filePath)
Example #47
0
def init_config(config_file):
    """
    Initialize the configuration from a config file.
    
    The values in config_file will override those already loaded from the default
    configuration file (defaults.cfg, in current package).
    
    This method does not setup logging.
    
    @param config_file: The path to a configuration file.
    @type config_file: C{str}
    
    @raise ValueError: if the specified config_file could not be read.
    @see: L{init_logging}  
    """
    global config

    if config_file and os.path.exists(config_file):
        read = config.read([config_file])
        if not read:
            raise ValueError("Could not read configuration from file: %s" %
                             config_file)
    def run(self, daemon, pidfile):
        logging.info("Starting oVirt guest agent")
        config = ConfigParser.ConfigParser()
        config.read(AGENT_DEFAULT_CONFIG)
        config.read(AGENT_DEFAULT_LOG_CONFIG)
        config.read(AGENT_CONFIG)

        self.agent = LinuxVdsAgent(config)

        if daemon:
            self._daemonize()

        f = file(pidfile, "w")
        f.write("%s\n" % (os.getpid()))
        f.close()
        os.chmod(pidfile, 0644)   # rw-rw-r-- (664)

        self.register_signal_handler()
        self.agent.run()

        logging.info("oVirt guest agent is down.")
Example #49
0
# -*- coding: utf-8 -*-
'''
Please read ../client.conf.example

Contains global variables. 🆘

'''
import logging
import logging.config  # needed for logging to work
import configparser
import os
import sys

# loading configuration file
config_file_name = 'client.conf'
config = configparser.ConfigParser()
config.read(config_file_name)

# setting up logger
file_name, extension = os.path.splitext(os.path.basename(sys.argv[0]))
logger = logging.getLogger(file_name)
handler = logging.handlers.RotatingFileHandler((file_name + '.log'),
                                               maxBytes=10485670,
                                               backupCount=5)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.addHandler(logging.StreamHandler())
logger.setLevel('INFO')
#logger.setLevel('DEBUG')
Example #50
0
#   X.Y     # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
#
__version__ = '0.1.dev'

import configparser
import json
import logging.config
import os

auth_config = configparser.ConfigParser()
auth_config.read('authentication.ini')
config = configparser.ConfigParser()
config.read('config.ini')


def setup_logging(config_file_path='logging.json',
                  default_level=logging.INFO,
                  env_key='LOG_CFG'):
    """
    Setup logging configuration
    :param config_file_path: logging configuration file path
    :param default_level: default logging level
    :param env_key: environment key that contain the logging configuration file path
    :return:
    """
    path = config_file_path
    value = os.getenv(env_key, None)
    if value:
Example #51
0
 def write(path, section, key, value):
     config = ConfigParser()
     config.read(path)
     config[section][key] = value
     with open(path, 'w') as configfile:
         config.write(configfile)
Example #52
0
import ConfigParser
import sys
from os.path import dirname

pid = -1
child = None
tunnelchild = None

BASEDIR = dirname(sys.argv[0])
print BASEDIR

logging.config.fileConfig(BASEDIR + '/logging_config.ini')
logger = logging.getLogger('smsserver')

config = ConfigParser.SafeConfigParser()
config.read(BASEDIR + '/smsserver.conf')


def checkConnection():
    DEVNULL = open(os.devnull, 'wb')
    logger.info("Checking connection status...")
    try:
        result = subprocess.check_call(["ping", "-c", "5", "www.abv.bg"],
                                       stdout=DEVNULL,
                                       stderr=DEVNULL)
    except subprocess.CalledProcessError, ex:  # error code <> 0
        result = ex.returncode

    DEVNULL.close()
    logger.info("Connection status: " + str(result))
    return result
Example #53
0
import logging.config
import configparser
import metrics
from datetime import datetime
import urllib.request
from unittest import mock
from requests import request
from aiohttp.web import Response
from jiracollector import JiraCollector
import pytest

config = configparser.ConfigParser()
config.read('metrics.ini')

logging.config.fileConfig(config.get('logging', 'config_file'),
                          defaults=None,
                          disable_existing_loggers=True)

logger = logging.getLogger()


# Asserts that "happy-path" works, i.e the returned metrics from JiraCollector
# is correctly converted and internal metrics are added to the cached metrics
@mock.patch('jiracollector.JiraCollector.__init__',
            mock.Mock(return_value=None))
@mock.patch('jiracollector.JiraCollector.collect')
def test_collect_metrics(mock_collector):
    metrics_dict = {"jira_total_done{project_name=\"BIP\"}": "42"}
    mock_collector.return_value = metrics_dict

    metrics.serviceIsReady = False
Example #54
0
import telebot
import time
import requests
import configparser
import logging.config

config = configparser.SafeConfigParser()
config.read('server.conf')
token = config.get('server', 'token')

bot = telebot.TeleBot(token)


@bot.message_handler(commands=['help'])
def send_help(message):
    logger.debug(message.chat.id)
    text = ('帮助\n')
    bot.send_message(message.chat.id, text)


@bot.message_handler()
def echo(message):
    bot.reply_to(message, message.text)


if __name__ == '__main__':
    logger.debug('telebot start...')
    while True:
        try:
            bot.polling(none_stop=True)
        except Exception as e:
Example #55
0
from tinydb import TinyDB, Query
import urllib.parse
import validators

from util import DateCleanerAndFaceter, HyperlinkRelevanceHeuristicSorter

'''
# TODO: move everything inside class
class ResourceSyncOAIPMHDestination:
    pass
'''
base_dir = os.path.abspath(os.path.dirname(__file__))

config_path = os.path.join(base_dir, 'destination.ini')
config = ConfigParser()
config.read(config_path)

logging_config_path = os.path.join(base_dir, 'destination_logging.ini')
logging_config = ConfigParser()
logging_config.read(logging_config_path)

logging.config.fileConfig(logging_config_path)
logger = logging.getLogger('root')

s3 = boto3.Session(profile_name=config['S3']['profile_name']).client('s3')

# map from DC tag name to Solr field name
tagNameToColumn = {
    'title': 'title_keyword',
    'creator': 'creator_keyword',
    'subject': 'subject_keyword',
Example #56
0
# MK Jul 2016
# helper to run apps on device and get some results back

import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('runner')

# initialize root adb
# initialize configuration parser
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('config.prop')

import os
import subprocess
from copy import copy

from db.Apps import Apps
from db.CodeAnalysis import CodeAnalysis
from db.Drozer import Drozer

adb_command = []

deviceId = config.get("dev", "dev.adb.id")
adb_command = ["adb"]
if deviceId <> "":
    adb_command.extend(["-s", deviceId])


# starts drozer app on phone
# app needs to run drozer server to allow communication
Example #57
0
import datetime
import psycopg2
import configparser
import random
import logging
import logging.config
from psycopg2 import sql
from pathlib import Path

logging.basicConfig(
    format='%(asctime)s :: %(levelname)s :: %(funcName)s :: %(lineno)d \
:: %(message)s',
    level=logging.INFO)

config = configparser.ConfigParser()
config.read('.\config.cfg')
#config.read_file(open(f"{Path(__file__).parents[0]}/config.cfg"))


class Tracker(object):
    """
    job_id, status, updated_time
    """
    def __init__(self, jobname, trade_date):
        self.jobname = jobname
        self.trade_date = trade_date

    def assign_job_id(self):

        job_id = random.randint(1, 10)
        return job_id
Example #58
0
import os
from ConfigParser import SafeConfigParser
from datetime import datetime
from pydispatch import dispatcher
import logging.config


class SignalingSafeConfigParser(SafeConfigParser):
    def set(self, section, option, value=None):
        SafeConfigParser.set(self, section, option, value)
        dispatcher.send('%s.%s' % (section, option), 'config')

config_path = os.path.dirname(__file__)
config = SignalingSafeConfigParser({
    'created': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
})
config.read(os.path.join(config_path, 'server.ini'))


def set_decorator(f):
    return f

__all__ = ['config']

logging.config.fileConfig(os.path.join(
    config_path, config.get('server', 'log_config')
))
Example #59
0
      error_count += 1
      time.sleep(1)

  if error_count >= 10:
    for sstr in cmd.split('&&'):
        subprocess.run(sstr.strip().split(' ', 1))
    logger.error('Error: 10 times without access to %s:%d -- executing cmd: \'%d\'', host, port, cmd)

# Setup global variables
DEFAULT_SLEEP = 5             # constant
timeout_sleep = DEFAULT_SLEEP # timeout to check internet -- increases as connection becomes stable

# Get ip configuration
config = configparser.ConfigParser()
try:
  config.read(os.path.join(dir_path, 'options.conf'))
  general = config['general']
except KeyError as ex:
  config['general'] = {}
  general = config['general']



# try to get config, fails to default case
options = {}
options['host'] = general.get('host', '8.8.8.8')
options['port'] = general.get('port', 53)
options['timeout'] = general.get('timeout', 3)
options['cmd'] = general.get('cmd', 'echo \'define cmd in options.conf\'')

# Runs forever
Example #60
0
from grp import getgrnam
from sys import stdin, stdout, stderr
import dencoderCommon
import sys
import socket
import re

config = ConfigParser.RawConfigParser()

# The OS X installer packages install to /usr/local
# but on Linux systems it's customary to install packages
# to the "normal" bin location in /usr.
# To support this I need to place the config file in a
# different location depending on the OS in question
if sys.platform == "darwin":
    config.read('/usr/local/etc/dencoder/dencoder.cfg')
else:
    config.read('/etc/dencoder/dencoder.cfg')

# get config options
hbpath = config.get('Dencoder', 'hbpath')
mp4tagsPath = config.get('Dencoder', 'mp4tagsPath')
hblog = config.get('Dencoder', 'hblog')
hberr = config.get('Dencoder', 'hberr')
mp4tagslog = config.get('Dencoder', 'mp4tagslog')
mp4tagserr = config.get('Dencoder', 'mp4tagserr')
basePath = config.get('Dencoder', 'basePath')
sourcePath = config.get('Dencoder', 'sourcePath')
destPath = config.get('Dencoder', 'destPath')
user = config.get('Dencoder', 'user')
group = config.get('Dencoder', 'group')