1 /* Recursively descend the filesystem and visit each file. */
13 #include <sys/sysmacros.h>
14 #include <sys/types.h>
38 /* Version information. This will be filled in by the Makefile. */
40 #define LBS_VERSION Unknown
42 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
43 #define LBS_STRINGIFY2(s) #s
44 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
46 static TarSegmentStore *tss = NULL;
47 static MetadataWriter *metawriter = NULL;
49 /* Buffer for holding a single block of data read from a file. */
50 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
51 static char *block_buf;
53 /* Local database, which tracks objects written in this and previous
54 * invocations to help in creating incremental snapshots. */
57 /* Keep track of all segments which are needed to reconstruct the snapshot. */
58 std::set<string> segment_list;
60 /* Snapshot intent: 1=daily, 7=weekly, etc. This is not used directly, but is
61 * stored in the local database and can help guide segment cleaning and
62 * snapshot expiration policies. */
63 double snapshot_intent = 1.0;
65 /* Selection of files to include/exclude in the snapshot. */
66 std::list<string> includes; // Paths in which files should be saved
67 std::list<string> excludes; // Paths which will not be saved
68 std::list<string> searches; // Directories we don't want to save, but
69 // do want to descend searching for data
72 bool relative_paths = true;
74 /* Ensure that the given segment is listed as a dependency of the current
76 void add_segment(const string& segment)
78 segment_list.insert(segment);
81 /* Read data from a file descriptor and return the amount of data read. A
82 * short read (less than the requested size) will only occur if end-of-file is
84 ssize_t file_read(int fd, char *buf, size_t maxlen)
86 size_t bytes_read = 0;
89 ssize_t res = read(fd, buf, maxlen);
93 fprintf(stderr, "error reading file: %m\n");
95 } else if (res == 0) {
107 /* Read the contents of a file (specified by an open file descriptor) and copy
108 * the data to the store. Returns the size of the file (number of bytes
109 * dumped), or -1 on error. */
110 int64_t dumpfile(int fd, dictionary &file_info, const string &path,
111 struct stat& stat_buf)
114 list<string> object_list;
115 const char *status = NULL; /* Status indicator printed out */
117 /* Look up this file in the old stat cache, if we can. If the stat
118 * information indicates that the file has not changed, do not bother
119 * re-reading the entire contents. */
122 if (metawriter->find(path) && metawriter->is_unchanged(&stat_buf)) {
124 list<ObjectReference> blocks = metawriter->get_blocks();
126 /* If any of the blocks in the object have been expired, then we should
127 * fall back to fully reading in the file. */
128 for (list<ObjectReference>::const_iterator i = blocks.begin();
129 i != blocks.end(); ++i) {
130 const ObjectReference &ref = *i;
131 if (!db->IsAvailable(ref)) {
138 /* If everything looks okay, use the cached information */
140 file_info["checksum"] = metawriter->get_checksum();
141 for (list<ObjectReference>::const_iterator i = blocks.begin();
142 i != blocks.end(); ++i) {
143 const ObjectReference &ref = *i;
144 object_list.push_back(ref.to_string());
146 add_segment(ref.get_segment());
149 size = stat_buf.st_size;
153 /* If the file is new or changed, we must read in the contents a block at a
158 ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
162 fprintf(stderr, "Backup contents for %s may be incorrect\n",
167 hash.process(block_buf, bytes);
169 // Sparse file processing: if we read a block of all zeroes, encode
171 bool all_zero = true;
172 for (int i = 0; i < bytes; i++) {
173 if (block_buf[i] != 0) {
179 // Either find a copy of this block in an already-existing segment,
180 // or index it so it can be re-used in the future
181 double block_age = 0.0;
184 SHA1Checksum block_hash;
185 block_hash.process(block_buf, bytes);
186 string block_csum = block_hash.checksum_str();
189 ref = ObjectReference(ObjectReference::REF_ZERO);
190 ref.set_range(0, bytes);
192 ref = db->FindObject(block_csum, bytes);
195 // Store a copy of the object if one does not yet exist
197 LbsObject *o = new LbsObject;
200 /* We might still have seen this checksum before, if the object
201 * was stored at some time in the past, but we have decided to
202 * clean the segment the object was originally stored in
203 * (FindObject will not return such objects). When rewriting
204 * the object contents, put it in a separate group, so that old
205 * objects get grouped together. The hope is that these old
206 * objects will continue to be used in the future, and we
207 * obtain segments which will continue to be well-utilized.
208 * Additionally, keep track of the age of the data by looking
209 * up the age of the block which was expired and using that
210 * instead of the current time. */
211 if (db->IsOldObject(block_csum, bytes,
212 &block_age, &object_group)) {
213 if (object_group == 0) {
214 o->set_group("data");
217 sprintf(group, "compacted-%d", object_group);
223 o->set_group("data");
227 o->set_data(block_buf, bytes);
230 db->StoreObject(ref, block_csum, bytes, block_age);
231 ref.set_range(0, bytes);
235 object_list.push_back(ref.to_string());
237 add_segment(ref.get_segment());
245 file_info["checksum"] = hash.checksum_str();
249 printf(" [%s]\n", status);
251 string blocklist = "";
252 for (list<string>::iterator i = object_list.begin();
253 i != object_list.end(); ++i) {
254 if (i != object_list.begin())
258 file_info["data"] = blocklist;
263 /* Dump a specified filesystem object (file, directory, etc.) based on its
264 * inode information. If the object is a regular file, an open filehandle is
266 void dump_inode(const string& path, // Path within snapshot
267 const string& fullpath, // Path to object in filesystem
268 struct stat& stat_buf, // Results of stat() call
269 int fd) // Open filehandle if regular file
272 dictionary file_info;
276 printf("%s\n", path.c_str());
277 metawriter->find(path);
279 file_info["name"] = uri_encode(path);
280 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
281 file_info["ctime"] = encode_int(stat_buf.st_ctime);
282 file_info["mtime"] = encode_int(stat_buf.st_mtime);
283 file_info["user"] = encode_int(stat_buf.st_uid);
284 file_info["group"] = encode_int(stat_buf.st_gid);
286 time_t now = time(NULL);
287 if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
288 if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
289 file_info["volatile"] = "1";
291 struct passwd *pwd = getpwuid(stat_buf.st_uid);
293 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
296 struct group *grp = getgrgid(stat_buf.st_gid);
298 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
301 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
302 file_info["links"] = encode_int(stat_buf.st_nlink);
305 file_info["inode"] = encode_int(major(stat_buf.st_dev))
306 + "/" + encode_int(minor(stat_buf.st_dev))
307 + "/" + encode_int(stat_buf.st_ino);
311 switch (stat_buf.st_mode & S_IFMT) {
320 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
321 file_info["device"] = encode_int(major(stat_buf.st_rdev))
322 + "/" + encode_int(minor(stat_buf.st_rdev));
327 /* Use the reported file size to allocate a buffer large enough to read
328 * the symlink. Allocate slightly more space, so that we ask for more
329 * bytes than we expect and so check for truncation. */
330 buf = new char[stat_buf.st_size + 2];
331 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
333 fprintf(stderr, "error reading symlink: %m\n");
334 } else if (len <= stat_buf.st_size) {
336 file_info["target"] = uri_encode(buf);
337 } else if (len > stat_buf.st_size) {
338 fprintf(stderr, "error reading symlink: name truncated\n");
346 file_size = dumpfile(fd, file_info, path, stat_buf);
347 file_info["size"] = encode_int(file_size);
350 return; // error occurred; do not dump file
352 if (file_size != stat_buf.st_size) {
353 fprintf(stderr, "Warning: Size of %s changed during reading\n",
355 file_info["volatile"] = "1";
364 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
368 file_info["type"] = string(1, inode_type);
370 metawriter->add(file_info);
373 void scanfile(const string& path, bool include)
377 struct stat stat_buf;
384 true_path = "/" + path;
386 // Set to true if we should scan through the contents of this directory,
387 // but not actually back files up
388 bool scan_only = false;
390 // Check this file against the include/exclude list to see if it should be
392 for (list<string>::iterator i = includes.begin();
393 i != includes.end(); ++i) {
395 printf("Including %s\n", path.c_str());
400 for (list<string>::iterator i = excludes.begin();
401 i != excludes.end(); ++i) {
403 printf("Excluding %s\n", path.c_str());
408 for (list<string>::iterator i = searches.begin();
409 i != searches.end(); ++i) {
411 printf("Scanning %s\n", path.c_str());
416 if (!include && !scan_only)
419 if (lstat(true_path.c_str(), &stat_buf) < 0) {
420 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
424 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
425 /* Be paranoid when opening the file. We have no guarantee that the
426 * file was not replaced between the stat() call above and the open()
427 * call below, so we might not even be opening a regular file. We
428 * supply flags to open to to guard against various conditions before
429 * we can perform an lstat to check that the file is still a regular
431 * - O_NOFOLLOW: in the event the file was replaced by a symlink
432 * - O_NONBLOCK: prevents open() from blocking if the file was
434 * We also add in O_NOATIME, since this may reduce disk writes (for
435 * inode updates). However, O_NOATIME may result in EPERM, so if the
436 * initial open fails, try again without O_NOATIME. */
437 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
439 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
442 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
446 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
448 flags = fcntl(fd, F_GETFL);
449 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
451 /* Perform the stat call again, and check that we still have a regular
453 if (fstat(fd, &stat_buf) < 0) {
454 fprintf(stderr, "fstat: %m\n");
459 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
460 fprintf(stderr, "file is no longer a regular file!\n");
466 dump_inode(path, true_path, stat_buf, fd);
471 // If we hit a directory, now that we've written the directory itself,
472 // recursively scan the directory.
473 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
474 DIR *dir = opendir(true_path.c_str());
477 fprintf(stderr, "Error: %m\n");
482 vector<string> contents;
483 while ((ent = readdir(dir)) != NULL) {
484 string filename(ent->d_name);
485 if (filename == "." || filename == "..")
487 contents.push_back(filename);
492 sort(contents.begin(), contents.end());
494 for (vector<string>::iterator i = contents.begin();
495 i != contents.end(); ++i) {
496 const string& filename = *i;
498 scanfile(filename, include);
500 scanfile(path + "/" + filename, include);
505 /* Include the specified file path in the backups. Append the path to the
506 * includes list, and to ensure that we actually see the path when scanning the
507 * directory tree, add all the parent directories to the search list, which
508 * means we will scan through the directory listing even if the files
509 * themselves are excluded from being backed up. */
510 void add_include(const char *path)
512 printf("Add: %s\n", path);
513 /* Was an absolute path specified? If so, we'll need to start scanning
514 * from the root directory. Make sure that the user was consistent in
515 * providing either all relative paths or all absolute paths. */
516 if (path[0] == '/') {
517 if (includes.size() > 0 && relative_paths == true) {
519 "Error: Cannot mix relative and absolute paths!\n");
523 relative_paths = false;
525 // Skip over leading '/'
527 } else if (relative_paths == false && path[0] != '/') {
528 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
532 includes.push_back(path);
534 /* Split the specified path into directory components, and ensure that we
535 * descend into all the directories along the path. */
536 const char *slash = path;
541 while ((slash = strchr(slash + 1, '/')) != NULL) {
542 string component(path, slash - path);
543 searches.push_back(component);
547 void usage(const char *program)
552 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
553 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
556 " --dest=PATH path where backup is to be written [REQUIRED]\n"
557 " --exclude=PATH exclude files in PATH from snapshot\n"
558 " --localdb=PATH local backup metadata is stored in PATH\n"
559 " --filter=COMMAND program through which to filter segment data\n"
560 " (defaults to \"bzip2 -c\")\n"
561 " --filter-extension=EXT\n"
562 " string to append to segment files\n"
563 " (defaults to \".bz2\")\n"
564 " --signature-filter=COMMAND\n"
565 " program though which to filter descriptor\n"
566 " --scheme=NAME optional name for this snapshot\n"
567 " --intent=FLOAT intended backup type: 1=daily, 7=weekly, ...\n"
568 " (defaults to \"1\")\n",
573 int main(int argc, char *argv[])
575 string backup_dest = "";
576 string localdb_dir = "";
577 string backup_scheme = "";
578 string signature_filter = "";
581 static struct option long_options[] = {
582 {"localdb", 1, 0, 0}, // 0
583 {"exclude", 1, 0, 0}, // 1
584 {"filter", 1, 0, 0}, // 2
585 {"filter-extension", 1, 0, 0}, // 3
586 {"dest", 1, 0, 0}, // 4
587 {"scheme", 1, 0, 0}, // 5
588 {"signature-filter", 1, 0, 0}, // 6
589 {"intent", 1, 0, 0}, // 7
594 int c = getopt_long(argc, argv, "", long_options, &long_index);
600 switch (long_index) {
602 localdb_dir = optarg;
605 if (optarg[0] != '/')
606 excludes.push_back(optarg);
608 excludes.push_back(optarg + 1);
611 filter_program = optarg;
613 case 3: // --filter-extension
614 filter_extension = optarg;
617 backup_dest = optarg;
620 backup_scheme = optarg;
622 case 6: // --signature-filter
623 signature_filter = optarg;
626 snapshot_intent = atof(optarg);
627 if (snapshot_intent <= 0)
631 fprintf(stderr, "Unhandled long option!\n");
640 if (optind == argc) {
645 searches.push_back(".");
646 for (int i = optind; i < argc; i++)
647 add_include(argv[i]);
649 if (backup_dest == "") {
651 "Error: Backup destination must be specified with --dest=\n");
656 // Default for --localdb is the same as --dest
657 if (localdb_dir == "") {
658 localdb_dir = backup_dest;
661 // Dump paths for debugging/informational purposes
663 list<string>::const_iterator i;
665 printf("LBS Version: %s\n", lbs_version);
667 printf("--dest=%s\n--localdb=%s\n\n",
668 backup_dest.c_str(), localdb_dir.c_str());
670 printf("Includes:\n");
671 for (i = includes.begin(); i != includes.end(); ++i)
672 printf(" %s\n", i->c_str());
674 printf("Excludes:\n");
675 for (i = excludes.begin(); i != excludes.end(); ++i)
676 printf(" %s\n", i->c_str());
678 printf("Searching:\n");
679 for (i = searches.begin(); i != searches.end(); ++i)
680 printf(" %s\n", i->c_str());
683 block_buf = new char[LBS_BLOCK_SIZE];
685 /* Store the time when the backup started, so it can be included in the
691 localtime_r(&now, &time_buf);
692 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
694 /* Open the local database which tracks all objects that are stored
695 * remotely, for efficient incrementals. Provide it with the name of this
697 string database_path = localdb_dir + "/localdb.sqlite";
699 db->Open(database_path.c_str(), desc_buf,
700 backup_scheme.size() ? backup_scheme.c_str() : NULL,
703 tss = new TarSegmentStore(backup_dest, db);
705 /* Initialize the stat cache, for skipping over unchanged files. */
706 metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
708 ? backup_scheme.c_str()
711 scanfile(".", false);
713 ObjectReference root_ref = metawriter->close();
714 add_segment(root_ref.get_segment());
715 string backup_root = root_ref.to_string();
723 /* Write out a checksums file which lists the checksums for all the
724 * segments included in this snapshot. The format is designed so that it
725 * may be easily verified using the sha1sums command. */
726 const char csum_type[] = "sha1";
727 string checksum_filename = backup_dest + "/snapshot-";
728 if (backup_scheme.size() > 0)
729 checksum_filename += backup_scheme + "-";
730 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
731 FILE *checksums = fopen(checksum_filename.c_str(), "w");
732 if (checksums != NULL) {
733 for (std::set<string>::iterator i = segment_list.begin();
734 i != segment_list.end(); ++i) {
735 string seg_path, seg_csum;
736 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
737 const char *raw_checksum = NULL;
738 if (strncmp(seg_csum.c_str(), csum_type,
739 strlen(csum_type)) == 0) {
740 raw_checksum = seg_csum.c_str() + strlen(csum_type);
741 if (*raw_checksum == '=')
747 if (raw_checksum != NULL)
748 fprintf(checksums, "%s *%s\n",
749 raw_checksum, seg_path.c_str());
754 fprintf(stderr, "ERROR: Unable to write checksums file: %m\n");
759 /* Write a backup descriptor file, which says which segments are needed and
760 * where to start to restore this snapshot. The filename is based on the
761 * current time. If a signature filter program was specified, filter the
762 * data through that to give a chance to sign the descriptor contents. */
763 string desc_filename = backup_dest + "/snapshot-";
764 if (backup_scheme.size() > 0)
765 desc_filename += backup_scheme + "-";
766 desc_filename = desc_filename + desc_buf + ".lbs";
768 int descriptor_fd = open(desc_filename.c_str(), O_WRONLY | O_CREAT, 0666);
769 if (descriptor_fd < 0) {
770 fprintf(stderr, "Unable to open descriptor output file: %m\n");
773 pid_t signature_pid = 0;
774 if (signature_filter.size() > 0) {
775 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
777 close(descriptor_fd);
778 descriptor_fd = new_fd;
780 FILE *descriptor = fdopen(descriptor_fd, "w");
782 fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
783 fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
784 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
785 fprintf(descriptor, "Date: %s\n", desc_buf);
786 if (backup_scheme.size() > 0)
787 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
788 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
790 SHA1Checksum checksum_csum;
791 if (checksum_csum.process_file(checksum_filename.c_str())) {
792 string csum = checksum_csum.checksum_str();
793 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
796 fprintf(descriptor, "Segments:\n");
797 for (std::set<string>::iterator i = segment_list.begin();
798 i != segment_list.end(); ++i) {
799 fprintf(descriptor, " %s\n", i->c_str());
806 waitpid(signature_pid, &status, 0);
808 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
809 throw IOException("Signature filter process error");