class Queue(object): """ SIMPLE MESSAGE QUEUE, multiprocessing.Queue REQUIRES SERIALIZATION, WHICH IS DIFFICULT TO USE JUST BETWEEN THREADS (SERIALIZATION REQUIRED) """ 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 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.pop() 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) 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)
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) self.name = coalesce(name, "thread_" + text(object.__hash__(self))) self.target = target self.end_of_thread = Data() self.synch_lock = Lock("response synch lock") 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.thread = None self.join_attempt = 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: 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): # if self.trace_func: # sys.settrace(self.trace_func) # self.trace_func = None 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) with self.synch_lock: 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: (Till(seconds=60) | self.join_attempt).wait() self.stopped.go() DEBUG and Log.note("thread {{name|quote}} is done, wait for join", name=self.name) if not self.join_attempt: 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 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.join_attempt.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 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)
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()