csfile.py 9.72 KB
Newer Older
1
#!/usr/bin/env python
Daniel Armbruster's avatar
Daniel Armbruster committed
2
## @file csfile.py
Daniel Armbruster's avatar
Daniel Armbruster committed
3
4
# @brief  Provide a module to read, write and treat with a csback
# checksumfiles.
Daniel Armbruster's avatar
Daniel Armbruster committed
5
6
7
8
9
10
11
# 
# -----------------------------------------------------------------------------
# 
# $Id$
# @author Daniel Armbruster
# \date 15/09/2011
# 
Daniel Armbruster's avatar
Daniel Armbruster committed
12
13
# Purpose: Provide a module to read, write and treat with a csback
# checksumfiles.
Daniel Armbruster's avatar
Daniel Armbruster committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#
# ----
# 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/>.
# ----
# 
# Copyright (c) 2011 by Daniel Armbruster
# 
# REVISIONS and CHANGES 
# 15/09/2011  V0.1    Daniel Armbruster
# 
# =============================================================================
38
""" CsFile module to handle checksum files. """
Daniel Armbruster's avatar
Daniel Armbruster committed
39

Daniel Armbruster's avatar
Daniel Armbruster committed
40
41
import os
import re
42
import sys
Daniel Armbruster's avatar
Daniel Armbruster committed
43
import hashlib
Daniel Armbruster's avatar
Daniel Armbruster committed
44
from datetime import datetime
Daniel Armbruster's avatar
Daniel Armbruster committed
45

46
__version__ = "V0.1"
Daniel Armbruster's avatar
Daniel Armbruster committed
47
__subversion__ = "$Id$"
48
49
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
Daniel Armbruster's avatar
Daniel Armbruster committed
50
51
52
53
54
55
__copyright__ = "Copyright (c) 2012 by Daniel Armbruster"

# -----------------------------------------------------------------------------
# global variables

chunkSize = 131072 # 128kB
Daniel Armbruster's avatar
Daniel Armbruster committed
56

57
58
59
# -----------------------------------------------------------------------------
class CsFileError(Exception):

60
  def __init__(self, msg, line):
61
    self.msg = msg
62
    self.line = line
63
64

  def display(self):
65
66
    sys.stderr.write("csfile (ERROR): " + self.msg + "\n")
    sys.stderr.write("triggered in line: " + str(self.line) + "\n")
67
68
69

# -----------------------------------------------------------------------------
class CsFile:
70
71
72
  """
  Provides an interface to handle a csback checksum file.
  """
Daniel Armbruster's avatar
Daniel Armbruster committed
73
74
75
  def __init__(self, filepath, hashfunc='sha256'):
    self.__filepath = filepath
    self.__filename = ".cs"
76
77
    self.__cslines = []
    self.__hashfunc = hashfunc
78
    self.createFile()
Daniel Armbruster's avatar
Daniel Armbruster committed
79
80
81
82
83
84

  def createFile(self):
    path = self.__filepath+os.sep+self.__filename
    if not os.path.isfile(path):
      try:
        csfile = open(path, 'w')
85
86
87
88
      except IOError as err:
        raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
          +err.filename, 87)
      else:
Daniel Armbruster's avatar
Daniel Armbruster committed
89
        csfile.close()
90
91

  def read(self):
92
93
94
    """
    Read a checksum file.
    """
Daniel Armbruster's avatar
Daniel Armbruster committed
95
    path = self.__filepath+os.sep+self.__filename
96
    try:
Daniel Armbruster's avatar
Daniel Armbruster committed
97
      csfile = open(path)
98
99
      self.__cslines = [CsLine(line.split()) for line in csfile \
      if len(line.rstrip()) and line[0] != '#'] 
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    except IOError as err:
      # Maybe better to create the file here and keep on going.
      # Will be managed later during further dev.
      raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
        +err.filename, 104)
    else:
      csfile.close()

  def write(self):
    """
    Write the entire checksumfile.
    """
    path = self.__filepath+os.sep+self.__filename
    try:
      csfile = open(path, 'w')
      for csline in self.__cslines:
        if isinstance(csline, CsLine):
          csfile.write(str(csline) + '\n')
        else:
          raise CsFileError("Argument must be of type CsLine.", 116)
    except IOError as err:
      raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
        +err.filename, 119)
    else:
124
      csfile.close()
Daniel Armbruster's avatar
Daniel Armbruster committed
125

Daniel Armbruster's avatar
Daniel Armbruster committed
126
  def append(self, cslines):
127
128
129
    """
    Append checksum lines to the checksum file.
    """
Daniel Armbruster's avatar
Daniel Armbruster committed
130
131
132
    path = self.__filepath+os.sep+self.__filename
    # Maybe not necessary to raise an exception here
    if 0 == len(cslines):
133
      raise CsFileError("Invalid argument. Empty list.", 130) 
Daniel Armbruster's avatar
Daniel Armbruster committed
134
135
136
137
138
139
    try:
      csfile = open(path, 'a')
      for csline in cslines:
        if isinstance(csline, CsLine):
          csfile.write(str(csline) + '\n')
        else:
140
          raise CsFileError("Argument must be of type CsLine.", 137)
Daniel Armbruster's avatar
Daniel Armbruster committed
141
    except IOError as err:
142
143
144
      raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
        +err.filename, 140)
    else:
Daniel Armbruster's avatar
Daniel Armbruster committed
145
146
147
      csfile.close()
      
  def update(self, regexes=[]):
148
149
150
151
152
153
    """
    Update a checksum file. Also includes appending of not registered files to
    checksum file in current directory.
    """
    if not isinstance(regexes, list):
      raise CsFileError("Pass regular expressions in a list of strings", 150)
Daniel Armbruster's avatar
Daniel Armbruster committed
154
    # fetch cslines in current csfile
155
    self.read()
Daniel Armbruster's avatar
Daniel Armbruster committed
156
    # IMPORTANT NOTE: Check again if it is more convenient to  whole path or 
157
    registeredFiles = [csline.path.split(os.sep)[-1] \
Daniel Armbruster's avatar
Daniel Armbruster committed
158
159
160
161
162
163
164
165
166
167
168
      for csline in self.__cslines]
    # fetch files excluding regex matches
    newFiles = list(set([file for file in os.listdir(self.__filepath) \
      if os.path.isfile(file) for regex in regexes \
      if None == re.search(regex,file)]))
    # exclude registered files
    newFiles = list(set([file for file in newFiles \
      for registeredFile in registeredFiles if registeredFile != file]))
    # generate cslines of newFiles
    csLines = [CsLine(self.__filepath+os.sep+file, self.__hashfunc) \
      for file in newFiles]
169
170
171
    for line in csLines:
      line.generate(chunkSize)
    self.append(csLines)
Daniel Armbruster's avatar
Daniel Armbruster committed
172

173
174
175
176
177
178
179
180
  def check(self, srcDir=''):
    """
    Check a checksum file which means:
    1. read checksum file
    2, calculate checksum of file which is located in srcDir and check results
    3. write the result to the checksum file
    """
    self.read()
181
    if 0 == len(self.__cslines):
182
183
184
185
186
187
188
189
      raise CsFileError("CSFILE does not contain any lines.", 179)
    for csline in self.__cslines:
      if not len(srcDir):
        csline.check()
      else:
        filename = csline.path.split(os.sep)[-1]
        csline.check(srcDir+os.sep+filename)
    self.write()
190
191

  def displayLines(self):
192
193
194
195
196
    """
    Display the content of the checksum file at stdout.
    """
    if not len(self.__cslines):
      raise CsFileError("CSFILE does not contain any lines.", 193)
197
198
199
200
201
    for line in self.__cslines:
      sys.stdout.write(line)

# -----------------------------------------------------------------------------
class CsLine:
202
203
204
  """
  Class to handle a checksum and further data for a registered file.
  """
Daniel Armbruster's avatar
Daniel Armbruster committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

  def __init__(self, path, hashfunc='sha256'):
    self.checksum = ''
    self.path = path
    self.hashfunc = hashfunc
    self.creationDateFile = ''
    self.creationLocationChecksum = ''
    self.creationDateChecksum = ''
    self.dateLastCheck = ''
    self.statusLastCheck = ''

  def __init__(self, argList):
    if not isinstance(argList, list):
      raise CsFileError("Invalid argument.")
    self.checksum = argList[0]
    self.path = argList[1]
    self.hashfunc = argList[2]
    self.creationDateFile = argList[3]
    self.creationLocationChecksum = argList[4]
    self.creationDateChecksum = argList[5]
    self.dateLastCheck = argList[6]
    self.statusLastCheck = argList[7]

  def generate(self, chunkSize):
229
230
231
232
    """
    Generate the checksum and establish corresponding data for a file. The
    result is a fully configured checksum line.
    """
Daniel Armbruster's avatar
Daniel Armbruster committed
233
234
235
236
237
    # generate checksum
    try:
      hashfunc = hashlib.new(self.hashfunc)
      blockSize = chunkSize * hashfunc.block_size
      with open(self.path, "rb") as file:
238
        for chunk in iter(lambda: file.read(blockSize), ''):
Daniel Armbruster's avatar
Daniel Armbruster committed
239
240
241
          hasfunc.update(chunk)
      self.checksum = hashfunc.hexdigest()
    except IOError as err:
242
243
244
245
246
      raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
        +err.filename, 240)
    else:
      file.close()
      
Daniel Armbruster's avatar
Daniel Armbruster committed
247
248
249
250
251
252
253
254
255
256
    # set remaining data
    self.creationDateFile = \
      datetime.fromtimestamp(os.path.getctime(self.path)).strftime( \
      "%Y/%m/%d-%H:%M:%S")
    self.creationLocationChecksum = os.uname()[1]
    self.creationDateChecksum = datetime.now().strftime("%Y/%m/%d-%H:%M:%S")
    self.dateLastCheck = self.creationDateChecksum 
    self.statusLastCheck = 'ok'

  def check(self, src=''):
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    """
    Check a checksum line. Either compare the checksum of the line with the
    checksum of the file located at src or compare the checksum with the checksum
    of the file located at the path of its one checksum line.
    """
    # calculate checksum
    try:
      hashfunc = hashlib.new(self.hashfunc)
      blockSize = chunkSize * hashfunc.block_size
      if 0 == len(src):
        with open(self.path, "rb") as file:
          for chunk in iter(lambda: file.read(blockSize), ''):
            hasfunc.update(chunk)
      else:
        with open(src, "rb") as file:
          for chunk in iter(lambda: file.read(blockSize), ''):
            hasfunc.update(chunk)
        checksum = hashfunc.hexdigest()
    except IOError as err:
      # Maybe better to avoid Exception here and just put the status to notice
      raise CsFileError("[Errno "+str(err.errno)+"] "+err.strerror+": " \
        +err.filename, 275)
    else:
      file.close()
      # checks
      if not len(self.checksum):
        raise CsFileError("No checksum calculated yet.", 280)
      if checksum == self.checksum:
        self.statusLastCheck = 'ok'
      else:
        self.statusLastCheck = 'error'
288

Daniel Armbruster's avatar
Daniel Armbruster committed
289
  def __str__(self):
290
291
292
    """
    String representation of a checksum line.
    """
Daniel Armbruster's avatar
Daniel Armbruster committed
293
294
295
296
    return '{0} {1} {2} {3} {4} {5} {6} {7}'.format(self.checksum, self.path, \
    self.hashfunc, self.creationDateFile, self.creationLocationChecksum, \
    self.creationDateChecksum, self.dateLastCheck, self.statusLastCheck)
    
297
# -----------------------------------------------------------------------------
298
# Tests
299
if __name__ == '__main__':
300
301
302
303
304
305
  try:
    file = CsFile('/home/daniel/')
    file.read()
  except CsFileError as err:
    err.display()
    sys.exit()
Daniel Armbruster's avatar
Daniel Armbruster committed
306
307
  
  
Daniel Armbruster's avatar
Daniel Armbruster committed
308
# ----- END OF csfile.py -----