def __init__(self, till=None, seconds=None): """ Signal after some elapsed time: Till(seconds=1).wait() :param till: UNIX TIMESTAMP OF WHEN TO SIGNAL :param seconds: PREFERRED OVER timeout """ now = time() if till != None: if not isinstance(till, (float, int)): from mo_logs import Log Log.error("Date objects for Till are no longer allowed") timeout = till elif seconds != None: timeout = now + seconds else: from mo_logs import Log raise Log.error("Should not happen") Signal.__init__(self, name=text(timeout)) with Till.locker: if timeout != None: Till.next_ping = min(Till.next_ping, timeout) Till.new_timers.append(TodoItem(timeout, ref(self)))
def __init__(self, name, target, *args, **kwargs): BaseThread.__init__(self, -1, coalesce(name, "thread_" + text(object.__hash__(self)))) self.target = target self.end_of_thread = Data() self.args = args # ENSURE THERE IS A SHARED please_stop SIGNAL self.kwargs = copy(kwargs) self.please_stop = self.kwargs.get(PLEASE_STOP) if self.please_stop is None: self.please_stop = self.kwargs[PLEASE_STOP] = Signal( "please_stop for " + self.name ) self.please_stop.then(self.start) self.thread = None self.ready_to_stop = Signal("joining with " + self.name) self.stopped = Signal("stopped signal for " + self.name) if PARENT_THREAD in kwargs: del self.kwargs[PARENT_THREAD] self.parent = kwargs[PARENT_THREAD] else: self.parent = Thread.current() self.parent.add_child(self)
def __init__(self, name, params, cwd=None, env=None, debug=False, shell=False, bufsize=-1): self.name = name self.service_stopped = Signal("stopped signal for " + strings.quote(name)) self.stdin = Queue("stdin for process " + strings.quote(name), silent=True) self.stdout = Queue("stdout for process " + strings.quote(name), silent=True) self.stderr = Queue("stderr for process " + strings.quote(name), silent=True) try: self.debug = debug or DEBUG self.service = service = subprocess.Popen( [str(p) for p in params], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=bufsize, cwd=cwd if isinstance(cwd, (str, NullType, none_type)) else cwd.abspath, env={str(k): str(v) for k, v in set_default(env, os.environ).items()}, shell=shell ) self.please_stop = Signal() self.please_stop.then(self._kill) self.child_lock = Lock("children of "+self.name) self.children = [ Thread.run(self.name + " stdin", self._writer, service.stdin, self.stdin, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stdout", self._reader, "stdout", service.stdout, self.stdout, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stderr", self._reader, "stderr", service.stderr, self.stderr, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " waiter", self._monitor, parent_thread=self), ] except Exception as e: Log.error("Can not call", e) self.debug and Log.note("{{process}} START: {{command}}", process=self.name, command=" ".join(map(strings.quote, params)))
def __init__(self): BaseThread.__init__(self, get_ident()) self.name = "Main Thread" self.please_stop = Signal() self.stopped = Signal() self.stop_logging = Log.stop self.timers = None self.shutdown_locker = allocate_lock()
def __init__(self, name, params, cwd=None, env=None, debug=False, shell=False, bufsize=-1): """ Spawns multiple threads to manage the stdin/stdout/stderr of the child process; communication is done via proper thread-safe queues of the same name. Since the process is managed and monitored by threads, the main thread is not blocked when the child process encounters problems :param name: name given to this process :param params: list of strings for program name and parameters :param cwd: current working directory :param env: enviroment variables :param debug: true to be verbose about stdin/stdout :param shell: true to run as command line :param bufsize: if you want to screw stuff up """ self.debug = debug or DEBUG self.process_id = Process.next_process_id Process.next_process_id += 1 self.name = name + " (" + text(self.process_id) + ")" self.service_stopped = Signal("stopped signal for " + strings.quote(name)) self.stdin = Queue("stdin for process " + strings.quote(name), silent=not self.debug) self.stdout = Queue("stdout for process " + strings.quote(name), silent=not self.debug) self.stderr = Queue("stderr for process " + strings.quote(name), silent=not self.debug) try: if cwd == None: cwd = os.getcwd() else: cwd = str(cwd) command = [str(p) for p in params] self.debug and Log.note("command: {{command}}", command=command) self.service = service = subprocess.Popen( [str(p) for p in params], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=bufsize, cwd=cwd, env={str(k): str(v) for k, v in set_default(env, os.environ).items()}, shell=shell ) self.please_stop = Signal() self.please_stop.then(self._kill) self.child_locker = Lock() self.children = [ Thread.run(self.name + " stdin", self._writer, service.stdin, self.stdin, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stdout", self._reader, "stdout", service.stdout, self.stdout, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stderr", self._reader, "stderr", service.stderr, self.stderr, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " waiter", self._monitor, parent_thread=self), ] except Exception as e: Log.error("Can not call", e) self.debug and Log.note("{{process}} START: {{command}}", process=self.name, command=" ".join(map(strings.quote, params)))
def __init__(self, message="ping", every="second", start=None, until=None): if is_text(message): self.message = show_message(message) else: self.message = message self.every = Duration(every) if isinstance(until, Signal): self.please_stop = until elif until == None: self.please_stop = Signal() else: self.please_stop = Till(Duration(until).seconds) self.thread = None if start: self.thread = Thread.run( "repeat", _repeat, self.message, self.every, Date(start), parent_thread=MAIN_THREAD, please_stop=self.please_stop, ).release()
def __init__(self, name, max=None, silent=False, unique=False, allow_add_after_close=False): """ max - LIMIT THE NUMBER IN THE QUEUE, IF TOO MANY add() AND extend() WILL BLOCK silent - COMPLAIN IF THE READERS ARE TOO SLOW unique - SET True IF YOU WANT ONLY ONE INSTANCE IN THE QUEUE AT A TIME """ self.name = name self.max = coalesce(max, 2**10) self.silent = silent self.allow_add_after_close = allow_add_after_close self.unique = unique self.closed = Signal( "stop adding signal for " + name) # INDICATE THE PRODUCER IS DONE GENERATING ITEMS TO QUEUE self.lock = Lock("lock for queue " + name) self.queue = deque()
def wait(self, till=None): """ THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED """ waiter = Signal() if self.waiting: # TELL ANOTHER THAT THE LOCK IS READY SOON other = self.waiting.pop() other.go() self.debug and _Log.note( "waiting with {{num}} others on {{name|quote}}", num=len(self.waiting), name=self.name, stack_depth=1) self.waiting.insert(0, waiter) else: self.debug and _Log.note("waiting by self on {{name|quote}}", name=self.name) self.waiting = [waiter] try: self.lock.release() self.debug and _Log.note("out of lock {{name|quote}}", name=self.name) (waiter | till).wait() self.debug and _Log.note( "done minimum wait (for signal {{till|quote}})", till=till.name if till else "", name=self.name) except Exception as e: if not _Log: _late_import() _Log.warning("problem", cause=e) finally: self.lock.acquire() self.debug and _Log.note("re-acquired lock {{name|quote}}", name=self.name) try: self.waiting.remove(waiter) self.debug and _Log.note("removed own signal from {{name|quote}}", name=self.name) except Exception: pass return bool(waiter)
class Thread(BaseThread): """ join() ENHANCED TO ALLOW CAPTURE OF CTRL-C, AND RETURN POSSIBLE THREAD EXCEPTIONS run() ENHANCED TO CAPTURE EXCEPTIONS """ num_threads = 0 def __init__(self, name, target, *args, **kwargs): BaseThread.__init__(self, -1, coalesce(name, "thread_" + text(object.__hash__(self)))) self.target = target self.end_of_thread = Data() self.args = args # ENSURE THERE IS A SHARED please_stop SIGNAL self.kwargs = copy(kwargs) self.please_stop = self.kwargs.get(PLEASE_STOP) if self.please_stop is None: self.please_stop = self.kwargs[PLEASE_STOP] = Signal( "please_stop for " + self.name ) self.please_stop.then(self.start) self.thread = None self.ready_to_stop = Signal("joining with " + self.name) self.stopped = Signal("stopped signal for " + self.name) if PARENT_THREAD in kwargs: del self.kwargs[PARENT_THREAD] self.parent = kwargs[PARENT_THREAD] else: self.parent = Thread.current() self.parent.add_child(self) def __enter__(self): return self def __exit__(self, type, value, traceback): if isinstance(type, BaseException): self.please_stop.go() # TODO: AFTER A WHILE START KILLING THREAD self.join() self.args = None self.kwargs = None def start(self): try: if self.thread: return self.thread = start_new_thread(Thread._run, (self,)) return self except Exception as e: Log.error("Can not start thread", e) def stop(self): """ SEND STOP SIGNAL, DO NOT BLOCK """ with self.child_locker: children = copy(self.children) for c in children: DEBUG and c.name and Log.note("Stopping thread {{name|quote}}", name=c.name) c.stop() self.please_stop.go() DEBUG and Log.note("Thread {{name|quote}} got request to stop", name=self.name) def _run(self): self.id = get_ident() with RegisterThread(self): try: if self.target is not None: a, k, self.args, self.kwargs = self.args, self.kwargs, None, None self.end_of_thread.response = self.target(*a, **k) except Exception as e: e = Except.wrap(e) self.end_of_thread.exception = e with self.parent.child_locker: emit_problem = self not in self.parent.children if emit_problem: # THREAD FAILURES ARE A PROBLEM ONLY IF NO ONE WILL BE JOINING WITH IT try: Log.error( "Problem in thread {{name|quote}}", name=self.name, cause=e ) except Exception: sys.stderr.write( str("ERROR in thread: " + self.name + " " + text(e) + "\n") ) finally: try: with self.child_locker: children = copy(self.children) for c in children: try: DEBUG and Log.note("Stopping thread " + c.name + "\n") c.stop() except Exception as e: Log.warning( "Problem stopping thread {{thread}}", thread=c.name, cause=e, ) for c in children: try: DEBUG and Log.note("Joining on thread " + c.name + "\n") c.join() except Exception as e: Log.warning( "Problem joining thread {{thread}}", thread=c.name, cause=e, ) finally: DEBUG and Log.note("Joined on thread " + c.name + "\n") del self.target, self.args, self.kwargs DEBUG and Log.note("thread {{name|quote}} stopping", name=self.name) except Exception as e: DEBUG and Log.warning( "problem with thread {{name|quote}}", cause=e, name=self.name ) finally: if not self.ready_to_stop: DEBUG and Log.note("thread {{name|quote}} is done, wait for join", name=self.name) # WHERE DO WE PUT THE THREAD RESULT? # IF NO THREAD JOINS WITH THIS, THEN WHAT DO WE DO WITH THE RESULT? # HOW LONG DO WE WAIT FOR ANOTHER TO ACCEPT THE RESULT? # # WAIT 60seconds, THEN SEND RESULT TO LOGGER (Till(seconds=60) | self.ready_to_stop).wait() self.stopped.go() if not self.ready_to_stop: if self.end_of_thread.exception: # THREAD FAILURES ARE A PROBLEM ONLY IF NO ONE WILL BE JOINING WITH IT try: Log.error( "Problem in thread {{name|quote}}", name=self.name, cause=e ) except Exception: sys.stderr.write( str("ERROR in thread: " + self.name + " " + text(e) + "\n") ) elif self.end_of_thread.response != None: Log.warning( "Thread {{thread}} returned a response, but was not joined with {{parent}} after 10min", thread=self.name, parent=self.parent.name ) else: # IF THREAD ENDS OK, AND NOTHING RETURNED, THEN FORGET ABOUT IT self.parent.remove_child(self) def is_alive(self): return not self.stopped def release(self): """ RELEASE THREAD TO FEND FOR ITSELF. THREAD CAN EXPECT TO NEVER JOIN. WILL SEND RESULTS TO LOGS WHEN DONE. PARENT THREAD WILL STILL ENSURE self HAS STOPPED PROPERLY """ self.ready_to_stop.go() return self def join(self, till=None): """ RETURN THE RESULT {"response":r, "exception":e} OF THE THREAD EXECUTION (INCLUDING EXCEPTION, IF EXISTS) """ if self is Thread: Log.error("Thread.join() is not a valid call, use t.join()") with self.child_locker: children = copy(self.children) for c in children: c.join(till=till) DEBUG and Log.note( "{{parent|quote}} waiting on thread {{child|quote}}", parent=Thread.current().name, child=self.name, ) self.ready_to_stop.go() (self.stopped | till).wait() if self.stopped: self.parent.remove_child(self) if not self.end_of_thread.exception: return self.end_of_thread.response else: Log.error( "Thread {{name|quote}} did not end well", name=self.name, cause=self.end_of_thread.exception, ) else: raise Except(context=THREAD_TIMEOUT) @staticmethod def run(name, target, *args, **kwargs): # ENSURE target HAS please_stop ARGUMENT if get_function_name(target) == "wrapper": pass # GIVE THE override DECORATOR A PASS elif PLEASE_STOP not in target.__code__.co_varnames: Log.error( "function must have please_stop argument for signalling emergency shutdown" ) Thread.num_threads += 1 output = Thread(name, target, *args, **kwargs) output.start() return output @staticmethod def current(): ident = get_ident() with ALL_LOCK: output = ALL.get(ident) if output is None: thread = BaseThread(ident) thread.cprofiler = CProfiler() thread.cprofiler.__enter__() with ALL_LOCK: ALL[ident] = thread Log.warning( "this thread is not known. Register this thread at earliest known entry point." ) return thread return output
class MainThread(BaseThread): def __init__(self): BaseThread.__init__(self, get_ident()) self.name = "Main Thread" self.please_stop = Signal() self.stopped = Signal() self.stop_logging = Log.stop self.timers = None self.shutdown_locker = allocate_lock() def stop(self): """ BLOCKS UNTIL ALL KNOWN THREADS, EXCEPT MainThread, HAVE STOPPED """ global DEBUG self_thread = Thread.current() if self_thread != MAIN_THREAD or self_thread != self: Log.error("Only the main thread can call stop() on main thread") DEBUG = True self.please_stop.go() join_errors = [] with self.child_locker: children = copy(self.children) for c in reversed(children): DEBUG and c.name and Log.note("Stopping thread {{name|quote}}", name=c.name) try: c.stop() except Exception as e: join_errors.append(e) for c in children: DEBUG and c.name and Log.note( "Joining on thread {{name|quote}}", name=c.name ) try: c.join() except Exception as e: join_errors.append(e) DEBUG and c.name and Log.note( "Done join on thread {{name|quote}}", name=c.name ) if join_errors: Log.error( "Problem while stopping {{name|quote}}", name=self.name, cause=unwraplist(join_errors), ) with self.shutdown_locker: if self.stopped: return self.stop_logging() self.timers.stop() self.timers.join() write_profiles(self.cprofiler) DEBUG and Log.note("Thread {{name|quote}} now stopped", name=self.name) self.stopped.go() def wait_for_shutdown_signal( self, please_stop=False, # ASSIGN SIGNAL TO STOP EARLY allow_exit=False, # ALLOW "exit" COMMAND ON CONSOLE TO ALSO STOP THE APP wait_forever=True, # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT ): """ FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUTDOWN IS REQUESTED CALLING THREAD WILL SLEEP UNTIL keyboard interrupt, OR please_stop, OR "exit" :param please_stop: :param allow_exit: :param wait_forever:: Assume all needed threads have been launched. When done :return: """ self_thread = Thread.current() if self_thread != MAIN_THREAD or self_thread != self: Log.error( "Only the main thread can sleep forever (waiting for KeyboardInterrupt)" ) if isinstance(please_stop, Signal): # MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL self.please_stop.then(please_stop.go) please_stop.then(self.please_stop.go) else: please_stop = self.please_stop if not wait_forever: # TRIGGER SIGNAL WHEN ALL CHILDREN THREADS ARE DONE with self_thread.child_locker: pending = copy(self_thread.children) children_done = AndSignals(self.please_stop, len(pending)) children_done.signal.then(self.please_stop.go) for p in pending: p.stopped.then(children_done.done) try: if allow_exit: _wait_for_exit(self.please_stop) else: _wait_for_interrupt(self.please_stop) Log.alert("Stop requested! Stopping...") except KeyboardInterrupt as _: Log.alert("SIGINT Detected! Stopping...") except SystemExit as _: Log.alert("SIGTERM Detected! Stopping...") finally: self.stop()
class Queue(object): """ SIMPLE MULTI-THREADED QUEUE (multiprocessing.Queue REQUIRES SERIALIZATION, WHICH IS DIFFICULT TO USE JUST BETWEEN THREADS) """ def __init__(self, name, max=None, silent=False, unique=False, allow_add_after_close=False): """ max - LIMIT THE NUMBER IN THE QUEUE, IF TOO MANY add() AND extend() WILL BLOCK silent - COMPLAIN IF THE READERS ARE TOO SLOW unique - SET True IF YOU WANT ONLY ONE INSTANCE IN THE QUEUE AT A TIME """ self.name = name self.max = coalesce(max, 2**10) self.silent = silent self.allow_add_after_close = allow_add_after_close self.unique = unique self.closed = Signal( "stop adding signal for " + name) # INDICATE THE PRODUCER IS DONE GENERATING ITEMS TO QUEUE self.lock = Lock("lock for queue " + name) self.queue = deque() def __iter__(self): try: while True: value = self.pop() if value is THREAD_STOP: break if value is not None: yield value except Exception as e: Log.warning("Tell me about what happened here", e) def add(self, value, timeout=None, force=False): """ :param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self """ with self.lock: if value is THREAD_STOP: # INSIDE THE lock SO THAT EXITING WILL RELEASE wait() self.queue.append(value) self.closed.go() return if not force: self._wait_for_queue_space(timeout=timeout) if self.closed and not self.allow_add_after_close: Log.error("Do not add to closed queue") if self.unique: if value not in self.queue: self.queue.append(value) else: self.queue.append(value) return self def push(self, value): """ SNEAK value TO FRONT OF THE QUEUE """ if self.closed and not self.allow_add_after_close: Log.error("Do not push to closed queue") with self.lock: self._wait_for_queue_space() if not self.closed: self.queue.appendleft(value) return self def push_all(self, values): """ SNEAK values TO FRONT OF THE QUEUE """ if self.closed and not self.allow_add_after_close: Log.error("Do not push to closed queue") with self.lock: self._wait_for_queue_space() if not self.closed: self.queue.extendleft(values) return self def pop_message(self, till=None): """ RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE DUMMY IMPLEMENTATION FOR DEBUGGING """ if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") return Null, self.pop(till=till) def extend(self, values): if self.closed and not self.allow_add_after_close: Log.error("Do not push to closed queue") with self.lock: # ONCE THE queue IS BELOW LIMIT, ALLOW ADDING MORE self._wait_for_queue_space() if not self.closed: if self.unique: for v in values: if v is THREAD_STOP: self.closed.go() continue if v not in self.queue: self.queue.append(v) else: for v in values: if v is THREAD_STOP: self.closed.go() continue self.queue.append(v) return self def _wait_for_queue_space(self, timeout=None): """ EXPECT THE self.lock TO BE HAD, WAITS FOR self.queue TO HAVE A LITTLE SPACE :param timeout: IN SECONDS """ wait_time = 5 (DEBUG and len(self.queue) > 1 * 1000 * 1000 ) and Log.warning("Queue {{name}} has over a million items") start = time() stop_waiting = Till(till=start + coalesce(timeout, DEFAULT_WAIT_TIME)) while not self.closed and len(self.queue) >= self.max: if stop_waiting: Log.error(THREAD_TIMEOUT) if self.silent: self.lock.wait(stop_waiting) else: self.lock.wait(Till(seconds=wait_time)) if not stop_waiting and len(self.queue) >= self.max: now = time() Log.alert( "Queue with name {{name|quote}} is full with ({{num}} items), thread(s) have been waiting {{wait_time}} sec", name=self.name, num=len(self.queue), wait_time=now - start) def __len__(self): with self.lock: return len(self.queue) def __nonzero__(self): with self.lock: return any(r != THREAD_STOP for r in self.queue) def pop(self, till=None): """ WAIT FOR NEXT ITEM ON THE QUEUE RETURN THREAD_STOP IF QUEUE IS CLOSED RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY :param till: A `Signal` to stop waiting and return None :return: A value, or a THREAD_STOP or None """ if till is not None and not isinstance(till, Signal): Log.error("expecting a signal") with self.lock: while True: if self.queue: return self.queue.popleft() if self.closed: break if not self.lock.wait(till=self.closed | till): if self.closed: break return None (DEBUG or not self.silent) and Log.note(self.name + " queue closed") return THREAD_STOP def pop_all(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ with self.lock: output = list(self.queue) self.queue.clear() return output def pop_one(self): """ NON-BLOCKING POP IN QUEUE, IF ANY """ with self.lock: if self.closed: return THREAD_STOP elif not self.queue: return None else: v = self.queue.popleft() if v is THREAD_STOP: # SENDING A STOP INTO THE QUEUE IS ALSO AN OPTION self.closed.go() return v def close(self): self.closed.go() def commit(self): pass def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()
class Process(object): def __init__(self, name, params, cwd=None, env=None, debug=False, shell=False, bufsize=-1): self.name = name self.service_stopped = Signal("stopped signal for " + strings.quote(name)) self.stdin = Queue("stdin for process " + strings.quote(name), silent=True) self.stdout = Queue("stdout for process " + strings.quote(name), silent=True) self.stderr = Queue("stderr for process " + strings.quote(name), silent=True) try: if cwd == None: cwd = os.getcwd() else: cwd = str(cwd) self.debug = debug or DEBUG self.service = service = subprocess.Popen( [str(p) for p in params], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=bufsize, cwd=cwd, env={ str(k): str(v) for k, v in set_default(env, os.environ).items() }, shell=shell) self.please_stop = Signal() self.please_stop.then(self._kill) self.child_locker = Lock() self.children = [ Thread.run(self.name + " stdin", self._writer, service.stdin, self.stdin, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stdout", self._reader, "stdout", service.stdout, self.stdout, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stderr", self._reader, "stderr", service.stderr, self.stderr, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " waiter", self._monitor, parent_thread=self), ] except Exception as e: Log.error("Can not call", e) self.debug and Log.note("{{process}} START: {{command}}", process=self.name, command=" ".join(map(strings.quote, params))) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.join(raise_on_error=True) def stop(self): self.stdin.add(THREAD_STOP) # ONE MORE SEND self.please_stop.go() def join(self, raise_on_error=False): self.service_stopped.wait() with self.child_locker: child_threads, self.children = self.children, [] for c in child_threads: c.join() if raise_on_error and self.returncode != 0: Log.error("{{process}} FAIL: returncode={{code}}\n{{stderr}}", process=self.name, code=self.service.returncode, stderr=list(self.stderr)) return self def remove_child(self, child): with self.child_locker: try: self.children.remove(child) except Exception: pass @property def pid(self): return self.service.pid @property def returncode(self): return self.service.returncode def _monitor(self, please_stop): with Timer(self.name): self.service.wait() self.debug and Log.note( "{{process}} STOP: returncode={{returncode}}", process=self.name, returncode=self.service.returncode) self.service_stopped.go() please_stop.go() def _reader(self, name, pipe, receive, please_stop): try: while not please_stop and self.service.returncode is None: line = to_text(pipe.readline().rstrip()) if line: receive.add(line) self.debug and Log.note("{{process}} ({{name}}): {{line}}", name=name, process=self.name, line=line) continue # GRAB A FEW MORE LINES for _ in range(100): try: line = to_text(pipe.readline().rstrip()) if line: receive.add(line) self.debug and Log.note( "{{process}} ({{name}}): {{line}}", name=name, process=self.name, line=line) break except Exception: break else: Till(seconds=5).wait() # GRAB A FEW MORE LINES max = 100 while max: try: line = to_text(pipe.readline().rstrip()) if line: max = 100 receive.add(line) self.debug and Log.note( "{{process}} ({{name}}): {{line}}", name=name, process=self.name, line=line) else: max -= 1 except Exception: break finally: pipe.close() receive.add(THREAD_STOP) self.debug and Log.note( "{{process}} ({{name}} is closed)", name=name, process=self.name) receive.add(THREAD_STOP) def _writer(self, pipe, send, please_stop): while not please_stop: line = send.pop(till=please_stop) if line is THREAD_STOP: please_stop.go() break elif line is None: continue self.debug and Log.note("{{process}} (stdin): {{line}}", process=self.name, line=line.rstrip()) pipe.write(line.encode('utf8') + b"\n") pipe.flush() def _kill(self): try: self.service.kill() Log.note("Service was successfully terminated.") except Exception as e: ee = Except.wrap(e) if 'The operation completed successfully' in ee: return if 'No such process' in ee: return Log.warning("Failure to kill process {{process|quote}}", process=self.name, cause=ee)
def daemon(please_stop): global enabled enabled.go() sorted_timers = [] try: while not please_stop: now = time() with Till.locker: later = Till.next_ping - now if later > 0: try: sleep(min(later, INTERVAL)) except Exception as e: Log.warning( "Call to sleep failed with ({{later}}, {{interval}})", later=later, interval=INTERVAL, cause=e ) continue with Till.locker: Till.next_ping = now + INTERVAL new_timers, Till.new_timers = Till.new_timers, [] if DEBUG and new_timers: if len(new_timers) > 5: Log.note("{{num}} new timers", num=len(new_timers)) else: Log.note("new timers: {{timers}}", timers=[t for t, _ in new_timers]) sorted_timers.extend(new_timers) if sorted_timers: sorted_timers.sort(key=actual_time) for i, rec in enumerate(sorted_timers): t = actual_time(rec) if now < t: work, sorted_timers = sorted_timers[:i], sorted_timers[i:] Till.next_ping = min(Till.next_ping, sorted_timers[0].timestamp) break else: work, sorted_timers = sorted_timers, [] if work: DEBUG and Log.note( "done: {{timers}}. Remaining {{pending}}", timers=[t for t, s in work] if len(work) <= 5 else len(work), pending=[t for t, s in sorted_timers] if len(sorted_timers) <= 5 else len(sorted_timers) ) for t, r in work: s = r() if s is not None: s.go() except Exception as e: Log.warning("unexpected timer shutdown", cause=e) finally: DEBUG and Log.alert("TIMER SHUTDOWN") enabled = Signal() # TRIGGER ALL REMAINING TIMERS RIGHT NOW with Till.locker: new_work, Till.new_timers = Till.new_timers, [] for t, r in new_work + sorted_timers: s = r() if s is not None: s.go()
# FOR FAST AND PREDICTABLE SHUTDOWN AND CLEANUP OF THREADS from __future__ import absolute_import, division, unicode_literals from collections import namedtuple from time import sleep, time from weakref import ref from mo_future import allocate_lock as _allocate_lock, text from mo_logs import Log from mo_threads.signals import DONE, Signal DEBUG = False INTERVAL = 0.1 enabled = Signal() class Till(Signal): """ TIMEOUT AS A SIGNAL """ __slots__ = [] locker = _allocate_lock() next_ping = time() new_timers = [] def __new__(cls, till=None, seconds=None): if not enabled: Log.note("Till daemon not enabled")
class Process(object): next_process_id = 0 def __init__(self, name, params, cwd=None, env=None, debug=False, shell=False, bufsize=-1): """ Spawns multiple threads to manage the stdin/stdout/stderr of the child process; communication is done via proper thread-safe queues of the same name. Since the process is managed and monitored by threads, the main thread is not blocked when the child process encounters problems :param name: name given to this process :param params: list of strings for program name and parameters :param cwd: current working directory :param env: enviroment variables :param debug: true to be verbose about stdin/stdout :param shell: true to run as command line :param bufsize: if you want to screw stuff up """ self.debug = debug or DEBUG self.process_id = Process.next_process_id Process.next_process_id += 1 self.name = name + " (" + text(self.process_id) + ")" self.service_stopped = Signal("stopped signal for " + strings.quote(name)) self.stdin = Queue("stdin for process " + strings.quote(name), silent=not self.debug) self.stdout = Queue("stdout for process " + strings.quote(name), silent=not self.debug) self.stderr = Queue("stderr for process " + strings.quote(name), silent=not self.debug) try: if cwd == None: cwd = os.getcwd() else: cwd = str(cwd) command = [str(p) for p in params] self.debug and Log.note("command: {{command}}", command=command) self.service = service = subprocess.Popen( [str(p) for p in params], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=bufsize, cwd=cwd, env={ str(k): str(v) for k, v in set_default(env, os.environ).items() }, shell=shell) self.please_stop = Signal() self.please_stop.then(self._kill) self.child_locker = Lock() self.children = [ Thread.run(self.name + " stdin", self._writer, service.stdin, self.stdin, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stdout", self._reader, "stdout", service.stdout, self.stdout, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " stderr", self._reader, "stderr", service.stderr, self.stderr, please_stop=self.service_stopped, parent_thread=self), Thread.run(self.name + " waiter", self._monitor, parent_thread=self), ] except Exception as e: Log.error("Can not call", e) self.debug and Log.note("{{process}} START: {{command}}", process=self.name, command=" ".join(map(strings.quote, params))) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.join(raise_on_error=True) def stop(self): self.stdin.add(THREAD_STOP) # ONE MORE SEND self.please_stop.go() def join(self, raise_on_error=False): self.service_stopped.wait() with self.child_locker: child_threads, self.children = self.children, [] for c in child_threads: c.join() if raise_on_error and self.returncode != 0: Log.error("{{process}} FAIL: returncode={{code}}\n{{stderr}}", process=self.name, code=self.service.returncode, stderr=list(self.stderr)) return self def remove_child(self, child): with self.child_locker: try: self.children.remove(child) except Exception: pass @property def pid(self): return self.service.pid @property def returncode(self): return self.service.returncode def _monitor(self, please_stop): with Timer(self.name, verbose=self.debug): self.service.wait() self.debug and Log.note( "{{process}} STOP: returncode={{returncode}}", process=self.name, returncode=self.service.returncode) self.service_stopped.go() please_stop.go() def _reader(self, name, pipe, receive, please_stop): try: while not please_stop and self.service.returncode is None: line = to_text(pipe.readline().rstrip()) if line: receive.add(line) self.debug and Log.note("{{process}} ({{name}}): {{line}}", name=name, process=self.name, line=line) else: (Till(seconds=1) | please_stop).wait() # GRAB A FEW MORE LINES max = 100 while max: try: line = to_text(pipe.readline().rstrip()) if line: max = 100 receive.add(line) self.debug and Log.note( "{{process}} RESIDUE: ({{name}}): {{line}}", name=name, process=self.name, line=line) else: max -= 1 except Exception: break finally: pipe.close() receive.add(THREAD_STOP) self.debug and Log.note( "{{process}} ({{name}} is closed)", name=name, process=self.name) receive.add(THREAD_STOP) def _writer(self, pipe, send, please_stop): while not please_stop: line = send.pop(till=please_stop) if line is THREAD_STOP: please_stop.go() break elif line is None: continue self.debug and Log.note("{{process}} (stdin): {{line}}", process=self.name, line=line.rstrip()) pipe.write(line.encode('utf8') + b"\n") pipe.flush() def _kill(self): try: self.service.kill() Log.note("Service was successfully terminated.") except Exception as e: ee = Except.wrap(e) if 'The operation completed successfully' in ee: return if 'No such process' in ee: return Log.warning("Failure to kill process {{process|quote}}", process=self.name, cause=ee)