Passed
Push — master ( 901c2b...6be349 )
by Humberto
02:14
created

kytos.utils.config.KytosConfig.check_sections()   A

Complexity

Conditions 3

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 3
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 1
import logging
10 1
import os
11 1
from collections import namedtuple
12 1
from configparser import ConfigParser
13
14 1
LOG = logging.getLogger(__name__)
15
16
17 1
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 1
    def __init__(self, config_file='~/.kytosrc'):
25
        """Init method.
26
27
        Receive the confi_file as argument.
28
        """
29 1
        self.config_file = os.path.expanduser(config_file)
30 1
        self.debug = False
31 1
        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 1
        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 1
        self.config.read(self.config_file)
40 1
        self.check_sections(self.config)
41
42 1
        self.set_env_or_defaults()
43
44 1
        if not os.path.exists(self.config_file):
45 1
            LOG.warning("Config file %s not found.", self.config_file)
46 1
            LOG.warning("Creating a new empty config file.")
47 1
            with open(self.config_file, 'w') as output_file:
48 1
                os.chmod(self.config_file, 0o0600)
49 1
                self.config.write(output_file)
50
51 1
    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 1
    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 1
        option = namedtuple('Option', ['section', 'name', 'env_var',
63
                                       'default_value'])
64
65 1
        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 1
        for option in options:
75 1
            if not self.config.has_option(option.section, option.name):
76 1
                env_value = os.environ.get(option.env_var,
77
                                           option.default_value)
78 1
                if env_value:
79 1
                    self.config.set(option.section, option.name, env_value)
80
81 1
        self.config.set('global', 'debug', str(self.debug))
82
83 1
    @staticmethod
84
    def check_sections(config):
85
        """Create a empty config file."""
86 1
        default_sections = ['global', 'auth', 'napps', 'kytos']
87 1
        for section in default_sections:
88 1
            if not config.has_section(section):
89 1
                config.add_section(section)
90
91 1
    def save_token(self, user, token):
92
        """Save the token on the config file."""
93
        self.config.set('auth', 'user', user)
94
        self.config.set('auth', 'token', token)
95
        # allow_no_value=True is used to keep the comments on the config file.
96
        new_config = ConfigParser(allow_no_value=True)
97
98
        # Parse the config file. If no config file was found, then create some
99
        # default sections on the config variable.
100
        new_config.read(self.config_file)
101
        self.check_sections(new_config)
102
103
        new_config.set('auth', 'user', user)
104
        new_config.set('auth', 'token', token)
105
        filename = os.path.expanduser(self.config_file)
106
        with open(filename, 'w') as out_file:
107
            os.chmod(filename, 0o0600)
108
            new_config.write(out_file)
109
110 1
    def clear_token(self):
111
        """Clear Token information on config file."""
112
        # allow_no_value=True is used to keep the comments on the config file.
113
        new_config = ConfigParser(allow_no_value=True)
114
115
        # Parse the config file. If no config file was found, then create some
116
        # default sections on the config variable.
117
        new_config.read(self.config_file)
118
        self.check_sections(new_config)
119
120
        new_config.remove_option('auth', 'user')
121
        new_config.remove_option('auth', 'token')
122
        filename = os.path.expanduser(self.config_file)
123
        with open(filename, 'w') as out_file:
124
            os.chmod(filename, 0o0600)
125
            new_config.write(out_file)
126