-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
Ned/studentmodulehistory cleaner command #411
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
07aad29
The clean_history management command to remove excess courseware_stud…
nedbat 3a49136
Quiet some debug output, get transactions right.
nedbat 83cb3d1
Add batch and sleep arguments so we can control the speed from the co…
nedbat 10f062c
Records should be sorted by created,id so that timestamp ties will be…
nedbat 3d67c50
Use TransactionTestCase, to keep other tests from failing, even thoug…
nedbat 900e794
Only quiet the particular logger we think is too noisy.
nedbat 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
239 changes: 239 additions & 0 deletions
239
lms/djangoapps/courseware/management/commands/clean_history.py
This file contains 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,239 @@ | ||
"""A command to clean the StudentModuleHistory table. | ||
|
||
When we added XBlock storage, each field modification wrote a new history row | ||
to the db. Now that we have bulk saves to avoid that database hammering, we | ||
need to clean out the unnecessary rows from the database. | ||
|
||
This command that does that. | ||
|
||
""" | ||
|
||
import datetime | ||
import json | ||
import logging | ||
import optparse | ||
import time | ||
import traceback | ||
|
||
from django.core.management.base import NoArgsCommand | ||
from django.db import connection | ||
|
||
|
||
class Command(NoArgsCommand): | ||
"""The actual clean_history command to clean history rows.""" | ||
|
||
help = "Deletes unneeded rows from the StudentModuleHistory table." | ||
|
||
option_list = NoArgsCommand.option_list + ( | ||
optparse.make_option( | ||
'--batch', | ||
type='int', | ||
default=100, | ||
help="Batch size, number of module_ids to examine in a transaction.", | ||
), | ||
optparse.make_option( | ||
'--dry-run', | ||
action='store_true', | ||
default=False, | ||
help="Don't change the database, just show what would be done.", | ||
), | ||
optparse.make_option( | ||
'--sleep', | ||
type='float', | ||
default=0, | ||
help="Seconds to sleep between batches.", | ||
), | ||
) | ||
|
||
def handle_noargs(self, **options): | ||
# We don't want to see the SQL output from the db layer. | ||
logging.getLogger("django.db.backends").setLevel(logging.INFO) | ||
|
||
smhc = StudentModuleHistoryCleaner( | ||
dry_run=options["dry_run"], | ||
) | ||
smhc.main(batch_size=options["batch"], sleep=options["sleep"]) | ||
|
||
|
||
class StudentModuleHistoryCleaner(object): | ||
"""Logic to clean rows from the StudentModuleHistory table.""" | ||
|
||
DELETE_GAP_SECS = 0.5 # Rows this close can be discarded. | ||
STATE_FILE = "clean_history.json" | ||
BATCH_SIZE = 100 | ||
|
||
def __init__(self, dry_run=False): | ||
self.dry_run = dry_run | ||
self.next_student_module_id = 0 | ||
self.last_student_module_id = 0 | ||
|
||
def main(self, batch_size=None, sleep=0): | ||
"""Invoked from the management command to do all the work.""" | ||
|
||
batch_size = batch_size or self.BATCH_SIZE | ||
|
||
connection.enter_transaction_management() | ||
|
||
self.last_student_module_id = self.get_last_student_module_id() | ||
self.load_state() | ||
|
||
while self.next_student_module_id <= self.last_student_module_id: | ||
for smid in self.module_ids_to_check(batch_size): | ||
try: | ||
self.clean_one_student_module(smid) | ||
except Exception: # pylint: disable=W0703 | ||
trace = traceback.format_exc() | ||
self.say("Couldn't clean student_module_id {}:\n{}".format(smid, trace)) | ||
if not self.dry_run: | ||
self.commit() | ||
self.save_state() | ||
if sleep: | ||
time.sleep(sleep) | ||
|
||
def say(self, message): | ||
""" | ||
Display a message to the user. | ||
|
||
The message will have a trailing newline added to it. | ||
|
||
""" | ||
print message | ||
|
||
def commit(self): | ||
""" | ||
Commit the transaction. | ||
""" | ||
self.say("Committing") | ||
connection.commit() | ||
|
||
def load_state(self): | ||
""" | ||
Load the latest state from disk. | ||
""" | ||
try: | ||
state_file = open(self.STATE_FILE) | ||
except IOError: | ||
self.say("No stored state") | ||
self.next_student_module_id = 0 | ||
else: | ||
with state_file: | ||
state = json.load(state_file) | ||
self.say( | ||
"Loaded stored state: {}".format( | ||
json.dumps(state, sort_keys=True) | ||
) | ||
) | ||
self.next_student_module_id = state['next_student_module_id'] | ||
|
||
def save_state(self): | ||
""" | ||
Save the state to disk. | ||
""" | ||
state = { | ||
'next_student_module_id': self.next_student_module_id, | ||
} | ||
with open(self.STATE_FILE, "w") as state_file: | ||
json.dump(state, state_file) | ||
self.say("Saved state: {}".format(json.dumps(state, sort_keys=True))) | ||
|
||
def get_last_student_module_id(self): | ||
""" | ||
Return the id of the last student_module. | ||
""" | ||
cursor = connection.cursor() | ||
cursor.execute(""" | ||
SELECT max(student_module_id) FROM courseware_studentmodulehistory | ||
""") | ||
last = cursor.fetchone()[0] | ||
self.say("Last student_module_id is {}".format(last)) | ||
return last | ||
|
||
def module_ids_to_check(self, batch_size): | ||
"""Produce a sequence of student module ids to check. | ||
|
||
`batch_size` is how many module ids to produce, max. | ||
|
||
The sequence starts with `next_student_module_id`, and goes up to | ||
and including `last_student_module_id`. | ||
|
||
`next_student_module_id` is updated as each id is yielded. | ||
|
||
""" | ||
start = self.next_student_module_id | ||
for smid in range(start, start+batch_size): | ||
if smid > self.last_student_module_id: | ||
break | ||
yield smid | ||
self.next_student_module_id = smid+1 | ||
|
||
def get_history_for_student_modules(self, student_module_id): | ||
""" | ||
Get the history rows for a student module. | ||
|
||
```student_module_id```: the id of the student module we're | ||
interested in. | ||
|
||
Return a list: [(id, created), ...], all the rows of history. | ||
|
||
""" | ||
cursor = connection.cursor() | ||
cursor.execute(""" | ||
SELECT id, created FROM courseware_studentmodulehistory | ||
WHERE student_module_id = %s | ||
ORDER BY created, id | ||
""", | ||
[student_module_id] | ||
) | ||
history = cursor.fetchall() | ||
return history | ||
|
||
def delete_history(self, ids_to_delete): | ||
""" | ||
Delete history rows. | ||
|
||
```ids_to_delete```: a non-empty list (or set...) of history row ids to delete. | ||
|
||
""" | ||
assert ids_to_delete | ||
cursor = connection.cursor() | ||
cursor.execute(""" | ||
DELETE FROM courseware_studentmodulehistory | ||
WHERE id IN ({ids}) | ||
""".format(ids=",".join(str(i) for i in ids_to_delete)) | ||
) | ||
|
||
def clean_one_student_module(self, student_module_id): | ||
"""Clean one StudentModule's-worth of history. | ||
|
||
`student_module_id`: the id of the StudentModule to process. | ||
|
||
""" | ||
delete_gap = datetime.timedelta(seconds=self.DELETE_GAP_SECS) | ||
|
||
history = self.get_history_for_student_modules(student_module_id) | ||
if not history: | ||
self.say("No history for student_module_id {}".format(student_module_id)) | ||
return | ||
|
||
ids_to_delete = [] | ||
next_created = None | ||
for history_id, created in reversed(history): | ||
if next_created is not None: | ||
# Compare this timestamp with the next one. | ||
if (next_created - created) < delete_gap: | ||
# This row is followed closely by another, we can discard | ||
# this one. | ||
ids_to_delete.append(history_id) | ||
|
||
next_created = created | ||
|
||
verb = "Would have deleted" if self.dry_run else "Deleting" | ||
self.say("{verb} {to_delete} rows of {total} for student_module_id {id}".format( | ||
verb=verb, | ||
to_delete=len(ids_to_delete), | ||
total=len(history), | ||
id=student_module_id, | ||
)) | ||
|
||
if ids_to_delete and not self.dry_run: | ||
self.delete_history(ids_to_delete) |
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.
Is the fact that we're opening the state file every time a problem at all on when the disk is backed by EBS? I don't think it necessarily needs changing, but I am curious if it becomes a factor when you're doing the speed test for this.
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're only saving state once per batch, not once per id, so this should be fine.
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.
Sure, but with these settings, we'd still have over half a million batches. If an open takes 10ms, that's an hour and a half. Probably not worth worrying about at this point -- I'm mostly just curious where this script will actually spend its time.