Passed
Pull Request — master (#1)
by Carlos Eduardo
01:52 queued 24s
created

KytosConfig.set_env_or_defaults()   C

Complexity

Conditions 7

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
c 1
b 0
f 0
dl 0
loc 31
rs 5.5
1
"""Kytos utils configuration."""
2
# This file is part of kytos-utils.
3
#
4
# Copyright (c) 2016 Kytos Team
5
#
6
# Authors:
7
#    Beraldo Leal <beraldo AT ncc DOT unesp DOT br>
8
9
import logging
10
import os
11
from configparser import ConfigParser
12
13
log = logging.getLogger(__name__)
14
15
16
class KytosConfig():
17
    """Kytos Configs.
18
19
    Read the config file for kytos utils and/or request data for the user in
20
    order to get the correct paths and links.
21
    """
22
23
    def __init__(self, config_file='~/.kytosrc'):
24
        """Init method.
25
26
        Receive the confi_file as argument.
27
        """
28
        self.config_file = os.path.expanduser(config_file)
29
        self.debug = False
30
        if self.debug:
31
            log.setLevel(logging.DEBUG)
32
33
        # allow_no_value=True is used to keep the comments on the config file.
34
        self.config = ConfigParser(allow_no_value=True)
35
36
        # Parse the config file. If no config file was found, then create some
37
        # default sections on the config variable.
38
        self.config.read(self.config_file)
39
        self.check_sections(self.config)
40
41
        self.set_env_or_defaults()
42
43
        if not os.path.exists(self.config_file):
44
            log.warning("Config file %s not found.", self.config_file)
45
            log.warning("Creating a new empty config file.")
46
            with open(self.config_file, 'w') as output_file:
47
                os.chmod(self.config_file, 0o0600)
48
                self.config.write(output_file)
49
50
    def log_configs(self):
51
        """Log the read configs if debug is enabled."""
52
        for sec in self.config.sections():
53
            log.debug('   %s: %s', sec, self.config.options(sec))
54
55
    def set_env_or_defaults(self):
56
        """Read some environment variables and set them on the config.
57
58
        If no environment variable is found and the config section/key is
59
        empty, then set some default values.
60
        """
61
        napps_api = os.environ.get('NAPPS_API_URI')
62
        napps_repo = os.environ.get('NAPPS_REPO_URI')
63
        user = os.environ.get('NAPPS_USER')
64
        token = os.environ.get('NAPPS_TOKEN')
65
        napps_path = os.environ.get('NAPPS_PATH')
66
67
        self.config.set('global', 'debug', str(self.debug))
68
69
        if user is not None:
70
            self.config.set('auth', 'user', user)
71
72
        if token is not None:
73
            self.config.set('auth', 'token', token)
74
75
        if napps_api is not None:
76
            self.config.set('napps', 'api', napps_api)
77
        elif not self.config.has_option('napps', 'api'):
78
            self.config.set('napps', 'api', 'https://napps.kytos.io/api/')
79
80
        if napps_repo is not None:
81
            self.config.set('napps', 'repo', napps_repo)
82
        elif not self.config.has_option('napps', 'repo'):
83
            self.config.set('napps', 'repo', 'https://napps.kytos.io/repo/')
84
85
        self._set_napps_path(napps_path)
86
87
    def _set_napps_path(self, napps_path):
88
        """Set paths if NAPPS_PATH is given or if not found in config."""
89
        if napps_path or not self.config.has_option('napps', 'enabled_path'):
90
            if not napps_path:  # default paths
91
                base = os.environ.get('VIRTUAL_ENV') or '/'
92
                napps_path = os.path.join(base, 'var', 'lib', 'kytos', 'napps')
93
            self.config.set('napps', 'enabled_path', napps_path)
94
            self.config.set('napps', 'installed_path',
95
                            os.path.join(napps_path, '.installed'))
96
97
    @staticmethod
98
    def check_sections(config):
99
        """Create a empty config file."""
100
        default_sections = ['global', 'auth', 'napps']
101
        for section in default_sections:
102
            if not config.has_section(section):
103
                config.add_section(section)
104
105
    def save_token(self, user, token):
106
        """Save the token on the config file."""
107
        self.config.set('auth', 'user', user)
108
        self.config.set('auth', 'token', token)
109
        # allow_no_value=True is used to keep the comments on the config file.
110
        new_config = ConfigParser(allow_no_value=True)
111
112
        # Parse the config file. If no config file was found, then create some
113
        # default sections on the config variable.
114
        new_config.read(self.config_file)
115
        self.check_sections(new_config)
116
117
        new_config.set('auth', 'user', user)
118
        new_config.set('auth', 'token', token)
119
        filename = os.path.expanduser(self.config_file)
120
        with open(filename, 'w') as out_file:
121
            os.chmod(filename, 0o0600)
122
            new_config.write(out_file)
123
124
    def clear_token(self):
125
        """Clear Token information on config file."""
126
        # allow_no_value=True is used to keep the comments on the config file.
127
        new_config = ConfigParser(allow_no_value=True)
128
129
        # Parse the config file. If no config file was found, then create some
130
        # default sections on the config variable.
131
        new_config.read(self.config_file)
132
        self.check_sections(new_config)
133
134
        new_config.remove_option('auth', 'user')
135
        new_config.remove_option('auth', 'token')
136
        filename = os.path.expanduser(self.config_file)
137
        with open(filename, 'w') as out_file:
138
            os.chmod(filename, 0o0600)
139
            new_config.write(out_file)
140