mirror of https://github.com/micromata/borgbackup-butler.git

Kai Reinhard
07.50.2019 219ec32448572da39d629dfcd9c37ec362378ffd
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package de.micromata.borgbutler.cache;
 
import de.micromata.borgbutler.cache.memory.MemoryCache;
import de.micromata.borgbutler.cache.memory.MemoryCacheObject;
import de.micromata.borgbutler.config.BorgRepoConfig;
import de.micromata.borgbutler.data.Archive;
import de.micromata.borgbutler.data.FileSystemFilter;
import de.micromata.borgbutler.data.Repository;
import de.micromata.borgbutler.json.borg.BorgFilesystemItem;
import de.micromata.borgbutler.utils.ReplaceUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.*;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.*;
 
/**
 * Cache for storing complete file lists of archives as gzipped files (using Java standard serialization for
 * fastest access).
 * <br>
 * A file list (archive content) with over million file system items is over 100MB large (uncompressed).
 * The compression is also useful for faster reading from the filesystem.
 */
class ArchiveFilelistCache {
    private static Logger log = LoggerFactory.getLogger(ArchiveFilelistCache.class);
    private static final String CACHE_ARCHIVE_LISTS_BASENAME = "archive-content-";
    private static final String CACHE_FILE_GZIP_EXTENSION = ".gz";
    private static final int MAX_SIZE_MEMORY_CACHE = 30 * 1024 * 1024; // 50 MB
    private File cacheDir;
    private int cacheArchiveContentMaxDiscSizeMB;
    private long FILES_EXPIRE_TIME = 7 * 24 * 3660 * 1000; // Expires after 7 days.
    // For avoiding concurrent writing of same files (e. g. after the user has pressed a button twice).
    private Set<File> savingFiles = new HashSet<>();
    private MemoryCache<Archive, RecentEntry> recents = new MemoryCache<>(MAX_SIZE_MEMORY_CACHE);
    final FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration();
 
    ArchiveFilelistCache(File cacheDir, int cacheArchiveContentMaxDiscSizeMB) {
        this.cacheDir = cacheDir;
        this.cacheArchiveContentMaxDiscSizeMB = cacheArchiveContentMaxDiscSizeMB;
        conf.registerClass(Integer.class, BorgFilesystemItem.class);
        conf.setShareReferences(false);
    }
 
    public void save(BorgRepoConfig repoConfig, Archive archive, List<BorgFilesystemItem> filesystemItems) {
        if (CollectionUtils.isEmpty(filesystemItems)) {
            return;
        }
        File file = getFile(repoConfig, archive);
        try {
            synchronized (savingFiles) {
                if (savingFiles.contains(file)) {
                    // File will already be written. This occurs if the user pressed a button twice.
                    log.info("Don't write the archive content twice.");
                    return;
                }
                savingFiles.add(file);
                Collections.sort(filesystemItems); // Sort by path.
            }
            log.info("Saving archive content as file list: " + file.getAbsolutePath());
            boolean ok = false;
 
            int fileNumber = -1;
            try (FSTObjectOutput outputStream
                         = new FSTObjectOutput(new BufferedOutputStream(new GzipCompressorOutputStream(new FileOutputStream(file))), conf)) {
                outputStream.writeObject(filesystemItems.size(), Integer.class);
                Iterator<BorgFilesystemItem> it = filesystemItems.iterator();
                while (it.hasNext()) {
                    BorgFilesystemItem item = it.next();
                    item.setFileNumber(++fileNumber);
                    outputStream.writeObject(item, BorgFilesystemItem.class);
                }
                outputStream.writeObject("EOF");
                ok = true;
            } catch (IOException ex) {
                log.error("Error while writing file list '" + file.getAbsolutePath() + "': " + ex.getMessage(), ex);
            }
            if (ok) {
                // Storing current read gz archive in memory cache (recents):
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    FileUtils.copyFile(file, baos);
                    recents.add(new RecentEntry(archive, baos.toByteArray()));
                } catch (IOException ex) {
                    log.error("Error while writing gz archive to memory cache: " + ex.getMessage(), ex);
                }
            }
        } finally {
            synchronized (savingFiles) {
                savingFiles.remove(file);
            }
        }
        log.info("Saving done.");
    }
 
    /**
     * @param repository
     * @param archive
     * @return true, if the content of the archive is already cached, otherwise false.
     */
    public boolean contains(Repository repository, Archive archive) {
        File file = getFile(repository, archive);
        return file.exists();
    }
 
    /**
     * Calls {@link #load(BorgRepoConfig, Archive, FileSystemFilter)} with filter null.
     *
     * @param repoConfig
     * @param archive
     * @return
     */
    public List<BorgFilesystemItem> load(BorgRepoConfig repoConfig, Archive archive) {
        return load(repoConfig, archive, null);
    }
 
 
    /**
     * Will load and touch the archive file if exist. The file will be touched (last modified time will be set to now)
     * for pruning oldest cache files. The last modified time will be the time of the last usage.
     *
     * @param repoConfig
     * @param archive
     * @param filter     If given, only file items matching this filter are returned.
     * @return
     */
    public List<BorgFilesystemItem> load(BorgRepoConfig repoConfig, Archive archive, FileSystemFilter filter) {
        File file = getFile(repoConfig, archive);
        if (!file.exists()) {
            return null;
        }
        return load(file, archive, filter);
    }
 
    /**
     * @param file
     * @param filter If given, only file items matching this filter are returned.
     * @return
     */
    public List<BorgFilesystemItem> load(File file, FileSystemFilter filter) {
        return load(file, null, filter);
    }
 
    /**
     * @param file
     * @param archive Only for storing file system items as recent (may-be null)
     * @param filter  If given, only file items matching this filter are returned.
     * @return
     */
    public List<BorgFilesystemItem> load(File file, Archive archive, FileSystemFilter filter) {
        if (!file.exists()) {
            log.error("File '" + file.getAbsolutePath() + "' doesn't exist. Can't get archive content files.");
            return null;
        }
        log.info("Loading archive content as file list from: " + file.getAbsolutePath());
        try {
            // Set last modified time of file:
            Files.setAttribute(file.toPath(), "lastModifiedTime", FileTime.fromMillis(System.currentTimeMillis()));
        } catch (IOException ex) {
            log.error("Can't set lastModifiedTime on file '" + file.getAbsolutePath() + "'. Pruning old cache files may not work.");
        }
        RecentEntry recentEntry = recents.getRecent(archive);
        byte[] bytes = null;
        if (recentEntry != null) {
            bytes = recentEntry.serializedGz;
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                FileUtils.copyFile(file, baos);
                bytes = baos.toByteArray();
                recents.add(new RecentEntry(archive, bytes));
            } catch (IOException ex) {
                log.error("Error while restoring file: " + file.getAbsolutePath() + ": " + ex.getMessage(), ex);
                return null;
            }
        }
        List<BorgFilesystemItem> list = new ArrayList<>();
        try (FSTObjectInput inputStream = new FSTObjectInput(new BufferedInputStream(new GzipCompressorInputStream(new ByteArrayInputStream(bytes))), conf)) {
            int size = (Integer) inputStream.readObject(Integer.class);
            for (int i = 0; i < size; i++) {
                BorgFilesystemItem item = (BorgFilesystemItem) inputStream.readObject(BorgFilesystemItem.class);
                if (filter == null || filter.matches(item)) {
                    list.add(item);
                    if (filter != null && filter.isFinished()) break;
                }
            }
        } catch (Exception ex) {
            log.error("Error while reading file list '" + file.getAbsolutePath() + "': " + ex.getMessage(), ex);
        }
 
        log.info("Loading done.");
        return filter(list, filter);
    }
 
    private List<BorgFilesystemItem> filter(List<BorgFilesystemItem> filesystemItems, FileSystemFilter filter) {
        if (filter != null) {
            return filter.reduce(filesystemItems);
        }
        return filesystemItems;
    }
 
    /**
     * Deletes archive contents older than 7 days and deletes the oldest archive contents if the max cache size is
     * exceeded. The last modified time of a file is equals to the last usage by
     * {@link #load(BorgRepoConfig, Archive, FileSystemFilter)}.
     */
    public void cleanUp() {
        File[] files = cacheDir.listFiles();
        long currentMillis = System.currentTimeMillis();
        for (File file : files) {
            try {
                if (!file.exists() || !isCacheFile(file)) continue;
                // Get last modified time of file:
                FileTime time = Files.readAttributes(file.toPath(), BasicFileAttributes.class).lastModifiedTime();
                if (currentMillis - FILES_EXPIRE_TIME > time.toMillis()) {
                    log.info("Delete expired cache file (last usage " + time + " older than 7 days): " + file.getAbsolutePath());
                    file.delete();
                }
            } catch (IOException ex) {
                log.error("Can't get last modified time from cache files (ignore file '" + file.getAbsolutePath() + "'): " + ex.getMessage(), ex);
            }
        }
        int sizeInMB = getCacheDiskSizeInMB(files);
        if (sizeInMB > cacheArchiveContentMaxDiscSizeMB) {
            log.info("Maximum size of cache files exceeded (" + sizeInMB + "MB > " + cacheArchiveContentMaxDiscSizeMB
                    + "MB). Deleting the old ones (with the oldest usage)...");
        } else {
            // Nothing to clean up anymore.
            return;
        }
        SortedMap<FileTime, File> sortedFiles = new TreeMap<>();
        for (File file : files) {
            if (!file.exists() || !isCacheFile(file)) continue;
            try {
                // Get last modified time of file:
                FileTime time = Files.readAttributes(file.toPath(), BasicFileAttributes.class).lastModifiedTime();
                sortedFiles.put(time, file);
            } catch (IOException ex) {
                log.error("Can't get last modified time from cache files (ignore file '" + file.getAbsolutePath() + "'): " + ex.getMessage(), ex);
            }
        }
        for (Map.Entry<FileTime, File> entry : sortedFiles.entrySet()) {
            FileTime time = entry.getKey();
            File file = entry.getValue();
            if (!file.exists() || !isCacheFile(file)) continue;
            log.info("Deleting cache file (last usage " + time + "): " + file.getAbsolutePath());
            file.delete();
            int newSizeInMB = getCacheDiskSizeInMB(files);
            if (newSizeInMB < cacheArchiveContentMaxDiscSizeMB) {
                log.info("New cache size is " + newSizeInMB + "MB. (" + (sizeInMB - newSizeInMB) + "MB deleted.)");
                break;
            }
        }
    }
 
    public int getCacheDiskSizeInMB() {
        return getCacheDiskSizeInMB(cacheDir.listFiles());
    }
 
    private int getCacheDiskSizeInMB(File[] files) {
        int sizeInMB = 0;
        for (File file : files) {
            if (!file.exists()) continue;
            if (!isCacheFile(file)) continue;
            sizeInMB += (int) (file.length() / 1048576); // In MB
        }
        return sizeInMB;
    }
 
    public void removeAllCacheFiles() {
        File[] files = cacheDir.listFiles();
        for (File file : files) {
            if (isCacheFile(file)) {
                log.info("Deleting cache file: " + file.getAbsolutePath());
                file.delete();
            }
        }
    }
 
    File getFile(Repository repository, Archive archive) {
        return getFile(repository.getName(), archive);
    }
 
    File getFile(BorgRepoConfig repoConfig, Archive archive) {
        return getFile(repoConfig.getRepo(), archive);
    }
 
    private File getFile(String repo, Archive archive) {
        return new File(cacheDir, ReplaceUtils.encodeFilename(CACHE_ARCHIVE_LISTS_BASENAME + archive.getTime()
                        + "-" + repo + "-" + archive.getName() + CACHE_FILE_GZIP_EXTENSION,
                true));
    }
 
    private boolean isCacheFile(File file) {
        return file.getName().startsWith(CACHE_ARCHIVE_LISTS_BASENAME);
    }
 
    private class RecentEntry extends MemoryCacheObject<Archive> {
        private byte[] serializedGz;
 
        @Override
        protected boolean matches(Archive identifier) {
            return StringUtils.equals(this.getIdentifier().getId(), identifier.getId());
        }
 
        @Override
        protected int getSize() {
            return serializedGz != null ? serializedGz.length : 0;
        }
 
        private RecentEntry(Archive archive, byte[] serializedGz) {
            super(archive);
            this.serializedGz = serializedGz;
        }
    }
}