Python logging.config() Examples

The following are 30 code examples for showing how to use logging.config(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: SecPi   Author: SecPi   File: manager.py    License: GNU General Public License v3.0 6 votes vote down vote up
def got_config_request(self, ch, method, properties, body):
		ip_addresses = json.loads(body)
		logging.info("Got config request with following IP addresses: %s" % ip_addresses)

		pi_id = None
		worker = db.session.query(db.objects.Worker).filter(db.objects.Worker.address.in_(ip_addresses)).first()
		if worker:
			pi_id = worker.id
			logging.debug("Found worker id %s for IP address %s" % (pi_id, worker.address))
		else: # wasn't able to find worker with given ip address(es)
			logging.error("Wasn't able to find worker for given IP adress(es)")
			reply_properties = pika.BasicProperties(correlation_id=properties.correlation_id)
			self.channel.basic_publish(exchange=utils.EXCHANGE, properties=reply_properties, routing_key=properties.reply_to, body="")
			return
		
		config = self.prepare_config(pi_id)
		logging.info("Sending intial config to worker with id %s" % pi_id)
		reply_properties = pika.BasicProperties(correlation_id=properties.correlation_id, content_type='application/json')
		self.channel.basic_publish(exchange=utils.EXCHANGE, properties=reply_properties, routing_key=properties.reply_to, body=json.dumps(config))

	# callback method for when the manager recieves data after a worker executed its actions 
Example 2
Project: SecPi   Author: SecPi   File: manager.py    License: GNU General Public License v3.0 6 votes vote down vote up
def got_on_off(self, ch, method, properties, body):
		msg = json.loads(body)
		
		self.cleanup_notifiers()
		
		if(msg['active_state'] == True):
			self.setup_notifiers()
			logging.info("Activating setup: %s" % msg['setup_name'])
		
		
		workers = db.session.query(db.objects.Worker).filter(db.objects.Worker.active_state == True).all()
		for pi in workers:
			config = self.prepare_config(pi.id)
			# check if we are deactivating --> worker should be deactivated!
			if(msg['active_state'] == False):
				config["active"] = False
				logging.info("Deactivating setup: %s" % msg['setup_name'])
				
			self.send_json_message(utils.QUEUE_CONFIG+str(pi.id), config)
			logging.info("Sent config to worker %s"%pi.name)

	# callback method which gets called when a worker raises an alarm 
Example 3
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 6 votes vote down vote up
def got_init_config(self, ch, method, properties, body):
		logging.info("Received intitial config %r" % (body))
		if self.corr_id == properties.correlation_id: #we got the right config
			try: #TODO: add check if response is empty...
				new_conf = json.loads(body)
				new_conf["rabbitmq"] = config.get("rabbitmq")
			except Exception as e:
				logging.exception("Wasn't able to read JSON config from manager:\n%s" % e)
				time.sleep(60) #sleep for X seconds and then ask again
				self.fetch_init_config()
				return
		
			logging.info("Trying to apply config and reconnect")
			self.apply_config(new_conf)
			self.connection_cleanup()
			self.connect() #hope this is the right spot
			logging.info("Initial config activated")
			self.start()
		else:
			logging.info("This config isn't meant for us")
	
	# Create a zip of all the files which were collected while actions were executed 
Example 4
Project: toolium   Author: Telefonica   File: driver_wrapper.py    License: Apache License 2.0 6 votes vote down vote up
def configure_properties(self, tc_config_prop_filenames=None, behave_properties=None):
        """Configure selenium instance properties

        :param tc_config_prop_filenames: test case specific properties filenames
        :param behave_properties: dict with behave user data properties
        """
        prop_filenames = DriverWrappersPool.get_configured_value('Config_prop_filenames', tc_config_prop_filenames,
                                                                 'properties.cfg;local-properties.cfg')
        prop_filenames = [os.path.join(DriverWrappersPool.config_directory, filename) for filename in
                          prop_filenames.split(';')]
        prop_filenames = ';'.join(prop_filenames)

        # Configure config only if properties filename has changed
        if self.config_properties_filenames != prop_filenames:
            # Initialize the config object
            self.config = ExtendedConfigParser.get_config_from_file(prop_filenames)
            self.config_properties_filenames = prop_filenames
            self.update_magic_config_names()

        # Override properties with system properties
        self.config.update_properties(os.environ)

        # Override properties with behave userdata properties
        if behave_properties:
            self.config.update_properties(behave_properties) 
Example 5
Project: toolium   Author: Telefonica   File: driver_wrapper.py    License: Apache License 2.0 6 votes vote down vote up
def get_config_window_bounds(self):
        """Reads bounds from config and, if monitor is specified, modify the values to match with the specified monitor

        :return: coords X and Y where set the browser window.
        """
        bounds_x = int(self.config.get_optional('Driver', 'bounds_x') or 0)
        bounds_y = int(self.config.get_optional('Driver', 'bounds_y') or 0)

        monitor_index = int(self.config.get_optional('Driver', 'monitor') or -1)
        if monitor_index > -1:
            try:
                monitor = screeninfo.get_monitors()[monitor_index]
                bounds_x += monitor.x
                bounds_y += monitor.y
            except NotImplementedError:
                self.logger.warn('Current environment doesn\'t support get_monitors')

        return bounds_x, bounds_y 
Example 6
Project: ciftify   Author: edickie   File: report.py    License: MIT License 6 votes vote down vote up
def define_atlas_settings():
    atlas_settings = {
        'DKT': {
            'path' : os.path.join(ciftify.config.find_HCP_S1200_GroupAvg(),
                                  'cvs_avg35_inMNI152.aparc.32k_fs_LR.dlabel.nii'),
            'order' : 1,
            'name': 'DKT',
            'map_number': 1
        },
        'MMP': {
            'path': os.path.join(ciftify.config.find_HCP_S1200_GroupAvg(),
                                 'Q1-Q6_RelatedValidation210.CorticalAreas_dil_Final_Final_Areas_Group_Colors.32k_fs_LR.dlabel.nii'),
            'order' : 3,
            'name' : 'MMP',
            'map_number': 1
        },
        'Yeo7': {
            'path' : os.path.join(ciftify.config.find_HCP_S1200_GroupAvg(),
                                  'RSN-networks.32k_fs_LR.dlabel.nii'),
            'order' : 2,
            'name' : 'Yeo7',
            'map_number': 1
        }
    }
    return(atlas_settings) 
Example 7
Project: ciftify   Author: edickie   File: cifti_vis_fmri.py    License: MIT License 6 votes vote down vote up
def generate_qc_page(user_settings, config, qc_dir, scene_dir, qc_html,
                    temp_dir, title_formatter):

    sbref_nii = change_sbref_palette(user_settings, temp_dir)
    dtseries_sm = get_smoothed_dtseries_file(user_settings, temp_dir)

    contents = config.get_template_contents()
    scene_file = personalize_template(contents, scene_dir, user_settings,
                                        sbref_nii, dtseries_sm)

    ciftify.utils.make_dir(qc_dir)
    with open(qc_html, 'w') as qc_page:
        ciftify.html.add_page_header(qc_page, config, user_settings.qc_mode,
                subject=user_settings.subject, path='..')
        wb_logging = 'INFO' if user_settings.debug_mode else 'WARNING'
        ciftify.html.add_images(qc_page, qc_dir, config.images,
            scene_file, wb_logging = wb_logging, add_titles = True,
            title_formatter = title_formatter) 
Example 8
Project: circleci-demo-python-flask   Author: CircleCI-Public   File: env.py    License: MIT License 6 votes vote down vote up
def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(url=url)

    with context.begin_transaction():
        context.run_migrations() 
Example 9
Project: errand-boy   Author: greyside   File: run.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main(argv):
    parsed_args = parser.parse_args(argv[1:])

    mod, klass = parsed_args.transport.rsplit('.', 1)

    transport = getattr(importlib.import_module(mod), klass)()

    command = parsed_args.command

    if not command:
        logging.config.dictConfig(LOGGING)

        transport.run_server(
            pool_size=parsed_args.pool_size,
            max_accepts=parsed_args.max_accepts,
            max_child_tasks=parsed_args.max_child_tasks
        )
    else:
        stdout, stderr, returncode = transport.run_cmd(' '.join(command))

        sys.stdout.write(stdout)
        sys.stderr.write(stderr)

        sys.exit(returncode) 
Example 10
Project: olympe   Author: Parrot-Developers   File: __init__.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update_config(update):
    """
    Update (recursively) the current logging condiguration dictionary.

    See: `Logging config dictionary schema <https://docs.python.org/3/library/logging.config.html#logging-config-dictschema>`_

    """
    global _config
    new_config = copy.deepcopy(_config)
    _update_dict_recursive(new_config, update)
    logging.config.dictConfig(new_config)
    _configure_ulog_bridge()
    _config = new_config


# set the default log configuration on import 
Example 11
Project: gitlab-tools   Author: Salamek   File: env.py    License: GNU General Public License v3.0 6 votes vote down vote up
def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(url=url)

    with context.begin_transaction():
        context.run_migrations() 
Example 12
Project: app   Author: simple-login   File: env.py    License: MIT License 6 votes vote down vote up
def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url, target_metadata=target_metadata, literal_binds=True
    )

    with context.begin_transaction():
        context.run_migrations() 
Example 13
Project: beavy   Author: beavyHQ   File: env.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(url=url)

    with context.begin_transaction():
        context.run_migrations() 
Example 14
Project: thingsboard-gateway   Author: thingsboard   File: tb_gateway_service.py    License: Apache License 2.0 6 votes vote down vote up
def _load_connectors(self, main_config):
        self.connectors_configs = {}
        if main_config.get("connectors"):
            for connector in main_config['connectors']:
                try:
                    connector_class = TBUtility.check_and_import(connector["type"], self._default_connectors.get(connector["type"], connector.get("class")))
                    self._implemented_connectors[connector["type"]] = connector_class
                    with open(self._config_dir + connector['configuration'], 'r', encoding="UTF-8") as conf_file:
                        connector_conf = load(conf_file)
                        if not self.connectors_configs.get(connector['type']):
                            self.connectors_configs[connector['type']] = []
                        connector_conf["name"] = connector["name"]
                        self.connectors_configs[connector['type']].append({"name": connector["name"], "config": {connector['configuration']: connector_conf}})
                except Exception as e:
                    log.error("Error on loading connector:")
                    log.exception(e)
        else:
            log.error("Connectors - not found! Check your configuration!")
            main_config["remoteConfiguration"] = True
            log.info("Remote configuration is enabled forcibly!") 
Example 15
Project: thingsboard-gateway   Author: thingsboard   File: tb_gateway_service.py    License: Apache License 2.0 6 votes vote down vote up
def _connect_with_connectors(self):
        for connector_type in self.connectors_configs:
            for connector_config in self.connectors_configs[connector_type]:
                for config in connector_config["config"]:
                    connector = None
                    try:
                        if connector_config["config"][config] is not None:
                            connector = self._implemented_connectors[connector_type](self, connector_config["config"][config],
                                                                                     connector_type)
                            connector.setName(connector_config["name"])
                            self.available_connectors[connector.get_name()] = connector
                            connector.open()
                        else:
                            log.info("Config not found for %s", connector_type)
                    except Exception as e:
                        log.exception(e)
                        if connector is not None:
                            connector.close() 
Example 16
Project: tf-yarn   Author: criteo   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def _add_monitor_to_experiment(experiment: experiment.Experiment) -> experiment.Experiment:
    logger.info(f"configured training hooks: {experiment.train_spec.hooks}")

    training_hooks = list(experiment.train_spec.hooks)

    if experiment.config.log_step_count_steps is not None:
        steps_per_second_hook = metrics.StepPerSecondHook(
            every_n_steps=experiment.config.log_step_count_steps
        )
        if not _hook_name_already_exists(steps_per_second_hook, training_hooks):
            training_hooks.append(steps_per_second_hook)
        else:
            logger.warning("do not add StepPerSecondHook as there is already one configured")

    monitored_train_spec = experiment.train_spec._replace(
        hooks=training_hooks
    )

    monitored_eval_spec = experiment.eval_spec._replace(
        hooks=(evaluator_metrics.EvalMonitorHook(), *experiment.eval_spec.hooks)
    )

    experiment = experiment._replace(eval_spec=monitored_eval_spec, train_spec=monitored_train_spec)
    return experiment 
Example 17
Project: yolo2-pytorch   Author: ruiminshen   File: detect.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, args, config):
        self.args = args
        self.config = config
        self.cache_dir = utils.get_cache_dir(config)
        self.model_dir = utils.get_model_dir(config)
        self.category = utils.get_category(config, self.cache_dir if os.path.exists(self.cache_dir) else None)
        self.draw_bbox = utils.visualize.DrawBBox(self.category, colors=args.colors, thickness=args.thickness)
        self.anchors = torch.from_numpy(utils.get_anchors(config)).contiguous()
        self.height, self.width = tuple(map(int, config.get('image', 'size').split()))
        self.path, self.step, self.epoch = utils.train.load_model(self.model_dir)
        state_dict = torch.load(self.path, map_location=lambda storage, loc: storage)
        self.dnn = utils.parse_attr(config.get('model', 'dnn'))(model.ConfigChannels(config, state_dict), self.anchors, len(self.category))
        self.dnn.load_state_dict(state_dict)
        self.inference = model.Inference(config, self.dnn, self.anchors)
        self.inference.eval()
        if torch.cuda.is_available():
            self.inference.cuda()
        logging.info(humanize.naturalsize(sum(var.cpu().numpy().nbytes for var in self.inference.state_dict().values())))
        self.cap = self.create_cap()
        self.keys = set(args.keys)
        self.resize = transform.parse_transform(config, config.get('transform', 'resize_test'))
        self.transform_image = transform.get_transform(config, config.get('transform', 'image_test').split())
        self.transform_tensor = transform.get_transform(config, config.get('transform', 'tensor').split()) 
Example 18
Project: SecPi   Author: SecPi   File: main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def connect(self, num_tries=3):
		credentials = pika.PlainCredentials(config.get('rabbitmq')['user'], config.get('rabbitmq')['password'])
		parameters = pika.ConnectionParameters(credentials=credentials,
			host=config.get('rabbitmq')['master_ip'],
			port=5671,
			ssl=True,
			socket_timeout=10,
			ssl_options = {
				"ca_certs":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['cacert'],
				"certfile":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['certfile'],
				"keyfile":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['keyfile']
			}
		)

		connected = False
		while not connected and num_tries > 0:
			try:
				cherrypy.log("Trying to connect to rabbitmq service...")
				self.connection = pika.BlockingConnection(parameters=parameters)
				self.channel = self.connection.channel()
				connected = True
				cherrypy.log("Connection to rabbitmq service established")
			#except pika.exceptions.AMQPConnectionError as pe:
			except Exception as e:
				cherrypy.log("Error connecting to Queue! %s" % e, traceback=True)
				num_tries-=1
				time.sleep(30)

		if not connected:
			return False
		# define exchange
		self.channel.exchange_declare(exchange=utils.EXCHANGE, exchange_type='direct')

		# define queues
		self.channel.queue_declare(queue=utils.QUEUE_ON_OFF)
		self.channel.queue_bind(exchange=utils.EXCHANGE, queue=utils.QUEUE_ON_OFF)
		return True 
Example 19
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
		self.actions = []
		self.sensors = []
		self.active = False
		self.data_directory = "/var/tmp/secpi/worker_data"
		self.zip_directory = "/var/tmp/secpi"
		self.message_queue = [] # stores messages which couldn't be sent
		
		try:
			logging.config.fileConfig(os.path.join(PROJECT_PATH, 'logging.conf'), defaults={'logfilename': 'worker.log'})
		except Exception as e:
			print("Error while trying to load config file for logging")

		logging.info("Initializing worker")

		try:
			config.load(PROJECT_PATH +"/worker/config.json")
			logging.debug("Config loaded")
		except ValueError: # Config file can't be loaded, e.g. no valid JSON
			logging.error("Wasn't able to load config file, exiting...")
			quit()
		
		time.sleep(60) # TEMPORARY FIX for #83

		self.prepare_data_directory(self.data_directory)
		self.connect()
		
		# if we don't have a pi id we need to request the initial config, afterwards we have to reconnect
		# to the queues which are specific to the pi id -> hence, call connect again
		if not config.get('pi_id'):
			logging.debug("No Pi ID found, will request initial configuration...")
			self.fetch_init_config()
		else:
			logging.info("Setting up sensors and actions")
			self.active = config.get('active')
			self.setup_sensors()
			self.setup_actions()
			logging.info("Setup done!") 
Example 20
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post_err(self, msg):
		logging.exception(msg)
		err = { "msg": msg,
				"level": utils.LEVEL_ERR,
				"sender": "Worker %s"%config.get('pi_id'),
				"datetime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
				
		self.send_json_msg(utils.QUEUE_LOG, err) 
Example 21
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_ip_addresses(self):
		result = []
		for interface in netifaces.interfaces(): # interate through interfaces: eth0, eth1, wlan0...
			if (interface != "lo") and (netifaces.AF_INET in netifaces.ifaddresses(interface)): # filter loopback, and active ipv4
				for ip_address in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
					logging.debug("Adding %s IP to result" % ip_address['addr'])
					result.append(ip_address['addr'])
			if (interface != "lo") and (netifaces.AF_INET6 in netifaces.ifaddresses(interface)): # filter loopback, and active ipv6
				for ipv6_address in netifaces.ifaddresses(interface)[netifaces.AF_INET6]:
					logging.debug("Adding %s IP to result" % ipv6_address['addr'])
					result.append(ipv6_address['addr'])

		return result

	# function which requests the initial config from the manager 
Example 22
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fetch_init_config(self):
		ip_addresses = self.get_ip_addresses()
		if ip_addresses:
			self.corr_id = str(uuid.uuid4())
			logging.info("Sending initial configuration request to manager")
			properties = pika.BasicProperties(reply_to=self.callback_queue,
											  correlation_id=self.corr_id,
											  content_type='application/json')
			self.send_msg(utils.QUEUE_INIT_CONFIG, json.dumps(ip_addresses), properties=properties)
		else:
			logging.error("Wasn't able to find any IP address(es), please check your network configuration. Exiting...")
			quit()

	# callback function which is executed when the manager replies with the initial config which is then applied 
Example 23
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def prepare_data(self):
		try:
			if os.listdir(self.data_directory): # check if there are any files available
				shutil.make_archive("%s/%s" % (self.zip_directory, config.get('pi_id')), "zip", self.data_directory)
				logging.info("Created ZIP file")
				return True
			else:
				logging.info("No data to zip")
				return False
		except OSError as oe:
			self.post_err("Pi with id '%s' wasn't able to prepare data for manager:\n%s" % (config.get('pi_id'), oe))
			logging.error("Wasn't able to prepare data for manager: %s" % oe)

	# Remove all the data that was created during the alarm, unlink == remove 
Example 24
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cleanup_data(self):
		try:
			os.unlink("%s/%s.zip" % (self.zip_directory, config.get('pi_id')))
			for the_file in os.listdir(self.data_directory):
				file_path = os.path.join(self.data_directory, the_file)
				if os.path.isfile(file_path):
					os.unlink(file_path)
				elif os.path.isdir(file_path):
					shutil.rmtree(file_path)
			logging.info("Cleaned up files")
		except OSError as oe:
			self.post_err("Pi with id '%s' wasn't able to execute cleanup:\n%s" % (config.get('pi_id'), oe))
			logging.error("Wasn't able to clean up data directory: %s" % oe)

	# callback method which processes the actions which originate from the manager 
Example 25
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def apply_config(self, new_config):
		# check if new config changed
		if(new_config != config.getDict()):
			# disable while loading config
			self.active = False
			
			# TODO: deactivate queues
			logging.info("Cleaning up actions and sensors")
			self.cleanup_sensors()
			self.cleanup_actions()
			
			# TODO: check valid config file?!
			# write config to file
			try:
				f = open('%s/worker/config.json'%(PROJECT_PATH),'w')
				f.write(json.dumps(new_config))
				f.close()
			except Exception as e:
				logging.exception("Wasn't able to write config file:\n%s" % e)
			
			# set new config
			config.load(PROJECT_PATH +"/worker/config.json")
			
			if(config.get('active')):
				logging.info("Activating actions and sensors")
				self.setup_sensors()
				self.setup_actions()
				# TODO: activate queues
				self.active = True
			
			logging.info("Config saved successfully...")
		else:
			logging.info("Config didn't change") 
Example 26
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def got_config(self, ch, method, properties, body):
		logging.info("Received config %r" % (body))
		
		try:
			new_conf = json.loads(body)
		except Exception as e:
			logging.exception("Wasn't able to read JSON config from manager:\n%s" % e) 
		
		# we don't get the rabbitmq config sent to us, so add the current one
		new_conf["rabbitmq"] = config.get("rabbitmq")
		
		self.apply_config(new_conf)
		
	# Initialize all the sensors for operation and add callback method
	# TODO: check for duplicated sensors 
Example 27
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup_sensors(self):
		if not config.get("sensors"):
			logging.info("No sensors configured")
			return
		for sensor in config.get("sensors"):
			try:
				logging.info("Trying to register sensor: %s" % sensor["id"])
				s = self.class_for_name(sensor["module"], sensor["class"])
				sen = s(sensor["id"], sensor["params"], self)
				sen.activate()
			except Exception as e:
				self.post_err("Pi with id '%s' wasn't able to register sensor '%s':\n%s" % (config.get('pi_id'), sensor["class"],e))
			else:
				self.sensors.append(sen)
				logging.info("Registered!") 
Example 28
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup_actions(self):
		if not config.get("actions"):
			logging.info("No actions configured")
			return
		for action in config.get("actions"):
			try:
				logging.info("Trying to register action: %s" % action["id"])
				a = self.class_for_name(action["module"], action["class"])
				act = a(action["id"], action["params"])
			except Exception as e: #AttributeError, KeyError
				self.post_err("Pi with id '%s' wasn't able to register action '%s':\n%s" % (config.get('pi_id'), action["class"],e))
			else:
				self.actions.append(act)
				logging.info("Registered!") 
Example 29
Project: SecPi   Author: SecPi   File: worker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def alarm(self, sensor_id, message):
		if(self.active):
			logging.info("Sensor with id %s detected something" % sensor_id)

			msg = {	"pi_id":config.get("pi_id"),
					"sensor_id": sensor_id,
					"message": message,
					"datetime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
			
			# send a message to the alarmQ and tell which sensor signaled
			self.send_json_msg(utils.QUEUE_ALARM, msg) 
Example 30
Project: toolium   Author: Telefonica   File: driver_wrapper.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        if not DriverWrappersPool.is_empty():
            # Copy config object and other properties from default driver
            default_wrapper = DriverWrappersPool.get_default_wrapper()
            self.config = default_wrapper.config.deepcopy()
            self.logger = default_wrapper.logger
            self.config_properties_filenames = default_wrapper.config_properties_filenames
            self.config_log_filename = default_wrapper.config_log_filename
            self.output_log_filename = default_wrapper.output_log_filename
            self.visual_baseline_directory = default_wrapper.visual_baseline_directory
            self.baseline_name = default_wrapper.baseline_name

        # Create utils instance and add wrapper to the pool
        self.utils = Utils(self)
        DriverWrappersPool.add_wrapper(self)