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