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

KytosConfig.set_env_or_defaults()   F

Complexity

Conditions 9

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
c 1
b 0
f 0
dl 0
loc 34
rs 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
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
        kytos_server = os.environ.get('KYTOS_API')
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
        if kytos_server is not None:
86
            self.config.set('kytos', 'api', kytos_server)
87
        elif not self.config.has_option('kytos', 'api'):
88
            self.config.set('kytos', 'api', 'http://localhost:8181/')
89
90
    @staticmethod
91
    def check_sections(config):
92
        """Create a empty config file."""
93
        default_sections = ['global', 'auth', 'napps', 'kytos']
94
        for section in default_sections:
95
            if not config.has_section(section):
96
                config.add_section(section)
97
98
    def save_token(self, user, token):
99
        """Save the token on the config file."""
100
        self.config.set('auth', 'user', user)
101
        self.config.set('auth', 'token', token)
102
        # allow_no_value=True is used to keep the comments on the config file.
103
        new_config = ConfigParser(allow_no_value=True)
104
105
        # Parse the config file. If no config file was found, then create some
106
        # default sections on the config variable.
107
        new_config.read(self.config_file)
108
        self.check_sections(new_config)
109
110
        new_config.set('auth', 'user', user)
111
        new_config.set('auth', 'token', token)
112
        filename = os.path.expanduser(self.config_file)
113
        with open(filename, 'w') as out_file:
114
            os.chmod(filename, 0o0600)
115
            new_config.write(out_file)
116
117
    def clear_token(self):
118
        """Clear Token information on config file."""
119
        # allow_no_value=True is used to keep the comments on the config file.
120
        new_config = ConfigParser(allow_no_value=True)
121
122
        # Parse the config file. If no config file was found, then create some
123
        # default sections on the config variable.
124
        new_config.read(self.config_file)
125
        self.check_sections(new_config)
126
127
        new_config.remove_option('auth', 'user')
128
        new_config.remove_option('auth', 'token')
129
        filename = os.path.expanduser(self.config_file)
130
        with open(filename, 'w') as out_file:
131
            os.chmod(filename, 0o0600)
132
            new_config.write(out_file)
133