vtn_service.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from asyncio import iscoroutine
  13. from http import HTTPStatus
  14. import os
  15. from aiohttp import web
  16. from jinja2 import Environment, PackageLoader, select_autoescape
  17. from .. import errors
  18. from ..messaging import create_message, parse_message
  19. class VTNService:
  20. def __init__(self, vtn_id):
  21. self.vtn_id = vtn_id
  22. self.handlers = {}
  23. for method in [getattr(self, attr) for attr in dir(self) if callable(getattr(self, attr))]:
  24. if hasattr(method, '__message_type__'):
  25. self.handlers[method.__message_type__] = method
  26. async def handler(self, request):
  27. """
  28. Handle all incoming POST requests.
  29. """
  30. content = await request.read()
  31. message_type, message_payload = self._parse_message(content)
  32. if message_type in self.handlers:
  33. handler = self.handlers[message_type]
  34. result = handler(message_payload)
  35. if iscoroutine(result):
  36. result = await result
  37. if result is not None:
  38. response_type, response_payload = result
  39. else:
  40. response_type, response_payload = 'oadrResponse', {}
  41. response_payload['vtn_id'] = self.vtn_id
  42. response_payload['response'] = {'request_id': message_payload.get('request_id', None),
  43. 'response_code': 200,
  44. 'response_description': 'OK'}
  45. # Create the XML response
  46. msg = self._create_message(response_type, **response_payload)
  47. response = web.Response(text=msg,
  48. status=HTTPStatus.OK,
  49. content_type='application/xml')
  50. else:
  51. msg = self._create_message('oadrResponse',
  52. status_code=errorcodes.COMPLIANCE_ERROR,
  53. status_description=f"A message of type {message_type} should not be sent to this endpoint")
  54. response = web.Response(
  55. text=msg,
  56. status=HTTPStatus.BAD_REQUEST,
  57. content_type='application/xml')
  58. return response