Auto-generate a version number for the program with git-describe.
[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 /* Version information.  This will be filled in by the Makefile. */
37 #ifndef LBS_VERSION
38 #define LBS_VERSION Unknown
39 #endif
40 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
41 #define LBS_STRINGIFY2(s) #s
42 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
43
44 static TarSegmentStore *tss = NULL;
45
46 /* Buffer for holding a single block of data read from a file. */
47 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
48 static char *block_buf;
49
50 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
51
52 /* Local database, which tracks objects written in this and previous
53  * invocations to help in creating incremental snapshots. */
54 LocalDb *db;
55
56 /* Stat cache, which stored data locally to speed the backup process by quickly
57  * skipping files which have not changed. */
58 StatCache *statcache;
59
60 /* Contents of the root object.  This will contain a set of indirect links to
61  * the metadata objects. */
62 std::ostringstream metadata_root;
63
64 /* Buffer for building up metadata. */
65 std::ostringstream metadata;
66
67 /* Keep track of all segments which are needed to reconstruct the snapshot. */
68 std::set<string> segment_list;
69
70 void scandir(const string& path, bool include);
71
72 /* Selection of files to include/exclude in the snapshot. */
73 std::list<string> includes;         // Paths in which files should be saved
74 std::list<string> excludes;         // Paths which will not be saved
75 std::list<string> searches;         // Directories we don't want to save, but
76                                     //   do want to descend searching for data
77                                     //   in included paths
78
79 bool relative_paths = true;
80
81 /* Ensure contents of metadata are flushed to an object. */
82 void metadata_flush()
83 {
84     string m = metadata.str();
85     if (m.size() == 0)
86         return;
87
88     /* Write current metadata information to a new object. */
89     LbsObject *meta = new LbsObject;
90     meta->set_group("metadata");
91     meta->set_data(m.data(), m.size());
92     meta->write(tss);
93     meta->checksum();
94
95     /* Write a reference to this block in the root. */
96     ObjectReference ref = meta->get_ref();
97     metadata_root << "@" << ref.to_string() << "\n";
98     segment_list.insert(ref.get_segment());
99
100     delete meta;
101
102     metadata.str("");
103 }
104
105 /* Read data from a file descriptor and return the amount of data read.  A
106  * short read (less than the requested size) will only occur if end-of-file is
107  * hit. */
108 size_t file_read(int fd, char *buf, size_t maxlen)
109 {
110     size_t bytes_read = 0;
111
112     while (true) {
113         ssize_t res = read(fd, buf, maxlen);
114         if (res < 0) {
115             if (errno == EINTR)
116                 continue;
117             throw IOException("file_read: error reading");
118         } else if (res == 0) {
119             break;
120         } else {
121             bytes_read += res;
122             buf += res;
123             maxlen -= res;
124         }
125     }
126
127     return bytes_read;
128 }
129
130 /* Read the contents of a file (specified by an open file descriptor) and copy
131  * the data to the store.  Returns the size of the file (number of bytes
132  * dumped), or -1 on error. */
133 int64_t dumpfile(int fd, dictionary &file_info, const string &path)
134 {
135     struct stat stat_buf;
136     fstat(fd, &stat_buf);
137     int64_t size = 0;
138     list<string> object_list;
139
140     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
141         fprintf(stderr, "file is no longer a regular file!\n");
142         return -1;
143     }
144
145     /* Look up this file in the old stat cache, if we can.  If the stat
146      * information indicates that the file has not changed, do not bother
147      * re-reading the entire contents. */
148     bool cached = false;
149
150     if (statcache->Find(path, &stat_buf)) {
151         cached = true;
152         const list<ObjectReference> &blocks = statcache->get_blocks();
153
154         /* If any of the blocks in the object have been expired, then we should
155          * fall back to fully reading in the file. */
156         for (list<ObjectReference>::const_iterator i = blocks.begin();
157              i != blocks.end(); ++i) {
158             const ObjectReference &ref = *i;
159             if (!db->IsAvailable(ref)) {
160                 cached = false;
161                 break;
162             }
163         }
164
165         /* If everything looks okay, use the cached information */
166         if (cached) {
167             file_info["checksum"] = statcache->get_checksum();
168             for (list<ObjectReference>::const_iterator i = blocks.begin();
169                  i != blocks.end(); ++i) {
170                 const ObjectReference &ref = *i;
171                 object_list.push_back(ref.to_string());
172                 segment_list.insert(ref.get_segment());
173                 db->UseObject(ref);
174             }
175             size = stat_buf.st_size;
176         }
177     }
178
179     /* If the file is new or changed, we must read in the contents a block at a
180      * time. */
181     if (!cached) {
182         printf("    [new]\n");
183
184         SHA1Checksum hash;
185         while (true) {
186             size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
187             if (bytes == 0)
188                 break;
189
190             hash.process(block_buf, bytes);
191
192             // Either find a copy of this block in an already-existing segment,
193             // or index it so it can be re-used in the future
194             double block_age = 0.0;
195             SHA1Checksum block_hash;
196             block_hash.process(block_buf, bytes);
197             string block_csum = block_hash.checksum_str();
198             ObjectReference ref = db->FindObject(block_csum, bytes);
199
200             // Store a copy of the object if one does not yet exist
201             if (ref.get_segment().size() == 0) {
202                 LbsObject *o = new LbsObject;
203
204                 /* We might still have seen this checksum before, if the object
205                  * was stored at some time in the past, but we have decided to
206                  * clean the segment the object was originally stored in
207                  * (FindObject will not return such objects).  When rewriting
208                  * the object contents, put it in a separate group, so that old
209                  * objects get grouped together.  The hope is that these old
210                  * objects will continue to be used in the future, and we
211                  * obtain segments which will continue to be well-utilized.
212                  * Additionally, keep track of the age of the data by looking
213                  * up the age of the block which was expired and using that
214                  * instead of the current time. */
215                 if (db->IsOldObject(block_csum, bytes, &block_age))
216                     o->set_group("compacted");
217                 else
218                     o->set_group("data");
219
220                 o->set_data(block_buf, bytes);
221                 o->write(tss);
222                 ref = o->get_ref();
223                 db->StoreObject(ref, block_csum, bytes, block_age);
224                 delete o;
225             }
226
227             object_list.push_back(ref.to_string());
228             segment_list.insert(ref.get_segment());
229             db->UseObject(ref);
230             size += bytes;
231         }
232
233         file_info["checksum"] = hash.checksum_str();
234     }
235
236     statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
237
238     /* For files that only need to be broken apart into a few objects, store
239      * the list of objects directly.  For larger files, store the data
240      * out-of-line and provide a pointer to the indrect object. */
241     if (object_list.size() < 8) {
242         string blocklist = "";
243         for (list<string>::iterator i = object_list.begin();
244              i != object_list.end(); ++i) {
245             if (i != object_list.begin())
246                 blocklist += " ";
247             blocklist += *i;
248         }
249         file_info["data"] = blocklist;
250     } else {
251         string blocklist = "";
252         for (list<string>::iterator i = object_list.begin();
253              i != object_list.end(); ++i) {
254             blocklist += *i + "\n";
255         }
256
257         LbsObject *i = new LbsObject;
258         i->set_group("metadata");
259         i->set_data(blocklist.data(), blocklist.size());
260         i->write(tss);
261         file_info["data"] = "@" + i->get_name();
262         segment_list.insert(i->get_ref().get_segment());
263         delete i;
264     }
265
266     return size;
267 }
268
269 void scanfile(const string& path, bool include)
270 {
271     int fd;
272     long flags;
273     struct stat stat_buf;
274     char *buf;
275     ssize_t len;
276     int64_t file_size;
277     list<string> refs;
278
279     string true_path;
280     if (relative_paths)
281         true_path = path;
282     else
283         true_path = "/" + path;
284
285     // Set to true if the item is a directory and we should recursively scan
286     bool recurse = false;
287
288     // Set to true if we should scan through the contents of this directory,
289     // but not actually back files up
290     bool scan_only = false;
291
292     // Check this file against the include/exclude list to see if it should be
293     // considered
294     for (list<string>::iterator i = includes.begin();
295          i != includes.end(); ++i) {
296         if (path == *i) {
297             printf("Including %s\n", path.c_str());
298             include = true;
299         }
300     }
301
302     for (list<string>::iterator i = excludes.begin();
303          i != excludes.end(); ++i) {
304         if (path == *i) {
305             printf("Excluding %s\n", path.c_str());
306             include = false;
307         }
308     }
309
310     for (list<string>::iterator i = searches.begin();
311          i != searches.end(); ++i) {
312         if (path == *i) {
313             printf("Scanning %s\n", path.c_str());
314             scan_only = true;
315         }
316     }
317
318     if (!include && !scan_only)
319         return;
320
321     dictionary file_info;
322
323     lstat(true_path.c_str(), &stat_buf);
324
325     printf("%s\n", path.c_str());
326
327     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
328     file_info["mtime"] = encode_int(stat_buf.st_mtime);
329     file_info["user"] = encode_int(stat_buf.st_uid);
330     file_info["group"] = encode_int(stat_buf.st_gid);
331
332     struct passwd *pwd = getpwuid(stat_buf.st_uid);
333     if (pwd != NULL) {
334         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
335     }
336
337     struct group *grp = getgrgid(stat_buf.st_gid);
338     if (pwd != NULL) {
339         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
340     }
341
342     char inode_type;
343
344     switch (stat_buf.st_mode & S_IFMT) {
345     case S_IFIFO:
346         inode_type = 'p';
347         break;
348     case S_IFSOCK:
349         inode_type = 's';
350         break;
351     case S_IFCHR:
352         inode_type = 'c';
353         break;
354     case S_IFBLK:
355         inode_type = 'b';
356         break;
357     case S_IFLNK:
358         inode_type = 'l';
359
360         /* Use the reported file size to allocate a buffer large enough to read
361          * the symlink.  Allocate slightly more space, so that we ask for more
362          * bytes than we expect and so check for truncation. */
363         buf = new char[stat_buf.st_size + 2];
364         len = readlink(true_path.c_str(), buf, stat_buf.st_size + 1);
365         if (len < 0) {
366             fprintf(stderr, "error reading symlink: %m\n");
367         } else if (len <= stat_buf.st_size) {
368             buf[len] = '\0';
369             file_info["contents"] = uri_encode(buf);
370         } else if (len > stat_buf.st_size) {
371             fprintf(stderr, "error reading symlink: name truncated\n");
372         }
373
374         delete[] buf;
375         break;
376     case S_IFREG:
377         inode_type = '-';
378
379         /* Be paranoid when opening the file.  We have no guarantee that the
380          * file was not replaced between the stat() call above and the open()
381          * call below, so we might not even be opening a regular file.  That
382          * the file descriptor refers to a regular file is checked in
383          * dumpfile().  But we also supply flags to open to to guard against
384          * various conditions before we can perform that verification:
385          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
386          *   - O_NONBLOCK: prevents open() from blocking if the file was
387          *     replaced by a fifo
388          * We also add in O_NOATIME, since this may reduce disk writes (for
389          * inode updates).  However, O_NOATIME may result in EPERM, so if the
390          * initial open fails, try again without O_NOATIME.  */
391         fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
392         if (fd < 0) {
393             fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
394         }
395         if (fd < 0) {
396             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
397             return;
398         }
399
400         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
401          * open. */
402         flags = fcntl(fd, F_GETFL);
403         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
404
405         file_size = dumpfile(fd, file_info, path);
406         file_info["size"] = encode_int(file_size);
407         close(fd);
408
409         if (file_size < 0)
410             return;             // error occurred; do not dump file
411
412         if (file_size != stat_buf.st_size) {
413             fprintf(stderr, "Warning: Size of %s changed during reading\n",
414                     path.c_str());
415         }
416
417         break;
418     case S_IFDIR:
419         inode_type = 'd';
420         recurse = true;
421         break;
422
423     default:
424         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
425         return;
426     }
427
428     file_info["type"] = string(1, inode_type);
429
430     metadata << "name: " << uri_encode(path) << "\n";
431     dict_output(metadata, file_info);
432     metadata << "\n";
433
434     // Break apart metadata listing if it becomes too large.
435     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
436         metadata_flush();
437
438     // If we hit a directory, now that we've written the directory itself,
439     // recursively scan the directory.
440     if (recurse)
441         scandir(path, include);
442 }
443
444 void scandir(const string& path, bool include)
445 {
446     string true_path;
447     if (relative_paths)
448         true_path = path;
449     else
450         true_path = "/" + path;
451
452     DIR *dir = opendir(true_path.c_str());
453
454     if (dir == NULL) {
455         fprintf(stderr, "Error: %m\n");
456         return;
457     }
458
459     struct dirent *ent;
460     vector<string> contents;
461     while ((ent = readdir(dir)) != NULL) {
462         string filename(ent->d_name);
463         if (filename == "." || filename == "..")
464             continue;
465         contents.push_back(filename);
466     }
467
468     sort(contents.begin(), contents.end());
469
470     for (vector<string>::iterator i = contents.begin();
471          i != contents.end(); ++i) {
472         const string& filename = *i;
473         if (path == ".")
474             scanfile(filename, include);
475         else
476             scanfile(path + "/" + filename, include);
477     }
478
479     closedir(dir);
480 }
481
482 /* Include the specified file path in the backups.  Append the path to the
483  * includes list, and to ensure that we actually see the path when scanning the
484  * directory tree, add all the parent directories to the search list, which
485  * means we will scan through the directory listing even if the files
486  * themselves are excluded from being backed up. */
487 void add_include(const char *path)
488 {
489     printf("Add: %s\n", path);
490     /* Was an absolute path specified?  If so, we'll need to start scanning
491      * from the root directory.  Make sure that the user was consistent in
492      * providing either all relative paths or all absolute paths. */
493     if (path[0] == '/') {
494         if (includes.size() > 0 && relative_paths == true) {
495             fprintf(stderr,
496                     "Error: Cannot mix relative and absolute paths!\n");
497             exit(1);
498         }
499
500         relative_paths = false;
501
502         // Skip over leading '/'
503         path++;
504     } else if (relative_paths == false && path[0] != '/') {
505         fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
506         exit(1);
507     }
508
509     includes.push_back(path);
510
511     /* Split the specified path into directory components, and ensure that we
512      * descend into all the directories along the path. */
513     const char *slash = path;
514
515     if (path[0] == '\0')
516         return;
517
518     while ((slash = strchr(slash + 1, '/')) != NULL) {
519         string component(path, slash - path);
520         searches.push_back(component);
521     }
522 }
523
524 void usage(const char *program)
525 {
526     fprintf(
527         stderr,
528         "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
529         "Produce backup snapshot of files in SOURCE and store to DEST.\n"
530         "\n"
531         "Options:\n"
532         "  --dest=PATH          path where backup is to be written [REQUIRED]\n"
533         "  --exclude=PATH       exclude files in PATH from snapshot\n"
534         "  --localdb=PATH       local backup metadata is stored in PATH\n"
535         "  --filter=COMMAND     program through which to filter segment data\n"
536         "                           (defaults to \"bzip2 -c\")\n"
537         "  --filter-extension=EXT\n"
538         "                       string to append to segment files\n"
539         "                           (defaults to \".bz2\")\n",
540         program
541     );
542 }
543
544 int main(int argc, char *argv[])
545 {
546     string backup_source = ".";
547     string backup_dest = "";
548     string localdb_dir = "";
549
550     while (1) {
551         static struct option long_options[] = {
552             {"localdb", 1, 0, 0},           // 0
553             {"exclude", 1, 0, 0},           // 1
554             {"filter", 1, 0, 0},            // 2
555             {"filter-extension", 1, 0, 0},  // 3
556             {"dest", 1, 0, 0},              // 4
557             {NULL, 0, 0, 0},
558         };
559
560         int long_index;
561         int c = getopt_long(argc, argv, "", long_options, &long_index);
562
563         if (c == -1)
564             break;
565
566         if (c == 0) {
567             switch (long_index) {
568             case 0:     // --localdb
569                 localdb_dir = optarg;
570                 break;
571             case 1:     // --exclude
572                 if (optarg[0] != '/')
573                     excludes.push_back(optarg);
574                 else
575                     excludes.push_back(optarg + 1);
576                 break;
577             case 2:     // --filter
578                 filter_program = optarg;
579                 break;
580             case 3:     // --filter-extension
581                 filter_extension = optarg;
582                 break;
583             case 4:     // --dest
584                 backup_dest = optarg;
585                 break;
586             default:
587                 fprintf(stderr, "Unhandled long option!\n");
588                 return 1;
589             }
590         } else {
591             usage(argv[0]);
592             return 1;
593         }
594     }
595
596     if (argc < optind + 2) {
597         usage(argv[0]);
598         return 1;
599     }
600
601     searches.push_back(".");
602     if (optind == argc) {
603         add_include(".");
604     } else {
605         for (int i = optind; i < argc; i++)
606             add_include(argv[i]);
607     }
608
609     backup_source = argv[optind];
610
611     if (backup_dest == "") {
612         fprintf(stderr,
613                 "Error: Backup destination must be specified with --dest=\n");
614         usage(argv[0]);
615         return 1;
616     }
617
618     // Default for --localdb is the same as --dest
619     if (localdb_dir == "") {
620         localdb_dir = backup_dest;
621     }
622
623     // Dump paths for debugging/informational purposes
624     {
625         list<string>::const_iterator i;
626
627         printf("LBS Version: %s\n", lbs_version);
628
629         printf("--dest=%s\n--localdb=%s\n\n",
630                backup_dest.c_str(), localdb_dir.c_str());
631
632         printf("Includes:\n");
633         for (i = includes.begin(); i != includes.end(); ++i)
634             printf("    %s\n", i->c_str());
635
636         printf("Excludes:\n");
637         for (i = excludes.begin(); i != excludes.end(); ++i)
638             printf("    %s\n", i->c_str());
639
640         printf("Searching:\n");
641         for (i = searches.begin(); i != searches.end(); ++i)
642             printf("    %s\n", i->c_str());
643     }
644
645     tss = new TarSegmentStore(backup_dest);
646     block_buf = new char[LBS_BLOCK_SIZE];
647
648     /* Store the time when the backup started, so it can be included in the
649      * snapshot name. */
650     time_t now;
651     struct tm time_buf;
652     char desc_buf[256];
653     time(&now);
654     localtime_r(&now, &time_buf);
655     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
656
657     /* Open the local database which tracks all objects that are stored
658      * remotely, for efficient incrementals.  Provide it with the name of this
659      * snapshot. */
660     string database_path = localdb_dir + "/localdb.sqlite";
661     db = new LocalDb;
662     db->Open(database_path.c_str(), desc_buf);
663
664     /* Initialize the stat cache, for skipping over unchanged files. */
665     statcache = new StatCache;
666     statcache->Open(localdb_dir.c_str(), desc_buf);
667
668     scanfile(".", false);
669
670     metadata_flush();
671     const string md = metadata_root.str();
672
673     LbsObject *root = new LbsObject;
674     root->set_group("metadata");
675     root->set_data(md.data(), md.size());
676     root->write(tss);
677     root->checksum();
678     segment_list.insert(root->get_ref().get_segment());
679
680     string backup_root = root->get_ref().to_string();
681     delete root;
682
683     db->Close();
684
685     statcache->Close();
686     delete statcache;
687
688     tss->sync();
689     tss->dump_stats();
690     delete tss;
691
692     /* Write a backup descriptor file, which says which segments are needed and
693      * where to start to restore this snapshot.  The filename is based on the
694      * current time. */
695     string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
696     std::ofstream descriptor(desc_filename.c_str());
697
698     descriptor << "Format: LBS Snapshot v0.1\n";
699     descriptor << "Producer: " << lbs_version << "\n";
700     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
701     descriptor << "Date: " << desc_buf << "\n";
702     descriptor << "Root: " << backup_root << "\n";
703
704     descriptor << "Segments:\n";
705     for (std::set<string>::iterator i = segment_list.begin();
706          i != segment_list.end(); ++i) {
707         descriptor << "    " << *i << "\n";
708     }
709
710     return 0;
711 }