Harmonize code formatting style across project

This commit is contained in:
Kristóf Tóth 2018-06-04 22:16:44 +02:00
parent afc84e1d1a
commit d0667253c2
17 changed files with 152 additions and 69 deletions

View File

@ -17,7 +17,9 @@ class LazyEnvironment:
return self.prefixed_envvars_to_namedtuple() return self.prefixed_envvars_to_namedtuple()
def prefixed_envvars_to_namedtuple(self): def prefixed_envvars_to_namedtuple(self):
envvars = {envvar.replace(self._prefix, '', 1): environ.get(envvar) envvars = {
envvar.replace(self._prefix, '', 1): environ.get(envvar)
for envvar in environ.keys() for envvar in environ.keys()
if envvar.startswith(self._prefix)} if envvar.startswith(self._prefix)
}
return namedtuple(self._tuple_name, envvars)(**envvars) return namedtuple(self._tuple_name, envvars)(**envvars)

View File

@ -64,8 +64,10 @@ class IdeReloadWatchdogEventHandler(FileSystemWatchdogEventHandler):
self.ignore = self.ignore - 1 self.ignore = self.ignore - 1
return return
LOG.debug(event) LOG.debug(event)
self.uplink.send({'key': 'ide', self.uplink.send({
'data': {'command': 'reload'}}) 'key': 'ide',
'data': {'command': 'reload'}
})
def with_monitor_paused(fun): def with_monitor_paused(fun):

View File

@ -17,10 +17,12 @@ class DirectoryMonitoringEventHandler(EventHandlerBase, MonitorManagerMixin):
self._directory = directory self._directory = directory
MonitorManagerMixin.__init__(self, DirectoryMonitor, self._directory) MonitorManagerMixin.__init__(self, DirectoryMonitor, self._directory)
self.commands = {'pause': self.pause, self.commands = {
'pause': self.pause,
'resume': self.resume, 'resume': self.resume,
'ignore': self.ignore, 'ignore': self.ignore,
'selectdir': self.selectdir} 'selectdir': self.selectdir
}
@property @property
def directory(self): def directory(self):

View File

@ -39,10 +39,14 @@ class HistoryMonitor(CallbackMixin, ObserverMixin, ABC):
self.histfile = histfile self.histfile = histfile
self._history = [] self._history = []
self._last_length = len(self._history) self._last_length = len(self._history)
self.observer.schedule(CallbackEventHandler([self.histfile], self.observer.schedule(
CallbackEventHandler(
[self.histfile],
self._fetch_history, self._fetch_history,
self._invoke_callbacks), self._invoke_callbacks
dirname(self.histfile)) ),
dirname(self.histfile)
)
@property @property
def history(self): def history(self):
@ -53,7 +57,10 @@ class HistoryMonitor(CallbackMixin, ObserverMixin, ABC):
with open(self.histfile, 'r') as ifile: with open(self.histfile, 'r') as ifile:
pattern = compileregex(self.command_pattern) pattern = compileregex(self.command_pattern)
data = ifile.read() data = ifile.read()
self._history = [self.sanitize_command(command) for command in findall(pattern, data)] self._history = [
self.sanitize_command(command)
for command in findall(pattern, data)
]
@property @property
@abstractmethod @abstractmethod

View File

@ -65,11 +65,13 @@ class FileManager: # pylint: disable=too-many-instance-attributes
@property @property
def files(self): def files(self):
return [self._relpath(file) return [
self._relpath(file)
for file in glob(join(self._workdir, '**/*'), recursive=True) for file in glob(join(self._workdir, '**/*'), recursive=True)
if isfile(file) if isfile(file)
and self._is_in_allowed_dir(file) and self._is_in_allowed_dir(file)
and not self._is_blacklisted(file)] and not self._is_blacklisted(file)
]
@property @property
def file_contents(self): def file_contents(self):
@ -82,11 +84,16 @@ class FileManager: # pylint: disable=too-many-instance-attributes
ofile.write(value) ofile.write(value)
def _is_in_allowed_dir(self, path): def _is_in_allowed_dir(self, path):
return any(realpath(path).startswith(allowed_dir) return any(
for allowed_dir in self.allowed_directories) realpath(path).startswith(allowed_dir)
for allowed_dir in self.allowed_directories
)
def _is_blacklisted(self, file): def _is_blacklisted(self, file):
return any(fnmatchcase(file, blacklisted) for blacklisted in self.exclude) return any(
fnmatchcase(file, blacklisted)
for blacklisted in self.exclude
)
def _filepath(self, filename): def _filepath(self, filename):
return join(self._workdir, filename) return join(self._workdir, filename)

View File

@ -14,7 +14,10 @@ from tfw.mixins import ObserverMixin, SupervisorLogMixin
class LogMonitor(ObserverMixin): class LogMonitor(ObserverMixin):
def __init__(self, process_name, log_tail=0): def __init__(self, process_name, log_tail=0):
self.prevent_log_recursion() self.prevent_log_recursion()
event_handler = SendLogWatchdogEventHandler(process_name, log_tail=log_tail) event_handler = SendLogWatchdogEventHandler(
process_name,
log_tail=log_tail
)
self.observer.schedule( self.observer.schedule(
event_handler, event_handler,
event_handler.path event_handler.path
@ -30,7 +33,10 @@ class SendLogWatchdogEventHandler(PatternMatchingWatchdogEventHandler, Superviso
def __init__(self, process_name, log_tail=0): def __init__(self, process_name, log_tail=0):
self.process_name = process_name self.process_name = process_name
self.procinfo = self.supervisor.getProcessInfo(self.process_name) self.procinfo = self.supervisor.getProcessInfo(self.process_name)
super().__init__([self.procinfo['stdout_logfile'], self.procinfo['stderr_logfile']]) super().__init__([
self.procinfo['stdout_logfile'],
self.procinfo['stderr_logfile']
])
self.uplink = ServerUplinkConnector() self.uplink = ServerUplinkConnector()
self.log_tail = log_tail self.log_tail = log_tail

View File

@ -23,7 +23,12 @@ class LogMonitoringEventHandler(EventHandlerBase, MonitorManagerMixin):
super().__init__(key) super().__init__(key)
self.process_name = process_name self.process_name = process_name
self.log_tail = log_tail self.log_tail = log_tail
MonitorManagerMixin.__init__(self, LogMonitor, self.process_name, self.log_tail) MonitorManagerMixin.__init__(
self,
LogMonitor,
self.process_name,
self.log_tail
)
self.command_handlers = { self.command_handlers = {
'process_name': self.handle_process_name, 'process_name': self.handle_process_name,

View File

@ -13,9 +13,11 @@ LOG = logging.getLogger(__name__)
class ProcessManager(SupervisorMixin, SupervisorLogMixin): class ProcessManager(SupervisorMixin, SupervisorLogMixin):
def __init__(self): def __init__(self):
self.commands = {'start': self.start_process, self.commands = {
'start': self.start_process,
'stop': self.stop_process, 'stop': self.stop_process,
'restart': self.restart_process} 'restart': self.restart_process
}
def __call__(self, command, process_name): def __call__(self, command, process_name):
return self.commands[command](process_name) return self.commands[command](process_name)
@ -50,8 +52,14 @@ class ProcessManagingEventHandler(EventHandlerBase):
except SupervisorFault as fault: except SupervisorFault as fault:
message['data']['error'] = fault.faultString message['data']['error'] = fault.faultString
finally: finally:
message['data']['stdout'] = self.processmanager.read_stdout(data['process_name'], self.log_tail) message['data']['stdout'] = self.processmanager.read_stdout(
message['data']['stderr'] = self.processmanager.read_stderr(data['process_name'], self.log_tail) data['process_name'],
self.log_tail
)
message['data']['stderr'] = self.processmanager.read_stderr(
data['process_name'],
self.log_tail
)
return message return message
except KeyError: except KeyError:
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message) LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)

View File

@ -14,15 +14,15 @@ LOG = logging.getLogger(__name__)
class TerminadoMiniServer: class TerminadoMiniServer:
def __init__(self, url, port, workdir, shellcmd): def __init__(self, url, port, workdir, shellcmd):
self.port = port self.port = port
self._term_manager = SingleTermManager(shell_command=shellcmd, self._term_manager = SingleTermManager(
term_settings={'cwd': workdir}) shell_command=shellcmd,
self.application = Application( term_settings={'cwd': workdir}
[( )
self.application = Application([(
url, url,
TerminadoMiniServer.ResetterTermSocket, TerminadoMiniServer.ResetterTermSocket,
{'term_manager': self._term_manager} {'term_manager': self._term_manager}
)] )])
)
@property @property
def term_manager(self): def term_manager(self):
@ -46,5 +46,10 @@ class TerminadoMiniServer:
if __name__ == '__main__': if __name__ == '__main__':
LOG.info('Terminado Mini Server listening on %s', TFWENV.TERMINADO_PORT) LOG.info('Terminado Mini Server listening on %s', TFWENV.TERMINADO_PORT)
TerminadoMiniServer('/terminal', TFWENV.TERMINADO_PORT, TFWENV.TERMINADO_WD, ['bash']).listen() TerminadoMiniServer(
'/terminal',
TFWENV.TERMINADO_PORT,
TFWENV.TERMINADO_WD,
['bash']
).listen()
IOLoop.instance().start() IOLoop.instance().start()

View File

@ -36,8 +36,12 @@ class TerminalCommands(ABC):
self._setup_bashrc_aliases(bashrc) self._setup_bashrc_aliases(bashrc)
def _build_command_to_implementation_dict(self): def _build_command_to_implementation_dict(self):
return {self._parse_command_name(fun): getattr(self, fun) for fun in dir(self) return {
if callable(getattr(self, fun)) and self._is_command_implementation(fun)} self._parse_command_name(fun): getattr(self, fun)
for fun in dir(self)
if callable(getattr(self, fun))
and self._is_command_implementation(fun)
}
def _setup_bashrc_aliases(self, bashrc): def _setup_bashrc_aliases(self, bashrc):
with open(bashrc, 'a') as ofile: with open(bashrc, 'a') as ofile:

View File

@ -31,7 +31,10 @@ class TerminalEventHandler(EventHandlerBase):
bash_as_user_cmd = ['sudo', '-u', TAOENV.USER, 'bash'] bash_as_user_cmd = ['sudo', '-u', TAOENV.USER, 'bash']
self.terminado_server = TerminadoMiniServer( self.terminado_server = TerminadoMiniServer(
'/terminal', TFWENV.TERMINADO_PORT, TFWENV.TERMINADO_WD, bash_as_user_cmd '/terminal',
TFWENV.TERMINADO_PORT,
TFWENV.TERMINADO_WD,
bash_as_user_cmd
) )
self.commands = { self.commands = {

View File

@ -20,13 +20,15 @@ class FSMBase(CallbackMixin):
def __init__(self, initial: str = None, accepted_states: List[str] = None): def __init__(self, initial: str = None, accepted_states: List[str] = None):
self.accepted_states = accepted_states or [self.states[-1]] self.accepted_states = accepted_states or [self.states[-1]]
self.machine = Machine(model=self, self.machine = Machine(
model=self,
states=self.states, states=self.states,
transitions=self.transitions, transitions=self.transitions,
initial=initial or self.states[0], initial=initial or self.states[0],
send_event=True, send_event=True,
ignore_invalid_triggers=True, ignore_invalid_triggers=True,
after_state_change='execute_callbacks') after_state_change='execute_callbacks'
)
def execute_callbacks(self, event_data): def execute_callbacks(self, event_data):
self._execute_callbacks(event_data.kwargs) self._execute_callbacks(event_data.kwargs)

View File

@ -16,6 +16,14 @@ class LinearFSM(FSMBase):
self.states = list(map(str, range(number_of_steps))) self.states = list(map(str, range(number_of_steps)))
self.transitions = [] self.transitions = []
for index in self.states[:-1]: for index in self.states[:-1]:
self.transitions.append({'trigger': f'step_{int(index)+1}', 'source': index, 'dest': str(int(index)+1)}) self.transitions.append({
self.transitions.append({'trigger': 'step_next', 'source': index, 'dest': str(int(index)+1)}) 'trigger': f'step_{int(index)+1}',
'source': index,
'dest': str(int(index)+1)
})
self.transitions.append({
'trigger': 'step_next',
'source': index,
'dest': str(int(index)+1)
})
super(LinearFSM, self).__init__() super(LinearFSM, self).__init__()

View File

@ -15,8 +15,8 @@ class CallbackMixin:
""" """
Subscribe a callable to invoke once an event is triggered. Subscribe a callable to invoke once an event is triggered.
:param callback: callable to be executed on events :param callback: callable to be executed on events
:param *args: arguments passed to callable :param args: arguments passed to callable
:param **kwargs: kwargs passed to callable :param kwargs: kwargs passed to callable
""" """
fun = partial(callback, *args, **kwargs) fun = partial(callback, *args, **kwargs)
self._callbacks.append(fun) self._callbacks.append(fun)

View File

@ -26,5 +26,7 @@ class MessageSender:
'timestamp': datetime.now().isoformat(), 'timestamp': datetime.now().isoformat(),
'message': message 'message': message
} }
self.server_connector.send({'key': self.key, self.server_connector.send({
'data': data}) 'key': self.key,
'data': data
})

View File

@ -43,11 +43,17 @@ def deserialize_tfw_msg(*args):
def _serialize_all(*args): def _serialize_all(*args):
return tuple(_serialize_single(arg) for arg in args) return tuple(
_serialize_single(arg)
for arg in args
)
def _deserialize_all(*args): def _deserialize_all(*args):
return tuple(_deserialize_single(arg) for arg in args) return tuple(
_deserialize_single(arg)
for arg in args
)
def _serialize_single(data): def _serialize_single(data):

View File

@ -30,13 +30,16 @@ class TFWServer:
self._fsm.subscribe_callback(self._fsm_updater.update) self._fsm.subscribe_callback(self._fsm_updater.update)
self._event_handler_connector = EventHandlerConnector() self._event_handler_connector = EventHandlerConnector()
self.application = Application( self.application = Application([(
[(r'/ws', ZMQWebSocketProxy, {'make_eventhandler_message': self.make_eventhandler_message, r'/ws', ZMQWebSocketProxy,{
'make_eventhandler_message': self.make_eventhandler_message,
'proxy_filter': self.proxy_filter, 'proxy_filter': self.proxy_filter,
'handle_trigger': self.handle_trigger, 'handle_trigger': self.handle_trigger,
'event_handler_connector': self._event_handler_connector})] 'event_handler_connector': self._event_handler_connector
})]
) )
#self.controller_responder = ControllerResponder(self.fsm) TODO: add this once controller stuff is resolved # self.controller_responder = ControllerResponder(self.fsm)
# TODO: add this once controller stuff is resolved
@property @property
def fsm(self): def fsm(self):
@ -97,8 +100,11 @@ class FSMManager:
self.trigger_predicates[trigger].extend(predicates) self.trigger_predicates[trigger].extend(predicates)
def unsubscribe_predicate(self, trigger, *predicates): def unsubscribe_predicate(self, trigger, *predicates):
self.trigger_predicates[trigger] = [predicate for predicate in self.trigger_predicates[trigger] self.trigger_predicates[trigger] = [
not in predicates] predicate
for predicate in self.trigger_predicates[trigger]
not in predicates
]
class FSMUpdater: class FSMUpdater:
@ -111,10 +117,18 @@ class FSMUpdater:
self.uplink.send(self.generate_fsm_update()) self.uplink.send(self.generate_fsm_update())
def generate_fsm_update(self): def generate_fsm_update(self):
return {'key': 'FSMUpdate', return {
'data': self.get_fsm_state_and_transitions()} 'key': 'FSMUpdate',
'data': self.get_fsm_state_and_transitions()
}
def get_fsm_state_and_transitions(self): def get_fsm_state_and_transitions(self):
state = self.fsm.state state = self.fsm.state
valid_transitions = [{'trigger': trigger} for trigger in self.fsm.machine.get_triggers(self.fsm.state)] valid_transitions = [
return {'current_state': state, 'valid_transitions': valid_transitions} {'trigger': trigger}
for trigger in self.fsm.machine.get_triggers(self.fsm.state)
]
return {
'current_state': state,
'valid_transitions': valid_transitions
}