ActivityTool.py 36.9 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#
# 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 31 32 33 34 35
import socket
import urllib
import threading
import sys
from types import TupleType, StringType
import re

Jean-Paul Smets's avatar
Jean-Paul Smets committed
36
from Products.CMFCore import CMFCorePermissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37
from Products.ERP5Type.Core.Folder import Folder
38
from Products.CMFActivity.ActiveResult import ActiveResult
39
from Products.PythonScripts.Utility import allow_class
40
from AccessControl import ClassSecurityInfo, Permissions
Jérome Perrin's avatar
Jérome Perrin committed
41 42 43 44
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.SecurityManagement import setSecurityManager
from AccessControl.SecurityManagement import getSecurityManager
45 46
from Products.CMFCore.utils import UniqueObject, _getAuthenticatedUser, getToolByName
from Globals import InitializeClass, DTMLFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
47
from Acquisition import aq_base
48
from Acquisition import aq_inner
49
from Products.CMFActivity.ActiveObject import DISTRIBUTABLE_STATE, INVOKE_ERROR_STATE, VALIDATE_ERROR_STATE
50
from ActivityBuffer import ActivityBuffer
51
from zExceptions import ExceptionFormatter
52

53
from ZODB.POSException import ConflictError
54
from Products.MailHost.MailHost import MailHostError
Jean-Paul Smets's avatar
Jean-Paul Smets committed
55

56
from zLOG import LOG, INFO, WARNING
57 58

try:
59
  from Products.TimerService import getTimerService
60
except ImportError:
61 62
  def getTimerService(self):
    pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
63

64
# minimal IP:Port regexp
65
NODE_RE = re.compile('^\d+\.\d+\.\d+\.\d+:\d+$')
66

Jean-Paul Smets's avatar
Jean-Paul Smets committed
67 68 69 70 71
# Using a RAM property (not a property of an instance) allows
# to prevent from storing a state in the ZODB (and allows to restart...)
active_threads = 0
max_active_threads = 1 # 2 will cause more bug to appear (he he)
is_initialized = 0
72 73
tic_lock = threading.Lock() # A RAM based lock to prevent too many concurrent tic() calls
timerservice_lock = threading.Lock() # A RAM based lock to prevent TimerService spamming when busy
74
first_run = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
75 76 77 78 79 80 81 82

# Activity Registration
activity_dict = {}
activity_list = []

def registerActivity(activity):
  # Must be rewritten to register
  # class and create instance for each activity
83
  #LOG('Init Activity', 0, str(activity.__name__))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
84 85 86 87 88
  activity_instance = activity()
  activity_list.append(activity_instance)
  activity_dict[activity.__name__] = activity_instance

class Message:
89
  """Activity Message Class.
90

91 92
  Message instances are stored in an activity queue, inside the Activity Tool.
  """
93 94 95
  def __init__(self, obj, active_process, activity_kw, method_id, args, kw):
    if isinstance(obj, str):
      self.object_path = obj.split('/')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
96
    else:
97
      self.object_path = obj.getPhysicalPath()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
98
    if type(active_process) is StringType:
99 100 101 102 103
      self.active_process = active_process.split('/')
    elif active_process is None:
      self.active_process = None
    else:
      self.active_process = active_process.getPhysicalPath()
104
      self.active_process_uid = active_process.getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
105 106 107 108
    self.activity_kw = activity_kw
    self.method_id = method_id
    self.args = args
    self.kw = kw
Jean-Paul Smets's avatar
Jean-Paul Smets committed
109
    self.is_executed = 0
110
    self.exc_type = None
111
    self.exc_value = None
112
    self.processing = None
113 114
    self.user_name = str(_getAuthenticatedUser(self))
    # Store REQUEST Info ?
Jean-Paul Smets's avatar
Jean-Paul Smets committed
115

116
  def getObject(self, activity_tool):
117
    """return the object referenced in this message."""
118
    return activity_tool.unrestrictedTraverse(self.object_path)
119

120
  def getObjectList(self, activity_tool):
121
    """return the list of object that can be expanded from this message."""
122 123 124 125 126 127 128
    try:
      expand_method_id = self.activity_kw['expand_method_id']
      obj = self.getObject(activity_tool)
      # FIXME: how to pass parameters?
      object_list = getattr(obj, expand_method_id)()
    except KeyError:
      object_list = [self.getObject(activity_tool)]
129

130
    return object_list
131

132
  def hasExpandMethod(self):
133 134 135 136 137
    """return true if the message has an expand method.
    An expand method is used to expand the list of objects and to turn a
    big recursive transaction affecting many objects into multiple
    transactions affecting only one object at a time (this can prevent
    duplicated method calls)."""
138
    return self.activity_kw.has_key('expand_method_id')
139

140
  def changeUser(self, user_name, activity_tool):
141
    """restore the security context for the calling user."""
142 143
    uf = activity_tool.getPortalObject().acl_users
    user = uf.getUserById(user_name)
144
    # if the user is not found, try to get it from a parent acl_users
145 146 147 148
    # XXX this is still far from perfect, because we need to store all
    # informations about the user (like original user folder, roles) to
    # replay the activity with exactly the same security context as if
    # it had been executed without activity.
149 150 151
    if user is None:
      uf = activity_tool.getPortalObject().aq_parent.acl_users
      user = uf.getUserById(user_name)
152 153 154
    if user is not None:
      user = user.__of__(uf)
      newSecurityManager(None, user)
155
    else :
156 157
      LOG("CMFActivity", WARNING,
          "Unable to find user %s in the portal" % user_name)
158
      noSecurityManager()
159 160 161 162 163
    return user

  def activateResult(self, activity_tool, result, object):
    if self.active_process is not None:
      active_process = activity_tool.unrestrictedTraverse(self.active_process)
164
      if isinstance(result,ActiveResult):
165 166
        result.edit(object_path=object)
        result.edit(method_id=self.method_id)
167 168
        # XXX Allow other method_id in future
        active_process.activateResult(result)
169
      else:
170
        active_process.activateResult(
171
                    ActiveResult(object_path=object,
172 173
                          method_id=self.method_id,
                          result=result)) # XXX Allow other method_id in future
174

Jean-Paul Smets's avatar
Jean-Paul Smets committed
175
  def __call__(self, activity_tool):
176
    try:
177
      obj = self.getObject(activity_tool)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
178
      # Change user if required (TO BE DONE)
179 180
      # We will change the user only in order to execute this method
      current_user = str(_getAuthenticatedUser(self))
181
      user = self.changeUser(self.user_name, activity_tool)
182 183 184 185 186 187 188
      try:
        result = getattr(obj, self.method_id)(*self.args, **self.kw)
      finally:
        # Use again the previous user
        if user is not None:
          self.changeUser(current_user, activity_tool)
      self.activateResult(activity_tool, result, obj)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
189
      self.is_executed = 1
190
    except:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
191
      self.is_executed = 0
192
      self.exc_type = sys.exc_info()[0]
193
      self.exc_value = str(sys.exc_info()[1])
194 195
      self.traceback = ''.join(ExceptionFormatter.format_exception(
                               *sys.exc_info()))
196
      LOG('ActivityTool', WARNING,
197
          'Could not call method %s on object %s' % (
198
          self.method_id, self.object_path), error=sys.exc_info())
199 200 201
      # push the error in ZODB error_log
      if hasattr(activity_tool, 'error_log'):
        activity_tool.error_log.raising(sys.exc_info())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
202

203 204 205 206 207 208 209
  def validate(self, activity, activity_tool, check_order_validation=1):
    return activity.validate(activity_tool, self,
                             check_order_validation=check_order_validation,
                             **self.activity_kw)

  def getDependentMessageList(self, activity, activity_tool):
    return activity.getDependentMessageList(activity_tool, self, **self.activity_kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
210

211
  def notifyUser(self, activity_tool, message="Failed Processing Activity"):
212 213 214 215 216 217
    """Notify the user that the activity failed."""
    portal = activity_tool.getPortalObject()
    user_email = None
    user = portal.portal_membership.getMemberById(self.user_name)
    if user is not None:
      user_email = user.getProperty('email')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
218
    if user_email in ('', None):
219 220
      user_email = portal.getProperty('email_to_address',
                       portal.getProperty('email_from_address'))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
221
    mail_text = """From: %s
222 223 224 225 226 227 228
To: %s
Subject: %s

%s

Document: %s
Method: %s
229
Exception: %s %s
230

231
%s
232
""" % (activity_tool.email_from_address, user_email, message,
233 234
       message, '/'.join(self.object_path), self.method_id,
       self.exc_type, self.exc_value, self.traceback)
235 236 237 238
    try:
      activity_tool.MailHost.send( mail_text )
    except (socket.error, MailHostError), message:
      LOG('ActivityTool.notifyUser', WARNING, 'Mail containing failure information failed to be sent: %s' % (message, ))
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  def reactivate(self, activity_tool):
    # Reactivate the original object.
    obj= self.getObject(activity_tool)
    # Change user if required (TO BE DONE)
    # We will change the user only in order to execute this method
    current_user = str(_getAuthenticatedUser(self))
    user = self.changeUser(self.user_name, activity_tool)
    try:
      active_obj = obj.activate(**self.activity_kw)
      getattr(active_obj, self.method_id)(*self.args, **self.kw)
    finally:
      # Use again the previous user
      if user is not None:
        self.changeUser(current_user, activity_tool)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
255 256
class Method:

257
  def __init__(self, passive_self, activity, active_process, kw, method_id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
258 259
    self.__passive_self = passive_self
    self.__activity = activity
260
    self.__active_process = active_process
Jean-Paul Smets's avatar
Jean-Paul Smets committed
261 262 263 264
    self.__kw = kw
    self.__method_id = method_id

  def __call__(self, *args, **kw):
265
    m = Message(self.__passive_self, self.__active_process, self.__kw, self.__method_id, args, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
266 267
    activity_dict[self.__activity].queueMessage(self.__passive_self.portal_activities, m)

268 269
allow_class(Method)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
270 271
class ActiveWrapper:

272
  def __init__(self, passive_self, activity, active_process, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
273 274
    self.__dict__['__passive_self'] = passive_self
    self.__dict__['__activity'] = activity
275
    self.__dict__['__active_process'] = active_process
Jean-Paul Smets's avatar
Jean-Paul Smets committed
276 277 278 279
    self.__dict__['__kw'] = kw

  def __getattr__(self, id):
    return Method(self.__dict__['__passive_self'], self.__dict__['__activity'],
280
                  self.__dict__['__active_process'],
Jean-Paul Smets's avatar
Jean-Paul Smets committed
281 282
                  self.__dict__['__kw'], id)

283
class ActivityTool (Folder, UniqueObject):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
284
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
285 286 287 288 289 290 291 292 293 294 295 296
    ActivityTool is the central point for activity management.

    Improvement to consider to reduce locks:

      Idea 1: create an SQL tool which accumulate queries and executes them at the end of a transaction,
              thus allowing all SQL transaction to happen in a very short time
              (this would also be a great way of using MyISAM tables)

      Idea 2: do the same at the level of ActivityTool

      Idea 3: do the same at the level of each activity (ie. queueMessage
              accumulates and fires messages at the end of the transactino)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
297 298 299
    """
    id = 'portal_activities'
    meta_type = 'CMF Activity Tool'
300
    portal_type = 'Activity Tool'
301
    allowed_types = ( 'CMF Active Process', )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
302 303
    security = ClassSecurityInfo()

304 305 306
    _distributingNode = ''
    _nodes = ()

307 308
    manage_options = tuple(
                     [ { 'label' : 'Overview', 'action' : 'manage_overview' }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
309
                     , { 'label' : 'Activities', 'action' : 'manageActivities' }
310
                     , { 'label' : 'LoadBalancing', 'action' : 'manageLoadBalancing'}
311
                     , { 'label' : 'Advanced', 'action' : 'manageActivitiesAdvanced' }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
312
                     ,
313
                     ] + list(Folder.manage_options))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
314 315 316 317

    security.declareProtected( CMFCorePermissions.ManagePortal , 'manageActivities' )
    manageActivities = DTMLFile( 'dtml/manageActivities', globals() )

318 319 320
    security.declareProtected( CMFCorePermissions.ManagePortal , 'manageActivitiesAdvanced' )
    manageActivitiesAdvanced = DTMLFile( 'dtml/manageActivitiesAdvanced', globals() )

321 322
    security.declareProtected( CMFCorePermissions.ManagePortal , 'manage_overview' )
    manage_overview = DTMLFile( 'dtml/explainActivityTool', globals() )
323 324 325 326 327 328
    
    security.declareProtected( CMFCorePermissions.ManagePortal , 'manageLoadBalancing' )
    manageLoadBalancing = DTMLFile( 'dtml/manageLoadBalancing', globals() )
    
    distributingNode = ''
    _nodes = ()
329 330 331

    def __init__(self):
        return Folder.__init__(self, ActivityTool.id)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
332

333 334 335 336 337 338 339 340 341 342
    # Filter content (ZMI))
    def filtered_meta_types(self, user=None):
        # Filters the list of available meta types.
        all = ActivityTool.inheritedAttribute('filtered_meta_types')(self)
        meta_types = []
        for meta_type in self.all_meta_types():
            if meta_type['name'] in self.allowed_types:
                meta_types.append(meta_type)
        return meta_types

Jean-Paul Smets's avatar
Jean-Paul Smets committed
343 344
    def initialize(self):
      global is_initialized
Sebastien Robin's avatar
Sebastien Robin committed
345
      from Activity import RAMQueue, RAMDict, SQLQueue, SQLDict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
346 347 348 349
      # Initialize each queue
      for activity in activity_list:
        activity.initialize(self)
      is_initialized = 1
350 351 352
      
    security.declareProtected(Permissions.manage_properties, 'isSubscribed')
    def isSubscribed(self):
Aurel's avatar
Aurel committed
353
        """
354 355 356 357 358 359 360 361 362 363 364 365
        return True, if we are subscribed to TimerService.
        Otherwise return False.
        """
        service = getTimerService(self)
        if not service:
            LOG('ActivityTool', INFO, 'TimerService not available')
            return False
        
        path = '/'.join(self.getPhysicalPath())
        if path in service.lisSubscriptions():
            return True
        return False
Jean-Paul Smets's avatar
Jean-Paul Smets committed
366

367
    security.declareProtected(Permissions.manage_properties, 'subscribe')
368
    def subscribe(self, REQUEST=None, RESPONSE=None):
369 370
        """ subscribe to the global Timer Service """
        service = getTimerService(self)
371
        url = '%s/manageLoadBalancing?manage_tabs_message=' %self.absolute_url()
372
        if not service:
373
            LOG('ActivityTool', INFO, 'TimerService not available')
374 375 376 377
            url += urllib.quote('TimerService not available')
        else:
            service.subscribe(self)
            url += urllib.quote("Subscribed to Timer Service")
378 379
        if RESPONSE is not None:
            RESPONSE.redirect(url)
380 381

    security.declareProtected(Permissions.manage_properties, 'unsubscribe')
382
    def unsubscribe(self, REQUEST=None, RESPONSE=None):
383 384
        """ unsubscribe from the global Timer Service """
        service = getTimerService(self)
385
        url = '%s/manageLoadBalancing?manage_tabs_message=' %self.absolute_url()
386
        if not service:
387
            LOG('ActivityTool', INFO, 'TimerService not available')
388 389 390 391
            url += urllib.quote('TimerService not available')
        else:
            service.unsubscribe(self)
            url += urllib.quote("Unsubscribed from Timer Service")
392 393
        if RESPONSE is not None:
            RESPONSE.redirect(url)
394 395 396

    def manage_beforeDelete(self, item, container):
        self.unsubscribe()
397 398
        Folder.inheritedAttribute('manage_beforeDelete')(self, item, container)
    
399 400
    def manage_afterAdd(self, item, container):
        self.subscribe()
401 402
        Folder.inheritedAttribute('manage_afterAdd')(self, item, container)
       
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    def getCurrentNode(self):
        """ Return current node in form ip:port """
        port = ''
        from asyncore import socket_map
        for k, v in socket_map.items():
            if hasattr(v, 'port'):
                # see Zope/lib/python/App/ApplicationManager.py: def getServers(self)
                type = str(getattr(v, '__class__', 'unknown'))
                if type == 'ZServer.HTTPServer.zhttp_server':
                    port = v.port
                    break
        ip = socket.gethostbyname(socket.gethostname())
        currentNode = '%s:%s' %(ip, port)
        return currentNode
        
    security.declarePublic('getDistributingNode')
    def getDistributingNode(self):
        """ Return the distributingNode """
        return self.distributingNode

423
    security.declarePublic('getNodeList getNodes')
424 425 426
    def getNodes(self):
        """ Return all nodes """
        return self._nodes
427
    getNodeList = getNodes
428

429 430 431 432
    def _isValidNodeName(self, node_name) :
      """Check we have been provided a good node name"""
      return isinstance(node_name, str) and NODE_RE.match(node_name)
      
433 434
    security.declarePublic('manage_setDistributingNode')
    def manage_setDistributingNode(self, distributingNode, REQUEST=None):
435
        """ set the distributing node """   
436
        if not distributingNode or self._isValidNodeName(distributingNode):
437 438 439 440 441 442 443 444 445 446 447 448 449
          self.distributingNode = distributingNode
          if REQUEST is not None:
              REQUEST.RESPONSE.redirect(
                  REQUEST.URL1 +
                  '/manageLoadBalancing?manage_tabs_message=' +
                  urllib.quote("Distributing Node successfully changed."))
        else :
          if REQUEST is not None:
              REQUEST.RESPONSE.redirect(
                  REQUEST.URL1 +
                  '/manageLoadBalancing?manage_tabs_message=' +
                  urllib.quote("Malformed Distributing Node."))

450 451 452
    security.declarePublic('manage_addNode')
    def manage_addNode(self, node, REQUEST=None):
        """ add a node """
453 454 455 456 457 458 459 460
        if not self._isValidNodeName(node) :
            if REQUEST is not None:
                REQUEST.RESPONSE.redirect(
                    REQUEST.URL1 +
                    '/manageLoadBalancing?manage_tabs_message=' +
                    urllib.quote("Malformed node."))
            return
        
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
        if node in self._nodes:
            if REQUEST is not None:
                REQUEST.RESPONSE.redirect(
                    REQUEST.URL1 +
                    '/manageLoadBalancing?manage_tabs_message=' +
                    urllib.quote("Node exists already."))
            return
            
        self._nodes = self._nodes + (node,)
        
        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(
                REQUEST.URL1 +
                '/manageLoadBalancing?manage_tabs_message=' +
                urllib.quote("Node successfully added."))
                        
    security.declarePublic('manage_delNode')
    def manage_delNode(self, deleteNodes, REQUEST=None):
        """ delete nodes """
        nodeList = list(self._nodes)
        for node in deleteNodes:
            if node in self._nodes:
                nodeList.remove(node)
        self._nodes = tuple(nodeList)
        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(
                REQUEST.URL1 +
                '/manageLoadBalancing?manage_tabs_message=' +
                urllib.quote("Node(s) successfully deleted."))
490

491
    def process_timer(self, tick, interval, prev="", next=""):
492
        """
493 494 495 496 497
        Call distribute() if we are the Distributing Node and call tic()
        with our node number.
        This method is called by TimerService in the interval given
        in zope.conf. The Default is every 5 seconds.
        """
498 499 500 501
        # Prevent TimerService from starting multiple threads in parallel
        acquired = timerservice_lock.acquire(0)
        if not acquired:
          return
502

Jérome Perrin's avatar
Jérome Perrin committed
503
        old_sm = getSecurityManager()
504 505 506
        try:
          # get owner of portal_catalog, so normally we should be able to
          # have the permission to invoke all activities
Jérome Perrin's avatar
Jérome Perrin committed
507
          user = self.portal_catalog.getWrappedOwner()
508
          newSecurityManager(self.REQUEST, user)
509

510
          currentNode = self.getCurrentNode()
511

512
          # only distribute when we are the distributingNode or if it's empty
513
          if (self.distributingNode == currentNode):
Jérome Perrin's avatar
Jérome Perrin committed
514
            self.distribute(len(self._nodes))
515 516

          elif not self.distributingNode:
Jérome Perrin's avatar
Jérome Perrin committed
517
            self.distribute(1)
518

519 520 521 522 523 524 525
          # SkinsTool uses a REQUEST cache to store skin objects, as
          # with TimerService we have the same REQUEST over multiple
          # portals, we clear this cache to make sure the cache doesn't
          # contains skins from another portal.
          stool = getToolByName(self, 'portal_skins', None)
          if stool is not None:
            stool.changeSkin(None)
526

527 528 529 530
          # call tic for the current processing_node
          # the processing_node numbers are the indices of the elements in the node tuple +1
          # because processing_node starts form 1
          if currentNode in self._nodes:
Jérome Perrin's avatar
Jérome Perrin committed
531
            self.tic(list(self._nodes).index(currentNode)+1)
532

533
          elif len(self._nodes) == 0:
Jérome Perrin's avatar
Jérome Perrin committed
534
            self.tic(1)
535

Jérome Perrin's avatar
Jérome Perrin committed
536
        finally:
537
          timerservice_lock.release()
Jérome Perrin's avatar
Jérome Perrin committed
538
          setSecurityManager(old_sm)
539

Jean-Paul Smets's avatar
Jean-Paul Smets committed
540 541 542 543 544 545
    security.declarePublic('distribute')
    def distribute(self, node_count=1):
      """
        Distribute load
      """
      # Initialize if needed
546
      global is_initialized
Jean-Paul Smets's avatar
Jean-Paul Smets committed
547 548 549 550
      if not is_initialized: self.initialize()

      # Call distribute on each queue
      for activity in activity_list:
551
        try:
552
          activity.distribute(aq_inner(self), node_count)
553 554
        except ConflictError:
          raise
555
        except:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
556
          LOG('CMFActivity:', 100, 'Core call to distribute failed for activity %s' % activity, error=sys.exc_info())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
557

Jean-Paul Smets's avatar
Jean-Paul Smets committed
558
    security.declarePublic('tic')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
559
    def tic(self, processing_node=1, force=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
560 561
      """
        Starts again an activity
Jean-Paul Smets's avatar
Jean-Paul Smets committed
562
        processing_node starts from 1 (there is not node 0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
563
      """
564
      global active_threads, is_initialized, first_run
Jean-Paul Smets's avatar
Jean-Paul Smets committed
565 566

      # return if the number of threads is too high
567
      # else, increase the number of active_threads and continue
568 569
      tic_lock.acquire()
      too_many_threads = (active_threads >= max_active_threads)
570
      if not too_many_threads or force:
571
        active_threads += 1
572 573 574
      else:
        tic_lock.release()
        raise RuntimeError, 'Too many threads'
575
      tic_lock.release()
576

Jean-Paul Smets's avatar
Jean-Paul Smets committed
577 578
      # Initialize if needed
      if not is_initialized: self.initialize()
579

580
      inner_self = aq_inner(self)
581

582 583 584
      # If this is the first tic after zope is started, reset the processing
      # flag for activities of this node
      if first_run:
585 586 587 588
        inner_self.SQLDict_clearProcessingFlag(
                                processing_node=processing_node)
        inner_self.SQLQueue_clearProcessingFlag(
                                processing_node=processing_node)
589 590
        first_run = 0

591 592
      try:
        # Wakeup each queue
Jean-Paul Smets's avatar
Jean-Paul Smets committed
593
        for activity in activity_list:
594
          try:
595
            activity.wakeup(inner_self, processing_node)
596 597
          except ConflictError:
            raise
598
          except:
599
            LOG('CMFActivity:', 100, 'Core call to wakeup failed for activity %s' % activity)
600

601 602 603 604 605 606
        # Process messages on each queue in round robin
        has_awake_activity = 1
        while has_awake_activity:
          has_awake_activity = 0
          for activity in activity_list:
            try:
607 608
              activity.tic(inner_self, processing_node) # Transaction processing is the responsability of the activity
              has_awake_activity = has_awake_activity or activity.isAwake(inner_self, processing_node)
609 610 611 612 613 614 615 616 617
            except ConflictError:
              raise
            except:
              LOG('CMFActivity:', 100, 'Core call to tic or isAwake failed for activity %s' % activity, error=sys.exc_info())
      finally:
        # decrease the number of active_threads
        tic_lock.acquire()
        active_threads -= 1
        tic_lock.release()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
618

619
    def hasActivity(self, *args, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
620
      # Check in each queue if the object has deferred tasks
621 622
      # if not argument is provided, then check on self
      if len(args) > 0:
623
        obj = args[0]
624
      else:
625
        obj = self
Jean-Paul Smets's avatar
Jean-Paul Smets committed
626
      for activity in activity_list:
627
        if activity.hasActivity(aq_inner(self), obj, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
628 629 630
          return 1
      return 0

631 632
    security.declarePrivate('activateObject')
    def activateObject(self, object, activity, active_process, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
633 634
      global is_initialized
      if not is_initialized: self.initialize()
635
      if getattr(self, '_v_activity_buffer', None) is None:
636
        self._v_activity_buffer = ActivityBuffer(activity_tool=self)
637
      return ActiveWrapper(object, activity, active_process, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
638

639 640
    def deferredQueueMessage(self, activity, message):
      self._v_activity_buffer.deferredQueueMessage(self, activity, message)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
641

642
    def deferredDeleteMessage(self, activity, message):
643
      if getattr(self, '_v_activity_buffer', None) is None:
644
        self._v_activity_buffer = ActivityBuffer(activity_tool=self)
645
      self._v_activity_buffer.deferredDeleteMessage(self, activity, message)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
646

Jean-Paul Smets's avatar
Jean-Paul Smets committed
647
    def getRegisteredMessageList(self, activity):
648 649 650
      activity_buffer = getattr(self, '_v_activity_buffer', None)
      if activity_buffer is not None:
        activity_buffer._register() # This is required if flush flush is called outside activate
651 652
        return activity.getRegisteredMessageList(self._v_activity_buffer,
                                                 aq_inner(self))
653 654
      else:
        return []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
655

Jean-Paul Smets's avatar
Jean-Paul Smets committed
656
    def unregisterMessage(self, activity, message):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
657
      self._v_activity_buffer._register() # Required if called by flush, outside activate
658
      return activity.unregisterMessage(self._v_activity_buffer, aq_inner(self), message)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
659

660
    def flush(self, obj, invoke=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
661 662
      global is_initialized
      if not is_initialized: self.initialize()
663
      if getattr(self, '_v_activity_buffer', None) is None:
664
        self._v_activity_buffer = ActivityBuffer(activity_tool=self)
665 666
      if isinstance(obj, tuple):
        object_path = obj
667
      else:
668
        object_path = obj.getPhysicalPath()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
669
      for activity in activity_list:
670
        activity.flush(aq_inner(self), object_path, invoke=invoke, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
671

672 673 674 675
    def start(self, **kw):
      global is_initialized
      if not is_initialized: self.initialize()
      for activity in activity_list:
676
        activity.start(aq_inner(self), **kw)
677 678 679 680 681

    def stop(self, **kw):
      global is_initialized
      if not is_initialized: self.initialize()
      for activity in activity_list:
682
        activity.stop(aq_inner(self), **kw)
683

Jean-Paul Smets's avatar
Jean-Paul Smets committed
684 685
    def invoke(self, message):
      message(self)
686

687 688 689 690 691 692 693 694 695
    def invokeGroup(self, method_id, message_list):
      # Invoke a group method.
      object_list = []
      expanded_object_list = []
      new_message_list = []
      path_dict = {}
      # Filter the list of messages. If an object is not available, ignore such a message.
      # In addition, expand an object if necessary, and make sure that no duplication happens.
      for m in message_list:
696 697
        # alternate method is used to segregate objects which cannot be grouped.
        alternate_method_id = m.activity_kw.get('alternate_method_id')
698 699
        try:
          obj = m.getObject(self)
700
          i = len(new_message_list) # This is an index of this message in new_message_list.
701
          if m.hasExpandMethod():
702 703
            for subobj in m.getObjectList(self):
              path = subobj.getPath()
704
              if path not in path_dict:
705
                path_dict[path] = i
706 707 708 709 710 711
                if alternate_method_id is not None \
                   and hasattr(aq_base(subobj), alternate_method_id):
                  # if this object is alternated, generate a new single active object.
                  activity_kw = m.activity_kw.copy()
                  if 'group_method_id' in activity_kw:
                    del activity_kw['group_method_id']
712 713
                  if 'group_id' in activity_kw:
                    del activity_kw['group_id']                    
714 715 716 717
                  active_obj = subobj.activate(**activity_kw)
                  getattr(active_obj, alternate_method_id)(*m.args, **m.kw)
                else:
                  expanded_object_list.append(subobj)
718 719 720
          else:
            path = obj.getPath()
            if path not in path_dict:
721
              path_dict[path] = i
722 723 724 725 726 727 728 729 730 731
              if alternate_method_id is not None \
                  and hasattr(aq_base(obj), alternate_method_id):
                # if this object is alternated, generate a new single active object.
                activity_kw = m.activity_kw.copy()
                if 'group_method_id' in activity_kw:
                  del activity_kw['group_method_id']
                active_obj = obj.activate(**activity_kw)
                getattr(active_obj, alternate_method_id)(*m.args, **m.kw)
              else:
                expanded_object_list.append(obj)
732
          object_list.append(obj)
733 734 735
          new_message_list.append(m)
        except:
          m.is_executed = 0
736
          m.exc_type = sys.exc_info()[0]
737
          LOG('WARNING ActivityTool', 0,
738 739
              'Could not call method %s on object %s' %
              (m.method_id, m.object_path), error=sys.exc_info())
740

741 742
      try:
        if len(expanded_object_list) > 0:
743 744
          method = self.unrestrictedTraverse(method_id)
          # FIXME: how to apply security here?
745 746
          # NOTE: expanded_object_list must be set to failed objects by the callee.
          #       If it fully succeeds, expanded_object_list must be empty when returning.
747
          result = method(expanded_object_list, **m.kw)
748
        else:
749 750 751 752 753 754 755
          result = None
      except:
        # In this case, the group method completely failed.
        for m in new_message_list:
          m.is_executed = 0
          m.exc_type = sys.exc_info()[0]
        LOG('WARNING ActivityTool', 0,
756 757
            'Could not call method %s on objects %s' %
            (method_id, expanded_object_list), error=sys.exc_info())
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
      else:
        # Obtain all indices of failed messages. Note that this can be a partial failure.
        failed_message_dict = {}
        for obj in expanded_object_list:
          path = obj.getPath()
          i = path_dict[path]
          failed_message_dict[i] = None

        # Only for succeeded messages, an activity process is invoked (if any).
        for i in xrange(len(object_list)):
          object = object_list[i]
          m = new_message_list[i]
          if i in failed_message_dict:
            m.is_executed = 0
            LOG('ActivityTool', WARNING,
773 774
                'the method %s partially failed on object %s' %
                (m.method_id, m.object_path,))
775 776 777 778 779
          else:
            try:
              m.activateResult(self, result, object)
              m.is_executed = 1
            except:
780
              m.is_executed = 0
781
              m.exc_type = sys.exc_info()[0]
782
              LOG('ActivityTool', WARNING,
783 784
                  'Could not call method %s on object %s' % (
                  m.method_id, m.object_path), error=sys.exc_info())
785

786 787
    def newMessage(self, activity, path, active_process,
                   activity_kw, method_id, *args, **kw):
788
      # Some Security Cheking should be made here XXX
Jean-Paul Smets's avatar
Jean-Paul Smets committed
789 790
      global is_initialized
      if not is_initialized: self.initialize()
791
      if getattr(self, '_v_activity_buffer', None) is None:
792
        self._v_activity_buffer = ActivityBuffer(activity_tool=self)
793
      activity_dict[activity].queueMessage(aq_inner(self),
794
        Message(path, active_process, activity_kw, method_id, args, kw))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
795

796
    security.declareProtected( CMFCorePermissions.ManagePortal, 'manageInvoke' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
797 798 799 800 801 802
    def manageInvoke(self, object_path, method_id, REQUEST=None):
      """
        Invokes all methods for object "object_path"
      """
      if type(object_path) is type(''):
        object_path = tuple(object_path.split('/'))
803
      self.flush(object_path,method_id=method_id,invoke=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
804
      if REQUEST is not None:
805 806
        return REQUEST.RESPONSE.redirect('%s/%s' %
                (self.absolute_url(), 'manageActivities'))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
807

808
    security.declareProtected( CMFCorePermissions.ManagePortal, 'manageCancel' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
809 810 811 812 813 814
    def manageCancel(self, object_path, method_id, REQUEST=None):
      """
        Cancel all methods for object "object_path"
      """
      if type(object_path) is type(''):
        object_path = tuple(object_path.split('/'))
815
      self.flush(object_path,method_id=method_id,invoke=0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
816
      if REQUEST is not None:
817 818
        return REQUEST.RESPONSE.redirect('%s/%s' %
                (self.absolute_url(), 'manageActivities'))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
819

820 821
    security.declareProtected( CMFCorePermissions.ManagePortal,
                               'manageClearActivities' )
822
    def manageClearActivities(self, keep=1, REQUEST=None):
823 824 825 826 827
      """
        Clear all activities and recreate tables.
      """
      folder = getToolByName(self, 'portal_skins').activity

828 829
      # Obtain all pending messages.
      message_list = []
830 831 832 833 834 835 836 837
      if keep:
        for activity in activity_list:
          if hasattr(activity, 'dumpMessageList'):
            try:
              message_list.extend(activity.dumpMessageList(self))
            except ConflictError:
              raise
            except:
838 839 840
              LOG('ActivityTool', WARNING,
                  'could not dump messages from %s' %
                  (activity,), error=sys.exc_info())
841 842

      if getattr(folder, 'SQLDict_createMessageTable', None) is not None:
843 844 845 846 847
        try:
          folder.SQLDict_dropMessageTable()
        except ConflictError:
          raise
        except:
848
          LOG('CMFActivity', WARNING,
849
              'could not drop the message table',
850 851 852
              error=sys.exc_info())
        folder.SQLDict_createMessageTable()

853
      if getattr(folder, 'SQLQueue_createMessageTable', None) is not None:
854 855 856 857 858
        try:
          folder.SQLQueue_dropMessageTable()
        except ConflictError:
          raise
        except:
859
          LOG('CMFActivity', WARNING,
860
              'could not drop the message queue table',
861 862 863
              error=sys.exc_info())
        folder.SQLQueue_createMessageTable()

864 865 866
      # Reactivate the messages.
      for m in message_list:
        try:
867
          m.reactivate(aq_inner(self))
868 869 870 871
        except ConflictError:
          raise
        except:
          LOG('ActivityTool', WARNING,
872 873
              'could not reactivate the message %r, %r' %
              (m.object_path, m.method_id), error=sys.exc_info())
874

875
      if REQUEST is not None:
876 877
        return REQUEST.RESPONSE.redirect('%s/%s' % (self.absolute_url(),
          'manageActivitiesAdvanced?manage_tabs_message=Activities%20Cleared'))
878

Jean-Paul Smets's avatar
Jean-Paul Smets committed
879
    security.declarePublic('getMessageList')
880
    def getMessageList(self,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
881 882 883
      """
        List messages waiting in queues
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
884 885 886
      # Initialize if needed
      if not is_initialized: self.initialize()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
887 888
      message_list = []
      for activity in activity_list:
Sebastien Robin's avatar
Sebastien Robin committed
889
        try:
890
          message_list += activity.getMessageList(aq_inner(self),**kw)
Sebastien Robin's avatar
Sebastien Robin committed
891 892
        except AttributeError:
          LOG('getMessageList, could not get message from Activity:',0,activity)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
893 894
      return message_list

895 896 897 898 899 900 901
    security.declarePublic('countMessageWithTag')
    def countMessageWithTag(self, value):
      """
        Return the number of messages which match the given tag.
      """
      message_count = 0
      for activity in activity_list:
902
        message_count += activity.countMessageWithTag(aq_inner(self), value)
Sebastien Robin's avatar
Sebastien Robin committed
903 904 905 906 907 908 909 910 911 912
      return message_count

    security.declarePublic('countMessage')
    def countMessage(self, **kw):
      """
        Return the number of messages which match the given parameter.

        Parameters allowed:

        method_id : the id of the method
Jérome Perrin's avatar
Jérome Perrin committed
913
        path : for activities on a particular object
Sebastien Robin's avatar
Sebastien Robin committed
914 915 916 917 918
        tag : activities with a particular tag
        message_uid : activities with a particular uid
      """
      message_count = 0
      for activity in activity_list:
919
        message_count += activity.countMessage(aq_inner(self), **kw)
920 921
      return message_count

922
    security.declareProtected( CMFCorePermissions.ManagePortal , 'newActiveProcess' )
923
    def newActiveProcess(self, **kw):
924 925 926
      from ActiveProcess import addActiveProcess
      new_id = str(self.generateNewId())
      addActiveProcess(self, new_id)
927 928 929
      active_process = self._getOb(new_id)
      active_process.edit(**kw)
      return active_process
930 931 932 933

    def reindexObject(self):
      self.immediateReindexObject()

934
    # Active synchronisation methods
935
    security.declarePrivate('validateOrder')
936
    def validateOrder(self, message, validator_id, validation_value):
937 938 939 940 941
      message_list = self.getDependentMessageList(message, validator_id, validation_value)
      return len(message_list) > 0

    security.declarePrivate('getDependentMessageList')
    def getDependentMessageList(self, message, validator_id, validation_value):
942 943
      global is_initialized
      if not is_initialized: self.initialize()
944
      message_list = []
Vincent Pelletier's avatar
Vincent Pelletier committed
945
      method_id = "_validate_%s" % validator_id
946
      for activity in activity_list:
947 948 949 950 951 952
        method = getattr(activity, method_id, None)
        if method is not None:
          result = method(aq_inner(self), message, validation_value)
          if result:
            message_list.extend([(activity, m) for m in result])
      return message_list
953

Yoshinori Okuji's avatar
Yoshinori Okuji committed
954 955
    # Required for tests (time shift)
    def timeShift(self, delay):
956 957 958
      global is_initialized
      if not is_initialized: self.initialize()
      for activity in activity_list:
959
        activity.timeShift(aq_inner(self), delay)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
960

961
InitializeClass(ActivityTool)