Skip to content

Commit

Permalink
Revert "adds job cancel methods, route and template UI"
Browse files Browse the repository at this point in the history
This reverts commit 0a32ddf.
  • Loading branch information
btylerburton committed Nov 5, 2024
1 parent da744ad commit 4c4483c
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 318 deletions.
6 changes: 2 additions & 4 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@
from flask_migrate import Migrate

from app.filters import usa_icon
from harvester.lib.load_manager import LoadManager
from app.scripts.load_manager import load_manager
from database.models import db

load_manager = LoadManager()

load_dotenv()


Expand All @@ -37,7 +35,7 @@ def create_app():

with app.app_context():
db.create_all()
load_manager.start()
load_manager()

return app

Expand Down
23 changes: 5 additions & 18 deletions app/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from flask import Blueprint, flash, redirect, render_template, request, session, url_for
from jinja2_fragments.flask import render_block

from harvester.lib.load_manager import LoadManager
from app.scripts.load_manager import schedule_first_job, trigger_manual_job
from database.interface import HarvesterDBInterface

from . import htmx
Expand All @@ -32,8 +32,6 @@

db = HarvesterDBInterface()

load_manager = LoadManager()

# Login authentication
load_dotenv()
CLIENT_ID = os.getenv("CLIENT_ID")
Expand Down Expand Up @@ -431,7 +429,7 @@ def add_harvest_source():

if request.is_json:
source = db.add_harvest_source(request.json)
job_message = load_manager.schedule_first_job(source.id)
job_message = schedule_first_job(source.id)
if source and job_message:
return {
"message": f"Added new harvest source with ID: {source.id}. {job_message}"
Expand All @@ -442,7 +440,7 @@ def add_harvest_source():
if form.validate_on_submit():
new_source = make_new_source_contract(form)
source = db.add_harvest_source(new_source)
job_message = load_manager.schedule_first_job(source.id)
job_message = schedule_first_job(source.id)
if source and job_message:
flash(f"Updated source with ID: {source.id}. {job_message}")
else:
Expand Down Expand Up @@ -554,7 +552,7 @@ def edit_harvest_source(source_id: str):
if form.validate_on_submit():
new_source_data = make_new_source_contract(form)
source = db.update_harvest_source(source_id, new_source_data)
job_message = load_manager.schedule_first_job(source.id)
job_message = schedule_first_job(source.id)
if source and job_message:
flash(f"Updated source with ID: {source.id}. {job_message}")
else:
Expand Down Expand Up @@ -620,7 +618,7 @@ def delete_harvest_source(source_id):
### Trigger Harvest
@mod.route("/harvest_source/harvest/<source_id>", methods=["GET"])
def trigger_harvest_source(source_id):
message = load_manager.trigger_manual_job(source_id)
message = trigger_manual_job(source_id)
flash(message)
return redirect(f"/harvest_source/{source_id}")

Expand Down Expand Up @@ -710,15 +708,6 @@ def delete_harvest_job(job_id):
return result


@mod.route("/harvest_job/cancel/<job_id>", methods=["GET", "POST"])
@login_required
def cancel_harvest_job(job_id):
"""Cancels a harvest job"""
message = load_manager.stop_job(job_id)
flash(message)
return redirect(f"/harvest_job/{job_id}")


### Get Job Errors by Type
@mod.route("/harvest_job/<job_id>/errors/<error_type>", methods=["GET"])
def get_harvest_errors_by_job(job_id, error_type):
Expand Down Expand Up @@ -758,7 +747,6 @@ def get_harvest_records():
records = db.pget_harvest_records(page)
return db._to_dict(records)


@mod.route("/harvest_record/<record_id>/raw", methods=["GET"])
def get_harvest_record_raw(record_id=None):
record = db.get_harvest_record(record_id)
Expand All @@ -771,7 +759,6 @@ def get_harvest_record_raw(record_id=None):
else:
return {"error": "Not Found"}, 404


### Add record
@mod.route("/harvest_record/add", methods=["POST", "GET"])
def add_harvest_record():
Expand Down
124 changes: 124 additions & 0 deletions app/scripts/load_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import logging
import os
from datetime import datetime

from database.interface import HarvesterDBInterface
from harvester.lib.cf_handler import CFHandler
from harvester.utils.general_utils import create_future_date

CF_API_URL = os.getenv("CF_API_URL")
CF_SERVICE_USER = os.getenv("CF_SERVICE_USER")
CF_SERVICE_AUTH = os.getenv("CF_SERVICE_AUTH")
HARVEST_RUNNER_APP_GUID = os.getenv("HARVEST_RUNNER_APP_GUID")

MAX_TASKS_COUNT = 3

interface = HarvesterDBInterface()

logger = logging.getLogger("harvest_admin")


def create_cf_handler():
# check for correct env vars to init CFHandler
if not CF_API_URL or not CF_SERVICE_USER or not CF_SERVICE_AUTH:
logger.info("CFHandler is not configured correctly. Check your env vars.")
return
return CFHandler(CF_API_URL, CF_SERVICE_USER, CF_SERVICE_AUTH)


def create_task(job_id, cf_handler=None):
task_contract = {
"app_guuid": HARVEST_RUNNER_APP_GUID,
"command": f"python harvester/harvest.py {job_id}",
"task_id": f"harvest-job-{job_id}",
}
if cf_handler is None:
cf_handler = create_cf_handler()

cf_handler.start_task(**task_contract)
updated_job = interface.update_harvest_job(job_id, {"status": "in_progress"})
message = f"Updated job {updated_job.id} to in_progress"
logger.info(message)
return message


def trigger_manual_job(source_id):
source = interface.get_harvest_source(source_id)
jobs_in_progress = interface.get_all_harvest_jobs_by_filter(
{"harvest_source_id": source.id, "status": "in_progress"}
)
if len(jobs_in_progress):
return (
f"Can't trigger harvest. Job {jobs_in_progress[0].id} already in progress."
)
job_data = interface.add_harvest_job(
{
"harvest_source_id": source.id,
"status": "new",
"date_created": datetime.now(),
}
)
if job_data:
logger.info(
f"Created new manual harvest job: for {job_data.harvest_source_id}."
)
return create_task(job_data.id)


def schedule_first_job(source_id):
future_jobs = interface.get_new_harvest_jobs_by_source_in_future(source_id)
# delete any future scheduled jobs
for job in future_jobs:
interface.delete_harvest_job(job.id)
logger.info(f"Deleted harvest job: {job.id} for source {source_id}.")
# then schedule next job
return schedule_next_job(source_id)


def schedule_next_job(source_id):
source = interface.get_harvest_source(source_id)
if source.frequency != "manual":
# schedule new future job
job_data = interface.add_harvest_job(
{
"harvest_source_id": source.id,
"status": "new",
"date_created": create_future_date(source.frequency),
}
)
message = f"Scheduled new harvest job: for {job_data.harvest_source_id} at {job_data.date_created}." # noqa E501
logger.info(message)
return message
else:
return "No job scheduled for manual source."


def load_manager():
# confirm CF_INSTANCE_INDEX == 0. we don't want multiple instances starting jobs
if os.getenv("CF_INSTANCE_INDEX") != "0":
logger.info("CF_INSTANCE_INDEX is not set or not equal to zero")
return

cf_handler = create_cf_handler()

# get new jobs older than now
jobs = interface.get_new_harvest_jobs_in_past()

# get list of running tasks
running_tasks = cf_handler.get_all_running_app_tasks(HARVEST_RUNNER_APP_GUID)

# confirm tasks < MAX_JOBS_COUNT or bail
if running_tasks >= MAX_TASKS_COUNT:
logger.info(
f"{running_tasks} running_tasks >= max tasks count ({MAX_TASKS_COUNT})."
)
return
else:
slots = MAX_TASKS_COUNT - running_tasks

# invoke cf_task with next job(s)
# then mark that job(s) as running in the DB
logger.info("Load Manager :: Updated Harvest Jobs")
for job in jobs[:slots]:
create_task(job.id, cf_handler)
schedule_next_job(job.harvest_source_id)
13 changes: 1 addition & 12 deletions app/templates/view_job_data.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,7 @@ <h2>Job Info</h2>
{% endfor %}
</table>
</div>
{% if session['user'] and data.harvest_job.status == "in_progress" %}
<div class="config-actions">
<ul class="usa-button-group">
<li class="usa-button-group__item">
<a href="{{ url_for('harvest.cancel_harvest_job', job_id=data.harvest_job_id)}}">
<button class="usa-button usa-button--secondary">Cancel</button>
</a>
</li>
</ul>
</div>
{% endif %}
<div class="section my-3">
<div class="section mb-3">
<h2>Job Error Table</h2>
{% if not data.harvest_job.errors %}
No job errors found
Expand Down
3 changes: 1 addition & 2 deletions app/templates/view_source_data.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
{% endblock %}

{% block content %}
<div id="flash-message"
style="display:none; position:fixed; top:10px; left:50%; transform:translateX(-50%); background-color:#ffcc00; color:black; padding:10px; border:1px solid #000; z-index:1000;">
<div id="flash-message" style="display:none; position:fixed; top:10px; left:50%; transform:translateX(-50%); background-color:#ffcc00; color:black; padding:10px; border:1px solid #000; z-index:1000;">
Action in progress...
</div>
<div class="wrapper source-data">
Expand Down
Loading

1 comment on commit 4c4483c

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests Skipped Failures Errors Time
2 0 💤 0 ❌ 0 🔥 8.844s ⏱️

Please sign in to comment.