app.py
Python script, ASCII text executable
1import datetime 2 3import celery 4import flask 5import sqlalchemy 6from flask_sqlalchemy import SQLAlchemy 7from flask_bcrypt import Bcrypt 8from flask_migrate import Migrate 9 10from sqlalchemy.orm import declarative_base 11from celery import shared_task 12import httpx 13 14app = flask.Flask(__name__) 15from celery import Celery, Task 16 17 18def celery_init_app(app_) -> Celery: 19class FlaskTask(Task): 20def __call__(self, *args: object, **kwargs: object) -> object: 21with app_.app_context(): 22return self.run(*args, **kwargs) 23 24celery_app = Celery(app_.name, task_cls=FlaskTask) 25celery_app.config_from_object(app_.config["CELERY"]) 26celery_app.set_default() 27app_.extensions["celery"] = celery_app 28return celery_app 29 30 31app.config.from_mapping( 32CELERY=dict( 33broker_url="redis://localhost:6379", 34result_backend="redis://localhost:6379" 35), 36) 37celery_app = celery_init_app(app) 38 39app.config["SQLALCHEMY_DATABASE_URI"] = \ 40"postgresql://echo:1234@localhost:5432/echo" 41app.config["SQLALCHEMY_ENGINE_OPTIONS"] = { 42"connect_args": { 43"options": "-c timezone=utc" 44} 45} 46db = SQLAlchemy(app) 47bcrypt = Bcrypt(app) 48migrate = Migrate(app, db) 49app.config["SESSION_TYPE"] = "filesystem" 50app.config["SECRET_KEY"] = "super secret" 51 52with app.app_context(): 53class User(db.Model): 54username = db.Column(db.String(64), unique=True, nullable=False, primary_key=True) 55password = db.Column(db.String(72), nullable=False) 56admin = db.Column(db.Boolean, nullable=False, default=False) 57 58applications = db.relationship("Application", back_populates="owner") 59 60def __init__(self, username, password, admin=False): 61self.username = username 62self.password = bcrypt.generate_password_hash(password).decode("utf-8") 63self.admin = admin 64 65class Application(db.Model): 66id = db.Column(db.Integer, primary_key=True, autoincrement=True, unique=True, default=0) 67name = db.Column(db.String(64), unique=True, nullable=False) 68owner_name = db.Column(db.String(64), db.ForeignKey("user.username"), nullable=False) 69 70owner = db.relationship("User", back_populates="applications") 71 72endpoints = db.relationship("Endpoint", back_populates="application") 73 74def __init__(self, name, owner): 75self.name = name 76self.owner_name = owner.username 77 78class Endpoint(db.Model): 79id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True, autoincrement=True) 80application_id = db.Column(db.Integer, db.ForeignKey("application.id"), nullable=False) 81address = db.Column(db.String(2048), nullable=False) 82name = db.Column(db.String(64), nullable=False) 83comment = db.Column(db.String(2048), nullable=True) 84ping_interval = db.Column(db.Integer, default=300, nullable=False) 85buggy = db.Column(db.Boolean, default=False) 86 87application = db.relationship("Application", back_populates="endpoints") 88statuses = db.relationship("Status", back_populates="endpoint", lazy="dynamic") 89 90def __init__(self, application, name, address, ping_interval, comment=""): 91self.application_id = application.id 92self.name = name 93self.address = address 94self.comment = comment 95self.ping_interval = ping_interval 96 97 98class Status(db.Model): 99id = db.Column(db.Integer, nullable=False, autoincrement=True, primary_key=True) 100endpoint_id = db.Column(db.Integer, db.ForeignKey("endpoint.id"), nullable=False) 101time = db.Column(db.DateTime, default=datetime.datetime.utcnow) 102 103status = db.Column(db.SmallInteger, nullable=False) 104buggy = db.Column(db.Boolean, default=False) 105endpoint = db.relationship("Endpoint", back_populates="statuses") 106 107def __init__(self, endpoint_id, status, buggy): 108self.endpoint_id = endpoint_id 109self.status = status 110self.buggy = buggy 111 112 113@celery.shared_task(name="ping") 114def ping(id, address, next_ping): 115if not db.session.get(Endpoint, id): 116return 117elif db.session.get(Endpoint, id).buggy: 118buggy = True 119else: 120buggy = False 121url = address 122print(f"Pinging {url}") 123response = httpx.get(url, verify=False) 124reading = Status(id, response.status_code, buggy) 125db.session.add(reading) 126db.session.commit() 127 128# Schedule the next ping 129ping.apply_async(args=(id, address, next_ping), countdown=next_ping) 130 131@celery.shared_task(name="ping_all") 132def ping_all(): 133endpoints = Endpoint.query.all() 134for endpoint in endpoints: 135ping.delay(endpoint.id, endpoint.address, endpoint.ping_interval) 136 137 138task = ping_all.delay() 139 140print() 141print() 142print(task) 143print() 144print() 145 146 147@app.context_processor 148def default(): 149return { 150"session": flask.session, 151} 152 153 154@app.route("/") 155def dashboard(): 156return flask.render_template("dashboard.html", apps=Application.query.all()) 157 158 159@app.route("/login", methods=["GET"]) 160def login(): 161return flask.render_template("login.html") 162 163 164@app.route("/signup", methods=["GET"]) 165def signup(): 166return flask.render_template("signup.html") 167 168 169@app.route("/new-app", methods=["GET"]) 170def new_app(): 171if not flask.session.get("username"): 172return flask.redirect("/login", code=303) 173return flask.render_template("new-app.html") 174 175 176@app.route("/new-app", methods=["POST"]) 177def new_app_post(): 178if not flask.session.get("username"): 179return flask.redirect("/login", code=303) 180if Application.query.filter_by(name=flask.request.form["name"]).first(): 181flask.flash("Application already exists") 182return flask.redirect("/new-app", code=303) 183 184new_app_ = Application( 185flask.request.form["name"], 186db.session.get(User, flask.session["username"]), 187) 188db.session.add(new_app_) 189db.session.commit() 190return flask.redirect("/", code=303) 191 192 193@app.route("/login", methods=["POST"]) 194def login_post(): 195user = db.session.get(User, flask.request.form["username"]) 196if not user: 197flask.flash("Username doesn't exist") 198return flask.redirect("/signup", code=303) 199if not bcrypt.check_password_hash(user.password, flask.request.form["password"]): 200flask.flash("Wrong password") 201return flask.redirect("/signup", code=303) 202 203flask.session["username"] = user.username 204return flask.redirect("/", code=303) 205 206 207@app.route("/logout") 208def logout(): 209flask.session.pop("username", None) 210return flask.redirect("/", code=303) 211 212 213@app.route("/signup", methods=["POST"]) 214def signup_post(): 215if flask.request.form["password"] != flask.request.form["password2"]: 216flask.flash("Passwords do not match") 217return flask.redirect("/signup", code=303) 218if db.session.get(User, flask.request.form["username"]): 219flask.flash("Username already exists") 220return flask.redirect("/signup", code=303) 221if len(flask.request.form["password"]) < 8: 222flask.flash("Password must be at least 8 characters") 223return flask.redirect("/signup", code=303) 224if len(flask.request.form["username"]) < 4: 225flask.flash("Username must be at least 4 characters") 226return flask.redirect("/signup", code=303) 227 228new_user = User( 229flask.request.form["username"], 230flask.request.form["password"], 231) 232db.session.add(new_user) 233db.session.commit() 234flask.session["username"] = new_user.username 235return flask.redirect("/", code=303) 236 237 238# UTC filter 239@app.template_filter("utc") 240def utc_filter(timestamp): 241return datetime.datetime.utcfromtimestamp(timestamp) 242 243 244@app.route("/app/<int:app_id>/") 245def app_info(app_id): 246app_ = db.session.get(Application, app_id) 247 248time_slices = [(datetime.datetime.utcnow() - datetime.timedelta(minutes=int(flask.request.args.get("bar_duration", 30)) * (i+1)), 249datetime.datetime.utcnow() - datetime.timedelta(minutes=int(flask.request.args.get("bar_duration", 30)) * i)) 250for i in range(int(flask.request.args.get("time_period", 30)) // int(flask.request.args.get("bar_duration", 1)))] 251 252slice_results = [] 253 254for slice_ in time_slices: 255slice_results.append(db.session.query(Status).filter( 256sqlalchemy.and_(Status.endpoint.has(application_id=app_id), 257Status.time >= slice_[0], 258Status.time < slice_[1])).all()) 259 260return flask.render_template("app.html", app=app_, sorted=sorted, list=list, 261sorting=lambda x: x.time, reverse=True, 262is_ok=lambda x: all(status.status in (200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 302, 304, 307) 263for status in x), and_=sqlalchemy.and_, 264bar_duration=int(flask.request.args.get("bar_duration", 30)), int=int, Status=Status, 265time_period=int(flask.request.args.get("time_period", 1440)), 266now=round(datetime.datetime.utcnow().timestamp()), func=sqlalchemy.func, 267reversed=reversed, fromtimestamp=datetime.datetime.utcfromtimestamp, 268slices=slice_results) 269 270 271@app.route("/app/<int:app_id>/edit/") 272def app_editor(app_id): 273if flask.session.get("username") != db.session.get(Application, app_id).owner_name: 274flask.abort(403) 275app_ = db.session.get(Application, app_id) 276return flask.render_template("app-editor.html", app=app_) 277 278 279@app.route("/app/<int:app_id>/edit/<int:endpoint_id>", methods=["POST"]) 280def endpoint_edit(app_id, endpoint_id): 281if flask.session.get("username") != db.session.get(Application, app_id).owner_name: 282flask.abort(403) 283endpoint = db.session.get(Endpoint, endpoint_id) 284if flask.request.form.get("delete") == "delete": 285statuses = db.session.query(Status).filter_by(endpoint_id=endpoint_id).all() 286for status in statuses: 287db.session.delete(status) 288db.session.delete(endpoint) 289db.session.commit() 290else: 291endpoint.name = flask.request.form["name"] 292endpoint.address = flask.request.form["url"] 293endpoint.ping_interval = max(15, int(flask.request.form["ping_interval"])) 294endpoint.comment = flask.request.form["comment"] 295db.session.commit() 296return flask.redirect(f"/app/{app_id}/edit", code=303) 297 298 299@app.route("/app/<int:app_id>/add-endpoint", methods=["POST"]) 300def app_add_endpoint(app_id): 301if flask.session.get("username") != db.session.get(Application, app_id).owner_name: 302flask.abort(403) 303app_ = db.session.get(Application, app_id) 304endpoint = Endpoint(app_, 305flask.request.form["name"], 306flask.request.form["url"], 307max(15, int(flask.request.form["ping_interval"])), 308flask.request.form["comment"]) 309db.session.add(endpoint) 310db.session.commit() 311 312ping.delay(endpoint.id, endpoint.address, endpoint.ping_interval) 313 314return flask.redirect(f"/app/{app_id}/edit", code=303) 315 316