def __init__(self, *args, **kwargs): self.config = ConfigHandler() self.args = args self.kwargs = kwargs self.default = DBHandler_defaults() self._check_host() self._check_db_name() self._check_db_port() # Sets database parameters from dbvars.cfg # self._set_db_vars() # # # Check for overriding vars passed into __init__ # if host is not None: self.dbvars['host'] = str(host) # if database is not None: self.dbvars['database'] = str(database) # if port is not None: self.dbvars['port'] = str(port) # if user is not None: self.dbvars['user'] = str(user) # if password is not None: self.dbvars['password'] = str(password) # # # Actually create the DB connection and cursor # self._set_db() # # self.values = {} log.debug("DBHandler set successfully.")
def gen_filesets(self): """ DO NOT call directly. Call via DirectorTools """ # only grab one level deep for dir in self.dir_list: if dir.startswith('.'): log.warning("Skipping hidden file/directory: '{D}'".format(D = dir)) continue # Make fileset dir = dir if dir.endswith(_delim) else dir + _delim _name = _name_from_path(dir) _filename = ''.join([self.director_path, "fileset", _delim, _name, ".conf"]) _template = fileset_template.format( NAME = _name, FILES =''.join([" File = \"", dir, self.symlinks, "\""]), EXCDIRCONTAINING = self.excdircontaining ) msg = "Creating: '{F}'".format(F = _filename) if self.test: msg += " (TEST ONLY)" log.debug(msg) if self.test: print(_template) else: with open(_filename, "w") as FH: FH.write(_template) os.chmod(_filename, 0o755) os.chown(_filename, self.diruid, self.dirgid)
def __init__(self, parser = {}, *args, **kwargs): self.app_name = self.__class__.__name__ # self.CONF = ConfigHandler()# ConfigHandler disabled until py3 update # Convert parsed args to dict and add to kwargs if isinstance(parser, ArgumentParser): # parser = self._arg_parser(parser) ### ALWAYS SET DEFAULTS IN @property ################################## parser.add_argument('--directory', action="store", dest="DIRECTORY", type=str, default = None, help='The directory upon which action is based. (I.e. --generate --jobdefs --directory /gen/jobdef/files/FOR/this/dir') parser.add_argument('--director-path', action="store", dest="DIRECTORPATH", type=str, default = None, help='The directory upon which action is based. (I.e. --generate --jobdefs --directory /gen/jobdef/files/FOR/this/dir') parser.add_argument('--full', action='store_true', dest="FULL", help='Run a Full backup ') parser.add_argument('--logfile', '-L', action="store", dest="LOGFILE", type=str, default = None, help='Logfile file name or full path.\nDEFAULT: ./classname.log') parser.add_argument('--log-level', '-l', action="store", dest="LOGLEVEL", type=str, default = None, help='Logging level.\nDEFAULT: 10.') parser.add_argument('--screendump', '-S', action="store", dest="SCREENDUMP", type=str, default = None, help='For logging only. If "True" all logging info will also be dumped to the terminal.\nDEFAULT: True.') parser.add_argument('--create-paths', '-C', action="store", dest="CREATEPATHS", type=str, default = None, help='For logging only. If "True" will create all paths and files (example create a non-existent logfile.\nDEFAULT: True') parser.add_argument('--test', action='store_true', dest="TEST", help='"test" mode only. Do not perform any real actions (I.e. file writes). \nDEFAULT: False') parser.add_argument('--dir-uid', action="store", dest="DIRUID", type=str, default = None, help='The user ID or username of for the bareos install. \nDEFAULT: bareos') parser.add_argument('--dir-gid', action="store", dest="DIRGID", type=str, default = None, help='The group ID or groupname of for the bareos install. \nDEFAULT: bareos') parser.add_argument('--include-symlinks', action='store_true', dest="SYMLINKS", help='Backup the actual data from symlinks. This is the equiv of putting a "." at the end of the fileset path. I.e. "/root/dir/."') ################################################################### parser_kwargs = parser.parse_args() kwargs.update(vars(parser_kwargs)) elif isinstance(parser, dict): kwargs.update(parser) else: err = "{C}.{M}: Parameter 'parser' ({P}) must be either an Argparse parser object or a dictionary. ".format(C = self.app_name, M = inspect.stack()[0][3], P = str(parser)) raise ValueError(err) # Set classwide self.parser = parser self.args = args self.kwargs = kwargs # # Here we parse out any args and kwargs that are not needed within the self or self.CONF objects # # if "flag" in args: self.flag = something ### ALWAYS SET DEFAULTS IN @property ################################# # # Logging self.logfile = kwargs.get("LOGFILE", None) self.log_level = kwargs.get("LOGLEVEL", None) self.screendump = kwargs.get("SCREENDUMP", None) self.create_paths = kwargs.get("CREATEPATHS", None) #=== loghandler bugfix in Jessie access to self.socket.send(msg) # Only use actual filesystem file for log for now # Log something log.debug("Starting {C}...".format(C = self.app_name), app_name = self.app_name, logfile = self.logfile, log_level = self.log_level, screendump = self.screendump, create_paths = self.create_paths, ) #ONLY the params local to this class. Subcleasses do their own self.directory = kwargs.get("DIRECTORY", None) self.director_path = kwargs.get("DIRECTORPATH",None) self.diruid = kwargs.get("DIRUID", None) self.dirgid = kwargs.get("DIRGID", None) self.symlinks = kwargs.get("SYMLINKS", None) self.test = True if kwargs.get("TEST", False) else False
def _check_db_port(self): try: # Errors if it doesnt exist self.config.db_port # Overrides self.config.db_host if it was passed in self.config.db_port = self.kwargs.pop("db_port", self.config.db_port) except AttributeError as e: log.error(MSG.DBPortNotConfigured()) self.config.db_port = self.default.db_port if (checkInt(self.config.db_port) is False): log.error(MSG.DBPortImproperlyConfigured()) raise AttributeError("Invalid database port '" + str(self.config.db_port) + "'") log.debug('DBHandler.db_port: ' + str(self.config.db_port))
def _check_db_name(self): try: # Errors if it doesnt exist self.config.db_name # Overrides self.config.db_host if it was passed in self.config.db_name = self.kwargs.pop("db_name", self.config.db_name) except AttributeError as e: log.error(MSG.DBNameNotConfigured()) self.config.db_name = self.default.db_name if (checkString(self.config.db_name) is False): log.error(MSG.DBNameImproperlyConfigured()) raise AttributeError("Invalid database name '" + str(self.config.db_name) + "'") log.debug('DBHandler.db_name: ' + str(self.config.db_name))
def controlled_delete(self, p): _p = str(p) msg = "DELETING FILE: '{P}'".format(P = _p) if self.test: msg += "(test only)" log.warning(msg) filename = ntpath.basename(_p) lastdir = ntpath.dirname(_p) lastdir = lastdir.split(_delim) lastdir = lastdir[len(lastdir)-1] tmpdir = os.path.join(tempfile.gettempdir(), "bareos_director_deletes", lastdir) if not os.path.isdir(tmpdir): try: os.makedirs(tmpdir) except Exception as e: err = "Unable to create 'deletion' directory '{D}'. Aborting delete. Please remove files manually. (ERR: {E}".format(D = tmpdir, E = str(e)) log.error(err) raise RuntimeError(err) dst = os.path.join(tmpdir, filename) # print("Copy from '{P}' to '{D}'".format(P = _p, D = dst) ) msg = "copyfile({P}, {D})' ...".format(P = str(p), D = dst) if self.test: msg += "OK (test only)" else: try: copyfile(str(p), dst) msg += "OK" log.debug(msg) except Exception as e: msg += "FAILED! (ERROR: {E})".format(E=str(e)) log.error(msg) msg = "{P}.unlink ...".format(P = str(p)) if self.test: msg += "OK (test only)" else: try: p.unlink() msg += "OK" log.debug(msg) except Exception as e: msg += "FAILED! (ERROR: {E})".format(E=str(e)) log.error(msg)
def _check_host(self): try: # Errors if it doesnt exist self.config.db_host # Overrides self.config.db_host if it was passed in self.config.db_host = self.kwargs.pop("db_host", self.config.db_host) except AttributeError as e: log.error(MSG.DBHostNotConfigured()) self.config.db_host = self.default.db_host if ((checkIP(self.config.db_host) is False) and (checkServername(self.config.db_host) is False)): log.error(MSG.DBHostImproperlyConfigured()) raise AttributeError("Invalid database host name '" + str(self.config.db_host) + "'") log.debug('DBHandler.db_host: ' + str(self.config.db_host))
def gen_jobdefs(self): """ DO NOT call directly. Call via DirectorTools """ # only grab one level deep for dir in self.dir_list: if dir.startswith('.'): log.warning("Skipping hidden file/directory: '{D}'".format(D = dir)) continue dir = dir if dir.endswith(_delim) else dir + _delim _name = _name_from_path(dir) _filename = ''.join([self.director_path, "jobdefs", _delim, _name, ".conf"]) _template = jobdef_template.format( NAME = _name, TYPE = self.backup_type, LEVEL = self.level, POOL = self.pool, CLIENT = self.client, FILESET = _name, # Uses the fileset name, not the actual dir SCHEDULE = self.schedule, STORAGE = self.storage, MESSAGES = self.messages, PRIORITY = self.priority, BOOTSTRAP = self.bootstrap, FULLBACKUPPOOL = self.fullbackuppool, DIFFBACKUPPOOL = self.diffbackuppool, INCBACKUPPOOL = self.incbackuppool ) msg = "Creating: '{F}'".format(F = _filename) if self.test: msg += " (TEST ONLY)" log.debug(msg) if self.test: print(_template) else: with open(_filename, "w") as FH: FH.write(_template) os.chmod(_filename, 0o755) os.chown(_filename, self.diruid, self.dirgid)
def __init__(self, parser={}, *args, **kwargs): """ ALL @properties and argparse for ALL SUBCLASSES should be defined HERE. """ self.app_name = self.__class__.__name__ if isinstance(parser, ArgumentParser): ### SET ALL ARGPARSE OPTIONS and ################# ### ALL KWARGS OPTIONS HERE for all child classes ################# ### ALWAYS SET DEFAULTS THROUGH THE @property ###################### # Always set the defaults via the @property.setter ONLY # As an example, # parser.add_argument('--someparam', action='store_true', dest="someparam", help='Usage instructions (DEFAULT: default_value)') # REMEBER THAT '--someparam', 'dest="someparam" ', and the later # @property def someparam(self) must all be the same word 'someparam' # and must all be small case! parser.add_argument('--someparam', '-P', action="store", dest="someparam", type=str, default=None, help='Some initial parameters.') parser.add_argument('--someflag', '-F', action="store_true", dest="someflag", help='Some initial parameters.') parser.add_argument( '--logfile', '-L', action="store", dest="logfile", type=str, help='Logfile file name or full path.\nDEFAULT: ./classname.log' ) parser.add_argument('--loglevel', '-l', action="store", dest="loglevel", type=str, help='Logging level.\nDEFAULT: 10.') parser.add_argument( '--screendump', '-S', action="store", dest="screendump", type=str, help= 'For logging only. If "True" all logging info will also be dumped to the terminal.\nDEFAULT: True.' ) parser.add_argument( '--createpaths', '-C', action="store", dest="createpaths", type=str, help= 'For logging only. If "True" will create all paths and files (example create a non-existent logfile.\nDEFAULT: True' ) parser_kwargs = parser.parse_args() kwargs.update(vars(parser_kwargs)) elif isinstance(parser, dict): kwargs.update(parser) else: err = "{C}.{M}: Parameter 'parser' ({P}) must be either an Argparse parser object or a dictionary. ".format( C=self.app_name, M=inspect.stack()[0][3], P=str(parser)) raise ValueError(err) # Set classwide here self.parser = parser self.args = args self.kwargs = kwargs # # Here we parse out any args and kwargs that are not needed within the self or self.CONF objects # # if "flag" in args: self.flag = something ### ALWAYS SET DEFAULTS IN @property ################################# # # Logging self.logfile = kwargs.get("logfile", ''.join(["./", self.app_name, ".log"])) self.log_level = kwargs.get("loglevel", 10) self.screendump = kwargs.get("screendump", True) self.create_paths = kwargs.get("createpaths", True) #=== loghandler bugfix in Jessie access to self.socket.send(msg) # Only use actual filesystem file for log for now # Log something log.debug( "Starting {C}...".format(C=self.app_name), app_name=self.app_name, logfile=self.logfile, log_level=self.log_level, screendump=self.screendump, create_paths=self.create_paths, ) ### ALWAYS SET DEFAULTS THROUGH AN @property ###################### self.someparam = kwargs.get("someparam", None) self.someflag = kwargs.get("someflag", None)