This repository has been archived by the owner on Oct 12, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
StatusTool
90 lines (69 loc) · 2.56 KB
/
StatusTool
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
See source:status
Here's a Tool for !CherryPy 3 which demonstrates functionality like Apache's mod_status. Notice we don't have to do any framework hacking; CP3 offers all the hooks we need. Note also that this is server-agnostic; it should work equally wel whether you're using CherryPy's builtin WSGI server, mod_python, or anything else. Just import this into your project and browse to /cpstatus whenever you like.
{{{
#!python
import threading
import time
import cherrypy
class ThreadStatus(object):
start = None
end = None
url = None
def last_req_time(self):
if self.end is None:
return 0
return self.end - self.start
def idle_time(self):
if self.end is None:
return 0
return time.time() - self.end
class StatusMonitor(cherrypy.Tool):
"""Register the status of each thread."""
def __init__(self):
self._point = 'on_start_resource'
self._name = 'status'
self._priority = 50
self.seen_threads = {}
def callable(self):
threadID = threading._get_ident()
ts = self.seen_threads.setdefault(threadID, ThreadStatus())
ts.start = cherrypy.response.time
ts.url = cherrypy.url()
ts.end = None
def unregister(self):
"""Unregister the current thread."""
threadID = threading._get_ident()
if threadID in self.seen_threads:
self.seen_threads[threadID].end = time.time()
def _setup(self):
cherrypy.Tool._setup(self)
cherrypy.request.hooks.attach('on_end_resource', self.unregister)
cherrypy.tools.status = StatusMonitor()
class Root(object):
def index(self):
threadstats = ["<tr><th>%s</th><td>%.4f</td><td>%.4f</td><td>%s</td></tr>"
% (id, ts.idle_time(), ts.last_req_time(), ts.url)
for id, ts in cherrypy.tools.status.seen_threads.items()]
return """
<html>
<head>
<title>CherryPy Status</title>
</head>
<body>
<h1>CherryPy Status</h1>
<table>
<tr><th>Thread ID</th><th>Idle Time</th><th>Last Request Time</th><th>URL</th></tr>
%s
</table>
</body>
</html>
""" % '\n'.join(threadstats)
index.exposed = True
def delay(self, secs):
# Help demo last_req_time (since my box returns index in under 1 msec).
time.sleep(float(secs))
return "OK"
delay.exposed = True
cherrypy.config.update({"tools.status.on": True})
cherrypy.tree.mount(Root(), '/cpstatus')
}}}