forked from Crapworks/RESTlos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restlosapi.py
executable file
·363 lines (284 loc) · 13.3 KB
/
restlosapi.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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from flask import Flask, request, render_template, jsonify, abort
from flask import Request, Response
from flask.views import MethodView
from werkzeug.exceptions import HTTPException, InternalServerError
from werkzeug.exceptions import default_exceptions, BadRequest
from utils import Config
from utils.authentication import Authentify
from subprocess import check_output, CalledProcessError
from pynag import Model, Parsers
from json import dumps
from cgi import escape
import os
import logging
import logging.config
config = Config(os.path.join(os.path.dirname(__file__), 'config.json'))
VERSION="0.3"
class JSONHTTPException(HTTPException):
""" JSONHTTPException: this exception provides a detailed error message
if a json parsing error occures. More helpful that just the standard 400
message which tells you that "something" is wrong
"""
def get_body(self, environ):
return dumps(dict(code=400, message=self.get_description(environ)))
def get_headers(self, environ):
return [('Content-Type', 'application/json')]
class JSONBadRequest(JSONHTTPException, BadRequest):
description = ('The browser (or proxy) sent a request that this server could not understand.')
class CustomRequestClass(Request):
def on_json_loading_failed(self, e):
raise JSONBadRequest(str(e))
class ApiEndpoints(dict):
""" ApiEndpoints: provides a dictionary for the available api endpoints.
it also defines unique keys for the available nagios objects and some
convenient functions for retrieving unique keys or validating object
attributes.
"""
main_cfg_values = {}
def __init__(self):
# create a map of valid endpoints/arguments
for endpoint in Model.all_attributes.object_definitions.keys():
self[endpoint] = Model.all_attributes.object_definitions[endpoint].keys()
self[endpoint] += Model.all_attributes.object_definitions["any"]
del self["any"]
if not self.main_cfg_values:
parser = Parsers.config(config['nagios_main_cfg'])
parser.parse()
self.main_cfg_values.update(dict(parser.maincfg_values))
# set endpoint keys
self.endpoint_keys = {
'hostgroup':'hostgroup_name',
'hostextinfo':'host_name',
'host':'host_name',
'service':'service_description',
'servicegroup':'servicegroup_name',
'contact':'contact_name',
'contactgroup':'contactgroup_name',
'timeperiod':'timeperiod_name',
'command':'command_name',
}
def get_unique_key(self, endpoint):
return self.endpoint_keys[endpoint]
def validate(self, endpoint, data={}):
for attr in data.keys():
if not attr.startswith('_') and attr not in self[endpoint]:
return {404: "unknown attribute: %s" % (attr, )}
if attr == self.endpoint_keys[endpoint]:
for illegal_char in self.main_cfg_values['illegal_object_name_chars']:
if illegal_char in list(data[attr]):
return {400: "illegal character (%s) found in attribute %s" % (illegal_char, attr)}
return {200: "OK"}
class NagiosControlView(MethodView):
"""
NagiosControlView: Provides a view function which is registered as an api
endpoint as well. This '/control' endpoint provides convenient functions
like reloading the core or verify the configuration
"""
decorators = [Authentify(config['auth'])]
def __init__(self, *args, **kwargs):
MethodView.__init__(self, *args, **kwargs)
try:
self.command_file = Model.Control.Command.find_command_file(config['nagios_main_cfg'])
except Exception, err:
abort(500, 'unable to locate command file: %s' % (str(err), ))
self.arguments = ['verify', 'restart']
def _format(self, data):
result = {'Error': [], 'Warning': [], 'Total Errors': [], 'Total Warnings': []}
for line in data.split('\n'):
for key in result.keys():
if line.upper().startswith(key.upper()):
result[key].append(line[len(key)+1:].strip())
for key in result.keys():
if len(result[key]) == 1:
result[key] = result[key][0]
if not result[key]:
del result[key]
return result
def _verify(self):
try:
if config['sudo']:
output = check_output(['sudo', config['nagios_bin'], '-v', config['nagios_main_cfg']])
else:
print [config['nagios_bin'], '-v', config['nagios_main_cfg']]
output = check_output([config['nagios_bin'], '-v', config['nagios_main_cfg']])
returncode = 0
except CalledProcessError, err:
output = err.output
returncode = err.returncode
except Exception, err:
output = str(err)
returncode = 255
result = self._format(output)
return {'output': result if result else output, 'returncode': returncode}
def _restart(self):
logging.warn("[audit] [user: %s] triggered the restart command" % (request.authorization.username), )
Model.Control.Command.restart_program(command_file=self.command_file)
return { 'result': 'successfully sent command to command file' }
def post(self):
if len(request.args.keys()) != 1:
abort(400, 'control endpoint accepts exactly ONE argument')
action = request.args.keys()[0]
if action not in self.arguments:
abort(400, 'invalid argument: %s' % (escape(action), ))
try:
result = getattr(self,'_' + action)()
except Exception, err:
abort(500, 'unable to execute action %s: %s' % (action, str(err)))
else:
return jsonify(result)
class NagiosObjectView(MethodView):
"""
NagiosObjectView: Wraps the flask MethodViews around the wonderful
pynag module providing a full featured RESTfull api for managing
Nagios/Icinga Configurations
"""
decorators = [Authentify(config['auth'])]
def __init__(self, *args, **kwargs):
MethodView.__init__(self, *args, **kwargs)
Model.cfg_file=config['nagios_main_cfg']
Model.pynag_directory=config['output_dir']
self.username = request.authorization.username
self.endpoint = request.path.lstrip('/')
self.endpoints = ApiEndpoints()
def _summary(self, results):
return {
"succeeded": len([r for r in results if r.has_key(200) ]),
"failed": len([r for r in results if not r.has_key(200) ]),
"total": len(results)
}
def get(self):
validate = self.endpoints.validate(self.endpoint, request.args)
if not validate.has_key(200):
abort(*validate.items()[0])
endpoint_objects = getattr(Model, self.endpoint.capitalize()).objects
# build the "contains" query string
query = dict([ (key + '__contains', value) for key, value in request.args.iteritems() ])
try:
result = [ obj['meta']['defined_attributes'] for obj in endpoint_objects.filter(**query)]
except IOError, err:
abort(500, "error opening config files: %s" % (str(err), ))
except:
abort(500)
else:
return Response(dumps(result, indent=None if request.is_xhr else 2), mimetype='application/json')
def delete(self):
validate = self.endpoints.validate(self.endpoint, request.args)
if not validate.has_key(200):
abort(*validate.items()[0])
endpoint_objects = getattr(Model, self.endpoint.capitalize()).objects
# build the "contains" query string
query = dict([ (key + '__contains', value) for key, value in request.args.iteritems() ])
try:
objects = endpoint_objects.filter(**query)
except IOError, err:
abort(500, "error opening config files: %s" % (str(err), ))
except:
abort(500)
unique_key = self.endpoints.get_unique_key(self.endpoint)
results = []
for obj in objects:
try:
obj.delete()
except Exception, err:
results.append({ 500: "unable to delete %s object %s: %s" % (self.endpoint, obj[unique_key], str(err)) })
logging.debug("[audit] [user: %s] failed to delete %s object %s: %s" % (self.username, self.endpoint, obj[unique_key], str(err)))
else:
results.append({ 200: "successfully deleted %s object: %s" % (self.endpoint, obj[unique_key]) })
logging.info("[audit] [user: %s] deleted %s object: %s" % (self.username, self.endpoint, obj[unique_key]))
summary = self._summary(results)
logging.warn("[audit] [user: %s] deleted %d %s objects (out of %d requested)" % (
self.username, summary['succeeded'],
self.endpoint, summary['total'])
)
return jsonify(results=results, summary=summary)
def post(self):
data = request.json
if data is None:
return jsonify(message='no json received. you need to set your content-type to application/json.')
if type(data) == list:
results = map(self._save_or_update, data)
else:
results = [self._save_or_update(data)]
summary = self._summary(results)
logging.warn("[audit] [user: %s] stored %d %s objects (out of %d requested)" % (
self.username,
summary['succeeded'],
self.endpoint,
summary['total'])
)
return jsonify(results=results, summary=summary)
def _save_or_update(self, item):
# does this object already exist
unique_key = self.endpoints.get_unique_key(self.endpoint)
if unique_key in item.keys():
query = { unique_key: item[unique_key] }
try:
endpoint_object = getattr(Model, self.endpoint.capitalize()).objects.filter(**query)
except IOError, err:
abort(500, "error opening config files: %s" % (str(err), ))
except:
abort(500)
if endpoint_object:
endpoint_object = endpoint_object[0]
else:
endpoint_object = getattr(Model, self.endpoint.capitalize())()
else:
return { 500: 'required key for %s object not set: %s' % (self.endpoint, unique_key) }
validate = self.endpoints.validate(self.endpoint, item)
if not validate.has_key(200):
return validate
for key, value in item.iteritems():
endpoint_object.set_attribute(key, value)
try:
endpoint_object.save()
except Exception, err:
logging.debug("[audit] [user: %s] failed to store %s object %s: %s" % (self.username, self.endpoint, item[unique_key], str(err)))
return { 500: 'unable to save %s object %s: %s' % (self.endpoint, item[unique_key], str(err)) }
logging.info("[audit] [user: %s] stored %s object %s" % (self.username, self.endpoint, item[unique_key]))
return { 200: "successfully stored %s object: %s" % (self.endpoint, item[unique_key]) }
class NagiosAPI(Flask):
"""
APIEndpoints: Handles the flask app, registers endpoints and wrapping
the run() function for development testing.
@app: Flask app where the enpoints sould be registered at
"""
def __init__(self, name):
Flask.__init__(self, name)
logging.config.dictConfig(config['logging'])
self.request_class = CustomRequestClass
self.endpoints = ApiEndpoints()
self._register_endpoints()
self._register_error_handler()
self._register_help_handler()
def _error_handler(self, err):
if not isinstance(err, HTTPException):
err = InternalServerError(description="Something went wrong. RUN!")
if request.content_type=='application/json':
response = jsonify(code=err.code, message=str(err))
else:
response = Response(render_template('error.html', err=err))
response.status_code = err.code
if err.code == 401:
response.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
return response
def _help(self):
if request.content_type=='application/json':
return jsonify(endpoints=self.endpoints)
else:
return render_template('help.html', endpoints=self.endpoints)
def _register_help_handler(self):
for endpoint, name in [('/', 'index'), ('/help', 'help')]:
self.add_url_rule(endpoint, name, self._help)
def _register_error_handler(self):
for code in default_exceptions.iterkeys():
self.error_handler_spec[None][code] = self._error_handler
def _register_endpoints(self):
for endpoint in self.endpoints.keys():
self.add_url_rule('/' + endpoint, view_func=NagiosObjectView.as_view(endpoint))
self.add_url_rule('/control', view_func=NagiosControlView.as_view('control'))
if __name__ == '__main__':
app = NagiosAPI(__name__)
logging.info(" * starting restlos V%s" % (VERSION, ))
app.run(port=config['port'])