Simpler thread to track whether main thread has been quiet for long enough
	that a thread dump should be printed.
357229
def managing_thread_main_simple():
	
	import shutit_global
	last_msg = ''
	while True:
		printed_anything = False
		if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > 10:
			this_msg = ''
			this_header = ''
			for thread_id, stack in sys._current_frames().items():
				# ignore own thread:
				if thread_id == threading.current_thread().ident:
					continue
				printed_thread_started = False
				for filename, lineno, name, line in traceback.extract_stack(stack):
					if not printed_anything:
						printed_anything = True
						this_header += '\n='*80 + '\n'
						this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str(thread_id) + ' at ' + time.strftime('%c') + '\n'
						this_header += '='*80 + '\n'
					if not printed_thread_started:
						printed_thread_started = True
					this_msg += '%s:%d:%s' % (filename, lineno, name) + '\n'
					if line:
						this_msg += '  %s' % (line,) + '\n'
			if printed_anything:
				this_msg += '='*80 + '\n'
				this_msg += 'STACK TRACES DONE\n'
				this_msg += '='*80 + '\n'
			if this_msg != last_msg:
				print(this_header + this_msg)
				last_msg = this_msg
		time.sleep(5)
829655
def _MainThreadProc(self):
    """"""
    registration_required = True
    while not self._shutdown:
      if registration_required:
        service = self._BuildService()
        registration_required, delay = self._RegisterDebuggee(service)

      if not registration_required:
        registration_required, delay = self._ListActiveBreakpoints(service)

      if self.on_idle is not None:
        self.on_idle()

      if not self._shutdown:
        time.sleep(delay)
189675
public synchronized boolean getThreadCpuTimes(int pid, long[] result) {
        int rc = GetThreadTimes(pid, callBuf);
        if (rc == 0) {
            long ktime = (0xFFFFFFFFl & callBuf[4]) | ((long)callBuf[5]) << 32;
            long utime = (0xFFFFFFFFl & callBuf[6]) | ((long)callBuf[7]) << 32;
            
            result[0] = ktime / 10;
            result[1] = utime / 10;
            return true;
        }
        else {
            System.out.println("Error code: " + rc);
            return false;
        }
    }
271729
def _main_loop(self):
        '''
        
        '''
        self.logger.debug("Running main loop")
        old_time = 0
        while True:
            for plugin_key in self.plugins_dict:
                obj = self.plugins_dict[plugin_key]
                self._process_plugin(obj)

            if self.settings['STATS_DUMP'] != 0:
                new_time = int(old_div(time.time(), self.settings['STATS_DUMP']))
                # only log every X seconds
                if new_time != old_time:
                    self._dump_stats()

                    if self.settings['STATS_DUMP_CRAWL']:
                        self._dump_crawl_stats()

                    if self.settings['STATS_DUMP_QUEUE']:
                        self._dump_queue_stats()

                    old_time = new_time
            self._report_self()
            time.sleep(self.settings['SLEEP_TIME'])
1054012
def wait_until_idle(self):
        

        done = threading.Event()

        def _callback():
            done.set()

        self.defer_until_idle(_callback)
        done.wait()
1047443
public static void assertMainThread() {
		if (imp != null && !DispatchQueue.isMainQueue()) {
			imp.assertFailed(StringUtils.format("Expected 'main' thread but was '%s'", Thread.currentThread().getName()));
		}
	}
658757
public void print(java.io.PrintWriter printWriter)
    {
        synchronized (flushHelper) {
            synchronized (notifyHelper) {
                synchronized (logBufferLock) {
                    printWriter.println("State Dump for:" + cclass.getName()
                                        + " logFile=" + logFile + "(java.io.RandomaccessFile)"
                                        + " fileLogHeader=" + fileLogHeader + "(FileLogHeader)"
                                        + "\n filePosition=" + filePosition + "(long)"
                                        + " filePositionSectorByte=" + filePositionSectorByte + "(byte)"
                                        + " bufferFilePosition=" + bufferFilePosition + "(long)"
                                        + " bufferSectorByte=" + bufferSectorByte + "(byte)"
                                        + " fileSpaceLeft=" + fileSpaceLeft + "(long)"
                                    );
                    printWriter.println(" firstPageToFlush=" + firstPageToFlush + "(int)"
                                        + " lastPageNotified=" + lastPageNotified + "(int)"
                                        + " nextPageToNotify=" + nextPageToNotify + "(int)"
                                        + " firstPageFilling=" + firstPageFilling + "(int)"
                                        + " lastPageFilling=" + lastPageFilling + "(int)"
                                        + "\n nextFreeByteInLogBuffer=" + nextFreeByteInLogBuffer + "(int)"
                                        + " newLogBufferPages=" + newLogBufferPages + "(int)"
                                    );
                    printWriter.println();

                    logBuffer.print(printWriter);
                } // synchronized (logBufferLock).
            } // synchronized (notifyHelper).
        } // synchronized (flushHelper).
    }
815971
public void checkAllThreads() {

        // if nothing is plugged in, exit early
        if (this.monitorPlugin == null) {
            return;
        }

        long currentTime = 0; // lazily initialize current time

        try {
            for (Iterator i = this.threads_.values().iterator(); i.hasNext();) {

                Worker thread = (Worker) i.next();
                synchronized (thread) { // d204471
                    if (thread.getStartTime() > 0) {
                        if (currentTime == 0) {
                            currentTime = System.currentTimeMillis();
                        }

                        if (!thread.isHung && this.monitorPlugin.checkThread(thread, thread.threadNumber, currentTime - thread.getStartTime())) { // PK25446
                            thread.isHung = true;
                        }
                    }
                }
            }

            this.lastThreadCheckDidntComplete = false; // D222794
        } catch (ConcurrentModificationException e) { // begin D222794
            // NOTE: we can pretty much ignore this exception ... if
            // we occasionally fail on the check, we'll be OK. So
            // we simply keep track with a flag. If two consecutive
            // checks fail, then we'll log to FFDC
            if (this.lastThreadCheckDidntComplete) {
                // Alex Ffdc.log(e, this, this.getClass().getName(), "1181", this); //
                // D477704.2
            }
            this.lastThreadCheckDidntComplete = true;
        } // end D222794
    }
695131
def monitor(seconds_frozen, test_interval):
    
    current_thread = threading.current_thread()
    hanging_threads = set()
    old_threads = {}  # Threads found on previous iteration.

    while not current_thread.is_stopped():
        new_threads = get_current_frames()

        # Report died threads.
        for thread_id in old_threads.keys():
            if thread_id not in new_threads and thread_id in hanging_threads:
                log_died_thread(thread_id)

        # Process live threads.
        time.sleep(test_interval/1000.)
        now = time.time()
        then = now - seconds_frozen
        for thread_id, thread_data in new_threads.items():
            # Don't report the monitor thread.
            if thread_id == current_thread.ident:
                continue
            frame = thread_data['frame']
            # If thread is new or it's stack is changed then update time.
            if (thread_id not in old_threads or
                    frame != old_threads[thread_id]['frame']):
                thread_data['time'] = now
                # If the thread was hanging then report awaked thread.
                if thread_id in hanging_threads:
                    hanging_threads.remove(thread_id)
                    log_awaked_thread(thread_id)
            else:
                # If stack is not changed then keep old time.
                last_change_time = old_threads[thread_id]['time']
                thread_data['time'] = last_change_time
                # Check if this is a new hanging thread.
                if (thread_id not in hanging_threads and
                        last_change_time < then):
                    # Gotcha!
                    hanging_threads.add(thread_id)
                    # Report the hanged thread.
                    log_hanged_thread(thread_id, frame)
        old_threads = new_threads
574735
def output_thread(log, stdout, stderr, timeout_event, is_alive, quit,
        stop_output_event):
    

    poller = Poller()
    if stdout is not None:
        poller.register_read(stdout)
    if stderr is not None:
        poller.register_read(stderr)

    # this is our poll loop for polling stdout or stderr that is ready to
    # be read and processed.  if one of those streamreaders indicate that it
    # is done altogether being read from, we remove it from our list of
    # things to poll.  when no more things are left to poll, we leave this
    # loop and clean up
    while poller:
        changed = no_interrupt(poller.poll, 0.1)
        for f, events in changed:
            if events & (POLLER_EVENT_READ | POLLER_EVENT_HUP):
                log.debug("%r ready to be read from", f)
                done = f.read()
                if done:
                    poller.unregister(f)
            elif events & POLLER_EVENT_ERROR:
                # for some reason, we have to just ignore streams that have had an
                # error.  i'm not exactly sure why, but don't remove this until we
                # figure that out, and create a test for it
                pass

        if timeout_event and timeout_event.is_set():
            break

        if stop_output_event.is_set():
            break

    # we need to wait until the process is guaranteed dead before closing our
    # outputs, otherwise SIGPIPE
    alive, _ = is_alive()
    while alive:
        quit.wait(1)
        alive, _ = is_alive()

    if stdout:
        stdout.close()

    if stderr:
        stderr.close()
1051744
def thread_details(io_handler, thread_id, max_depth=0):
        
        # Normalize maximum depth
        try:
            max_depth = int(max_depth)
            if max_depth < 1:
                max_depth = None
        except (ValueError, TypeError):
            max_depth = None

        # pylint: disable=W0212
        try:
            # Get the stack
            thread_id = int(thread_id)
            stack = sys._current_frames()[thread_id]
        except KeyError:
            io_handler.write_line("Unknown thread ID: {0}", thread_id)
        except ValueError:
            io_handler.write_line("Invalid thread ID: {0}", thread_id)
        except AttributeError:
            io_handler.write_line("sys._current_frames() is not available.")
        else:
            # Get the name
            try:
                name = threading._active[thread_id].name
            except KeyError:
                name = "<unknown>"

            lines = [
                "Thread ID: {0} - Name: {1}".format(thread_id, name),
                "Stack trace:",
            ]

            trace_lines = []
            depth = 0
            frame = stack
            while frame is not None and (
                max_depth is None or depth < max_depth
            ):
                # Store the line information
                trace_lines.append(format_frame_info(frame))

                # Previous frame...
                frame = frame.f_back
                depth += 1

            # Reverse the lines
            trace_lines.reverse()

            # Add them to the printed lines
            lines.extend(trace_lines)

            lines.append("")
            io_handler.write("\n".join(lines))
559832
def _main_thread_terminated(self):
        """"""
        if not self.is_alive:
            return

        if not self._queue.empty():
            print(
                "Program shutting down, attempting to send %d queued log "
                "entries to Stackdriver Logging..." % (self._queue.qsize(),),
                file=sys.stderr,
            )

        if self.stop(self._grace_period):
            print("Sent all pending logs.", file=sys.stderr)
        else:
            print(
                "Failed to send %d pending logs." % (self._queue.qsize(),),
                file=sys.stderr,
            )
614153
private void readThreads(){
		long[] ids = threadMxBean.getAllThreadIds();

		Map<Thread.State, Long> count = new EnumMap<>(Thread.State.class);
		for (int i = 0; i<ids.length; i++){
			long id = ids[i];
			ThreadInfo info = threadMxBean.getThreadInfo(id);
			if (info!=null){
				Thread.State state = info.getThreadState();

				Long old = count.get(state);
				if (old==null) {
					old = 0L;
				}
				count.put(state, old+1);
			}
		}

		long total = 0;
		for (Map.Entry<Thread.State, ThreadStateStats> entry : statsMap.entrySet()){
			Long c = count.get(entry.getKey());
			entry.getValue().updateCurrentValue(c==null ? 0 : c.longValue());
			if (c!=null)
				total += c.longValue();
		}
		cumulated.updateCurrentValue(total);

	}
1303140
public void dump(Printer printer, boolean verbose) {
        Printer indentedPrinter = printer;
        synchronized (mLock) {
            printer.println("Connection pool for " + mConfiguration.path + ":");
            printer.println("  Open: " + mIsOpen);
            printer.println("  Max connections: " + mMaxConnectionPoolSize);

            printer.println("  Available primary connection:");
            if (mAvailablePrimaryConnection != null) {
                mAvailablePrimaryConnection.dump(indentedPrinter, verbose);
            } else {
                indentedPrinter.println("<none>");
            }

            printer.println("  Available non-primary connections:");
            if (!mAvailableNonPrimaryConnections.isEmpty()) {
                final int count = mAvailableNonPrimaryConnections.size();
                for (int i = 0; i < count; i++) {
                    mAvailableNonPrimaryConnections.get(i).dump(indentedPrinter, verbose);
                }
            } else {
                indentedPrinter.println("<none>");
            }

            printer.println("  Acquired connections:");
            if (!mAcquiredConnections.isEmpty()) {
                for (Map.Entry<SQLiteConnection, AcquiredConnectionStatus> entry :
                        mAcquiredConnections.entrySet()) {
                    final SQLiteConnection connection = entry.getKey();
                    connection.dumpUnsafe(indentedPrinter, verbose);
                    indentedPrinter.println("  Status: " + entry.getValue());
                }
            } else {
                indentedPrinter.println("<none>");
            }

            printer.println("  Connection waiters:");
            if (mConnectionWaiterQueue != null) {
                int i = 0;
                final long now = SystemClock.uptimeMillis();
                for (ConnectionWaiter waiter = mConnectionWaiterQueue; waiter != null;
                        waiter = waiter.mNext, i++) {
                    indentedPrinter.println(i + ": waited for "
                            + ((now - waiter.mStartTime) * 0.001f)
                            + " ms - thread=" + waiter.mThread
                            + ", priority=" + waiter.mPriority
                            + ", sql='" + waiter.mSql + "'");
                }
            } else {
                indentedPrinter.println("<none>");
            }
        }
    }
940719
def _write_status_to_log(self, return_code, stream=sys.stdout):
        """"""
        stream.write("Timestamp: %i\n" % get_timestamp())
        if return_code == 0:
            stream.write("%s\n" % self._interface.string_successful)
        else:
            stream.write("%s %i\n" %
                         (self._interface.string_exited, return_code))
96602
@GET
    @Path("stack")
    @Produces(MediaType.TEXT_PLAIN)
    public String getThreadDump() {
        if (LOG.isDebugEnabled()) {
            LOG.debug("==> AdminResource.getThreadDump()");
        }

        ThreadGroup topThreadGroup = Thread.currentThread().getThreadGroup();

        while (topThreadGroup.getParent() != null) {
            topThreadGroup = topThreadGroup.getParent();
        }
        Thread[] threads = new Thread[topThreadGroup.activeCount()];

        int nr = topThreadGroup.enumerate(threads);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < nr; i++) {
            builder.append(threads[i].getName()).append("\nState: ").
                    append(threads[i].getState()).append("\n");
            String stackTrace = StringUtils.join(threads[i].getStackTrace(), "\n");
            builder.append(stackTrace);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("<== AdminResource.getThreadDump()");
        }

        return builder.toString();
    }
140651
def log_debug(func, *args, **kwargs):
    '''  '''
    logging.debug('Starting "%s" in thread %s...', func.__name__, current_thread())
    results = func(*args, **kwargs)
    logging.debug('Successfully finished "%s" in thread %s.', func.__name__, current_thread())
    return results