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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
|
from userreport.models import UserReport, UserReport_hwdetect, GraphicsDevice, GraphicsExtension, GraphicsLimit
import userreport.x86 as x86
import userreport.gl
import hashlib
import datetime
import zlib
import re
from django.http import HttpResponseBadRequest, HttpResponse, Http404, QueryDict
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from django.db import connection, transaction
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
class hashabledict(dict):
def __hash__(self):
return hash(tuple(sorted(self.items())))
@csrf_exempt
@require_POST
def upload(request):
try:
decompressed = zlib.decompress(request.raw_post_data)
except zlib.error:
return HttpResponseBadRequest('Invalid POST data.\n', content_type = 'text/plain')
POST = QueryDict(decompressed)
try:
user_id = POST['user_id']
generation_date = datetime.datetime.utcfromtimestamp(int(POST['time']))
data_type = POST['type']
data_version = int(POST['version'])
data = POST['data']
except KeyError, e:
return HttpResponseBadRequest('Missing required fields.\n', content_type = 'text/plain')
uploader = request.META['REMOTE_ADDR']
# Fix the IP address if running via proxy on localhost
if uploader == '127.0.0.1':
try:
uploader = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
except KeyError:
pass
user_id_hash = hashlib.sha1(user_id).hexdigest()
report = UserReport(
uploader = uploader,
user_id_hash = user_id_hash,
generation_date = generation_date,
data_type = data_type,
data_version = data_version,
data = data
)
report.save()
return HttpResponse('OK', content_type = 'text/plain')
def index(request):
return render_to_response('index.html')
def report_cpu(request):
reports = UserReport_hwdetect.objects
reports = reports.filter(data_type = 'hwdetect', data_version__gte = 4, data_version__lte = 5)
# TODO: add v6 support
all_users = set()
cpus = {}
for report in reports:
json = report.data_json_nocache()
if json is None:
continue
cpu = {}
for x in (
'x86_vendor', 'x86_model', 'x86_family',
'cpu_identifier', 'cpu_frequency',
'cpu_numprocs', 'cpu_numpackages', 'cpu_coresperpackage', 'cpu_logicalpercore',
'cpu_numcaches',
'cpu_pagesize', 'cpu_largepagesize',
'numa_numnodes', 'numa_factor', 'numa_interleaved',
):
cpu[x] = json[x]
cpu['os'] = report.os()
def fmt_size(s):
if s % (1024*1024) == 0:
return "%d MB" % (s / (1024*1024))
if s % 1024 == 0:
return "%d kB" % (s / 1024)
return "%d B" % s
def fmt_assoc(w):
if w == 255:
return 'fully-assoc'
else:
return '%d-way' % w
def fmt_cache(c, t):
types = ('?', 'D', 'I ', 'U')
if c['type'] == 0:
return "(Unknown %s cache)" % t
return "L%d %s: %s (%s, shared %dx%s)" % (
c['level'], types[c['type']], fmt_size(c['totalsize']),
fmt_assoc(c['associativity']), c['sharedby'],
('' if c['linesize'] == 64 else ', %dB line' % c['linesize'])
)
def fmt_tlb(c, t):
types = ('?', 'D', 'I ', 'U')
if c['type'] == 0:
return "(Unknown %s TLB)" % t
return "L%d %s: %d-entry (%s, %s page)" % (
c['level'], types[c['type']], c['entries'],
fmt_assoc(c['associativity']), fmt_size(c['pagesize'])
)
def fmt_caches(d, i, cb):
dcaches = d[:]
icaches = i[:]
caches = []
while len(dcaches) or len(icaches):
if len(dcaches) and len(icaches) and dcaches[0] == icaches[0] and dcaches[0]['type'] == 3:
caches.append(cb(dcaches[0], 'U'))
dcaches.pop(0)
icaches.pop(0)
else:
if len(dcaches):
caches.append(cb(dcaches[0], 'D'))
dcaches.pop(0)
if len(icaches):
caches.append(cb(icaches[0], 'I'))
icaches.pop(0)
return tuple(caches)
try:
cpu['caches'] = fmt_caches(json['x86_dcaches'], json['x86_icaches'], fmt_cache)
cpu['tlbs'] = fmt_caches(json['x86_dtlbs'], json['x86_itlbs'], fmt_tlb)
except TypeError:
continue # skip on bogus cache data
caps = set()
for (n,_,b) in x86.cap_bits:
if n.endswith('[2]'):
continue
if json['x86_caps[%d]' % (b / 32)] & (1 << (b % 32)):
caps.add(n)
cpu['caps'] = frozenset(caps)
all_users.add(report.user_id_hash)
cpus.setdefault(hashabledict(cpu), set()).add(report.user_id_hash)
return render_to_response('reports/cpu.html', {'cpus': cpus, 'x86_cap_descs': x86.cap_descs})
def report_opengl_json(request):
devices = {}
reports = GraphicsDevice.objects.all()
for report in reports:
exts = frozenset(e.name for e in report.graphicsextension_set.all())
limits = dict((l.name, l.value) for l in report.graphicslimit_set.all())
device = (report.vendor, report.renderer, report.os, report.driver)
devices.setdefault((hashabledict(limits), exts), set()).add(device)
sorted_devices = sorted(devices.items(), key = lambda (k,deviceset): sorted(deviceset))
data = []
for (limits,exts),deviceset in sorted_devices:
devices = [
{'vendor': v, 'renderer': r, 'os': o, 'driver': d}
for (v,r,o,d) in sorted(deviceset)
]
data.append({'devices': devices, 'limits': limits, 'extensions': sorted(exts)})
json = simplejson.dumps(data, indent=1, sort_keys=True)
return HttpResponse(json, content_type = 'text/plain')
def report_opengl_json_format(request):
return render_to_response('jsonformat.html')
def report_opengl_index(request):
cursor = connection.cursor()
cursor.execute('''
SELECT SUM(usercount)
FROM userreport_graphicsdevice
''')
num_users = sum(c for (c,) in cursor)
cursor.execute('''
SELECT name, SUM(usercount)
FROM userreport_graphicsextension e
JOIN userreport_graphicsdevice d
ON e.device_id = d.id
GROUP BY name
''')
exts = cursor.fetchall()
all_exts = set(n for n,c in exts)
ext_devices = dict((n,c) for n,c in exts)
cursor.execute('''
SELECT name
FROM userreport_graphicslimit l
JOIN userreport_graphicsdevice d
ON l.device_id = d.id
GROUP BY name
''')
all_limits = set(n for (n,) in cursor.fetchall())
cursor.execute('''
SELECT device_name, SUM(usercount)
FROM userreport_graphicsdevice
GROUP BY device_name
''')
all_devices = dict((n,c) for n,c in cursor.fetchall())
all_limits = sorted(all_limits)
all_exts = sorted(all_exts)
return render_to_response('reports/opengl_index.html', {
'all_limits': all_limits,
'all_exts': all_exts,
'all_devices': all_devices,
'ext_devices': ext_devices,
'num_users': num_users,
'ext_versions': userreport.gl.glext_versions,
})
def report_opengl_feature(request, feature):
all_values = set()
usercounts = {}
values = {}
cursor = connection.cursor()
is_extension = False
if re.search(r'[a-z]', feature):
is_extension = True
if is_extension:
cursor.execute('''
SELECT vendor, renderer, os, driver, device_name, SUM(usercount),
(SELECT 1 FROM userreport_graphicsextension e WHERE e.name = %s AND e.device_id = d.id) AS val
FROM userreport_graphicsdevice d
GROUP BY vendor, renderer, os, driver, device_name, val
''', [feature])
for vendor, renderer, os, driver, device_name, usercount, val in cursor:
val = 'true' if val else 'false'
all_values.add(val)
usercounts[val] = usercounts.get(val, 0) + usercount
v = values.setdefault(val, {}).setdefault(hashabledict({
'vendor': vendor,
'renderer': renderer,
'os': os,
'device': device_name
}), {'usercount': 0, 'drivers': set()})
v['usercount'] += usercount
v['drivers'].add(driver)
else:
cursor.execute('''
SELECT value, vendor, renderer, os, driver, device_name, usercount
FROM userreport_graphicslimit l
JOIN userreport_graphicsdevice d
ON l.device_id = d.id
WHERE name = %s
''', [feature])
for val, vendor, renderer, os, driver, device_name, usercount in cursor:
# Convert to int/float if possible, for better sorting
try: val = int(val)
except ValueError:
try: val = float(val)
except ValueError: pass
all_values.add(val)
usercounts[val] = usercounts.get(val, 0) + usercount
v = values.setdefault(val, {}).setdefault(hashabledict({
'vendor': vendor,
'renderer': renderer,
'os': os,
'device': device_name
}), {'usercount': 0, 'drivers': set()})
v['usercount'] += usercount
v['drivers'].add(driver)
if values.keys() == [] or values.keys() == ['false']:
raise Http404
num_users = sum(usercounts.values())
return render_to_response('reports/opengl_feature.html', {
'feature': feature,
'all_values': all_values,
'values': values,
'is_extension': is_extension,
'usercounts': usercounts,
'num_users': num_users,
})
def report_opengl_devices(request, selected):
cursor = connection.cursor()
cursor.execute('''
SELECT DISTINCT device_name
FROM userreport_graphicsdevice
''')
all_devices = set(n for (n,) in cursor.fetchall())
all_limits = set()
all_exts = set()
devices = {}
gl_renderers = set()
reports = GraphicsDevice.objects.filter(device_name__in = selected)
for report in reports:
exts = frozenset(e.name for e in report.graphicsextension_set.all())
all_exts |= exts
limits = dict((l.name, l.value) for l in report.graphicslimit_set.all())
all_limits |= set(limits.keys())
devices.setdefault(hashabledict({'device': report.device_name, 'os': report.os}), {}).setdefault((hashabledict(limits), exts), set()).add(report.driver)
gl_renderers.add(report.renderer)
if len(selected) == 1 and len(devices) == 0:
raise Http404
all_limits = sorted(all_limits)
all_exts = sorted(all_exts)
distinct_devices = []
for (renderer, v) in devices.items():
for (caps, versions) in v.items():
distinct_devices.append((renderer, sorted(versions), caps))
distinct_devices.sort(key = lambda x: (x[0]['device'], x))
return render_to_response('reports/opengl_device.html', {
'selected': selected,
'all_limits': all_limits,
'all_exts': all_exts,
'all_devices': all_devices,
'devices': distinct_devices,
'gl_renderers': gl_renderers,
})
def report_opengl_device(request, device):
return report_opengl_devices(request, [device])
def report_opengl_device_compare(request):
return report_opengl_devices(request, request.GET.getlist('d'))
def report_usercount(request):
reports = UserReport.objects.raw('''
SELECT id, upload_date, user_id_hash
FROM userreport_userreport
ORDER BY upload_date
''')
users_by_date = {}
for report in reports:
t = report.upload_date.date() # group by day
users_by_date.setdefault(t, set()).add(report.user_id_hash)
seen_users = set()
data_scatter = ([], [], [])
for date,users in sorted(users_by_date.items()):
data_scatter[0].append(date)
data_scatter[1].append(len(users))
data_scatter[2].append(len(users - seen_users))
seen_users |= users
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
import matplotlib.artist
fig = Figure(figsize=(12,6))
ax = fig.add_subplot(111)
fig.subplots_adjust(left = 0.08, right = 0.95, top = 0.95, bottom = 0.2)
ax.plot(data_scatter[0], data_scatter[1], marker='o')
ax.plot(data_scatter[0], data_scatter[2], marker='o')
ax.legend(('Total users', 'New users'), 'upper left', frameon=False)
matplotlib.artist.setp(ax.get_legend().get_texts(), fontsize='small')
ax.set_ylabel('Number of users per day')
for label in ax.get_xticklabels():
label.set_rotation(90)
label.set_fontsize(9)
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
canvas = FigureCanvas(fig)
response = HttpResponse(content_type = 'image/png')
canvas.print_png(response, dpi=80)
return response
|