得益于OpenStack的良好架构,对OpenStack进行扩展非常方便,每个模块都留出了各种接口和扩展点,能够让用户扩展自定义功能。下面以操作记录为例子,介绍一下如何扩展nova-api组件。
需求:
用户的一些重要操作必须记录下来,方便进行事后查询,比如instance的创建、销毁,比如公网IP的申请、分配等等。
实现:
因为所有的这些操作都是通过调用nova-api进行,我们要对nova-api进行扩展,记录相关的请求。nova-api是基于Python Paste来构建的,只需要在配置文件里面进行修改(nova-api-paste.ini),在pipeline上添加一个名为audit的filter:
Text代码
- [pipeline:openstackapi11]
- pipeline = faultwrap authtoken keystonecontext ratelimit audit extensions osapiapp11
- [filter:audit]
- paste.filter_factory = nova.api.openstack.audit:AuditMiddleware.factory
然后我们写一个Middleware:
Python代码
- import time
- from nova import log as logging
- from nova import wsgi as base_wsgi
- from nova.api.openstack import wsgi
- LOG = logging.getLogger('nova.api.audit')
- class AuditMiddleware(base_wsgi.Middleware):
- """store POST/PUT/DELETE api request for audit."""
- def __init__(self, application, audit_methods='POST,PUT,DELETE'):
- base_wsgi.Middleware.__init__(self, application)
- self._audit_methods = audit_methods.split(",")
- def process_request(self, req):
- self._need_audit = req.method in self._audit_methods
- if self._need_audit:
- self._request = req
- self._requested_at = time.time()
- def process_response(self, response):
- if self._need_audit and response.status_int >= 200 and response.status_int < 300:
- self._store_log(response)
- return response
- def _store_log(self, response):
- req = self._request
- LOG.info("tenant: %s, user: %s, %s: %s, at: %s",
- req.headers.get('X-Tenant', 'admin'),
- req.headers.get('X-User', 'admin'),
- req.method,
- req.path_info,
- self._requested_at)
重启一下nova-api进程,然后在dashboard上做一些操作,我们就能在日志文件里面看到如下的信息:
Text代码
- tenant: 1, user: admin, POST: /1/os-security-group-rules, at: 1326352441.16
- tenant: 1, user: admin, DELETE: /1/servers/32, at: 1326353021.58
这里默认记录所有的非GET请求,如果不想将PUT请求记录(PUT对应更新),在配置文件里面更改一下:
Text代码
- [filter:audit]
- audit_methods=POST,DELETE
更进一步,可以将_store_log改造一下,将数据保存到数据库,我们可以在配置文件里面添加数据库的连接信息等,然后利用API Extension来写一个扩展API,提供查询租户audit log的api功能。