-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path__main__.py
134 lines (111 loc) · 3.65 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import base64
import logging
import os
import ssl
import sys
from pathlib import Path
from time import strftime
from datetime import datetime
import aiohttp_jinja2
import jinja2
from aiohttp import web
import aiohttp_cors
from aiohttp_session import setup as session_setup
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from cryptography import fernet
from beacon import conf, load_logger
from beacon.request import ontologies
from beacon.response import middlewares
from beacon.request.routes import routes
from beacon.db import client
LOG = logging.getLogger(__name__)
async def initialize(app):
# Load static
app["static_root_url"] = "/static"
# Configure jinja
env = aiohttp_jinja2.get_env(app)
env.globals.update(
len=len,
max=max,
enumerate=enumerate,
range=range,
conf=conf,
now=strftime("%Y"),
)
setattr(conf, 'update_datetime', datetime.now().isoformat())
LOG.info("Initialization done.")
async def destroy(app):
"""Upon server close, close the DB connections."""
LOG.info("Shutting down.")
client.close()
def main(path=None):
# Configure the logging
load_logger()
# Configure the beacon
beacon = web.Application(
middlewares=[web.normalize_path_middleware(), middlewares.error_middleware]
)
beacon.on_startup.append(initialize)
beacon.on_cleanup.append(destroy)
# Prepare for the UI
main_dir = Path(__file__).parent.parent.resolve()
# Where the templates are
template_loader = jinja2.FileSystemLoader(str(main_dir / "ui" / "templates"))
aiohttp_jinja2.setup(beacon, loader=template_loader)
# Session middleware
fernet_key = fernet.Fernet.generate_key()
secret_key = base64.urlsafe_b64decode(
fernet_key
) # 32 url-safe base64-encoded bytes
storage = EncryptedCookieStorage(
secret_key, cookie_name=middlewares.SESSION_STORAGE
)
session_setup(beacon, storage)
# Configure the endpoints
beacon.add_routes(routes)
cors = aiohttp_cors.setup(beacon, defaults={
"*": aiohttp_cors.ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
)
})
for route in list(beacon.router.routes()):
cors.add(route)
# Configure HTTPS (or not)
ssl_context = None
if getattr(conf, "beacon_tls_enabled", False):
use_as_client = getattr(conf, "beacon_tls_client", False)
sslcontext = ssl.create_default_context(
ssl.Purpose.CLIENT_AUTH if use_as_client else ssl.Purpose.SERVER_AUTH
)
sslcontext.load_cert_chain(conf.beacon_cert, conf.beacon_key) # should exist
sslcontext.check_hostname = False
# TODO: add the CA chain
# Load ontologies
#LOG.info("Loading ontologies... (this might take a while)")
#ontologies.load_obo()
#LOG.info("Finished loading the ontologies...")
# Run beacon
if path:
if os.path.exists(path):
os.unlink(path)
# will create the UDS socket and bind to it
web.run_app(beacon, path=path, shutdown_timeout=0, ssl_context=ssl_context)
else:
static_files = Path(__file__).parent.parent.resolve() / "ui" / "static"
beacon.add_routes([web.static("/static", str(static_files))])
web.run_app(
beacon,
host=getattr(conf, "beacon_host", "0.0.0.0"),
port=getattr(conf, "beacon_port", 5050),
shutdown_timeout=0,
ssl_context=ssl_context,
)
if __name__ == "__main__":
# Unix socket
if len(sys.argv) > 1:
main(path=sys.argv[1])
# host:port
else:
main()