source: ogAgent-Git/src/opengnsys/httpserver.py @ 0099a05

exec-ogbrowserlog-sess-lenmainoggit 5.1.1
Last change on this file since 0099a05 was 9af7469, checked in by Natalia Serrano <natalia.serrano@…>, 7 weeks ago

refs #1784 ignore module name in URLs

  • Property mode set to 100644
File size: 7.2 KB
RevLine 
[11f7a07]1# -*- coding: utf-8 -*-
2#
3# Copyright (c) 2015 Virtual Cable S.L.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without modification,
7# are permitted provided that the following conditions are met:
8#
9#    * Redistributions of source code must retain the above copyright notice,
10#      this list of conditions and the following disclaimer.
11#    * Redistributions in binary form must reproduce the above copyright notice,
12#      this list of conditions and the following disclaimer in the documentation
13#      and/or other materials provided with the distribution.
14#    * Neither the name of Virtual Cable S.L. nor the names of its contributors
15#      may be used to endorse or promote products derived from this software
16#      without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[2350389]28"""
[11f7a07]29@author: Adolfo Gómez, dkmaster at dkmon dot com
[2350389]30"""
[53e7d45]31
[11f7a07]32
[9af7469]33import os
[2350389]34import json
35import ssl
36import threading
[11f7a07]37from six.moves.socketserver import ThreadingMixIn  # @UnresolvedImport
38from six.moves.BaseHTTPServer import BaseHTTPRequestHandler  # @UnresolvedImport
39from six.moves.BaseHTTPServer import HTTPServer  # @UnresolvedImport
40from six.moves.urllib.parse import unquote  # @UnresolvedImport
41
42from .utils import exceptionToMessage
43from .certs import createSelfSignedCert
44from .log import logger
45
[e274dc0]46
[11f7a07]47class HTTPServerHandler(BaseHTTPRequestHandler):
48    service = None
49    protocol_version = 'HTTP/1.0'
50    server_version = 'OpenGnsys Agent Server'
51    sys_version = ''
52   
53    def sendJsonError(self, code, message):
54        self.send_response(code)
55        self.send_header('Content-type', 'application/json')
56        self.end_headers()
[e274dc0]57        self.wfile.write(str.encode(json.dumps({'error': message})))
[11f7a07]58        return
59
60    def sendJsonResponse(self, data):
[d7a7a1f]61        try: self.send_response(200)
[8c6a652]62        except Exception as e: logger.warn ('exception: "{}"'.format(str(e)))
[11f7a07]63        data = json.dumps(data)
64        self.send_header('Content-type', 'application/json')
[2350389]65        self.send_header('Content-Length', str(len(data)))
[11f7a07]66        self.end_headers()
67        # Send the html message
[e274dc0]68        self.wfile.write(str.encode(data))
69
[11f7a07]70    def parseUrl(self):
[e274dc0]71        """
72        Very simple path & params splitter
73        """
[11f7a07]74        path = self.path.split('?')[0][1:].split('/')
75       
76        try:
77            params = dict((v[0], unquote(v[1])) for v in (v.split('=') for v in self.path.split('?')[1].split('&')))
78        except Exception:
79            params = {}
80
[9af7469]81        ## quick override because universities do not actually want the module to be extracted out of the URL
82        module = 'ogAdmClient' if os.path.exists ('/scripts/oginit') else 'opengnsys'
83
[11f7a07]84        for v in self.service.modules:
[9af7469]85            if v.name == module:  # Case Sensitive!!!!
[e274dc0]86                return v, path[1:], params
[11f7a07]87           
[e274dc0]88        return None, path, params
[11f7a07]89   
[2350389]90    def notifyMessage(self, module, path, get_params, post_params):
[e274dc0]91        """
[11f7a07]92        Locates witch module will process the message based on path (first folder on url path)
[e274dc0]93        """
[11f7a07]94        try:
[8a36992]95            if module is None:
96                raise Exception ({ '_httpcode': 404, '_msg': f'Module {path[0]} not found' })
[2350389]97            data = module.processServerMessage(path, get_params, post_params, self)
[11f7a07]98            self.sendJsonResponse(data)
99        except Exception as e:
100            logger.exception()
[5b058a5]101            n_args = len (e.args)
102            if 0 == n_args:
[1fdeb2a]103                logger.debug ('Empty exception raised from message processor for "{}"'.format(path[0]))
[5b058a5]104                self.sendJsonError(500, exceptionToMessage(e))
105            else:
106                arg0 = e.args[0]
107                if type (arg0) is str:
[1fdeb2a]108                    logger.debug ('Message processor for "{}" returned exception string "{}"'.format(path[0], str(e)))
[5b058a5]109                    self.sendJsonError (500, exceptionToMessage(e))
110                elif type (arg0) is dict:
111                    if '_httpcode' in arg0:
[1fdeb2a]112                        logger.debug ('Message processor for "{}" returned HTTP code "{}" with exception string "{}"'.format(path[0], str(arg0['_httpcode']), str(arg0['_msg'])))
[5b058a5]113                        self.sendJsonError (arg0['_httpcode'], arg0['_msg'])
114                    else:
[1fdeb2a]115                        logger.debug ('Message processor for "{}" returned exception dict "{}" with no HTTP code'.format(path[0], str(e)))
[5b058a5]116                        self.sendJsonError (500, exceptionToMessage(e))
117                else:
[1fdeb2a]118                    logger.debug ('Message processor for "{}" returned non-string and non-dict exception "{}", type "{}"'.format(path[0], str(e), type(e)))
[5b058a5]119                    self.sendJsonError (500, exceptionToMessage(e))
120            ## not reached
[11f7a07]121           
122    def do_GET(self):
123        module, path, params = self.parseUrl()
124       
125        self.notifyMessage(module, path, params, None)
126       
127    def do_POST(self):
[2350389]128        module, path, get_params = self.parseUrl()
129        post_params = None
[11f7a07]130
[b0b6500]131        # Tries to get JSON content (UTF-8 encoded)
[11f7a07]132        try:
[2350389]133            length = int(self.headers.get('content-length'))
[b0b6500]134            content = self.rfile.read(length).decode('utf-8')
[2350389]135            logger.debug('length: {0}, content >>{1}<<'.format(length, content))
136            post_params = json.loads(content)
[11f7a07]137        except Exception as e:
138            self.sendJsonError(500, exceptionToMessage(e))
139           
[2350389]140        self.notifyMessage(module, path, get_params, post_params)
[11f7a07]141
142    def log_error(self, fmt, *args):
143        logger.error('HTTP ' + fmt % args)
144       
145    def log_message(self, fmt, *args):
[10fab78]146        logger.debug('HTTP ' + fmt % args)
[11f7a07]147       
148
149class HTTPThreadingServer(ThreadingMixIn, HTTPServer):
150    pass
151
[e274dc0]152
[11f7a07]153class HTTPServerThread(threading.Thread):
154    def __init__(self, address, service):
155        super(self.__class__, self).__init__()
156
157        HTTPServerHandler.service = service  # Keep tracking of service so we can intercact with it
158
159        self.certFile = createSelfSignedCert()
160        self.server = HTTPThreadingServer(address, HTTPServerHandler)
[d7a7a1f]161        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
162        context.load_cert_chain(certfile=self.certFile)
163        self.server.socket = context.wrap_socket(self.server.socket, server_side=True)
[11f7a07]164       
165        logger.debug('Initialized HTTPS Server thread on {}'.format(address))
166
167    def getServerUrl(self):
168        return 'https://{}:{}/'.format(self.server.server_address[0], self.server.server_address[1])
169
170    def stop(self):
171        self.server.shutdown()
172
173    def run(self):
174        self.server.serve_forever()
Note: See TracBrowser for help on using the repository browser.