Initial all url of api v2
[yardstick.git] / api / server.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from __future__ import absolute_import
10
11 import inspect
12 import logging
13 import socket
14 from six.moves import filter
15
16 from flasgger import Swagger
17 from flask import Flask
18 from flask_restful import Api
19
20 from api.database import Base
21 from api.database import db_session
22 from api.database import engine
23 from api.database.v1 import models
24 from api.urls import urlpatterns
25 from api import ApiResource
26 from yardstick import _init_logging
27 from yardstick.common import utils
28 from yardstick.common import constants as consts
29
30 try:
31     from urlparse import urljoin
32 except ImportError:
33     from urllib.parse import urljoin
34
35 LOG = logging.getLogger(__name__)
36
37 app = Flask(__name__)
38
39 Swagger(app)
40
41 api = Api(app)
42
43
44 @app.teardown_request
45 def shutdown_session(exception=None):
46     db_session.remove()
47
48
49 def get_resource(resource_name):
50     name = ''.join(resource_name.split('_'))
51     return next((r for r in utils.itersubclasses(ApiResource)
52                  if r.__name__.lower() == name))
53
54
55 def init_db():
56     def func(a):
57         try:
58             if issubclass(a[1], Base):
59                 return True
60         except TypeError:
61             pass
62         return False
63
64     subclses = filter(func, inspect.getmembers(models, inspect.isclass))
65     LOG.debug('Import models: %s', [a[1] for a in subclses])
66     Base.metadata.create_all(bind=engine)
67
68
69 def app_wrapper(*args, **kwargs):
70     init_db()
71     return app(*args, **kwargs)
72
73
74 def get_endpoint(url):
75     ip = socket.gethostbyname(socket.gethostname())
76     return urljoin('http://{}:{}'.format(ip, consts.API_PORT), url)
77
78
79 for u in urlpatterns:
80     try:
81         api.add_resource(get_resource(u.target), u.url, endpoint=get_endpoint(u.url))
82     except StopIteration:
83         LOG.error('url resource not found: %s', u.url)
84
85
86 if __name__ == '__main__':
87     _init_logging()
88     LOG.setLevel(logging.DEBUG)
89     LOG.info('Starting server')
90     init_db()
91     app.run(host='0.0.0.0')