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