Write the backup descriptor as the very last step in a backup.
[cumulus.git] / scandir.cc
1 /* Recursively descend the filesystem and visit each file. */
2
3 #include <dirent.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <getopt.h>
7 #include <grp.h>
8 #include <pwd.h>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include <algorithm>
17 #include <fstream>
18 #include <iostream>
19 #include <list>
20 #include <set>
21 #include <sstream>
22 #include <string>
23 #include <vector>
24
25 #include "format.h"
26 #include "localdb.h"
27 #include "store.h"
28 #include "sha1.h"
29 #include "statcache.h"
30
31 using std::list;
32 using std::string;
33 using std::vector;
34 using std::ostream;
35
36 static TarSegmentStore *tss = NULL;
37
38 /* Buffer for holding a single block of data read from a file. */
39 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
40 static char *block_buf;
41
42 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
43
44 /* Local database, which tracks objects written in this and previous
45  * invocations to help in creating incremental snapshots. */
46 LocalDb *db;
47
48 /* Stat cache, which stored data locally to speed the backup process by quickly
49  * skipping files which have not changed. */
50 StatCache *statcache;
51
52 /* Contents of the root object.  This will contain a set of indirect links to
53  * the metadata objects. */
54 std::ostringstream metadata_root;
55
56 /* Buffer for building up metadata. */
57 std::ostringstream metadata;
58
59 /* Keep track of all segments which are needed to reconstruct the snapshot. */
60 std::set<string> segment_list;
61
62 void scandir(const string& path);
63
64 /* Selection of files to include/exclude in the snapshot. */
65 std::list<string> excludes;
66
67 /* Ensure contents of metadata are flushed to an object. */
68 void metadata_flush()
69 {
70     string m = metadata.str();
71     if (m.size() == 0)
72         return;
73
74     /* Write current metadata information to a new object. */
75     LbsObject *meta = new LbsObject;
76     meta->set_group("metadata");
77     meta->set_data(m.data(), m.size());
78     meta->write(tss);
79     meta->checksum();
80
81     /* Write a reference to this block in the root. */
82     ObjectReference ref = meta->get_ref();
83     metadata_root << "@" << ref.to_string() << "\n";
84     segment_list.insert(ref.get_segment());
85
86     delete meta;
87
88     metadata.str("");
89 }
90
91 /* Read data from a file descriptor and return the amount of data read.  A
92  * short read (less than the requested size) will only occur if end-of-file is
93  * hit. */
94 size_t file_read(int fd, char *buf, size_t maxlen)
95 {
96     size_t bytes_read = 0;
97
98     while (true) {
99         ssize_t res = read(fd, buf, maxlen);
100         if (res < 0) {
101             if (errno == EINTR)
102                 continue;
103             throw IOException("file_read: error reading");
104         } else if (res == 0) {
105             break;
106         } else {
107             bytes_read += res;
108             buf += res;
109             maxlen -= res;
110         }
111     }
112
113     return bytes_read;
114 }
115
116 /* Read the contents of a file (specified by an open file descriptor) and copy
117  * the data to the store.  Returns the size of the file (number of bytes
118  * dumped), or -1 on error. */
119 int64_t dumpfile(int fd, dictionary &file_info, const string &path)
120 {
121     struct stat stat_buf;
122     fstat(fd, &stat_buf);
123     int64_t size = 0;
124     list<string> object_list;
125
126     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
127         fprintf(stderr, "file is no longer a regular file!\n");
128         return -1;
129     }
130
131     /* The index data consists of a sequence of pointers to the data blocks
132      * that actually comprise the file data.  This level of indirection is used
133      * so that the same data block can be used in multiple files, or multiple
134      * versions of the same file. */
135     SHA1Checksum hash;
136     while (true) {
137         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
138         if (bytes == 0)
139             break;
140
141         hash.process(block_buf, bytes);
142
143         // Either find a copy of this block in an already-existing segment, or
144         // index it so it can be re-used in the future
145         double block_age = 0.0;
146         SHA1Checksum block_hash;
147         block_hash.process(block_buf, bytes);
148         string block_csum = block_hash.checksum_str();
149         ObjectReference ref = db->FindObject(block_csum, bytes);
150
151         // Store a copy of the object if one does not yet exist
152         if (ref.get_segment().size() == 0) {
153             LbsObject *o = new LbsObject;
154
155             /* We might still have seen this checksum before, if the object was
156              * stored at some time in the past, but we have decided to clean
157              * the segment the object was originally stored in (FindObject will
158              * not return such objects).  When rewriting the object contents,
159              * put it in a separate group, so that old objects get grouped
160              * together.  The hope is that these old objects will continue to
161              * be used in the future, and we obtain segments which will
162              * continue to be well-utilized.  Additionally, keep track of the
163              * age of the data by looking up the age of the block which was
164              * expired and using that instead of the current time. */
165             if (db->IsOldObject(block_csum, bytes, &block_age))
166                 o->set_group("compacted");
167             else
168                 o->set_group("data");
169
170             o->set_data(block_buf, bytes);
171             o->write(tss);
172             ref = o->get_ref();
173             db->StoreObject(ref, block_csum, bytes, block_age);
174             delete o;
175         }
176
177         object_list.push_back(ref.to_string());
178         segment_list.insert(ref.get_segment());
179         db->UseObject(ref);
180         size += bytes;
181     }
182
183     file_info["checksum"] = hash.checksum_str();
184
185     statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
186
187     /* For files that only need to be broken apart into a few objects, store
188      * the list of objects directly.  For larger files, store the data
189      * out-of-line and provide a pointer to the indrect object. */
190     if (object_list.size() < 8) {
191         string blocklist = "";
192         for (list<string>::iterator i = object_list.begin();
193              i != object_list.end(); ++i) {
194             if (i != object_list.begin())
195                 blocklist += " ";
196             blocklist += *i;
197         }
198         file_info["data"] = blocklist;
199     } else {
200         string blocklist = "";
201         for (list<string>::iterator i = object_list.begin();
202              i != object_list.end(); ++i) {
203             blocklist += *i + "\n";
204         }
205
206         LbsObject *i = new LbsObject;
207         i->set_group("metadata");
208         i->set_data(blocklist.data(), blocklist.size());
209         i->write(tss);
210         file_info["data"] = "@" + i->get_name();
211         segment_list.insert(i->get_ref().get_segment());
212         delete i;
213     }
214
215     return size;
216 }
217
218 void scanfile(const string& path)
219 {
220     int fd;
221     long flags;
222     struct stat stat_buf;
223     char *buf;
224     ssize_t len;
225     int64_t file_size;
226     list<string> refs;
227
228     // Set to true if the item is a directory and we should recursively scan
229     bool recurse = false;
230
231     // Check this file against the include/exclude list to see if it should be
232     // considered
233     for (list<string>::iterator i = excludes.begin();
234          i != excludes.end(); ++i) {
235         if (path == *i) {
236             printf("Excluding %s\n", path.c_str());
237             return;
238         }
239     }
240
241     dictionary file_info;
242
243     lstat(path.c_str(), &stat_buf);
244
245     printf("%s\n", path.c_str());
246
247     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
248     file_info["mtime"] = encode_int(stat_buf.st_mtime);
249     file_info["user"] = encode_int(stat_buf.st_uid);
250     file_info["group"] = encode_int(stat_buf.st_gid);
251
252     struct passwd *pwd = getpwuid(stat_buf.st_uid);
253     if (pwd != NULL) {
254         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
255     }
256
257     struct group *grp = getgrgid(stat_buf.st_gid);
258     if (pwd != NULL) {
259         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
260     }
261
262     char inode_type;
263
264     switch (stat_buf.st_mode & S_IFMT) {
265     case S_IFIFO:
266         inode_type = 'p';
267         break;
268     case S_IFSOCK:
269         inode_type = 's';
270         break;
271     case S_IFCHR:
272         inode_type = 'c';
273         break;
274     case S_IFBLK:
275         inode_type = 'b';
276         break;
277     case S_IFLNK:
278         inode_type = 'l';
279
280         /* Use the reported file size to allocate a buffer large enough to read
281          * the symlink.  Allocate slightly more space, so that we ask for more
282          * bytes than we expect and so check for truncation. */
283         buf = new char[stat_buf.st_size + 2];
284         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
285         if (len < 0) {
286             fprintf(stderr, "error reading symlink: %m\n");
287         } else if (len <= stat_buf.st_size) {
288             buf[len] = '\0';
289             file_info["contents"] = uri_encode(buf);
290         } else if (len > stat_buf.st_size) {
291             fprintf(stderr, "error reading symlink: name truncated\n");
292         }
293
294         delete[] buf;
295         break;
296     case S_IFREG:
297         inode_type = '-';
298
299         /* Be paranoid when opening the file.  We have no guarantee that the
300          * file was not replaced between the stat() call above and the open()
301          * call below, so we might not even be opening a regular file.  That
302          * the file descriptor refers to a regular file is checked in
303          * dumpfile().  But we also supply flags to open to to guard against
304          * various conditions before we can perform that verification:
305          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
306          *   - O_NONBLOCK: prevents open() from blocking if the file was
307          *     replaced by a fifo
308          * We also add in O_NOATIME, since this may reduce disk writes (for
309          * inode updates).  However, O_NOATIME may result in EPERM, so if the
310          * initial open fails, try again without O_NOATIME.  */
311         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
312         if (fd < 0) {
313             fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
314         }
315         if (fd < 0) {
316             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
317             return;
318         }
319
320         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
321          * open. */
322         flags = fcntl(fd, F_GETFL);
323         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
324
325         file_size = dumpfile(fd, file_info, path);
326         file_info["size"] = encode_int(file_size);
327         close(fd);
328
329         if (file_size < 0)
330             return;             // error occurred; do not dump file
331
332         if (file_size != stat_buf.st_size) {
333             fprintf(stderr, "Warning: Size of %s changed during reading\n",
334                     path.c_str());
335         }
336
337         break;
338     case S_IFDIR:
339         inode_type = 'd';
340         recurse = true;
341         break;
342
343     default:
344         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
345         return;
346     }
347
348     file_info["type"] = string(1, inode_type);
349
350     metadata << "name: " << uri_encode(path) << "\n";
351     dict_output(metadata, file_info);
352     metadata << "\n";
353
354     // Break apart metadata listing if it becomes too large.
355     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
356         metadata_flush();
357
358     // If we hit a directory, now that we've written the directory itself,
359     // recursively scan the directory.
360     if (recurse)
361         scandir(path);
362 }
363
364 void scandir(const string& path)
365 {
366     DIR *dir = opendir(path.c_str());
367
368     if (dir == NULL) {
369         fprintf(stderr, "Error: %m\n");
370         return;
371     }
372
373     struct dirent *ent;
374     vector<string> contents;
375     while ((ent = readdir(dir)) != NULL) {
376         string filename(ent->d_name);
377         if (filename == "." || filename == "..")
378             continue;
379         contents.push_back(filename);
380     }
381
382     sort(contents.begin(), contents.end());
383
384     for (vector<string>::iterator i = contents.begin();
385          i != contents.end(); ++i) {
386         const string& filename = *i;
387         if (path == ".")
388             scanfile(filename);
389         else
390             scanfile(path + "/" + filename);
391     }
392
393     closedir(dir);
394 }
395
396 void usage(const char *program)
397 {
398     fprintf(stderr,
399             "Usage: %s [OPTION]... SOURCE DEST\n"
400             "Produce backup snapshot of files in SOURCE and store to DEST.\n"
401             "\n"
402             "Options:\n"
403             "  --exclude=PATH       exclude files in PATH from snapshot\n"
404             "  --localdb=PATH       local backup metadata is stored in PATH\n",
405             program);
406 }
407
408 int main(int argc, char *argv[])
409 {
410     string backup_source = ".";
411     string backup_dest = ".";
412     string localdb_dir = "";
413
414     while (1) {
415         static struct option long_options[] = {
416             {"localdb", 1, 0, 0},           // 0
417             {"exclude", 1, 0, 0},           // 1
418             {"filter", 1, 0, 0},            // 2
419             {"filter-extension", 1, 0, 0},  // 3
420             {NULL, 0, 0, 0},
421         };
422
423         int long_index;
424         int c = getopt_long(argc, argv, "", long_options, &long_index);
425
426         if (c == -1)
427             break;
428
429         if (c == 0) {
430             switch (long_index) {
431             case 0:     // --localdb
432                 localdb_dir = optarg;
433                 break;
434             case 1:     // --exclude
435                 excludes.push_back(optarg);
436                 break;
437             case 2:     // --filter
438                 filter_program = optarg;
439                 break;
440             case 3:     // --filter-extension
441                 filter_extension = optarg;
442                 break;
443             default:
444                 fprintf(stderr, "Unhandled long option!\n");
445                 return 1;
446             }
447         } else {
448             usage(argv[0]);
449             return 1;
450         }
451     }
452
453     if (argc < optind + 2) {
454         usage(argv[0]);
455         return 1;
456     }
457
458     backup_source = argv[optind];
459     backup_dest = argv[argc - 1];
460
461     if (localdb_dir == "") {
462         localdb_dir = backup_dest;
463     }
464
465     printf("Source: %s\nDest: %s\nDatabase: %s\n\n",
466            backup_source.c_str(), backup_dest.c_str(), localdb_dir.c_str());
467
468     tss = new TarSegmentStore(backup_dest);
469     block_buf = new char[LBS_BLOCK_SIZE];
470
471     /* Store the time when the backup started, so it can be included in the
472      * snapshot name. */
473     time_t now;
474     struct tm time_buf;
475     char desc_buf[256];
476     time(&now);
477     localtime_r(&now, &time_buf);
478     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
479
480     /* Open the local database which tracks all objects that are stored
481      * remotely, for efficient incrementals.  Provide it with the name of this
482      * snapshot. */
483     string database_path = localdb_dir + "/localdb.sqlite";
484     db = new LocalDb;
485     db->Open(database_path.c_str(), desc_buf);
486
487     /* Initialize the stat cache, for skipping over unchanged files. */
488     statcache = new StatCache;
489     statcache->Open(localdb_dir.c_str(), desc_buf);
490
491     try {
492         scanfile(".");
493     } catch (IOException e) {
494         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
495     }
496
497     metadata_flush();
498     const string md = metadata_root.str();
499
500     LbsObject *root = new LbsObject;
501     root->set_group("metadata");
502     root->set_data(md.data(), md.size());
503     root->write(tss);
504     root->checksum();
505     segment_list.insert(root->get_ref().get_segment());
506
507     string backup_root = root->get_ref().to_string();
508     delete root;
509
510     db->Close();
511
512     statcache->Close();
513     delete statcache;
514
515     tss->sync();
516     delete tss;
517
518     /* Write a backup descriptor file, which says which segments are needed and
519      * where to start to restore this snapshot.  The filename is based on the
520      * current time. */
521     string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
522     std::ofstream descriptor(desc_filename.c_str());
523
524     descriptor << "Format: LBS Snapshot v0.1\n";
525     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
526     descriptor << "Date: " << desc_buf << "\n";
527     descriptor << "Root: " << backup_root << "\n";
528
529     descriptor << "Segments:\n";
530     for (std::set<string>::iterator i = segment_list.begin();
531          i != segment_list.end(); ++i) {
532         descriptor << "    " << *i << "\n";
533     }
534
535     return 0;
536 }