api_helper.py 14.4 KB
Newer Older
1 2 3 4 5 6
"""
Helper lib for instructor_tasks API.

Includes methods to check args for rescoring task, encoding student input,
and task submission logic, including handling the Celery backend.
"""
7 8 9
import hashlib
import json
import logging
Brian Wilson committed
10

11
from django.utils.translation import ugettext as _
12
from util.db import outer_atomic
13

14 15 16 17
from celery.result import AsyncResult
from celery.states import READY_STATES, SUCCESS, FAILURE, REVOKED

from courseware.module_render import get_xqueue_callback_url_prefix
18
from courseware.courses import get_problems_in_section
19 20

from xmodule.modulestore.django import modulestore
21
from opaque_keys.edx.keys import UsageKey
22
from instructor_task.models import InstructorTask, PROGRESS
23 24


25
log = logging.getLogger(__name__)
26 27 28


class AlreadyRunningError(Exception):
29
    """Exception indicating that a background task is already running"""
30 31 32 33 34
    pass


def _task_is_running(course_id, task_type, task_key):
    """Checks if a particular task is already running"""
35 36 37
    running_tasks = InstructorTask.objects.filter(
        course_id=course_id, task_type=task_type, task_key=task_key
    )
38 39
    # exclude states that are "ready" (i.e. not "running", e.g. failure, success, revoked):
    for state in READY_STATES:
40 41
        running_tasks = running_tasks.exclude(task_state=state)
    return len(running_tasks) > 0
42 43 44 45 46 47 48


def _reserve_task(course_id, task_type, task_key, task_input, requester):
    """
    Creates a database entry to indicate that a task is in progress.

    Throws AlreadyRunningError if the task is already in progress.
Brian Wilson committed
49 50
    Includes the creation of an arbitrary value for task_id, to be
    submitted with the task call to celery.
51

Brian Wilson committed
52 53 54 55 56 57
    Note that there is a chance of a race condition here, when two users
    try to run the same task at almost exactly the same time.  One user
    could be after the check and before the create when the second user
    gets to the check.  At that point, both users are able to run their
    tasks simultaneously.  This is deemed a small enough risk to not
    put in further safeguards.
58 59 60
    """

    if _task_is_running(course_id, task_type, task_key):
61
        log.warning("Duplicate task found for task_type %s and task_key %s", task_type, task_key)
62 63
        raise AlreadyRunningError("requested task is already running")

64 65 66 67 68 69 70 71 72 73 74 75
    try:
        most_recent_id = InstructorTask.objects.latest('id').id
    except InstructorTask.DoesNotExist:
        most_recent_id = "None found"
    finally:
        log.warning(
            "No duplicate tasks found: task_type %s, task_key %s, and most recent task_id = %s",
            task_type,
            task_key,
            most_recent_id
        )

76 77
    # Create log entry now, so that future requests will know it's running.
    return InstructorTask.create(course_id, task_type, task_key, task_input, requester)
78 79


80
def _get_xmodule_instance_args(request, task_id):
81 82 83 84 85 86
    """
    Calculate parameters needed for instantiating xmodule instances.

    The `request_info` will be passed to a tracking log function, to provide information
    about the source of the task request.   The `xqueue_callback_url_prefix` is used to
    permit old-style xqueue callbacks directly to the appropriate module in the LMS.
87
    The `task_id` is also passed to the tracking log function.
88 89 90
    """
    request_info = {'username': request.user.username,
                    'ip': request.META['REMOTE_ADDR'],
91
                    'agent': request.META.get('HTTP_USER_AGENT', '').decode('latin1'),
92 93 94 95 96
                    'host': request.META['SERVER_NAME'],
                    }

    xmodule_instance_args = {'xqueue_callback_url_prefix': get_xqueue_callback_url_prefix(request),
                             'request_info': request_info,
97
                             'task_id': task_id,
98 99 100 101 102 103 104 105
                             }
    return xmodule_instance_args


def _update_instructor_task(instructor_task, task_result):
    """
    Updates and possibly saves a InstructorTask entry based on a task Result.

Brian Wilson committed
106
    Used when updated status is requested.
107 108 109 110 111

    The `instructor_task` that is passed in is updated in-place, but
    is usually not saved.  In general, tasks that have finished (either with
    success or failure) should have their entries updated by the task itself,
    so are not updated here.  Tasks that are still running are not updated
112
    and saved while they run.  The one exception to the no-save rule are tasks that
113 114 115
    are in a "revoked" state.  This may mean that the task never had the
    opportunity to update the InstructorTask entry.

116 117 118 119 120 121
    Tasks that are in progress and have subtasks doing the processing do not look
    to the task's AsyncResult object.  When subtasks are running, the
    InstructorTask object itself is updated with the subtasks' progress,
    not any AsyncResult object.  In this case, the InstructorTask is
    not updated at all.

122
    Calculates json to store in "task_output" field of the `instructor_task`,
Brian Wilson committed
123
    as well as updating the task_state.
124

Brian Wilson committed
125 126 127
    For a successful task, the json contains the output of the task result.
    For a failed task, the json contains "exception", "message", and "traceback"
    keys.   A revoked task just has a "message" stating it was revoked.
128 129 130 131 132 133 134 135 136 137
    """
    # Pull values out of the result object as close to each other as possible.
    # If we wait and check the values later, the values for the state and result
    # are more likely to have changed.  Pull the state out first, and
    # then code assuming that the result may not exactly match the state.
    task_id = task_result.task_id
    result_state = task_result.state
    returned_result = task_result.result
    result_traceback = task_result.traceback

138 139 140 141
    # Assume we don't always save the InstructorTask entry if we don't have to,
    # but that in most cases we will update the InstructorTask in-place with its
    # current progress.
    entry_needs_updating = True
142
    entry_needs_saving = False
143
    task_output = None
144

145
    if instructor_task.task_state == PROGRESS and len(instructor_task.subtasks) > 0:
146 147 148 149 150 151 152
        # This happens when running subtasks:  the result object is marked with SUCCESS,
        # meaning that the subtasks have successfully been defined.  However, the InstructorTask
        # will be marked as in PROGRESS, until the last subtask completes and marks it as SUCCESS.
        # We want to ignore the parent SUCCESS if subtasks are still running, and just trust the
        # contents of the InstructorTask.
        entry_needs_updating = False
    elif result_state in [PROGRESS, SUCCESS]:
153 154
        # construct a status message directly from the task result's result:
        # it needs to go back with the entry passed in.
Brian Wilson committed
155
        log.info("background task (%s), state %s:  result: %s", task_id, result_state, returned_result)
156
        task_output = InstructorTask.create_output_for_success(returned_result)
157 158 159 160 161
    elif result_state == FAILURE:
        # on failure, the result's result contains the exception that caused the failure
        exception = returned_result
        traceback = result_traceback if result_traceback is not None else ''
        log.warning("background task (%s) failed: %s %s", task_id, returned_result, traceback)
162
        task_output = InstructorTask.create_output_for_failure(exception, result_traceback)
163 164 165 166 167 168
    elif result_state == REVOKED:
        # on revocation, the result's result doesn't contain anything
        # but we cannot rely on the worker thread to set this status,
        # so we set it here.
        entry_needs_saving = True
        log.warning("background task (%s) revoked.", task_id)
169
        task_output = InstructorTask.create_output_for_revoked()
170

Brian Wilson committed
171 172 173
    # save progress and state into the entry, even if it's not being saved:
    # when celery is run in "ALWAYS_EAGER" mode, progress needs to go back
    # with the entry passed in.
174 175 176 177
    if entry_needs_updating:
        instructor_task.task_state = result_state
        if task_output is not None:
            instructor_task.task_output = task_output
178

179 180
        if entry_needs_saving:
            instructor_task.save()
181 182


Brian Wilson committed
183 184 185
def get_updated_instructor_task(task_id):
    """
    Returns InstructorTask object corresponding to a given `task_id`.
186

Brian Wilson committed
187 188 189
    If the InstructorTask thinks the task is still running, then
    the task's result is checked to return an updated state and output.
    """
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    # First check if the task_id is known
    try:
        instructor_task = InstructorTask.objects.get(task_id=task_id)
    except InstructorTask.DoesNotExist:
        log.warning("query for InstructorTask status failed: task_id=(%s) not found", task_id)
        return None

    # if the task is not already known to be done, then we need to query
    # the underlying task's result object:
    if instructor_task.task_state not in READY_STATES:
        result = AsyncResult(task_id)
        _update_instructor_task(instructor_task, result)

    return instructor_task


Brian Wilson committed
206
def get_status_from_instructor_task(instructor_task):
207
    """
Brian Wilson committed
208
    Get the status for a given InstructorTask entry.
209 210

    Returns a dict, with the following keys:
Brian Wilson committed
211 212 213
      'task_id': id assigned by LMS and used by celery.
      'task_state': state of task as stored in celery's result store.
      'in_progress': boolean indicating if task is still running.
214 215
      'task_progress': dict containing progress information.  This includes:
          'attempted': number of attempts made
216
          'succeeded': number of attempts that "succeeded"
217 218 219
          'total': number of possible subtasks to attempt
          'action_name': user-visible verb to use in status messages.  Should be past-tense.
          'duration_ms': how long the task has (or had) been running.
Brian Wilson committed
220 221 222
          'exception': name of exception class raised in failed tasks.
          'message': returned for failed and revoked tasks.
          'traceback': optional, returned if task failed and produced a traceback.
223

224
     """
225 226
    status = {}

227 228 229 230 231 232 233
    if instructor_task is not None:
        # status basic information matching what's stored in InstructorTask:
        status['task_id'] = instructor_task.task_id
        status['task_state'] = instructor_task.task_state
        status['in_progress'] = instructor_task.task_state not in READY_STATES
        if instructor_task.task_output is not None:
            status['task_progress'] = json.loads(instructor_task.task_output)
234 235 236 237

    return status


238
def check_arguments_for_rescoring(usage_key):
239 240 241
    """
    Do simple checks on the descriptor to confirm that it supports rescoring.

242
    Confirms first that the usage_key is defined (since that's currently typed
243 244 245 246
    in).  An ItemNotFoundException is raised if the corresponding module
    descriptor doesn't exist.  NotImplementedError is raised if the
    corresponding module doesn't support rescoring calls.
    """
247
    descriptor = modulestore().get_item(usage_key)
248 249 250 251 252
    if not hasattr(descriptor, 'module_class') or not hasattr(descriptor.module_class, 'rescore_problem'):
        msg = "Specified module does not support rescoring."
        raise NotImplementedError(msg)


253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
def check_entrance_exam_problems_for_rescoring(exam_key):  # pylint: disable=invalid-name
    """
    Grabs all problem descriptors in exam and checks each descriptor to
    confirm that it supports re-scoring.

    An ItemNotFoundException is raised if the corresponding module
    descriptor doesn't exist for exam_key. NotImplementedError is raised if
    any of the problem in entrance exam doesn't support re-scoring calls.
    """
    problems = get_problems_in_section(exam_key).values()
    if any(not hasattr(problem, 'module_class') or not hasattr(problem.module_class, 'rescore_problem')
           for problem in problems):
        msg = _("Not all problems in entrance exam support re-scoring.")
        raise NotImplementedError(msg)


269
def encode_problem_and_student_input(usage_key, student=None):  # pylint: disable=invalid-name
270
    """
271
    Encode optional usage_key and optional student into task_key and task_input values.
272

273 274 275
    Args:
        usage_key (Location): The usage_key identifying the problem.
        student (User): the student affected
276
    """
277

278
    assert isinstance(usage_key, UsageKey)
279
    if student is not None:
280 281
        task_input = {'problem_url': usage_key.to_deprecated_string(), 'student': student.username}
        task_key_stub = "{student}_{problem}".format(student=student.id, problem=usage_key.to_deprecated_string())
282
    else:
283 284
        task_input = {'problem_url': usage_key.to_deprecated_string()}
        task_key_stub = "_{problem}".format(problem=usage_key.to_deprecated_string())
285 286 287 288 289 290 291

    # create the key value by using MD5 hash:
    task_key = hashlib.md5(task_key_stub).hexdigest()

    return task_input, task_key


292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
def encode_entrance_exam_and_student_input(usage_key, student=None):  # pylint: disable=invalid-name
    """
    Encode usage_key and optional student into task_key and task_input values.

    Args:
        usage_key (Location): The usage_key identifying the entrance exam.
        student (User): the student affected
    """
    assert isinstance(usage_key, UsageKey)
    if student is not None:
        task_input = {'entrance_exam_url': unicode(usage_key), 'student': student.username}
        task_key_stub = "{student}_{entranceexam}".format(student=student.id, entranceexam=unicode(usage_key))
    else:
        task_input = {'entrance_exam_url': unicode(usage_key)}
        task_key_stub = "_{entranceexam}".format(entranceexam=unicode(usage_key))

    # create the key value by using MD5 hash:
    task_key = hashlib.md5(task_key_stub).hexdigest()

    return task_input, task_key


314
def submit_task(request, task_type, task_class, course_key, task_input, task_key):
315 316 317
    """
    Helper method to submit a task.

318
    Reserves the requested task, based on the `course_key`, `task_type`, and `task_key`,
319 320 321
    checking to see if the task is already running.  The `task_input` is also passed so that
    it can be stored in the resulting InstructorTask entry.  Arguments are extracted from
    the `request` provided by the originating server request.  Then the task is submitted to run
Brian Wilson committed
322
    asynchronously, using the specified `task_class` and using the task_id constructed for it.
323

324
    Cannot be inside an atomic block.
Brian Wilson committed
325

326
    `AlreadyRunningError` is raised if the task is already running.
327
    """
328 329 330 331 332
    with outer_atomic():
        # check to see if task is already running, and reserve it otherwise:
        instructor_task = _reserve_task(course_key, task_type, task_key, task_input, request.user)

    # make sure all data has been committed before handing off task to celery.
333

Brian Wilson committed
334
    task_id = instructor_task.task_id
335
    task_args = [instructor_task.id, _get_xmodule_instance_args(request, task_id)]
Brian Wilson committed
336
    task_class.apply_async(task_args, task_id=task_id)
337

338
    return instructor_task