-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_exception_runner.py
210 lines (168 loc) · 5.2 KB
/
run_exception_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
import time
SCARLETT_DEBUG = None
if SCARLETT_DEBUG:
# Setting GST_DEBUG_DUMP_DOT_DIR environment variable enables us to have a
# dotfile generated
os.environ[
"GST_DEBUG_DUMP_DOT_DIR"] = "/home/pi/dev/bossjones-github/scarlett-dbus-poc/_debug"
os.putenv('GST_DEBUG_DUMP_DIR_DIR',
'/home/pi/dev/bossjones-github/scarlett-dbus-poc/_debug')
import argparse
import pprint
pp = pprint.PrettyPrinter(indent=4)
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject
from gi.repository import Gst
from gi.repository import GLib
from gi.repository import Gio
import threading
GObject.threads_init()
Gst.init(None)
print '********************************************************'
print 'GObject: '
pp.pprint(GObject.pygobject_version)
print ''
print 'Gst: '
pp.pprint(Gst.version_string())
print '********************************************************'
Gst.debug_set_active(True)
Gst.debug_set_default_threshold(3)
import StringIO
import re
import ConfigParser
from signal import signal, SIGWINCH, SIGKILL, SIGTERM
from IPython.core.debugger import Tracer
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose',
color_scheme='Linux',
call_pdb=True,
ostream=sys.__stdout__)
from colorlog import ColoredFormatter
import logging
SCARLETT_CANCEL = "pi-cancel"
SCARLETT_LISTENING = "pi-listening"
SCARLETT_RESPONSE = "pi-response"
SCARLETT_FAILED = "pi-response2"
from gettext import gettext as _
gst = Gst
import scarlett_gstutils
import scarlett_config
import threading
import traceback
from functools import wraps
import Queue
from random import randint
def setup_logger():
"""Return a logger with a default ColoredFormatter."""
formatter = ColoredFormatter(
"(%(threadName)-9s) %(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
},
secondary_log_colors={
'message': {
'ERROR': 'red',
'CRITICAL': 'red',
'DEBUG': 'yellow'
}
},
style='%'
)
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
# Create a player
PWD = '/home/pi/dev/bossjones-github/scarlett-dbus-poc'
logger = setup_logger()
gst = Gst
# source: https://github.com/jcollado/pygtk-webui/blob/master/demo.py
def trace(func):
"""Tracing wrapper to log when function enter/exit happens.
:param func: Function to wrap
:type func: callable
"""
@wraps(func)
def wrapper(*args, **kwargs):
logger.debug('Start {!r}'. format(func.__name__))
result = func(*args, **kwargs)
logger.debug('End {!r}'. format(func.__name__))
return result
return wrapper
NUM_THREADS = 10
class ExcThread(threading.Thread):
"""
Exception Thread Class aka Producer. Acts as the Child thread.
Any errors that happen here will get placed into a Queue and raised for the parent thread to consume.
A thread class that supports raising exception in the thread from another thread.
"""
@trace
def __init__(self, bucket, *args, **kargs):
threading.Thread.__init__(self, *args, **kargs)
self.bucket = bucket
self.running = True
self._stop = threading.Event()
@trace
def run(self):
try:
print "Child Thread Started", self
threading.Thread.run(self)
# raise Exception('An error occured here.')
except Exception:
self.bucket.put(sys.exc_info())
raise
@trace
def stop(self):
self._stop.set()
@trace
def stopped(self):
return self._stop.isSet()
@trace
def main():
"""
Parent thread and supervisor.
"""
bucket = Queue.Queue()
# TODO: Try calling child thread like below.
# TODO: Allow us to pass in a target, and args.
# TODO: Eg. target=ScarlettPlayer or target=ScarlettSpeaker
# SOURCE: https://github.com/jhcepas/npr/blob/master/nprlib/interface.py
# t = ExcThread(bucket=exceptions, target=func, args=[args])
# Start child thread
thread_obj = ExcThread(bucket)
thread_obj.daemon = True
thread_obj.start()
while True:
try:
exc = bucket.get(block=False)
# print "GOT FROM BUCKET QUEUE: ", exc
except Queue.Empty:
time.sleep(.2)
else:
exc_type, exc_obj, exc_trace = exc
# deal with the exception
# print exc_type, exc_obj
# print exc_trace
# deal with the exception
# print exc_trace, exc_type, exc_obj
raise exc_obj
thread_obj.join(0.1)
if thread_obj.isAlive():
continue
else:
break
if __name__ == '__main__':
main()