1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
33 from cStringIO import StringIO
34 from openerp.tools.translate import _
35 import openerp.netsvc as netsvc
36 import openerp.pooler as pooler
37 import openerp.release as release
38 import openerp.sql_db as sql_db
39 import openerp.tools as tools
40 import openerp.modules
42 #.apidoc title: Exported Service methods
43 #.apidoc module-mods: member-order: bysource
45 """ This python module defines the RPC methods available to remote clients.
47 Each 'Export Service' is a group of 'methods', which in turn are RPC
48 procedures to be called. Each method has its own arguments footprint.
51 # This should be moved to openerp.modules.db, along side initialize().
52 def _initialize_db(serv, id, db_name, demo, lang, user_password):
55 serv.actions[id]['progress'] = 0
56 cr = sql_db.db_connect(db_name).cursor()
57 openerp.modules.db.initialize(cr) # TODO this should be removed as it is done by pooler.restart_pool.
58 tools.config['lang'] = lang
62 pool = pooler.restart_pool(db_name, demo, serv.actions[id],
63 update_module=True)[1]
65 cr = sql_db.db_connect(db_name).cursor()
68 modobj = pool.get('ir.module.module')
69 mids = modobj.search(cr, 1, [('state', '=', 'installed')])
70 modobj.update_translations(cr, 1, mids, lang)
72 cr.execute('UPDATE res_users SET password=%s, context_lang=%s, active=True WHERE login=%s', (
73 user_password, lang, 'admin'))
74 cr.execute('SELECT login, password, name ' \
77 serv.actions[id].update(users=cr.dictfetchall(), clean=True)
81 serv.actions[id].update(clean=False, exception=e)
82 logging.getLogger('db.create').exception('CREATE DATABASE failed:')
83 serv.actions[id]['traceback'] = traceback.format_exc()
87 class db(netsvc.ExportService):
88 def __init__(self, name="db"):
89 netsvc.ExportService.__init__(self, name)
90 self.joinGroup("web-services")
93 self.id_protect = threading.Semaphore()
95 self._pg_psw_env_var_is_set = False # on win32, pg_dump need the PGPASSWORD env var
97 def dispatch(self, method, auth, params):
98 if method in [ 'create', 'get_progress', 'drop', 'dump',
100 'change_admin_password', 'migrate_databases' ]:
103 security.check_super(passwd)
104 elif method in [ 'db_exist', 'list', 'list_lang', 'server_version' ]:
106 # No security check for these methods
109 raise KeyError("Method not found: %s" % method)
110 fn = getattr(self, 'exp_'+method)
113 def new_dispatch(self,method,auth,params):
115 def _create_empty_database(self, name):
116 db = sql_db.db_connect('template1')
119 cr.autocommit(True) # avoid transaction block
120 cr.execute("""CREATE DATABASE "%s" ENCODING 'unicode' TEMPLATE "template0" """ % name)
124 def exp_create(self, db_name, demo, lang, user_password='admin'):
125 self.id_protect.acquire()
128 self.id_protect.release()
130 self.actions[id] = {'clean': False}
132 self._create_empty_database(db_name)
134 logging.getLogger('db.create').info('CREATE DATABASE %s', db_name.lower())
135 create_thread = threading.Thread(target=_initialize_db,
136 args=(self, id, db_name, demo, lang, user_password))
137 create_thread.start()
138 self.actions[id]['thread'] = create_thread
141 def exp_get_progress(self, id):
142 if self.actions[id]['thread'].isAlive():
143 # return openerp.modules.init_progress[db_name]
144 return (min(self.actions[id].get('progress', 0),0.95), [])
146 clean = self.actions[id]['clean']
148 users = self.actions[id]['users']
152 e = self.actions[id]['exception']
156 def exp_drop(self, db_name):
157 sql_db.close_db(db_name)
158 openerp.modules.registry.RegistryManager.clear_caches(db_name)
159 openerp.netsvc.Agent.cancel(db_name)
160 logger = netsvc.Logger()
162 db = sql_db.db_connect('template1')
164 cr.autocommit(True) # avoid transaction block
167 cr.execute('DROP DATABASE "%s"' % db_name)
169 logger.notifyChannel("web-services", netsvc.LOG_ERROR,
170 'DROP DB: %s failed:\n%s' % (db_name, e))
171 raise Exception("Couldn't drop database %s: %s" % (db_name, e))
173 logger.notifyChannel("web-services", netsvc.LOG_INFO,
174 'DROP DB: %s' % (db_name))
179 def _set_pg_psw_env_var(self):
180 if os.name == 'nt' and not os.environ.get('PGPASSWORD', ''):
181 os.environ['PGPASSWORD'] = tools.config['db_password']
182 self._pg_psw_env_var_is_set = True
184 def _unset_pg_psw_env_var(self):
185 if os.name == 'nt' and self._pg_psw_env_var_is_set:
186 os.environ['PGPASSWORD'] = ''
188 def exp_dump(self, db_name):
189 logger = netsvc.Logger()
191 self._set_pg_psw_env_var()
193 cmd = ['pg_dump', '--format=c', '--no-owner']
194 if tools.config['db_user']:
195 cmd.append('--username=' + tools.config['db_user'])
196 if tools.config['db_host']:
197 cmd.append('--host=' + tools.config['db_host'])
198 if tools.config['db_port']:
199 cmd.append('--port=' + str(tools.config['db_port']))
202 stdin, stdout = tools.exec_pg_command_pipe(*tuple(cmd))
207 logger.notifyChannel("web-services", netsvc.LOG_ERROR,
208 'DUMP DB: %s failed\n%s' % (db_name, data))
209 raise Exception, "Couldn't dump database"
210 logger.notifyChannel("web-services", netsvc.LOG_INFO,
211 'DUMP DB: %s' % (db_name))
213 self._unset_pg_psw_env_var()
215 return base64.encodestring(data)
217 def exp_restore(self, db_name, data):
218 logger = netsvc.Logger()
220 self._set_pg_psw_env_var()
222 if self.exp_db_exist(db_name):
223 logger.notifyChannel("web-services", netsvc.LOG_WARNING,
224 'RESTORE DB: %s already exists' % (db_name,))
225 raise Exception, "Database already exists"
227 self._create_empty_database(db_name)
229 cmd = ['pg_restore', '--no-owner']
230 if tools.config['db_user']:
231 cmd.append('--username=' + tools.config['db_user'])
232 if tools.config['db_host']:
233 cmd.append('--host=' + tools.config['db_host'])
234 if tools.config['db_port']:
235 cmd.append('--port=' + str(tools.config['db_port']))
236 cmd.append('--dbname=' + db_name)
239 buf=base64.decodestring(data)
241 tmpfile = (os.environ['TMP'] or 'C:\\') + os.tmpnam()
242 file(tmpfile, 'wb').write(buf)
244 args2.append(' ' + tmpfile)
246 stdin, stdout = tools.exec_pg_command_pipe(*args2)
247 if not os.name == "nt":
248 stdin.write(base64.decodestring(data))
252 raise Exception, "Couldn't restore database"
253 logger.notifyChannel("web-services", netsvc.LOG_INFO,
254 'RESTORE DB: %s' % (db_name))
256 self._unset_pg_psw_env_var()
260 def exp_rename(self, old_name, new_name):
261 sql_db.close_db(old_name)
262 openerp.modules.registry.RegistryManager.clear_caches(old_name)
263 openerp.netsvc.Agent.cancel(old_name)
264 logger = netsvc.Logger()
266 db = sql_db.db_connect('template1')
268 cr.autocommit(True) # avoid transaction block
271 cr.execute('ALTER DATABASE "%s" RENAME TO "%s"' % (old_name, new_name))
273 logger.notifyChannel("web-services", netsvc.LOG_ERROR,
274 'RENAME DB: %s -> %s failed:\n%s' % (old_name, new_name, e))
275 raise Exception("Couldn't rename database %s to %s: %s" % (old_name, new_name, e))
277 fs = os.path.join(tools.config['root_path'], 'filestore')
278 if os.path.exists(os.path.join(fs, old_name)):
279 os.rename(os.path.join(fs, old_name), os.path.join(fs, new_name))
281 logger.notifyChannel("web-services", netsvc.LOG_INFO,
282 'RENAME DB: %s -> %s' % (old_name, new_name))
287 def exp_db_exist(self, db_name):
288 ## Not True: in fact, check if connection to database is possible. The database may exists
289 return bool(sql_db.db_connect(db_name))
291 def exp_list(self, document=False):
292 if not tools.config['list_db'] and not document:
293 raise Exception('AccessDenied')
295 db = sql_db.db_connect('template1')
299 db_user = tools.config["db_user"]
300 if not db_user and os.name == 'posix':
302 db_user = pwd.getpwuid(os.getuid())[0]
304 cr.execute("select decode(usename, 'escape') from pg_user where usesysid=(select datdba from pg_database where datname=%s)", (tools.config["db_name"],))
306 db_user = res and str(res[0])
308 cr.execute("select decode(datname, 'escape') from pg_database where datdba=(select usesysid from pg_user where usename=%s) and datname not in ('template0', 'template1', 'postgres') order by datname", (db_user,))
310 cr.execute("select decode(datname, 'escape') from pg_database where datname not in('template0', 'template1','postgres') order by datname")
311 res = [str(name) for (name,) in cr.fetchall()]
319 def exp_change_admin_password(self, new_password):
320 tools.config['admin_passwd'] = new_password
324 def exp_list_lang(self):
325 return tools.scan_languages()
327 def exp_server_version(self):
328 """ Return the version of the server
329 Used by the client to verify the compatibility with its own version
331 return release.version
333 def exp_migrate_databases(self,databases):
335 from openerp.osv.orm import except_orm
336 from openerp.osv.osv import except_osv
341 l.notifyChannel('migration', netsvc.LOG_INFO, 'migrate database %s' % (db,))
342 tools.config['update']['base'] = True
343 pooler.restart_pool(db, force_demo=False, update_module=True)
344 except except_orm, inst:
345 self.abortResponse(1, inst.name, 'warning', inst.value)
346 except except_osv, inst:
347 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
350 tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback))
351 l.notifyChannel('web-services', netsvc.LOG_ERROR, tb_s)
355 class _ObjectService(netsvc.ExportService):
356 "A common base class for those who have fn(db, uid, password,...) "
358 def common_dispatch(self, method, auth, params):
359 (db, uid, passwd ) = params[0:3]
361 security.check(db,uid,passwd)
362 cr = pooler.get_db(db).cursor()
363 fn = getattr(self, 'exp_'+method)
364 res = fn(cr, uid, *params)
369 class common(_ObjectService):
370 def __init__(self,name="common"):
371 _ObjectService.__init__(self,name)
372 self.joinGroup("web-services")
374 def dispatch(self, method, auth, params):
375 logger = netsvc.Logger()
376 if method == 'login':
377 # At this old dispatcher, we do NOT update the auth proxy
378 res = security.login(params[0], params[1], params[2])
379 msg = res and 'successful login' or 'bad login or password'
380 # TODO log the client ip address..
381 logger.notifyChannel("web-service", netsvc.LOG_INFO, "%s from '%s' using database '%s'" % (msg, params[1], params[0].lower()))
383 elif method == 'logout':
385 auth.logout(params[1])
386 logger.notifyChannel("web-service", netsvc.LOG_INFO,'Logout %s from database %s'%(login,db))
388 elif method in ['about', 'timezone_get', 'get_server_environment',
389 'login_message','get_stats', 'check_connectivity',
390 'list_http_services']:
392 elif method in ['get_available_updates', 'get_migration_scripts', 'set_loglevel', 'get_os_time', 'get_sqlcount']:
395 security.check_super(passwd)
397 raise Exception("Method not found: %s" % method)
399 fn = getattr(self, 'exp_'+method)
403 def new_dispatch(self,method,auth,params):
406 def exp_about(self, extended=False):
407 """Return information about the OpenERP Server.
409 @param extended: if True then return version info
410 @return string if extended is False else tuple
415 OpenERP is an ERP+CRM program for small and medium businesses.
417 The whole source code is distributed under the terms of the
420 (c) 2003-TODAY, Fabien Pinckaers - Tiny sprl''')
423 return info, release.version
426 def exp_timezone_get(self, db, login, password):
427 return tools.misc.get_server_timezone()
429 def exp_get_available_updates(self, contract_id, contract_password):
430 import openerp.tools.maintenance as tm
432 rc = tm.remote_contract(contract_id, contract_password)
434 raise tm.RemoteContractException('This contract does not exist or is not active')
436 return rc.get_available_updates(rc.id, openerp.modules.get_modules_with_version())
438 except tm.RemoteContractException, e:
439 self.abortResponse(1, 'Migration Error', 'warning', str(e))
442 def exp_get_migration_scripts(self, contract_id, contract_password):
444 import openerp.tools.maintenance as tm
446 rc = tm.remote_contract(contract_id, contract_password)
448 raise tm.RemoteContractException('This contract does not exist or is not active')
449 if rc.status != 'full':
450 raise tm.RemoteContractException('Can not get updates for a partial contract')
452 l.notifyChannel('migration', netsvc.LOG_INFO, 'starting migration with contract %s' % (rc.name,))
454 zips = rc.retrieve_updates(rc.id, openerp.modules.get_modules_with_version())
456 from shutil import rmtree, copytree, copy
458 backup_directory = os.path.join(tools.config['root_path'], 'backup', time.strftime('%Y-%m-%d-%H-%M'))
459 if zips and not os.path.isdir(backup_directory):
460 l.notifyChannel('migration', netsvc.LOG_INFO, 'create a new backup directory to \
461 store the old modules: %s' % (backup_directory,))
462 os.makedirs(backup_directory)
465 l.notifyChannel('migration', netsvc.LOG_INFO, 'upgrade module %s' % (module,))
466 mp = openerp.modules.get_module_path(module)
468 if os.path.isdir(mp):
469 copytree(mp, os.path.join(backup_directory, module))
470 if os.path.islink(mp):
475 copy(mp + 'zip', backup_directory)
476 os.unlink(mp + '.zip')
480 base64_decoded = base64.decodestring(zips[module])
482 l.notifyChannel('migration', netsvc.LOG_ERROR, 'unable to read the module %s' % (module,))
485 zip_contents = StringIO(base64_decoded)
489 tools.extract_zip_file(zip_contents, tools.config['addons_path'] )
491 l.notifyChannel('migration', netsvc.LOG_ERROR, 'unable to extract the module %s' % (module, ))
497 l.notifyChannel('migration', netsvc.LOG_ERROR, 'restore the previous version of the module %s' % (module, ))
498 nmp = os.path.join(backup_directory, module)
499 if os.path.isdir(nmp):
500 copytree(nmp, tools.config['addons_path'])
502 copy(nmp+'.zip', tools.config['addons_path'])
506 except tm.RemoteContractException, e:
507 self.abortResponse(1, 'Migration Error', 'warning', str(e))
510 tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback))
511 l.notifyChannel('migration', netsvc.LOG_ERROR, tb_s)
514 def exp_get_server_environment(self):
515 os_lang = '.'.join( [x for x in locale.getdefaultlocale() if x] )
518 environment = '\nEnvironment Information : \n' \
521 %(platform.platform(), platform.os.name)
522 if os.name == 'posix':
523 if platform.system() == 'Linux':
524 lsbinfo = os.popen('lsb_release -a').read()
525 environment += '%s'%(lsbinfo)
527 environment += 'Your System is not lsb compliant\n'
528 environment += 'Operating System Release : %s\n' \
529 'Operating System Version : %s\n' \
530 'Operating System Architecture : %s\n' \
531 'Operating System Locale : %s\n'\
532 'Python Version : %s\n'\
533 'OpenERP-Server Version : %s'\
534 %(platform.release(), platform.version(), platform.architecture()[0],
535 os_lang, platform.python_version(),release.version)
538 def exp_login_message(self):
539 return tools.config.get('login_message', False)
541 def exp_set_loglevel(self, loglevel, logger=None):
543 l.set_loglevel(int(loglevel), logger)
546 def exp_get_stats(self):
548 res = "OpenERP server: %d threads\n" % threading.active_count()
549 res += netsvc.Server.allStats()
552 def exp_list_http_services(self):
553 return http_server.list_http_services()
555 def exp_check_connectivity(self):
556 return bool(sql_db.db_connect('template1'))
558 def exp_get_os_time(self):
561 def exp_get_sqlcount(self):
562 logger = logging.getLogger('db.cursor')
563 if not logger.isEnabledFor(logging.DEBUG_SQL):
564 logger.warning("Counters of SQL will not be reliable unless DEBUG_SQL is set at the server's config.")
565 return sql_db.sql_counter
568 class objects_proxy(netsvc.ExportService):
569 def __init__(self, name="object"):
570 netsvc.ExportService.__init__(self,name)
571 self.joinGroup('web-services')
573 def dispatch(self, method, auth, params):
574 (db, uid, passwd ) = params[0:3]
576 if method == 'obj_list':
577 raise NameError("obj_list has been discontinued via RPC as of 6.0, please query ir.model directly!")
578 if method not in ['execute','exec_workflow']:
579 raise NameError("Method not available %s" % method)
580 security.check(db,uid,passwd)
581 ls = netsvc.LocalService('object_proxy')
582 fn = getattr(ls, method)
583 res = fn(db, uid, *params)
587 def new_dispatch(self,method,auth,params):
593 # - None = end of wizard
595 # Wizard Type: 'form'
600 # TODO: change local request to OSE request/reply pattern
602 class wizard(netsvc.ExportService):
603 def __init__(self, name='wizard'):
604 netsvc.ExportService.__init__(self,name)
605 self.joinGroup('web-services')
611 def dispatch(self, method, auth, params):
612 (db, uid, passwd ) = params[0:3]
614 if method not in ['execute','create']:
615 raise KeyError("Method not supported %s" % method)
616 security.check(db,uid,passwd)
617 fn = getattr(self, 'exp_'+method)
618 res = fn(db, uid, *params)
621 def new_dispatch(self,method,auth,params):
624 def _execute(self, db, uid, wiz_id, datas, action, context):
625 self.wiz_datas[wiz_id].update(datas)
626 wiz = netsvc.LocalService('wizard.'+self.wiz_name[wiz_id])
627 return wiz.execute(db, uid, self.wiz_datas[wiz_id], action, context)
629 def exp_create(self, db, uid, wiz_name, datas=None):
632 #FIXME: this is not thread-safe
634 self.wiz_datas[self.id] = {}
635 self.wiz_name[self.id] = wiz_name
636 self.wiz_uid[self.id] = uid
639 def exp_execute(self, db, uid, wiz_id, datas, action='init', context=None):
643 if wiz_id in self.wiz_uid:
644 if self.wiz_uid[wiz_id] == uid:
645 return self._execute(db, uid, wiz_id, datas, action, context)
647 raise Exception, 'AccessDenied'
649 raise Exception, 'WizardNotFound'
652 # TODO: set a maximum report number per user to avoid DOS attacks
658 class ExceptionWithTraceback(Exception):
659 def __init__(self, msg, tb):
662 self.args = (msg, tb)
664 class report_spool(netsvc.ExportService):
665 def __init__(self, name='report'):
666 netsvc.ExportService.__init__(self, name)
667 self.joinGroup('web-services')
670 self.id_protect = threading.Semaphore()
672 def dispatch(self, method, auth, params):
673 (db, uid, passwd ) = params[0:3]
675 if method not in ['report','report_get']:
676 raise KeyError("Method not supported %s" % method)
677 security.check(db,uid,passwd)
678 fn = getattr(self, 'exp_' + method)
679 res = fn(db, uid, *params)
683 def new_dispatch(self,method,auth,params):
686 def exp_report(self, db, uid, object, ids, datas=None, context=None):
692 self.id_protect.acquire()
695 self.id_protect.release()
697 self._reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None}
699 def go(id, uid, ids, datas, context):
700 cr = pooler.get_db(db).cursor()
704 obj = netsvc.LocalService('report.'+object)
705 (result, format) = obj.create(cr, uid, ids, datas, context)
708 self._reports[id]['exception'] = ExceptionWithTraceback('RML is not available at specified location or not enough data to print!', tb)
709 self._reports[id]['result'] = result
710 self._reports[id]['format'] = format
711 self._reports[id]['state'] = True
712 except Exception, exception:
715 tb_s = "".join(traceback.format_exception(*tb))
716 logger = netsvc.Logger()
717 logger.notifyChannel('web-services', netsvc.LOG_ERROR,
718 'Exception: %s\n%s' % (str(exception), tb_s))
719 if hasattr(exception, 'name') and hasattr(exception, 'value'):
720 self._reports[id]['exception'] = ExceptionWithTraceback(tools.ustr(exception.name), tools.ustr(exception.value))
722 self._reports[id]['exception'] = ExceptionWithTraceback(tools.exception_to_unicode(exception), tb)
723 self._reports[id]['state'] = True
728 thread.start_new_thread(go, (id, uid, ids, datas, context))
731 def _check_report(self, report_id):
732 result = self._reports[report_id]
733 exc = result['exception']
735 self.abortResponse(exc, exc.message, 'warning', exc.traceback)
736 res = {'state': result['state']}
738 if tools.config['reportgz']:
740 res2 = zlib.compress(result['result'])
743 #CHECKME: why is this needed???
744 if isinstance(result['result'], unicode):
745 res2 = result['result'].encode('latin1', 'replace')
747 res2 = result['result']
749 res['result'] = base64.encodestring(res2)
750 res['format'] = result['format']
751 del self._reports[report_id]
754 def exp_report_get(self, db, uid, report_id):
755 if report_id in self._reports:
756 if self._reports[report_id]['uid'] == uid:
757 return self._check_report(report_id)
759 raise Exception, 'AccessDenied'
761 raise Exception, 'ReportNotFound'
764 def start_web_services():
772 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: