Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions celery_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@


# -------------------------------------------------

REDIS_HOST = os.getenv("REDIS_HOST")
REDIS_PORT = os.getenv("REDIS_PORT")

Expand All @@ -17,24 +18,30 @@
raise RuntimeError(
f"Missing required environment variables: {', '.join(missing_envs)}"
)

# -------------------------------------------------

REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/0"

# -------------------------------------------------

celery_app = Celery(
"deploy_tracker",
broker=REDIS_URL,
backend=REDIS_URL,
)

# -------------------------------------------------

celery_app.conf.beat_schedule = {
"health_check_30s": {
"task": "tasks.health_checker",
"task": "tasks.check_all_applications",
"schedule": 30.0, # seconds
"args": (1,),
},
}

# -------------------------------------------------

celery_app.conf.include = ["tasks"]
# Auto-discover tasks from tasks.py

Expand Down
43 changes: 29 additions & 14 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,38 @@
# -----------------------------------------------------


@celery_app.task
def health_checker(application_id):
db = SessionLocal()
app_class = db.query(Application).filter(Application.id == application_id).first()
response = requests.get(app_class.url) # Get the application url
status_code = response.status_code
is_up = status_code == 200

time = response.elapsed.total_seconds() # Time it took the website to respond.
def check_single_application(db, application):
try:
response = requests.get(application.url, timeout=5)
status = response.status_code == 200
http_code = response.status_code
response_time = response.elapsed.total_seconds()
except requests.RequestException:
status = False
http_code = 0
response_time = 0

new_check = HealthCheck(
application_id=application_id,
status=is_up,
http_code=response.status_code,
response_time=time,
application_id=application.id,
status=status,
http_code=http_code,
response_time=response_time,
)

db.add(new_check)
db.commit()
db.close() # Need to close manully, (no FastAPI dependency injection here).


# -----------------------------------------------------


@celery_app.task
def check_all_applications():
db = SessionLocal()
try:
applications = db.query(Application).all()

for application in applications:
check_single_application(db, application)
finally:
db.close()
Loading