-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
372 lines (306 loc) · 11.8 KB
/
views.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
import base64
try:
import cPickle as pickle
except ImportError:
import pickle
import logging
import re
import zlib
import json
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponse, HttpResponseBadRequest, \
HttpResponseForbidden, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils import timezone
from sentry import conf
from sentry.helpers import get_filters
from sentry.models import GroupedMessage, Message
from sentry.plugins import GroupActionProvider
from sentry.templatetags.sentry_helpers import with_priority
from sentry.reporter import ImprovedExceptionReporter
uuid_re = re.compile(r'^[a-z0-9]{32}$')
def get_search_query_set(query):
from haystack.query import SearchQuerySet
from sentry.search_indexes import site, backend
class SentrySearchQuerySet(SearchQuerySet):
"Returns actual instances rather than search results."
def __getitem__(self, k):
result = []
for r in super(SentrySearchQuerySet, self).__getitem__(k):
inst = r.object
if not inst:
continue
inst.score = r.score
result.append(inst)
return result
return SentrySearchQuerySet(
site=site,
query=backend.SearchQuery(backend=site.backend),
).filter(content=query)
def login_required(func):
def wrapped(request, *args, **kwargs):
if not conf.PUBLIC:
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('sentry-login'))
if not request.user.has_perm('sentry.can_view'):
return HttpResponseRedirect(reverse('sentry-login'))
return func(request, *args, **kwargs)
wrapped.__doc__ = func.__doc__
wrapped.__name__ = func.__name__
return wrapped
@csrf_protect
def login(request):
from django.contrib.auth import login as login_
from django.contrib.auth.forms import AuthenticationForm
if request.POST:
form = AuthenticationForm(request, request.POST)
if form.is_valid():
login_(request, form.get_user())
return HttpResponseRedirect(request.POST.get('next') or reverse('sentry'))
else:
request.session.set_test_cookie()
else:
form = AuthenticationForm(request)
request.session.set_test_cookie()
context = locals()
context.update(csrf(request))
return render_to_response('sentry/login.html', context)
def logout(request):
from django.contrib.auth import logout
logout(request)
return HttpResponseRedirect(reverse('sentry'))
@login_required
def index(request):
filters = []
for filter_ in get_filters():
filters.append(filter_(request))
try:
page = int(request.GET.get('p', 1))
except (TypeError, ValueError):
page = 1
query = request.GET.get('content')
is_search = query
if is_search:
if uuid_re.match(query):
# Forward to message if it exists
try:
message = Message.objects.get(message_id=query)
except Message.DoesNotExist:
pass
else:
return HttpResponseRedirect(message.get_absolute_url())
message_list = get_search_query_set(query)
else:
message_list = GroupedMessage.objects.extra(
select={
'score': GroupedMessage.get_score_clause(),
}
)
if query:
# You really shouldnt be doing this
message_list = message_list.filter(
Q(view__icontains=query) \
| Q(message__icontains=query) \
| Q(traceback__icontains=query)
)
sort = request.GET.get('sort')
if sort == 'date':
message_list = message_list.order_by('-last_seen')
elif sort == 'new':
message_list = message_list.order_by('-first_seen')
else:
sort = 'priority'
if not is_search:
message_list = message_list.order_by('-score', '-last_seen')
any_filter = False
for filter_ in filters:
if not filter_.is_set():
continue
any_filter = True
message_list = filter_.get_query_set(message_list)
today = timezone.now()
has_realtime = page == 1
return render_to_response('sentry/index.html', {
'has_realtime': has_realtime,
'message_list': message_list,
'today': today,
'query': query,
'sort': sort,
'any_filter': any_filter,
'request': request,
'filters': filters,
})
@login_required
def ajax_handler(request):
op = request.REQUEST.get('op')
if op == 'notification':
return render_to_response('sentry/partial/_notification.html', request.GET)
elif op == 'poll':
filters = []
for filter_ in get_filters():
filters.append(filter_(request))
query = request.GET.get('content')
is_search = query
if is_search:
message_list = get_search_query_set(query)
else:
message_list = GroupedMessage.objects.extra(
select={
'score': GroupedMessage.get_score_clause(),
}
)
if query:
# You really shouldnt be doing this
message_list = message_list.filter(
Q(view__icontains=query) \
| Q(message__icontains=query) \
| Q(traceback__icontains=query)
)
sort = request.GET.get('sort')
if sort == 'date':
message_list = message_list.order_by('-last_seen')
elif sort == 'new':
message_list = message_list.order_by('-first_seen')
else:
sort = 'priority'
if not is_search:
message_list = message_list.order_by('-score', '-last_seen')
for filter_ in filters:
if not filter_.is_set():
continue
message_list = filter_.get_query_set(message_list)
data = [
(m.pk, {
'html': render_to_string('sentry/partial/_group.html', {
'group': m,
'priority': p,
'request': request,
}).strip(),
'title': m.view or m.message_top(),
'message': m.error(),
'level': m.get_level_display(),
'logger': m.logger,
'count': m.times_seen,
'priority': p,
}) for m, p in with_priority(message_list[0:15])]
elif op == 'resolve':
gid = request.REQUEST.get('gid')
if not gid:
return HttpResponseForbidden()
try:
group = GroupedMessage.objects.get(pk=gid)
except GroupedMessage.DoesNotExist:
return HttpResponseForbidden()
GroupedMessage.objects.filter(pk=group.pk).update(status=1)
group.status = 1
if not request.is_ajax():
return HttpResponseRedirect(request.META['HTTP_REFERER'])
data = [
(m.pk, {
'html': render_to_string('sentry/partial/_group.html', {
'group': m,
'request': request,
}).strip(),
'count': m.times_seen,
}) for m in [group]]
else:
return HttpResponseBadRequest()
response = HttpResponse(json.dumps(data))
response['Content-Type'] = 'application/json'
return response
@login_required
def group(request, group_id):
group = get_object_or_404(GroupedMessage, pk=group_id)
try:
obj = group.message_set.all().order_by('-id')[0]
except IndexError:
# It's possible that a message would not be created under certain circumstances
# (such as a post_save signal failing)
obj = Message(group=group, data=group.data)
if '__sentry__' in obj.data and 'exc' in obj.data['__sentry__']:
module, args, frames = obj.data['__sentry__']['exc']
obj.class_name = str(obj.class_name)
# We fake the exception class due to many issues with imports/builtins/etc
exc_type = type(obj.class_name, (Exception,), {})
exc_value = exc_type(obj.message)
exc_value.args = args
reporter = ImprovedExceptionReporter(obj.request, exc_type, exc_value, frames, obj.data['__sentry__'].get('template'))
traceback = mark_safe(reporter.get_traceback_html())
version_data = obj.data['__sentry__'].get('versions', {}).iteritems()
elif group.traceback:
traceback = mark_safe('<pre>%s</pre>' % (group.traceback,))
version_data = None
def iter_data(obj):
for k, v in obj.data.iteritems():
if k.startswith('_') or k in ['url']:
continue
yield k, v
json_data = iter_data(obj)
page = 'details'
return render_to_response('sentry/group/details.html', locals())
@login_required
def group_message_list(request, group_id):
group = get_object_or_404(GroupedMessage, pk=group_id)
message_list = group.message_set.all().order_by('-datetime')
page = 'messages'
return render_to_response('sentry/group/message_list.html', locals())
@login_required
def group_message_details(request, group_id, message_id):
group = get_object_or_404(GroupedMessage, pk=group_id)
message = get_object_or_404(group.message_set, pk=message_id)
if '__sentry__' in message.data and 'exc' in message.data['__sentry__']:
module, args, frames = message.data['__sentry__']['exc']
message.class_name = str(message.class_name)
# We fake the exception class due to many issues with imports/builtins/etc
exc_type = type(message.class_name, (Exception,), {})
exc_value = exc_type(message.message)
exc_value.args = args
reporter = ImprovedExceptionReporter(message.request, exc_type, exc_value, frames, message.data['__sentry__'].get('template'))
traceback = mark_safe(reporter.get_traceback_html())
elif group.traceback:
traceback = mark_safe('<pre>%s</pre>' % (group.traceback,))
def iter_data(obj):
for k, v in obj.data.iteritems():
if k.startswith('_') or k in ['url']:
continue
yield k, v
json_data = iter_data(message)
page = 'messages'
return render_to_response('sentry/group/message.html', locals())
@csrf_exempt
def store(request):
key = request.POST.get('key')
if key != conf.KEY:
return HttpResponseForbidden('Invalid credentials')
data = request.POST.get('data')
if not data:
return HttpResponseForbidden('Missing data')
try:
try:
data = pickle.loads(base64.b64decode(data).decode('zlib'))
except zlib.error:
data = pickle.loads(base64.b64decode(data))
except Exception, e:
logger = logging.getLogger('sentry.server')
# This error should be caught as it suggests that there's a
# bug somewhere in the Sentry code.
logger.exception('Bad data received')
return HttpResponseForbidden('Bad data')
GroupedMessage.objects.from_kwargs(**data)
return HttpResponse()
@login_required
def group_plugin_action(request, group_id, slug):
group = get_object_or_404(GroupedMessage, pk=group_id)
try:
cls = GroupActionProvider.plugins[slug]
except KeyError:
raise Http404('Plugin not found')
response = cls(group_id)(request, group)
if response:
return response
return HttpResponseRedirect(request.META['HTTP_REFERER'])