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