Passed
Pull Request — master (#3640)
by Lakshmi
06:19
created

_print_options()   B

Complexity

Conditions 5

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
c 1
b 0
f 0
dl 0
loc 22
rs 8.3411
1
#!/usr/bin/env python
2
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
3
# contributor license agreements.  See the NOTICE file distributed with
4
# this work for additional information regarding copyright ownership.
5
# The ASF licenses this file to You under the Apache License, Version 2.0
6
# (the "License"); you may not use this file except in compliance with
7
# the License.  You may obtain a copy of the License at
8
#
9
#     http://www.apache.org/licenses/LICENSE-2.0
10
#
11
# Unless required by applicable law or agreed to in writing, software
12
# distributed under the License is distributed on an "AS IS" BASIS,
13
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
# See the License for the specific language governing permissions and
15
# limitations under the License.
16
17
import collections
18
import importlib
19
import six
20
import sys
21
import traceback
22
23
from oslo_config import cfg
24
25
26
CONFIGS = ['st2actions.config',
27
           'st2actions.notifier.config',
28
           'st2actions.resultstracker.config',
29
           'st2api.config',
30
           'st2stream.config',
31
           'st2auth.config',
32
           'st2common.config',
33
           'st2exporter.config',
34
           'st2reactor.rules.config',
35
           'st2reactor.sensor.config',
36
           'st2reactor.garbage_collector.config']
37
38
SKIP_GROUPS = ['api_pecan', 'rbac', 'results_tracker']
39
40
# We group auth options together to nake it a bit more clear what applies where
41
AUTH_OPTIONS = {
42
    'common': [
43
        'enable',
44
        'mode',
45
        'logging',
46
        'api_url',
47
        'token_ttl',
48
        'service_token_ttl',
49
        'debug'
50
    ],
51
    'standalone': [
52
        'host',
53
        'port',
54
        'use_ssl',
55
        'cert',
56
        'key',
57
        'backend',
58
        'backend_kwargs'
59
    ]
60
}
61
62
# Some of the config values change depenending on the environment where this script is ran so we
63
# set them to static values to ensure consistent and stable output
64
STATIC_OPTION_VALUES = {
65
    'actionrunner': {
66
        'virtualenv_binary': '/data/stanley/virtualenv/bin/virtualenv',
67
        'python_binary': '/data/stanley/virtualenv/bin/python'
68
    },
69
    'webui': {
70
        'webui_base_url': 'https://localhost'
71
    }
72
}
73
74
COMMON_AUTH_OPTIONS_COMMENT = """
75
# Common option - options below apply in both scenarios - when auth service is running as a WSGI
76
# service (e.g. under Apache or Nginx) and when it's running in the standalone mode.
77
""".strip()
78
79
STANDALONE_AUTH_OPTIONS_COMMENT = """
80
# Standalone mode options - options below only apply when auth service is running in the standalone
81
# mode.
82
""".strip()
83
84
85
def _import_config(config):
86
    try:
87
        return importlib.import_module(config)
88
    except:
89
        traceback.print_exc()
90
    return None
91
92
93
def _read_current_config(opt_groups):
94
    for k, v in six.iteritems(cfg.CONF._groups):
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _groups was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
95
        if k in SKIP_GROUPS:
96
            continue
97
        if k not in opt_groups:
98
            opt_groups[k] = v
99
    return opt_groups
100
101
102
def _clear_config():
103
    cfg.CONF.reset()
104
105
106
def _read_group(opt_group):
107
    all_options = opt_group._opts.values()
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _opts was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
108
109
    if opt_group.name == 'auth':
110
        print(COMMON_AUTH_OPTIONS_COMMENT)
111
        print('')
112
        common_options = [option for option in all_options if option['opt'].name in
113
                          AUTH_OPTIONS['common']]
114
        _print_options(opt_group=opt_group, options=common_options)
115
116
        print('')
117
        print(STANDALONE_AUTH_OPTIONS_COMMENT)
118
        print('')
119
        standalone_options = [option for option in all_options if option['opt'].name in
120
                              AUTH_OPTIONS['standalone']]
121
        _print_options(opt_group=opt_group, options=standalone_options)
122
123
        if len(common_options) + len(standalone_options) != len(all_options):
124
            msg = ('Not all options are declared in AUTH_OPTIONS dict, please update it')
125
            raise Exception(msg)
126
    else:
127
        options = all_options
128
        _print_options(opt_group=opt_group, options=options)
129
130
131
def _read_groups(opt_groups):
132
    opt_groups = collections.OrderedDict(sorted(opt_groups.items()))
133
    for name, opt_group in six.iteritems(opt_groups):
134
        print('[%s]' % name)
135
        _read_group(opt_group)
136
        print('')
137
138
139
def _print_options(opt_group, options):
140
    for opt in options:
141
        opt = opt['opt']
142
143
        # Special case for options which could change during this script run
144
        static_option_value = STATIC_OPTION_VALUES.get(opt_group.name, {}).get(opt.name, None)
145
        if static_option_value:
146
            opt.default = static_option_value
147
148
        # Special handling for list options
149
        if isinstance(opt, cfg.ListOpt):
150
            if opt.default:
151
                value = ','.join(opt.default)
152
            else:
153
                value = ''
154
155
            value += ' # comma separated list allowed here.'
156
        else:
157
            value = opt.default
158
159
        print('# %s' % opt.help)
160
        print('%s = %s' % (opt.name, value))
161
162
163
def main(args):
164
    opt_groups = {}
165
    for config in CONFIGS:
166
        mod = _import_config(config)
167
        mod.register_opts()
168
        _read_current_config(opt_groups)
169
        _clear_config()
170
    _read_groups(opt_groups)
171
172
173
if __name__ == '__main__':
174
    main(sys.argv)
175