git » abk » master » tree

[master] / abk

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
#!/usr/bin/python

# A backup script
# Alberto Bertogli (albertogli@telpin.com.ar)
# Version 0.03

import sys
import os
import sha
import cPickle
import re
from stat import *


#
# constants
#

PSIZE = 4 * 1024

VERSION = "0.03"


#
# classes
#

# file_info functions are not included directly in the class to avoid memory
# waste, which is about 1k per file.

def finfo_load(finfo):
	"Loads data from the file."
	s = os.lstat(finfo.fullname)
	finfo.stat = s
	if S_ISREG(s.st_mode):
		finfo.type = 'r'
	elif S_ISLNK(s.st_mode):
		finfo.type = 'l'
	elif S_ISCHR(s.st_mode):
		finfo.type = 'c'
		finfo.rdev = s.st_rdev
	elif S_ISBLK(s.st_mode):
		finfo.type = 'b'
		finfo.rdev = s.st_rdev
	elif S_ISFIFO(s.st_mode):
		finfo.type = 'f'
		finfo.linkto = os.readlink(finfo.fullname)
	elif S_ISDIR(s.st_mode):
		finfo.type = 'd'
	else:
		finfo.type = 'u'

	finfo.mtime = s.st_mtime
	finfo.atime = s.st_atime
	finfo.size = s.st_size
	finfo.mode = s.st_mode
	finfo.uid = s.st_uid
	finfo.gid = s.st_gid

	if finfo.type == 'r':
		finfo.hash = finfo.hash_file()

def finfo_cmp_mdata(finfo, other):
	"Compares metadata to other."
	if finfo.mtime != other.mtime: return 0
	if finfo.mode != other.mode: return 0
	if finfo.uid != other.uid: return 0
	if finfo.gid != other.gid: return 0
	return 1

def finfo_cmp_data(finfo, other):
	"Compares data to other."
	if finfo.size != other.size: return 0
	if finfo.hash != other.hash: return 0
	if finfo.type != other.type: return 0
	if finfo.type == 'b' or finfo.type == 'c':
		if finfo.rdev != other.rdev:
			return 0
	if finfo.type == 'l':
		if finfo.linkto != other.linkto:
			return 0
	return 1

def finfo_copy_file_reg_raw(finfo, dst):
	"Copy a regular file."
	sfile = open(finfo.fullname, 'r')
	dfile = open(dst, 'w')

	# the data
	data = sfile.read(PSIZE)
	while data:
		dfile.write(data)
		data = sfile.read(PSIZE)

	sfile.close()
	dfile.close()

def finfo_copy_file_reg_bzip2(finfo, dst):
	"Copy a regular file, destination is bz2 compressed."
	import bz2
	sfile = open(finfo.fullname)
	dfile = open(dst, 'w')

	bcomp = bz2.BZ2Compressor()
	data = sfile.read(PSIZE)
	while data:
		dfile.write(bcomp.compress(data))
		data = sfile.read(PSIZE)
	dfile.write(bcomp.flush())
	sfile.close()
	dfile.close()

def finfo_copy_file_reg_gzip(finfo, dst):
	"Copy a regular file, destination is gzip compressed."
	import gzip
	sfile = open(finfo.fullname)
	dfile = gzip.open(dst, 'w')

	data = sfile.read(PSIZE)
	while data:
		dfile.write(data)
		data = sfile.read(PSIZE)

	sfile.close()
	dfile.close()

# the copy function is modified by configuration
#finfo_copy_file_reg = finfo_copy_file_reg_gzip


def finfo_copy_file_link(finfo, dst):
	"Copy a symbolic link."
	linkto = os.readlink(finfo.fullname)
	os.symlink(linkto, dst)


def finfo_copy_file_dev(finfo, dst):
	"Copy a device file."
	major = os.major(finfo.rdev)
	minor = os.minor(finfo.rdev)
	dev = os.makedev(major, minor)
	os.mknod(dst, finfo.mode, dev)

def finfo_update_mdata(finfo, dst):
	"Updates a file's metadata."
	os.lchown(dst, finfo.uid, finfo.gid)
	if finfo.type != 'l':
		# these don't really like symlinks
		os.utime(dst, (finfo.atime, finfo.mtime))
		os.chmod(dst, finfo.mode & 07777)

def finfo_copy_file(finfo, dst):
	"Copies a file, along with its permissions and ownership."
	# create the path to dst if it doesn't exist
	make_path(dst)

	# copy accordingly to the file type
	if finfo.type == 'r':
		finfo_copy_file_reg(finfo, dst)
	elif finfo.type == 'l':
		finfo_copy_file_link(finfo, dst)
	elif finfo.type == 'b' or finfo.type == 'c':
		finfo_copy_file_dev(finfo, dst)
	elif finfo.type == 'f':
		# we just create fifos
		os.mkfifo(dst, finfo.mode & 07777)
	elif finfo.type == 'd':
		# we just create directories
		try:
			os.makedirs(dst, finfo.mode & 07777)
		except OSError:
			# ignore if the dir already exists, it could
			# happen because the walker doesn't do it in
			# any kind of order, so a subdirectory might
			# be created before the parent.
			pass
	else:
		raise 'Unk type: 0x%x %d' % (finfo.mode, finfo.name)

def finfo_hash_file_sha(finfo):
	"Returns the sha1sum of a file."
	import sha
	hash = sha.new()
	f = open(finfo.fullname)
	data = f.read(PSIZE)
	while data:
		hash.update(data)
		data = f.read(PSIZE)
	f.close()
	return hash.hexdigest()

def finfo_hash_file_md5(finfo):
	"Returns the md5sum of a file."
	import md5
	hash = md5.new()
	f = open(finfo.fullname)
	data = f.read(PSIZE)
	while data:
		hash.update(data)
		data = f.read(PSIZE)
	f.close()
	return hash.hexdigest()

def finfo_hash_file_none(finfo):
	"Empty hash."
	return '-'

# the hash function is modified by configuration
finfo_hash_file = finfo_hash_file_sha


class file_info:
	"Represents a file"
	def __init__(self, name, fullname):
		self.name = name
		self.fullname = fullname
		self.mode = 0
		self.uid = 0
		self.gid = 0
		self.mtime = 0
		self.atime = 0
		self.size = 0
		self.type = ''
		self.linkto = None
		self.rdev = None
		self.hash = None
		self.stat = None

	def __repr__(self):
		return "<%s: %s %d>" % (self.name, self.type, self.size)

	def __eq__(self, other):
		"Compares to other file_info object."
		if self.name != other.name: return 0
		if not finfo_cmp_data(self, other): return 0
		if not finfo_cmp_mdata(self, other): return 0

		return 1

	def __ne__(self, other):
		return not (self == other)


class index_file:
	"Represents the index file."
	def __init__(self, name):
		self.name = name
		self.db = {}
		self.names = []
		self.pathdb = {}

	def load(self):
		"Loads data from the file."
		try:
			f = open(self.name)
		except IOError:
			# probably file doesn't exist, ignore
			return
		(self.db, self.names) = cPickle.load(f)
		f.close()

	def save(self):
		"Saves the index to the disk."
		for f in self.db.keys():
			self.db[f].fullname = ''
		f = open(self.name, 'w')
		cPickle.dump((self.db, self.names), f, cPickle.HIGHEST_PROTOCOL)
		f.close()

	def put_file(self, filename, fullpath):
		"Incorporates a file into the index."
		self.db[filename] = file_info(filename, fullpath)
		finfo_load(self.db[filename])
		if self.db[filename].type == 'u':
			# ignore files of unknown types, like unix sockets
			del(self.db[filename])
			return
		self.names.append(filename)
		self.pathdb[filename] = fullpath

	def get_file(self, filename):
		"Get the file_info object for the given filename."
		return self.db[filename]

	def populate(self, root, exclude):
		"Populate the index from a root path."

		def skip_file(relname):
			"Check if the file matches the exclude list"
			for r in exclude:
				if r.search(relname):
					return 1
			return 0

		root = os.path.abspath(root)
		base, reduced = os.path.split(root)
		self.put_file(reduced, root)
		tree = os.walk(root, topdown = True)
		for path, childs, files in tree:
			for f in files:
				full = path + '/' + f
				name = relative_path(base, full)
				if skip_file(name):
					continue
				self.put_file(name, full)
			for c in childs:
				full = path + '/' + c
				name = relative_path(base, full)
				if skip_file(name):
					continue
				self.put_file(name, full)


def quiet_unlink(path):
	"Removes the given file if exists, or do nothing if not."
	try:
		os.unlink(path)
	except OSError:
		pass


def force_unlink(path, type):
	"Removes a file or directory, recurses if necesary."
	if type != 'd':
		try:
			os.unlink(path)
		except OSError:
			pass
	else:
		try:
			os.removedirs(path)
		except OSError:
			pass

def make_path(f):
	"If f is 'a/b/c/f', make sure 'a/b/c' exist."
	dir = os.path.dirname(f)
	try:
		os.makedirs(dir)
	except OSError:
		# it can fail if already exist
		pass

def relative_path(base, path):
	"""If base = '/x/x/b' and path = '/x/x/b/c/d', returns 'b/c/d'. Both
	must be absolute for simplicity."""
	res = path[len(base):]
	while res[0] == '/':
		res = res[1:]
	return res


#
# main operations
#

def make_sync(sources, srcidx_path, dst_path, dstidx_path, exclude):
	"Sync two directories."
	# destination and indexes are always a complete path
	srcidx_path = os.path.join(os.getcwd(), srcidx_path)
	dst_path = os.path.join(os.getcwd(), dst_path)
	dstidx_path = os.path.join(os.getcwd(), dstidx_path)

	# process regular expressions
	exclude_re = []
	for r in exclude:
		exclude_re.append(re.compile(r))

	# load destination index
	printv("* loading destination index")
	dstidx = index_file(dstidx_path)
	dstidx.load()

	# create source index
	printv("* building source index")
	srcidx = index_file(srcidx_path)
	for src_path in sources:
		printv("\t* " + src_path)
		srcidx.populate(src_path, exclude_re)

	printv("* sync")

	# compare them
	update_files = []
	for f in srcidx.names:
		if f not in dstidx.names or \
				not finfo_cmp_data(srcidx.db[f], dstidx.db[f]):
			# files missing in destination, or data changed
			#dst = os.path.join(dst_path, f)
			dst = dst_path + '/' + f
			printv('data\t', f, dst)
			quiet_unlink(dst)
			finfo_copy_file(srcidx.db[f], dst)
			update_files.append((f, dst))
		elif not finfo_cmp_mdata(srcidx.db[f], dstidx.db[f]):
			# metadata changed
			#dst = os.path.join(dst_path, f)
			dst = dst_path + '/' + f
			printv('mdata\t', f, dst)
			update_files.append((f, dst))

	# metadata gets changed later because otherwise we could leave
	# directory times wrong due to files being added to a directory after
	# their creation; this way we're sure there will be no more file
	# creation afterwards
	printv('* mdata')
	for f, dst in update_files:
		try:
			finfo_update_mdata(srcidx.db[f], dst)
		except:
			# it can fail if the destination doesn't have the
			# file, ignore for now; TODO: output some kind of
			# script so people can run it later when they get all
			# back together
			pass

	printv('* unlink')
	for f in dstidx.names:
		if f not in srcidx.names:
			# files in destination and not in source
			#dst = os.path.join(dst_path, f)
			dst = dst_path + '/' + f
			printv('unlink\t', f, dst)
			force_unlink(dst, dstidx.db[f].type)

	# we save the index at last because it voids file_info.fullpath so we
	# don't save unnecesary information
	printv('* saving index')
	srcidx.save()


def show_idx(idx_path):
	printv("* loading index")
	idx = index_file(idx_path)
	idx.load()
	for f in idx.names:
		fi = idx.db[f]
		printv( "%s %d %f %s %s" % (fi.type, fi.size, fi.mtime,
				str(fi.hash), fi.name) )

def build_idx(idx_path, path):
	printv("* building index")

	# see comments in make_sync()
	while path[-1] == '/' and path != '/':
		path = path[:-1]
	idx_path = os.path.join(os.getcwd(), idx_path)
	if path != '/':
		parent, src = os.path.split(path)
		if parent:
			os.chdir(parent)
			path = src

	# build the index
	idx = index_file(idx_path)
	idx.populate(path)
	idx.save()


#
# helper functions
#

def printv(*params):
	"Equivalent to 'if verbose: print params'."
	if not verbose:
		return
	for i in params:
		print i,
	print


def parse_options():
	"Commandline options parser."
	from optparse import OptionParser
	class AbkOptionParser(OptionParser):
		"Custom abk command line option parser."
		def format_help (self, formatter=None):
			"Displays the description before usage."
			if formatter is None:
				formatter = self.formatter
			result = []
			if self.description:
				result.append(self.get_prog_name() + ' - ' + \
					self.format_description(formatter)+"\n\n")
			if self.usage:
				result.append(self.get_usage() + "\n")
			result.append(self.format_option_help(formatter))
			return "".join(result)
	usage = """%prog [options] command params

commands:
  show idx_file
    shows the given index file contents
  mkidx idx_file dir
    builds an index file for the given directory
  sync idx src1 [src2 ... srcN] dst
    synchronizes all sources with dst, using the given idx index file"""
	parser = AbkOptionParser(usage=usage, description="A backup script - "
		"Alberto Bertogli (albertogli@telpin.com.ar)",
		version="%prog " + VERSION, prog='abk')
	parser.add_option("-v", "--verbose",
		action="store_true", dest="verbose", default=True,
		help="print progress information [default]")
	parser.add_option("-q", "--quiet",
		action="store_false", dest="verbose",
		help="don't print progress information (just errors)")
	parser.add_option("-c", "--copy-mode", default='gzip', metavar="MODE",
		action="store", dest="copy_mode",
		help="select copy mode to use. Available modes: "
		"raw, gzip, bzip2 [default: gzip]")
	parser.add_option("-a", "--hash-mode", default='sha', metavar="MODE",
		action="store", dest="hash_mode",
		help="select the hash to use to check for file content change. "
		"Available modes: none, sha, md5 [default: sha]")
	parser.add_option("-e", "--exclude", metavar="REGEX",
		action="append", dest="exclude",
		help="excludes files that matches with the regular expression. "
		"This option accepts multiple instances")
	parser.add_option("-i", "--new-idx", metavar="FILE",
		action="store", dest="new_idx",
		help="select where to write the new generated index. "
		"This is useful for incremental backups. "
		"If not specified, the old index file (idx) is overwritten")
	(opts, args) = parser.parse_args()
	return (parser, opts, args)


#
# main
#

# command line options
(parser, opts, args) = parse_options()
verbose = opts.verbose

# configuration
if opts.copy_mode == 'raw':
	finfo_copy_file_reg = finfo_copy_file_reg_raw
elif opts.copy_mode == 'gzip':
	finfo_copy_file_reg = finfo_copy_file_reg_gzip
elif opts.copy_mode == 'bzip2':
	finfo_copy_file_reg = finfo_copy_file_reg_bzip2
else:
	parser.error("Invalid copy mode (%s)." % opts.copy_mode)

if opts.hash_mode == 'none':
	file_info.hash_file = finfo_hash_file_none
elif opts.hash_mode == 'md5':
	file_info.hash_file = finfo_hash_file_md5
elif opts.hash_mode == 'sha':
	file_info.hash_file = finfo_hash_file_sha
else:
	parser.error("Invalid hash mode (%s)." % opts.hash_mode)

# main command
try:
	cmd = args[0]
except:
	parser.error("Command missing.")

if cmd == 'show':
	try:
		show_idx(args[1])
	except:
		parser.error("Missing idx_file parameter.")
elif cmd == 'mkidx':
	try:
		idx_path = args[1]
		path = args[2]
	except:
		parser.error("Missing parameter(s) for command mkidx.")
	build_idx(idx_path, path)
elif cmd == 'sync':
	try:
		old_idx_path = args[1]
		new_idx_path = old_idx_path
		sources = args[2:-1]
		dst_path = args[-1]
	except:
		parser.error("Missing parameter(s) for command sync.")
	if opts.new_idx:
		new_idx_path = opts.new_idx
	exclude = []
	if opts.exclude:
		exclude = opts.exclude
	make_sync(sources, new_idx_path, dst_path, old_idx_path, exclude)
else:
	parser.error("Unknown command (%s)." % cmd)