示例#1
0
def serve(entrypoint: str, location: str, deps: str, wsgi: bool, host: str,
          port: int) -> typing.Any:
    """CLI serve."""
    if deps:
        click.echo(f"Installing deps: {deps}")
        _deps(deps, location)

    signal.signal(signal.SIGTERM, handle_sigterm)

    app = ps.generate_app()
    app = ps.append_entrypoint(app, entrypoint, os.path.abspath(location))

    if not wsgi:
        click.echo("Starting Flask Development server")
        app.run(
            host=os.getenv("DPLOY_KICKSTART_HOST", "0.0.0.0"),
            port=int(os.getenv("DPLOY_KICKSTART_PORT", 8080)),
        )
    else:
        click.echo("Starting Waitress server")
        waitress_serve(
            TransLogger(app, setup_console_handler=False),
            host=os.getenv("dploy_kickstart_HOST", "0.0.0.0"),
            port=int(os.getenv("dploy_kickstart_PORT", 8080)),
        )
示例#2
0
    def __init__(self, themedir, siteconftemplate):
        self.installdir = sys.path[0] # Note: this should ideally be gotten from somewhere else.
        self.wsgiapp = Bottle()
        self.apiclass = sandbox.csg2api(self.wsgiapp, self.runningsessions)
        
        # Parse arguments
        argparser = argparse.ArgumentParser()
        argparser.add_argument('sitesfolder', metavar='<site storage folder>', help="path to the folder containing sites")
        argparser.add_argument('siteroot', metavar='<site name>', help="site name/the folder with config.json")
        self.parsedargs = argparser.parse_args()

        # Setup configuration and path to site
        self.sitepath = os.path.abspath(os.path.join(self.parsedargs.sitesfolder, self.parsedargs.siteroot))
        siteconffile = open(os.path.join(self.sitepath, "config.json"), mode="rt", encoding="utf-8")
        self.siteconf = configman.normalize_config(json.load(siteconffile), self.parsedargs.siteroot)
        siteconffile.close()
        
        # Setup theming
        themesroot = os.path.abspath(themedir)
        self.themepath = os.path.join(themesroot, self.siteconf["site"]["theme"])
        os.chdir(self.sitepath)
        
        # Assign routes (done before the site code to allow overrides)
        # This is functionally equivalent of what the language does, but makes sure Bottle will call the right instance.
        self.getrandstaticredirect = self.wsgiapp.route("/rand/<filepath:path>")(self.getrandstaticredirect)
        self.getstatic = self.wsgiapp.route("/static/<filepath:path>")(self.getstatic)
        self.compilethemesass = self.wsgiapp.route("/theme/sass/master.scss")(self.compilethemesass)
        self.getthemeasset = self.wsgiapp.route("/theme/static/<filepath:path>")(self.getthemeasset)
        self.compilesass = self.wsgiapp.route("/sass/<filename:re:.*\.scss>")(self.compilesass)
        self.catchall = self.wsgiapp.route("/")(
            self.wsgiapp.route("/<filepath:path>")(
                view(os.path.join(self.themepath, "master.tpl"))(self.catchall)
            )
        )
        self.dologin = self.wsgiapp.route("/login", method="POST")(self.dologin)
        
        # If they have code, run it
        if "additional_code" in self.siteconf["site"]:
            oldpath = sys.path
            sys.path[0] = self.sitepath
            importlib.invalidate_caches()
            with open(os.path.join(self.sitepath, self.siteconf["site"]["additional_code"]), mode="rt") as codefile:
                sandbox.create_box(codefile.read(), self.wsgiapp, apiclass=self.apiclass) # This file is excempt from the linking clauses in the license, allowing it to be non-(A)GPL.
            sys.path = oldpath
            importlib.invalidate_caches()

        # Configure Nginx
        socketpath = "/tmp/csg2_{}.sock".format(self.siteconf["site"]["domain_name"].replace(".", "_"))
        print("-> Generating config.")
        with open(os.path.abspath(siteconftemplate), mode="rt", encoding="utf-8") as sitetemplate:
            sitetemplatetxt = sitetemplate.read()
            newsite = sitetemplatetxt.replace("%%SERVERNAME%%", self.siteconf["site"]["domain_name"]).replace("%%SOCKETPATH%%", socketpath)
            with open("/tmp/{}.csg2nginx".format(self.siteconf["site"]["domain_name"].replace(".", "_")), mode="wt", encoding="utf-8") as newconf:
                newconf.write(newsite)
        
        # Serve site.
        print("-> Serving up site on '{}'.".format(socketpath))
        waitress_serve(self.wsgiapp, unix_socket=socketpath)
示例#3
0
def serve(args):
    """Run the web server for the application."""
    from waitress import serve as waitress_serve
    from ..wsgi import app

    if args.reload:
        try:
            import hupper
        except ImportError:
            sys.stderr.write(
                "Please install dev dependencies to use reloader.\n")
            sys.exit(1)
        hupper.start_reloader("fanboi2.cmd.ctl.main")

    waitress_serve(app, host=args.host, port=args.port)
    sys.exit(0)
示例#4
0
def run_web():
    waitress_serve(app, host='0.0.0.0', port=cfg["host_port"])
示例#5
0
        Rrd.dump_histogram_analytics(dbfiles=dbfiles,
                                     period=RrdPeriod.PERIOD_14_DAYS_SEC)
        Rrd.dump_histogram_analytics(dbfiles=dbfiles,
                                     period=RrdPeriod.PERIOD_YEAR_SEC)
        time.sleep(export_interval)


# validating configs
if KOA_CONFIG.cost_model == 'CHARGE_BACK' and KOA_CONFIG.billing_hourly_rate <= 0.0:
    KOA_LOGGER.fatal(
        'invalid billing hourly rate for CHARGE_BACK cost allocation')
    sys.exit(1)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Kubernetes Opex Analytics Backend')
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + KOA_CONFIG.version)
    args = parser.parse_args()
    th_puller = threading.Thread(target=create_metrics_puller)
    th_exporter = threading.Thread(target=dump_analytics)
    th_puller.start()
    th_exporter.start()

    if not KOA_CONFIG.enable_debug:
        waitress_serve(wsgi_dispatcher, listen='*:5483')
    else:
        app.run(host='0.0.0.0', port=5483)
示例#6
0
LISTEN_PORT = 8000
app = Flask(__name__)

rdb = ReportDatabase("reports.db")
rdb.create_db()


# Flask: Listen for PUT https request from extensions
@app.route("/report", methods=['POST', 'PUT'])
def handle_report():
    rdb.new_entry(request.args["sender"], request.args["content"])


@app.route("/")
def display_db_browser():
    with open("pages/reportbrowser.html") as dbb_file:
        dbb_string = ""
        for line in dbb_file:
            dbb_string += str(line)
        return dbb_string


@app.route('/items')
def fetch_items():
    return rdb.items()


# NOTE: `app.run` is for testing only, NOT deployment.
# app.run(debug=True, )
waitress_serve(app, host='0.0.0.0', port=LISTEN_PORT)
示例#7
0
    def __init__(self, themedir, siteconftemplate):
        self.installdir = sys.path[
            0]  # Note: this should ideally be gotten from somewhere else.
        self.wsgiapp = Bottle()
        self.apiclass = sandbox.csg2api(self.wsgiapp, self.runningsessions)

        # Parse arguments
        argparser = argparse.ArgumentParser()
        argparser.add_argument('sitesfolder',
                               metavar='<site storage folder>',
                               help="path to the folder containing sites")
        argparser.add_argument('siteroot',
                               metavar='<site name>',
                               help="site name/the folder with config.json")
        self.parsedargs = argparser.parse_args()

        # Setup configuration and path to site
        self.sitepath = os.path.abspath(
            os.path.join(self.parsedargs.sitesfolder,
                         self.parsedargs.siteroot))
        siteconffile = open(os.path.join(self.sitepath, "config.json"),
                            mode="rt",
                            encoding="utf-8")
        self.siteconf = configman.normalize_config(json.load(siteconffile),
                                                   self.parsedargs.siteroot)
        siteconffile.close()

        # Setup theming
        themesroot = os.path.abspath(themedir)
        self.themepath = os.path.join(themesroot,
                                      self.siteconf["site"]["theme"])
        os.chdir(self.sitepath)

        # Assign routes (done before the site code to allow overrides)
        # This is functionally equivalent of what the language does, but makes sure Bottle will call the right instance.
        self.getrandstaticredirect = self.wsgiapp.route(
            "/rand/<filepath:path>")(self.getrandstaticredirect)
        self.getstatic = self.wsgiapp.route("/static/<filepath:path>")(
            self.getstatic)
        self.compilethemesass = self.wsgiapp.route("/theme/sass/master.scss")(
            self.compilethemesass)
        self.getthemeasset = self.wsgiapp.route(
            "/theme/static/<filepath:path>")(self.getthemeasset)
        self.compilesass = self.wsgiapp.route("/sass/<filename:re:.*\.scss>")(
            self.compilesass)
        self.catchall = self.wsgiapp.route("/")(
            self.wsgiapp.route("/<filepath:path>")(view(
                os.path.join(self.themepath, "master.tpl"))(self.catchall)))
        self.dologin = self.wsgiapp.route("/login",
                                          method="POST")(self.dologin)

        # If they have code, run it
        if "additional_code" in self.siteconf["site"]:
            oldpath = sys.path
            sys.path[0] = self.sitepath
            importlib.invalidate_caches()
            with open(os.path.join(self.sitepath,
                                   self.siteconf["site"]["additional_code"]),
                      mode="rt") as codefile:
                sandbox.create_box(
                    codefile.read(), self.wsgiapp, apiclass=self.apiclass
                )  # This file is excempt from the linking clauses in the license, allowing it to be non-(A)GPL.
            sys.path = oldpath
            importlib.invalidate_caches()

        # Configure Nginx
        socketpath = "/tmp/csg2_{}.sock".format(
            self.siteconf["site"]["domain_name"].replace(".", "_"))
        print("-> Generating config.")
        with open(os.path.abspath(siteconftemplate),
                  mode="rt",
                  encoding="utf-8") as sitetemplate:
            sitetemplatetxt = sitetemplate.read()
            newsite = sitetemplatetxt.replace(
                "%%SERVERNAME%%",
                self.siteconf["site"]["domain_name"]).replace(
                    "%%SOCKETPATH%%", socketpath)
            with open("/tmp/{}.csg2nginx".format(
                    self.siteconf["site"]["domain_name"].replace(".", "_")),
                      mode="wt",
                      encoding="utf-8") as newconf:
                newconf.write(newsite)

        # Serve site.
        print("-> Serving up site on '{}'.".format(socketpath))
        waitress_serve(self.wsgiapp, unix_socket=socketpath)