Files
zuul/zuul/lib/repl.py
Tobias Henkel a863f55ba8 Add repl server for debug purposes
Sometimes it can be necessary to debug complex problems in a running
instance. A repl server can be useful in this case. However this can
be highly dangerous in case the port is not correctly firewalled
of. Thus add an undocumented command to enable and disable it.

To enable:
zuul-scheduler repl

To disable
zuul-scheduler norepl

Change-Id: I860db5d088c6b07a66b4390cdfd66637341e7a7a
Co-Authored-By: Tobias Henkel <tobias.henkel@bmw.de>
2019-06-21 16:12:03 +00:00

82 lines
2.5 KiB
Python

# 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.
# Based on ASL2 code from:
# https://gist.github.com/tim-patterson/4471877
import sys
import io
import threading
import socketserver
import code
class ThreadLocalProxy(object):
def __init__(self, default):
self.files = {}
self.default = default
def __getattr__(self, name):
obj = self.files.get(threading.currentThread(), self.default)
return getattr(obj, name)
def register(self, obj):
self.files[threading.currentThread()] = obj
def unregister(self):
self.files.pop(threading.currentThread())
class REPLHandler(socketserver.StreamRequestHandler):
def handle(self):
sys.stdout.register(io.TextIOWrapper(self.wfile, 'utf8'))
sys.stderr.register(io.TextIOWrapper(self.wfile, 'utf8'))
sys.stdin.register(io.TextIOWrapper(self.rfile, 'utf8'))
try:
console = code.InteractiveConsole(locals())
console.interact('Console:')
except Exception:
pass
finally:
sys.stdout.unregister()
sys.stderr.unregister()
sys.stdin.unregister()
class REPLThreadedTCPServer(socketserver.ThreadingMixIn,
socketserver.TCPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, scheduler, *args, **kw):
self.scheduler = scheduler
super(REPLThreadedTCPServer, self).__init__(*args, **kw)
sys.stdout = ThreadLocalProxy(sys.stdout)
sys.stderr = ThreadLocalProxy(sys.stderr)
sys.stdin = ThreadLocalProxy(sys.stdin)
class REPLServer(object):
def __init__(self, scheduler):
self.server = REPLThreadedTCPServer(
scheduler, ('localhost', 3000), REPLHandler)
def start(self):
self.thread = threading.Thread(target=self.server.serve_forever)
self.thread.daemon = True
self.thread.start()
def stop(self):
self.server.shutdown()
self.server.server_close()
self.thread.join(10)