寫在前頭,最近更新到了odoo13, 抽空看了一下odoo的源碼,瀏覽了啟動(dòng)過程。
啟動(dòng)文件 odoo-bin.py
主要過程:
1.導(dǎo)入os,設(shè)置環(huán)境上下文
2.執(zhí)行cli目錄下的main()方法
#!/usr/bin/env python3
# set server timezone in UTC before time module imported
__import__('os').environ['TZ'] = 'UTC' #此處是導(dǎo)入os模塊并設(shè)置全局環(huán)境
import odoo
if __name__ == "__main__":
odoo.cli.main() #啟動(dòng)腳本, 執(zhí)行main()函數(shù)
cli目錄下的 command.py
cli.main()執(zhí)行的是command.py中的 main()方法
主要過程:
1.獲取系統(tǒng)啟動(dòng)參數(shù)
2.獲取模塊信息并導(dǎo)入
3.根據(jù)命令,實(shí)例化服務(wù)并啟動(dòng)
def main():
args = sys.argv[1:] # 此處是獲取啟動(dòng)參數(shù)
# The only shared option is '--addons-path=' needed to discover additional
# commands from modules
if len(args) > 1 and args[0].startswith('--addons-path=') and not args[1].startswith("-"):
# parse only the addons-path, do not setup the logger...
odoo.tools.config._parse_config([args[0]])
args = args[1:]
# Default legacy command
command = "server" # 默認(rèn)啟動(dòng)命令的方式 為‘server’
# TODO: find a way to properly discover addons subcommands without importing the world
# Subcommand discovery
if len(args) and not args[0].startswith("-"):
logging.disable(logging.CRITICAL)
for module in get_modules(): # 獲取模塊
if isdir(joinpath(get_module_path(module), 'cli')):
__import__('odoo.addons.' + module) # 導(dǎo)入模塊
logging.disable(logging.NOTSET)
command = args[0]
args = args[1:]
if command in commands:
o = commands[command]() #獲取命令并執(zhí)行, 實(shí)際是實(shí)例了一個(gè) Server對(duì)象
o.run(args) # 調(diào)用Server的run()方法
else:
sys.exit('Unknow command %r' % (command,))
cli目錄下的 server.py
Server類用于啟動(dòng)odoo服務(wù),啟動(dòng)方法為run,而run 執(zhí)行的是server.py中的 main()方法
主要過程:
1.檢查用戶(包括數(shù)據(jù)庫用戶)以及設(shè)置config參數(shù)
2.創(chuàng)建數(shù)據(jù)庫(此處后續(xù)文章詳細(xì)說明)
3.啟動(dòng)odoo的http服務(wù),執(zhí)行service目錄下的server.py中的start()方法
def main(args):
check_root_user() #檢查root用戶
odoo.tools.config.parse_config(args) #解析配置參數(shù)
check_postgres_user() # 檢查數(shù)據(jù)庫用戶, 針對(duì) postgres用戶
report_configuration() #記錄配置的值
config = odoo.tools.config
# the default limit for CSV fields in the module is 128KiB, which is not
# quite sufficient to import images to store in attachment. 500MiB is a
# bit overkill, but better safe than sorry I guess
csv.field_size_limit(500 * 1024 * 1024)
preload = []
if config['db_name']:
preload = config['db_name'].split(',')
for db_name in preload:
try:
odoo.service.db._create_empty_database(db_name) #創(chuàng)建空的數(shù)據(jù)庫
config['init']['base'] = True
except ProgrammingError as err:
if err.pgcode == errorcodes.INSUFFICIENT_PRIVILEGE:
# We use an INFO loglevel on purpose in order to avoid
# reporting unnecessary warnings on build environment
# using restricted database access.
_logger.info("Could not determine if database %s exists, "
"skipping auto-creation: %s", db_name, err)
else:
raise err
except odoo.service.db.DatabaseExists:
pass
if config["translate_out"]:
export_translation()
sys.exit(0)
if config["translate_in"]:
import_translation()
sys.exit(0)
# This needs to be done now to ensure the use of the multiprocessing
# signaling mecanism for registries loaded with -d
if config['workers']:
odoo.multi_process = True
stop = config["stop_after_init"]
setup_pid_file()
rc = odoo.service.server.start(preload=preload, stop=stop) #啟動(dòng)odoo的http服務(wù)
sys.exit(rc)
class Server(Command):
"""Start the odoo server (default command)"""
def run(self, args):
main(args)
service目錄下的 server.py
start用于啟動(dòng)odoo的http服務(wù)
主要過程:
1.設(shè)置一個(gè)全局的server對(duì)象
2.實(shí)例server對(duì)象(wsgi_server)
3.啟動(dòng)wsgi_server(實(shí)際是實(shí)例化root對(duì)象,位于http.py中)
4.啟動(dòng)http服務(wù)后,便會(huì)加載模塊,路由分發(fā)等等
def start(preload=None, stop=False):
""" Start the odoo http server and cron processor.
"""
global server
load_server_wide_modules()
odoo.service.wsgi_server._patch_xmlrpc_marshaller()
if odoo.evented:
server = GeventServer(odoo.service.wsgi_server.application)
elif config['workers']:
if config['test_enable'] or config['test_file']:
_logger.warning("Unit testing in workers mode could fail; use --workers 0.")
server = PreforkServer(odoo.service.wsgi_server.application)
# Workaround for Python issue24291, fixed in 3.6 (see Python issue26721)
if sys.version_info[:2] == (3,5):
# turn on buffering also for wfile, to avoid partial writes (Default buffer = 8k)
werkzeug.serving.WSGIRequestHandler.wbufsize = -1
else:
server = ThreadedServer(odoo.service.wsgi_server.application)
watcher = None
if 'reload' in config['dev_mode'] and not odoo.evented:
if inotify:
watcher = FSWatcherInotify()
watcher.start()
elif watchdog:
watcher = FSWatcherWatchdog()
watcher.start()
else:
if os.name == 'posix' and platform.system() != 'Darwin':
module = 'inotify'
else:
module = 'watchdog'
_logger.warning("'%s' module not installed. Code autoreload feature is disabled", module)
if 'werkzeug' in config['dev_mode']:
server.app = DebuggedApplication(server.app, evalex=True)
rc = server.run(preload, stop)
if watcher:
watcher.stop()
# like the legend of the phoenix, all ends with beginnings
if getattr(odoo, 'phoenix', False):
_reexec()
return rc if rc else 0
以上,為啟動(dòng)的大致過程。其實(shí)加載模塊,也是應(yīng)用了python本身的導(dǎo)入機(jī)制。后續(xù)抽空研究odoo的模塊加載機(jī)制,路由分發(fā)機(jī)制等等。
============================================================================================================================
