예제 #1
0
    def __init__(self, config, logger, hostfile=None):
        """
        Construct object

        Args:
            config (object): holds instance of GcConfig class
            logger (object): holds instance of GcLogging class
            hostfile (str): json file with definitions


        """
        # enable logging and config, add some utils, create a proper objects
        self.gLogging = logger
        self.gConfig = config.config
        #used by _indexHosts, list of 5element tuples contain uuids from every level
        self.hosts_idx = []
        #used to drill down hierarchy of objects such as groups, hosts..
        self.pick_drill = ""
        # if hostfile not provided, use default one from config file
        # start TinyDB object
        try:
            if hostfile is None:
                hostfile = "{}/{}".format(gutils.gcpath(),
                                          self.gConfig['JSON']['hostfile'])
                self.hostfile = TinyDB(hostfile)
                self.hosttable = self.hostfile.table("HOSTS")
            else:
                self.hostfile = TinyDB(hostfile)
                self.hosttable = self.hostfile.table("HOSTS")
            #refresh uuids
            self._indexHosts()
        except Exception as e:
            self.gLogging.critical("hosts definitions cannot be loaded")
예제 #2
0
    def __init__(self, config, logger, credfile=None):
        """
        Construct object

        Args:
            config (object): holds instance of GcConfig class
            logger (object): holds instance of GcLogging class
            credfile (str): json file with definitions


        """
        # enable logging and config, create a proper objects
        self.gLogging = logger
        self.gConfig = config.config
        #if credfile not provided, use default one from config file
        #start TinyDB object
        try:
            if credfile is None:
                credfile = "{}/{}".format(gutils.gcpath(), self.gConfig['JSON']['credfile'])
                self.credfile = TinyDB(credfile)
                self.credtable = self.credfile.table("CREDS")
            else:
                self.credfile = TinyDB(credfile)
                self.credfile = self.credfile.table("CREDS")
        except Exception:
            self.gLogging.critical("credentials definitions cannot be loaded")
예제 #3
0
    def __init__(self, config, logger, command):
        """
        Construct object

        Args:
            config (object): holds instance of GcConfig class
            logger (object): holds instance of GcLogging class
            command (object): holds instance of GcCommands class


        """
        cmd.Cmd.doc_header = "GlobalConsole: type <help> to see this message"
        cmd.Cmd.undoc_header = "Commands: type <command> -h to get help (+h for db2 command)"
        cmd.Cmd.__init__(self)

        #initialize required objects
        self.gLogging = logger
        self.gConfig = config.config
        self.gCommand = command
        self.gLogging.info("Session started.")

        #set cmd module environment
        self.epilog = ""
        try:
            if self.gConfig['CMD']['print_header'] == "YES":
                self.header()
        except Exception:
            self.gLogging.warning("not supported terminal, you may experience a strange behaviour")

        #check env variable

        try:
            len(os.environ[self.gConfig['JSON']['decrypt_key_os_var']])
        except Exception:
            self.gLogging.warning("ENV VARIABLE: {} is not set! this may cause problems if password encryption is or will be enabled! Exit program and run: export GC_KEY=<YourPassword>".format(self.gConfig['JSON']['decrypt_key_os_var']))

        #initialize history file
        try:
            if os.path.exists("{}/{}".format(gutils.gcpath(), self.gConfig['CMD']['histfile'])) is False:
                with open("{}/{}".format(gutils.gcpath(), self.gConfig['CMD']['histfile']), "w") as f:
                    f.write("")

            readline.read_history_file("{}/{}".format(gutils.gcpath(), self.gConfig['CMD']['histfile']))
            # default history len is -1 (infinite), which may grow unruly
            readline.set_history_length(int(self.gConfig['CMD']['histlen']))
        except Exception:
            self.gLogging.error("cannot load history file")
예제 #4
0
    def do_exit(self, args):
        """
        This method saves command history and exit program

        """
        self.gLogging.debug("do_exit invoked")
        atexit.register(readline.write_history_file, "{}/{}".format(gutils.gcpath(), self.gConfig['CMD']['histfile']))
        self.gCommand.exit()
예제 #5
0
    def __init__(self, config, logger):
        """
        Construct object

        Args:
            config (object): holds instance of GcConfig class
            logger (object): holds instance of GcLogging class


        """
        # enable logging and config
        self.gLogging = logger
        self.gConfig = config.config
        #
        try:
            varsfile = "{}/{}".format(gutils.gcpath(),
                                      self.gConfig['JSON']['varfile'])
            self.varsfile = TinyDB(varsfile)
            self.varstable = self.varsfile.table("VARS")
            self.allvars = self.varstable.all()
        except Exception:
            self.gLogging.critical("variables definitions cannot be loaded")
예제 #6
0
    def __init__(self, config):
        """
        Construct object

        Args:
            config (object): holds instance of GcConfig class


        """
        self.gConfig = config.config
        try:
            self.logger = logging.getLogger(self.gConfig['LOGGING']['logger_name'])
            self.logger.setLevel(self.gConfig['LOGGING']['logging_level'])
            #file
            self.handler = RotatingFileHandler("{}/{}".format(gutils.gcpath(), self.gConfig['LOGGING']['log_file']),  maxBytes=int(self.gConfig['LOGGING']['log_file_size']), backupCount=int(self.gConfig['LOGGING']['log_file_rotate']))
            self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            self.handler.setFormatter(self.formatter)
            self.logger.addHandler(self.handler)

        except Exception as e:
            print("cannot start logging mechanism. reason: {}. exiting..".format(e))

        self.logging_levels = {"CRITICAL": 50, "ERROR": 40, "WARNING": 30, "INFO": 20, "DEBUG": 10, "NOSET": 10}
        self.logging_level = self.logging_levels[self.gConfig['LOGGING']['logging_level']]
예제 #7
0
    def __init__(self):

        self.config = configparser.ConfigParser()

        try:
            loaded = self.config.read(
                glob.glob("{}/{}".format(gutils.gcpath(), self.CONFIG_MASK)))

            if self.CONFIG_MAIN not in [
                    gutils.gcfile(file) for file in loaded
            ]:
                raise Exception(
                    "main config file: {} cannot be found. exiting..".format(
                        self.CONFIG_MAIN))

            if not all(elem in self.config.sections()
                       for elem in self.CONFIG_MAIN_SECTIONS):
                raise Exception(
                    "main config file: {} seems to be invalid. exiting..".
                    format(self.CONFIG_MAIN))

        except Exception as e:
            print(e)
            exit(1)