Commit e5f3f9af authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

Debugged. Should do now it's job.

This is a legacy commit from before 2015-05-18.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.

I'll finish testing tomorrow.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 4361
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 7c6d3aaf
......@@ -46,18 +46,18 @@ import sys
import getopt
import os
from datetime import datetime
if sys.version_info == (2,)
if sys.version_info >= (2,) and sys.version_info < (3,):
from ConfigParser import ConfigParser
from ConfigParser import ParsingError
from ConfigParser import NoSectionError
from ConfigParser import NoOptionError
elif sys.version_info == (3,)
elif sys.version_info >= (3,):
from configparser import ConfigParser
from configparser import ParsingError
from configparser import NoSectionError
from configparser import NoOptionError
else
sys.stderr.write("csback2cron: Incompatible python version.")
else:
sys.stderr.write("csback2cron: Incompatible python version.\n")
__version__ = "V0.1"
__subversion__ = "$Id$"
......@@ -103,7 +103,7 @@ def help():
If this argument wasn't passed csback2cron assumes
~/.csback/csbackrc as default path to the configuration
file.
-o/--overwrite Overwrite already existing crontab.
-o|--overwrite Overwrite already existing crontab.
<CRONTABFILENAME> Outputfilename of the generated crontab.
-------------------------------------------------------------------------------
Notice that csback2cron does not check any logical values e.g. pathes and/or
......@@ -120,16 +120,16 @@ class Converter():
self.line = ''
self.addCronExpr = True
def covert(self)
def convert(self):
"""
Abstract function
"""
self.convertDict(self)
self.convertDict()
def convertDict(self):
raise NotImplementedError("function must be defined!")
def __str__(self)
def __str__(self):
"""
String representation of converted section dictionary.
"""
......@@ -178,7 +178,7 @@ class BackupConverter(Converter):
"""
def convertDict(self):
self.line = self.sectionDict['cronexpr']+' rsync -aq'
for regex in self.sectionDict['exclude']
for regex in self.sectionDict['exclude']:
self.line += " --exclude='"+regex+"'"
self.line += self.sectionDict['srcdir']+' '+self.sectionDict['targetdir']+ \
'; csbackgen'
......@@ -188,12 +188,12 @@ class BackupConverter(Converter):
self.line += ' -R'
if self.sectionDict['followlinks']:
self.line += ' -f'
for regex in self.sectionDict['exclude']
self.line += " -e '"+regex+"'
for regex in self.sectionDict['exclude']:
self.line += " -e '"+regex+"'"
self.line += ' -t '+self.sectionDict['targetdir']+' '+ \
self.sectionDict['srcdir']
if self.sectionDict['test']:
testConv = TestConverter({'cronexpr:' self.sectionDict['cronexpr'], \
testConv = TestConverter({'cronexpr': self.sectionDict['cronexpr'], \
'srcdir': self.sectionDict['targetdir'], \
'dir': self.sectionDict['targetdir'], \
'exclude': self.sectionDict['exclude'], \
......@@ -225,26 +225,27 @@ class Processor():
"""
Read the csback configuration file.
"""
if not os.path.isfile(self.__configfile):
if not os.path.isfile(self.configfile):
raise Error("Given CONFIGFILE is not a regular file.")
if os.stat(self.__configfile).st_size == 0:
if 0 == os.stat(self.configfile).st_size:
raise Error("Given CONFIGFILE is an empty file.")
if self.__verbose:
sys.stdout.write("csback2cron: Reading CONFIGFILE ... ")
sys.stdout.write("csback2cron: Reading CONFIGFILE ... \n")
try:
self.config.read(configfile)
self.config.read(self.configfile)
except ParsingError as err:
raise Error("{0}".format(err.message))
# fetch mail section
if self.config.has_section('mail'):
try:
self.mail['cronexpr'] = config.get('mail', 'cronexpr').strip()
self.mail['cronexpr'] = self.config.get('mail', 'cronexpr').strip()
self.mail['receivers'] = \
self.config.get('mail', 'receivers').split(',')
self.mail['receivers'] = [add.strip() \
for add in self.mail['receivers']]
self.mail['sender'] = self.config.get('mail', 'sender').strip()
self.mail['host'] = self.config.get('mail', 'host').strip()
self.mail['port'] = self.config.get('mail', 'port').strip()
self.mail['username'] = self.config.get('mail', 'username').strip()
self.mail['password'] = self.config.get('mail', 'password').strip()
if self.config.has_option('mail', 'logging'):
......@@ -259,39 +260,32 @@ class Processor():
self.mail = {}
# fetch backups section
try:
backupKeys = dict(self.config.items('backups'))
if 'keys' in backupKeys:
backups = set(backupKeys['keys'].split(","))
backups = ['backup_'+key.strip() for key in backups]
# fetch every backup section
for key in backups:
if not self.config.has_section(key):
raise Error("Section {0} in configfile not defined.".format(key))
backup = {'id': key}
try:
backup['cronexpr'] = config.get(key, 'cronexpr').strip()
backup['srcdir'] = config.get(key, 'srcdir').strip()
backup['targetdir'] = config.get(key, 'targetdir').strip()
backup['exclude'] = config.get(key, 'exclude').split(", ")
if self.config.has_option(key, 'recursive'):
backup['recursive'] = self.config.getboolean(key, 'recursive')
if self.config.has_option(key, 'logging'):
backup['logging'] = self.config.getboolean(key, 'logging')
if self.config.has_option(key, 'followlinks'):
backup['followlinks'] = self.config.getboolean(key, 'followlinks')
if self.config.has_option(key, 'test'):
backup['test'] = self.config.getboolean(key, 'test')
if self.config.has_option(key, 'tolerant'):
backup['tolerant'] = self.config.getboolean(key, 'tolerant')
except NoOptionError as err:
raise Error("{0}".format(err.message))
except ValueError:
raise Error("Argument error in [{0}] section.".format(key))
else:
self.backups.append(backup)
else:
raise Error(\
"Key 'keys' in configfile section [backups] not defined.")
backupKeys = self.config.get('backups', 'keys')
backupKeys = set(backupKeys.split(","))
backupKeys = ['backup_'+key.strip() for key in backupKeys]
# fetch every backup section
for key in backupKeys:
if not self.config.has_section(key):
raise Error("Section {0} in configfile not defined.".format(key))
backup = {'id': key}
try:
backup['cronexpr'] = self.config.get(key, 'cronexpr').strip()
backup['srcdir'] = self.config.get(key, 'srcdir').strip()
backup['targetdir'] = self.config.get(key, 'targetdir').strip()
backup['exclude'] = self.config.get(key, 'exclude',raw=1).split(", ")
backup['recursive'] = self.config.getboolean(key, 'recursive')
backup['logging'] = self.config.getboolean(key, 'logging')
backup['followlinks'] = self.config.getboolean(key, 'followlinks')
backup['test'] = self.config.getboolean(key, 'test')
backup['tolerant'] = self.config.getboolean(key, 'tolerant')
except NoOptionError as err:
raise Error("{0}".format(err.message))
except ValueError:
raise Error("Argument error in [{0}] section.".format(key))
else:
self.backups.append(backup)
except NoOptionError as err:
raise Error("{0}".format(err.message))
except NoSectionError:
self.backups = {}
# fetch tests section
......@@ -306,21 +300,17 @@ class Processor():
raise Error("Section {0} in configfile not defined.".format(key))
test = {'id': key}
try:
test['cronexpr'] = config.get(key, 'cronexpr').strip()
test['dir'] = config.get(key, 'dir').strip()
test['cronexpr'] = self.config.get(key, 'cronexpr').strip()
test['dir'] = self.config.get(key, 'dir').strip()
if self.config.has_option(key, 'srcdir'):
test['srcdir'] = self.config.get(key, 'srcdir').strip()
else:
test['srcdir'] = test['dir']
test['exclude'] = config.get(key, 'exclude').split(", ")
if self.config.has_option(key, 'recursive'):
test['recursive'] = self.config.getboolean(key, 'recursive')
if self.config.has_option(key, 'logging'):
test['logging'] = self.config.getboolean(key, 'logging')
if self.config.has_option(key, 'followlinks'):
test['followlinks'] = self.config.getboolean(key, 'followlinks')
if self.config.has_option(key, 'tolerant'):
test['tolerant'] = self.config.getboolean(key, 'tolerant')
test['exclude'] = self.config.get(key, 'exclude', raw=1).split(", ")
test['recursive'] = self.config.getboolean(key, 'recursive')
test['logging'] = self.config.getboolean(key, 'logging')
test['followlinks'] = self.config.getboolean(key, 'followlinks')
test['tolerant'] = self.config.getboolean(key, 'tolerant')
except NoOptionError as err:
raise Error("{0}".format(err.message))
except ValueError:
......@@ -333,31 +323,31 @@ class Processor():
except NoSectionError:
self.tests = {}
if self.__verbose:
sys.stdout.write("csback2cron: Finished reading CONFIGFILE.")
sys.stdout.write("csback2cron: Finished reading CONFIGFILE.\n")
def convert(self):
"""
Convert the csback configuration file to a crontab file.
"""
if self.__verbose:
sys.stdout.write("csback2cron: Conversion ... ")
sys.stdout.write("csback2cron: Conversion ... \n")
# convert backup sections
if len(self.backups) and self.__verbose:
sys.stdout.write("csback2cron: Converting backup sections ...")
sys.stdout.write("csback2cron: Converting backup sections ...\n")
for backup in self.backups:
backupConv = BackupConverter(backup)
backupConv.convert()
self.result.append(str(backupConv)+"\n")
# convert test sections
if len(self.tests) and self.__verbose:
sys.stdout.write("csback2cron: Converting test sections ...")
sys.stdout.write("csback2cron: Converting test sections ...\n")
for test in self.tests:
testConv = TestConverter(test)
testConv.convert()
self.result.append(str(testConv)+"\n")
# convert mail section
if len(self.mail) and self.__verbose:
sys.stdout.write("csback2cron: Converting mail section ...")
sys.stdout.write("csback2cron: Converting mail section ...\n")
if len(self.mail):
mailConv = MailConverter(self.mail)
mailConv.convert()
......@@ -371,16 +361,19 @@ class Processor():
output = ['# This is <' + self.crontabfile + '>\n',
'# Generated with csback2cron.\n',
'# '+datetime.now().strftime("%Y-%m-%d %H:%M:%S")+'\n',
'# -------------------------------------------------------------\n']
'# -------------------------------------------------------------\n\n']
output.extend(self.result)
if self.__verbose:
sys.stdout.write("csback2cron: Writing " + self.__crontabfile + " ...")
crontabfile = open(self.__crontabfile, 'w')
sys.stdout.write("csback2cron: Writing " + self.crontabfile + \
" ...\n")
crontabfile = open(self.crontabfile, 'w')
crontabfile.writelines(output)
crontabfile.close()
if self.__verbose:
sys.stdout.write("csback2cron: " + self.crontabfile + " written.\n")
DEFAULTS = {'logging': True, 'recursive': True, 'followlinks': False, \
'tolerant': False, 'test': True, 'exclude' : ''}
DEFAULTS = {'logging': 'yes', 'recursive': 'yes', 'followlinks': 'false', \
'tolerant': 'no', 'test': 'yes', 'exclude': ''}
# -----------------------------------------------------------------------------
def main(argv=None):
......@@ -420,7 +413,10 @@ def main(argv=None):
processor = Processor(inputfile, outputfile, verbose=verbose)
processor.read()
processor.convert()
process.write()
processor.write()
except Error as err:
err.display()
return 2
except Usage as err:
err.display()
return 2
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment