1
0
mirror of https://github.com/GNS3/gns3-server synced 2024-11-24 17:28:08 +00:00
gns3-server/gns3server/config.py

285 lines
9.0 KiB
Python
Raw Normal View History

#
# Copyright (C) 2021 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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/>.
"""
Reads the configuration file and store the settings for the server.
"""
import sys
import os
import shutil
import secrets
import configparser
from pydantic import ValidationError
from .schemas import ServerConfig
from .version import __version_info__
2016-06-10 15:51:19 +00:00
from .utils.file_watcher import FileWatcher
import logging
2021-04-13 09:16:50 +00:00
log = logging.getLogger(__name__)
2016-08-22 15:21:03 +00:00
class Config:
"""
Configuration file management using configparser.
2015-02-02 14:01:48 +00:00
2016-08-22 15:21:03 +00:00
:param files: Array of configuration files (optional)
:param profile: Profile settings (default use standard config file)
"""
2016-09-07 15:44:51 +00:00
def __init__(self, files=None, profile=None):
2015-02-02 14:01:48 +00:00
self._settings = None
2015-02-02 14:01:48 +00:00
self._files = files
2016-09-07 15:44:51 +00:00
self._profile = profile
if files and len(files):
if not os.access(files[0], os.R_OK) or not os.path.isfile(files[0]):
raise SystemExit(f"Unable to read configuration file: {files[0]}")
directory_name = os.path.dirname(files[0])
if not directory_name or directory_name == "":
files[0] = os.path.dirname(os.path.abspath(files[0])) + os.path.sep + files[0]
self._main_config_file = files[0]
else:
self._main_config_file = None
# Monitor configuration files for changes
2015-02-02 14:01:48 +00:00
self._watched_files = {}
self._watch_callback = []
appname = "GNS3"
2021-04-13 09:07:58 +00:00
version = f"{__version_info__[0]}.{__version_info__[1]}"
2022-01-19 11:58:36 +00:00
# On UNIX-like platforms, the configuration file location can be one of the following:
# 1: $HOME/.config/GNS3/gns3_server.conf
# 2: $HOME/.config/GNS3.conf
# 3: /etc/xdg/GNS3/gns3_server.conf
# 4: /etc/xdg/GNS3.conf
# 5: gns3_server.conf in the current working directory
home = os.path.expanduser("~")
server_filename = "gns3_server.conf"
if self._profile:
legacy_user_dir = os.path.join(home, ".config", appname, "profiles", self._profile)
versioned_user_dir = os.path.join(home, ".config", appname, version, "profiles", self._profile)
else:
2022-01-19 11:58:36 +00:00
legacy_user_dir = os.path.join(home, ".config", appname)
versioned_user_dir = os.path.join(home, ".config", appname, version)
if self._files is None and not hasattr(sys, "_called_from_test"):
self._files = [
os.path.join(os.getcwd(), server_filename),
os.path.join(versioned_user_dir, server_filename),
os.path.join(home, ".config", appname + ".conf"),
os.path.join("/etc/gns3", server_filename),
os.path.join("/etc/xdg", appname, server_filename),
os.path.join("/etc/xdg", appname + ".conf"),
]
if self._files is None:
self._files = []
if self._main_config_file is None:
# TODO: migrate versioned config file from a previous version of GNS3 (for instance 2.2 -> 3.0) + support profiles
# migrate post version 2.2.0 config files if they exist
os.makedirs(versioned_user_dir, exist_ok=True)
try:
# migrate the server config file
old_server_config = os.path.join(legacy_user_dir, server_filename)
new_server_config = os.path.join(versioned_user_dir, server_filename)
if not os.path.exists(new_server_config) and os.path.exists(old_server_config):
shutil.copyfile(old_server_config, new_server_config)
except OSError as e:
2021-04-13 09:07:58 +00:00
log.error(f"Cannot migrate old config files: {e}")
self._main_config_file = os.path.join(versioned_user_dir, server_filename)
for file in self._files:
if os.path.exists(file):
self._main_config_file = file
break
2015-03-17 14:40:58 +00:00
self.clear()
self._watch_config_file()
@property
def settings(self) -> ServerConfig:
"""
Return the settings.
"""
return self._settings
def listen_for_config_changes(self, callback):
"""
Call the callback when the configuration file change
"""
self._watch_callback.append(callback)
2016-08-22 15:21:03 +00:00
@property
2016-09-07 15:44:51 +00:00
def profile(self):
2016-08-22 15:21:03 +00:00
"""
2016-09-07 15:44:51 +00:00
Settings profile
2016-08-22 15:21:03 +00:00
"""
2016-09-07 15:44:51 +00:00
return self._profile
2016-08-22 15:21:03 +00:00
@property
def config_dir(self):
"""
Return the directory where the configuration file is located.
"""
return os.path.dirname(self._main_config_file)
@property
def controller_vars(self):
"""
Return the controller variables file path.
"""
controller_vars_filename = "gns3_controller.vars"
return os.path.join(self.config_dir, controller_vars_filename)
@property
def server_config(self):
"""
Return the server configuration file path.
"""
2022-01-19 11:58:36 +00:00
server_config_filename = "gns3_server.conf"
return os.path.join(self.config_dir, server_config_filename)
2015-03-17 14:40:58 +00:00
def clear(self):
"""
Restart with a clean config
"""
self.read_config()
def _watch_config_file(self):
"""
Add config files to be monitored for changes.
"""
2016-06-10 15:51:19 +00:00
for file in self._files:
if os.path.exists(file):
self._watched_files[file] = FileWatcher(file, self._config_file_change)
def _config_file_change(self, file_path):
"""
Callback when a config file has been updated.
"""
log.info(f"'{file_path}' has been updated, reloading the config...")
2016-06-10 15:51:19 +00:00
self.read_config()
for callback in self._watch_callback:
callback()
2015-02-02 14:01:48 +00:00
2015-03-02 19:46:05 +00:00
def reload(self):
2015-02-02 14:01:48 +00:00
"""
2015-03-02 19:46:05 +00:00
Reload configuration
2015-02-02 14:01:48 +00:00
"""
2015-03-02 19:46:05 +00:00
self.read_config()
def get_config_files(self):
"""
Return the config files in use.
"""
return self._watched_files
def _load_jwt_secret_key(self):
"""
Load the JWT secret key.
"""
jwt_secret_key_path = os.path.join(self._settings.Server.secrets_dir, "gns3_jwt_secret_key")
if not os.path.exists(jwt_secret_key_path):
log.info(f"No JWT secret key configured, generating one in '{jwt_secret_key_path}'...")
try:
with open(jwt_secret_key_path, "w+", encoding="utf-8") as fd:
fd.write(secrets.token_hex(32))
except OSError as e:
log.error(f"Could not create JWT secret key file '{jwt_secret_key_path}': {e}")
try:
with open(jwt_secret_key_path, encoding="utf-8") as fd:
jwt_secret_key_content = fd.read()
self._settings.Controller.jwt_secret_key = jwt_secret_key_content
except OSError as e:
log.error(f"Could not read JWT secret key file '{jwt_secret_key_path}': {e}")
def _load_secret_files(self):
"""
Load the secret files.
"""
if not self._settings.Server.secrets_dir:
self._settings.Server.secrets_dir = os.path.dirname(self.server_config)
self._load_jwt_secret_key()
def read_config(self):
2015-01-23 16:39:17 +00:00
"""
Read the configuration files and validate the settings.
2015-01-23 16:39:17 +00:00
"""
config = configparser.ConfigParser(interpolation=None)
try:
parsed_files = config.read(self._files, encoding="utf-8")
except configparser.Error as e:
log.error("Can't parse configuration file: %s", str(e))
return
if not parsed_files:
log.warning("No configuration file could be found or read")
self._settings = ServerConfig()
return
2015-01-23 16:39:17 +00:00
for file in parsed_files:
log.info(f"Configuration file '{file}' loaded")
self._watched_files[file] = os.stat(file).st_mtime
2015-03-16 14:03:41 +00:00
try:
self._settings = ServerConfig(**config._sections)
except ValidationError as e:
log.critical(f"Could not validate configuration file settings: {e}")
raise
2015-03-16 14:03:41 +00:00
self._load_secret_files()
2015-03-16 14:03:41 +00:00
@staticmethod
2016-08-22 15:21:03 +00:00
def instance(*args, **kwargs):
"""
Singleton to return only one instance of Config.
:returns: instance of Config
"""
if not hasattr(Config, "_instance") or Config._instance is None:
2016-08-22 15:21:03 +00:00
Config._instance = Config(*args, **kwargs)
return Config._instance
@staticmethod
def reset():
"""
Reset singleton
"""
Config._instance = None