summaryrefslogtreecommitdiffstats
path: root/pyfirstaidkit/utils/backup.py
blob: 7c4537f17d64d961cc890c022dc954f026cba6ba (plain)
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
# File name: backup.py
# Date:      2008/03/14
# Author:    Martin Sivak <msivak at redhet dot com>
#
# Copyright (C) Red Hat 2008
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# in a file called COPYING along with this program; if not, write to
# the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
# 02139, USA.
from errors import NotImplemented
import os
import shutil
import hashlib
import weakref
import cPickle as pickle
import copy
import tempfile
import datetime

class BackupException(Exception):
    pass

class BackupStoreInterface(object):
    class Backup:
        def __init__(self, id):
            raise NotImplemented()

        def backupPath(self, path, name = None):
            raise NotImplemented()
        def backupValue(self, value, name):
            raise NotImplemented()

        def restoreName(self, name, path = None):
            raise NotImplemented()
        def restorePath(self, path, name = None):
            raise NotImplemented()
        def restoreValue(self, name):
            raise NotImplemented()

        def delete(self, name):
            raise NotImplemented()
        def cleanup(self):
            raise NotImplemented()

        def exists(self, name = None, path = None):
            raise NotImplemented()

    def __init__(self):
        raise NotImplemented()

    def getBackup(self, id, persistent = False):
        raise NotImplemented()

    def closeBackup(self, id):
        raise NotImplemented()

    def __del__(self):
        raise NotImplemented()

class FileBackupStore(BackupStoreInterface):
    _singleton = None

    class Backup(BackupStoreInterface.Backup):
        def __init__(self, id, path, reverting = False):
            self._id = id
            self._path = path
            self._metafile = "__meta.pickle"
            self._data = {} # name -> (stored as, origin)
            self._origin = {} # origin -> name
            # Because the dir is suppose to be there when we are reverting.
            if not reverting:
                os.makedirs(self._path)

        def saveMeta(self):
            f = open(os.path.join(self._path, self._metafile), "wb")
            pickle.dump((self._id, self._data, self._origin), f, \
                    pickle.HIGHEST_PROTOCOL)
            f.close()
            return True

        def loadMeta(self):
            f = open(os.path.join(self._path, self._metafile), "rb")
            (id, data, origin) = pickle.load(f)
            f.close()

            if id==self._id:
                self._data = data
                self._origin = origin
            else:
                raise BackupException("Loading metadata for different Backup " \
                        "(ID mismatch: '%s' and '%s')" % (self._id, id))

            return True

        def backupPath(self, path, name = None):
            if name is None:
                name = path

            if self._origin.has_key(path):
                raise BackupException("Path %s already in the backup store %s!"
                        % (path,self._id))
            if self._data.has_key(name):
                raise BackupException("Named backup %s already in the backup "
                        "store %s!" % (name,self._id))

            stored = hashlib.sha224(name).hexdigest()

            if os.path.isdir(path):
                shutil.copytree(path, os.path.join(self._path, stored),
                        symlinks = True)
            else:
                shutil.copy2(path, os.path.join(self._path, stored))

            self._origin[path] = name
            self._data[name] = (stored, path)

            self.saveMeta()

            return True

        def backupValue(self, value, name):
            if self._data.has_key(name):
                raise BackupException("Named backup %s already in the backup "
                        "store %s!" % (name,self._id))
            stored = hashlib.sha224(name).hexdigest()

            f = open(os.path.join(self._path, stored), "wb")
            pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
            f.close()

            self._data[name] = (stored, None)

            self.saveMeta()

            return True

        def restoreValue(self, name):
            stored, origin = self._data[name]
            if origin is not None:
                raise BackupException("Named backup %s is not a value object!"
                        % (name,))


            f = open(os.path.join(self._path, stored), "rb")
            val = pickle.load(f)
            f.close()

            return val

        def restoreName(self, name, path = None):
            stored, origin = self._data[name]
            if origin is None:
                raise BackupException("Named backup %s is not a filesystem "
                        "object!" % (name,))

            assert self._origin[name]==origin

            if path is None:
                path = origin

            if os.path.exists(path):
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.unlink(path)

            stored = os.path.join(self._path, stored)

            if os.path.isdir(stored):
                shutil.copytree(stored, path, symlinks = True)
            else:
                shutil.copy2(stored, path)
            return True

        def restorePath(self, path, name = None):
            assert self._data[self._origin[path]][1]==path

            if name is None:
                name = self._origin[path]

            return self.restoreName(name, path)

        def delete(self, name):
            stored, origin = self._data[name]
            stored = os.path.join(self._path, stored)

            if os.path.isdir(stored):
                shutil.rmtree(stored)
            else:
                os.unlink(stored)

            del self._data[name]
            if origin is not None:
                del self._origin[origin]

            self.saveMeta()

            return True

        def cleanup(self):
            _datakeys = self._data.keys()
            for name in _datakeys:
                self.delete(name)
            try:
                os.remove(os.path.join(self._path, self._metafile))
            except OSError:
                pass
            os.rmdir(self._path)
            return True

        def exists(self, name=None, path=None):
            if name == None and path == None:
                raise BackupException("Cannot call the exists method with both "
                        "the arguments equal to None")

            if name != None and path != None:
                try:
                    if self._data[name] == path:
                        return True
                    else:
                        return False
                except KeyError:
                    return False

            if name != None and self._data.has_key(name):
                return True

            if path != None and self._origin.has_key(path):
                return True

            return False

    class BackupPersistent(Backup):
        def cleanup(self):
            self.saveMeta()
            return False

    def __init__(self, rootpath = "/tmp", fullpath = ""):
        if self.__class__._singleton:
            raise BackupException("BackupStore with %s type can have only "
                    "one instance" % (self.__name__,))

        assert self.__class__._singleton==None

        if fullpath:
            if os.path.isdir(fullpath):
                raise BackupException("Backupdir %s already exists. Erase "
                        "dir or change backup dir." % self._path)
            else:
                self._path = fullpath
                os.makedirs(fullpath)

        else:
            if not os.path.isdir(rootpath):
                os.makedirs(rootpath)
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%m%S")
            self._path = tempfile.mkdtemp(prefix = "fakbackup-%s-"%timestamp,
                    dir = rootpath)

        self._backups = {}

        self.__class__._singleton = weakref.proxy(self)
        print("Backup system initialized")

    def getBackup(self, id, persistent = False):
        if not self._backups.has_key(id):
            if persistent:
                self._backups[id] = self.BackupPersistent(id, self._path+"/"+id+"/")
            else:
                self._backups[id] = self.Backup(id, self._path+"/"+id+"/")
        return self._backups[id]

    def closeBackup(self, id):
        if not self._backups.has_key(id):
            raise BackupException("Backup with id %s does not exist" % (id,))
        if self._backups[id].cleanup():
            del self._backups[id]

    def __del__(self):
        if self.__class__._singleton is None:
            return

        backupEmpty = True

        for id,backup in self._backups.iteritems():
            backupEmpty = backupEmpty and backup.cleanup()

        if backupEmpty:
            os.rmdir(self._path)
        else:
            print("I'm keeping persistent backup spaces intact in %s" % (self._path,))


        print("Backup closed")

    @classmethod
    def get(cls, path):
        if cls._singleton:
            return cls._singleton
        else:
            return cls(path)