1 /* Recursively descend the filesystem and visit each file. */
13 #include <sys/sysmacros.h>
14 #include <sys/types.h>
30 #include "statcache.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;
48 /* Buffer for holding a single block of data read from a file. */
49 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
50 static char *block_buf;
52 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
54 /* Local database, which tracks objects written in this and previous
55 * invocations to help in creating incremental snapshots. */
58 /* Stat cache, which stored data locally to speed the backup process by quickly
59 * skipping files which have not changed. */
62 /* Contents of the root object. This will contain a set of indirect links to
63 * the metadata objects. */
64 std::ostringstream metadata_root;
66 /* Buffer for building up metadata. */
67 std::ostringstream metadata;
69 /* Keep track of all segments which are needed to reconstruct the snapshot. */
70 std::set<string> segment_list;
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
79 bool relative_paths = true;
81 /* Ensure contents of metadata are flushed to an object. */
84 string m = metadata.str();
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());
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());
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
108 ssize_t file_read(int fd, char *buf, size_t maxlen)
110 size_t bytes_read = 0;
113 ssize_t res = read(fd, buf, maxlen);
117 fprintf(stderr, "error reading file: %m\n");
119 } else if (res == 0) {
131 /* Read the contents of a file (specified by an open file descriptor) and copy
132 * the data to the store. Returns the size of the file (number of bytes
133 * dumped), or -1 on error. */
134 int64_t dumpfile(int fd, dictionary &file_info, const string &path,
135 struct stat& stat_buf)
138 list<string> object_list;
139 const char *status = NULL; /* Status indicator printed out */
141 /* Look up this file in the old stat cache, if we can. If the stat
142 * information indicates that the file has not changed, do not bother
143 * re-reading the entire contents. */
146 if (statcache->Find(path, &stat_buf)) {
148 const list<ObjectReference> &blocks = statcache->get_blocks();
150 /* If any of the blocks in the object have been expired, then we should
151 * fall back to fully reading in the file. */
152 for (list<ObjectReference>::const_iterator i = blocks.begin();
153 i != blocks.end(); ++i) {
154 const ObjectReference &ref = *i;
155 if (!db->IsAvailable(ref)) {
162 /* If everything looks okay, use the cached information */
164 file_info["checksum"] = statcache->get_checksum();
165 for (list<ObjectReference>::const_iterator i = blocks.begin();
166 i != blocks.end(); ++i) {
167 const ObjectReference &ref = *i;
168 object_list.push_back(ref.to_string());
169 segment_list.insert(ref.get_segment());
172 size = stat_buf.st_size;
176 /* If the file is new or changed, we must read in the contents a block at a
181 ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
185 fprintf(stderr, "Backup contents for %s may be incorrect\n",
190 hash.process(block_buf, bytes);
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);
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;
205 /* We might still have seen this checksum before, if the object
206 * was stored at some time in the past, but we have decided to
207 * clean the segment the object was originally stored in
208 * (FindObject will not return such objects). When rewriting
209 * the object contents, put it in a separate group, so that old
210 * objects get grouped together. The hope is that these old
211 * objects will continue to be used in the future, and we
212 * obtain segments which will continue to be well-utilized.
213 * Additionally, keep track of the age of the data by looking
214 * up the age of the block which was expired and using that
215 * instead of the current time. */
216 if (db->IsOldObject(block_csum, bytes,
217 &block_age, &object_group)) {
218 if (object_group == 0) {
219 o->set_group("data");
222 sprintf(group, "compacted-%d", object_group);
228 o->set_group("data");
232 o->set_data(block_buf, bytes);
235 db->StoreObject(ref, block_csum, bytes, block_age);
239 object_list.push_back(ref.to_string());
240 segment_list.insert(ref.get_segment());
248 file_info["checksum"] = hash.checksum_str();
252 printf(" [%s]\n", status);
254 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
256 /* For files that only need to be broken apart into a few objects, store
257 * the list of objects directly. For larger files, store the data
258 * out-of-line and provide a pointer to the indrect object. */
259 if (object_list.size() < 8) {
260 string blocklist = "";
261 for (list<string>::iterator i = object_list.begin();
262 i != object_list.end(); ++i) {
263 if (i != object_list.begin())
267 file_info["data"] = blocklist;
269 string blocklist = "";
270 for (list<string>::iterator i = object_list.begin();
271 i != object_list.end(); ++i) {
272 blocklist += *i + "\n";
275 LbsObject *i = new LbsObject;
276 i->set_group("metadata");
277 i->set_data(blocklist.data(), blocklist.size());
279 file_info["data"] = "@" + i->get_name();
280 segment_list.insert(i->get_ref().get_segment());
287 /* Dump a specified filesystem object (file, directory, etc.) based on its
288 * inode information. If the object is a regular file, an open filehandle is
290 void dump_inode(const string& path, // Path within snapshot
291 const string& fullpath, // Path to object in filesystem
292 struct stat& stat_buf, // Results of stat() call
293 int fd) // Open filehandle if regular file
296 dictionary file_info;
300 printf("%s\n", path.c_str());
302 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
303 file_info["mtime"] = encode_int(stat_buf.st_mtime);
304 file_info["user"] = encode_int(stat_buf.st_uid);
305 file_info["group"] = encode_int(stat_buf.st_gid);
307 struct passwd *pwd = getpwuid(stat_buf.st_uid);
309 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
312 struct group *grp = getgrgid(stat_buf.st_gid);
314 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
317 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
318 file_info["links"] = encode_int(stat_buf.st_nlink);
319 file_info["inode"] = encode_int(major(stat_buf.st_dev))
320 + "/" + encode_int(minor(stat_buf.st_dev))
321 + "/" + encode_int(stat_buf.st_ino);
326 switch (stat_buf.st_mode & S_IFMT) {
335 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
336 file_info["device"] = encode_int(major(stat_buf.st_rdev))
337 + "/" + encode_int(minor(stat_buf.st_rdev));
342 /* Use the reported file size to allocate a buffer large enough to read
343 * the symlink. Allocate slightly more space, so that we ask for more
344 * bytes than we expect and so check for truncation. */
345 buf = new char[stat_buf.st_size + 2];
346 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
348 fprintf(stderr, "error reading symlink: %m\n");
349 } else if (len <= stat_buf.st_size) {
351 file_info["contents"] = uri_encode(buf);
352 } else if (len > stat_buf.st_size) {
353 fprintf(stderr, "error reading symlink: name truncated\n");
361 file_size = dumpfile(fd, file_info, path, stat_buf);
362 file_info["size"] = encode_int(file_size);
365 return; // error occurred; do not dump file
367 if (file_size != stat_buf.st_size) {
368 fprintf(stderr, "Warning: Size of %s changed during reading\n",
378 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
382 file_info["type"] = string(1, inode_type);
384 metadata << "name: " << uri_encode(path) << "\n";
385 dict_output(metadata, file_info);
388 // Break apart metadata listing if it becomes too large.
389 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
393 void scanfile(const string& path, bool include)
397 struct stat stat_buf;
404 true_path = "/" + path;
406 // Set to true if we should scan through the contents of this directory,
407 // but not actually back files up
408 bool scan_only = false;
410 // Check this file against the include/exclude list to see if it should be
412 for (list<string>::iterator i = includes.begin();
413 i != includes.end(); ++i) {
415 printf("Including %s\n", path.c_str());
420 for (list<string>::iterator i = excludes.begin();
421 i != excludes.end(); ++i) {
423 printf("Excluding %s\n", path.c_str());
428 for (list<string>::iterator i = searches.begin();
429 i != searches.end(); ++i) {
431 printf("Scanning %s\n", path.c_str());
436 if (!include && !scan_only)
439 if (lstat(true_path.c_str(), &stat_buf) < 0) {
440 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
444 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
445 /* Be paranoid when opening the file. We have no guarantee that the
446 * file was not replaced between the stat() call above and the open()
447 * call below, so we might not even be opening a regular file. We
448 * supply flags to open to to guard against various conditions before
449 * we can perform an lstat to check that the file is still a regular
451 * - O_NOFOLLOW: in the event the file was replaced by a symlink
452 * - O_NONBLOCK: prevents open() from blocking if the file was
454 * We also add in O_NOATIME, since this may reduce disk writes (for
455 * inode updates). However, O_NOATIME may result in EPERM, so if the
456 * initial open fails, try again without O_NOATIME. */
457 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
459 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
462 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
466 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
468 flags = fcntl(fd, F_GETFL);
469 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
471 /* Perform the stat call again, and check that we still have a regular
473 if (fstat(fd, &stat_buf) < 0) {
474 fprintf(stderr, "fstat: %m\n");
479 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
480 fprintf(stderr, "file is no longer a regular file!\n");
486 dump_inode(path, true_path, stat_buf, fd);
491 // If we hit a directory, now that we've written the directory itself,
492 // recursively scan the directory.
493 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
494 DIR *dir = opendir(true_path.c_str());
497 fprintf(stderr, "Error: %m\n");
502 vector<string> contents;
503 while ((ent = readdir(dir)) != NULL) {
504 string filename(ent->d_name);
505 if (filename == "." || filename == "..")
507 contents.push_back(filename);
512 sort(contents.begin(), contents.end());
514 for (vector<string>::iterator i = contents.begin();
515 i != contents.end(); ++i) {
516 const string& filename = *i;
518 scanfile(filename, include);
520 scanfile(path + "/" + filename, include);
525 /* Include the specified file path in the backups. Append the path to the
526 * includes list, and to ensure that we actually see the path when scanning the
527 * directory tree, add all the parent directories to the search list, which
528 * means we will scan through the directory listing even if the files
529 * themselves are excluded from being backed up. */
530 void add_include(const char *path)
532 printf("Add: %s\n", path);
533 /* Was an absolute path specified? If so, we'll need to start scanning
534 * from the root directory. Make sure that the user was consistent in
535 * providing either all relative paths or all absolute paths. */
536 if (path[0] == '/') {
537 if (includes.size() > 0 && relative_paths == true) {
539 "Error: Cannot mix relative and absolute paths!\n");
543 relative_paths = false;
545 // Skip over leading '/'
547 } else if (relative_paths == false && path[0] != '/') {
548 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
552 includes.push_back(path);
554 /* Split the specified path into directory components, and ensure that we
555 * descend into all the directories along the path. */
556 const char *slash = path;
561 while ((slash = strchr(slash + 1, '/')) != NULL) {
562 string component(path, slash - path);
563 searches.push_back(component);
567 void usage(const char *program)
572 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
573 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
576 " --dest=PATH path where backup is to be written [REQUIRED]\n"
577 " --exclude=PATH exclude files in PATH from snapshot\n"
578 " --localdb=PATH local backup metadata is stored in PATH\n"
579 " --filter=COMMAND program through which to filter segment data\n"
580 " (defaults to \"bzip2 -c\")\n"
581 " --filter-extension=EXT\n"
582 " string to append to segment files\n"
583 " (defaults to \".bz2\")\n"
584 " --signature-filter=COMMAND\n"
585 " program though which to filter descriptor\n"
586 " --scheme=NAME optional name for this snapshot\n",
591 int main(int argc, char *argv[])
593 string backup_dest = "";
594 string localdb_dir = "";
595 string backup_scheme = "";
596 string signature_filter = "";
599 static struct option long_options[] = {
600 {"localdb", 1, 0, 0}, // 0
601 {"exclude", 1, 0, 0}, // 1
602 {"filter", 1, 0, 0}, // 2
603 {"filter-extension", 1, 0, 0}, // 3
604 {"dest", 1, 0, 0}, // 4
605 {"scheme", 1, 0, 0}, // 5
606 {"signature-filter", 1, 0, 0}, // 6
611 int c = getopt_long(argc, argv, "", long_options, &long_index);
617 switch (long_index) {
619 localdb_dir = optarg;
622 if (optarg[0] != '/')
623 excludes.push_back(optarg);
625 excludes.push_back(optarg + 1);
628 filter_program = optarg;
630 case 3: // --filter-extension
631 filter_extension = optarg;
634 backup_dest = optarg;
637 backup_scheme = optarg;
639 case 6: // --signature-filter
640 signature_filter = optarg;
643 fprintf(stderr, "Unhandled long option!\n");
652 if (optind == argc) {
657 searches.push_back(".");
658 for (int i = optind; i < argc; i++)
659 add_include(argv[i]);
661 if (backup_dest == "") {
663 "Error: Backup destination must be specified with --dest=\n");
668 // Default for --localdb is the same as --dest
669 if (localdb_dir == "") {
670 localdb_dir = backup_dest;
673 // Dump paths for debugging/informational purposes
675 list<string>::const_iterator i;
677 printf("LBS Version: %s\n", lbs_version);
679 printf("--dest=%s\n--localdb=%s\n\n",
680 backup_dest.c_str(), localdb_dir.c_str());
682 printf("Includes:\n");
683 for (i = includes.begin(); i != includes.end(); ++i)
684 printf(" %s\n", i->c_str());
686 printf("Excludes:\n");
687 for (i = excludes.begin(); i != excludes.end(); ++i)
688 printf(" %s\n", i->c_str());
690 printf("Searching:\n");
691 for (i = searches.begin(); i != searches.end(); ++i)
692 printf(" %s\n", i->c_str());
695 block_buf = new char[LBS_BLOCK_SIZE];
697 /* Store the time when the backup started, so it can be included in the
703 localtime_r(&now, &time_buf);
704 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
706 /* Open the local database which tracks all objects that are stored
707 * remotely, for efficient incrementals. Provide it with the name of this
709 string database_path = localdb_dir + "/localdb.sqlite";
711 db->Open(database_path.c_str(), desc_buf,
712 backup_scheme.size() ? backup_scheme.c_str() : NULL);
714 tss = new TarSegmentStore(backup_dest, db);
716 /* Initialize the stat cache, for skipping over unchanged files. */
717 statcache = new StatCache;
718 statcache->Open(localdb_dir.c_str(), desc_buf,
719 backup_scheme.size() ? backup_scheme.c_str() : NULL);
721 scanfile(".", false);
724 const string md = metadata_root.str();
726 LbsObject *root = new LbsObject;
727 root->set_group("metadata");
728 root->set_data(md.data(), md.size());
731 segment_list.insert(root->get_ref().get_segment());
733 string backup_root = root->get_ref().to_string();
743 /* Write out a checksums file which lists the checksums for all the
744 * segments included in this snapshot. The format is designed so that it
745 * may be easily verified using the sha1sums command. */
746 const char csum_type[] = "sha1";
747 string checksum_filename = backup_dest + "/snapshot-";
748 if (backup_scheme.size() > 0)
749 checksum_filename += backup_scheme + "-";
750 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
751 FILE *checksums = fopen(checksum_filename.c_str(), "w");
752 if (checksums != NULL) {
753 for (std::set<string>::iterator i = segment_list.begin();
754 i != segment_list.end(); ++i) {
755 string seg_path, seg_csum;
756 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
757 const char *raw_checksum = NULL;
758 if (strncmp(seg_csum.c_str(), csum_type,
759 strlen(csum_type)) == 0) {
760 raw_checksum = seg_csum.c_str() + strlen(csum_type);
761 if (*raw_checksum == '=')
767 if (raw_checksum != NULL)
768 fprintf(checksums, "%s *%s\n",
769 raw_checksum, seg_path.c_str());
774 fprintf(stderr, "ERROR: Unable to write checksums file: %m\n");
779 /* Write a backup descriptor file, which says which segments are needed and
780 * where to start to restore this snapshot. The filename is based on the
781 * current time. If a signature filter program was specified, filter the
782 * data through that to give a chance to sign the descriptor contents. */
783 string desc_filename = backup_dest + "/snapshot-";
784 if (backup_scheme.size() > 0)
785 desc_filename += backup_scheme + "-";
786 desc_filename = desc_filename + desc_buf + ".lbs";
788 int descriptor_fd = open(desc_filename.c_str(), O_WRONLY | O_CREAT, 0666);
789 if (descriptor_fd < 0) {
790 fprintf(stderr, "Unable to open descriptor output file: %m\n");
793 pid_t signature_pid = 0;
794 if (signature_filter.size() > 0) {
795 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
797 close(descriptor_fd);
798 descriptor_fd = new_fd;
800 FILE *descriptor = fdopen(descriptor_fd, "w");
802 fprintf(descriptor, "Format: LBS Snapshot v0.2\n");
803 fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
804 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
805 fprintf(descriptor, "Date: %s\n", desc_buf);
806 if (backup_scheme.size() > 0)
807 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
808 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
810 SHA1Checksum checksum_csum;
811 if (checksum_csum.process_file(checksum_filename.c_str())) {
812 string csum = checksum_csum.checksum_str();
813 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
816 fprintf(descriptor, "Segments:\n");
817 for (std::set<string>::iterator i = segment_list.begin();
818 i != segment_list.end(); ++i) {
819 fprintf(descriptor, " %s\n", i->c_str());
826 waitpid(signature_pid, &status, 0);
828 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
829 throw IOException("Signature filter process error");