2 # -*- coding: utf-8 -*-
3 ##############################################################################
5 # OpenERP, Open Source Management Solution
6 # Copyright (C) 2004-2011 OpenERP SA (<http://www.openerp.com>)
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as
10 # published by the Free Software Foundation, either version 3 of the
11 # License, or (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
18 # You should have received a copy of the GNU Affero General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
25 import logging.handlers
35 from pprint import pformat
37 # TODO modules that import netsvc only for things from loglevels must be changed to use loglevels.
38 from loglevels import *
42 def close_socket(sock):
43 """ Closes a socket instance cleanly
45 :param sock: the network socket to close
46 :type sock: socket.socket
49 sock.shutdown(socket.SHUT_RDWR)
50 except socket.error, e:
51 # On OSX, socket shutdowns both sides if any side closes it
52 # causing an error 57 'Socket is not connected' on shutdown
53 # of the other side (or something), see
54 # http://bugs.python.org/issue4397
55 # note: stdlib fixed test, not behavior
56 if e.errno != errno.ENOTCONN or platform.system() != 'Darwin':
61 #.apidoc title: Common Services: netsvc
62 #.apidoc module-mods: member-order: bysource
64 def abort_response(dummy_1, description, dummy_2, details):
65 # TODO Replace except_{osv,orm} with these directly.
66 raise openerp.osv.osv.except_osv(description, details)
68 class Service(object):
69 """ Base class for *Local* services
71 Functionality here is trusted, no authentication.
74 def __init__(self, name):
75 Service._services[name] = self
79 def exists(cls, name):
80 return name in cls._services
83 def remove(cls, name):
85 cls._services.pop(name)
87 def LocalService(name):
88 # Special case for addons support, will be removed in a few days when addons
89 # are updated to directly use openerp.osv.osv.service.
90 if name == 'object_proxy':
91 return openerp.osv.osv.service
93 return Service._services[name]
95 class ExportService(object):
96 """ Proxy for exported services.
98 Note that this class has no direct proxy, capable of calling
99 eservice.method(). Rather, the proxy should call
100 dispatch(method, params)
104 _logger = logging.getLogger('web-services')
106 def __init__(self, name):
107 ExportService._services[name] = self
109 self._logger.debug("Registered an exported service: %s" % name)
112 def getService(cls,name):
113 return cls._services[name]
115 # Dispatch a RPC call w.r.t. the method name. The dispatching
116 # w.r.t. the service (this class) is done by OpenERPDispatcher.
117 def dispatch(self, method, params):
118 raise Exception("stub dispatch at %s" % self.__name)
120 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, _NOTHING, DEFAULT = range(10)
121 #The background is set with 40 plus the number of the color, and the foreground with 30
122 #These are the sequences need to get colored ouput
123 RESET_SEQ = "\033[0m"
124 COLOR_SEQ = "\033[1;%dm"
126 COLOR_PATTERN = "%s%s%%s%s" % (COLOR_SEQ, COLOR_SEQ, RESET_SEQ)
127 LEVEL_COLOR_MAPPING = {
128 logging.DEBUG_SQL: (WHITE, MAGENTA),
129 logging.DEBUG_RPC: (BLUE, WHITE),
130 logging.DEBUG_RPC_ANSWER: (BLUE, WHITE),
131 logging.DEBUG: (BLUE, DEFAULT),
132 logging.INFO: (GREEN, DEFAULT),
133 logging.TEST: (WHITE, BLUE),
134 logging.WARNING: (YELLOW, DEFAULT),
135 logging.ERROR: (RED, DEFAULT),
136 logging.CRITICAL: (WHITE, RED),
139 class DBFormatter(logging.Formatter):
140 def format(self, record):
141 record.dbname = getattr(threading.currentThread(), 'dbname', '?')
142 return logging.Formatter.format(self, record)
144 class ColoredFormatter(DBFormatter):
145 def format(self, record):
146 fg_color, bg_color = LEVEL_COLOR_MAPPING[record.levelno]
147 record.levelname = COLOR_PATTERN % (30 + fg_color, 40 + bg_color, record.levelname)
148 return DBFormatter.format(self, record)
151 from tools.translate import resetlocale
154 # create a format for log messages and dates
155 format = '[%(asctime)s][%(dbname)s] %(levelname)s:%(name)s:%(message)s'
157 if tools.config['syslog']:
160 handler = logging.handlers.NTEventLogHandler("%s %s" % (release.description, release.version))
162 handler = logging.handlers.SysLogHandler('/dev/log')
163 format = '%s %s' % (release.description, release.version) \
164 + ':%(dbname)s:%(levelname)s:%(name)s:%(message)s'
166 elif tools.config['logfile']:
168 logf = tools.config['logfile']
170 dirname = os.path.dirname(logf)
171 if dirname and not os.path.isdir(dirname):
173 if tools.config['logrotate'] is not False:
174 handler = logging.handlers.TimedRotatingFileHandler(logf,'D',1,30)
175 elif os.name == 'posix':
176 handler = logging.handlers.WatchedFileHandler(logf)
178 handler = logging.handlers.FileHandler(logf)
180 sys.stderr.write("ERROR: couldn't create the logfile directory. Logging to the standard output.\n")
181 handler = logging.StreamHandler(sys.stdout)
183 # Normal Handler on standard output
184 handler = logging.StreamHandler(sys.stdout)
186 if isinstance(handler, logging.StreamHandler) and os.isatty(handler.stream.fileno()):
187 formatter = ColoredFormatter(format)
189 formatter = DBFormatter(format)
190 handler.setFormatter(formatter)
192 # add the handler to the root logger
193 logger = logging.getLogger()
195 logger.addHandler(handler)
196 logger.setLevel(int(tools.config['log_level'] or '0'))
198 # A alternative logging scheme for automated runs of the
199 # server intended to test it.
200 def init_alternative_logger():
201 class H(logging.Handler):
202 def emit(self, record):
203 if record.levelno > 20:
204 print record.levelno, record.pathname, record.msg
206 logger = logging.getLogger()
208 logger.addHandler(handler)
209 logger.setLevel(logging.ERROR)
212 """ Generic interface for all servers with an event loop etc.
213 Override this to impement http, net-rpc etc. servers.
215 Servers here must have threaded behaviour. start() must not block,
220 __starter_threads = []
222 # we don't want blocking server calls (think select()) to
223 # wait forever and possibly prevent exiting the process,
224 # but instead we want a form of polling/busy_wait pattern, where
225 # _server_timeout should be used as the default timeout for
226 # all I/O blocking operations
227 _busywait_timeout = 0.5
230 __logger = logging.getLogger('server')
233 Server.__servers.append(self)
234 if Server.__is_started:
235 # raise Exception('All instances of servers must be inited before the startAll()')
236 # Since the startAll() won't be called again, allow this server to
237 # init and then start it after 1sec (hopefully). Register that
238 # timer thread in a list, so that we can abort the start if quitAll
239 # is called in the meantime
240 t = threading.Timer(1.0, self._late_start)
241 t.name = 'Late start timer for %s' % str(self.__class__)
242 Server.__starter_threads.append(t)
246 self.__logger.debug("called stub Server.start")
248 def _late_start(self):
250 for thr in Server.__starter_threads:
251 if thr.finished.is_set():
252 Server.__starter_threads.remove(thr)
255 self.__logger.debug("called stub Server.stop")
258 """ This function should return statistics about the server """
259 return "%s: No statistics" % str(self.__class__)
265 cls.__logger.info("Starting %d services" % len(cls.__servers))
266 for srv in cls.__servers:
268 cls.__is_started = True
272 if not cls.__is_started:
274 cls.__logger.info("Stopping %d services" % len(cls.__servers))
275 for thr in cls.__starter_threads:
276 if not thr.finished.is_set():
278 cls.__starter_threads.remove(thr)
280 for srv in cls.__servers:
282 cls.__is_started = False
286 res = ["Servers %s" % ('stopped', 'started')[cls.__is_started]]
287 res.extend(srv.stats() for srv in cls.__servers)
288 return '\n'.join(res)
290 def _close_socket(self):
291 close_socket(self.socket)
293 def replace_request_password(args):
294 # password is always 3rd argument in a request, we replace it in RPC logs
295 # so it's easier to forward logs for diagnostics/debugging purposes...
301 def log(title, msg, channel=logging.DEBUG_RPC, depth=None, fn=""):
302 logger = logging.getLogger(title)
303 if logger.isEnabledFor(channel):
305 indent_after=' '*len(fn)
306 for line in (fn+pformat(msg, depth=depth)).split('\n'):
307 logger.log(channel, indent+line)
310 def dispatch_rpc(service_name, method, params):
311 """ Handle a RPC call.
313 This is pure Python code, the actual marshalling (from/to XML-RPC or
314 NET-RPC) is done in a upper layer.
316 def _log(title, msg, channel=logging.DEBUG_RPC, depth=None, fn=""):
317 log(title, msg, channel=channel, depth=depth, fn=fn)
319 logger = logging.getLogger('result')
320 start_time = end_time = 0
321 if logger.isEnabledFor(logging.DEBUG_RPC_ANSWER):
322 _log('service', tuple(replace_request_password(params)), depth=None, fn='%s.%s'%(service_name,method))
323 if logger.isEnabledFor(logging.DEBUG_RPC):
324 start_time = time.time()
325 result = ExportService.getService(service_name).dispatch(method, params)
326 if logger.isEnabledFor(logging.DEBUG_RPC):
327 end_time = time.time()
328 if not logger.isEnabledFor(logging.DEBUG_RPC_ANSWER):
329 _log('service (%.3fs)' % (end_time - start_time), tuple(replace_request_password(params)), depth=1, fn='%s.%s'%(service_name,method))
330 _log('execution time', '%.3fs' % (end_time - start_time), channel=logging.DEBUG_RPC_ANSWER)
331 _log('result', result, channel=logging.DEBUG_RPC_ANSWER)
333 except openerp.exceptions.AccessError:
335 except openerp.exceptions.AccessDenied:
337 except openerp.exceptions.Warning:
339 except openerp.exceptions.DeferredException, e:
340 _log('exception', tools.exception_to_unicode(e))
341 post_mortem(e.traceback)
344 _log('exception', tools.exception_to_unicode(e))
345 post_mortem(sys.exc_info())
348 def post_mortem(info):
349 if tools.config['debug_mode'] and isinstance(info[2], types.TracebackType):
351 pdb.post_mortem(info[2])
353 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: