/usr/lib/python2.7/dist-packages/trytond/ir/cron.py is in tryton-server 3.8.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 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 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 | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime
from dateutil.relativedelta import relativedelta
import traceback
import sys
import logging
from email.mime.text import MIMEText
from email.header import Header
from ast import literal_eval
from ..model import ModelView, ModelSQL, fields
from ..tools import get_smtp_server
from ..transaction import Transaction
from ..pool import Pool
from .. import backend
from ..config import config
__all__ = [
'Cron',
]
logger = logging.getLogger(__name__)
_INTERVALTYPES = {
'days': lambda interval: relativedelta(days=interval),
'hours': lambda interval: relativedelta(hours=interval),
'weeks': lambda interval: relativedelta(weeks=interval),
'months': lambda interval: relativedelta(months=interval),
'minutes': lambda interval: relativedelta(minutes=interval),
}
class Cron(ModelSQL, ModelView):
"Cron"
__name__ = "ir.cron"
name = fields.Char('Name', required=True, translate=True)
user = fields.Many2One('res.user', 'Execution User', required=True,
domain=[('active', '=', False)],
help="The user used to execute this action")
request_user = fields.Many2One(
'res.user', 'Request User', required=True,
help="The user who will receive requests in case of failure")
active = fields.Boolean('Active', select=True)
interval_number = fields.Integer('Interval Number', required=True)
interval_type = fields.Selection([
('minutes', 'Minutes'),
('hours', 'Hours'),
('days', 'Days'),
('weeks', 'Weeks'),
('months', 'Months'),
], 'Interval Unit')
number_calls = fields.Integer('Number of Calls', select=1, required=True,
help=('Number of times the function is called, a negative '
'number indicates that the function will always be '
'called'))
repeat_missed = fields.Boolean('Repeat Missed')
next_call = fields.DateTime('Next Call', required=True,
select=True)
model = fields.Char('Model')
function = fields.Char('Function')
args = fields.Text('Arguments')
@classmethod
def __setup__(cls):
super(Cron, cls).__setup__()
cls._error_messages.update({
'request_title': 'Scheduled action failed',
'request_body': ("The following action failed to execute "
"properly: \"%s\"\n%s\n Traceback: \n\n%s\n")
})
@classmethod
def __register__(cls, module_name):
TableHandler = backend.get('TableHandler')
cursor = Transaction().cursor
cron = cls.__table__()
# Migration from 2.0: rename numbercall, doall and nextcall
table = TableHandler(cursor, cls, module_name)
table.column_rename('numbercall', 'number_calls')
table.column_rename('doall', 'repeat_missed')
table.column_rename('nextcall', 'next_call')
table.drop_column('running')
super(Cron, cls).__register__(module_name)
# Migration from 2.0: work_days removed
cursor.execute(*cron.update(
[cron.interval_type], ['days'],
where=cron.interval_type == 'work_days'))
@staticmethod
def default_next_call():
return datetime.datetime.now()
@staticmethod
def default_interval_number():
return 1
@staticmethod
def default_interval_type():
return 'months'
@staticmethod
def default_number_calls():
return -1
@staticmethod
def default_active():
return True
@staticmethod
def default_repeat_missed():
return True
@staticmethod
def check_xml_record(crons, values):
return True
@staticmethod
def get_delta(cron):
'''
Return the relativedelta for the next call
'''
return _INTERVALTYPES[cron.interval_type](cron.interval_number)
@classmethod
def send_error_message(cls, cron):
tb_s = ''.join(traceback.format_exception(*sys.exc_info()))
tb_s = tb_s.decode('utf-8', 'ignore')
subject = cls.raise_user_error('request_title',
raise_exception=False)
body = cls.raise_user_error('request_body',
(cron.name, cron.__url__, tb_s),
raise_exception=False)
from_addr = config.get('email', 'from')
to_addr = cron.request_user.email
msg = MIMEText(body, _charset='utf-8')
msg['To'] = to_addr
msg['From'] = from_addr
msg['Subject'] = Header(subject, 'utf-8')
if not to_addr:
logger.error(msg.as_string())
else:
try:
server = get_smtp_server()
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
except Exception:
logger.error('Unable to deliver email:\n %s',
msg.as_string(), exc_info=True)
@classmethod
def _callback(cls, cron):
pool = Pool()
Config = pool.get('ir.configuration')
try:
args = (cron.args or []) and literal_eval(cron.args)
Model = pool.get(cron.model)
with Transaction().set_user(cron.user.id):
getattr(Model, cron.function)(*args)
except Exception:
Transaction().cursor.rollback()
req_user = cron.request_user
language = (req_user.language.code if req_user.language
else Config.get_language())
with Transaction().set_user(cron.user.id), \
Transaction().set_context(language=language):
cls.send_error_message(cron)
@classmethod
def run(cls, db_name):
now = datetime.datetime.now()
with Transaction().start(db_name, 0) as transaction:
transaction.cursor.lock(cls._table)
crons = cls.search([
('number_calls', '!=', 0),
('next_call', '<=', datetime.datetime.now()),
])
for cron in crons:
try:
next_call = cron.next_call
number_calls = cron.number_calls
first = True
while next_call < now and number_calls != 0:
if first or cron.repeat_missed:
cls._callback(cron)
next_call += cls.get_delta(cron)
if number_calls > 0:
number_calls -= 1
first = False
cron.next_call = next_call
cron.number_calls = number_calls
if not number_calls:
cron.active = False
cron.save()
transaction.cursor.commit()
except Exception:
transaction.cursor.rollback()
logger.error('Running cron %s', cron.id, exc_info=True)
|