Update copyright notices to use a central AUTHORS file.
[cumulus.git] / python / cumulus / retention.py
1 # Cumulus: Efficient Filesystem Backup to the Cloud
2 # Copyright (C) 2012 The Cumulus Developers
3 # See the AUTHORS file for a list of contributors.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19 """Backup retention policies.
20
21 Retention policies control how long different backup snapshots should be kept,
22 for example keeping daily snapshots for short periods of time but retaining
23 weekly snapshots going back further in time.
24 """
25
26 import calendar
27 import datetime
28
29 TIMESTAMP_FORMAT = "%Y%m%dT%H%M%S"
30
31 # Different classes of backups--such as "daily" or "monthly"--can have
32 # different retention periods applied.  A single backup snapshot might belong
33 # to multiple classes (i.e., perhaps be both a "daily" and a "monthly", though
34 # not a "weekly").
35 #
36 # Backups are classified using partitioning functions, defined below.  For a
37 # "monthly" backup classifier, all backups for a given month should map to the
38 # same partition.  Then, we apply the class label to the earliest snapshot in
39 # each partition--so the set of "monthly" backups would consist of all backups
40 # which were the first to run after the start of a month.
41 #
42 # A partitioning function must take a datetime instance as input and return a
43 # partition representative as output; timestamps that should be part of the
44 # same partition should map to equal partition representatives.  For a
45 # "monthly" classifier, an easy way to do this is to truncate the timestamp to
46 # keep only the month and year, and in general truncating timestamps works
47 # well, but the values are not used in any other way than equality testing so
48 # any type is allowed.
49 #
50 # _backup_classes is a registry of useful backup types; it maps a descriptive
51 # name to a partition function which implements it.
52 _backup_classes = {}
53
54 def add_backup_class(name, partioning_function):
55     """Registers a new class of backups for which policies can be applied.
56
57     The new class will be available as name to RetentionEngine.add_policy.
58     partioning_function should be a function for grouping together backups in
59     the same time period.
60
61     Predefined backups classes are: "yearly", "monthly", "weekly", "daily", and
62     "all".
63     """
64     _backup_classes[name] = partioning_function
65
66 add_backup_class("yearly", lambda t: t.date().replace(day=1, month=1))
67 add_backup_class("monthly", lambda t: t.date().replace(day=1))
68 add_backup_class("weekly", lambda t: t.isocalendar()[0:2])
69 add_backup_class("daily", lambda t: t.date())
70 add_backup_class("all", lambda t: t)
71
72
73 class RetentionEngine(object):
74     """Class for applying a retention policy to a set of snapshots.
75
76     Allows a retention policy to be set, then matches a sequence of backup
77     snapshots to the policy to decide which ones should be kept.
78     """
79
80     def __init__(self):
81         self.set_utc(False)
82         self._policies = {}
83         self._last_snapshots = {}
84         self._now = datetime.datetime.utcnow()
85
86     def set_utc(self, use_utc=True):
87         """Perform policy matching with timestamps in UTC.
88
89         By default, the policy converts timestamps to local time, but calling
90         set_utc(True) will select snapshots based on UTC timestamps.
91         """
92         self._convert_to_localtime = not use_utc
93
94     def set_now(self, timestamp):
95         """Sets the "current time" for the purposes of snapshot expiration.
96
97         timestamp should be a datetime object, expressed in UTC.  If set_now()
98         is not called, the current time defaults to the time at which the
99         RetentionEngine object was instantiated.
100         """
101         self._now = timestamp
102
103     def add_policy(self, backup_class, retention_period):
104         self._policies[backup_class] = retention_period
105         self._last_snapshots[backup_class] = (None, None)
106
107     @staticmethod
108     def parse_timestamp(s):
109         return datetime.datetime.strptime(s, TIMESTAMP_FORMAT)
110
111     def consider_snapshot(self, snapshot):
112         """Compute whether a given snapshot should be expired.
113
114         Successive calls to consider_snapshot() must be for snapshots in
115         chronological order.  For each call, consider_snapshot() will return a
116         boolean indicating whether the snapshot should be retained (True) or
117         expired (False).
118         """
119         timestamp_utc = self.parse_timestamp(snapshot)
120         snapshot_age = self._now - timestamp_utc
121
122         # timestamp_policy is the timestamp in the format that will be used for
123         # doing policy matching: either in the local timezone or UTC, depending
124         # on the setting of set_utc().
125         if self._convert_to_localtime:
126             unixtime = calendar.timegm(timestamp_utc.timetuple())
127             timestamp_policy = datetime.datetime.fromtimestamp(unixtime)
128         else:
129             timestamp_policy = timestamp_utc
130
131         self._labels = set()
132         retain = False
133         for (backup_class, retention_period) in self._policies.iteritems():
134             partition = _backup_classes[backup_class](timestamp_policy)
135             last_snapshot = self._last_snapshots[backup_class]
136             if self._last_snapshots[backup_class][0] != partition:
137                 self._last_snapshots[backup_class] = (partition, snapshot)
138                 self._labels.add(backup_class)
139                 if snapshot_age < retention_period: retain = True
140         return retain
141
142     def last_labels(self):
143         """Return the set of policies that applied to the last snapshot.
144
145         This will fail if consider_snapshot has not yet been called.
146         """
147         return self._labels
148
149     def last_snapshots(self):
150         """Returns the most recent snapshot in each backup class."""
151         return dict((k, v[1]) for (k, v) in self._last_snapshots.iteritems())