1
2import traceback, sys, string, time, socket, os
3import who_calls
4
5#DUMP_DIR = "/neo/data/bugs"
6DUMP_DIR = "/tmp/bugs"
7
8Warning = "handle_error.Warning"
9
10# levels
11LV_MESSAGE = "LV_MESSAGE"
12LV_WARNING = "LV_WARNING"
13LV_ERROR   = "LV_ERROR"
14
15Count = 0
16
17gErrorCount = 0
18DISABLE_DUMP = 0
19
20def exceptionReason():
21  return "%s.%s" % (str(sys.exc_type), str(sys.exc_value))
22
23def exceptionString():
24  tb_list = traceback.format_exception(sys.exc_type,sys.exc_value,sys.exc_traceback)
25  return string.join(tb_list,"")
26
27  #### old way
28  import StringIO
29  ## get the traceback message
30  sfp = StringIO.StringIO()
31  traceback.print_exc(file=sfp)
32  exception = sfp.getvalue()
33  sfp.close()
34
35  return exception
36
37
38def handleException (msg=None, lvl=LV_ERROR, dump = 1):
39  global gErrorCount
40  gErrorCount = gErrorCount + 1
41
42  tb_list = traceback.format_exception(sys.exc_type,sys.exc_value,sys.exc_traceback)
43  if msg:
44    sys.stderr.write ("%s\n" % msg)
45  else:
46    msg = "Unhandled Exception"
47
48  sys.stderr.write (string.join(tb_list,""))
49  try:
50    if dump: dump_bug(lvl, "handleException", msg, string.join(tb_list, ""))
51  except:
52    handleException("Unable to dump_bug", dump = 0)
53
54def handleWarning (msg=""):
55  header = "*** handleWarning: %s\n" % msg
56  sys.stderr.write(header)
57  tb = who_calls.pretty_who_calls(strip=1) + "\n"
58  sys.stderr.write(tb)
59
60  try:
61    dump_bug(LV_WARNING, "handleException", msg, tb)
62  except:
63    handleException("Unable to dump_bug", dump = 0)
64
65def checkPaths():
66  paths = (DUMP_DIR,
67           os.path.join (DUMP_DIR, "tmp"),
68           os.path.join (DUMP_DIR, "new"))
69  for path in paths:
70    if not os.path.isdir(path):
71      os.mkdir(path, 0755)
72
73
74def dump_bug (level, etype, msg, location=None, nhdf=None):
75    global DISABLE_DUMP
76    if DISABLE_DUMP: return
77
78    now = int(time.time())
79    pid = os.getpid()
80
81    import neo_cgi, neo_util
82    hdf = neo_util.HDF()
83    hdf.setValue("Required.Level", level)
84    hdf.setValue("Required.When", str(int(time.time())))
85    hdf.setValue("Required.Type", etype)
86    hdf.setValue("Required.Title", msg)
87    hdf.setValue("Optional.Hostname", socket.gethostname())
88    if location:
89        hdf.setValue("Optional.Location", location)
90
91    for (key, value) in os.environ.items():
92        hdf.setValue ("Environ.%s" % key, value)
93
94    global Count
95    Count = Count + 1
96    fname = "%d.%d_%d.%s" % (now, pid, Count, socket.gethostname())
97    checkPaths()
98
99    tpath = os.path.join (DUMP_DIR, "tmp", fname)
100    npath = os.path.join (DUMP_DIR, "new", fname)
101    hdf.writeFile(tpath)
102    os.rename(tpath, npath)
103
104