Merge "API proposal for functest"
[functest.git] / functest / api / server.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """
11 Used to launch Functest RestApi
12
13 """
14
15 import logging
16 import socket
17 from urlparse import urljoin
18 import pkg_resources
19
20 from flask import Flask
21 from flask_restful import Api
22
23 from functest.api.base import ApiResource
24 from functest.api.urls import URLPATTERNS
25 from functest.api.common import api_utils
26
27
28 LOGGER = logging.getLogger(__name__)
29
30
31 def get_resource(resource_name):
32     """ Obtain the required resource according to resource name """
33     name = ''.join(resource_name.split('_'))
34     return next((r for r in api_utils.itersubclasses(ApiResource)
35                  if r.__name__.lower() == name))
36
37
38 def get_endpoint(url):
39     """ Obtain the endpoint of url """
40     address = socket.gethostbyname(socket.gethostname())
41     return urljoin('http://{}:5000'.format(address), url)
42
43
44 def api_add_resource(api):
45     """
46     The resource has multiple URLs and you can pass multiple URLs to the
47     add_resource() method on the Api object. Each one will be routed to
48     your Resource
49     """
50     for url_pattern in URLPATTERNS:
51         try:
52             api.add_resource(
53                 get_resource(url_pattern.target), url_pattern.url,
54                 endpoint=get_endpoint(url_pattern.url))
55         except StopIteration:
56             LOGGER.error('url resource not found: %s', url_pattern.url)
57
58
59 def main():
60     """Entry point"""
61     logging.config.fileConfig(pkg_resources.resource_filename(
62         'functest', 'ci/logging.ini'))
63     LOGGER.info('Starting Functest server')
64     app = Flask(__name__)
65     api = Api(app)
66     api_add_resource(api)
67     app.run(host='0.0.0.0')