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 ObjectReference 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);
234 object_list.push_back(ref.to_string());
236 add_segment(ref.get_segment());
244 file_info["checksum"] = hash.checksum_str();
248 printf(" [%s]\n", status);
250 string blocklist = "";
251 for (list<string>::iterator i = object_list.begin();
252 i != object_list.end(); ++i) {
253 if (i != object_list.begin())
257 file_info["data"] = blocklist;
262 /* Dump a specified filesystem object (file, directory, etc.) based on its
263 * inode information. If the object is a regular file, an open filehandle is
265 void dump_inode(const string& path, // Path within snapshot
266 const string& fullpath, // Path to object in filesystem
267 struct stat& stat_buf, // Results of stat() call
268 int fd) // Open filehandle if regular file
271 dictionary file_info;
275 printf("%s\n", path.c_str());
276 metawriter->find(path);
278 file_info["name"] = uri_encode(path);
279 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
280 file_info["ctime"] = encode_int(stat_buf.st_ctime);
281 file_info["mtime"] = encode_int(stat_buf.st_mtime);
282 file_info["user"] = encode_int(stat_buf.st_uid);
283 file_info["group"] = encode_int(stat_buf.st_gid);
285 time_t now = time(NULL);
286 if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
287 if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
288 file_info["volatile"] = "1";
290 struct passwd *pwd = getpwuid(stat_buf.st_uid);
292 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
295 struct group *grp = getgrgid(stat_buf.st_gid);
297 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
300 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
301 file_info["links"] = encode_int(stat_buf.st_nlink);
304 file_info["inode"] = encode_int(major(stat_buf.st_dev))
305 + "/" + encode_int(minor(stat_buf.st_dev))
306 + "/" + encode_int(stat_buf.st_ino);
310 switch (stat_buf.st_mode & S_IFMT) {
319 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
320 file_info["device"] = encode_int(major(stat_buf.st_rdev))
321 + "/" + encode_int(minor(stat_buf.st_rdev));
326 /* Use the reported file size to allocate a buffer large enough to read
327 * the symlink. Allocate slightly more space, so that we ask for more
328 * bytes than we expect and so check for truncation. */
329 buf = new char[stat_buf.st_size + 2];
330 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
332 fprintf(stderr, "error reading symlink: %m\n");
333 } else if (len <= stat_buf.st_size) {
335 file_info["target"] = uri_encode(buf);
336 } else if (len > stat_buf.st_size) {
337 fprintf(stderr, "error reading symlink: name truncated\n");
345 file_size = dumpfile(fd, file_info, path, stat_buf);
346 file_info["size"] = encode_int(file_size);
349 return; // error occurred; do not dump file
351 if (file_size != stat_buf.st_size) {
352 fprintf(stderr, "Warning: Size of %s changed during reading\n",
354 file_info["volatile"] = "1";
363 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
367 file_info["type"] = string(1, inode_type);
369 metawriter->add(file_info);
372 void scanfile(const string& path, bool include)
376 struct stat stat_buf;
383 true_path = "/" + path;
385 // Set to true if we should scan through the contents of this directory,
386 // but not actually back files up
387 bool scan_only = false;
389 // Check this file against the include/exclude list to see if it should be
391 for (list<string>::iterator i = includes.begin();
392 i != includes.end(); ++i) {
394 printf("Including %s\n", path.c_str());
399 for (list<string>::iterator i = excludes.begin();
400 i != excludes.end(); ++i) {
402 printf("Excluding %s\n", path.c_str());
407 for (list<string>::iterator i = searches.begin();
408 i != searches.end(); ++i) {
410 printf("Scanning %s\n", path.c_str());
415 if (!include && !scan_only)
418 if (lstat(true_path.c_str(), &stat_buf) < 0) {
419 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
423 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
424 /* Be paranoid when opening the file. We have no guarantee that the
425 * file was not replaced between the stat() call above and the open()
426 * call below, so we might not even be opening a regular file. We
427 * supply flags to open to to guard against various conditions before
428 * we can perform an lstat to check that the file is still a regular
430 * - O_NOFOLLOW: in the event the file was replaced by a symlink
431 * - O_NONBLOCK: prevents open() from blocking if the file was
433 * We also add in O_NOATIME, since this may reduce disk writes (for
434 * inode updates). However, O_NOATIME may result in EPERM, so if the
435 * initial open fails, try again without O_NOATIME. */
436 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
438 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
441 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
445 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
447 flags = fcntl(fd, F_GETFL);
448 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
450 /* Perform the stat call again, and check that we still have a regular
452 if (fstat(fd, &stat_buf) < 0) {
453 fprintf(stderr, "fstat: %m\n");
458 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
459 fprintf(stderr, "file is no longer a regular file!\n");
465 dump_inode(path, true_path, stat_buf, fd);
470 // If we hit a directory, now that we've written the directory itself,
471 // recursively scan the directory.
472 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
473 DIR *dir = opendir(true_path.c_str());
476 fprintf(stderr, "Error: %m\n");
481 vector<string> contents;
482 while ((ent = readdir(dir)) != NULL) {
483 string filename(ent->d_name);
484 if (filename == "." || filename == "..")
486 contents.push_back(filename);
491 sort(contents.begin(), contents.end());
493 for (vector<string>::iterator i = contents.begin();
494 i != contents.end(); ++i) {
495 const string& filename = *i;
497 scanfile(filename, include);
499 scanfile(path + "/" + filename, include);
504 /* Include the specified file path in the backups. Append the path to the
505 * includes list, and to ensure that we actually see the path when scanning the
506 * directory tree, add all the parent directories to the search list, which
507 * means we will scan through the directory listing even if the files
508 * themselves are excluded from being backed up. */
509 void add_include(const char *path)
511 printf("Add: %s\n", path);
512 /* Was an absolute path specified? If so, we'll need to start scanning
513 * from the root directory. Make sure that the user was consistent in
514 * providing either all relative paths or all absolute paths. */
515 if (path[0] == '/') {
516 if (includes.size() > 0 && relative_paths == true) {
518 "Error: Cannot mix relative and absolute paths!\n");
522 relative_paths = false;
524 // Skip over leading '/'
526 } else if (relative_paths == false && path[0] != '/') {
527 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
531 includes.push_back(path);
533 /* Split the specified path into directory components, and ensure that we
534 * descend into all the directories along the path. */
535 const char *slash = path;
540 while ((slash = strchr(slash + 1, '/')) != NULL) {
541 string component(path, slash - path);
542 searches.push_back(component);
546 void usage(const char *program)
551 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
552 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
555 " --dest=PATH path where backup is to be written [REQUIRED]\n"
556 " --exclude=PATH exclude files in PATH from snapshot\n"
557 " --localdb=PATH local backup metadata is stored in PATH\n"
558 " --filter=COMMAND program through which to filter segment data\n"
559 " (defaults to \"bzip2 -c\")\n"
560 " --filter-extension=EXT\n"
561 " string to append to segment files\n"
562 " (defaults to \".bz2\")\n"
563 " --signature-filter=COMMAND\n"
564 " program though which to filter descriptor\n"
565 " --scheme=NAME optional name for this snapshot\n"
566 " --intent=FLOAT intended backup type: 1=daily, 7=weekly, ...\n"
567 " (defaults to \"1\")\n",
572 int main(int argc, char *argv[])
574 string backup_dest = "";
575 string localdb_dir = "";
576 string backup_scheme = "";
577 string signature_filter = "";
580 static struct option long_options[] = {
581 {"localdb", 1, 0, 0}, // 0
582 {"exclude", 1, 0, 0}, // 1
583 {"filter", 1, 0, 0}, // 2
584 {"filter-extension", 1, 0, 0}, // 3
585 {"dest", 1, 0, 0}, // 4
586 {"scheme", 1, 0, 0}, // 5
587 {"signature-filter", 1, 0, 0}, // 6
588 {"intent", 1, 0, 0}, // 7
593 int c = getopt_long(argc, argv, "", long_options, &long_index);
599 switch (long_index) {
601 localdb_dir = optarg;
604 if (optarg[0] != '/')
605 excludes.push_back(optarg);
607 excludes.push_back(optarg + 1);
610 filter_program = optarg;
612 case 3: // --filter-extension
613 filter_extension = optarg;
616 backup_dest = optarg;
619 backup_scheme = optarg;
621 case 6: // --signature-filter
622 signature_filter = optarg;
625 snapshot_intent = atof(optarg);
626 if (snapshot_intent <= 0)
630 fprintf(stderr, "Unhandled long option!\n");
639 if (optind == argc) {
644 searches.push_back(".");
645 for (int i = optind; i < argc; i++)
646 add_include(argv[i]);
648 if (backup_dest == "") {
650 "Error: Backup destination must be specified with --dest=\n");
655 // Default for --localdb is the same as --dest
656 if (localdb_dir == "") {
657 localdb_dir = backup_dest;
660 // Dump paths for debugging/informational purposes
662 list<string>::const_iterator i;
664 printf("LBS Version: %s\n", lbs_version);
666 printf("--dest=%s\n--localdb=%s\n\n",
667 backup_dest.c_str(), localdb_dir.c_str());
669 printf("Includes:\n");
670 for (i = includes.begin(); i != includes.end(); ++i)
671 printf(" %s\n", i->c_str());
673 printf("Excludes:\n");
674 for (i = excludes.begin(); i != excludes.end(); ++i)
675 printf(" %s\n", i->c_str());
677 printf("Searching:\n");
678 for (i = searches.begin(); i != searches.end(); ++i)
679 printf(" %s\n", i->c_str());
682 block_buf = new char[LBS_BLOCK_SIZE];
684 /* Store the time when the backup started, so it can be included in the
690 localtime_r(&now, &time_buf);
691 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
693 /* Open the local database which tracks all objects that are stored
694 * remotely, for efficient incrementals. Provide it with the name of this
696 string database_path = localdb_dir + "/localdb.sqlite";
698 db->Open(database_path.c_str(), desc_buf,
699 backup_scheme.size() ? backup_scheme.c_str() : NULL,
702 tss = new TarSegmentStore(backup_dest, db);
704 /* Initialize the stat cache, for skipping over unchanged files. */
705 metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
707 ? backup_scheme.c_str()
710 scanfile(".", false);
712 ObjectReference root_ref = metawriter->close();
713 add_segment(root_ref.get_segment());
714 string backup_root = root_ref.to_string();
722 /* Write out a checksums file which lists the checksums for all the
723 * segments included in this snapshot. The format is designed so that it
724 * may be easily verified using the sha1sums command. */
725 const char csum_type[] = "sha1";
726 string checksum_filename = backup_dest + "/snapshot-";
727 if (backup_scheme.size() > 0)
728 checksum_filename += backup_scheme + "-";
729 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
730 FILE *checksums = fopen(checksum_filename.c_str(), "w");
731 if (checksums != NULL) {
732 for (std::set<string>::iterator i = segment_list.begin();
733 i != segment_list.end(); ++i) {
734 string seg_path, seg_csum;
735 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
736 const char *raw_checksum = NULL;
737 if (strncmp(seg_csum.c_str(), csum_type,
738 strlen(csum_type)) == 0) {
739 raw_checksum = seg_csum.c_str() + strlen(csum_type);
740 if (*raw_checksum == '=')
746 if (raw_checksum != NULL)
747 fprintf(checksums, "%s *%s\n",
748 raw_checksum, seg_path.c_str());
753 fprintf(stderr, "ERROR: Unable to write checksums file: %m\n");
758 /* Write a backup descriptor file, which says which segments are needed and
759 * where to start to restore this snapshot. The filename is based on the
760 * current time. If a signature filter program was specified, filter the
761 * data through that to give a chance to sign the descriptor contents. */
762 string desc_filename = backup_dest + "/snapshot-";
763 if (backup_scheme.size() > 0)
764 desc_filename += backup_scheme + "-";
765 desc_filename = desc_filename + desc_buf + ".lbs";
767 int descriptor_fd = open(desc_filename.c_str(), O_WRONLY | O_CREAT, 0666);
768 if (descriptor_fd < 0) {
769 fprintf(stderr, "Unable to open descriptor output file: %m\n");
772 pid_t signature_pid = 0;
773 if (signature_filter.size() > 0) {
774 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
776 close(descriptor_fd);
777 descriptor_fd = new_fd;
779 FILE *descriptor = fdopen(descriptor_fd, "w");
781 fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
782 fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
783 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
784 fprintf(descriptor, "Date: %s\n", desc_buf);
785 if (backup_scheme.size() > 0)
786 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
787 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
789 SHA1Checksum checksum_csum;
790 if (checksum_csum.process_file(checksum_filename.c_str())) {
791 string csum = checksum_csum.checksum_str();
792 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
795 fprintf(descriptor, "Segments:\n");
796 for (std::set<string>::iterator i = segment_list.begin();
797 i != segment_list.end(); ++i) {
798 fprintf(descriptor, " %s\n", i->c_str());
805 waitpid(signature_pid, &status, 0);
807 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
808 throw IOException("Signature filter process error");