Exemple #1
0
    def get_default_manager(self, ask_if_not_found: bool = False):
        """ Get default package manager. """
        current_distro = distro.id()

        if current_distro not in self.couples and ask_if_not_found:
            print(
                "Sorry, but we cannot recognize your package manager. Now you cannot use a few of features."
                "But we support these managers: ")
            self._show_managers()

            manager = input("Please, choose one of them: ")
            self._check_if_manager_exists(manager)

            return self.managers[manager]

        elif current_distro not in self.couples and not ask_if_not_found:
            config_content = ConfigReader().read()
            assert "package_manager" in config_content, "You did not set the package manager in you config file!"

            return self.managers[config_content["package_manager"]]

        default_manager = self.couples[current_distro]
        logger.log(
            f"A default package manager was defined: {default_manager.name} at "
            "modules.package_managers.DefaultManager.get_default_manager method."
        )

        return default_manager
def main():
    sum_data = []
    time_now = datetime.datetime.now()

    # read config
    config_collectors = os.path.join(
        os.path.dirname(os.path.realpath(__file__)), config_file_collectors)
    config_db = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             config_file_db)
    config_reader = ConfigReader(config_db=config_db,
                                 config_collectors=config_collectors)

    # collect data
    for server in config_reader.collector_settings:
        if server['collector'] == 'veeam' or server[
                'collector'] == 'veeam cloud connect':
            collector = VeeamConnector(server)
            protected_vms = collector._CalculateProtectedVms()
            collector._RequestVeeamSessionDelete()

        elif server['collector'] == 'baashunter':
            collector = Baashunter(server)
            protected_vms = collector._RequestBaashunterVmstat()
            collector._RequestBaashunterSessionDelete()

        else:
            raise BaseException('ERROR: %s is not a valid collector' %
                                (server['collector']))

        # add data to summary list
        sum_data.append({
            'hostname': server['hostname'],
            'protected_vms': protected_vms,
            'collector': server['collector'],
            'points': protected_vms * int(server['point_value']),
            'license': server['license']
        })

    if sum_data:
        # connect to mysql
        mysql = MysqlConnector(config_reader.mysql_settings, time_now)

        # create mysql table
        mysql._QueryCreateMysqlTable()

        # add summary data to mysql db
        mysql._QueryAddSumData(sum_data)

        # summary monthly data
        mysql._SummerizeMonthlyData()

        # remove old report values
        mysql._RemoveOldValuesFromReports()

        # close connection to mysql
        mysql._Close()
Exemple #3
0
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.canvas = tk.Canvas(self, width=self.WIDTH, height=self.HEIGHT)
        self.canvas.pack(side=tk.BOTTOM)
        self.control_info = tk.Frame(self)
        self.control_info.pack(side=tk.TOP, fill=tk.X)
        self.start_button = tk.Button(self.control_info,
                                      text='Start',
                                      command=self.start)
        self.start_button.pack(side=tk.RIGHT)
        self.pause_button = tk.Button(self.control_info,
                                      text='Pause',
                                      command=self.pause)
        self.pause_button.pack(side=tk.RIGHT)
        self.reset_button = tk.Button(self.control_info,
                                      text='Reset & Change Pattern',
                                      command=self.reset)
        self.reset_button.pack(side=tk.RIGHT)
        self.generation_text_var = tk.StringVar()
        self.generation_text = tk.Label(self.control_info,
                                        textvariable=self.generation_text_var)
        self.generation_text.pack()

        # Read config file
        cfg = ConfigReader()
        cfg.read('./')
        dim = (cfg.height, cfg.width)
        if cfg.height > 200 or cfg.width > 200:
            eprint("Height and Width must be equal to less than 200!")
            sys.exit()
        nos = cfg.numofseed
        self.u = Universe(dim)
        self.nseed = nos

        self.status = GameStatus.ONGOING
        self.reset()
def main():
    time_now = datetime.datetime.now()

    # read config
    config_db = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             config_file_db)
    config_mail = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               config_file_mail)
    config_reader = ConfigReader(config_db=config_db, config_mail=config_mail)

    # connect to mysql
    mysql = MysqlConnector(config_reader.mysql_settings, time_now)

    reports = mysql._GetMonthlyReports()
    email = Mailer(reports, config_reader.mail_settings, time_now)
    email._GenerateEmail()
                break
            sleep(self.delay_between_updates)


class WebThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        from modules import web_server
        web_server.run()


if __name__ == "__main__":
    args = arguments.parse_args()
    config = ConfigReader('conf/updater.conf')
    logging.basicConfig(filename=config.log_file(),
                        level=logging.getLevelName(config.log_level().upper()),
                        format='%(asctime)s - %(levelname)s - %(message)s')

    updater_kwargs = {}

    if len(sys.argv) > 1:
        # called script with args, so check the args, and override the configs settings
        if args.ini:
            config.set_path_to_one_file(args.ini)
            updater_kwargs['demonize'] = False

        if args.configs_directory:
            config.set_path_to_projects_configs(args.configs_directory)
Exemple #6
0
from flask import Flask, abort, request
import logging
from modules.config_reader import ConfigReader
from modules.updater import Updater
import json

app = Flask('WebGitUpdaterService', )
config_instance = ConfigReader('conf/updater.conf')

# global instance for Updater class
updater = None

# log

logging.basicConfig(filename=config_instance.log_file(),
                    level=logging.getLevelName(
                        config_instance.log_level().upper()),
                    format='%(asctime)s - %(levelname)s - %(message)s')


def github_get_repo_name(data):
    return data['repository']['name']


def gitlab_get_repo_name(data):
    pass


def gogs_get_repo_name(data):
    pass
Exemple #7
0
""" There is basic user info """
import os
import sys

from modules.config_reader import ConfigReader
from modules.logger import logger
from modules.paths import get_path
from modules.errors import *

home = get_path("home")
config_reader = ConfigReader(get_path("config"))


def check_if_config_exists():
    """ Check if required configuration file exists. """
    if not os.path.isfile(get_path("config")):
        logger.log(
            Warning(
                "✘ You haven't initialized! Execute doondler --init to create a"
                " user config file and continue!"))
        raise InitializationError(
            "Initialization error! Initialize and try again!")


class User:
    """ Main user class """
    def __init__(self):
        self.username = ""
        self.city = ""
        self.home_dir = ""
        self.handler = ""
# pip install MySQL-python sqlalchemy
import sys
import time
import ConfigParser

from modules.config_reader import ConfigReader
from modules.stock import Stock
from modules.mysqlclient import MySQLClient
from modules.logger import Logger

CONF_FILE_PATH = 'config/stock.conf'

if __name__ == '__main__':
    log = Logger.get_instance()
    log.info(
        '------------------ START TO FETCH STOCK HISTORY ------------------')

    try:
        conf = ConfigReader(ConfigParser.ConfigParser(), CONF_FILE_PATH)
    except Exception as e:
        print e
        log.error('Failed to read config file: %s', e)
        sys.exit(1)

    db = MySQLClient(conf.user, conf.password, conf.host, conf.dbname)
    db.create_tables()
    Stock(None, from_date=conf.from_date, db=db, log=log)
Exemple #9
0
    def _set_local_params(self):
        local_config = ConfigReader(self.copy_path)
        local_config = local_config.read()

        for param, value in local_config.items():
            self.user[param] = value
Exemple #10
0
 def __init__(self):
     self.city = ConfigReader(get_path("config")).read()["city"]
     self.api_url = f"https://yandex.com/pogoda/{self.city}"
     self.headers = {'User-Agent': UserAgent().chrome}
     logger.log(
         "An instance of the modules.synoptic.Synoptic class was made.")
Exemple #11
0
"""
    Config reader module tests.
    These tests require correct working of the config_writer module.
"""

import os
import sys
from modules.config_reader import ConfigReader
from modules.config_writer import ConfigWriter
from modules.paths import get_path
from tests.test_box import test_box
from tests.success import success


CONFIG_PATH = get_path("config")
config_reader = ConfigReader(CONFIG_PATH)


def check_config_size(config_content: str):
    """ Check if config size is correct. """
    config_size = sys.getsizeof(config_content)
    assert config_size > 50, "Incorrect config size (less than 50 bytes)"

    success("Config size test")


def check_config_length(config_content: str):
    """ Check config length is correct. """
    assert len(config_content) >= 4, "Incorrect config length!"

    success("Config length test")
Exemple #12
0
class ConfigWriter:
    """
        A class used to write or erase something to/from configuration file.

        Attributes
        ----------
        path: str
            Location of a configuration file; default = get_path("config").
        config_reader: ConfigReader
            The class needs to read config for erasing from it.

        Methods
        -------
        write(name=None, value=None, items=None)
            Write a couple name = value or items({ name: value }) to the config.
        erase(name=None, names=None)
            Erase attribute(name) or attributes(names) from the config.
    """

    def __init__(self, path=get_path("config")):
        self.path = path
        self.config_reader = ConfigReader(self.path)
        logger.log("Created an instance of the modules.config_writer.ConfigWriter class.")

    def _create_config_item(self, key, value):
        try:
            assert bool(key) is True, "You cannot set empty parameter name!"
            assert bool(value) is True, "You cannot set empty parameter value!"

            return f"{key} = {value}\n"

        except AssertionError as e:
            logger.log(e)
            sys.exit()

    def _write_par_to_config(self, config, name: str, value: str):
        config_item = self._create_config_item(name, value)
        config.write(config_item)

    def _write_items_to_config(self, config, items: dict):
        try:
            assert len(items.keys()) != 0, "You cannot set empty list of parameters!"

            for name, value in items.items():
                self._write_par_to_config(config, name, value)

        except AssertionError as e:
            logger.log(e)
            sys.exit()

    def _erase_items(self, config_content, names):
        for name in names:
            assert name in config_content is not False, "You cannot delete item which not exists!"
            del config_content[name]

            return config_content

    def _check_if_given_both(self, name, names):
        assert not (name and names), "You can give either name or names parameter, but not both!"

    def write(self, name=None, value=None, items=None):
        """
            Write element to a config.

            Arguments
            ---------
            name: str
                Name of a config attribute.
            value: str
                Value of a config attribute.
            items: dict { "name" : "value" }
                A dictionary of couples name: value. Any Items will be written to a config.
        """
        try:
            assert os.path.isfile(self.path), "Config file does not exists!"

            config = open(self.path, "a")
            self._write_items_to_config(config, items or {name: value})
            config.close()

            logger.log("The param(s) ha(s/ve) been written to the config.")

        except AssertionError as error:
            logger.log(error)
            sys.exit()

    def erase(self, name=None, names=None):
        """
            Erase element or elements from a config.

            Attributes
            ----------
            name: str
                Name of an erasing element.
            names: list [ "name", "name" ]
                List of names those should be erased.
        """
        config = open(self.path, "r")
        config_backup = self.config_reader.read()
        config_content = self.config_reader.read()
        config.close()

        try:
            self._check_if_given_both(name, names)

            config = open(self.path, "w")
            config_content = self._erase_items(config_content, names or [name])
            self._write_items_to_config(config, config_content or {})
            config.close()

            logger.log("The param(s) ha(s/ve) been erased from the config.")

        except AssertionError as e:
            config_writer.write(items=config_backup)
            logger.log(e)
            sys.exit()
Exemple #13
0
 def __init__(self, path=get_path("config")):
     self.path = path
     self.config_reader = ConfigReader(self.path)
     logger.log("Created an instance of the modules.config_writer.ConfigWriter class.")