diff --git a/generate_schema_config.py b/generate_schema_config.py index 123de907cd461abfb03702e5c6f61f7ff25c5795..03888de520f71fc8a4ea107989a97129e9318847 100644 --- a/generate_schema_config.py +++ b/generate_schema_config.py @@ -14,11 +14,18 @@ from formats.alert import alert_schema from flasgger import Swagger from flask import Flask +import argparse +import json import os -app = Flask(__name__) -url_prefix = os.getenv("URL_PREFIX", "") +# Enable running on domain sub-path +URL_PREFIX = os.getenv("URL_PREFIX", "") +# Allow env override of default host +FLASK_HOST = os.getenv("FLASK_HOST", "localhost") +# Allow env override of default port +FLASK_PORT = os.getenv("FLASK_PORT", 5000) + swagger_config = { "openapi": "3.0.2", @@ -35,7 +42,7 @@ swagger_config = { "route": "/soar_protocol.json", } ], - "url_prefix": url_prefix, + "url_prefix": URL_PREFIX, "paths": {}, "components": { "schemas": { @@ -103,11 +110,49 @@ swagger_config = { }, } -swag = Swagger(app, config=swagger_config, merge=True) +def serve(): + """ + Run as local flask app on port 5000 + """ + app = Flask(__name__) + Swagger(app, config=swagger_config, merge=True) + + app.run(debug=False, host=FLASK_HOST, port=FLASK_PORT) + + +def write_schema(swagger_config, file_path): + """ + Dump schema to specified file + """ + json_schema = json.dumps(swagger_config, indent=2) + with open(file_path, "w") as f: + f.write(json_schema) + + +def get_options(): + """ + Parse script arguments + """ + parser = argparse.ArgumentParser(description="Generate the schema", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("-s", "--serve", dest="run_flask", action="store_true", help="Run flask app", default=False) + parser.add_argument("-f", "--file", dest="output_file", action="store_true", help="Save output to schema file", default=False) + args = parser.parse_args() + config = vars(args) + # If no flag is specified default to running the flask server + if (all(v is False for v in config.values())): + config["run_flask"] = True + return config + -flask_host = os.getenv( - "FLASK_HOST", "localhost" -) # Sets to whatever FLASK_HOST is, or defaults to localhost +if __name__ == "__main__": + # Parse script args + config = get_options() + + # Output compiled schema + if config.get("output_file"): + write_schema(swagger_config, "project/soar/swagger.json") -if __name__ == "__main__": - app.run(debug=False, host=flask_host) + # Run flask app + if config.get("run_flask"): + serve()