Passed
Pull Request — master (#88)
by macartur
01:46
created

KytosConfig.set_env_or_defaults()   B

Complexity

Conditions 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 27
rs 8.5806
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 collections import namedtuple
12
from configparser import ConfigParser
13
14
log = logging.getLogger(__name__)
15
16
17
class KytosConfig():
18
    """Kytos Configs.
19
20
    Read the config file for kytos utils and/or request data for the user in
21
    order to get the correct paths and links.
22
    """
23
24
    def __init__(self, config_file='~/.kytosrc'):
25
        """Init method.
26
27
        Receive the confi_file as argument.
28
        """
29
        self.config_file = os.path.expanduser(config_file)
30
        self.debug = False
31
        if self.debug:
32
            log.setLevel(logging.DEBUG)
33
34
        # allow_no_value=True is used to keep the comments on the config file.
35
        self.config = ConfigParser(allow_no_value=True)
36
37
        # Parse the config file. If no config file was found, then create some
38
        # default sections on the config variable.
39
        self.config.read(self.config_file)
40
        self.check_sections(self.config)
41
42
        self.set_env_or_defaults()
43
44
        if not os.path.exists(self.config_file):
45
            log.warning("Config file %s not found.", self.config_file)
46
            log.warning("Creating a new empty config file.")
47
            with open(self.config_file, 'w') as output_file:
48
                os.chmod(self.config_file, 0o0600)
49
                self.config.write(output_file)
50
51
    def log_configs(self):
52
        """Log the read configs if debug is enabled."""
53
        for sec in self.config.sections():
54
            log.debug('   %s: %s', sec, self.config.options(sec))
55
56
    def set_env_or_defaults(self):
57
        """Read some environment variables and set them on the config.
58
59
        If no environment variable is found and the config section/key is
60
        empty, then set some default values.
61
        """
62
        Option = namedtuple('Option', ['section', 'name', 'env_var',
63
                                       'default_value'])
64
65
        options = [Option('auth', 'user', 'NAPPS_USER', None),
66
                   Option('auth', 'token', 'NAPPS_TOKEN', None),
67
                   Option('napps', 'api', 'NAPPS_API_URI',
68
                          'https://napps.kytos.io/api/'),
69
                   Option('napps', 'repo', 'NAPPS_REPO_URI',
70
                          'https://napps.kytos.io/repo'),
71
                   Option('kytos', 'api', 'KYTOS_API',
72
                          'http://localhost:8181/')]
73
74
        for option in options:
75
            env_value = os.environ.get(option.env_var)
76
            if env_value:
77
                self.config.set(option.section, option.name, env_value)
78
            elif option.default_value:
79
                self.config.set(option.section, option.name,
80
                                option.default_value)
81
82
        self.config.set('global', 'debug', str(self.debug))
83
84
    @staticmethod
85
    def check_sections(config):
86
        """Create a empty config file."""
87
        default_sections = ['global', 'auth', 'napps', 'kytos']
88
        for section in default_sections:
89
            if not config.has_section(section):
90
                config.add_section(section)
91
92
    def save_token(self, user, token):
93
        """Save the token on the config file."""
94
        self.config.set('auth', 'user', user)
95
        self.config.set('auth', 'token', token)
96
        # allow_no_value=True is used to keep the comments on the config file.
97
        new_config = ConfigParser(allow_no_value=True)
98
99
        # Parse the config file. If no config file was found, then create some
100
        # default sections on the config variable.
101
        new_config.read(self.config_file)
102
        self.check_sections(new_config)
103
104
        new_config.set('auth', 'user', user)
105
        new_config.set('auth', 'token', token)
106
        filename = os.path.expanduser(self.config_file)
107
        with open(filename, 'w') as out_file:
108
            os.chmod(filename, 0o0600)
109
            new_config.write(out_file)
110
111
    def clear_token(self):
112
        """Clear Token information on config file."""
113
        # allow_no_value=True is used to keep the comments on the config file.
114
        new_config = ConfigParser(allow_no_value=True)
115
116
        # Parse the config file. If no config file was found, then create some
117
        # default sections on the config variable.
118
        new_config.read(self.config_file)
119
        self.check_sections(new_config)
120
121
        new_config.remove_option('auth', 'user')
122
        new_config.remove_option('auth', 'token')
123
        filename = os.path.expanduser(self.config_file)
124
        with open(filename, 'w') as out_file:
125
            os.chmod(filename, 0o0600)
126
            new_config.write(out_file)
127