csbackchk.py 7.94 KB
Newer Older
1
2
#!/usr/bin/env python
## @file csbackchk.py
3
# @brief Check checksums or rather integrity of corresponding files. 
4
5
6
7
8
# 
# -----------------------------------------------------------------------------
# 
# $Id$
# @author Daniel Armbruster
9
# \date 03/01/2012
10
# 
11
# Purpose: Check checksums or rather integrity of corresponding files.
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#
# ----
# This file is part of csback.
#
# csback 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.
# 
# csback 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 csback.  If not, see <http://www.gnu.org/licenses/>.
# ----
# 
30
# Copyright (c) 2012 by Daniel Armbruster
31
32
# 
# REVISIONS and CHANGES 
33
# 03/01/2012  V0.1  Daniel Armbruster
34
35
# 10/01/2012  V0.2  adjustments because every subdirectory now contains its own
#                   checksumfile.
36
37
38
# 
# =============================================================================
 
39
40
41
42
43
44
import getopt
import os
import sys
import pwd
import logging
import csfile
45
import csbacklog
46

47
__version__ = "V0.2"
48
49
50
51
__subversion__ = "$Id$"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
__copyright__ = "Copyright (c) 2012 by Daniel Armbruster"
52

53
54
55
# -----------------------------------------------------------------------------
class Error(Exception):

56
57
  def __init__(self, line, msg):
    self.line = str(line)
58
59
60
61
    self.msg = msg

  def display(self):
    sys.stderr.write("csbackchk (ERROR): " + self.msg + "\n")
62
    sys.stderr.write("triggered in line: " + self.line + "\n")
63
64
65
66
67
68
69
70
71


class Usage(Error):

  def display(self):
    usage_text = "Version: "+__version__+"\nLicense: "+__license__+ \
      "\n"+__subversion__+"\nAuthor: "+__author__+ """
 Usage: csbackchk [-v|--verbose] [-e REGEX [-e REGEX [...]]]
                  [-R|--notrecursive] [-d|--debug] [-f|--followlinks] 
72
                  [-t|--tolerant] [-l|--logging] [SOURCEPATH] PATH
73
    or: csbackchk -h|--help\n"""
74
    sys.stderr.write("csbackchk [line "+self.line+"]: "+self.msg+"\n")
75
76
77
78
79
80
81
82
83
84
85
    sys.stderr.write(usage_text)

# -----------------------------------------------------------------------------
def help():
  """
  Printing helptext to stdout.
  """
  help_text = "Version: "+__version__+"\nLicense: "+__license__+"\n"+ \
    __subversion__+"\nAuthor: "+__author__+"""
 Usage: csbackchk [-v|--verbose] [-e REGEX [-e REGEX [...]]]
                  [-R|--notrecursive] [-d|--debug] [-f|--followlinks]
86
                  [-t|--tolerant] [-l|--logging] [SOURCEPATH] PATH
87
88
89
90
    or: csbackchk -h|--help
-------------------------------------------------------------------------------
 -v|--verbose       Be verbose.
 -h|--help          Display this help.
91
92
 -e REGEX           While checking a checksumfile(s) exclude files and
                    directories matching REGEX(s).
93
94
95
96
97
98
99
100
101
 -R|--notrecursive  Do not search in subdirectories of PATH.
 -d|--debug         Debug mode. Be really verbose.
 -f|--followlinks   Follow symbolic links. Only available if option -R is not
                    set. Note that this option can lead to infinite recursion.
 -t|--tolerant      Be tolerant.
                    While checking don't report anything if a file listed in
                    the checksumfile is missing. This flag is useful if a test
                    of a directory is executed but this directory is realized
                    e.g. as a ring buffer.
102
103
 -l|--logging       Switch on logging to files. Logfiles will be located in
                    ~/.csback/log/.
104
 SOURCEPATH         Optional sourcepath for comparison with files backed up in
105
106
                    PATH. PATH and its subdirectories (if option '-R' had not
                    been selected) must contain the csback checksumfile(s).
107
                    Note that the directory structure (if option '-R' is not
108
                    set) bellow SOURCEPATH should be equal to those in PATH
109
                    because otherwise the files won't be found.
110
111
                    If SOURCEPATH is not passed a check of files located in
                    PATH with its checksumfiles will be performed.
112
113
114
 PATH               Path to perform check with its checksumfile(s). If option
                    '-R' had not been set the check will be performed
                    additionally for PATHs' subdirectories.
115
116
"""
  sys.stdout.write(help_text)
117
118

# -----------------------------------------------------------------------------
119
120
def main(argv=None):
  # configure logger
121
122
  logger = csbacklog.CsbackLog('csbackchk')
  
123
  console = logging.StreamHandler()
124
125
  console.setFormatter(logging.Formatter( \
    '%(name)-8s [%(lineno)d]: %(levelname)-8s %(message)s'))
126

127
  # fetch arguments
128
129
130
131
  if argv is None:
    argv = sys.argv
  try:
    try:
132
133
      opts, args = getopt.getopt(argv[1:], "vhe:Rdftl", ["help", "verbose", \
        "notrecursive", "debug", "followlinks", "tolerant", "logging"])
134
    except getopt.GetoptError as err:
135
      raise Usage(135,err.msg)
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    verbose = False
    debugMode = False
    notRecursive = False
    followLinks = False
    beTolerant = False
    regexes = []
    # collect arguments
    for opt, arg in opts:
      if opt in ("-v", "--verbose"):
        verbose = True
        console.setLevel(logging.INFO)
      elif opt in ("-h", "--help"):
        sys.exit(help())
        return 0
      elif opt in ("-R", "--notrecursive"):
        notRecursive = True
      elif opt in ("-e"):
        regexes.append(arg)
      elif opt in ("-d", "--debug"):
        debugMode = True
        console.setLevel(logging.DEBUG)
      elif opt in ("-f", "--followlinks"):
        followLinks = True
      elif opt in ("-t", "--tolerant"):
        beTolerant = True
161
162
      elif opt in ("-l", "--logging"):
        logger.configure()
163
      else:
164
        raise Usage(164,"Unhandled option chosen.")
165
166

    if verbose or debugMode:
167
      logger.addHandler(console)
168

Daniel Armbruster's avatar
Daniel Armbruster committed
169
170
    if 1 == len(args) or 2 == len(args) and \
      args[0].rstrip(os.sep)+os.sep == args[1].rstrip(os.sep)+os.sep:
171
      sourcepath = str(args[0]).rstrip(os.sep)+os.sep
172
      sourceDirs = [sourcepath]
173
      inputpath = sourcepath 
174
      inputDirs = sourceDirs
175
176
    elif 2 == len(args):
      sourcepath = str(args[0]).rstrip(os.sep)+os.sep 
177
      sourceDirs = [sourcepath] 
178
      inputpath = str(args[1]).rstrip(os.sep)+os.sep 
179
      inputDirs = [inputpath] 
180
    else:
181
      raise Usage(180,"Invalid argument(s).")
182
183

    # major part
184
185
186
187
188
189
190
191
192
193
    logger.getLogger().debug("Collecting subdirectories ...")
    # recursive
    if not notRecursive:
      sourceDirs.extend( \
        csfile.getSubDirectories(sourcepath, regexes, followLinks))
      if sourceDirs[0] != inputDirs[0]:
        inputDirs.extend( \
          csfile.getSubDirectories(inputpath, regexes, followLinks))
         
    if len(sourceDirs) != len(inputDirs):
Daniel Armbruster's avatar
Daniel Armbruster committed
194
      raise Error(194, \
195
196
        "Directory structure of inputpath and sourcepath different.")
      
197
    if not csfile.hasCsFile(inputpath):
Daniel Armbruster's avatar
Daniel Armbruster committed
198
      raise Error(198,"PATH does not contain a checksumfile.")
199
200
201
202
203
204
205
206

    paths = list(zip(inputDirs, sourceDirs))
  
    logger.getLogger().info("Start checking checksums ...")
    for path in paths:
      checksumfile = csfile.CsFile(path[0], path[1])
      checksumfile.read()
      checksumfile.check(regexes, beTolerant)
207

208
209
210
  except Usage as err:
    err.display()
    return 2
211
  except Error as err:
212
    logger.getLogger().error("message: %s [line %s]", err.msg, err.line)
213
214
    err.display()
    return 2
215
  except csfile.CsFileError as err:
216
    logger.getLogger().error("message: %s [line %s]", err.msg, err.line)
217
218
219
    err.display()
    return 2
  else:
220
    logger.getLogger().info("Checks performed.")
221
222
223
224
225
226
227
    return 0
    
# -----------------------------------------------------------------------------
if __name__ == "__main__":
  sys.exit(main())

# ----- END OF csbackchk.py -----