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