Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow configuring the date and time formatting used in snapshot names #39

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion pyznap/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,12 @@ def clean_filesystem(filesystem, conf):
logger = logging.getLogger(__name__)
logger.debug('Cleaning snapshots on {}...'.format(filesystem))

prefix = conf.get('prefix', 'pyznap')

snapshots = {'frequent': [], 'hourly': [], 'daily': [], 'weekly': [], 'monthly': [], 'yearly': []}
for snap in filesystem.snapshots():
# Ignore snapshots not taken with pyznap or sanoid
if not snap.name.split('@')[1].startswith(('pyznap', 'autosnap')):
if not snap.name.split('@')[1].startswith(('pyznap', 'autosnap', prefix)):
continue
snap_type = snap.name.split('_')[-1]

Expand Down
26 changes: 16 additions & 10 deletions pyznap/take.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from .process import DatasetBusyError, DatasetNotFoundError, DatasetExistsError


def take_snap(filesystem, _type):
def take_snap(filesystem, prefix, datetime_format, _type):
"""Takes a snapshot of type '_type'

Parameters
Expand All @@ -31,7 +31,7 @@ def take_snap(filesystem, _type):
logger = logging.getLogger(__name__)
now = datetime.now

snapname = lambda _type: 'pyznap_{:s}_{:s}'.format(now().strftime('%Y-%m-%d_%H:%M:%S'), _type)
snapname = lambda _type: '{:s}_{:s}_{:s}'.format(prefix, now().strftime(datetime_format), _type)

logger.info('Taking snapshot {}@{:s}...'.format(filesystem, snapname(_type)))
try:
Expand Down Expand Up @@ -62,14 +62,20 @@ def take_filesystem(filesystem, conf):
logger.debug('Taking snapshots on {}...'.format(filesystem))
now = datetime.now

prefix = conf.get('prefix', 'pyznap')

date_format = conf.get('date_format', '%Y-%m-%d')
time_format = conf.get('time_format', '%H:%M:%S')
datetime_format = '{:s}_{:s}'.format(date_format, time_format)

snapshots = {'frequent': [], 'hourly': [], 'daily': [], 'weekly': [], 'monthly': [], 'yearly': []}
for snap in filesystem.snapshots():
# Ignore snapshots not taken with pyznap or sanoid
if not snap.name.split('@')[1].startswith(('pyznap', 'autosnap')):
if not snap.name.split('@')[1].startswith(('pyznap', 'autosnap', prefix)):
continue
try:
_date, _time, snap_type = snap.name.split('_')[-3:]
snap_time = datetime.strptime('{:s}_{:s}'.format(_date, _time), '%Y-%m-%d_%H:%M:%S')
snap_time = datetime.strptime('{:s}_{:s}'.format(_date, _time), datetime_format)
snapshots[snap_type].append((snap, snap_time))
except (ValueError, KeyError):
continue
Expand All @@ -80,32 +86,32 @@ def take_filesystem(filesystem, conf):

if conf['yearly'] and (not snapshots['yearly'] or
snapshots['yearly'][0][1].year != now().year):
take_snap(filesystem, 'yearly')
take_snap(filesystem, prefix, datetime_format, 'yearly')

if conf['monthly'] and (not snapshots['monthly'] or
snapshots['monthly'][0][1].month != now().month or
now() - snapshots['monthly'][0][1] > timedelta(days=31)):
take_snap(filesystem, 'monthly')
take_snap(filesystem, prefix, datetime_format, 'monthly')

if conf['weekly'] and (not snapshots['weekly'] or
snapshots['weekly'][0][1].isocalendar()[1] != now().isocalendar()[1] or
now() - snapshots['weekly'][0][1] > timedelta(days=7)):
take_snap(filesystem, 'weekly')
take_snap(filesystem, prefix, datetime_format, 'weekly')

if conf['daily'] and (not snapshots['daily'] or
snapshots['daily'][0][1].day != now().day or
now() - snapshots['daily'][0][1] > timedelta(days=1)):
take_snap(filesystem, 'daily')
take_snap(filesystem, prefix, datetime_format, 'daily')

if conf['hourly'] and (not snapshots['hourly'] or
snapshots['hourly'][0][1].hour != now().hour or
now() - snapshots['hourly'][0][1] > timedelta(hours=1)):
take_snap(filesystem, 'hourly')
take_snap(filesystem, prefix, datetime_format, 'hourly')

if conf['frequent'] and (not snapshots['frequent'] or
snapshots['frequent'][0][1].minute != now().minute or
now() - snapshots['frequent'][0][1] > timedelta(minutes=1)):
take_snap(filesystem, 'frequent')
take_snap(filesystem, prefix, datetime_format, 'frequent')


def take_config(config):
Expand Down
8 changes: 6 additions & 2 deletions pyznap/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def read_config(path):

config = []
options = ['key', 'frequent', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'snap', 'clean',
'dest', 'dest_keys', 'compress']
'dest', 'dest_keys', 'compress', 'prefix', 'date_format', 'time_format']

for section in parser.sections():
dic = {}
Expand All @@ -115,6 +115,10 @@ def read_config(path):
elif option in ['dest_keys']:
dic[option] = [i.strip() if os.path.isfile(i.strip()) else None
for i in value.split(',')]
elif option in ['prefix']:
dic[option] = value.strip().replace('_', '')
elif option in ['date_format', 'time_format']:
dic[option] = value.strip()
# Pass through values recursively
for parent in config:
for child in config:
Expand All @@ -123,7 +127,7 @@ def read_config(path):
child_parent = '/'.join(child['name'].split('/')[:-1]) # get parent of child filesystem
if child_parent.startswith(parent['name']):
for option in ['key', 'frequent', 'hourly', 'daily', 'weekly', 'monthly', 'yearly',
'snap', 'clean']:
'snap', 'clean', 'prefix', 'date_format', 'time_format']:
child[option] = child[option] if child[option] is not None else parent[option]
# Sort by pathname
config = sorted(config, key=lambda entry: entry['name'].split('/'))
Expand Down