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