예제 #1
0
def start():
  log = logging.getLogger('Rocket')
  log.addHandler(logging.FileHandler('server.log'))

  session_opts = {
    'session.data_dir'  : '/tmp/fmk/data',
    'session.lock_dir'  : '/tmp/fmk/lock',
    'session.type'  : 'redis',
    'session.url'   : '127.0.0.1:6379?db=3'
  }

  app = Dispatcher(mapfile='rest.map', wrap=Request)
  app = Session(app, session_opts)

  server = Server(
      interfaces=('127.0.0.1', 9000),
      method='wsgi',
      app_info=dict(wsgi_app=app),
      min_threads=64,
      max_threads=128,
      timeout=60
  )
  
  try:
    print 'starting wsgi server...'
    server.start()
  except KeyboardInterrupt:
    server.stop()
  except Exception as e:
    print type(e)
    print e.args, e
    server.stop()
예제 #2
0
def run_server():
    log = logging.getLogger('Rocket')
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler(sys.stdout))
    server = Rocket(interfaces=('0.0.0.0', 5000),
                    method='wsgi',
                    app_info={"wsgi_app": app})
    server.start()
예제 #3
0
파일: logger.py 프로젝트: sujalpatel92/ccl5
def run_server():
    global platform_log
    if print_debug:
        print("Starting iotplatform")
    server = Rocket(
        interfaces = ('0.0.0.0', 8005),
        method = 'wsgi',
        app_info = {'wsgi_app': app})
    server.start()
    platform_log.info("Started Server")
예제 #4
0
def run_server():
    # Setup logging
    log = logging.getLogger('Rocket')
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler(sys.stdout))

    # Set the configuration of the web server
    server = Rocket(interfaces=('0.0.0.0', 5000), method='wsgi',
                    app_info={"wsgi_app": app})

    # Start the Rocket web server
    server.start()
예제 #5
0
def rocket_http(debug=False):
    # Setup logging
    log = logging.getLogger('Rocket')
    log.setLevel(logging.INFO)
    if debug:
       log.addHandler(logging.StreamHandler(sys.stdout))
    else:
       log.addHandler(logging.FileHandler('http.log'))

    # Set the configuration of the web server
    server = Rocket(interfaces=('0.0.0.0', 8010, 'ssl/server.key', 'ssl/server.crt'), method='wsgi', app_info={"wsgi_app": app})
    server.start(background=True)
예제 #6
0
def rocket_http(debug=False):
    # Setup logging
    log = logging.getLogger('Rocket')
    log.setLevel(logging.INFO)
    if debug:
        log.addHandler(logging.StreamHandler(sys.stdout))
    else:
        log.addHandler(logging.FileHandler('http.log'))

    # Set the configuration of the web server
    server = Rocket(interfaces=('0.0.0.0', 8010, 'ssl/server.key',
                                'ssl/server.crt'),
                    method='wsgi',
                    app_info={"wsgi_app": app})
    server.start(background=True)
예제 #7
0
파일: webserver.py 프로젝트: P-Product/err
 def run_webserver(self):
     #noinspection PyBroadException
     try:
         host = self.config['HOST']
         port = self.config['PORT']
         ssl = self.config['SSL']
         interfaces = [(host, port)]
         if ssl['enabled']:
             interfaces.append((ssl['host'], ssl['port'], ssl['key'], ssl['certificate']))
         logging.info('Firing up the Rocket')
         rocket = Rocket(interfaces=interfaces,
                         app_info={'wsgi_app': bottle_app}, )
         rocket.start()
         logging.debug('Rocket has landed')
     except KeyboardInterrupt as _:
         logging.exception('Keyboard interrupt, request a global shutdown.')
         holder.bot.shutdown()
     except Exception as _:
         logging.exception('The Rocket has exploded.')
         self.warn_admins("There's an issue with the Rocket: %s" % _)
예제 #8
0
파일: webserver.py 프로젝트: garmann/errbot
class Webserver(BotPlugin):

    def __init__(self, *args, **kwargs):
        self.webserver = None
        self.webchat_mode = False
        self.ssl_context = None
        self.test_app = TestApp(bottle_app)
        super().__init__(*args, **kwargs)

    def get_configuration_template(self):
        return {'HOST': '0.0.0.0',
                'PORT': 3141,
                'SSL': {'enabled': False,
                        'host': '0.0.0.0',
                        'port': 3142,
                        'certificate': "",
                        'key': ""}}

    def check_configuration(self, configuration):
        # it is a pain, just assume a default config if SSL is absent or set to None
        if configuration.get('SSL', None) is None:
            configuration['SSL'] = {'enabled': False, 'host': '0.0.0.0', 'port': 3142, 'certificate': "", 'key': ""}
        super().check_configuration(configuration)

    def activate(self):
        if not self.config:
            self.log.info('Webserver is not configured. Forbid activation')
            return

        host = self.config['HOST']
        port = self.config['PORT']
        ssl = self.config['SSL']
        interfaces = [(host, port)]
        if ssl['enabled']:
            # noinspection PyTypeChecker
            interfaces.append((ssl['host'], ssl['port'], ssl['key'], ssl['certificate']))
        self.log.info('Firing up the Rocket')
        self.webserver = Rocket(interfaces=interfaces,
                                app_info={'wsgi_app': bottle_app}, )
        self.webserver.start(background=True)
        self.log.debug('Liftoff!')

        super().activate()

    def deactivate(self):
        if self.webserver is not None:
            self.log.debug('Sending signal to stop the webserver')
            self.webserver.stop()
        super().deactivate()

    # noinspection PyUnusedLocal
    @botcmd(template='webstatus')
    def webstatus(self, mess, args):
        """
        Gives a quick status of what is mapped in the internal webserver
        """
        return {'rules': (((route.rule, route.name) for route in bottle_app.routes))}

    @webhook
    def echo(self, incoming_request):
        """
        A simple test webhook
        """
        self.log.debug("Your incoming request is :" + str(incoming_request))
        return str(incoming_request)

    @botcmd(split_args_with=' ')
    def webhook_test(self, _, args):
        """
            Test your webhooks from within err.

        The syntax is :
        !webhook test [relative_url] [post content]

        It triggers the notification and generate also a little test report.
        """
        url = args[0]
        content = ' '.join(args[1:])

        # try to guess the content-type of what has been passed
        try:
            # try if it is plain json
            loads(content)
            contenttype = 'application/json'
        except ValueError:
            # try if it is a form
            splitted = content.split('=')
            # noinspection PyBroadException
            try:
                payload = '='.join(splitted[1:])
                loads(unquote(payload))
                contenttype = 'application/x-www-form-urlencoded'
            except Exception as _:
                contenttype = 'text/plain'  # dunno what it is

        self.log.debug('Detected your post as : %s' % contenttype)

        response = self.test_app.post(url, params=content, content_type=contenttype)
        return TEST_REPORT % (url, contenttype, response.status_code)

    @botcmd(admin_only=True)
    def generate_certificate(self, mess, args):
        """
        Generate a self-signed SSL certificate for the Webserver
        """
        if not has_crypto:
            yield ("It looks like pyOpenSSL isn't installed. Please install this "
                   "package using for example `pip install pyOpenSSL`, then try again")
            return

        yield ("Generating a new private key and certificate. This could take a "
               "while if your system is slow or low on entropy")
        key_path = os.sep.join((self.bot_config.BOT_DATA_DIR, "webserver_key.pem"))
        cert_path = os.sep.join((self.bot_config.BOT_DATA_DIR, "webserver_certificate.pem"))
        make_ssl_certificate(key_path=key_path, cert_path=cert_path)
        yield "Certificate successfully generated and saved in {}".format(self.bot_config.BOT_DATA_DIR)

        suggested_config = self.config
        suggested_config['SSL']['enabled'] = True
        suggested_config['SSL']['host'] = suggested_config['HOST']
        suggested_config['SSL']['port'] = suggested_config['PORT'] + 1
        suggested_config['SSL']['key'] = key_path
        suggested_config['SSL']['certificate'] = cert_path
        yield ("To enable SSL with this certificate, the following config "
               "is recommended:")
        yield "{!r}".format(suggested_config)
예제 #9
0
def run_server():
	server = Rocket(
		interfaces = ('0.0.0.0', 9200),
		method = 'wsgi',
		app_info = {'wsgi_app': app})
	server.start()
예제 #10
0
                path_info = MAP_FILES[path_info]
            if path_info in FILES:
                content_type = FILES[path_info]
                path_info = os.path.join(os.getcwd(), path_info.strip("/"))
                f = open(path_info, "r")
                http_content = substitue_content(f.read())
                if "$$$MODULE_CONTENT$$$" in http_content:
                    http_content = insert_modules(http_content)
    except:
        traceback.print_exc()

    headers = [('Content-type', content_type)]
    start_response(status, headers)
    return http_content


my_demo = {"wsgi_app": my_simple_app}

if __name__ == '__main__':
    log = logging.getLogger('Rocket.Requests')
    log.setLevel(logging.INFO)
    fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
    h = logging.StreamHandler()
    h.setFormatter(fmt)
    log.addHandler(h)

    r = Rocket(interfaces=[('127.0.0.1', 8000), ('::1', 8000)],
               method='wsgi',
               app_info=my_demo)
    r.start()
예제 #11
0
class FlaskWebThread(threading.Thread):
    def __init__(self, queues, port, username, password):
        self.credentials = [{"username": username, "password": password}]
        self.app = Flask(__name__,
                         static_folder='static',
                         static_path='/static',
                         static_url_path='/static')
        self.app.debug = False
        self.authHelper = authenticator(self.credentials)
        self.cmd_q = queues['in']
        self.reply_q = queues['out']
        self.logger = logging.getLogger('app')
        self.host = '0.0.0.0'
        self.port = port
        self.shutdown_pass = self.random_string()
        self.server = None

        rocketlog = logging.getLogger('Rocket')
        rocketlog.setLevel(logging.INFO)

        super(FlaskWebThread, self).__init__()

    def random_string(self):
        return ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(50))

    def admin(self):
        return render_template('admin.html')

    def sense(self):
        self.logger.debug("Got sense command")
        return self.status()

    def status(self):
        self.logger.debug("Got status command")
        command = interlockcommands.ReadState()
        response = self.sendCommand(command)
        if self.is_json():
            status = self.interpret_response(response.data)
            buffer = json.dumps({"status": status})
        else:
            buffer = render_template('status.html',
                                     data=print_bytes(response.data),
                                     cmd='status')
        return buffer

    def enable(self, data):
        shutdowns = data.get('shutdowns', 0)
        shutdowns = int(shutdowns)
        problems = data.get('problems', 0)
        problems = int(problems)

        self.logger.debug("Got enable command, %s shutdowns, %s problems" %
                          (shutdowns, problems))
        if shutdowns > 0:
            #command = interlockcommands.EnterState(9) #only available if keyswitch is turned
            command = interlockcommands.EnterState(4)
        elif problems > 0:
            command = interlockcommands.EnterState(4)
        else:
            command = interlockcommands.EnterState(2)

        response = self.sendCommand(command)
        if self.is_json():
            buffer = json.dumps({"status": "unlocked"})
        else:
            buffer = render_template('enable.html',
                                     data=print_bytes(response.data),
                                     cmd='enable')
        return buffer

    def disable(self, data):
        shutdowns = data.get('shutdowns', 0)
        shutdowns = int(shutdowns)
        problems = data.get('problems', 0)
        problems = int(problems)
        self.logger.debug("Got disable command, %s shutdowns, %s problems" %
                          (shutdowns, problems))
        if shutdowns > 0:
            command = interlockcommands.EnterState(8)
        elif problems > 0:
            command = interlockcommands.EnterState(3)
        else:
            command = interlockcommands.EnterState(1)

        response = self.sendCommand(command)
        if self.is_json():
            buffer = json.dumps({"status": "locked"})
        else:
            buffer = render_template('enable.html',
                                     data=print_bytes(response.data),
                                     cmd='disable')
        return buffer

    def proxy(self, data):
        #verify
        shutdowns = data.get('shutdowns', 0)
        shutdowns = int(shutdowns)
        problems = data.get('problems', 0)
        problems = int(problems)
        scheme = data.get('scheme', 'http')
        host = data['host']
        port = data['port']
        username = data.get('username', self.credentials[0]['username'])
        password = data.get(
            'password', self.credentials[0]['password']
        )  #since this method requires authentication, this should be okay
        command = data['command']

        if command not in [
                "status", "sense", "enable", "disable", "unlock", "lock"
        ]:
            return Response(
                '{"status": "error", "message": "no such command"}', 404)

        if scheme not in ["http", "https"]:
            return Response('{"status": "error", "message": "no such scheme"}',
                            404)

        headers = {'Content-type': 'application/json'}
        json_data = {"shutdowns": shutdowns, "problems": problems}
        url = '%s://%s:%s/%s' % (scheme, host, port, command)
        auth = HTTPBasicAuth(username, password)
        self.logger.debug("Proxying request: %s, %s, %s, %s" %
                          (url, command, shutdowns, problems))
        response = requests.post(url,
                                 data=json_data,
                                 headers=headers,
                                 auth=auth)
        self.logger.debug("Got response code %s " % response.status_code)
        return Response(response.text, response.status_code)

    def is_json(self):
        self.logger.debug("IS JSON?")
        self.logger.debug("Accept header: " +
                          request.headers.get("Accept", ""))
        self.logger.debug("Content-Type header: " +
                          request.headers.get("Content-Type", ""))
        json = False

        if request.headers.get('Content-Type', False) == 'application/json' or \
            request.headers.get('Accept', False) == 'application/json':
            json = True
        return json

    def run(self):
        self.setupRoutes()
        self.logger.debug('Flask Server Starting')
        self.server = Rocket((self.host, self.port), 'wsgi',
                             {"wsgi_app": self.app})
        self.server.start(background=False)
        #self.app.run(host=self.host, port=self.port)
        self.logger.debug('Flask Server Stopping')

    def setupRoutes(self):
        @self.app.route('/admin', methods=['GET', 'POST'])
        @self.authHelper.requires_auth
        def admin():
            return self.admin()

        @self.app.route('/sense', methods=['GET', 'POST'])
        @self.authHelper.requires_auth
        def sense():
            return self.sense()

        @self.app.route('/status', methods=['GET', 'POST'])
        @self.authHelper.requires_auth
        def status():
            return self.status()

        @self.app.route('/enable', methods=['POST'])
        @self.authHelper.requires_auth
        def enable():
            return self.enable(request.form)

        @self.app.route('/disable', methods=['POST'])
        @self.authHelper.requires_auth
        def disable():
            return self.disable(request.form)

        @self.app.route('/unlock', methods=['POST'])
        @self.authHelper.requires_auth
        def unlock_to_enable():
            return self.enable(request.form)

        @self.app.route('/lock', methods=['POST'])
        @self.authHelper.requires_auth
        def log_to_disable():
            return self.disable(request.form)

        @self.app.route('/static', methods=['GET'])
        @self.app.route('/static/', methods=['GET'])
        @self.app.route('/', methods=['GET'])
        def serve_static_index():
            self.logger.debug('static asset')
            return self.app.send_static_file('index.html')

        @self.app.route('/swagger.yaml', methods=['GET'])
        def swagger():
            self.logger.debug('swagger yaml')
            buffer = render_template('swagger.yaml', host=request.host)
            return buffer

        @self.app.route('/proxy', methods=['POST'])
        @self.authHelper.requires_auth
        def proxy():
            return self.proxy(request.get_json())

        @self.app.route('/shutdown/<shutdown_pass>', methods=['POST'])
        def shutdown(shutdown_pass):
            if shutdown_pass == self.shutdown_pass:
                func = request.environ.get('werkzeug.server.shutdown')
                if func is None:
                    raise RuntimeError('Not running with the Werkzeug Server')
                func()
                return "Shutting down..."
            else:
                return ""

    def sendCommand(self, command):
        self.cmd_q.put(command)
        response = self.reply_q.get(True, 5)
        if response.type == ClientReply.ERROR:
            self.logger.error("ERROR response is : %s" %
                              pprint.pformat(response))
            raise Exception('Error response from interlock box: %s' %
                            response.data)
        self.logger.debug("response is : %s" % pprint.pformat(response))
        return response

    def shutdown_flask(self):
        requests.post('http://localhost:' + str(self.port) + '/shutdown/' +
                      self.shutdown_pass)

    def join(self):
        self.logger.debug("shutting down")
        self.server.stop()
        #self.shutdown_flask()
        self.logger.debug("shutdown request sent")
        threading.Thread.join(self)

    def interpret_response(self, data):
        unlocked_states = [2, 4, 5, 9]
        locked_states = [1, 3, 7, 8]
        if len(data) == 2 and data[0] == 85:
            if data[1] in unlocked_states:
                return "unlocked"
            elif data[1] in locked_states:
                return "locked"
            else:
                return "unknown"
        else:
            return "unknown"
예제 #12
0
class Webserver(BotPlugin):

    def __init__(self, *args, **kwargs):
        self.webserver = None
        self.webchat_mode = False
        self.ssl_context = None
        self.test_app = TestApp(bottle_app)
        super().__init__(*args, **kwargs)

    def get_configuration_template(self):
        return {'HOST': '0.0.0.0',
                'PORT': 3141,
                'SSL': {'enabled': False,
                        'host': '0.0.0.0',
                        'port': 3142,
                        'certificate': "",
                        'key': ""}}

    def check_configuration(self, configuration):
        # it is a pain, just assume a default config if SSL is absent or set to None
        if configuration.get('SSL', None) is None:
            configuration['SSL'] = {'enabled': False, 'host': '0.0.0.0', 'port': 3142, 'certificate': "", 'key': ""}
        super().check_configuration(configuration)

    def activate(self):
        if not self.config:
            self.log.info('Webserver is not configured. Forbid activation')
            return

        host = self.config['HOST']
        port = self.config['PORT']
        ssl = self.config['SSL']
        interfaces = [(host, port)]
        if ssl['enabled']:
            # noinspection PyTypeChecker
            interfaces.append((ssl['host'], ssl['port'], ssl['key'], ssl['certificate']))
        self.log.info('Firing up the Rocket')
        self.webserver = Rocket(interfaces=interfaces,
                                app_info={'wsgi_app': bottle_app}, )
        self.webserver.start(background=True)
        self.log.debug('Liftoff!')

        super().activate()

    def deactivate(self):
        if self.webserver is not None:
            self.log.debug('Sending signal to stop the webserver')
            self.webserver.stop()
        super().deactivate()

    # noinspection PyUnusedLocal
    @botcmd(template='webstatus')
    def webstatus(self, msg, args):
        """
        Gives a quick status of what is mapped in the internal webserver
        """
        return {'rules': (((route.rule, route.name) for route in bottle_app.routes))}

    @webhook
    def echo(self, incoming_request):
        """
        A simple test webhook
        """
        self.log.debug("Your incoming request is :" + str(incoming_request))
        return str(incoming_request)

    @botcmd(split_args_with=' ')
    def webhook_test(self, _, args):
        """
            Test your webhooks from within err.

        The syntax is :
        !webhook test [relative_url] [post content]

        It triggers the notification and generate also a little test report.
        """
        url = args[0]
        content = ' '.join(args[1:])

        # try to guess the content-type of what has been passed
        try:
            # try if it is plain json
            loads(content)
            contenttype = 'application/json'
        except ValueError:
            # try if it is a form
            splitted = content.split('=')
            # noinspection PyBroadException
            try:
                payload = '='.join(splitted[1:])
                loads(unquote(payload))
                contenttype = 'application/x-www-form-urlencoded'
            except Exception as _:
                contenttype = 'text/plain'  # dunno what it is

        self.log.debug('Detected your post as : %s' % contenttype)

        response = self.test_app.post(url, params=content, content_type=contenttype)
        return TEST_REPORT % (url, contenttype, response.status_code)

    @botcmd(admin_only=True)
    def generate_certificate(self, _, args):
        """
        Generate a self-signed SSL certificate for the Webserver
        """
        if not has_crypto:
            yield ("It looks like pyOpenSSL isn't installed. Please install this "
                   "package using for example `pip install pyOpenSSL`, then try again")
            return

        yield ("Generating a new private key and certificate. This could take a "
               "while if your system is slow or low on entropy")
        key_path = os.sep.join((self.bot_config.BOT_DATA_DIR, "webserver_key.pem"))
        cert_path = os.sep.join((self.bot_config.BOT_DATA_DIR, "webserver_certificate.pem"))
        make_ssl_certificate(key_path=key_path, cert_path=cert_path)
        yield "Certificate successfully generated and saved in {}".format(self.bot_config.BOT_DATA_DIR)

        suggested_config = self.config
        suggested_config['SSL']['enabled'] = True
        suggested_config['SSL']['host'] = suggested_config['HOST']
        suggested_config['SSL']['port'] = suggested_config['PORT'] + 1
        suggested_config['SSL']['key'] = key_path
        suggested_config['SSL']['certificate'] = cert_path
        yield ("To enable SSL with this certificate, the following config "
               "is recommended:")
        yield "{!r}".format(suggested_config)
예제 #13
0
 def run(self, handler):
     from rocket import Rocket
     server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
     server.start()
예제 #14
0
class Webserver(BotPlugin):
    min_err_version = VERSION  # don't copy paste that for your plugin, it is just because it is a bundled plugin !
    max_err_version = VERSION

    def __init__(self):
        self.webserver = None
        self.webchat_mode = False
        self.ssl_context = None
        self.test_app = TestApp(bottle_app)
        super(Webserver, self).__init__()

    def get_configuration_template(self):
        return {'HOST': '0.0.0.0',
                'PORT': 3141,
                'SSL': {'enabled': False,
                        'host': '0.0.0.0',
                        'port': 3142,
                        'certificate': "",
                        'key': ""}}

    def check_configuration(self, configuration):
        # it is a pain, just assume a default config if SSL is absent or set to None
        if configuration.get('SSL', None) is None:
            configuration['SSL'] = {'enabled': False, 'host': '0.0.0.0', 'port': 3142, 'certificate': "", 'key': ""}
        super(Webserver, self).check_configuration(configuration)

    def activate(self):
        if not self.config:
            logging.info('Webserver is not configured. Forbid activation')
            return

        host = self.config['HOST']
        port = self.config['PORT']
        ssl = self.config['SSL']
        interfaces = [(host, port)]
        if ssl['enabled']:
            interfaces.append((ssl['host'], ssl['port'], ssl['key'], ssl['certificate']))
        logging.info('Firing up the Rocket')
        self.webserver = Rocket(interfaces=interfaces,
                                app_info={'wsgi_app': bottle_app}, )
        self.webserver.start(background=True)
        logging.debug('Liftoff!')

        super(Webserver, self).activate()
        logging.info('Webserver activated')

    def deactivate(self):
        if self.webserver is not None:
            logging.debug('Sending signal to stop the webserver')
            self.webserver.stop()
        super(Webserver, self).deactivate()

    #noinspection PyUnusedLocal
    @botcmd(template='webstatus')
    def webstatus(self, mess, args):
        """
        Gives a quick status of what is mapped in the internal webserver
        """
        return {'rules': (((route.rule, route.name) for route in bottle_app.routes))}

    @webhook
    def echo(self, incoming_request):
        """
        A simple test webhook
        """
        logging.debug("Your incoming request is :" + str(incoming_request))
        return str(incoming_request)

    @botcmd(split_args_with=' ')
    def webhook_test(self, _, args):
        """
            Test your webhooks from within err.

        The syntax is :
        !webhook test [relative_url] [post content]

        It triggers the notification and generate also a little test report.
        """
        url = args[0] if PY3 else args[0].encode()  # PY2 needs a str not unicode
        content = ' '.join(args[1:])

        # try to guess the content-type of what has been passed
        try:
            # try if it is plain json
            loads(content)
            contenttype = 'application/json'
        except ValueError:
            # try if it is a form
            splitted = content.split('=')
            #noinspection PyBroadException
            try:
                payload = '='.join(splitted[1:])
                loads(unquote(payload))
                contenttype = 'application/x-www-form-urlencoded'
            except Exception as _:
                contenttype = 'text/plain'  # dunno what it is

        logging.debug('Detected your post as : %s' % contenttype)

        response = self.test_app.post(url, params=content, content_type=contenttype)
        return TEST_REPORT % (url, contenttype, response.status_code)
class FlaskProxyWebThread(threading.Thread):
    def __init__(self, queues, port, username, password):
        self.credentials = [{"username": username, "password": password}]
        self.app = Flask(__name__,
                         static_folder='static',
                         static_path='/static',
                         static_url_path='/static')
        self.app.debug = False
        self.authHelper = authenticator(self.credentials)
        self.cmd_q = queues['in']
        self.reply_q = queues['out']
        self.logger = logging.getLogger('app')
        self.host = '0.0.0.0'
        self.port = port
        self.shutdown_pass = self.random_string()
        self.server = None

        rocketlog = logging.getLogger('Rocket')
        rocketlog.setLevel(logging.INFO)

        super(FlaskProxyWebThread, self).__init__()

    def random_string(self):
        return ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(50))

    def proxy(self, data):
        #verify
        shutdowns = data.get('shutdowns', 0)
        shutdowns = int(shutdowns)
        problems = data.get('problems', 0)
        problems = int(problems)
        scheme = data.get('scheme', 'http')
        host = data['host']
        port = data['port']
        username = data.get('username', self.credentials[0]['username'])
        password = data.get(
            'password', self.credentials[0]['password']
        )  #since this method requires authentication, this should be okay
        command = data['command']

        if command not in [
                "status", "sense", "enable", "disable", "unlock", "lock"
        ]:
            return Response(
                '{"status": "error", "message": "no such command"}', 404)

        if scheme not in ["http", "https"]:
            return Response('{"status": "error", "message": "no such scheme"}',
                            404)

        headers = {'Content-type': 'application/json'}
        json_data = {"shutdowns": shutdowns, "problems": problems}
        url = '%s://%s:%s/%s' % (scheme, host, port, command)
        auth = HTTPBasicAuth(username, password)
        self.logger.debug("Proxying request: %s, %s, %s, %s" %
                          (url, command, shutdowns, problems))
        response = requests.post(url,
                                 data=json_data,
                                 headers=headers,
                                 auth=auth)
        self.logger.debug("Got response code %s " % response.status_code)
        return Response(response.text, response.status_code)

    def is_json(self):
        self.logger.debug("IS JSON?")
        self.logger.debug("Accept header: " +
                          request.headers.get("Accept", ""))
        self.logger.debug("Content-Type header: " +
                          request.headers.get("Content-Type", ""))
        json = False

        if request.headers.get('Content-Type', False) == 'application/json' or \
            request.headers.get('Accept', False) == 'application/json':
            json = True
        return json

    def run(self):
        self.setupRoutes()
        self.logger.debug('Flask Proxy Server Starting')
        self.server = Rocket((self.host, self.port), 'wsgi',
                             {"wsgi_app": self.app})
        self.server.start(background=False)
        #self.app.run(host=self.host, port=self.port)
        self.logger.debug('Flask Server Stopping')

    def setupRoutes(self):
        @self.app.route('/static', methods=['GET'])
        @self.app.route('/static/', methods=['GET'])
        @self.app.route('/', methods=['GET'])
        def serve_static_index():
            self.logger.debug('static asset')
            return self.app.send_static_file('index.html')

        @self.app.route('/swagger.yaml', methods=['GET'])
        def swagger():
            self.logger.debug('swagger yaml')
            buffer = render_template('swaggerProxy.yaml', host=request.host)
            return buffer

        @self.app.route('/proxy', methods=['POST'])
        @self.authHelper.requires_auth
        def proxy():
            return self.proxy(request.get_json())

        @self.app.route('/shutdown/<shutdown_pass>', methods=['POST'])
        def shutdown(shutdown_pass):
            if shutdown_pass == self.shutdown_pass:
                func = request.environ.get('werkzeug.server.shutdown')
                if func is None:
                    raise RuntimeError('Not running with the Werkzeug Server')
                func()
                return "Shutting down..."
            else:
                return ""

    def shutdown_flask(self):
        requests.post('http://localhost:' + str(self.port) + '/shutdown/' +
                      self.shutdown_pass)

    def join(self):
        self.logger.debug("shutting down")
        self.server.stop()
        self.logger.debug("shutdown request sent")
        threading.Thread.join(self)
예제 #16
0
    def __init__(self, root):
        super(RedfishServer, self).__init__(autojson=False)
        self.redfish_root = root
        self.create_handlers()
        self.install_handlers()

    def create_handlers(self):
        self.get_request_handler = GetRequestHandler(self, self.redfish_root)

    def install_handlers(self):
        self.get_request_handler.install()


if __name__ == '__main__':
    log = logging.getLogger('Rocket.Errors')
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler(sys.stdout))
    redfish_root = RedfishBottleRoot()

    app = RedfishServer(redfish_root)
    default_cert = os.path.join(
        sys.prefix, 'share', os.path.basename(__file__), 'cert.pem')

    server = Rocket(
        ('0.0.0.0', 8080, default_cert, default_cert),
        'wsgi', {'wsgi_app': app},
        min_threads=1,
        max_threads=1)
    print "Starting Server"
    server.start()
예제 #17
0
class Webserver(BotPlugin):
    min_err_version = VERSION  # don't copy paste that for your plugin, it is just because it is a bundled plugin !
    max_err_version = VERSION

    def __init__(self):
        self.webserver = None
        self.webchat_mode = False
        self.ssl_context = None
        self.test_app = TestApp(bottle_app)
        super(Webserver, self).__init__()

    def get_configuration_template(self):
        return {
            'HOST': '0.0.0.0',
            'PORT': 3141,
            'SSL': {
                'enabled': False,
                'host': '0.0.0.0',
                'port': 3142,
                'certificate': "",
                'key': ""
            }
        }

    def check_configuration(self, configuration):
        # it is a pain, just assume a default config if SSL is absent or set to None
        if configuration.get('SSL', None) is None:
            configuration['SSL'] = {
                'enabled': False,
                'host': '0.0.0.0',
                'port': 3142,
                'certificate': "",
                'key': ""
            }
        super(Webserver, self).check_configuration(configuration)

    def activate(self):
        if not self.config:
            logging.info('Webserver is not configured. Forbid activation')
            return

        host = self.config['HOST']
        port = self.config['PORT']
        ssl = self.config['SSL']
        interfaces = [(host, port)]
        if ssl['enabled']:
            interfaces.append(
                (ssl['host'], ssl['port'], ssl['key'], ssl['certificate']))
        logging.info('Firing up the Rocket')
        self.webserver = Rocket(
            interfaces=interfaces,
            app_info={'wsgi_app': bottle_app},
        )
        self.webserver.start(background=True)
        logging.debug('Liftoff!')

        super(Webserver, self).activate()
        logging.info('Webserver activated')

    def deactivate(self):
        if self.webserver is not None:
            logging.debug('Sending signal to stop the webserver')
            self.webserver.stop()
        super(Webserver, self).deactivate()

    #noinspection PyUnusedLocal
    @botcmd(template='webstatus')
    def webstatus(self, mess, args):
        """
        Gives a quick status of what is mapped in the internal webserver
        """
        return {
            'rules':
            (((route.rule, route.name) for route in bottle_app.routes))
        }

    @webhook
    def echo(self, incoming_request):
        """
        A simple test webhook
        """
        logging.debug("Your incoming request is :" + str(incoming_request))
        return str(incoming_request)

    @botcmd(split_args_with=' ')
    def webhook_test(self, _, args):
        """
            Test your webhooks from within err.

        The syntax is :
        !webhook test [relative_url] [post content]

        It triggers the notification and generate also a little test report.
        """
        url = args[0] if PY3 else args[0].encode(
        )  # PY2 needs a str not unicode
        content = ' '.join(args[1:])

        # try to guess the content-type of what has been passed
        try:
            # try if it is plain json
            loads(content)
            contenttype = 'application/json'
        except ValueError:
            # try if it is a form
            splitted = content.split('=')
            #noinspection PyBroadException
            try:
                payload = '='.join(splitted[1:])
                loads(unquote(payload))
                contenttype = 'application/x-www-form-urlencoded'
            except Exception as _:
                contenttype = 'text/plain'  # dunno what it is

        logging.debug('Detected your post as : %s' % contenttype)

        response = self.test_app.post(url,
                                      params=content,
                                      content_type=contenttype)
        return TEST_REPORT % (url, contenttype, response.status_code)
예제 #18
0
class ConnectionTest(unittest.TestCase):
    def setUp(self):
        global SERVER_PORT_START

        SERVER_PORT_START += 1
        self.starttuple = ('127.0.0.1', SERVER_PORT_START)

        #log = logging.getLogger('Rocket')
        #log.setLevel(logging.DEBUG)
        #fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
        #h = logging.StreamHandler()
        #h.setFormatter(fmt)
        #log.addHandler(h)

        self.server = Rocket(self.starttuple, "fs", min_threads=0)
        self.server.start(background=True)

        # Create a socket connecting to listener's port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(SOCKET_TIMEOUT)
        self.sock.connect(self.starttuple)

    def tearDown(self):
        self.sock.close()
        self.server.stop()

    def testMembers(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        members = [
            "close", "client_addr", "server_port", "ssl", "socket",
            "start_time"
        ]
        for m in members:
            self.assert_(hasattr(c, m),
                         msg="Connection object does not have %s " % m)

    def testSocketTimeout(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        timeout = c.socket.gettimeout()
        self.assertEqual(timeout, SOCKET_TIMEOUT)

    def testSocketRecv(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = "this is a test"
        self.sock.send(SENT_DATA)

        data = c.recv(len(SENT_DATA))

        self.assertEqual(data, SENT_DATA)

    def testSocketSend(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        RECVD_DATA = "this is a test"
        c.send(RECVD_DATA)

        data = self.sock.recv(len(RECVD_DATA))

        self.assertEqual(data, RECVD_DATA)

    def testFileLikeSocketRead(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = "this is a test"
        self.sock.send(SENT_DATA)

        f = c.makefile()
        data = f.read(len(SENT_DATA))

        self.assertEqual(data, SENT_DATA)

        f.close()

    def testFileLikeSocketReadline(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = """this is a test\r\nthis is another line\r\n"""
        self.sock.send(SENT_DATA)

        time.sleep(0.25)

        f = c.makefile()

        for l in SENT_DATA.splitlines():
            data = f.readline()
            self.assertEqual(data, l + "\r\n")

        f.close()

    def testFileLikeSocketReadlines(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = """this is a test\r\nthis is another line\r\n"""
        self.sock.send(SENT_DATA)
        self.sock.close()

        time.sleep(0.25)

        f = c.makefile()

        sent_lines = [x + '\r\n' for x in SENT_DATA.splitlines()]
        data_lines = f.readlines()

        self.assertEqual(sent_lines, data_lines)

        f.close()
예제 #19
0
                http_content = "moduuid {} not available".format(mod_uuid)
        else:
            path_info = environ["PATH_INFO"]
            if path_info in MAP_FILES:
                path_info = MAP_FILES[path_info]
            if path_info in FILES:
                content_type = FILES[path_info]
                path_info = os.path.join(os.getcwd(), path_info.strip("/"))
                f = open(path_info, "r")
                http_content = substitue_content(f.read())
                if "$$$MODULE_CONTENT$$$" in http_content:   http_content = insert_modules(http_content)
    except:
        traceback.print_exc()

    headers = [('Content-type', content_type)]
    start_response(status, headers)
    return http_content

my_demo = { "wsgi_app": my_simple_app }

if __name__ == '__main__':
    log = logging.getLogger('Rocket.Requests')
    log.setLevel(logging.INFO)
    fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
    h = logging.StreamHandler()
    h.setFormatter(fmt)
    log.addHandler(h)

    r = Rocket(interfaces=[('127.0.0.1', 8000), ('::1', 8000)], method='wsgi', app_info=my_demo)
    r.start()
예제 #20
0
from rocket import Rocket

my_argparser = argparse.ArgumentParser()
my_argparser.add_argument( '--listen-on-ip', '-l', required=True )
my_argparser.add_argument( '--listen-on-port', '-p', type=int, required=True )
my_argparser.add_argument( '--ssl-key', required=True )
my_argparser.add_argument( '--ssl-cert', required=True )
my_argparser.add_argument( '--verbose', action='store_true')
parsedargs = my_argparser.parse_args()
my_example_app = Bottle( )

# A global handler that runs for all requests
@my_example_app.hook('before_request')
def before_request():
	response.set_header('X-Rocket-Powered', socket.getfqdn())

# Let people test to see if we are alive
@my_example_app.route('/ping')
def hello():
    return "pong"

#Enable INFO logging?
if parsedargs.verbose:
	log = logging.getLogger('Rocket')
	log.setLevel( logging.INFO )
	log.addHandler(logging.StreamHandler())

#Let's go
my_rocket = Rocket( ( parsedargs.listen_on_ip, parsedargs.listen_on_port, parsedargs.ssl_key, parsedargs.ssl_cert ), 'wsgi', { "wsgi_app":my_example_app } )
my_rocket.start()
예제 #21
0
class ConnectionTest(unittest.TestCase):
    def setUp(self):
        global SERVER_PORT_START

        SERVER_PORT_START += 1
        self.starttuple = ('127.0.0.1', SERVER_PORT_START)

        #log = logging.getLogger('Rocket')
        #log.setLevel(logging.DEBUG)
        #fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
        #h = logging.StreamHandler()
        #h.setFormatter(fmt)
        #log.addHandler(h)

        self.server = Rocket(self.starttuple,
                             "fs",
                             min_threads=0)
        self.server.start(background=True)

        # Create a socket connecting to listener's port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(SOCKET_TIMEOUT)
        self.sock.connect(self.starttuple)

    def tearDown(self):
        self.sock.close()
        self.server.stop()

    def testMembers(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        members = ["close", "client_addr", "server_port", "ssl", "socket", "start_time"]
        for m in members:
            self.assertTrue(hasattr(c, m),
                         msg="Connection object does not have %s " % m)

    def testSocketTimeout(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        timeout = c.socket.gettimeout()
        self.assertEqual(timeout, SOCKET_TIMEOUT)

    def testSocketRecv(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("this is a test")
        self.sock.send(SENT_DATA)

        data = c.recv(len(SENT_DATA))

        self.assertEqual(data, SENT_DATA)

    def testSocketSend(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        RECVD_DATA = b("this is a test")
        c.send(RECVD_DATA)

        data = self.sock.recv(len(RECVD_DATA))

        self.assertEqual(data, RECVD_DATA)

    def testFileLikeSocketRead(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("this is a test")
        self.sock.send(SENT_DATA)

        f = c.makefile()
        data = b(f.read(len(SENT_DATA)))

        self.assertEqual(data, SENT_DATA)

        f.close()

    def testFileLikeSocketReadline(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("""this is a test\nthis is another line\n""")
        self.sock.send(SENT_DATA)

        time.sleep(0.25)

        f = c.makefile()

        try:
            for l in SENT_DATA.splitlines():
                data = b(f.readline())
                self.assertEqual(data, l+b("\n"))
        finally:
            f.close()
            c.close()

    def testFileLikeSocketReadlines(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("""this is a test\nthis is another line\n""")
        self.sock.send(SENT_DATA)
        self.sock.close()

        time.sleep(0.25)

        f = c.makefile()

        sent_lines = [x + b('\n') for x in SENT_DATA.splitlines()]
        data_lines = [b(x) for x in f.readlines()]

        self.assertEqual(sent_lines, data_lines)

        f.close()
        c.close()
예제 #22
0
                response = r.read()
                if response == 'ON':
                    state = '1'
                else:
                    state = '0'
        else:
            state = msg.payload
        client.publish(PREFIX + '{}_Relay_{}'.format(controller, relay), state)

if __name__ == '__main__':
    log = logging.getLogger('Rocket')
    log.setLevel(logging.INFO)
    fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
    h = logging.FileHandler('/var/log/wb-ab-log-eth.log')
    h.setFormatter(fmt)
    log.addHandler(h)

    mqttc.on_connect = on_connect
    mqttc.on_message = on_message
                    
    mqttc.connect("localhost", 1883)
    
    server = Rocket(interfaces=('0.0.0.0', 9999),
                    method='wsgi', 
                    app_info={"wsgi_app":ab_log_app})
                    
    mqttc.loop_start()
    server.start()
    mqttc.loop_stop()
    mqttc.disconnect()
예제 #23
0
파일: wsgi-fs.py 프로젝트: zoni/Rocket
teaching WSGI concepts."""