A signal handler used to print asyncio task stacks and thread stacks.
196987
def _asynciostacks(*args, **kwargs):  # pragma: no cover
    '''
    
    '''
    print(80 * '*')
    print('Asyncio tasks stacks:')
    tasks = asyncio.all_tasks(_glob_loop)
    for task in tasks:
        task.print_stack()
    print(80 * '*')
    print('Faulthandler stack frames per thread:')
    faulthandler.dump_traceback()
    print(80 * '*')
926143
def dump_stacks(self):
        '''
        
        '''

        dump = []

        # threads
        threads = dict([(th.ident, th.name)
                            for th in threading.enumerate()])

        for thread, frame in sys._current_frames().items():
            if thread not in threads: continue
            dump.append('Thread 0x%x (%s)\n' % (thread, threads[thread]))
            dump.append(''.join(traceback.format_stack(frame)))
            dump.append('\n')

        return ''.join(dump)
280061
def sample_stack_all(count=10, interval=0.1):
    """"""

    def print_stack_all(l, ll):
        l1 = list()
        l1.append("*** STACKTRACE - START ***")
        code = []
        for threadId, stack in sys._current_frames().items():
            sub_code = []
            sub_code.append("# ThreadID: %s" % threadId)
            for filename, lineno, name, line in traceback.extract_stack(stack):
                sub_code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
                if line:
                    sub_code.append("  %s" % (line.strip()))
            if not "in select" in sub_code[-2] and \
               not "in wait" in sub_code[-2] and \
               not "in print_stack_all" in sub_code[-2] and \
               not "in sample_stack_all" in sub_code[-2] and \
               not "in checkcache" in sub_code[-2] and \
               not "do_sleep" in sub_code[-2] and \
               not "sleep" in sub_code[-1] and \
               not any(["in do_sample" in s for s in sub_code]):
                code.extend(sub_code)
        for line in code:
            l1.append(line)
        l1.append("*** STACKTRACE - END ***")
        with l:
            ll.extend(l1)

    def do_sample():
        l = threading.RLock()
        ll = list()
        for i in range(count):
            print_stack_all(l, ll)
            time.sleep(interval)
        with l:
            print("\n".join(ll))

    threading.Thread(target=do_sample).start()
535340
def sig_handler(self, sig, _):
        
        import tornado.ioloop
        from tornado.process import task_id
        tid = task_id()
        pid = os.getpid()
        if tid is None:
            logger.warning("main process (pid %s) caught signal: %s" %
                           (pid, sig))
        else:
            logger.warning("child %s (pid %s) caught signal: %s" %
                           (tid, pid, sig))
        tornado.ioloop.IOLoop.current().add_callback(self.shutdown)
282783
def _signal_handler(self, signal_interupt, frame):  # pylint: disable=W0613
        
        if self.container is not None:
            print('{}{}Stopping docker container.'.format(c.Style.BRIGHT, c.Fore.YELLOW))
            self.container.stop()
        print('{}{}Interrupt signal received.'.format(c.Style.BRIGHT, c.Fore.RED))
        self.log.error('tcrun received an interrupt signal and will now exit.')
        sys.exit(1)
215848
def __process_requests_stack(self):
        

        while self.__requests_stack:
            try:
                exec self.__requests_stack.popleft() in self.__locals
            except Exception as error:
                umbra.exceptions.notify_exception_handler(error)
68906
def show_event_handlers(self, stream=sys.stdout, verbose=0):
        """"""
        lines = ["List of event handlers installed:"]
        for handler in self.event_handlers:
            if verbose:
                lines.extend(handler.__class__.cls2str().split("\n"))
            else:
                lines.extend(str(handler).split("\n"))

        stream.write("\n".join(lines))
        stream.write("\n")
162509
def print_stack_events(self):
        '''
        
        '''
        first_token = '7be7981bd6287dd8112305e8f3822a6f'
        keep_going = True
        next_token = first_token
        current_request_token = None
        rows = []
        try:
            while keep_going and next_token:
                if next_token == first_token:
                    response = self._cf_client.describe_stack_events(
                        StackName=self._stack_name
                    )
                else:
                    response = self._cf_client.describe_stack_events(
                        StackName=self._stack_name,
                        NextToken=next_token
                    )

                next_token = response.get('NextToken', None)
                for event in response['StackEvents']:
                    row = []
                    event_time = event.get('Timestamp')
                    request_token = event.get('ClientRequestToken', 'unknown')
                    if current_request_token is None:
                        current_request_token = request_token
                    elif current_request_token != request_token:
                        keep_going = False
                        break

                    row.append(event_time.strftime('%x %X'))
                    row.append(event.get('LogicalResourceId'))
                    row.append(event.get('ResourceStatus'))
                    row.append(event.get('ResourceStatusReason', ''))
                    rows.append(row)

            if len(rows) > 0:
                print('\nEvents for the current upsert:')
                print(tabulate(rows, headers=['Time', 'Logical ID', 'Status', 'Message']))
                return True
            else:
                print('\nNo stack events found\n')
        except Exception as wtf:
            print(wtf)

        return False
446117
def signal_handler_as(sig, handler):
  
  old_handler = signal.signal(sig, handler)
  try:
    yield
  finally:
    signal.signal(sig, old_handler)
357188
def print_stack(sig, frame):
    """"""
    if _debug: print_stack._debug("print_stack %r %r", sig, frame)
    global running, deferredFns, sleeptime

    sys.stderr.write("==== USR1 Signal, %s\n" % time.strftime("%d-%b-%Y %H:%M:%S"))

    sys.stderr.write("---------- globals\n")
    sys.stderr.write("    running: %r\n" % (running,))
    sys.stderr.write("    deferredFns: %r\n" % (deferredFns,))
    sys.stderr.write("    sleeptime: %r\n" % (sleeptime,))

    sys.stderr.write("---------- stack\n")
    traceback.print_stack(frame)

    # make a list of interesting frames
    flist = []
    f = frame
    while f.f_back:
        flist.append(f)
        f = f.f_back

    # reverse the list so it is in the same order as print_stack
    flist.reverse()
    for f in flist:
        sys.stderr.write("---------- frame: %s\n" % (f,))
        for k, v in f.f_locals.items():
            sys.stderr.write("    %s: %r\n" % (k, v))

    sys.stderr.flush()
158488
def threadsafe_call(self, fn, *args, **kwargs):
        """"""
        def handler():
            try:
                fn(*args, **kwargs)
            except Exception:
                warn("error caught while excecuting async callback\n%s\n",
                     format_exc())

        def greenlet_wrapper():
            gr = greenlet.greenlet(handler)
            gr.switch()

        self._async_session.threadsafe_call(greenlet_wrapper)
1158553
public void printTopStack() throws IOException {
		System.out.printf("%n Stack trace of top %d threads:%n", view.threadLimit);

		ThreadInfo[] infos = view.topThreadInfo.getTopThreadInfo();
		for (ThreadInfo info : infos) {
			if (info == null) {
				continue;
			}
			printSingleThread(info);
		}
		System.out.flush();
	}
94818
def _thread_worker(self):
        """"""
        while self._running:
            # Retrieve next cmd, or block
            packet = self._queue.get(True)
            if isinstance(packet, dict) and QS_CMD in packet:
                try:
                    self._callback_listen(packet)
                except Exception as err:  # pylint: disable=broad-except
                    _LOGGER.error("Exception in callback\nType: %s: %s",
                                  type(err), err)
            self._queue.task_done()
20700
def signal(self, details):
        
        log = self._params.get('log', self._discard)
        if '_signal' not in dir(self._parent) or not callable(getattr(self._parent, '_signal')):
            log.error("Event parent '%s' has no '_signal' method", self._name)
            return
        sig = utils.signum(self._handler_arg)
        if sig is None:
            log.error("Invalid signal '%s' for task '%s'", self._handler_arg, sig._name)
            return
        log.info("sending %s to all '%s' processes", utils.signame(sig), self._name)
        self._parent._signal(sig)
271000
async def addSignalHandlers(self):
        '''
        
        '''

        def sigterm():
            print('Caught SIGTERM, shutting down.')
            asyncio.create_task(self.fini())

        def sigint():
            print('Caught SIGINT, shutting down.')
            asyncio.create_task(self.fini())

        loop = asyncio.get_running_loop()
        loop.add_signal_handler(signal.SIGINT, sigint)
        loop.add_signal_handler(signal.SIGTERM, sigterm)
294111
def _reader_thread_proc(self, timeout):
    """"""
    for data in self.stream.read_until_close(timeout_ms=timeout):
      if self.stdout is not None:
        self.stdout.write(data)
1070906
def __print_async(self, frame_type, headers, body):
        
        if self.__quit:
            return
        if self.verbose:
            self.__sysout(frame_type)
            for k, v in headers.items():
                self.__sysout('%s: %s' % (k, v))
        else:
            if 'message-id' in headers:
                self.__sysout('message-id: %s' % headers['message-id'])
            if 'subscription' in headers:
                self.__sysout('subscription: %s' % headers['subscription'])
        if self.prompt != '':
            self.__sysout('')
        self.__sysout(body)
        if not self.__start:
            self.__sysout(self.prompt, end='')
        else:
            self.__start = False
        self.stdout.flush()