forked from pagekite/PyPagekite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyamond.py
executable file
·222 lines (185 loc) · 6.44 KB
/
yamond.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
211
212
213
214
215
216
217
218
219
220
221
"""
This is a class implementing a flexible metric-store and an HTTP
thread for browsing the numbers.
"""
##############################################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see: <http://www.gnu.org/licenses/>
"""
##############################################################################
from six.moves import range
from six.moves import BaseHTTPServer
from six.moves.urllib.request import urlopen
from six.moves.urllib.parse import parse_qs, urlparse
import getopt
import os
import random
import re
import select
import socket
import struct
import sys
import threading
import time
import traceback
class YamonRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_yamon_vars(self):
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Cache-Control', 'no-cache')
self.end_headers()
self.wfile.write(self.server.yamond.render_vars_text())
def do_heapy(self):
from guppy import hpy
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Cache-Control', 'no-cache')
self.end_headers()
self.wfile.write(hpy().heap())
def do_404(self):
self.send_response(404)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write('<h1>404: What? Where? Cannot find it!</h1>')
def do_root(self):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write('<h1>Hello!</h1>')
def handle_path(self, path, query):
if path == '/vars.txt':
self.do_yamon_vars()
elif path == '/heap.txt':
self.do_heapy()
elif path == '/':
self.do_root()
else:
self.do_404()
def do_GET(self):
(scheme, netloc, path, params, query, frag) = urlparse(self.path)
qs = parse_qs(query)
return self.handle_path(path, query)
class YamonHttpServer(BaseHTTPServer.HTTPServer):
def __init__(self, yamond, handler):
BaseHTTPServer.HTTPServer.__init__(self, yamond.sspec, handler)
self.yamond = yamond
class YamonD(threading.Thread):
"""Handle HTTP in a separate thread."""
daemon = True
def __init__(self, sspec,
server=YamonHttpServer,
handler=YamonRequestHandler):
threading.Thread.__init__(self)
self.server = server
self.handler = handler
self.sspec = sspec
self.httpd = None
self.running = False
self.values = {}
self.lists = {}
self.views = {}
# Important: threading.Lock() will deadlock pypy and generally we want
# to avoid locking. The methods below only hold this lock
# if they are adding/removing elements from our dicts and
# lists. For mutating existing values we either just accept
# things getting overwritten or rely on the GIL.
self.lock = threading.RLock()
def vmax(self, var, value):
# Unlocked, since we don't change the size of self.values
if value > self.values[var]:
self.values[var] = value
def vmin(self, var, value):
# Unlocked, since we don't change the size of self.values
if value < self.values[var]:
self.values[var] = value
def vscale(self, var, ratio, add=0):
if var not in self.values:
with self.lock:
self.values[var] = self.values.get(var, 0)
# Unlocked, since we don't change the size of self.values
self.values[var] *= ratio
self.values[var] += add
def vset(self, var, value):
with self.lock:
self.values[var] = value
def vadd(self, var, value, wrap=None):
if var not in self.values:
with self.lock:
self.values[var] = self.values.get(var, 0)
# We assume the GIL will guarantee these do sane things
self.values[var] += value
if wrap:
self.values[var] %= wrap
def vdel(self, var):
if var in self.values:
with self.lock:
del self.values[var]
def lcreate(self, listn, elems):
with self.lock:
self.lists[listn] = [elems, 0, ['' for x in range(0, elems)]]
def ladd(self, listn, value):
with self.lock:
lst = self.lists[listn]
lst[2][lst[1]] = value
lst[1] += 1
lst[1] %= lst[0]
def render_vars_text(self, view=None):
if view:
if view == 'heapy':
from guppy import hpy
return hpy().heap()
else:
values, lists = self.views[view]
else:
values, lists = self.values, self.lists
data = []
for var in values:
data.append('%s: %s\n' % (var, values[var]))
if var == 'started':
data.append(
'started_days_ago: %.3f\n' % ((time.time() - values[var]) / 86400))
for lname in lists:
(elems, offset, lst) = lists[lname]
l = lst[offset:]
l.extend(lst[:offset])
data.append('%s: %s\n' % (lname, ' '.join(['%s' % (x, ) for x in l])))
try:
slist = sorted([float(i) for i in l if i])
if len(slist) >= 10:
data.append('%s_m50: %.2f\n' % (lname, slist[int(len(slist) * 0.5)]))
data.append('%s_m90: %.2f\n' % (lname, slist[int(len(slist) * 0.9)]))
data.append('%s_avg: %.2f\n' % (lname, sum(slist) / len(slist)))
except (ValueError, TypeError, IndexError, ZeroDivisionError):
pass
data.sort()
return ''.join(data)
def quit(self):
if self.httpd:
self.running = False
urlopen('http://%s:%s/exiting/' % self.sspec, proxies={}).readlines()
def run(self):
self.httpd = self.server(self, self.handler)
self.sspec = self.httpd.server_address
self.running = True
while self.running:
self.httpd.handle_request()
if __name__ == '__main__':
yd = YamonD(('', 0))
yd.vset('bjarni', 100)
yd.lcreate('foo', 2)
yd.ladd('foo', 1)
yd.ladd('foo', 2)
yd.ladd('foo', 3)
yd.run()