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