【原創】Swift服務啓動架構分析

    Swift中會用到三個很是有用的python模塊它們分別是webob,eventlet,paste.deploy,其中webob提供了WSGI封裝的Request,Response和其餘的一些HTTP操做,eventlet是一個並行的網絡編程庫,Swift使用它提供多線程的編程,固然更重要的是我接下來要介紹的wsig服務的提供,paste,deploy是提供配置文件書寫,啓動多個服務(例如proxy-server.conf中的每個服務)。python

    初學python的話,必定對這些雲裏霧裏,我就是這樣,不過沒有關係,對照源碼,本身把架構抽離出來發現,其實真的不難(固然這是大牛們的架構,固然簡單易懂)。web

    例如啓動一個proxy服務,最終的啓動操做在/swift/common/wsgi.py中的run_server方法中的wsgi.server()。這個方法是eventlet提供的方法,用來啓動一個應用服務(你能夠提供給它ip,port,app)app經過loadapp方法從proxy-server.conf中加載其中的app,調用其中的app_factory方法 實例化功能類(Application),要保證這個Application類是能夠callable的,須要實現__call__方法,經過webob的Request類,封裝一個請求(經過env),而後進行相應的請求操做,而後返回響應。編程

上碼:myserver.pyswift

import eventlet
from eventlet import wsgi
from paste.deploy import loadapp
import os
app = loadapp('config:%s' % os.path.abspath('proxy.conf'))

wsgi.server(eventlet.listen(('', 8090)), app)

 很簡單,啓動一個app。網絡

proxy.conf多線程

[DEFAULT]

[pipeline:main]
pipeline = myapp

[app:myapp]
paste.app_factory = myapp:app_factory

就是app指向myapp。架構

myapp.pyapp

from webob import Request, Response

class Application(object):

    def __init__(self, conf):
        pass
    def __call__(self, env, start_response):
       req = Request(env)
       return self.handle_request(req)(env, start_response)
    
    def handle_request(self, req):
        if (req.method == 'GET'):
            resp = Response(request=req)
            resp.body = 'you send GET method'
            return resp

def app_factory(global_conf, **local_conf):
    conf = global_conf.copy()
    conf.update(local_conf)
    return Application(conf)
若是發一個GET請求,返回you send GET method。

    這樣就把服務啓動的架構抽離抽離出來,這個三段代碼分別對應了,Swift中的/swift/common/wsgi.py,proxy-server.conf,/swift/proxy/server.py中的相關代碼,而後Swift把具體操做GET POST等請求的代碼封裝大/swift/proxy/controllers中進行。spa

對於eventlet,webob,paste.deploy更多理解,請看官方文檔:.net

http://eventlet.net/

http://webob.org/

http://pythonpaste.org/deploy/

相關文章
相關標籤/搜索