-
-
Notifications
You must be signed in to change notification settings - Fork 64
Fix background jobs that previously failed and were never completed properly #3113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
tw4l
wants to merge
5
commits into
main
Choose a base branch
from
issue-3067-rerun-bg-jobs-not-finished
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+178
−1
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c393fa3
Add migration to fix failed bg jobs with weird state
tw4l 0260016
Fix typo
tw4l 28eb811
Add migration to look for unreplicated files and replicate them
tw4l 7102be3
Remove unnecessary success filter
tw4l acbddbf
Remove unnecessary variable
tw4l File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,7 +44,7 @@ | |
| ) = object | ||
|
|
||
|
|
||
| CURR_DB_VERSION = "0055" | ||
| CURR_DB_VERSION = "0057" | ||
|
|
||
| MIN_DB_VERSION = 7.0 | ||
|
|
||
|
|
||
60 changes: 60 additions & 0 deletions
60
backend/btrixcloud/migrations/migration_0056_rerun_bg_jobs.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| """ | ||
| Migration 0056 - Fix failed background jobs with success and finished unset | ||
| """ | ||
|
|
||
| from datetime import timedelta | ||
| import os | ||
|
|
||
| from btrixcloud.migrations import BaseMigration | ||
| from btrixcloud.utils import dt_now | ||
|
|
||
|
|
||
| MIGRATION_VERSION = "0056" | ||
|
|
||
|
|
||
| class Migration(BaseMigration): | ||
| """Migration class.""" | ||
|
|
||
| # pylint: disable=unused-argument | ||
| def __init__(self, mdb, **kwargs): | ||
| super().__init__(mdb, migration_version=MIGRATION_VERSION) | ||
|
|
||
| async def migrate_up(self): | ||
| """Perform migration up. | ||
|
|
||
| Identify background jobs that failed but never had finished or success | ||
| updated in database and correct them in the database so that they can | ||
| be restarted via the retry endpoints. | ||
|
|
||
| We don't want to modify jobs that are still in process or subject to | ||
| the replica deletion delay, so target jobs that are either (replica delay | ||
| deltion + 1) or 7 days old, whichever is greater. | ||
| """ | ||
| jobs_mdb = self.mdb["jobs"] | ||
|
|
||
| replica_deletion_days = int(os.environ.get("REPLICA_DELETION_DELAY_DAYS", 0)) | ||
| days_delta = max(replica_deletion_days + 1, 7) | ||
| started_before = dt_now() - timedelta(days=days_delta) | ||
|
|
||
| match_query = { | ||
| "finished": None, | ||
| "success": None, | ||
| "started": {"$lte": started_before}, | ||
| } | ||
|
|
||
| try: | ||
| await jobs_mdb.update_many( | ||
| match_query, | ||
| { | ||
| "$set": { | ||
| "success": False, | ||
| "finished": started_before, | ||
| } | ||
| }, | ||
| ) | ||
| # pylint: disable=broad-exception-caught | ||
| except Exception as err: | ||
| print( | ||
| f"Error updating failed background jobs: {err}", | ||
| flush=True, | ||
| ) |
117 changes: 117 additions & 0 deletions
117
backend/btrixcloud/migrations/migration_0057_replicate_files.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| """ | ||
| Migration 0057 - Replicate any unreplicated crawl and profile files | ||
| """ | ||
|
|
||
| from btrixcloud.migrations import BaseMigration | ||
| from btrixcloud.models import BaseCrawl, Profile, BgJobType | ||
|
|
||
|
|
||
| MIGRATION_VERSION = "0057" | ||
|
|
||
|
|
||
| class Migration(BaseMigration): | ||
| """Migration class.""" | ||
|
|
||
| # pylint: disable=unused-argument | ||
| def __init__(self, mdb, **kwargs): | ||
| super().__init__(mdb, migration_version=MIGRATION_VERSION) | ||
|
|
||
| self.background_job_ops = kwargs.get("background_job_ops") | ||
|
|
||
| # pylint: disable=too-many-locals | ||
| async def migrate_up(self): | ||
| """Perform migration up. | ||
|
|
||
| Identify files from archived items and profiles that should have been | ||
| replicated but weren't, and start new background jobs to re-replicate | ||
| the files if there isn't already an in-progress job to do the same. | ||
| """ | ||
| orgs_mdb = self.mdb["organizations"] | ||
| jobs_mdb = self.mdb["jobs"] | ||
| crawls_mdb = self.mdb["crawls"] | ||
| profiles_mdb = self.mdb["profiles"] | ||
|
|
||
| if self.background_job_ops is None: | ||
| print( | ||
| "Unable to replicate unreplicated files, missing required ops", | ||
| flush=True, | ||
| ) | ||
| return | ||
|
|
||
| # Future-proof in anticipation of custom storage - do not attempt to | ||
| # replicate files for orgs that don't have a replica location configured | ||
| orgs_with_replicas = [] | ||
| async for org in orgs_mdb.find( | ||
| {"storageReplicas.0": {"$exists": True}}, projection=["_id"] | ||
| ): | ||
| orgs_with_replicas.append(org["_id"]) | ||
|
|
||
| # Archived items | ||
|
|
||
| crawls_match_query = { | ||
| "oid": {"$in": orgs_with_replicas}, | ||
| "files": {"$elemMatch": {"replicas": {"$in": [None, []]}}}, | ||
| } | ||
| async for crawl_raw in crawls_mdb.find(crawls_match_query): | ||
| crawl = BaseCrawl.from_dict(crawl_raw) | ||
| for file_ in crawl.files: | ||
| if not file_.replicas: | ||
| # Check that there isn't an in-progress job for this file | ||
| if await jobs_mdb.find( | ||
| { | ||
| "type": BgJobType.CREATE_REPLICA.value, | ||
| "object_id": crawl.id, | ||
| "object_type": crawl.type, | ||
| "file_path": file_.filename, | ||
| "started": {"$ne": None}, | ||
| "finished": None, | ||
| } | ||
| ): | ||
| continue | ||
|
|
||
| try: | ||
| await self.background_job_ops.create_replica_jobs( | ||
| crawl.oid, file_, crawl.id, crawl.type | ||
| ) | ||
| # pylint: disable=broad-exception-caught | ||
| except Exception as err: | ||
| print( | ||
| f"Error replicating unreplicated file for item {crawl.id}: {err}", | ||
| flush=True, | ||
| ) | ||
|
|
||
| # Profiles | ||
|
|
||
| profiles_match_query = { | ||
| "oid": {"$in": orgs_with_replicas}, | ||
| "resource.replicas": {"$in": [None, []]}, | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We may want to instead check that the length of the replica array isn't the same length as the number of configured replica locations. It's possible a file would be replicated to one location but not to another. |
||
| } | ||
| async for profile_raw in profiles_mdb.find(profiles_match_query): | ||
| profile = Profile.from_dict(profile_raw) | ||
|
|
||
| if not profile.resource: | ||
| continue | ||
|
|
||
| # Check there isn't already an in-progress job for this profile | ||
| if await jobs_mdb.find( | ||
| { | ||
| "type": BgJobType.CREATE_REPLICA.value, | ||
| "object_id": profile.id, | ||
| "object_type": "profile", | ||
| "file_path": profile.resource.filename, | ||
| "started": {"$ne": None}, | ||
| "finished": None, | ||
| } | ||
| ): | ||
| continue | ||
|
|
||
| try: | ||
| await self.background_job_ops.create_replica_jobs( | ||
| profile.oid, profile.resource, profile.id, "profile" | ||
| ) | ||
| # pylint: disable=broad-exception-caught | ||
| except Exception as err: | ||
| print( | ||
| f"Error replicating unreplicated file for profile {profile.id}: {err}", | ||
| flush=True, | ||
| ) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We may want to instead check that the length of the replica array isn't the same length as the number of configured replica locations. It's possible a file would be replicated to one location but not to another.