def test_read_json(self): with tempfile.TemporaryDirectory() as tmpdirname: tmpfilename = tmpdirname + '/f' create_file(tmpfilename, SAMPLE_JSON.split('\n')) result = read_json.read_json(tmpfilename) self.assertEqual(result['gyr1']['port'], '/tmp/tty_gyr1') self.assertEqual(len(result), 4)
def _read_definitions(self, json_path): definitions = {} for filename in glob.glob(json_path): new_defs = read_json.read_json(filename) for key in new_defs: if key in definitions: logging.warning('Duplicate definition for key "%s" found in %s', key, filename) definitions[key] = new_defs[key] return definitions
help='Increase output verbosity') parser.add_argument('-V', '--logger_verbosity', dest='logger_verbosity', default=0, action='count', help='Increase output verbosity of component loggers') args = parser.parse_args() LOGGING_FORMAT = '%(asctime)-15s %(filename)s:%(lineno)d %(message)s' logging.basicConfig(format=LOGGING_FORMAT) LOG_LEVELS = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG} # Our verbosity args.verbosity = min(args.verbosity, max(LOG_LEVELS)) run_logging.setLevel(LOG_LEVELS[args.verbosity]) # Verbosity of our component loggers (and everything else) args.logger_verbosity = min(args.logger_verbosity, max(LOG_LEVELS)) logging.getLogger().setLevel(LOG_LEVELS[args.logger_verbosity]) config_json = read_json(args.config) runner = LoggerRunner(config=config_json, mode=args.mode, interactive=args.interactive, interval=args.interval) runner.run()
def __init__(self, config_file): """Create a Listener from a Python config file.""" config = read_json.read_json(config_file) super().__init__(config)
def process_command(self, command): """Parse and execute the command string we've received.""" # cruises try: if not command: logging.info('Empty command received') elif command == 'cruises': cruises = self.api.get_cruises() if cruises: print('Loaded cruises: ' + ', '.join(cruises)) else: print('No cruises loaded') # load_cruise <cruise config file name> elif command == 'load_cruise': raise ValueError('format: load_cruise <cruise config file name>') elif command.find('load_cruise ') == 0: (load_cmd, filename) = command.split(maxsplit=1) logging.info('Loading cruise config from %s', filename) try: cruise_config = read_json(filename) self.api.load_cruise(cruise_config) except FileNotFoundError as e: logging.error('Unable to find file "%s"', filename) # set_cruise <JSON encoding of a cruise> elif command == 'set_cruise': raise ValueError('format: set_cruise <JSON encoding of a cruise') elif command.find('set_cruise ') == 0: (cruise_cmd, cruise_json) = command.split(maxsplit=1) logging.info('Setting cruise config to %s', cruise_json) self.api.load_cruise(json.loads(cruise_json)) # delete_cruise <cruise_id> elif command == 'delete_cruise': raise ValueError('format: delete_cruise <cruise id>') elif command.find('delete_cruise ') == 0: (cruise_cmd, cruise_id) = command.split(maxsplit=1) logging.info('Deleting cruise %s', cruise_id) self.api.delete_cruise(cruise_id) ############################ # mode <cruise_id> elif command == 'mode': raise ValueError('format: mode <cruise id>') elif command.find('mode ') == 0: (mode_cmd, cruise_id) = command.split(maxsplit=1) mode = self.api.get_mode(cruise_id) print('Current mode for %s: %s' % (cruise_id, mode)) # modes <cruise_id> elif command == 'modes': raise ValueError('format: modes <cruise id>') elif command.find('modes ') == 0: (mode_cmd, cruise_id) = command.split(maxsplit=1) modes = self.api.get_modes(cruise_id) print('Modes for %s: %s' % (cruise_id, ', '.join(modes))) # set_mode <cruise_id> <mode> elif command == 'set_mode': raise ValueError('format: set_mode <cruise id> <mode>') elif command.find('set_mode ') == 0: (mode_cmd, cruise_id, mode_name) = command.split(maxsplit=2) logging.info('Setting mode to %s', mode_name) self.api.set_mode(cruise_id, mode_name) ############################ # loggers <cruise_id> elif command == 'loggers': raise ValueError('format: loggers <cruise id>') elif command.find('loggers ') == 0: (loggers_cmd, cruise_id) = command.split(maxsplit=1) loggers = self.api.get_loggers(cruise_id) print('Loggers for %s: %s' % (cruise_id, ', '.join(loggers))) # logger_configs <cruise_id> <logger> elif command == 'logger_configs': raise ValueError('format: logger_configs <cruise_id> <logger>') elif command.find('logger_configs ') == 0: (logger_cmd, cruise_id, logger_name) = command.split(maxsplit=2) logger_configs = self.api.get_logger_config_names(cruise_id, logger_name) print('Configs for %s:%s: %s' % (cruise_id, logger_name, ', '.join(logger_configs))) # set_logger_config_name <cruise_id> <logger name> <name of logger config> elif command == 'set_logger_config_name': raise ValueError('format: set_logger_config_name <cruise_id> <logger name> <name of logger config>') elif command.find('set_logger_config_name ') == 0: (logger_cmd, cruise_id, logger_name, config_name) = command.split(maxsplit=3) logging.info('Setting logger %s to config %s', logger_name, config_name) # Is this a valid config for this logger? if not config_name in self.api.get_logger_config_names(cruise_id, logger_name): raise ValueError('Config "%s" is not valid for logger "%s"' % (config_name, logger_name)) self.api.set_logger_config_name(cruise_id, logger_name, config_name) # configs <cruise_id> elif command == 'configs': raise ValueError('format: configs <cruise id>') elif command.find('configs ') == 0: (config_cmd, cruise_id) = command.split(maxsplit=1) config_names = {logger_id:self.api.get_logger_config_name(cruise_id, logger_id) for logger_id in self.api.get_loggers(cruise_id)} for logger_id, config_name in config_names.items(): print('%s: %s' % (logger_id, config_name)) # status elif command == 'status': raise ValueError('format: status <cruise id>') elif command.find('status ') == 0: (status_cmd, cruise_id) = command.split(maxsplit=1) status_dict = self.api.get_status(cruise_id) print('%s' % pprint.pformat(status_dict)) # status_since elif command == 'status_since': raise ValueError('format: status_since <cruise id> <timestamp>') elif command.find('status_since ') == 0: (status_cmd, cruise_id, since_timestamp) = command.split(maxsplit=2) status_dict = self.api.get_status(cruise_id, float(since_timestamp)) print('%s' % pprint.pformat(status_dict)) # server_log elif command == 'server_log': server_log = self.api.get_message_log(source=SOURCE_NAME) print('%s' % pprint.pformat(server_log)) # server_log timestamp elif command.find('server_log') == 0: (log_cmd, since_timestamp) = command.split(maxsplit=1) server_log = self.api.get_message_log(source=SOURCE_NAME, user=None, log_level=self.api.DEBUG, since_timestamp=float(since_timestamp)) print('%s' % pprint.pformat(server_log)) # Quit gracefully elif command == 'quit': logging.info('Got quit command') self.quit() elif command == 'help': self.show_commands() else: print('Got unknown command: "{}"'.format(command)) print('Type "help" for help') except ValueError as e: logging.error('%s', e) finally: self.api.message_log(SOURCE_NAME, '(%s@%s)' % (USER, HOSTNAME), self.api.INFO, 'command: '+ command)
default=0, action='count', help='Increase output verbosity') args = parser.parse_args() LOGGING_FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(format=LOGGING_FORMAT) LOG_LEVELS = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG} args.verbosity = min(args.verbosity, max(LOG_LEVELS)) logging.getLogger().setLevel(LOG_LEVELS[args.verbosity]) # Okay - get to work here if args.config: configs = read_json(args.config) logging.info('Read configs: %s', configs) thread_list = [] for inst in configs: config = configs[inst] sim = SimSerial(port=config['port'], source_file=config['logfile']) sim_thread = threading.Thread(target=sim.run) sim_thread.start() thread_list.append(sim_thread) # If no config file, just a simple, single serial port elif args.logfile and args.port: sim_serial = SimSerial(port=args.port, baudrate=args.baud, source_file=args.logfile) sim_serial.run()
parser.add_argument('-V', '--logger_verbosity', dest='logger_verbosity', default=0, action='count', help='Increase output verbosity of component loggers') args = parser.parse_args() LOGGING_FORMAT = '%(asctime)-15s %(filename)s:%(lineno)d %(message)s' LOG_LEVELS ={0:logging.WARNING, 1:logging.INFO, 2:logging.DEBUG} # Set our logging verbosity logging.basicConfig(format=LOGGING_FORMAT) args.verbosity = min(args.verbosity, max(LOG_LEVELS)) run_logging.setLevel(LOG_LEVELS[args.verbosity]) if not args.websocket and not args.config: logging.error('No initial configs and no websocket to take commands from, ' 'so nothing to do - exiting.') exit(1) if args.websocket and not args.host_id: logging.error('Websocket client needs --host_id or it will not ever get ' 'tasks assigned to it - exiting.') exit(1) initial_configs = read_json(args.config) if args.config else None runner = LoggerRunner(interval=args.interval, max_tries=args.max_tries, initial_configs=initial_configs, websocket=args.websocket, host_id=args.host_id) runner.run()
logger_verbosity=args.logger_verbosity) # Register a callback: when api.set_mode() or api.set_config() have # completed, they call api.signal_update(cruise_id). We're # registering update_configs() with the API so that it gets called # when the api signals that an update has occurred. api.on_update(callback=logger_manager.update_configs) ############################ # Start all the various LoggerManager threads running logger_manager.start() ############################ # If they've given us an initial cruise_config, get and load it. if args.config: cruise_config = read_json(args.config) api.load_cruise(cruise_config) api.message_log(SOURCE_NAME, '(%s@%s)' % (USER, HOSTNAME), api.INFO, 'started with cruise: %s' % args.config) if args.mode: if not args.config: raise ValueError('Argument --mode can only be used with --config') cruise_id = cruise_config.get('cruise', {}).get('id', None) if not cruise_id: raise ValueError('Unable to find cruise_id in config: %s' % args.config) api.set_mode(cruise_id, args.mode) api.message_log(SOURCE_NAME, api.INFO, 'initial mode (%s@%s): %s', (USER, HOSTNAME, args.mode)) try: