Completed
Push — master ( 265317...7ca1a7 )
by W
06:30
created

st2common.setup()   F

Complexity

Conditions 12

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 67
rs 2.5741
cc 12

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like st2common.setup() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
"""
17
This module contains common service setup and teardown code.
18
"""
19
20
from __future__ import absolute_import
21
22
import os
23
24
from oslo_config import cfg
25
26
from st2common import log as logging
27
from st2common.models import db
28
from st2common.constants.logging import DEFAULT_LOGGING_CONF_PATH
29
from st2common.persistence import db_init
30
from st2common.transport.bootstrap_utils import register_exchanges
31
from st2common.signal_handlers import register_common_signal_handlers
32
from st2common.util.debugging import enable_debugging
33
from st2common.models.utils.profiling import enable_profiling
34
from st2common import triggers
35
36
from st2common.rbac.migrations import run_all as run_all_rbac_migrations
37
38
__all__ = [
39
    'setup',
40
    'teardown',
41
42
    'db_setup',
43
    'db_teardown'
44
]
45
46
LOG = logging.getLogger(__name__)
47
48
49
def setup(service, config, setup_db=True, register_mq_exchanges=True,
50
          register_signal_handlers=True, register_internal_trigger_types=False,
51
          run_migrations=True, config_args=None):
52
    """
53
    Common setup function.
54
55
    Currently it performs the following operations:
56
57
    1. Parses config and CLI arguments
58
    2. Establishes DB connection
59
    3. Set log level for all the loggers to DEBUG if --debug flag is present
60
    4. Registers RabbitMQ exchanges
61
    5. Registers common signal handlers
62
    6. Register internal trigger types
63
64
    :param service: Name of the service.
65
    :param config: Config object to use to parse args.
66
    """
67
    # Set up logger which logs everything which happens during and before config
68
    # parsing to sys.stdout
69
    logging.setup(DEFAULT_LOGGING_CONF_PATH)
70
71
    # Parse args to setup config.
72
    if config_args:
73
        config.parse_args(config_args)
74
    else:
75
        config.parse_args()
76
77
    config_file_paths = cfg.CONF.config_file
78
    config_file_paths = [os.path.abspath(path) for path in config_file_paths]
79
    LOG.debug('Using config files: %s', ','.join(config_file_paths))
80
81
    # Setup logging.
82
    logging_config_path = config.get_logging_config_path()
83
    logging_config_path = os.path.abspath(logging_config_path)
84
85
    LOG.debug('Using logging config: %s', logging_config_path)
86
    logging.setup(logging_config_path)
87
88
    if cfg.CONF.debug:
89
        enable_debugging()
90
91
    if cfg.CONF.profile:
92
        enable_profiling()
93
94
    # All other setup which requires config to be parsed and logging to
95
    # be correctly setup.
96
    if setup_db:
97
        db_setup()
98
99
    if register_mq_exchanges:
100
        register_exchanges()
101
102
    if register_signal_handlers:
103
        register_common_signal_handlers()
104
105
    if register_internal_trigger_types:
106
        triggers.register_internal_trigger_types()
107
108
    # TODO: This is a "not so nice" workaround until we have a proper migration system in place
109
    if run_migrations:
110
        run_all_rbac_migrations()
111
112
    if cfg.CONF.rbac.enable and not cfg.CONF.auth.enable:
113
        msg = ('Authentication is not enabled. RBAC only works when authentication is enabled.'
114
               'You can either enable authentication or disable RBAC.')
115
        raise Exception(msg)
116
117
118
def teardown():
119
    """
120
    Common teardown function.
121
    """
122
    db_teardown()
123
124
125
def db_setup():
126
    username = getattr(cfg.CONF.database, 'username', None)
127
    password = getattr(cfg.CONF.database, 'password', None)
128
129
    connection = db_init.db_setup_with_retry(
130
        db_name=cfg.CONF.database.db_name, db_host=cfg.CONF.database.host,
131
        db_port=cfg.CONF.database.port, username=username, password=password
132
    )
133
    return connection
134
135
136
def db_teardown():
137
    return db.db_teardown()
138