SQLBase.py 10.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 30
import sys
from zLOG import LOG, TRACE, INFO, WARNING, ERROR
31
from ZODB.POSException import ConflictError
32 33 34 35 36 37
from Products.CMFActivity.ActivityTool import (
  MESSAGE_NOT_EXECUTED, MESSAGE_EXECUTED)
from Products.CMFActivity.ActiveObject import (
  INVOKE_ERROR_STATE, VALIDATE_ERROR_STATE)
from Queue import VALIDATION_ERROR_DELAY

38
MAX_RETRY = 5
39

40

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
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]
56

57 58 59
  def getMessageList(self, activity_tool, processing_node=None,
                     include_processing=0, **kw):
    # YO: reading all lines might cause a deadlock
60
    class_name = self.__class__.__name__
61
    readMessageList = getattr(activity_tool,
62
                              class_name + '_readMessageList',
63 64 65 66
                              None)
    if readMessageList is None:
      return []
    return [self.loadMessage(line.message,
67
                             activity=class_name,
68 69
                             uid=line.uid,
                             processing_node=line.processing_node,
70
                             retry=line.retry,
71 72 73 74 75 76 77
                             processing=line.processing)
            for line in readMessageList(path=None,
                                        method_id=None,
                                        processing_node=processing_node,
                                        to_date=None,
                                        include_processing=include_processing)]

78
  def _getPriority(self, activity_tool, method, default):
79
    result = method()
80 81 82 83 84
    assert len(result) == 1
    priority = result[0]['priority']
    if priority is None:
      priority = default
    return priority
85

86
  def _retryOnLockError(self, method, args=(), kw={}):
87 88
    while True:
      try:
89
        return method(*args, **kw)
90 91 92 93
      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...')
94

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  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)
124 125 126 127 128 129 130 131 132 133 134 135

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

  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,
136 137
          but their retry count is *not* increased.
        - Failures of messages already above maximum retry count cause them to
138
          be put in a permanent-error state.
139
        - In all other cases, retry count is increased and message is delayed.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    """
    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 \
           issubclass(m.exc_type, ConflictError):
          delay_uid_list.append(uid)
        else:
172 173 174 175 176 177 178
          retry = m.line.retry
          if retry >= MAX_RETRY:
            notify_user_list.append(m)
            final_error_uid_list.append(uid)
            continue
          # XXX: What about making delay quadratic to the number of retries ?
          delay = VALIDATION_ERROR_DELAY #* (retry * retry + 1) / 2
179 180 181 182
          try:
            # Immediately update, because values different for every message
            activity_tool.SQLBase_reactivate(table=self.sql_table,
                                             uid=[uid],
183 184
                                             delay=delay,
                                             retry=1)
185
          except:
186 187
            self._log(WARNING, 'Failed to reactivate %r' % uid)
        make_available_uid_list.append(uid)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
      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)
    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:
204
        # If this is a conflict error, do not increase 'retry' but only delay.
205
        activity_tool.SQLBase_reactivate(table=self.sql_table,
206
          uid=delay_uid_list, delay=VALIDATION_ERROR_DELAY, retry=None)
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
      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:
      for m in notify_user_list:
        m.notifyUser(activity_tool)
    except:
      # Notification failures must not cause this method to raise.
      self._log(WARNING,
        'Exception during notification phase of finalizeMessageExecution')