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