|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# --- BEGIN_HEADER --- |
| 5 | +# |
| 6 | +# mig/services/coreapi/server - coreapi service server internals |
| 7 | +# Copyright (C) 2003-2025 The MiG Project by the Science HPC Center at UCPH |
| 8 | +# |
| 9 | +# This file is part of MiG. |
| 10 | +# |
| 11 | +# MiG is free software: you can redistribute it and/or modify |
| 12 | +# it under the terms of the GNU General Public License as published by |
| 13 | +# the Free Software Foundation; either version 2 of the License, or |
| 14 | +# (at your option) any later version. |
| 15 | +# |
| 16 | +# MiG is distributed in the hope that it will be useful, |
| 17 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 18 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 19 | +# GNU General Public License for more details. |
| 20 | +# |
| 21 | +# You should have received a copy of the GNU General Public License |
| 22 | +# along with this program; if not, write to the Free Software |
| 23 | +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 24 | +# |
| 25 | +# -- END_HEADER --- |
| 26 | +# |
| 27 | + |
| 28 | + |
| 29 | +"""HTTP server parts of the coreapi service.""" |
| 30 | + |
| 31 | +from __future__ import print_function |
| 32 | +from __future__ import absolute_import |
| 33 | + |
| 34 | +from http.server import HTTPServer, BaseHTTPRequestHandler |
| 35 | +from socketserver import ThreadingMixIn |
| 36 | + |
| 37 | +import base64 |
| 38 | +from collections import defaultdict, namedtuple |
| 39 | +from flask import Flask, request, Response |
| 40 | +import os |
| 41 | +import sys |
| 42 | +import threading |
| 43 | +import time |
| 44 | +import werkzeug.exceptions as httpexceptions |
| 45 | +from wsgiref.simple_server import WSGIRequestHandler |
| 46 | + |
| 47 | +from mig.lib.coresvc.payloads import PayloadException, \ |
| 48 | + PAYLOAD_POST_USER as _REQUEST_ARGS_POST_USER |
| 49 | +from mig.shared.base import canonical_user, keyword_auto, force_native_str_rec |
| 50 | +from mig.shared.useradm import fill_user, \ |
| 51 | + create_user as useradm_create_user, search_users as useradm_search_users |
| 52 | +from mig.shared.userdb import default_db_path |
| 53 | + |
| 54 | + |
| 55 | +httpexceptions_by_code = { |
| 56 | + exc.code: exc for exc in httpexceptions.__dict__.values() if hasattr(exc, 'code')} |
| 57 | + |
| 58 | + |
| 59 | +def http_error_from_status_code(http_status_code, http_url, description=None): |
| 60 | + return httpexceptions_by_code[http_status_code](description) |
| 61 | + |
| 62 | + |
| 63 | +def _create_user(user_dict, conf_path, **kwargs): |
| 64 | + try: |
| 65 | + useradm_create_user(user_dict, conf_path, keyword_auto, **kwargs) |
| 66 | + except Exception as exc: |
| 67 | + return 1 |
| 68 | + return 0 |
| 69 | + |
| 70 | + |
| 71 | +def search_users(configuration, search_filter): |
| 72 | + _, hits = useradm_search_users(search_filter, configuration, keyword_auto) |
| 73 | + return list((obj for _, obj in hits)) |
| 74 | + |
| 75 | + |
| 76 | +def _create_and_expose_server(server, configuration): |
| 77 | + app = Flask('coreapi') |
| 78 | + |
| 79 | + @app.get('/user') |
| 80 | + def GET_user(): |
| 81 | + raise http_error_from_status_code(400, None) |
| 82 | + |
| 83 | + @app.get('/user/<username>') |
| 84 | + def GET_user_username(username): |
| 85 | + return 'FOOBAR' |
| 86 | + |
| 87 | + @app.get('/user/find') |
| 88 | + def GET_user_find(): |
| 89 | + query_params = request.args |
| 90 | + |
| 91 | + objects = search_users(configuration, { |
| 92 | + 'email': query_params['email'] |
| 93 | + }) |
| 94 | + |
| 95 | + if len(objects) != 1: |
| 96 | + raise http_error_from_status_code(404, None) |
| 97 | + |
| 98 | + return dict(objects=objects) |
| 99 | + |
| 100 | + @app.post('/user') |
| 101 | + def POST_user(): |
| 102 | + payload = request.get_json() |
| 103 | + |
| 104 | + try: |
| 105 | + validated = _REQUEST_ARGS_POST_USER.ensure(payload) |
| 106 | + except PayloadException as vr: |
| 107 | + return http_error_from_status_code(400, None, vr.serialize()) |
| 108 | + |
| 109 | + user_dict = canonical_user( |
| 110 | + configuration, validated, _REQUEST_ARGS_POST_USER._fields) |
| 111 | + fill_user(user_dict) |
| 112 | + force_native_str_rec(user_dict) |
| 113 | + |
| 114 | + ret = _create_user(user_dict, configuration, default_renew=True) |
| 115 | + if ret != 0: |
| 116 | + raise http_error_from_status_code(400, None) |
| 117 | + |
| 118 | + greeting = 'hello client!' |
| 119 | + return Response(greeting, 201) |
| 120 | + |
| 121 | + return app |
| 122 | + |
| 123 | + |
| 124 | +class ApiHttpServer(HTTPServer): |
| 125 | + """ |
| 126 | + http(s) server that contains a reference to an OpenID Server and |
| 127 | + knows its base URL. |
| 128 | + Extended to fork on requests to avoid one slow or broken login stalling |
| 129 | + the rest. |
| 130 | + """ |
| 131 | + |
| 132 | + def __init__(self, configuration, logger=None, host=None, port=None, **kwargs): |
| 133 | + self.configuration = configuration |
| 134 | + self.logger = logger if logger else configuration.logger |
| 135 | + self.server_app = None |
| 136 | + self._on_start = kwargs.pop('on_start', lambda _: None) |
| 137 | + |
| 138 | + addr = (host, port) |
| 139 | + HTTPServer.__init__(self, addr, ApiHttpRequestHandler, **kwargs) |
| 140 | + |
| 141 | + @property |
| 142 | + def base_environ(self): |
| 143 | + return {} |
| 144 | + |
| 145 | + def get_app(self): |
| 146 | + return self.server_app |
| 147 | + |
| 148 | + def server_activate(self): |
| 149 | + HTTPServer.server_activate(self) |
| 150 | + self._on_start(self) |
| 151 | + |
| 152 | + |
| 153 | +class ThreadedApiHttpServer(ThreadingMixIn, ApiHttpServer): |
| 154 | + """Multi-threaded version of the ApiHttpServer""" |
| 155 | + |
| 156 | + @property |
| 157 | + def base_url(self): |
| 158 | + proto = 'http' |
| 159 | + return '%s://%s:%d/' % (proto, self.server_name, self.server_port) |
| 160 | + |
| 161 | + |
| 162 | +class ApiHttpRequestHandler(WSGIRequestHandler): |
| 163 | + """TODO: docstring""" |
| 164 | + |
| 165 | + def __init__(self, socket, addr, server, **kwargs): |
| 166 | + self.server = server |
| 167 | + |
| 168 | + # NOTE: drop idle clients after N seconds to clean stale connections. |
| 169 | + # Does NOT include clients that connect and do nothing at all :-( |
| 170 | + self.timeout = 120 |
| 171 | + |
| 172 | + self._http_url = None |
| 173 | + self.parsed_uri = None |
| 174 | + self.path_parts = None |
| 175 | + self.retry_url = '' |
| 176 | + |
| 177 | + WSGIRequestHandler.__init__(self, socket, addr, server, **kwargs) |
| 178 | + |
| 179 | + @property |
| 180 | + def configuration(self): |
| 181 | + return self.server.configuration |
| 182 | + |
| 183 | + @property |
| 184 | + def daemon_conf(self): |
| 185 | + return self.server.configuration.daemon_conf |
| 186 | + |
| 187 | + @property |
| 188 | + def logger(self): |
| 189 | + return self.server.logger |
| 190 | + |
| 191 | + |
| 192 | +def start_service(configuration, host=None, port=None): |
| 193 | + assert host is not None, "required kwarg: host" |
| 194 | + assert port is not None, "required kwarg: port" |
| 195 | + |
| 196 | + logger = configuration.logger |
| 197 | + |
| 198 | + def _on_start(server, *args, **kwargs): |
| 199 | + server.server_app = _create_and_expose_server( |
| 200 | + None, server.configuration) |
| 201 | + |
| 202 | + httpserver = ThreadedApiHttpServer( |
| 203 | + configuration, host=host, port=port, on_start=_on_start) |
| 204 | + |
| 205 | + serve_msg = 'Server running at: %s' % httpserver.base_url |
| 206 | + logger.info(serve_msg) |
| 207 | + print(serve_msg) |
| 208 | + while True: |
| 209 | + logger.debug('handle next request') |
| 210 | + httpserver.handle_request() |
| 211 | + logger.debug('done handling request') |
| 212 | + httpserver.expire_volatile() |
| 213 | + |
| 214 | + |
| 215 | +def main(configuration=None): |
| 216 | + if not configuration: |
| 217 | + from mig.shared.conf import get_configuration_object |
| 218 | + # Force no log init since we use separate logger |
| 219 | + configuration = get_configuration_object(skip_log=True) |
| 220 | + |
| 221 | + logger = configuration.logger |
| 222 | + |
| 223 | + # Allow e.g. logrotate to force log re-open after rotates |
| 224 | + #register_hangup_handler(configuration) |
| 225 | + |
| 226 | + # FIXME: |
| 227 | + host = 'localhost' # configuration.user_openid_address |
| 228 | + port = 5555 # configuration.user_openid_port |
| 229 | + server_address = (host, port) |
| 230 | + |
| 231 | + info_msg = "Starting coreapi..." |
| 232 | + logger.info(info_msg) |
| 233 | + print(info_msg) |
| 234 | + |
| 235 | + try: |
| 236 | + start_service(configuration, host=host, port=port) |
| 237 | + except KeyboardInterrupt: |
| 238 | + info_msg = "Received user interrupt" |
| 239 | + logger.info(info_msg) |
| 240 | + print(info_msg) |
| 241 | + info_msg = "Leaving with no more workers active" |
| 242 | + logger.info(info_msg) |
| 243 | + print(info_msg) |
0 commit comments