/
part.py
297 lines (255 loc) · 9.99 KB
/
part.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Appier Framework
# Copyright (c) 2008-2018 Hive Solutions Lda.
#
# This file is part of Hive Appier Framework.
#
# Hive Appier Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Appier Framework 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
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Appier Framework. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2018 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import socket
import datetime
import appier
from appier_extras import base
from appier_extras.parts.diag import models
class DiagPart(appier.Part):
"""
Modular part class that provides an infra-structure of diagnostics
that allow more and better debugging of an Application.
Notice that most of the diagnostics is performed locally and is
not optimized for proper asynchronous usage.
"""
def __init__(self, *args, **kwargs):
appier.Part.__init__(self, *args, **kwargs)
self.store = kwargs.get("store", False)
self.loggly = kwargs.get("loggly", False)
self.output = kwargs.get("output", True)
self.geo = kwargs.get("geo", True)
self.verbose = kwargs.get("verbose", False)
self.format = kwargs.get("format", "combined")
self.empty = kwargs.get("empty", False)
self.store = appier.conf("DIAG_STORE", self.store, cast = bool)
self.loggly = appier.conf("DIAG_LOGGLY", self.loggly, cast = bool)
self.output = appier.conf("DIAG_OUTPUT", self.output, cast = bool)
self.output = appier.conf("DIAG_STDOUT", self.output, cast = bool)
self.geo = appier.conf("DIAG_GEO", self.geo, cast = bool)
self.verbose = appier.conf("DIAG_VERBOSE", self.verbose)
self.format = appier.conf("DIAG_FORMAT", self.format)
self.empty = appier.conf("DIAG_EMPTY", self.empty, cast = bool)
self._loggly_api = None
self._hostname_s = None
def version(self):
return base.VERSION
def info(self):
info = appier.Part.info(self)
info.update(
store = self.store,
loggly = self.loggly,
output = self.output,
format = self.format
)
return info
def load(self):
appier.Part.load(self)
if self.owner.admin_part:
self.owner.admin_part.add_section_item(
"Requests", "diag.list_requests",
section = "Diag"
)
appier.App.add_custom("before_request", self.before_request)
appier.App.add_custom("after_request", self.after_request)
# in case the empty flag is set the complete set of
# request entities in the data store are deleted
if self.empty: models.DiagRequest.delete_c()
def unload(self):
appier.Part.unload(self)
if self.owner.admin_part:
self.owner.admin_part.remove_section_item(
"Requests",
section = "Diag"
)
appier.App.remove_custom("before_request", self.before_request)
appier.App.remove_custom("after_request", self.after_request)
self.flush_all()
def routes(self):
return [
(("GET",), "/admin/diag/requests", self.list_requests),
(("GET",), "/admin/diag/requests/<int:id>", self.show_request)
]
def models(self):
return models
def before_request(self):
pass
def after_request(self):
method = getattr(self, "_%s_log" % self.format)
result = method()
if self.output: print(result)
if self.store: self._store_log()
if self.loggly: self._loggly_log()
def flush_all(self):
self._loggly_flush()
@appier.ensure(token = "admin.status")
def list_requests(self):
object = appier.get_object(
alias = True,
page = True,
find = True,
sort = (("id", -1),)
)
page = models.DiagRequest.paginate(**object)
requests = models.DiagRequest.find(meta = True, **object)
return self.template(
"request/list.html.tpl",
section = "section:diag:requests",
page = page,
requests = requests,
model = models.DiagRequest
)
@appier.ensure(token = "admin.status")
def show_request(self, id):
return self.template(
"request/show.html.tpl",
section = "section:diag:requests",
request = models.DiagRequest.get(id = id)
)
def _common_log(self, user = "root"):
template = "%s - %s [%s] \"%s %s %s\" %d %s"
return template % (
self.request.get_address(),
user,
self.request.get_sdate(),
self.request.method,
self.request.path,
self.request.protocol,
self.request.code,
str(self.request.result_l or "-")
)
def _combined_log(self, user = "root"):
template = "%s - %s [%s] \"%s %s %s\" %d %s \"%s\" \"%s\""
return template % (
self.request.get_address(),
user,
self.request.get_sdate(),
self.request.method,
self.request.path,
self.request.protocol,
self.request.code,
str(self.request.result_l or "-"),
self.request.get_header("Referer") or "",
self.request.get_header("User-Agent") or ""
)
def _store_log(self):
browser_info = self.request.browser_info
browser_info = browser_info or dict()
diag_request = models.DiagRequest(
address = self.request.get_address(),
url = self.request.get_url(),
method = self.request.method,
path = self.request.path,
query = self.request.query,
code = self.request.code,
protocol = self.request.protocol,
duration = self.request.duration,
browser = self._browser,
headers = self.request.in_headers,
browser_info = self.request.browser_info,
meta_info = self._meta_info,
geo_info = self._geo_info
)
diag_request.save()
def _loggly_log(self):
item = dict(
timestamp = self._timestamp,
address = self.request.get_address(),
url = self.request.get_url(),
method = self.request.method,
path = self.request.path,
query = self.request.query,
code = self.request.code,
protocol = self.request.protocol,
duration = self.request.duration,
browser = self._browser,
headers = self.request.in_headers,
browser_info = self.request.browser_info,
meta_info = self._meta_info,
geo_info = self._geo_info
)
item.update(
hostname = self._hostname,
name = self.owner.name_b,
instance = self.owner.instance,
appier = appier.VERSION,
platform = appier.PLATFORM,
server = self.owner.server_full,
libraries = self.owner.get_libraries(map = True),
parts = self.owner.get_parts(simple = True)
)
if self.verbose: item.update(info_dict = self.owner.info_dict())
api = self._get_loggly_api()
if not api: return
api.log_buffer(item)
def _loggly_flush(self):
if not self._loggly_api: return
api = self._get_loggly_api()
api.log_flush()
def _get_loggly_api(self):
if self._loggly_api: return self._loggly_api
try: loggly = appier.import_pip("loggly", package = "loggly_api_python")
except: return None
self._loggly_api = loggly.API(delayer = self.owner.delay)
return self._loggly_api
@property
def _timestamp(self, format = "%Y-%m-%dT%H:%M:%S"):
now = datetime.datetime.utcnow()
return now.strftime(format)
@property
def _hostname(self):
if self._hostname_s: return self._hostname_s
self._hostname_s = socket.gethostname()
return self._hostname_s
@property
def _browser(self, default = "unknown"):
browser_info = self.request.browser_info
browser_info = browser_info or {}
browser_name = browser_info.get("name", None)
browser_version = browser_info.get("version", None)
if browser_name and browser_version:
return "%s/%s" % (browser_name, browser_version)
elif browser_name:
return browser_name
return default
@property
def _meta_info(self):
return dict(
is_mobile = self.request.is_mobile(),
is_tablet = self.request.is_tablet(),
is_browser = self.request.is_browser(),
is_bot = self.request.is_bot()
)
@property
def _geo_info(self):
if not self.geo: return {}
address = self.request.get_address()
return appier.GeoResolver.resolve(address) or {}