SQLBase.py 22.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#                    Vincent Pelletier <vincent@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

29
import sys
30
import transaction
Julien Muchembled's avatar
Julien Muchembled committed
31
from zLOG import LOG, TRACE, INFO, WARNING, ERROR, PANIC
32
from ZODB.POSException import ConflictError
33 34 35 36
from Products.CMFActivity.ActivityTool import (
  MESSAGE_NOT_EXECUTED, MESSAGE_EXECUTED)
from Products.CMFActivity.ActiveObject import (
  INVOKE_ERROR_STATE, VALIDATE_ERROR_STATE)
37 38
from Products.CMFActivity.ActivityRuntimeEnvironment import (
  ActivityRuntimeEnvironment, getTransactionalVariable)
39 40
from Queue import VALIDATION_ERROR_DELAY

41 42 43
# Stop electing more messages for processing if more than this number of
# objects are impacted by elected messages.
MAX_GROUPED_OBJECTS = 100
44

45 46 47 48 49
def sort_message_key(message):
  # same sort key as in SQL{Dict,Queue}_readMessageList
  return message.line.priority, message.line.date, message.uid


50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
class SQLBase:
  """
    Define a set of common methods for SQL-based storage of activities.
  """
 
  def getNow(self, context):
    """
      Return the current value for SQL server's NOW().
      Note that this value is not cached, and is not transactionnal on MySQL
      side.
    """
    result = context.SQLBase_getNow()
    assert len(result) == 1
    assert len(result[0]) == 1
    return result[0][0]
65

66 67 68
  def getMessageList(self, activity_tool, processing_node=None,
                     include_processing=0, **kw):
    # YO: reading all lines might cause a deadlock
69
    class_name = self.__class__.__name__
70
    readMessageList = getattr(activity_tool,
71
                              class_name + '_readMessageList',
72 73 74 75
                              None)
    if readMessageList is None:
      return []
    return [self.loadMessage(line.message,
76
                             activity=class_name,
77 78
                             uid=line.uid,
                             processing_node=line.processing_node,
79
                             retry=line.retry,
80 81 82 83 84 85 86
                             processing=line.processing)
            for line in readMessageList(path=None,
                                        method_id=None,
                                        processing_node=processing_node,
                                        to_date=None,
                                        include_processing=include_processing)]

87
  def _getPriority(self, activity_tool, method, default):
88
    result = method()
89 90 91 92 93
    assert len(result) == 1
    priority = result[0]['priority']
    if priority is None:
      priority = default
    return priority
94

95
  def _retryOnLockError(self, method, args=(), kw={}):
96 97
    while True:
      try:
98
        return method(*args, **kw)
99 100 101 102
      except ConflictError:
        # Note that this code assumes that a database adapter translates
        # a lock error into a conflict error.
        LOG('SQLBase', INFO, 'Got a lock error, retrying...')
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  def _validate_after_method_id(self, activity_tool, message, value):
    return self._validate(activity_tool, method_id=value)

  def _validate_after_path(self, activity_tool, message, value):
    return self._validate(activity_tool, path=value)

  def _validate_after_message_uid(self, activity_tool, message, value):
    return self._validate(activity_tool, message_uid=value)

  def _validate_after_path_and_method_id(self, activity_tool, message, value):
    if not (isinstance(value, (tuple, list)) and len(value) == 2):
      LOG('CMFActivity', WARNING,
          'unable to recognize value for after_path_and_method_id: %r' % (value,))
      return []
    return self._validate(activity_tool, path=value[0], method_id=value[1])

  def _validate_after_tag(self, activity_tool, message, value):
    return self._validate(activity_tool, tag=value)

  def _validate_after_tag_and_method_id(self, activity_tool, message, value):
    # Count number of occurances of tag and method_id
    if not (isinstance(value, (tuple, list)) and len(value) == 2):
      LOG('CMFActivity', WARNING,
          'unable to recognize value for after_tag_and_method_id: %r' % (value,))
      return []
    return self._validate(activity_tool, tag=value[0], method_id=value[1])

  def _validate_serialization_tag(self, activity_tool, message, value):
    return self._validate(activity_tool, serialization_tag=value)
133 134 135 136 137

  def _log(self, severity, summary):
    LOG(self.__class__.__name__, severity, summary,
        error=severity>INFO and sys.exc_info() or None)

138 139
  def getReservedMessageList(self, activity_tool, date, processing_node,
                             limit=None, group_method_id=None):
140 141 142 143 144 145 146 147 148 149 150
    """
      Get and reserve a list of messages.
      limit
        Maximum number of messages to fetch.
        This number is not garanted to be reached, because of:
         - not enough messages being pending execution
         - race condition (other nodes reserving the same messages at the same
           time)
        This number is guaranted not to be exceeded.
        If None (or not given) no limit apply.
    """
151 152 153
    select = activity_tool.SQLBase_selectReservedMessageList
    result = not group_method_id and select(table=self.sql_table, count=limit,
                                            processing_node=processing_node)
154
    if not result:
155 156 157 158 159
      activity_tool.SQLBase_reserveMessageList(table=self.sql_table,
        count=limit, processing_node=processing_node, to_date=date,
        group_method_id=group_method_id)
      result = select(table=self.sql_table,
                      processing_node=processing_node, count=limit)
160 161 162 163 164 165 166
    return result

  def makeMessageListAvailable(self, activity_tool, uid_list):
    """
      Put messages back in processing_node=0 .
    """
    if len(uid_list):
167 168
      activity_tool.SQLBase_makeMessageListAvailable(table=self.sql_table,
                                                     uid=uid_list)
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

  def getProcessableMessageList(self, activity_tool, processing_node):
    """
      Always true:
        For each reserved message, delete redundant messages when it gets
        reserved (definitely lost, but they are expandable since redundant).

      - reserve a message
      - set reserved message to processing=1 state
      - if this message has a group_method_id:
        - reserve a bunch of BUNDLE_MESSAGE_COUNT messages
        - untill number of impacted objects goes over MAX_GROUPED_OBJECTS
          - get one message from the reserved bunch (this messages will be
            "needed")
          - increase the number of impacted object
        - set "needed" reserved messages to processing=1 state
        - unreserve "unneeded" messages
      - return still-reserved message list and a group_method_id

      If any error happens in above described process, try to unreserve all
      messages already reserved in that process.
      If it fails, complain loudly that some messages might still be in an
      unclean state.

      Returned values:
        4-tuple:
          - list of messages
          - impacted object count
          - group_method_id
          - uid_to_duplicate_uid_list_dict
    """
    def getReservedMessageList(limit, group_method_id=None):
      line_list = self.getReservedMessageList(activity_tool=activity_tool,
                                              date=now_date,
                                              processing_node=processing_node,
                                              limit=limit,
                                              group_method_id=group_method_id)
      if len(line_list):
207
        self._log(TRACE, 'Reserved messages: %r' % [x.uid for x in line_list])
208 209
      return line_list
    def getDuplicateMessageUidList(line):
210
      uid_list = self.getDuplicateMessageUidList(activity_tool=activity_tool,
211 212
        line=line, processing_node=processing_node)
      if len(uid_list):
213
        self._log(TRACE, 'Reserved duplicate messages: %r' % (uid_list, ))
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      return uid_list
    BUNDLE_MESSAGE_COUNT = 100 # Arbitrary number
    now_date = self.getNow(activity_tool)
    message_list = []
    count = 0
    group_method_id = None
    try:
      result = getReservedMessageList(limit=1)
      uid_to_duplicate_uid_list_dict = {}
      if len(result) > 0:
        line = result[0]
        uid = line.uid
        m = self.loadMessage(line.message, uid=uid, line=line)
        message_list.append(m)
        group_method_id = line.group_method_id
229
        activity_tool.SQLBase_processMessage(table=self.sql_table, uid=[uid])
230 231 232 233 234 235 236
        uid_to_duplicate_uid_list_dict.setdefault(uid, []) \
          .extend(getDuplicateMessageUidList(line))
        if group_method_id not in (None, '', '\0'):
          # Count the number of objects to prevent too many objects.
          count += len(m.getObjectList(activity_tool))
          if count < MAX_GROUPED_OBJECTS:
            # Retrieve objects which have the same group method.
237 238
            result = getReservedMessageList(limit=BUNDLE_MESSAGE_COUNT,
                                            group_method_id=group_method_id)
239 240 241 242 243 244 245 246 247 248 249
            path_and_method_id_dict = {}
            unreserve_uid_list = []
            for line in result:
              if line.uid == uid:
                continue
              # All fetched lines have the same group_method_id and
              # processing_node.
              # Their dates are lower-than or equal-to now_date.
              # We read each line once so lines have distinct uids.
              # So what remains to be filtered on are path, method_id and
              # order_validation_text.
250 251 252 253 254 255 256 257 258 259 260 261 262
              try:
                key = line.path, line.method_id, line.order_validation_text
              except AttributeError:
                pass # message_queue does not have 'order_validation_text'
              else:
                original_uid = path_and_method_id_dict.get(key)
                if original_uid is not None:
                  uid_to_duplicate_uid_list_dict.setdefault(original_uid, []) \
                  .append(line.uid)
                  continue
                path_and_method_id_dict[key] = line.uid
                uid_to_duplicate_uid_list_dict.setdefault(line.uid, []) \
                .extend(getDuplicateMessageUidList(line))
263 264 265 266 267 268
              if count < MAX_GROUPED_OBJECTS:
                m = self.loadMessage(line.message, uid=line.uid, line=line)
                count += len(m.getObjectList(activity_tool))
                message_list.append(m)
              else:
                unreserve_uid_list.append(line.uid)
269
            activity_tool.SQLBase_processMessage(table=self.sql_table,
270
              uid=[m.uid for m in message_list])
271
            # Unreserve extra messages as soon as possible.
272 273 274 275
            self.makeMessageListAvailable(activity_tool=activity_tool,
                                          uid_list=unreserve_uid_list)
      return (message_list, count, group_method_id,
              uid_to_duplicate_uid_list_dict)
276
    except:
277
      self._log(WARNING, 'Exception while reserving messages.')
278 279 280
      if len(message_list):
        to_free_uid_list = [m.uid for m in message_list]
        try:
281 282
          self.makeMessageListAvailable(activity_tool=activity_tool,
                                        uid_list=to_free_uid_list)
283
        except:
284
          self._log(ERROR, 'Failed to free messages: %r' % to_free_uid_list)
285 286
        else:
          if len(to_free_uid_list):
287
            self._log(TRACE, 'Freed messages %r' % to_free_uid_list)
288
      else:
289
        self._log(TRACE, '(no message was reserved)')
290 291 292 293 294 295 296 297 298
      return [], 0, None, {}

  # Queue semantic
  def dequeueMessage(self, activity_tool, processing_node):
    def makeMessageListAvailable(uid_list, uid_to_duplicate_uid_list_dict):
      final_uid_list = []
      for uid in uid_list:
        final_uid_list.append(uid)
        final_uid_list.extend(uid_to_duplicate_uid_list_dict.get(uid, []))
299 300
      self.makeMessageListAvailable(activity_tool=activity_tool,
                                    uid_list=final_uid_list)
301 302 303 304 305 306 307 308
    message_list, count, group_method_id, uid_to_duplicate_uid_list_dict = \
      self.getProcessableMessageList(activity_tool, processing_node)
    if message_list:
      # Remove group_id parameter from group_method_id
      if group_method_id is not None:
        group_method_id = group_method_id.split('\0')[0]
      if group_method_id not in (None, ""):
        method  = activity_tool.invokeGroup
309 310
        args = (group_method_id, message_list, self.__class__.__name__,
                self.merge_duplicate)
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        activity_runtime_environment = ActivityRuntimeEnvironment(None)
      else:
        method = activity_tool.invoke
        message = message_list[0]
        args = (message, )
        activity_runtime_environment = ActivityRuntimeEnvironment(message)
      # Commit right before executing messages.
      # As MySQL transaction does not start exactly at the same time as ZODB
      # transactions but a bit later, messages available might be called
      # on objects which are not available - or available in an old
      # version - to ZODB connector.
      # So all connectors must be committed now that we have selected
      # everything needed from MySQL to get a fresh view of ZODB objects.
      transaction.commit()
      tv = getTransactionalVariable(None)
      tv['activity_runtime_environment'] = activity_runtime_environment
      # Try to invoke
      try:
        method(*args)
      except:
331 332 333
        self._log(WARNING,
          'Exception raised when invoking messages (uid, path, method_id) %r'
          % [(m.uid, m.object_path, m.method_id) for m in message_list])
334 335 336
        try:
          transaction.abort()
        except:
337 338 339
          # Unfortunately, database adapters may raise an exception against
          # abort.
          self._log(PANIC,
340 341 342 343 344 345
              'abort failed, thus some objects may be modified accidentally')
          raise
        # XXX Is it still useful to free messages now that this node is able
        #     to reselect them ?
        to_free_uid_list = [x.uid for x in message_list]
        try:
346 347
          makeMessageListAvailable(to_free_uid_list,
                                   uid_to_duplicate_uid_list_dict)
348
        except:
349
          self._log(ERROR, 'Failed to free messages: %r' % to_free_uid_list)
350
        else:
351
          self._log(TRACE, 'Freed messages %r' % to_free_uid_list)
352 353 354 355 356 357 358 359
      # Abort if something failed.
      if [m for m in message_list if m.getExecutionState() == MESSAGE_NOT_EXECUTED]:
        endTransaction = transaction.abort
      else:
        endTransaction = transaction.commit
      try:
        endTransaction()
      except:
360 361 362
        self._log(WARNING,
          'Failed to end transaction for messages (uid, path, method_id) %r'
          % [(m.uid, m.object_path, m.method_id) for m in message_list])
363
        if endTransaction == transaction.abort:
364 365
          self._log(PANIC, 'Failed to abort executed messages.'
            ' Some objects may be modified accidentally.')
366 367 368 369
        else:
          try:
            transaction.abort()
          except:
370 371
            self._log(PANIC, 'Failed to abort executed messages which also'
              ' failed to commit. Some objects may be modified accidentally.')
372 373 374
            raise
        exc_info = sys.exc_info()
        for m in message_list:
375
          m.setExecutionState(MESSAGE_NOT_EXECUTED, exc_info, log=False)
376
        try:
377 378
          makeMessageListAvailable([x.uid for x in message_list],
                                   uid_to_duplicate_uid_list_dict)
379
        except:
380 381
          self._log(ERROR, 'Failed to free remaining messages: %r'
                           % (message_list, ))
382
        else:
383 384 385
          self._log(TRACE, 'Freed messages %r' % (message_list, ))
      self.finalizeMessageExecution(activity_tool, message_list,
                                    uid_to_duplicate_uid_list_dict)
386 387 388
    transaction.commit()
    return not message_list

389 390 391 392 393 394 395
  def finalizeMessageExecution(self, activity_tool, message_list,
                               uid_to_duplicate_uid_list_dict=None):
    """
      If everything was fine, delete all messages.
      If anything failed, make successful messages available (if any), and
      the following rules apply to failed messages:
        - Failures due to ConflictErrors cause messages to be postponed,
396 397
          but their retry count is *not* increased.
        - Failures of messages already above maximum retry count cause them to
398
          be put in a permanent-error state.
399
        - In all other cases, retry count is increased and message is delayed.
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    """
    deletable_uid_list = []
    delay_uid_list = []
    final_error_uid_list = []
    make_available_uid_list = []
    notify_user_list = []
    non_executable_message_list = []
    executed_uid_list = deletable_uid_list
    if uid_to_duplicate_uid_list_dict is not None:
      for m in message_list:
        if m.getExecutionState() == MESSAGE_NOT_EXECUTED:
          executed_uid_list = make_available_uid_list
          break
    for m in message_list:
      uid = m.uid
      if m.getExecutionState() == MESSAGE_EXECUTED:
        executed_uid_list.append(uid)
        if uid_to_duplicate_uid_list_dict is not None:
          executed_uid_list += uid_to_duplicate_uid_list_dict.get(uid, ())
      elif m.getExecutionState() == MESSAGE_NOT_EXECUTED:
        # Should duplicate messages follow strictly the original message, or
        # should they be just made available again ?
        if uid_to_duplicate_uid_list_dict is not None:
          make_available_uid_list += uid_to_duplicate_uid_list_dict.get(uid, ())
        # BACK: Only exceptions can be classes in Python 2.6.
        # Once we drop support for Python 2.4,
        # please, remove the "type(m.exc_type) is type(ConflictError)" check
        # and leave only the "issubclass(m.exc_type, ConflictError)" check.
        if type(m.exc_type) is type(ConflictError) and \
429
           m.conflict_retry and issubclass(m.exc_type, ConflictError):
430 431
          delay_uid_list.append(uid)
        else:
432
          max_retry = m.max_retry
433
          retry = m.line.retry
434 435
          if max_retry is not None and retry >= max_retry:
            # Always notify when we stop retrying.
436
            notify_user_list.append((m, False))
437 438
            final_error_uid_list.append(uid)
            continue
439 440 441
          # In case of infinite retry, notify the user
          # when the default limit is reached.
          if max_retry is None and retry == m.__class__.max_retry:
442
            notify_user_list.append((m, True))
443 444 445 446
          delay = m.delay
          if delay is None:
            # By default, make delay quadratic to the number of retries.
            delay = VALIDATION_ERROR_DELAY * (retry * retry + 1) / 2
447 448 449 450
          try:
            # Immediately update, because values different for every message
            activity_tool.SQLBase_reactivate(table=self.sql_table,
                                             uid=[uid],
451 452
                                             delay=delay,
                                             retry=1)
453
          except:
454 455
            self._log(WARNING, 'Failed to reactivate %r' % uid)
        make_available_uid_list.append(uid)
456 457 458 459 460
      else:
        # Internal CMFActivity error: the message can not be executed because
        # something is missing (context object cannot be found, method cannot
        # be accessed on object).
        non_executable_message_list.append(uid)
461
        notify_user_list.append((m, False))
462 463 464 465 466 467 468 469 470 471 472
    if deletable_uid_list:
      try:
        self._retryOnLockError(activity_tool.SQLBase_delMessage,
                               kw={'table': self.sql_table,
                                   'uid': deletable_uid_list})
      except:
        self._log(ERROR, 'Failed to delete messages %r' % deletable_uid_list)
      else:
        self._log(TRACE, 'Deleted messages %r' % deletable_uid_list)
    if delay_uid_list:
      try:
473
        # If this is a conflict error, do not increase 'retry' but only delay.
474
        activity_tool.SQLBase_reactivate(table=self.sql_table,
475
          uid=delay_uid_list, delay=VALIDATION_ERROR_DELAY, retry=None)
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
      except:
        self._log(ERROR, 'Failed to delay %r' % delay_uid_list)
    if final_error_uid_list:
      try:
        activity_tool.SQLBase_assignMessage(table=self.sql_table,
          uid=final_error_uid_list, processing_node=INVOKE_ERROR_STATE)
      except:
        self._log(ERROR, 'Failed to set message to error state for %r'
                         % final_error_uid_list)
    if non_executable_message_list:
      try:
        activity_tool.SQLBase_assignMessage(table=self.sql_table,
          uid=non_executable_message_list, processing_node=VALIDATE_ERROR_STATE)
      except:
        self._log(ERROR, 'Failed to set message to invalid path state for %r'
                         % non_executable_message_list)
    if make_available_uid_list:
      try:
        self.makeMessageListAvailable(activity_tool=activity_tool,
                                      uid_list=make_available_uid_list)
      except:
        self._log(ERROR, 'Failed to unreserve %r' % make_available_uid_list)
      else:
        self._log(TRACE, 'Freed messages %r' % make_available_uid_list)
    try:
501 502
      for m, retry in notify_user_list:
        m.notifyUser(activity_tool, retry)
503 504 505 506
    except:
      # Notification failures must not cause this method to raise.
      self._log(WARNING,
        'Exception during notification phase of finalizeMessageExecution')