Add some tools from osdk repo

These tools are not meant to be used as-is They need a full rework.
They are more reference material than anything else right now. I
also had to do some awful stuff to them to get them to pass the gate
in a hurry, code looks bad because of it.

I am cleaning them up as I go.

We will remove these in the future once they are no longer useful to
reference any longer.

Change-Id: I8f13ef282a2a05e72c53a0c307832a46db18d2b4
This commit is contained in:
SamYaple 2016-01-04 21:06:49 +00:00
parent fdfb83197c
commit e6d67dca74
3 changed files with 346 additions and 0 deletions

94
tools/backup.py Normal file
View File

@ -0,0 +1,94 @@
#!/usr/bin/python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copied and licensed from https://github.com/SamYaple/osdk
from hashlib import sha1
from osdk import osdk
from uuid import uuid4 as uuid
def get_disk_size(device):
with open(device, 'rb') as f:
return f.seek(0, 2)
def read_segments(f, lst, size, o):
zero_hash = sha1(bytes([0] * size)).hexdigest()
for segment in lst:
f.seek(segment * size, 0)
data = f.read(size)
if not data:
raise Exception('Failed to read data')
sha1_hash = sha1(data)
if sha1_hash.hexdigest() != zero_hash:
meta = dict()
meta['incremental'] = o.metadata['incremental']
meta['base'] = len(o.metadata['bases']) - 1
meta['encryption'] = 0
meta['compression'] = 0
meta['sha1_hash'] = sha1_hash.digest()
o.segments[segment] = meta
else:
try:
del o.segments[segment]
except KeyError:
pass
def main():
device = '/dev/loop0'
old_manifest = 'manifest0.osdk'
manifest = 'manifest0.osdk'
manifest = 'manifest1.osdk'
segment_size = 4 * 1024**2 # 4MiB
size_of_disk = get_disk_size(device)
num_of_sectors = int(size_of_disk / 512)
num_of_segments = int(size_of_disk / segment_size)
o = osdk(manifest)
o.metadata['sectors'] = num_of_sectors
new = True
new = False
existing = True
existing_full = True
existing_full = False
if new:
o.metadata['incremental'] = 0
o.metadata['segment_size'] = segment_size
o.metadata['bases'] = [uuid().bytes]
segments_to_read = range(0, num_of_segments - 1)
elif existing:
o.read_manifest(old_manifest)
o.metadata['incremental'] += 1
segments_to_read = range(1, num_of_segments - 1)
elif existing_full:
o.read_manifest(old_manifest)
o.metadata['incremental'] += 1
segments_to_read = range(0, num_of_segments - 1)
with open(device, 'rb+') as f:
read_segments(f, segments_to_read, segment_size, o)
o.write_manifest()
if __name__ == '__main__':
main()

184
tools/osdk.py Normal file
View File

@ -0,0 +1,184 @@
#!/usr/bin/python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copied and licensed from https://github.com/SamYaple/osdk
from binascii import b2a_hex
from binascii import crc32
from datetime import datetime
from struct import pack
from struct import unpack
from uuid import UUID
class osdk(object):
def __init__(self, manifest):
self.manifest = manifest
self.segments = dict()
self.metadata = dict()
self.metadata['signature'] = \
UUID('d326503ab5ca49adac56c89eb0b8ef08').bytes
self.metadata['version'] = 0
def write_manifest(self):
with open(self.manifest, 'wb') as f:
self.write_header(f)
self.write_body(f)
def build_header(self):
timestamp = utctimestamp()
padding = str.encode('\0\0' * 14)
data = pack(
'<i2IQH14s',
timestamp,
self.metadata['incremental'],
self.metadata['segment_size'],
self.metadata['sectors'],
len(self.metadata['bases']),
padding
)
checksum = crc32(data)
for i in self.metadata['bases']:
data += i
checksum = crc32(i, checksum)
return data, checksum
def write_body(self, f):
checksum = 0
for segment, meta in self.segments.items():
data = pack(
'<2IH2B20s',
segment,
meta['incremental'],
meta['base'],
meta['encryption'],
meta['compression'],
meta['sha1_hash']
)
f.write(data)
checksum = crc32(data, checksum)
""" Backfill the body_checksum """
f.seek(24, 0)
f.write(pack('<I', checksum))
def write_header(self, f):
data, checksum = self.build_header()
f.write(self.metadata['signature'])
f.write(pack('<3I', self.metadata['version'], checksum, 0))
f.write(data)
f.write(self.metadata['signature'])
def read_signature(self, f):
if not self.metadata['signature'] == f.read(16):
raise Exception('File signiture is not valid')
def read_header(self, f):
self.read_signature(f)
data = f.read(12)
if len(data) != 12:
raise Exception('Failed to read amount of requested data')
version, header_checksum, body_checksum = unpack('<3I', data)
if self.metadata['version'] < version:
raise Exception(
'The manifest version is newer than I know how to read'
)
data = f.read(36)
if len(data) != 36:
raise Exception('Failed to read amount of requested data')
checksum = crc32(data)
num_of_bases = ""
padding = ""
self.metadata['timestamp'],
self.metadata['incremental'],
self.metadata['segment_size'],
self.metadata['sectors'],
num_of_bases,
padding = unpack('<i2IQH14s', data)
if padding:
continue
self.metadata['bases'] = []
for i in range(0, num_of_bases):
data = f.read(16)
if len(data) != 16:
raise Exception('Failed to read amount of requested data')
self.metadata['bases'].append(data)
checksum = crc32(data, checksum)
if checksum != header_checksum:
raise Exception('Header checksum does not match')
self.read_signature(f)
return body_checksum
def read_body(self, f, body_checksum):
checksum = 0
data = f.read(32)
while len(data) == 32:
meta = dict()
segment = ""
segment,
meta['incremental'],
meta['base'],
meta['encryption'],
meta['compression'],
sha1 = unpack('<2IH2B20s', data)
meta['sha1_hash'] = b2a_hex(sha1)
self.segments[segment] = meta
checksum = crc32(data, checksum)
data = f.read(32)
if checksum != body_checksum:
raise Exception('Body checksum does not match')
def read_manifest(self, manifest=None):
if manifest:
with open(manifest, 'rb') as f:
body_checksum = self.read_header(f)
self.read_body(f, body_checksum)
else:
with open(self.manifest, 'rb') as f:
body_checksum = self.read_header(f)
self.read_body(f, body_checksum)
def utctimestamp():
ts = datetime.utcnow() - datetime(1970, 1, 1)
return ts.seconds + ts.days * 24 * 3600

68
tools/print.py Normal file
View File

@ -0,0 +1,68 @@
#!/usr/bin/python
# Copyright 2016 Sam Yaple
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copied and licensed from https://github.com/SamYaple/osdk
from datetime import datetime
from osdk import osdk
from uuid import UUID
def get_timestamp(o):
return datetime.fromtimestamp(
o.metadata['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
def convert_size(size_in_bytes):
sizes = {4: " TiB", 3: " GiB", 2: " MiB", 1: "KiB", 0: "B"}
for i in range(len(sizes), 1, -1):
size = int(size_in_bytes / 1024**i)
if size > 0:
break
return str(size) + sizes[i]
def print_header(o):
formated_out = """Version:\t%(version)s
Creation Date:\t%(timestamp)s
Incremental:\t%(incremental)s
Volume Size:\t%(volume_size)s
Segment Size:\t%(segment_size)s
Backup Set:\t%(backup_set)s"""
dict_out = dict()
dict_out['backup_set'] = UUID(bytes=o.metadata['bases'][-1])
dict_out['version'] = o.metadata['version']
dict_out['incremental'] = o.metadata['incremental']
dict_out['timestamp'] = get_timestamp(o)
dict_out['volume_size'] = convert_size(o.metadata['sectors'] * 512)
dict_out['segment_size'] = convert_size(o.metadata['segment_size'])
print(formated_out % dict_out)
def main():
manifest = 'manifest1.osdk'
o = osdk(manifest)
o.read_manifest()
print_header(o)
if __name__ == '__main__':
main()