1
0
Fork 0
mirror of https://github.com/borgbackup/borg.git synced 2024-12-26 17:57:59 +00:00
borg/darc/cache.py

210 lines
7.7 KiB
Python
Raw Normal View History

2011-06-23 20:47:51 +00:00
from __future__ import with_statement
2010-12-21 20:29:09 +00:00
from ConfigParser import RawConfigParser
import fcntl
import msgpack
2010-10-20 19:08:46 +00:00
import os
2010-12-21 20:29:09 +00:00
import shutil
2011-08-06 11:01:58 +00:00
from .helpers import error_callback, get_cache_dir
from .hashindex import ChunkIndex
2010-03-06 17:25:35 +00:00
class Cache(object):
"""Client Side cache
"""
def __init__(self, store, key, manifest):
2010-12-21 20:29:09 +00:00
self.txn_active = False
2010-03-06 17:25:35 +00:00
self.store = store
self.key = key
self.manifest = manifest
self.path = os.path.join(get_cache_dir(), store.id.encode('hex'))
2010-12-21 20:29:09 +00:00
if not os.path.exists(self.path):
self.create()
2010-03-06 17:25:35 +00:00
self.open()
if self.manifest.id != self.manifest_id:
2010-12-21 20:29:09 +00:00
self.sync()
self.commit()
2010-03-06 17:25:35 +00:00
2010-12-21 20:29:09 +00:00
def create(self):
"""Create a new empty store at `path`
"""
2011-01-04 22:00:39 +00:00
os.makedirs(self.path)
2010-12-21 20:29:09 +00:00
with open(os.path.join(self.path, 'README'), 'wb') as fd:
fd.write('This is a DARC cache')
config = RawConfigParser()
config.add_section('cache')
config.set('cache', 'version', '1')
config.set('cache', 'store', self.store.id.encode('hex'))
config.set('cache', 'manifest', '')
2010-12-21 20:29:09 +00:00
with open(os.path.join(self.path, 'config'), 'wb') as fd:
config.write(fd)
ChunkIndex.create(os.path.join(self.path, 'chunks'))
2010-12-21 20:29:09 +00:00
with open(os.path.join(self.path, 'files'), 'wb') as fd:
pass # empty file
2010-03-06 17:25:35 +00:00
def open(self):
2010-12-21 20:29:09 +00:00
if not os.path.isdir(self.path):
raise Exception('%s Does not look like a darc cache' % self.path)
self.lock_fd = open(os.path.join(self.path, 'README'), 'r+')
fcntl.flock(self.lock_fd, fcntl.LOCK_EX)
self.rollback()
self.config = RawConfigParser()
self.config.read(os.path.join(self.path, 'config'))
if self.config.getint('cache', 'version') != 1:
raise Exception('%s Does not look like a darc cache')
self.id = self.config.get('cache', 'store')
self.manifest_id = self.config.get('cache', 'manifest').decode('hex')
self.chunks = ChunkIndex(os.path.join(self.path, 'chunks'))
self.files = None
2011-07-02 18:39:35 +00:00
def _read_files(self):
2011-07-06 20:23:41 +00:00
self.files = {}
2010-12-21 20:29:09 +00:00
with open(os.path.join(self.path, 'files'), 'rb') as fd:
u = msgpack.Unpacker()
while True:
data = fd.read(64 * 1024)
if not data:
break
u.feed(data)
for hash, item in u:
if item[0] < 10:
2010-12-21 20:29:09 +00:00
self.files[hash] = (item[0] + 1,) + item[1:]
def begin_txn(self):
# Initialize transaction snapshot
txn_dir = os.path.join(self.path, 'txn.tmp')
os.mkdir(txn_dir)
shutil.copy(os.path.join(self.path, 'config'), txn_dir)
shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
shutil.copy(os.path.join(self.path, 'files'), txn_dir)
os.rename(os.path.join(self.path, 'txn.tmp'),
os.path.join(self.path, 'txn.active'))
self.txn_active = True
def commit(self):
"""Commit transaction
"""
2011-01-04 22:16:55 +00:00
if not self.txn_active:
return
if self.files is not None:
with open(os.path.join(self.path, 'files'), 'wb') as fd:
for item in self.files.iteritems():
msgpack.pack(item, fd)
self.config.set('cache', 'manifest', self.manifest.id.encode('hex'))
2010-12-21 20:29:09 +00:00
with open(os.path.join(self.path, 'config'), 'w') as fd:
self.config.write(fd)
self.chunks.flush()
os.rename(os.path.join(self.path, 'txn.active'),
os.path.join(self.path, 'txn.tmp'))
shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
self.txn_active = False
def rollback(self):
"""Roll back partial and aborted transactions
"""
# Roll back active transaction
txn_dir = os.path.join(self.path, 'txn.active')
if os.path.exists(txn_dir):
shutil.copy(os.path.join(txn_dir, 'config'), self.path)
shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
shutil.copy(os.path.join(txn_dir, 'files'), self.path)
os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
# Remove partial transaction
if os.path.exists(os.path.join(self.path, 'txn.tmp')):
shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
2010-12-21 20:29:09 +00:00
self.txn_active = False
def sync(self):
2010-03-06 17:25:35 +00:00
"""Initializes cache by fetching and reading all archive indicies
"""
2011-08-03 15:31:22 +00:00
def cb(chunk, error, id):
assert not error
data = self.key.decrypt(id, chunk)
try:
count, size, csize = self.chunks[id]
self.chunks[id] = count + 1, size, csize
except KeyError:
self.chunks[id] = 1, len(data), len(chunk)
2011-08-03 15:31:22 +00:00
unpacker.feed(data)
for item in unpacker:
try:
for id, size, csize in item['chunks']:
try:
count, size, csize = self.chunks[id]
self.chunks[id] = count + 1, size, csize
except KeyError:
self.chunks[id] = 1, size, csize
pass
except KeyError:
pass
2010-12-21 20:29:09 +00:00
self.begin_txn()
2010-10-30 11:44:25 +00:00
print 'Initializing cache...'
self.chunks.clear()
unpacker = msgpack.Unpacker()
for name, info in self.manifest.archives.items():
id = info['id']
cdata = self.store.get(id)
data = self.key.decrypt(id, cdata)
try:
count, size, csize = self.chunks[id]
self.chunks[id] = count + 1, size, csize
except KeyError:
self.chunks[id] = 1, len(data), len(cdata)
archive = msgpack.unpackb(data)
print 'Analyzing archive:', archive['name']
for id in archive['items']:
self.store.get(id, callback=cb, callback_data=id)
2011-08-03 15:31:22 +00:00
self.store.flush_rpc()
2010-03-06 17:25:35 +00:00
def add_chunk(self, id, data, stats):
2010-12-21 20:29:09 +00:00
if not self.txn_active:
self.begin_txn()
if self.seen_chunk(id):
return self.chunk_incref(id, stats)
size = len(data)
data = self.key.encrypt(data)
csize = len(data)
self.store.put(id, data, callback=error_callback)
self.chunks[id] = (1, size, csize)
stats.update(size, csize, True)
return id, size, csize
2010-03-06 17:25:35 +00:00
def seen_chunk(self, id):
return self.chunks.get(id, (0, 0, 0))[0]
2010-03-06 17:25:35 +00:00
def chunk_incref(self, id, stats):
2010-12-21 20:29:09 +00:00
if not self.txn_active:
self.begin_txn()
count, size, csize = self.chunks[id]
self.chunks[id] = (count + 1, size, csize)
stats.update(size, csize, False)
return id, size, csize
2010-03-06 17:25:35 +00:00
def chunk_decref(self, id):
2010-12-21 20:29:09 +00:00
if not self.txn_active:
self.begin_txn()
count, size, csize = self.chunks[id]
if count == 1:
2010-12-21 20:29:09 +00:00
del self.chunks[id]
self.store.delete(id, callback=error_callback)
else:
self.chunks[id] = (count - 1, size, csize)
def file_known_and_unchanged(self, path_hash, st):
if self.files is None:
2011-07-02 18:39:35 +00:00
self._read_files()
2010-12-21 20:29:09 +00:00
entry = self.files.get(path_hash)
2010-10-26 18:50:30 +00:00
if (entry and entry[3] == st.st_mtime
and entry[2] == st.st_size and entry[1] == st.st_ino):
# reset entry age
2010-12-21 20:29:09 +00:00
self.files[path_hash] = (0,) + entry[1:]
return entry[4]
else:
return None
2010-12-21 20:29:09 +00:00
def memorize_file(self, path_hash, st, ids):
# Entry: Age, inode, size, mtime, chunk ids
2010-12-21 20:29:09 +00:00
self.files[path_hash] = 0, st.st_ino, st.st_size, st.st_mtime, ids