views.py 11.5 KB
Newer Older
1 2 3 4 5

import json
import logging

from django.http import HttpResponse
6
from django.utils.translation import ugettext as _
7 8 9

from celery.states import FAILURE, REVOKED, READY_STATES

Brian Wilson committed
10 11
from instructor_task.api_helper import (get_status_from_instructor_task,
                                        get_updated_instructor_task)
12
from instructor_task.models import PROGRESS
13 14 15 16


log = logging.getLogger(__name__)

Brian Wilson committed
17 18 19
# return status for completed tasks and tasks in progress
STATES_WITH_STATUS = [state for state in READY_STATES] + [PROGRESS]

20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
def _get_instructor_task_status(task_id):
    """
    Returns status for a specific task.

    Written as an internal method here (rather than as a helper)
    so that get_task_completion_info() can be called without
    causing a circular dependency (since it's also called directly).
    """
    instructor_task = get_updated_instructor_task(task_id)
    status = get_status_from_instructor_task(instructor_task)
    if instructor_task is not None and instructor_task.task_state in STATES_WITH_STATUS:
        succeeded, message = get_task_completion_info(instructor_task)
        status['message'] = message
        status['succeeded'] = succeeded
    return status


38 39 40 41 42 43
def instructor_task_status(request):
    """
    View method that returns the status of a course-related task or tasks.

    Status is returned as a JSON-serialized dict, wrapped as the content of a HTTPResponse.

44
    The task_id can be specified to this view in one of two ways:
45 46 47 48 49 50 51 52 53 54 55

    * by making a request containing 'task_id' as a parameter with a single value
      Returns a dict containing status information for the specified task_id

    * by making a request containing 'task_ids' as a parameter,
      with a list of task_id values.
      Returns a dict of dicts, with the task_id as key, and the corresponding
      dict containing status information for the specified task_id

      Task_id values that are unrecognized are skipped.

Brian Wilson committed
56
    The dict with status information for a task contains the following keys:
Brian Wilson committed
57 58 59
      'message': on complete tasks, status message reporting on final progress,
          or providing exception message if failed.  For tasks in progress,
          indicates the current progress.
60
      'succeeded': on complete tasks or tasks in progress, boolean value indicates if the
Brian Wilson committed
61
          task outcome was successful:  did it achieve what it set out to do.
Brian Wilson committed
62 63 64 65 66 67 68
          This is in contrast with a successful task_state, which indicates that the
          task merely completed.
      '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.
      'task_progress': dict containing progress information.  This includes:
          'attempted': number of attempts made
69
          'succeeded': number of attempts that "succeeded"
Brian Wilson committed
70 71 72 73 74 75 76
          '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.
          '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.

77 78 79 80
    """
    output = {}
    if 'task_id' in request.REQUEST:
        task_id = request.REQUEST['task_id']
81
        output = _get_instructor_task_status(task_id)
82 83 84
    elif 'task_ids[]' in request.REQUEST:
        tasks = request.REQUEST.getlist('task_ids[]')
        for task_id in tasks:
85
            task_output = _get_instructor_task_status(task_id)
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
            if task_output is not None:
                output[task_id] = task_output

    return HttpResponse(json.dumps(output, indent=4))


def get_task_completion_info(instructor_task):
    """
    Construct progress message from progress information in InstructorTask entry.

    Returns (boolean, message string) duple, where the boolean indicates
    whether the task completed without incident.  (It is possible for a
    task to attempt many sub-tasks, such as rescoring many students' problem
    responses, and while the task runs to completion, some of the students'
    responses could not be rescored.)

    Used for providing messages to instructor_task_status(), as well as
    external calls for providing course task submission history information.
    """
    succeeded = False

Brian Wilson committed
107
    if instructor_task.task_state not in STATES_WITH_STATUS:
108
        return (succeeded, _("No status information available"))
Brian Wilson committed
109 110

    # we're more surprised if there is no output for a completed task, but just warn:
111
    if instructor_task.task_output is None:
112 113
        log.warning(_("No task_output information found for instructor_task {0}").format(instructor_task.task_id))
        return (succeeded, _("No status information available"))
114

Brian Wilson committed
115 116 117
    try:
        task_output = json.loads(instructor_task.task_output)
    except ValueError:
118
        fmt = _("No parsable task_output information found for instructor_task {0}: {1}")
Brian Wilson committed
119
        log.warning(fmt.format(instructor_task.task_id, instructor_task.task_output))
120
        return (succeeded, _("No parsable status information available"))
121

Brian Wilson committed
122
    if instructor_task.task_state in [FAILURE, REVOKED]:
123
        return (succeeded, task_output.get('message', _('No message provided')))
Brian Wilson committed
124

125
    if any([key not in task_output for key in ['action_name', 'attempted', 'total']]):
126
        fmt = _("Invalid task_output information found for instructor_task {0}: {1}")
Brian Wilson committed
127
        log.warning(fmt.format(instructor_task.task_id, instructor_task.task_output))
128
        return (succeeded, _("No progress status information available"))
Brian Wilson committed
129

130
    action_name = _(task_output['action_name'])    # pylint: disable=translation-of-non-string
131 132
    num_attempted = task_output['attempted']
    num_total = task_output['total']
Brian Wilson committed
133

134 135 136 137
    # In earlier versions of this code, the key 'updated' was used instead of
    # (the more general) 'succeeded'.  In order to support history that may contain
    # output with the old key, we check for values with both the old and the current
    # key, and simply sum them.
138 139 140
    num_succeeded = task_output.get('updated', 0) + task_output.get('succeeded', 0)
    num_skipped = task_output.get('skipped', 0)

Brian Wilson committed
141
    student = None
142 143
    problem_url = None
    email_id = None
Brian Wilson committed
144 145 146
    try:
        task_input = json.loads(instructor_task.task_input)
    except ValueError:
147
        fmt = _("No parsable task_input information found for instructor_task {0}: {1}")
Brian Wilson committed
148 149 150
        log.warning(fmt.format(instructor_task.task_id, instructor_task.task_input))
    else:
        student = task_input.get('student')
151
        problem_url = task_input.get('problem_url')
152
        entrance_exam_url = task_input.get('entrance_exam_url')
153
        email_id = task_input.get('email_id')
154

Brian Wilson committed
155 156
    if instructor_task.task_state == PROGRESS:
        # special message for providing progress updates:
157
        # Translators: {action} is a past-tense verb that is localized separately. {attempted} and {succeeded} are counts.
158
        msg_format = _("Progress: {action} {succeeded} of {attempted} so far")
159 160
    elif student is not None and problem_url is not None:
        # this reports on actions on problems for a particular student:
161
        if num_attempted == 0:
162 163
            # Translators: {action} is a past-tense verb that is localized separately. {student} is a student identifier.
            msg_format = _("Unable to find submission to be {action} for student '{student}'")
164
        elif num_succeeded == 0:
165 166
            # Translators: {action} is a past-tense verb that is localized separately. {student} is a student identifier.
            msg_format = _("Problem failed to be {action} for student '{student}'")
167 168
        else:
            succeeded = True
169 170
            # Translators: {action} is a past-tense verb that is localized separately. {student} is a student identifier.
            msg_format = _("Problem successfully {action} for student '{student}'")
171 172 173 174 175 176 177 178 179 180 181
    elif student is not None and entrance_exam_url is not None:
        # this reports on actions on entrance exam for a particular student:
        if num_attempted == 0:
            # Translators: {action} is a past-tense verb that is localized separately.
            # {student} is a student identifier.
            msg_format = _("Unable to find entrance exam submission to be {action} for student '{student}'")
        else:
            succeeded = True
            # Translators: {action} is a past-tense verb that is localized separately.
            # {student} is a student identifier.
            msg_format = _("Entrance exam successfully {action} for student '{student}'")
182 183 184
    elif student is None and problem_url is not None:
        # this reports on actions on problems for all students:
        if num_attempted == 0:
185 186
            # Translators: {action} is a past-tense verb that is localized separately.
            msg_format = _("Unable to find any students with submissions to be {action}")
187
        elif num_succeeded == 0:
188 189
            # Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
            msg_format = _("Problem failed to be {action} for any of {attempted} students")
190
        elif num_succeeded == num_attempted:
191
            succeeded = True
192 193
            # Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
            msg_format = _("Problem successfully {action} for {attempted} students")
194
        else:  # num_succeeded < num_attempted
195 196
            # Translators: {action} is a past-tense verb that is localized separately. {succeeded} and {attempted} are counts.
            msg_format = _("Problem {action} for {succeeded} of {attempted} students")
197 198 199
    elif email_id is not None:
        # this reports on actions on bulk emails
        if num_attempted == 0:
200 201
            # Translators: {action} is a past-tense verb that is localized separately.
            msg_format = _("Unable to find any recipients to be {action}")
202
        elif num_succeeded == 0:
203 204
            # Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
            msg_format = _("Message failed to be {action} for any of {attempted} recipients ")
205
        elif num_succeeded == num_attempted:
206
            succeeded = True
207 208
            # Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
            msg_format = _("Message successfully {action} for {attempted} recipients")
209
        else:  # num_succeeded < num_attempted
210 211
            # Translators: {action} is a past-tense verb that is localized separately. {succeeded} and {attempted} are counts.
            msg_format = _("Message {action} for {succeeded} of {attempted} recipients")
212 213
    else:
        # provide a default:
214 215
        # Translators: {action} is a past-tense verb that is localized separately. {succeeded} and {attempted} are counts.
        msg_format = _("Status: {action} {succeeded} of {attempted}")
216 217

    if num_skipped > 0:
218 219
        # Translators: {skipped} is a count.  This message is appended to task progress status messages.
        msg_format += _(" (skipping {skipped})")
220

Brian Wilson committed
221
    if student is None and num_attempted != num_total:
222 223
        # Translators: {total} is a count.  This message is appended to task progress status messages.
        msg_format += _(" (out of {total})")
224 225

    # Update status in task result object itself:
226 227 228 229 230 231
    message = msg_format.format(
        action=action_name,
        succeeded=num_succeeded,
        attempted=num_attempted,
        total=num_total,
        skipped=num_skipped,
232 233
        student=student
    )
234
    return (succeeded, message)