iro/controller/task.py
changeset 302 3f4bdea2abbf
parent 294 0e75bd39767d
equal deleted inserted replaced
90:eb04ac3a8327 302:3f4bdea2abbf
       
     1 # Copyright (c) 2012 netzguerilla.net <iro@netzguerilla.net>
       
     2 # 
       
     3 # This file is part of Iro.
       
     4 # 
       
     5 # Permission is hereby granted, free of charge, to any person obtaining a copy of
       
     6 # this software and associated documentation files (the "Software"), to deal in
       
     7 # the Software without restriction, including without limitation the rights to use,
       
     8 # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
       
     9 # #Software, and to permit persons to whom the Software is furnished to do so,
       
    10 # subject to the following conditions:
       
    11 # 
       
    12 # The above copyright notice and this permission notice shall be included in
       
    13 # all copies or substantial portions of the Software.
       
    14 # 
       
    15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
       
    16 # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
       
    17 # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
       
    18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
       
    19 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
       
    20 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    21 
       
    22 from functools import partial
       
    23 
       
    24 from twisted.python import log
       
    25 from twisted.internet.defer import inlineCallbacks, returnValue, maybeDeferred, Deferred
       
    26 
       
    27 from ..error import NoRouteForTask, RejectRecipient
       
    28 
       
    29 from ..model.offer import offers
       
    30 from ..model.job import exJobs
       
    31 
       
    32 from .pool  import taskPool
       
    33 
       
    34 class Task:
       
    35     '''A Task is one message to one recipient and is a part of one :class:`iro.model.job.ExJob`.
       
    36     '''
       
    37     def __init__(self, recipient, job):
       
    38         """
       
    39         :param recipient: a recipient
       
    40         :param `iro.model.job.ExJob` job: connected job
       
    41         """
       
    42         self.recipient = recipient
       
    43         self.job = job
       
    44         self.status = None
       
    45         self.error = False
       
    46 
       
    47     def setStatus(self,status):
       
    48         """callback, to set status of task"""
       
    49         self.status = status
       
    50         return status
       
    51 
       
    52     def setError(self, error):
       
    53         """errback to set error of task"""
       
    54         self.status = error
       
    55         self.error = True
       
    56         return error
       
    57 
       
    58     def start(self):
       
    59         """Starting to send message to recipient.
       
    60 
       
    61         :return: a defer, that is fired, when message is sended successfully over any offer.
       
    62         """
       
    63         self.d = Deferred()
       
    64         self.d.addCallback(self.setStatus)
       
    65         self.d.addCallback(partial(self.job.setStatus,self))
       
    66         self.d.addErrback(self.setError)
       
    67         self.d.addErrback(partial(self.job.setError,self))
       
    68         taskPool.run(self._run)
       
    69         return self.d
       
    70 
       
    71     def _run(self):
       
    72         """sends the message to recipient, tries all possible offers."""
       
    73         os= iter(self.job.offers)
       
    74         def n():
       
    75             try:
       
    76                 offer = os.next()
       
    77                 d = maybeDeferred(offers[offer],self.recipient,self.job.message)
       
    78                 d.addCallback(self.d.callback)
       
    79                 d.addErrback(addErr,offer)
       
    80                 d.addErrback(self.d.errback)
       
    81                 return d
       
    82             except StopIteration:
       
    83                 self.d.errback(NoRouteForTask())
       
    84 
       
    85         def addErr(failure, offer):
       
    86             if not isinstance(failure.value, RejectRecipient):  
       
    87                 log.err(_why="Job(%s): Send to '%s' failed via '%s'"%(self.job.dbjob, self.recipient, offer),_stuff=failure)
       
    88             n()
       
    89         
       
    90         n()
       
    91 
       
    92 
       
    93 @inlineCallbacks
       
    94 def createJob(user,recipients, msg, offers, info=None):
       
    95     """Creates a :class:`iro.model.job.ExJob` and start for all recipients one task.
       
    96     
       
    97     :param `iro.model.schema.User` user: the sender 
       
    98     :param `iro.model.message.Message` msg: the message
       
    99     :param list offers: a list of possible offer and provider names, to try to send the message over. The first entry will be tried first.
       
   100     :param string info: a bill group name
       
   101     :return: the new :class:`iro.model.job.ExJob` object.
       
   102     """
       
   103     job = yield exJobs.create(user, recipients, msg, offers, info)
       
   104     for r in recipients:
       
   105         task = Task(r,job)
       
   106         job.addTask(task)
       
   107         task.start()
       
   108     returnValue(job)