#!/usr/bin/env python3
# Author(s): Toni Sissala
# Copyright 2020 Finnish Social Science Data Archive FSD / University of Tampere
# Licensed under the EUPL. See LICENSE.txt for full license.
"""Main entry point for starting Document Store server.
"""
import sys
import logging
import traceback
import kuha_common.server
from kuha_common.document_store.records import COLLECTIONS
from kuha_document_store.configure import configure
from kuha_document_store.database import DocumentStoreDatabase
from kuha_document_store.importers import importers as DS_IMPORTERS
from kuha_document_store.handlers import (
ImportHandler,
RestApiHandler,
QueryHandler
)
[docs]def get_app(api_version, app_settings=None):
"""Setup routes and return initialized Tornado web application.
:param api_version: HTTP Api version gets prepended to routes.
:type api_version: str
:param app_settings: Settings to store to application.
:type app_settings: dict or None.
:returns: Tornado web application.
:rtype: :obj:`tornado.web.Application`
"""
collections = r'|'.join(COLLECTIONS)
importers = r'|'.join(DS_IMPORTERS.keys())
handlers = [
# REST
(kuha_common.server.str_api_endpoint(
api_version, r"(?P<collection>{})/?".format(collections)
), RestApiHandler),
(kuha_common.server.str_api_endpoint(
api_version, r"(?P<collection>{})/(?P<resource_id>\w+)".format(collections)
), RestApiHandler),
# IMPORT
(kuha_common.server.str_api_endpoint(
api_version, r"import/(?P<importer_id>{})/?".format(importers)
), ImportHandler),
(kuha_common.server.str_api_endpoint(
api_version, r"import/(?P<importer_id>{})/(?P<collection>{})".format(importers, collections)
), ImportHandler),
# QUERY WITH JSON-BODY
(kuha_common.server.str_api_endpoint(
api_version, r"query/(?P<collection>{})/?".format(collections)
), QueryHandler),
]
web_app = kuha_common.server.WebApplication(handlers)
if app_settings:
web_app.settings = app_settings
return web_app
[docs]def main():
"""Application main function.
Parse commandline for settings.
Initialize database and web application.
Start serving via :func:`kuha_common.server.serve`.
Exit on exceptions propagated at this level.
:returns: exit code, 1 on error, 0 on success.
:rtype: int
"""
rval = 0
settings = configure()
if settings.print_configuration:
print("Print active configuration and exit\n")
for key, value in settings._get_kwargs():
print("{} ... {}".format(key, value))
return rval
database = DocumentStoreDatabase(settings)
app_settings = {'db': database, 'importers': DS_IMPORTERS}
web_app = get_app(settings.document_store_api_version, app_settings)
try:
kuha_common.server.serve(web_app, settings.document_store_port,
process_count=settings.server_process_count,
on_exit=database.close)
except KeyboardInterrupt:
rval = 1
logging.warning("Shutdown by CTRL + C")
except Exception as exc:
rval = 1
logging.error(str(exc))
traceback.print_exc()
finally:
logging.info("Shutdown")
return rval
if __name__ == '__main__':
sys.exit(main())