summaryrefslogtreecommitdiff
path: root/src/helpers/run-config-activation.py
blob: 7e7a6571e537ea1af8b46907ea4cdbcad2468b1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
#
# Copyright VyOS maintainers and contributors <maintainers@vyos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import sys
import logging

from pathlib import Path
from argparse import ArgumentParser

from vyos.compose_config import ComposeConfig
from vyos.compose_config import ComposeConfigError
from vyos.utils.activate import refresh_activation_list
from vyos.utils.activate import get_activation_scripts
from vyos.utils.activate import get_activation
from vyos.utils.activate import set_activation
from vyos.utils.activate import is_active
from vyos.utils.system import load_as_module
from vyos.utils.func import FalseCallable
from vyos.defaults import directories
from vyos.defaults import activation_list


parser = ArgumentParser()
parser.add_argument(
    'config_file',
    type=str,
    help='configuration file to modify with system-specific settings',
)
parser.add_argument('--test-script', type=str, help='test effect of named script')

args = parser.parse_args()

checkpoint_file = '/run/vyos-activate-checkpoint'
log_file = Path(directories['config']).joinpath('vyos-activate.log')

logger = logging.getLogger(__name__)
fh = logging.FileHandler(log_file)
formatter = logging.Formatter('%(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)


if 'vyos-activate-debug' in Path('/proc/cmdline').read_text():
    print(f'\nactivate-debug enabled: file {checkpoint_file}_* on error')
    debug = checkpoint_file
    logger.setLevel(logging.DEBUG)
else:
    debug = None
    logger.setLevel(logging.INFO)


def file_ext(file_name: str) -> str:
    """Return an identifier from file name for checkpoint file extension."""
    return Path(file_name).stem


refresh_activation_list()

if not Path(activation_list).exists():
    logger.error('Missing config activation list!')
    sys.exit(1)

script_dir = Path(directories['activate'])

if args.test_script:
    script_list = [script_dir.joinpath(args.test_script).stem]
else:
    script_list = list(get_activation_scripts())

config_file = args.config_file
config_str = Path(config_file).read_text()

compose = ComposeConfig(config_str, checkpoint_file=debug)

false_call = FalseCallable()

update_config = False
for file in script_list:
    if not is_active(file):
        continue

    logger.info(f'calling {file}')

    mod_name = Path(file).stem.replace('-', '_')
    mod = load_as_module(mod_name, script_dir.joinpath(f'{file}.py').as_posix())

    pre_condition = getattr(mod, 'pre_condition', false_call)
    post_condition = getattr(mod, 'post_condition', false_call)
    activate = getattr(mod, 'activate', false_call)

    if not activate:
        logger.error(f'missing activate function in {file}')
        continue

    if not pre_condition or pre_condition():
        try:
            compose.apply_func(activate)
        except ComposeConfigError as e:
            if debug:
                compose.write(f'{compose.checkpoint_file}_{file_ext(file)}')
            logger.error(f'config-activation error in {file}: {e}')
            update_config = False
            break

        if post_condition:
            post_condition()

        if get_activation(file) == 'once':
            set_activation(file, 'off')

        update_config = True

if update_config:
    compose.write(config_file, with_version=True)