Openstack nova-api 处理过程
- 背景知识
1、WSGI APP -- http://archimedeanco.com/wsgi-tutorial/
WSGI 是理解整个nova-api的基础
WSGI是一个Python针对Web应用的实现框架。此框架由Server/Gateway和Framework/App构成。
WSGI APP是一个python中的callable,它定义了可以作为WSGI框架中Application的对象的标准。
一个python函数示例:
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers)
return ['Hello world!\n']
一个python类的示例:
class AppClass:
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def __iter__(self):
status = '200 OK‘
response_headers = [('Content-type', 'text/plain')] self.start(status, response_headers)
yield "Hello world!\n"
所有的web请求参数都被封装在environ这个dictionary中,start-response函数让人难以理解,其主要作用是设置reponse的http返回码和http header.返回的list的一个item对应于http response中的一个chunk。
2、Webob -- http://docs.webob.org/en/latest/reference.html
webob的主要作用是:
使用类webob.Request来封装Http请求,对比wsgi 框架中的environ;
使用webob.Response来封装Http返回;对比在wsgi中http返回是分开写的。
使用@webob.dec.wsgify来将一般的func修饰为WSGI App。
一个使用webob的WSGI App的示例:
from webob import Request, Response
class WikiApp(object):
def __call__(self, environ, start_response):
req = Request(environ)
resp = Response( 'Hello %s!' % req.params.get('name', 'World'))
return resp(environ, start_response)
Webob.dec.wsgify示例:
class MyRequest(webob.Request):
@property
def is_local(self):
return self.remote_addr == '127.0.0.1'
@wsgify(RequestClass=MyRequest)
def myfunc(req):
if req.is_local:
return Response('hi!')
else:
raise webob.exc.HTTPForbidden
3、Paste Deploy -- http://blog.csdn.net/sonicatnoc/article/details/6539716
Paste deploy:
利用.ini文件将python对象载入到运行环境中
为被载入的对象进行进行初始化设置。
.ini示例:
[DEFAULT]
key1=value1
key2=value2
key3=value3
[composite:pdl]
use=egg:Paste#urlmap
/:root
/calc:calc
[pipeline:root]
pipeline = logrequest showversion
[pipeline:calc]
pipeline = logrequest calculator
[filter:logrequest]
username = root
password = root123
paste.filter_factory = pastedeploylab:LogFilter.factory
[app:showversion]
version = 1.0.0
paste.app_factory = pastedeploylab:ShowVersion.factory
[app:calculator]
description = This is an "+-*/" Calculator
paste.app_factory = pastedeploylab:Calculator.factory
python code 示例:
#Filter
class LogFilter():
…
@classmethod
def factory(cls, global_conf, **kwargs):
return LogFilter
class ShowVersion():
def __init__(self):
pass
@classmethod
def factory(cls, global_conf, **kwargs):
return ShowVersion()
class Calculator():
def __init__(self):
pass
def __call__(self, environ, start_response):
… …
@classmethod
def factory(cls, global_conf, **kwargs):
return Calculator()
if __name__ == '__main__':
configfile = "pastedeploylab.ini"
appname = "pdl"
wsgi_app = loadapp("config:%s" % os.path.abspath(configfile), ap pname)
print wsgi_app.keys()
print wsgi_app.applications
server = make_server('localhost', 8080, wsgi_app)
server.serve_forever()
4、Routes -- http://svn.pythonpaste.org/Paste/WebOb/branches/ianb-decorator-experiment/docs/do-it-yourself.txt
Routes :
将URL 映射到Controller或Action上。
灵活的URL 映射机制
针对Restful的resource定义
python code示例:
>>> class Hello(object):
... def __init__(self, req):
... self.request = req
... def get(self):
... return '''<form method="POST">
... You're name: <input type="text" name="name">
... <input type="submit">
... </form>'''
... def post(self):
... return 'Hello %s!' % self.request.params['name']
>>> hello = rest_controller(Hello)
We'll run the same test as before:
.. code-block:: python
>>> hello_world = Router()
>>> hello_world.add_route('/', controller=hello)
>>> req = Request.blank('/')
>>> resp = req.get_response(hello_world)
>>> print resp
- Openstack Request的处理过程
1、Openstack架构简单介绍
nova-api模块对外提供基于nova-api的Restful的Web api接口。
nova-api模块对各个功能模块的调用是通过Queue topic的方式异步地进行,数据传递使用database进行。
nova-api模块和各个功能模块在操作系统中都是作为service存在。
2、nova-api初始化过程
1. openstack/bin/nova-api-compute.py
if __name__ == '__main__':
utils.default_flagfile()
flags.FLAGS(sys.argv)
logging.setup()
utils.monkey_patch()
server = service.WSGIService('osapi_compute')
service.serve(server)
service.wait()
2. nova.service.WSGIService
class WSGIService(object):
"""Provides ability to launch API from a 'paste' configuration."""
def __init__(self, name, loader=None):
self.name = name
self.manager = self._get_manager()
self.loader = loader or wsgi.Loader()
self.app = self.loader.load_app(name)
self.host = getattr(FLAGS, '%s_listen' % name, "0.0.0.0")
self.port = getattr(FLAGS, '%s_listen_port' % name, 0)
self.server = wsgi.Server(name,
self.app,
host=self.host,
port=self.port)
3. nova.wsgi.Server
def __init__(self, name, app, host=None, port=None, pool_size=None,
protocol=eventlet.wsgi.HttpProtocol):
self.name = name
self.app = app
self.host = host or "0.0.0.0"
self.port = port or 0
self._server = None
self._tcp_server = None
self._socket = None
self._protocol = protocol
self._pool = eventlet.GreenPool(pool_size or self.default_pool_size)
self._logger = logging.getLogger("eventlet.wsgi.server")
self._wsgi_logger = logging.WritableLogger(self._logger)
def _start(self):
eventlet.wsgi.server(self._socket,
self.app,
protocol=self._protocol,
custom_pool=self._pool,
log=self._wsgi_logger)
4. openstack/etc/api-paste.ini
[composite:osapi_compute]
use = call:nova.api.openstack.urlmap:urlmap_factory
/: oscomputeversions
/v1.1: openstack_compute_api_v2
/v2: openstack_compute_api_v2
[composite:openstack_compute_api_v2]
use = call:nova.api.auth:pipeline_factory
noauth = faultwrap noauth ratelimit osapi_compute_app_v2
deprecated = faultwrap auth ratelimit osapi_compute_app_v2
keystone = faultwrap authtoken keystonecontext ratelimit osapi_compute_app_v2
keystone_nolimit = faultwrap authtoken keystonecontext osapi_compute_app_v2
[app:osapi_compute_app_v2]
paste.app_factory = nova.api.openstack.compute:APIRouter.factory
5. nova.api.openstack.compute.APIRouter
class APIRouter(nova.api.openstack.APIRouter):
ExtensionManager = extensions.ExtensionManager
def _setup_routes(self, mapper):
self.resources['versions'] = versions.create_resource()
mapper.connect("versions", "/",
controller=self.resources['versions'],
action='show')
mapper.redirect("", "/")
def create_resource():
return wsgi.Resource(Controller())
6. nova.api.openstack.wsgi.Resource
7. nova.api.openstack.compute.servers.Controller
3、nova-api 的类结构模型
4、nova api Request 的处理过程
- 碰到的问题