OpenStack擴(kuò)展自定義功能介紹
得益于OpenStack的良好架構(gòu),對(duì)OpenStack進(jìn)行擴(kuò)展非常方便,每個(gè)模塊都留出了各種接口和擴(kuò)展點(diǎn),能夠讓用戶(hù)擴(kuò)展自定義功能。下面以操作記錄為例子,介紹一下如何擴(kuò)展nova-api組件。
需求:
用戶(hù)的一些重要操作必須記錄下來(lái),方便進(jìn)行事后查詢(xún),比如instance的創(chuàng)建、銷(xiāo)毀,比如公網(wǎng)IP的申請(qǐng)、分配等等。
實(shí)現(xiàn):
因?yàn)樗械倪@些操作都是通過(guò)調(diào)用nova-api進(jìn)行,我們要對(duì)nova-api進(jìn)行擴(kuò)展,記錄相關(guān)的請(qǐng)求。nova-api是基于Python Paste來(lái)構(gòu)建的,只需要在配置文件里面進(jìn)行修改(nova-api-paste.ini),在pipeline上添加一個(gè)名為audit的filter:
Text代碼
- [pipeline:openstackapi11]
- pipeline = faultwrap authtoken keystonecontext ratelimit audit extensions osapiapp11
- [filter:audit]
- paste.filter_factory = nova.api.openstack.audit:AuditMiddleware.factory
然后我們寫(xiě)一個(gè)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進(jìn)程,然后在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
這里默認(rèn)記錄所有的非GET請(qǐng)求,如果不想將PUT請(qǐng)求記錄(PUT對(duì)應(yīng)更新),在配置文件里面更改一下:
Text代碼
- [filter:audit]
- audit_methods=POST,DELETE
更進(jìn)一步,可以將_store_log改造一下,將數(shù)據(jù)保存到數(shù)據(jù)庫(kù),我們可以在配置文件里面添加數(shù)據(jù)庫(kù)的連接信息等,然后利用API Extension來(lái)寫(xiě)一個(gè)擴(kuò)展API,提供查詢(xún)租戶(hù)audit log的api功能。