from __future__ import absolute_import

from celery.signals import task_prerun, task_postrun, task_sent
from django.db.models.signals import post_save

from sentry.utils import metrics


def record_instance_creation(instance, created, **kwargs):
    if not created:
        return

    metrics.incr('objects.created', instance=instance._meta.db_table)

post_save.connect(
    record_instance_creation,
    weak=False,
    dispatch_uid='record_instance_creation',
)


def _get_task_name(task):
    return task.name or '{0}.{1}'.format(task.__module__, task.__name__)


def record_task_signal(signal, name):
    def handler(task, **kwargs):
        if not isinstance(task, basestring):
            task = _get_task_name(task)
        metrics.incr('jobs.{0}'.format(name), instance=task)

    signal.connect(
        handler,
        weak=False,
        dispatch_uid='sentry.stats.{0}'.format(name),
    )


record_task_signal(task_sent, 'dispatched')
record_task_signal(task_prerun, 'started')
record_task_signal(task_postrun, 'finished')

@@ -82,24 +82,38 @@
 ask_postrun,
+ task_revoked,
  task_sent%0Af
@@ -443,16 +443,35 @@
 ch_uid='
+sentry.stats.tasks.
 record_i
@@ -904,16 +904,22 @@
 y.stats.
+tasks.
 %7B0%7D'.for
@@ -941,51 +941,387 @@
 )%0A%0A%0A
-record_task_signal(task_sent, 'dispatched')
+def task_revoked_handler(task, expired=False, **kwargs):%0A    if not isinstance(task, basestring):%0A        task = _get_task_name(task)%0A    if expired:%0A        metrics.incr('jobs.expired', instance=task)%0A    else:%0A        metrics.incr('jobs.revoked', instance=task)%0A%0A%0Atask_revoked.connect(%0A    task_revoked_handler,%0A    weak=False,%0A    dispatch_uid='sentry.stats.tasks.revoked',%0A)%0A
 %0Arec
@@ -1401,12 +1401,56 @@
 'finished')%0A
+record_task_signal(task_sent, 'dispatched')%0A

Add stats for task revoked