# Copyright 2012 James McCauley
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Primitive help for debugging deadlocks.
Prints stack info for all threads.
(Might be more useful if it only printed stack frames that
were not changing, sort of like recoco_spy.)

This was initially factored out from a pox.py modification by
Colin or Andi.
"""

import sys
import time
import inspect
import traceback
import threading
from pox.core import core

def _trace_thread_proc ():
  try:
    while core.running:
      frames = sys._current_frames()
      for key in frames:
        frame = frames[key]
        print(inspect.getframeinfo(frame))
        outer_frames = inspect.getouterframes(frame)
        for i in range(0, len(outer_frames)):
          print("     " + str(inspect.getframeinfo(outer_frames[i][0])))

      time.sleep(5)
  except:
    traceback.print_exc()


def launch ():

  _trace_thread = threading.Thread(target=_trace_thread_proc)
  _trace_thread.daemon = True

  # Start it up a bit in the future so that it doesn't print all over
  # init messages.
  core.callDelayed(3, _trace_thread.start)

@@ -936,16 +936,400 @@
 ort core
+%0Aimport os%0Abase_path = __file__%0Abase_path = os.path.split(base_path)%5B0%5D%0Abase_path = os.path.split(base_path)%5B0%5D%0Abase_path += os.path.sep%0A%0Adef fmt_tb (tb):%0A  f = tb.filename%0A  if f.startswith(base_path):%0A    f = f%5Blen(base_path):%5D%0A  l = %22%25s:%25i%22 %25 (f, tb.lineno)%0A  code = tb.code_context%0A  if code: code = code%5B0%5D.strip()%0A  if not code: code = %22%3CUnknown%3E%22%0A  return %22%2520s: %25s%22 %25 (l,code)
 %0A%0Adef _t
@@ -1484,16 +1484,23 @@
   print(
+fmt_tb(
 inspect.
@@ -1519,16 +1519,17 @@
 (frame))
+)
 %0A       
@@ -1641,20 +1641,20 @@
 nt(%22
-   
   %22 + 
-str
+fmt_tb
 (ins

Improve debug_deadlock formatting