##// END OF EJS Templates
moved out celerypylons import to enviromnet to prevent celery from displaying celeryconfig.py warning
marcink -
r1006:02246101 beta
parent child Browse files
Show More
@@ -1,81 +1,86 b''
1 """Pylons environment configuration"""
1 """Pylons environment configuration"""
2
3 import os
4 import logging
5
2 from mako.lookup import TemplateLookup
6 from mako.lookup import TemplateLookup
3 from pylons.configuration import PylonsConfig
7 from pylons.configuration import PylonsConfig
4 from pylons.error import handle_mako_error
8 from pylons.error import handle_mako_error
9
10 import rhodecode.lib.app_globals as app_globals
11 import rhodecode.lib.helpers
12
5 from rhodecode.config.routing import make_map
13 from rhodecode.config.routing import make_map
14 from rhodecode.lib import celerypylons
6 from rhodecode.lib.auth import set_available_permissions, set_base_path
15 from rhodecode.lib.auth import set_available_permissions, set_base_path
7 from rhodecode.lib.utils import repo2db_mapper, make_ui, set_rhodecode_config
16 from rhodecode.lib.utils import repo2db_mapper, make_ui, set_rhodecode_config
8 from rhodecode.model import init_model
17 from rhodecode.model import init_model
9 from rhodecode.model.scm import ScmModel
18 from rhodecode.model.scm import ScmModel
10 from sqlalchemy import engine_from_config
19 from sqlalchemy import engine_from_config
11 import logging
12 import os
13 import rhodecode.lib.app_globals as app_globals
14 import rhodecode.lib.helpers
15
20
16 log = logging.getLogger(__name__)
21 log = logging.getLogger(__name__)
17
22
18 def load_environment(global_conf, app_conf, initial=False):
23 def load_environment(global_conf, app_conf, initial=False):
19 """Configure the Pylons environment via the ``pylons.config``
24 """Configure the Pylons environment via the ``pylons.config``
20 object
25 object
21 """
26 """
22 config = PylonsConfig()
27 config = PylonsConfig()
23
28
24 # Pylons paths
29 # Pylons paths
25 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26 paths = dict(root=root,
31 paths = dict(root=root,
27 controllers=os.path.join(root, 'controllers'),
32 controllers=os.path.join(root, 'controllers'),
28 static_files=os.path.join(root, 'public'),
33 static_files=os.path.join(root, 'public'),
29 templates=[os.path.join(root, 'templates')])
34 templates=[os.path.join(root, 'templates')])
30
35
31 # Initialize config with the basic options
36 # Initialize config with the basic options
32 config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)
37 config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)
33
38
34 config['routes.map'] = make_map(config)
39 config['routes.map'] = make_map(config)
35 config['pylons.app_globals'] = app_globals.Globals(config)
40 config['pylons.app_globals'] = app_globals.Globals(config)
36 config['pylons.h'] = rhodecode.lib.helpers
41 config['pylons.h'] = rhodecode.lib.helpers
37
42
38 # Setup cache object as early as possible
43 # Setup cache object as early as possible
39 import pylons
44 import pylons
40 pylons.cache._push_object(config['pylons.app_globals'].cache)
45 pylons.cache._push_object(config['pylons.app_globals'].cache)
41
46
42 # Create the Mako TemplateLookup, with the default auto-escaping
47 # Create the Mako TemplateLookup, with the default auto-escaping
43 config['pylons.app_globals'].mako_lookup = TemplateLookup(
48 config['pylons.app_globals'].mako_lookup = TemplateLookup(
44 directories=paths['templates'],
49 directories=paths['templates'],
45 error_handler=handle_mako_error,
50 error_handler=handle_mako_error,
46 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
51 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
47 input_encoding='utf-8', default_filters=['escape'],
52 input_encoding='utf-8', default_filters=['escape'],
48 imports=['from webhelpers.html import escape'])
53 imports=['from webhelpers.html import escape'])
49
54
50 #sets the c attribute access when don't existing attribute are accessed
55 #sets the c attribute access when don't existing attribute are accessed
51 config['pylons.strict_tmpl_context'] = True
56 config['pylons.strict_tmpl_context'] = True
52 test = os.path.split(config['__file__'])[-1] == 'test.ini'
57 test = os.path.split(config['__file__'])[-1] == 'test.ini'
53 if test:
58 if test:
54 from rhodecode.lib.utils import create_test_env, create_test_index
59 from rhodecode.lib.utils import create_test_env, create_test_index
55 from rhodecode.tests import TESTS_TMP_PATH
60 from rhodecode.tests import TESTS_TMP_PATH
56 create_test_env(TESTS_TMP_PATH, config)
61 create_test_env(TESTS_TMP_PATH, config)
57 create_test_index(TESTS_TMP_PATH, True)
62 create_test_index(TESTS_TMP_PATH, True)
58
63
59 #MULTIPLE DB configs
64 #MULTIPLE DB configs
60 # Setup the SQLAlchemy database engine
65 # Setup the SQLAlchemy database engine
61 if config['debug'] and not test:
66 if config['debug'] and not test:
62 #use query time debugging.
67 #use query time debugging.
63 from rhodecode.lib.timerproxy import TimerProxy
68 from rhodecode.lib.timerproxy import TimerProxy
64 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.',
69 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.',
65 proxy=TimerProxy())
70 proxy=TimerProxy())
66 else:
71 else:
67 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
72 sa_engine_db1 = engine_from_config(config, 'sqlalchemy.db1.')
68
73
69 init_model(sa_engine_db1)
74 init_model(sa_engine_db1)
70 #init baseui
75 #init baseui
71 config['pylons.app_globals'].baseui = make_ui('db')
76 config['pylons.app_globals'].baseui = make_ui('db')
72
77
73 g = config['pylons.app_globals']
78 g = config['pylons.app_globals']
74 repo2db_mapper(ScmModel().repo_scan(g.paths[0][1], g.baseui))
79 repo2db_mapper(ScmModel().repo_scan(g.paths[0][1], g.baseui))
75 set_available_permissions(config)
80 set_available_permissions(config)
76 set_base_path(config)
81 set_base_path(config)
77 set_rhodecode_config(config)
82 set_rhodecode_config(config)
78 # CONFIGURATION OPTIONS HERE (note: all config options will override
83 # CONFIGURATION OPTIONS HERE (note: all config options will override
79 # any Pylons config options)
84 # any Pylons config options)
80
85
81 return config
86 return config
@@ -1,106 +1,105 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.lib.celerylib.__init__
3 rhodecode.lib.celerylib.__init__
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
5
6 celery libs for RhodeCode
6 celery libs for RhodeCode
7
7
8 :created_on: Nov 27, 2010
8 :created_on: Nov 27, 2010
9 :author: marcink
9 :author: marcink
10 :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
10 :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
11 :license: GPLv3, see COPYING for more details.
11 :license: GPLv3, see COPYING for more details.
12 """
12 """
13 # This program is free software; you can redistribute it and/or
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; version 2
15 # as published by the Free Software Foundation; version 2
16 # of the License or (at your opinion) any later version of the license.
16 # of the License or (at your opinion) any later version of the license.
17 #
17 #
18 # This program is distributed in the hope that it will be useful,
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
21 # GNU General Public License for more details.
22 #
22 #
23 # You should have received a copy of the GNU General Public License
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
26 # MA 02110-1301, USA.
26 # MA 02110-1301, USA.
27
27
28 import os
28 import os
29 import sys
29 import sys
30 import socket
30 import socket
31 import traceback
31 import traceback
32 import logging
32 import logging
33
33
34 from hashlib import md5
34 from hashlib import md5
35 from decorator import decorator
35 from decorator import decorator
36 from vcs.utils.lazy import LazyProperty
36 from vcs.utils.lazy import LazyProperty
37
37
38 from rhodecode.lib import str2bool
38 from rhodecode.lib import str2bool
39 from rhodecode.lib.pidlock import DaemonLock, LockHeld
39 from rhodecode.lib.pidlock import DaemonLock, LockHeld
40
40
41 from celery.messaging import establish_connection
41 from celery.messaging import establish_connection
42 from pylons import config
42 from pylons import config
43 from rhodecode.lib import celerypylons
44
43
45 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
46
45
47 try:
46 try:
48 CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
47 CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
49 except KeyError:
48 except KeyError:
50 CELERY_ON = False
49 CELERY_ON = False
51
50
52 class ResultWrapper(object):
51 class ResultWrapper(object):
53 def __init__(self, task):
52 def __init__(self, task):
54 self.task = task
53 self.task = task
55
54
56 @LazyProperty
55 @LazyProperty
57 def result(self):
56 def result(self):
58 return self.task
57 return self.task
59
58
60 def run_task(task, *args, **kwargs):
59 def run_task(task, *args, **kwargs):
61 if CELERY_ON:
60 if CELERY_ON:
62 try:
61 try:
63 t = task.apply_async(args=args, kwargs=kwargs)
62 t = task.apply_async(args=args, kwargs=kwargs)
64 log.info('running task %s:%s', t.task_id, task)
63 log.info('running task %s:%s', t.task_id, task)
65 return t
64 return t
66 except socket.error, e:
65 except socket.error, e:
67 if e.errno == 111:
66 if e.errno == 111:
68 log.debug('Unable to connect to celeryd. Sync execution')
67 log.debug('Unable to connect to celeryd. Sync execution')
69 else:
68 else:
70 log.error(traceback.format_exc())
69 log.error(traceback.format_exc())
71 except KeyError, e:
70 except KeyError, e:
72 log.debug('Unable to connect to celeryd. Sync execution')
71 log.debug('Unable to connect to celeryd. Sync execution')
73 except Exception, e:
72 except Exception, e:
74 log.error(traceback.format_exc())
73 log.error(traceback.format_exc())
75
74
76 log.debug('executing task %s in sync mode', task)
75 log.debug('executing task %s in sync mode', task)
77 return ResultWrapper(task(*args, **kwargs))
76 return ResultWrapper(task(*args, **kwargs))
78
77
79
78
80 def locked_task(func):
79 def locked_task(func):
81 def __wrapper(func, *fargs, **fkwargs):
80 def __wrapper(func, *fargs, **fkwargs):
82 params = list(fargs)
81 params = list(fargs)
83 params.extend(['%s-%s' % ar for ar in fkwargs.items()])
82 params.extend(['%s-%s' % ar for ar in fkwargs.items()])
84
83
85 lockkey = 'task_%s' % \
84 lockkey = 'task_%s' % \
86 md5(str(func.__name__) + '-' + \
85 md5(str(func.__name__) + '-' + \
87 '-'.join(map(str, params))).hexdigest()
86 '-'.join(map(str, params))).hexdigest()
88 log.info('running task with lockkey %s', lockkey)
87 log.info('running task with lockkey %s', lockkey)
89 try:
88 try:
90 l = DaemonLock(lockkey)
89 l = DaemonLock(lockkey)
91 ret = func(*fargs, **fkwargs)
90 ret = func(*fargs, **fkwargs)
92 l.release()
91 l.release()
93 return ret
92 return ret
94 except LockHeld:
93 except LockHeld:
95 log.info('LockHeld')
94 log.info('LockHeld')
96 return 'Task with key %s already running' % lockkey
95 return 'Task with key %s already running' % lockkey
97
96
98 return decorator(__wrapper, func)
97 return decorator(__wrapper, func)
99
98
100
99
101
100
102
101
103
102
104
103
105
104
106
105
General Comments 0
You need to be logged in to leave comments. Login now