Dump statistics of data written at the end of a backup run.
[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     /* Look up this file in the old stat cache, if we can.  If the stat
132      * information indicates that the file has not changed, do not bother
133      * re-reading the entire contents. */
134     bool cached = false;
135
136     if (statcache->Find(path, &stat_buf)) {
137         cached = true;
138         const list<ObjectReference> &blocks = statcache->get_blocks();
139
140         /* If any of the blocks in the object have been expired, then we should
141          * fall back to fully reading in the file. */
142         for (list<ObjectReference>::const_iterator i = blocks.begin();
143              i != blocks.end(); ++i) {
144             const ObjectReference &ref = *i;
145             if (!db->IsAvailable(ref)) {
146                 cached = false;
147                 break;
148             }
149         }
150
151         /* If everything looks okay, use the cached information */
152         if (cached) {
153             file_info["checksum"] = statcache->get_checksum();
154             for (list<ObjectReference>::const_iterator i = blocks.begin();
155                  i != blocks.end(); ++i) {
156                 const ObjectReference &ref = *i;
157                 object_list.push_back(ref.to_string());
158                 segment_list.insert(ref.get_segment());
159                 db->UseObject(ref);
160             }
161             size = stat_buf.st_size;
162         }
163     }
164
165     /* If the file is new or changed, we must read in the contents a block at a
166      * time. */
167     if (!cached) {
168         printf("    [new]\n");
169
170         SHA1Checksum hash;
171         while (true) {
172             size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
173             if (bytes == 0)
174                 break;
175
176             hash.process(block_buf, bytes);
177
178             // Either find a copy of this block in an already-existing segment,
179             // or index it so it can be re-used in the future
180             double block_age = 0.0;
181             SHA1Checksum block_hash;
182             block_hash.process(block_buf, bytes);
183             string block_csum = block_hash.checksum_str();
184             ObjectReference ref = db->FindObject(block_csum, bytes);
185
186             // Store a copy of the object if one does not yet exist
187             if (ref.get_segment().size() == 0) {
188                 LbsObject *o = new LbsObject;
189
190                 /* We might still have seen this checksum before, if the object
191                  * was stored at some time in the past, but we have decided to
192                  * clean the segment the object was originally stored in
193                  * (FindObject will not return such objects).  When rewriting
194                  * the object contents, put it in a separate group, so that old
195                  * objects get grouped together.  The hope is that these old
196                  * objects will continue to be used in the future, and we
197                  * obtain segments which will continue to be well-utilized.
198                  * Additionally, keep track of the age of the data by looking
199                  * up the age of the block which was expired and using that
200                  * instead of the current time. */
201                 if (db->IsOldObject(block_csum, bytes, &block_age))
202                     o->set_group("compacted");
203                 else
204                     o->set_group("data");
205
206                 o->set_data(block_buf, bytes);
207                 o->write(tss);
208                 ref = o->get_ref();
209                 db->StoreObject(ref, block_csum, bytes, block_age);
210                 delete o;
211             }
212
213             object_list.push_back(ref.to_string());
214             segment_list.insert(ref.get_segment());
215             db->UseObject(ref);
216             size += bytes;
217         }
218
219         file_info["checksum"] = hash.checksum_str();
220     }
221
222     statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
223
224     /* For files that only need to be broken apart into a few objects, store
225      * the list of objects directly.  For larger files, store the data
226      * out-of-line and provide a pointer to the indrect object. */
227     if (object_list.size() < 8) {
228         string blocklist = "";
229         for (list<string>::iterator i = object_list.begin();
230              i != object_list.end(); ++i) {
231             if (i != object_list.begin())
232                 blocklist += " ";
233             blocklist += *i;
234         }
235         file_info["data"] = blocklist;
236     } else {
237         string blocklist = "";
238         for (list<string>::iterator i = object_list.begin();
239              i != object_list.end(); ++i) {
240             blocklist += *i + "\n";
241         }
242
243         LbsObject *i = new LbsObject;
244         i->set_group("metadata");
245         i->set_data(blocklist.data(), blocklist.size());
246         i->write(tss);
247         file_info["data"] = "@" + i->get_name();
248         segment_list.insert(i->get_ref().get_segment());
249         delete i;
250     }
251
252     return size;
253 }
254
255 void scanfile(const string& path)
256 {
257     int fd;
258     long flags;
259     struct stat stat_buf;
260     char *buf;
261     ssize_t len;
262     int64_t file_size;
263     list<string> refs;
264
265     // Set to true if the item is a directory and we should recursively scan
266     bool recurse = false;
267
268     // Check this file against the include/exclude list to see if it should be
269     // considered
270     for (list<string>::iterator i = excludes.begin();
271          i != excludes.end(); ++i) {
272         if (path == *i) {
273             printf("Excluding %s\n", path.c_str());
274             return;
275         }
276     }
277
278     dictionary file_info;
279
280     lstat(path.c_str(), &stat_buf);
281
282     printf("%s\n", path.c_str());
283
284     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
285     file_info["mtime"] = encode_int(stat_buf.st_mtime);
286     file_info["user"] = encode_int(stat_buf.st_uid);
287     file_info["group"] = encode_int(stat_buf.st_gid);
288
289     struct passwd *pwd = getpwuid(stat_buf.st_uid);
290     if (pwd != NULL) {
291         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
292     }
293
294     struct group *grp = getgrgid(stat_buf.st_gid);
295     if (pwd != NULL) {
296         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
297     }
298
299     char inode_type;
300
301     switch (stat_buf.st_mode & S_IFMT) {
302     case S_IFIFO:
303         inode_type = 'p';
304         break;
305     case S_IFSOCK:
306         inode_type = 's';
307         break;
308     case S_IFCHR:
309         inode_type = 'c';
310         break;
311     case S_IFBLK:
312         inode_type = 'b';
313         break;
314     case S_IFLNK:
315         inode_type = 'l';
316
317         /* Use the reported file size to allocate a buffer large enough to read
318          * the symlink.  Allocate slightly more space, so that we ask for more
319          * bytes than we expect and so check for truncation. */
320         buf = new char[stat_buf.st_size + 2];
321         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
322         if (len < 0) {
323             fprintf(stderr, "error reading symlink: %m\n");
324         } else if (len <= stat_buf.st_size) {
325             buf[len] = '\0';
326             file_info["contents"] = uri_encode(buf);
327         } else if (len > stat_buf.st_size) {
328             fprintf(stderr, "error reading symlink: name truncated\n");
329         }
330
331         delete[] buf;
332         break;
333     case S_IFREG:
334         inode_type = '-';
335
336         /* Be paranoid when opening the file.  We have no guarantee that the
337          * file was not replaced between the stat() call above and the open()
338          * call below, so we might not even be opening a regular file.  That
339          * the file descriptor refers to a regular file is checked in
340          * dumpfile().  But we also supply flags to open to to guard against
341          * various conditions before we can perform that verification:
342          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
343          *   - O_NONBLOCK: prevents open() from blocking if the file was
344          *     replaced by a fifo
345          * We also add in O_NOATIME, since this may reduce disk writes (for
346          * inode updates).  However, O_NOATIME may result in EPERM, so if the
347          * initial open fails, try again without O_NOATIME.  */
348         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
349         if (fd < 0) {
350             fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
351         }
352         if (fd < 0) {
353             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
354             return;
355         }
356
357         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
358          * open. */
359         flags = fcntl(fd, F_GETFL);
360         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
361
362         file_size = dumpfile(fd, file_info, path);
363         file_info["size"] = encode_int(file_size);
364         close(fd);
365
366         if (file_size < 0)
367             return;             // error occurred; do not dump file
368
369         if (file_size != stat_buf.st_size) {
370             fprintf(stderr, "Warning: Size of %s changed during reading\n",
371                     path.c_str());
372         }
373
374         break;
375     case S_IFDIR:
376         inode_type = 'd';
377         recurse = true;
378         break;
379
380     default:
381         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
382         return;
383     }
384
385     file_info["type"] = string(1, inode_type);
386
387     metadata << "name: " << uri_encode(path) << "\n";
388     dict_output(metadata, file_info);
389     metadata << "\n";
390
391     // Break apart metadata listing if it becomes too large.
392     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
393         metadata_flush();
394
395     // If we hit a directory, now that we've written the directory itself,
396     // recursively scan the directory.
397     if (recurse)
398         scandir(path);
399 }
400
401 void scandir(const string& path)
402 {
403     DIR *dir = opendir(path.c_str());
404
405     if (dir == NULL) {
406         fprintf(stderr, "Error: %m\n");
407         return;
408     }
409
410     struct dirent *ent;
411     vector<string> contents;
412     while ((ent = readdir(dir)) != NULL) {
413         string filename(ent->d_name);
414         if (filename == "." || filename == "..")
415             continue;
416         contents.push_back(filename);
417     }
418
419     sort(contents.begin(), contents.end());
420
421     for (vector<string>::iterator i = contents.begin();
422          i != contents.end(); ++i) {
423         const string& filename = *i;
424         if (path == ".")
425             scanfile(filename);
426         else
427             scanfile(path + "/" + filename);
428     }
429
430     closedir(dir);
431 }
432
433 void usage(const char *program)
434 {
435     fprintf(stderr,
436             "Usage: %s [OPTION]... SOURCE DEST\n"
437             "Produce backup snapshot of files in SOURCE and store to DEST.\n"
438             "\n"
439             "Options:\n"
440             "  --exclude=PATH       exclude files in PATH from snapshot\n"
441             "  --localdb=PATH       local backup metadata is stored in PATH\n",
442             program);
443 }
444
445 int main(int argc, char *argv[])
446 {
447     string backup_source = ".";
448     string backup_dest = ".";
449     string localdb_dir = "";
450
451     while (1) {
452         static struct option long_options[] = {
453             {"localdb", 1, 0, 0},           // 0
454             {"exclude", 1, 0, 0},           // 1
455             {"filter", 1, 0, 0},            // 2
456             {"filter-extension", 1, 0, 0},  // 3
457             {NULL, 0, 0, 0},
458         };
459
460         int long_index;
461         int c = getopt_long(argc, argv, "", long_options, &long_index);
462
463         if (c == -1)
464             break;
465
466         if (c == 0) {
467             switch (long_index) {
468             case 0:     // --localdb
469                 localdb_dir = optarg;
470                 break;
471             case 1:     // --exclude
472                 excludes.push_back(optarg);
473                 break;
474             case 2:     // --filter
475                 filter_program = optarg;
476                 break;
477             case 3:     // --filter-extension
478                 filter_extension = optarg;
479                 break;
480             default:
481                 fprintf(stderr, "Unhandled long option!\n");
482                 return 1;
483             }
484         } else {
485             usage(argv[0]);
486             return 1;
487         }
488     }
489
490     if (argc < optind + 2) {
491         usage(argv[0]);
492         return 1;
493     }
494
495     backup_source = argv[optind];
496     backup_dest = argv[argc - 1];
497
498     if (localdb_dir == "") {
499         localdb_dir = backup_dest;
500     }
501
502     printf("Source: %s\nDest: %s\nDatabase: %s\n\n",
503            backup_source.c_str(), backup_dest.c_str(), localdb_dir.c_str());
504
505     tss = new TarSegmentStore(backup_dest);
506     block_buf = new char[LBS_BLOCK_SIZE];
507
508     /* Store the time when the backup started, so it can be included in the
509      * snapshot name. */
510     time_t now;
511     struct tm time_buf;
512     char desc_buf[256];
513     time(&now);
514     localtime_r(&now, &time_buf);
515     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
516
517     /* Open the local database which tracks all objects that are stored
518      * remotely, for efficient incrementals.  Provide it with the name of this
519      * snapshot. */
520     string database_path = localdb_dir + "/localdb.sqlite";
521     db = new LocalDb;
522     db->Open(database_path.c_str(), desc_buf);
523
524     /* Initialize the stat cache, for skipping over unchanged files. */
525     statcache = new StatCache;
526     statcache->Open(localdb_dir.c_str(), desc_buf);
527
528     try {
529         scanfile(".");
530     } catch (IOException e) {
531         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
532     }
533
534     metadata_flush();
535     const string md = metadata_root.str();
536
537     LbsObject *root = new LbsObject;
538     root->set_group("metadata");
539     root->set_data(md.data(), md.size());
540     root->write(tss);
541     root->checksum();
542     segment_list.insert(root->get_ref().get_segment());
543
544     string backup_root = root->get_ref().to_string();
545     delete root;
546
547     db->Close();
548
549     statcache->Close();
550     delete statcache;
551
552     tss->sync();
553     tss->dump_stats();
554     delete tss;
555
556     /* Write a backup descriptor file, which says which segments are needed and
557      * where to start to restore this snapshot.  The filename is based on the
558      * current time. */
559     string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
560     std::ofstream descriptor(desc_filename.c_str());
561
562     descriptor << "Format: LBS Snapshot v0.1\n";
563     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
564     descriptor << "Date: " << desc_buf << "\n";
565     descriptor << "Root: " << backup_root << "\n";
566
567     descriptor << "Segments:\n";
568     for (std::set<string>::iterator i = segment_list.begin();
569          i != segment_list.end(); ++i) {
570         descriptor << "    " << *i << "\n";
571     }
572
573     return 0;
574 }