CherryPy Project Download

root/status/trunk/status.py

Revision 6 (checked in by fumanchu, 3 weeks ago)

Fix for http://www.cherrypy.org/ticket/793.

  • Property svn:eol-style set to native
Line 
1 """Tool to generate mod_status-like output.
2
3 Usage:
4
5 import status
6
7 cherrypy.tools.status = status.StatusMonitor()
8 cherrypy.config.update({"tools.status.on": True})
9 cherrypy.tree.mount(status.Root(), '/cpstatus')
10 """
11
12 import threading
13 import time
14
15 import cherrypy
16
17
18 class ThreadStatus(object):
19    
20     start = None
21     end = None
22     url = None
23    
24     def last_req_time(self):
25         if self.end is None:
26             return 0
27         return self.end - self.start
28    
29     def idle_time(self):
30         if self.end is None:
31             return 0
32         return time.time() - self.end
33
34
35 class StatusMonitor(cherrypy.Tool):
36     """Register the status of each thread."""
37    
38     def __init__(self):
39         self._point = 'on_start_resource'
40         self._name = 'status'
41         self._priority = 50
42         self.seen_threads = {}
43    
44     def callable(self):
45         threadID = threading._get_ident()
46         ts = self.seen_threads.setdefault(threadID, ThreadStatus())
47         ts.start = cherrypy.response.time
48         ts.url = cherrypy.url()
49         ts.end = None
50    
51     def unregister(self):
52         """Unregister the current thread."""
53         threadID = threading._get_ident()
54         if threadID in self.seen_threads:
55             self.seen_threads[threadID].end = time.time()
56    
57     def _setup(self):
58         cherrypy.Tool._setup(self)
59         cherrypy.request.hooks.attach('on_end_resource', self.unregister)
60
61
62 class Root(object):
63    
64     def index(self):
65         threadstats = ["<tr><th>%s</th><td>%.4f</td><td>%.4f</td><td>%s</td></tr>"
66                        % (id, ts.idle_time(), ts.last_req_time(), ts.url)
67                        for id, ts in cherrypy.tools.status.seen_threads.items()]
68         return """
69 <html>
70 <head>
71     <title>CherryPy Status</title>
72 </head>
73 <body>
74 <h1>CherryPy Status</h1>
75 <table>
76 <tr><th>Thread ID</th><th>Idle Time</th><th>Last Request Time</th><th>URL</th></tr>
77 %s
78 </table>
79 </body>
80 </html>
81 """ % '\n'.join(threadstats)
82     index.exposed = True
83    
84     def delay(self, secs):
85         # Help demo last_req_time (since my box returns index in under 1 msec).
86         time.sleep(float(secs))
87         return "OK"
88     delay.exposed = True
89
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cherrypy to create/edit wiki pages