summaryrefslogtreecommitdiffstats
path: root/bottle-rest
blob: f655599b28a2a178a4720face5b83adc79e6f684 (plain)
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
#!/usr/bin/env python

import os
import sys
import dbus
import dbus.exceptions
import json
import logging
from xml.etree import ElementTree
from rocket import Rocket
from bottle import Bottle, abort, request, response, JSONPlugin, HTTPError
import OpenBMCMapper
from OpenBMCMapper import Mapper, PathTree, IntrospectionNodeParser, ListMatch

DBUS_UNKNOWN_INTERFACE = 'org.freedesktop.UnknownInterface'
DBUS_UNKNOWN_METHOD = 'org.freedesktop.DBus.Error.UnknownMethod'
DBUS_INVALID_ARGS = 'org.freedesktop.DBus.Error.InvalidArgs'
DELETE_IFACE = 'org.openbmc.object.Delete'

_4034_msg = "The specified %s cannot be %s: '%s'"

def find_case_insensitive(value, lst):
	return next((x for x in lst if x.lower() == value.lower()), None)

def makelist(data):
	if isinstance(data, list):
		return data
	elif data:
		return [data]
	else:
		return []

class RouteHandler(object):
	def __init__(self, app, bus, verbs, rules):
		self.app = app
		self.bus = bus
		self.mapper = Mapper(bus)
		self._verbs = makelist(verbs)
		self._rules = rules

	def _setup(self, **kw):
		request.route_data = {}
		if request.method in self._verbs:
			return self.setup(**kw)
		else:
			self.find(**kw)
			raise HTTPError(405, "Method not allowed.",
					Allow=','.join(self._verbs))

	def __call__(self, **kw):
		return getattr(self, 'do_' + request.method.lower())(**kw)

	def install(self):
		self.app.route(self._rules, callback = self,
				method = ['GET', 'PUT', 'PATCH', 'POST', 'DELETE'])

	@staticmethod
	def try_mapper_call(f, callback = None, **kw):
		try:
			return f(**kw)
		except dbus.exceptions.DBusException, e:
			if e.get_dbus_name() != OpenBMCMapper.MAPPER_NOT_FOUND:
				raise
			if callback is None:
				def callback(e, **kw):
					abort(404, str(e))

			callback(e, **kw)

	@staticmethod
	def try_properties_interface(f, *a):
		try:
			return f(*a)
		except dbus.exceptions.DBusException, e:
			if DBUS_UNKNOWN_INTERFACE in e.get_dbus_message():
				# interface doesn't have any properties
				return None
			if DBUS_UNKNOWN_METHOD == e.get_dbus_name():
				# properties interface not implemented at all
				return None
			raise

class DirectoryHandler(RouteHandler):
	verbs = 'GET'
	rules = '<path:path>/'

	def __init__(self, app, bus):
		super(DirectoryHandler, self).__init__(
				app, bus, self.verbs, self.rules)

	def find(self, path = '/'):
		return self.try_mapper_call(
				self.mapper.get_subtree_paths,
				path = path, depth = 1)

	def setup(self, path = '/'):
		request.route_data['map'] = self.find(path)

	def do_get(self, path = '/'):
		return request.route_data['map']

class ListNamesHandler(RouteHandler):
	verbs = 'GET'
	rules = ['/list', '<path:path>/list']

	def __init__(self, app, bus):
		super(ListNamesHandler, self).__init__(
				app, bus, self.verbs, self.rules)

	def find(self, path = '/'):
		return self.try_mapper_call(
				self.mapper.get_subtree, path = path).keys()

	def setup(self, path = '/'):
		request.route_data['map'] = self.find(path)

	def do_get(self, path = '/'):
		return request.route_data['map']

class ListHandler(RouteHandler):
	verbs = 'GET'
	rules = ['/enumerate', '<path:path>/enumerate']

	def __init__(self, app, bus):
		super(ListHandler, self).__init__(
				app, bus, self.verbs, self.rules)

	def find(self, path = '/'):
		return self.try_mapper_call(
				self.mapper.get_subtree, path = path)

	def setup(self, path = '/'):
		request.route_data['map'] = self.find(path)

	def do_get(self, path = '/'):
		objs = {}
		mapper_data = request.route_data['map']
		tree = PathTree()
		for x,y in mapper_data.iteritems():
			tree[x] = y

		try:
			# Check to see if the root path implements
			# enumerate in addition to any sub tree
			# objects.
			root = self.try_mapper_call(self.mapper.get_object,
					path = path)
			mapper_data[path] = root
		except:
			pass

		have_enumerate = [ (x[0], self.enumerate_capable(*x)) \
				for x in mapper_data.iteritems() \
					if self.enumerate_capable(*x) ]

		for x,y in have_enumerate:
			objs.update(self.call_enumerate(x, y))
			tmp = tree[x]
			# remove the subtree
			del tree[x]
			# add the new leaf back since enumerate results don't
			# include the object enumerate is being invoked on
			tree[x] = tmp

		# make dbus calls for any remaining objects
		for x,y in tree.dataitems():
			objs[x] = self.app.instance_handler.do_get(x)

		return objs

	@staticmethod
	def enumerate_capable(path, bus_data):
		busses = []
		for name, ifaces in bus_data.iteritems():
			if OpenBMCMapper.ENUMERATE_IFACE in ifaces:
				busses.append(name)
		return busses

	def call_enumerate(self, path, busses):
		objs = {}
		for b in busses:
			obj = self.bus.get_object(b, path, introspect = False)
			iface = dbus.Interface(obj, OpenBMCMapper.ENUMERATE_IFACE)
			objs.update(iface.enumerate())
		return objs

class MethodHandler(RouteHandler):
	verbs = 'POST'
	rules = '<path:path>/action/<method>'
	request_type = list

	def __init__(self, app, bus):
		super(MethodHandler, self).__init__(
				app, bus, self.verbs, self.rules)

	def find(self, path, method):
		busses = self.try_mapper_call(self.mapper.get_object,
				path = path)
		for items in busses.iteritems():
			m = self.find_method_on_bus(path, method, *items)
			if m:
				return m

		abort(404, _4034_msg %('method', 'found', method))

	def setup(self, path, method):
		request.route_data['method'] = self.find(path, method)

	def do_post(self, path, method):
		try:
			if request.parameter_list:
				return request.route_data['method'](*request.parameter_list)
			else:
				return request.route_data['method']()

		except dbus.exceptions.DBusException, e:
			if e.get_dbus_name() == DBUS_INVALID_ARGS:
				abort(400, str(e))
			raise

	@staticmethod
	def find_method_in_interface(method, obj, interface, methods):
		if methods is None:
			return None

		method = find_case_insensitive(method, methods.keys())
		if method is not None:
			iface = dbus.Interface(obj, interface)
			return iface.get_dbus_method(method)

	def find_method_on_bus(self, path, method, bus, interfaces):
		obj = self.bus.get_object(bus, path, introspect = False)
		iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
		data = iface.Introspect()
		parser = IntrospectionNodeParser(
				ElementTree.fromstring(data),
				intf_match = ListMatch(interfaces))
		for x,y in parser.get_interfaces().iteritems():
			m = self.find_method_in_interface(method, obj, x,
					y.get('method'))
			if m:
				return m

class PropertyHandler(RouteHandler):
	verbs = ['PUT', 'GET']
	rules = '<path:path>/attr/<prop>'

	def __init__(self, app, bus):
		super(PropertyHandler, self).__init__(
				app, bus, self.verbs, self.rules)

	def find(self, path, prop):
		self.app.instance_handler.setup(path)
		obj = self.app.instance_handler.do_get(path)
		try:
			obj[prop]
		except KeyError, e:
			if request.method == 'PUT':
				abort(403, _4034_msg %('property', 'created', str(e)))
			else:
				abort(404, _4034_msg %('property', 'found', str(e)))

		return { path: obj }

	def setup(self, path, prop):
		request.route_data['obj'] = self.find(path, prop)

	def do_get(self, path, prop):
		return request.route_data['obj'][path][prop]

	def do_put(self, path, prop, value = None):
		if value is None:
			value = request.parameter_list

		prop, iface, properties_iface = self.get_host_interface(
				path, prop, request.route_data['map'][path])
		try:
			properties_iface.Set(iface, prop, value)
		except ValueError, e:
			abort(400, str(e))
		except dbus.exceptions.DBusException, e:
			if e.get_dbus_name() == DBUS_INVALID_ARGS:
				abort(403, str(e))
			raise

	def get_host_interface(self, path, prop, bus_info):
		for bus, interfaces in bus_info.iteritems():
			obj = self.bus.get_object(bus, path, introspect = True)
			properties_iface = dbus.Interface(
				obj, dbus_interface=dbus.PROPERTIES_IFACE)

			info = self.get_host_interface_on_bus(
					path, prop, properties_iface,
					bus, interfaces)
			if info is not None:
				prop, iface = info
				return prop, iface, properties_iface

	def get_host_interface_on_bus(self, path, prop, iface, bus, interfaces):
		for i in interfaces:
			properties = self.try_properties_interface(iface.GetAll, i)
			if properties is None:
				continue
			prop = find_case_insensitive(prop, properties.keys())
			if prop is None:
				continue
			return prop, i

class InstanceHandler(RouteHandler):
	verbs = ['GET', 'PUT', 'DELETE']
	rules = '<path:path>'
	request_type = dict

	def __init__(self, app, bus):
		super(InstanceHandler, self).__init__(
				app, bus, self.verbs, self.rules)

	def find(self, path, callback = None):
		return { path: self.try_mapper_call(
			self.mapper.get_object,
			callback,
			path = path) }

	def setup(self, path):
		callback = None
		if request.method == 'PUT':
			def callback(e, **kw):
				abort(403, _4034_msg %('resource',
					'created', path))

		if request.route_data.get('map') is None:
			request.route_data['map'] = self.find(path, callback)

	def do_get(self, path):
		properties = {}
		for item in request.route_data['map'][path].iteritems():
			properties.update(self.get_properties_on_bus(
				path, *item))

		return properties

	@staticmethod
	def get_properties_on_iface(properties_iface, iface):
		properties = InstanceHandler.try_properties_interface(
				properties_iface.GetAll, iface)
		if properties is None:
			return {}
		return properties

	def get_properties_on_bus(self, path, bus, interfaces):
		properties = {}
		obj = self.bus.get_object(bus, path, introspect = False)
		properties_iface = dbus.Interface(
				obj, dbus_interface=dbus.PROPERTIES_IFACE)
		for i in interfaces:
			properties.update(self.get_properties_on_iface(
				properties_iface, i))

		return properties

	def do_put(self, path):
		# make sure all properties exist in the request
		obj = set(self.do_get(path).keys())
		req = set(request.parameter_list.keys())

		diff = list(obj.difference(req))
		if diff:
			abort(403, _4034_msg %('resource', 'removed',
				'%s/attr/%s' %(path, diff[0])))

		diff = list(req.difference(obj))
		if diff:
			abort(403, _4034_msg %('resource', 'created',
				'%s/attr/%s' %(path, diff[0])))

		for p,v in request.parameter_list.iteritems():
			self.app.property_handler.do_put(
					path, p, v)

	def do_delete(self, path):
		for bus_info in request.route_data['map'][path].iteritems():
			if self.bus_missing_delete(path, *bus_info):
				abort(403, _4034_msg %('resource', 'removed',
					path))

		for bus in request.route_data['map'][path].iterkeys():
			self.delete_on_bus(path, bus)

	def bus_missing_delete(self, path, bus, interfaces):
		return DELETE_IFACE not in interfaces

	def delete_on_bus(self, path, bus):
		obj = self.bus.get_object(bus, path, introspect = False)
		delete_iface = dbus.Interface(
				obj, dbus_interface = DELETE_IFACE)
		delete_iface.Delete()

class JsonApiRequestPlugin(object):
	''' Ensures request content satisfies the OpenBMC json api format. '''
	name = 'json_api_request'
	api = 2

	error_str = "Expecting request format { 'data': <value> }, got '%s'"
	type_error_str = "Unsupported Content-Type: '%s'"
	json_type = "application/json"
	request_methods = ['PUT', 'POST', 'PATCH']

	@staticmethod
	def content_expected():
		return request.method in JsonApiRequestPlugin.request_methods

	def validate_request(self):
		if request.content_length > 0 and \
				request.content_type != self.json_type:
			abort(415, self.type_error_str %(request.content_type))

		try:
			request.parameter_list = request.json.get('data')
		except ValueError, e:
			abort(400, str(e))
		except (AttributeError, KeyError, TypeError):
			abort(400, self.error_str %(request.json))

	def apply(self, callback, route):
		verbs = getattr(route.get_undecorated_callback(),
				'_verbs', None)
		if verbs is None:
			return callback

		if not set(self.request_methods).intersection(verbs):
			return callback

		def wrap(*a, **kw):
			if self.content_expected():
				self.validate_request()
			return callback(*a, **kw)

		return wrap

class JsonApiRequestTypePlugin(object):
	''' Ensures request content type satisfies the OpenBMC json api format. '''
	name = 'json_api_method_request'
	api = 2

	error_str = "Expecting request format { 'data': %s }, got '%s'"

	def apply(self, callback, route):
		request_type = getattr(route.get_undecorated_callback(),
				'request_type', None)
		if request_type is None:
			return callback

		def validate_request():
			if not isinstance(request.parameter_list, request_type):
				abort(400, self.error_str %(str(request_type), request.json))

		def wrap(*a, **kw):
			if JsonApiRequestPlugin.content_expected():
				validate_request()
			return callback(*a, **kw)

		return wrap

class JsonApiResponsePlugin(object):
	''' Emits normal responses in the OpenBMC json api format. '''
	name = 'json_api_response'
	api = 2

	def apply(self, callback, route):
		def wrap(*a, **kw):
			resp = { 'data': callback(*a, **kw) }
			resp['status'] = 'ok'
			resp['message'] = response.status_line
			return resp
		return wrap

class JsonApiErrorsPlugin(object):
	''' Emits error responses in the OpenBMC json api format. '''
	name = 'json_api_errors'
	api = 2

	def __init__(self, **kw):
		self.app = None
		self.function_type = None
		self.original = None
		self.json_opts = { x:y for x,y in kw.iteritems() \
			if x in ['indent','sort_keys'] }

	def setup(self, app):
		self.app = app
		self.function_type = type(app.default_error_handler)
		self.original = app.default_error_handler
		self.app.default_error_handler = self.function_type(
			self.json_errors, app, Bottle)

	def apply(self, callback, route):
		return callback

	def close(self):
		self.app.default_error_handler = self.function_type(
				self.original, self.app, Bottle)

	def json_errors(self, res, error):
		response_object = {'status': 'error', 'data': {} }
		response_object['message'] = error.status_line
		response_object['data']['description'] = str(error.body)
		if error.status_code == 500:
			response_object['data']['exception'] = repr(error.exception)
			response_object['data']['traceback'] = error.traceback.splitlines()

		json_response = json.dumps(response_object, **self.json_opts)
		res.content_type = 'application/json'
		return json_response

class RestApp(Bottle):
	def __init__(self, bus):
		super(RestApp, self).__init__(autojson = False)
		self.bus = bus
		self.mapper = Mapper(bus)

		self.install_hooks()
		self.install_plugins()
		self.create_handlers()
		self.install_handlers()

	def install_plugins(self):
		# install json api plugins
		json_kw = {'indent': 2, 'sort_keys': True}
		self.install(JSONPlugin(**json_kw))
		self.install(JsonApiErrorsPlugin(**json_kw))
		self.install(JsonApiResponsePlugin())
		self.install(JsonApiRequestPlugin())
		self.install(JsonApiRequestTypePlugin())

	def install_hooks(self):
		self.real_router_match = self.router.match
		self.router.match = self.custom_router_match
		self.add_hook('before_request', self.strip_extra_slashes)

	def create_handlers(self):
		# create route handlers
		self.directory_handler = DirectoryHandler(self, self.bus)
		self.list_names_handler = ListNamesHandler(self, self.bus)
		self.list_handler = ListHandler(self, self.bus)
		self.method_handler = MethodHandler(self, self.bus)
		self.property_handler = PropertyHandler(self, self.bus)
		self.instance_handler = InstanceHandler(self, self.bus)

	def install_handlers(self):
		self.directory_handler.install()
		self.list_names_handler.install()
		self.list_handler.install()
		self.method_handler.install()
		self.property_handler.install()
		# this has to come last, since it matches everything
		self.instance_handler.install()

	def custom_router_match(self, environ):
		''' The built-in Bottle algorithm for figuring out if a 404 or 405 is
                    needed doesn't work for us since the instance rules match everything.
                    This monkey-patch lets the route handler figure out which response is
                    needed.  This could be accomplished with a hook but that would require
		    calling the router match function twice.
		'''
		route, args = self.real_router_match(environ)
		if isinstance(route.callback, RouteHandler):
			route.callback._setup(**args)

		return route, args

	@staticmethod
	def strip_extra_slashes():
		path = request.environ['PATH_INFO']
		trailing = ("","/")[path[-1] == '/']
		parts = filter(bool, path.split('/'))
		request.environ['PATH_INFO'] = '/' + '/'.join(parts) + trailing

if __name__ == '__main__':
	log = logging.getLogger('Rocket.Errors')
	log.setLevel(logging.INFO)
	log.addHandler(logging.StreamHandler(sys.stdout))

	bus = dbus.SystemBus()
	app = RestApp(bus)
	default_cert = os.path.join(sys.prefix, 'share',
			os.path.basename(__file__), 'cert.pem')

	server = Rocket(('0.0.0.0',
			443,
			default_cert,
			default_cert),
		'wsgi', {'wsgi_app': app})
	server.start()
OpenPOWER on IntegriCloud