| 1 |
from django.core.exceptions import ImproperlyConfigured |
| 2 |
from django.core.management import call_command |
| 3 |
from django.apps import apps |
| 4 |
|
| 5 |
from .conf import settings |
| 6 |
|
| 7 |
from haystack import connections, connection_router |
| 8 |
from haystack.exceptions import NotHandled as IndexNotFoundException |
| 9 |
|
| 10 |
from celery import current_app |
| 11 |
from celery.utils.log import get_task_logger |
| 12 |
|
| 13 |
logger = get_task_logger(__name__) |
| 14 |
|
| 15 |
|
| 16 |
@current_app.register_task |
| 17 |
class CeleryHaystackSignalHandler(current_app.Task): |
| 18 |
name = "haystack_signal_handler" |
| 19 |
using = settings.CELERY_HAYSTACK_DEFAULT_ALIAS |
| 20 |
max_retries = settings.CELERY_HAYSTACK_MAX_RETRIES |
| 21 |
default_retry_delay = settings.CELERY_HAYSTACK_RETRY_DELAY |
| 22 |
ignore_result = settings.CELERY_HAYSTACK_IGNORE_RESULT |
| 23 |
store_errors_even_if_ignored = True |
| 24 |
|
| 25 |
def split_identifier(self, identifier, **kwargs): |
| 26 |
""" |
| 27 |
Break down the identifier representing the instance. |
| 28 |
|
| 29 |
Converts 'notes.note.23' into ('notes.note', 23). |
| 30 |
""" |
| 31 |
bits = identifier.split('.') |
| 32 |
|
| 33 |
if len(bits) < 2: |
| 34 |
logger.error("Unable to parse object " |
| 35 |
"identifer '%s'. Moving on..." % identifier) |
| 36 |
return (None, None) |
| 37 |
|
| 38 |
pk = bits[-1] |
| 39 |
|
| 40 |
object_path = '.'.join(bits[:-1]) |
| 41 |
return (object_path, pk) |
| 42 |
|
| 43 |
def get_model_class(self, object_path, **kwargs): |
| 44 |
""" |
| 45 |
Fetch the model's class in a standarized way. |
| 46 |
""" |
| 47 |
bits = object_path.split('.') |
| 48 |
app_name = '.'.join(bits[:-1]) |
| 49 |
classname = bits[-1] |
| 50 |
model_class = apps.get_model(app_name, classname) |
| 51 |
|
| 52 |
if model_class is None: |
| 53 |
raise ImproperlyConfigured("Could not load model '%s'." % |
| 54 |
object_path) |
| 55 |
return model_class |
| 56 |
|
| 57 |
def get_instance(self, model_class, pk, **kwargs): |
| 58 |
""" |
| 59 |
Fetch the instance in a standarized way. |
| 60 |
""" |
| 61 |
instance = None |
| 62 |
try: |
| 63 |
instance = model_class._default_manager.get(pk=pk) |
| 64 |
except model_class.DoesNotExist: |
| 65 |
logger.error("Couldn't load %s.%s.%s. Somehow it went missing?" % |
| 66 |
(model_class._meta.app_label.lower(), |
| 67 |
model_class._meta.object_name.lower(), pk)) |
| 68 |
except model_class.MultipleObjectsReturned: |
| 69 |
logger.error("More than one object with pk %s. Oops?" % pk) |
| 70 |
return instance |
| 71 |
|
| 72 |
def get_indexes(self, model_class, **kwargs): |
| 73 |
""" |
| 74 |
Fetch the model's registered ``SearchIndex`` in a standarized way. |
| 75 |
""" |
| 76 |
try: |
| 77 |
using_backends = connection_router.for_write(**{'models': [model_class]}) |
| 78 |
for using in using_backends: |
| 79 |
index_holder = connections[using].get_unified_index() |
| 80 |
yield index_holder.get_index(model_class), using |
| 81 |
except IndexNotFoundException: |
| 82 |
raise ImproperlyConfigured("Couldn't find a SearchIndex for %s." % |
| 83 |
model_class) |
| 84 |
|
| 85 |
def run(self, queue, **kwargs): |
| 86 |
"""Trigger actual index handler for a list of actions.""" |
| 87 |
for action, identifier in queue: |
| 88 |
self._run_one(action, identifier) |
| 89 |
|
| 90 |
def _run_one(self, action, identifier, **kwargs): |
| 91 |
""" |
| 92 |
Trigger the actual index handler depending on the |
| 93 |
given action ('update' or 'delete'). |
| 94 |
""" |
| 95 |
|
| 96 |
object_path, pk = self.split_identifier(identifier, **kwargs) |
| 97 |
if object_path is None or pk is None: |
| 98 |
msg = "Couldn't handle object with identifier %s" % identifier |
| 99 |
logger.error(msg) |
| 100 |
raise ValueError(msg) |
| 101 |
|
| 102 |
|
| 103 |
model_class = self.get_model_class(object_path, **kwargs) |
| 104 |
for current_index, using in self.get_indexes(model_class, **kwargs): |
| 105 |
current_index_name = ".".join([current_index.__class__.__module__, |
| 106 |
current_index.__class__.__name__]) |
| 107 |
|
| 108 |
if action == 'delete': |
| 109 |
|
| 110 |
|
| 111 |
try: |
| 112 |
current_index.remove_object(identifier, using=using) |
| 113 |
except Exception as exc: |
| 114 |
logger.exception(exc) |
| 115 |
self.retry(exc=exc) |
| 116 |
else: |
| 117 |
msg = ("Deleted '%s' (with %s)" % |
| 118 |
(identifier, current_index_name)) |
| 119 |
logger.debug(msg) |
| 120 |
elif action == 'update': |
| 121 |
|
| 122 |
instance = self.get_instance(model_class, pk, **kwargs) |
| 123 |
if instance is None: |
| 124 |
logger.debug("Failed updating '%s' (with %s)" % |
| 125 |
(identifier, current_index_name)) |
| 126 |
raise ValueError("Couldn't load object '%s'" % identifier) |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
try: |
| 131 |
current_index.update_object(instance, using=using) |
| 132 |
except Exception as exc: |
| 133 |
logger.exception(exc) |
| 134 |
self.retry(exc=exc) |
| 135 |
else: |
| 136 |
msg = ("Updated '%s' (with %s)" % |
| 137 |
(identifier, current_index_name)) |
| 138 |
logger.debug(msg) |
| 139 |
else: |
| 140 |
logger.error("Unrecognized action '%s'. Moving on..." % action) |
| 141 |
raise ValueError("Unrecognized action %s" % action) |
| 142 |
|
| 143 |
|
| 144 |
@current_app.register_task |
| 145 |
class CeleryHaystackUpdateIndex(current_app.Task): |
| 146 |
""" |
| 147 |
A celery task class to be used to call the update_index management |
| 148 |
command from Celery. |
| 149 |
""" |
| 150 |
name = "haystack_update_index" |
| 151 |
|
| 152 |
def run(self, apps=None, **kwargs): |
| 153 |
defaults = { |
| 154 |
'batchsize': settings.CELERY_HAYSTACK_COMMAND_BATCH_SIZE, |
| 155 |
'age': settings.CELERY_HAYSTACK_COMMAND_AGE, |
| 156 |
'remove': settings.CELERY_HAYSTACK_COMMAND_REMOVE, |
| 157 |
'using': [settings.CELERY_HAYSTACK_DEFAULT_ALIAS], |
| 158 |
'workers': settings.CELERY_HAYSTACK_COMMAND_WORKERS, |
| 159 |
'verbosity': settings.CELERY_HAYSTACK_COMMAND_VERBOSITY, |
| 160 |
} |
| 161 |
defaults.update(kwargs) |
| 162 |
if apps is None: |
| 163 |
apps = settings.CELERY_HAYSTACK_COMMAND_APPS |
| 164 |
|
| 165 |
logger.info("Starting update index") |
| 166 |
call_command('update_index', *apps, **defaults) |
| 167 |
logger.info("Finishing update index") |