This repository has been archived by the owner on Feb 1, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
models.py
763 lines (610 loc) · 20.9 KB
/
models.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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
"""
Remember! Every new model you introduce here automatically gets exposed
in the public API in the `api` app.
"""
import datetime
import hashlib
import os
import urlparse
import json
import logging
import requests
import stat
import time
import urllib
from django.conf import settings
from django.core.cache import cache
from django.utils.encoding import iri_to_uri
from django.utils.hashcompat import md5_constructor
from django.template.defaultfilters import slugify
class BadStatusCodeError(Exception): # XXX poor name
pass
class RequiredParameterError(Exception):
pass
def _clean_path(path):
"""return a cleaned up version of the path appropriate for saving
as a file directory.
"""
path = iri_to_uri(path)
path = path.replace(' ', '_')
path = '/'.join(slugify(x) for x in path.split('/'))
if path.startswith('/'):
path = path[1:]
return path
def _clean_query(query, max_length=30):
cleaned = _clean_path(query.replace('&', '/'))
# if we allow the query part become too long,
# we might run the rist of getting a OSError number 63
# which is "File name too long"
if len(cleaned) > max_length:
# it's huge! hash it
cleaned = hashlib.md5(cleaned).hexdigest()
return cleaned
class SocorroCommon(object):
# by default, we don't need username and password
username = password = None
# http_host
http_host = None
# default cache expiration time if applicable
cache_seconds = 60 * 60
def fetch(self, url, headers=None, method='get', data=None,
expect_json=True, dont_cache=False):
if url.startswith('/'):
url = self._complete_url(url)
if not headers:
if self.http_host:
headers = {'Host': self.http_host}
else:
headers = {}
if self.username and self.password:
auth = self.username, self.password
else:
auth = ()
cache_key = None
cache_file = None
if settings.CACHE_MIDDLEWARE and not dont_cache:
cache_key = md5_constructor(iri_to_uri(url)).hexdigest()
result = cache.get(cache_key)
if result is not None:
logging.debug("CACHE HIT %s" % url)
return result
# not in the memcache/locmem but is it in cache files?
if settings.CACHE_MIDDLEWARE_FILES:
root = settings.CACHE_MIDDLEWARE_FILES
if isinstance(root, bool):
cache_file = os.path.join(settings.ROOT, 'models-cache')
else:
cache_file = root
split = urlparse.urlparse(url)
cache_file = os.path.join(cache_file,
split.netloc,
_clean_path(split.path))
if split.query:
cache_file = os.path.join(cache_file,
_clean_query(split.query))
if expect_json:
cache_file = os.path.join(cache_file,
'%s.json' % cache_key)
else:
cache_file = os.path.join(cache_file,
'%s.dump' % cache_key)
if os.path.isfile(cache_file):
# but is it fresh enough?
age = time.time() - os.stat(cache_file)[stat.ST_MTIME]
if age > self.cache_seconds:
logging.debug("CACHE FILE TOO OLD")
os.remove(cache_file)
else:
logging.debug("CACHE FILE HIT %s" % url)
if expect_json:
return json.load(open(cache_file))
else:
return open(cache_file).read()
if method == 'post':
request_method = requests.post
elif method == 'get':
request_method = requests.get
else:
raise ValueError(method)
logging.info("FETCHING %s" % url)
resp = request_method(url=url, auth=auth, headers=headers, data=data)
if not resp.status_code == 200:
raise BadStatusCodeError('%s: on: %s' % (resp.status_code, url))
result = resp.content
if expect_json:
result = json.loads(result)
if cache_key:
cache.set(cache_key, result, self.cache_seconds)
if cache_file:
if not os.path.isdir(os.path.dirname(cache_file)):
os.makedirs(os.path.dirname(cache_file))
if expect_json:
json.dump(result, open(cache_file, 'w'), indent=2)
else:
open(cache_file, 'w').write(result)
return result
def _complete_url(self, url):
if url.startswith('/'):
if not getattr(self, 'base_url', None):
raise NotImplementedError("No base_url defined in context")
url = '%s%s' % (self.base_url, url)
return url
class SocorroMiddleware(SocorroCommon):
base_url = settings.MWARE_BASE_URL
http_host = settings.MWARE_HTTP_HOST
username = settings.MWARE_USERNAME
password = settings.MWARE_PASSWORD
default_date_format = '%Y-%m-%d'
default_datetime_format = '%Y-%m-%dT%H:%M:%S'
# def fetch(self, url, *args, **kwargs):
# url = self._complete_url(url)
# return super(SocorroMiddleware, self).fetch(url, *args, **kwargs)
def post(self, url, payload):
url = self._complete_url(url)
headers = {'Host': self.http_host}
# set dont_cache=True here because the request depends on the payload
return self.fetch(url, headers=headers, method='post', data=payload,
dont_cache=True)
def get(self, expect_json=True, **kwargs):
"""
This is the generic `get` method that will take
`self.required_params` and `self.possible_params` and construct
a URL using only a known prefix.
ALl classes that don't need to do any particular hacks, just need
to define a `URL_PREFIX` and (`required_params` and/or
`possible_params`)
"""
url = self.URL_PREFIX
assert url.startswith('/'), 'URL_PREFIX must start with a /'
assert url.endswith('/'), 'URL_PREFIX must end with a /'
params = {}
required_params = self.flatten_params(
getattr(self, 'required_params', [])
)
possible_params = self.flatten_params(
getattr(self, 'possible_params', [])
)
defaults = getattr(self, 'defaults', {})
aliases = getattr(self, 'aliases', {})
for key, value in defaults.items():
kwargs[key] = kwargs.get(key) or value
for param in required_params + possible_params:
if param in required_params and not kwargs.get(param):
raise RequiredParameterError(param)
value = kwargs.get(param)
if not value:
continue
if param in ('signature', 'reasons', 'terms'): # XXX factor out
value = self.encode_special_chars(value)
if isinstance(value, (list, tuple)):
value = '+'.join(value)
params[param] = value
url += aliases.get(param, param) + '/%(' + param + ')s/'
self.urlencode_params(params)
return self.fetch(url % params, expect_json=expect_json)
def urlencode_params(self, params):
"""in-place replacement URL encoding parameter values.
For example, if params == {'foo': 'bar1 bar2'}
it changes it to == {'foo': 'bar1%20bar2'}
"""
def quote(value):
# the special chars %0A (newline char) and %00 (null byte)
# break the middleware
# we want to simply remove them from all URLs
return (
urllib.quote(value, '') # Slashes are not safe in our URLs
.replace('%0A', '')
.replace('%00', '')
)
for key, value in params.iteritems():
if isinstance(value, datetime.datetime):
value = value.strftime(self.default_datetime_format)
if isinstance(value, datetime.date):
value = value.strftime(self.default_date_format)
if isinstance(value, unicode):
value = value.encode('utf-8')
if isinstance(value, basestring):
params[key] = quote(value)
if isinstance(value, (list, tuple)):
params[key] = [
quote(v)
for v in value
if isinstance(v, basestring)
]
def build_middleware_url(
self,
url_base,
parameters=None,
params_aliases=None,
params_separator='/',
key_value_separator='/',
values_separator='+',
url_params_separator='/'
):
"""Return a complete URL to call a middleware service.
Keyword args:
url_base - base of the URL to call, before parameters
parameters - dict of the parameters to add to the URL
params_aliases - dict to alias some keys before building the URL
params_separator - separator used between each key/value pair
key_value_separator - separator used between a key and its value
values_separator - separator used to join lists in parameters
url_params_separator - separator used between url_base and parameters
"""
if not parameters:
return url_base
self.urlencode_params(parameters)
url_params = []
for param, value in parameters.iteritems():
try:
# For empty strings and lists
valid = len(value) > 0
except TypeError:
# value was neither a string nor a list, it's valid by default
valid = True
if value is not None and valid:
if params_aliases:
param = params_aliases.get(param, param)
if isinstance(value, (list, tuple)):
value = values_separator.join(value)
else:
value = str(value)
url_params.append(key_value_separator.join((param, value)))
url_params = params_separator.join(url_params)
return url_params_separator.join((url_base, url_params))
def encode_special_chars(self, input_):
"""Return the passed string with url-encoded slashes and pluses.
We do that for two reasons: first, Apache won't by default accept
encoded slashes in URLs. Second, '+' is a special character in the
middleware, used as a list separator.
This function should be called only on parameters that are allowed to
contain slashes or pluses, which means basically only signature fields.
"""
def clean(string):
return string.replace('/', '%2F').replace('+', '%2B')
if isinstance(input_, (tuple, list)):
return [clean(x) for x in input_]
else:
return clean(input_)
@staticmethod
def flatten_params(params):
names = []
for param in params:
if isinstance(param, basestring):
names.append(param)
elif isinstance(param, dict):
names.append(param['name'])
else:
assert isinstance(param, (list, tuple))
names.append(param[0])
return names
@classmethod
def get_annotated_params(cls):
"""return an iterator. One dict for each parameter that the
class takes.
Each dict must have the following keys:
* name
* type
* required
"""
for required, items in ((True, getattr(cls, 'required_params', [])),
(False, getattr(cls, 'possible_params', []))):
for item in items:
if isinstance(item, basestring):
type_ = basestring
name = item
elif isinstance(item, dict):
type_ = item['type']
name = item['name']
else:
assert isinstance(item, tuple)
name = item[0]
type_ = item[1]
yield {
'name': name,
'required': required,
'type': type_,
}
class CurrentVersions(SocorroMiddleware):
def get(self):
products = CurrentProducts().get()['products']
releases = CurrentProducts().get()['hits']
currentversions = []
for product_name in products:
for release in releases[product_name]:
currentversions.append(release)
return currentversions
class CurrentProducts(SocorroMiddleware):
URL_PREFIX = '/products/'
possible_params = (
'versions',
)
class ProductsVersions(CurrentVersions):
def get(self):
versions = super(ProductsVersions, self).get()
products = {}
for version in versions:
product = version['product']
if product not in products:
products[product] = []
products[product].append(version)
return products
class Platforms(SocorroMiddleware):
def get(self):
# For dev only, this should be moved to a middleware service
# using the database as soon as possible.
platforms = [
{
'code': 'win',
'name': 'Windows'
},
{
'code': 'mac',
'name': 'Mac OS X'
},
{
'code': 'lin',
'name': 'Linux'
}
]
return platforms
class CrashesPerAdu(SocorroMiddleware):
# Fetch records for active daily users.
URL_PREFIX = '/crashes/daily/'
required_params = (
'product',
('versions', list),
)
possible_params = (
('from_date', datetime.date),
('to_date', datetime.date),
'date_range_type',
'os',
'report_type',
'separated_by', # used for a hack in get()
)
def get(self, **kwargs):
# hack a bit before moving on to the sensible stuff
if 'os' in kwargs:
# Operating systems can be specified for by version as
# well but, we only want to separate the results by OS
# if the selected, report type was by_os.
if ('form_selection' in kwargs and
kwargs.get('form_selection') == 'by_os'):
kwargs['separated_by'] = 'os'
return super(CrashesPerAdu, self).get(**kwargs)
class TCBS(SocorroMiddleware):
URL_PREFIX = '/crashes/signatures/'
required_params = (
'product',
'version',
)
possible_params = (
'crash_type',
('end_date', datetime.date),
'date_range_type',
('duration', int),
('limit', int),
'os',
)
defaults = {
'limit': 300,
}
class ReportList(SocorroMiddleware):
URL_PREFIX = '/report/list/'
required_params = (
'signature',
)
possible_params = (
('products', list),
('versions', list),
('os', list),
('start_date', datetime.datetime),
('end_date', datetime.datetime),
'build_ids',
'reasons',
'release_channels',
'report_process',
'report_type',
'plugin_in',
'plugin_search_mode',
'plugin_terms',
'result_number',
'result_offset'
)
aliases = {
'start_date': 'from',
'end_date': 'to',
}
class ProcessedCrash(SocorroMiddleware):
URL_PREFIX = '/crash_data/'
required_params = (
'crash_id',
)
possible_params = (
'format',
)
defaults = {
'format': 'processed',
}
aliases = {
'crash_id': 'uuid',
'format': 'datatype',
}
class RawCrash(SocorroMiddleware):
URL_PREFIX = '/crash_data/'
required_params = (
'crash_id',
)
possible_params = (
'format',
)
defaults = {
'format': 'meta',
}
aliases = {
'crash_id': 'uuid',
'format': 'datatype',
}
def get(self, **kwargs):
format = kwargs.get('format', 'meta')
if format == 'raw_crash':
format = kwargs['format'] = 'raw'
kwargs['expect_json'] = format != 'raw'
return super(RawCrash, self).get(**kwargs)
class CommentsBySignature(SocorroMiddleware):
URL_PREFIX = '/crashes/comments/'
required_params = (
'signature',
)
possible_params = (
'products',
'versions',
'os',
'start_date',
'end_date',
'build_ids',
'reasons',
'report_process',
'report_type',
'plugin_in',
'plugin_search_mode',
'plugin_terms',
'result_number',
'result_offset'
)
aliases = {
'start_date': 'from',
'end_date': 'to'
}
class CrashPairsByCrashId(SocorroMiddleware):
URL_PREFIX = '/crashes/paireduuid/'
required_params = (
'crash_id',
'hang_id',
)
class Search(SocorroMiddleware):
URL_PREFIX = '/search/signatures/'
possible_params = (
'terms',
('products', list),
('versions', list),
('os', list),
('start_date', datetime.datetime),
('end_date', datetime.datetime),
'search_mode',
'build_ids',
'reasons',
'release_channels',
'report_process',
'report_type',
'plugin_in',
'plugin_search_mode',
'plugin_terms',
'result_number',
'result_offset',
'_force_api_impl'
)
aliases = {
'terms': 'for',
'start_date': 'from',
'end_date': 'to'
}
class Bugs(SocorroMiddleware):
required_params = (
'signatures',
)
def get(self, **kwargs):
url = '/bugs/'
if not kwargs.get('signatures'):
raise ValueError("'signatures' can not be empty")
payload = {'signatures': kwargs['signatures']}
return self.post(url, payload)
class SignatureTrend(SocorroMiddleware):
URL_PREFIX = '/topcrash/sig/trend/history/'
required_params = (
'product',
'version',
'signature',
('end_date', datetime.date),
('duration', int),
)
possible_params = (
('steps', int),
)
defaults = {
'steps': 60
}
aliases = {
# means SignatureTrend.get(product=XXX)
# becomes '/p/XXX' for example
'product': 'p',
'version': 'v',
'end_date': 'end',
'signature': 'sig',
}
class SignatureSummary(SocorroMiddleware):
URL_PREFIX = '/signaturesummary/'
required_params = (
'report_type',
'signature',
('start_date', datetime.date),
('end_date', datetime.date),
)
class Status(SocorroMiddleware):
possible_params = (
'duration',
)
def get(self, decode_json=True, **kwargs):
duration = kwargs.get('duration') or 12
return self.fetch(
'/server_status/duration/%s' % duration,
expect_json=decode_json
)
class CrontabberState(SocorroMiddleware):
URL_PREFIX = '/crontabber_state/'
cache_seconds = 60 * 5 # 5 minutes
class DailyBuilds(SocorroMiddleware):
URL_PREFIX = '/products/builds/'
required_params = (
'product',
)
possible_params = (
'version',
)
class CrashTrends(SocorroMiddleware):
URL_PREFIX = '/crashtrends/'
required_params = (
'product',
'version',
('start_date', datetime.date),
('end_date', datetime.date),
)
class BugzillaAPI(SocorroCommon):
base_url = settings.BZAPI_BASE_URL
username = password = None
# def get(self, *args, **kwargs):
# raise NotImplementedError("You're supposed to override this")
class BugzillaBugInfo(BugzillaAPI):
def get(self, bugs, fields):
if isinstance(bugs, basestring):
bugs = [bugs]
if isinstance(fields, basestring):
fields = [fields]
params = {
'bugs': ','.join(bugs),
'fields': ','.join(fields),
}
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
url = ('/bug?id=%(bugs)s&include_fields=%(fields)s' % params)
return self.fetch(url, headers)
class SignatureURLs(SocorroMiddleware):
URL_PREFIX = '/signatureurls/'
required_params = (
('products', list),
('versions', list),
'signature',
('start_date', datetime.datetime),
('end_date', datetime.datetime),
)