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;
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");
220 o->set_group("data");
224 o->set_data(block_buf, bytes);
227 db->StoreObject(ref, block_csum, bytes, block_age);
231 object_list.push_back(ref.to_string());
232 segment_list.insert(ref.get_segment());
240 file_info["checksum"] = hash.checksum_str();
244 printf(" [%s]\n", status);
246 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
248 /* For files that only need to be broken apart into a few objects, store
249 * the list of objects directly. For larger files, store the data
250 * out-of-line and provide a pointer to the indrect object. */
251 if (object_list.size() < 8) {
252 string blocklist = "";
253 for (list<string>::iterator i = object_list.begin();
254 i != object_list.end(); ++i) {
255 if (i != object_list.begin())
259 file_info["data"] = blocklist;
261 string blocklist = "";
262 for (list<string>::iterator i = object_list.begin();
263 i != object_list.end(); ++i) {
264 blocklist += *i + "\n";
267 LbsObject *i = new LbsObject;
268 i->set_group("metadata");
269 i->set_data(blocklist.data(), blocklist.size());
271 file_info["data"] = "@" + i->get_name();
272 segment_list.insert(i->get_ref().get_segment());
279 /* Dump a specified filesystem object (file, directory, etc.) based on its
280 * inode information. If the object is a regular file, an open filehandle is
282 void dump_inode(const string& path, // Path within snapshot
283 const string& fullpath, // Path to object in filesystem
284 struct stat& stat_buf, // Results of stat() call
285 int fd) // Open filehandle if regular file
288 dictionary file_info;
292 printf("%s\n", path.c_str());
294 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
295 file_info["mtime"] = encode_int(stat_buf.st_mtime);
296 file_info["user"] = encode_int(stat_buf.st_uid);
297 file_info["group"] = encode_int(stat_buf.st_gid);
299 struct passwd *pwd = getpwuid(stat_buf.st_uid);
301 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
304 struct group *grp = getgrgid(stat_buf.st_gid);
306 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
309 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
310 file_info["links"] = encode_int(stat_buf.st_nlink);
311 file_info["inode"] = encode_int(major(stat_buf.st_dev))
312 + "/" + encode_int(minor(stat_buf.st_dev))
313 + "/" + encode_int(stat_buf.st_ino);
318 switch (stat_buf.st_mode & S_IFMT) {
327 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
328 file_info["device"] = encode_int(major(stat_buf.st_rdev))
329 + "/" + encode_int(minor(stat_buf.st_rdev));
334 /* Use the reported file size to allocate a buffer large enough to read
335 * the symlink. Allocate slightly more space, so that we ask for more
336 * bytes than we expect and so check for truncation. */
337 buf = new char[stat_buf.st_size + 2];
338 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
340 fprintf(stderr, "error reading symlink: %m\n");
341 } else if (len <= stat_buf.st_size) {
343 file_info["contents"] = uri_encode(buf);
344 } else if (len > stat_buf.st_size) {
345 fprintf(stderr, "error reading symlink: name truncated\n");
353 file_size = dumpfile(fd, file_info, path, stat_buf);
354 file_info["size"] = encode_int(file_size);
357 return; // error occurred; do not dump file
359 if (file_size != stat_buf.st_size) {
360 fprintf(stderr, "Warning: Size of %s changed during reading\n",
370 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
374 file_info["type"] = string(1, inode_type);
376 metadata << "name: " << uri_encode(path) << "\n";
377 dict_output(metadata, file_info);
380 // Break apart metadata listing if it becomes too large.
381 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
385 void scanfile(const string& path, bool include)
389 struct stat stat_buf;
396 true_path = "/" + path;
398 // Set to true if we should scan through the contents of this directory,
399 // but not actually back files up
400 bool scan_only = false;
402 // Check this file against the include/exclude list to see if it should be
404 for (list<string>::iterator i = includes.begin();
405 i != includes.end(); ++i) {
407 printf("Including %s\n", path.c_str());
412 for (list<string>::iterator i = excludes.begin();
413 i != excludes.end(); ++i) {
415 printf("Excluding %s\n", path.c_str());
420 for (list<string>::iterator i = searches.begin();
421 i != searches.end(); ++i) {
423 printf("Scanning %s\n", path.c_str());
428 if (!include && !scan_only)
431 if (lstat(true_path.c_str(), &stat_buf) < 0) {
432 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
436 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
437 /* Be paranoid when opening the file. We have no guarantee that the
438 * file was not replaced between the stat() call above and the open()
439 * call below, so we might not even be opening a regular file. We
440 * supply flags to open to to guard against various conditions before
441 * we can perform an lstat to check that the file is still a regular
443 * - O_NOFOLLOW: in the event the file was replaced by a symlink
444 * - O_NONBLOCK: prevents open() from blocking if the file was
446 * We also add in O_NOATIME, since this may reduce disk writes (for
447 * inode updates). However, O_NOATIME may result in EPERM, so if the
448 * initial open fails, try again without O_NOATIME. */
449 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
451 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
454 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
458 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
460 flags = fcntl(fd, F_GETFL);
461 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
463 /* Perform the stat call again, and check that we still have a regular
465 if (fstat(fd, &stat_buf) < 0) {
466 fprintf(stderr, "fstat: %m\n");
471 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
472 fprintf(stderr, "file is no longer a regular file!\n");
478 dump_inode(path, true_path, stat_buf, fd);
483 // If we hit a directory, now that we've written the directory itself,
484 // recursively scan the directory.
485 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
486 DIR *dir = opendir(true_path.c_str());
489 fprintf(stderr, "Error: %m\n");
494 vector<string> contents;
495 while ((ent = readdir(dir)) != NULL) {
496 string filename(ent->d_name);
497 if (filename == "." || filename == "..")
499 contents.push_back(filename);
504 sort(contents.begin(), contents.end());
506 for (vector<string>::iterator i = contents.begin();
507 i != contents.end(); ++i) {
508 const string& filename = *i;
510 scanfile(filename, include);
512 scanfile(path + "/" + filename, include);
517 /* Include the specified file path in the backups. Append the path to the
518 * includes list, and to ensure that we actually see the path when scanning the
519 * directory tree, add all the parent directories to the search list, which
520 * means we will scan through the directory listing even if the files
521 * themselves are excluded from being backed up. */
522 void add_include(const char *path)
524 printf("Add: %s\n", path);
525 /* Was an absolute path specified? If so, we'll need to start scanning
526 * from the root directory. Make sure that the user was consistent in
527 * providing either all relative paths or all absolute paths. */
528 if (path[0] == '/') {
529 if (includes.size() > 0 && relative_paths == true) {
531 "Error: Cannot mix relative and absolute paths!\n");
535 relative_paths = false;
537 // Skip over leading '/'
539 } else if (relative_paths == false && path[0] != '/') {
540 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
544 includes.push_back(path);
546 /* Split the specified path into directory components, and ensure that we
547 * descend into all the directories along the path. */
548 const char *slash = path;
553 while ((slash = strchr(slash + 1, '/')) != NULL) {
554 string component(path, slash - path);
555 searches.push_back(component);
559 void usage(const char *program)
564 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
565 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
568 " --dest=PATH path where backup is to be written [REQUIRED]\n"
569 " --exclude=PATH exclude files in PATH from snapshot\n"
570 " --localdb=PATH local backup metadata is stored in PATH\n"
571 " --filter=COMMAND program through which to filter segment data\n"
572 " (defaults to \"bzip2 -c\")\n"
573 " --filter-extension=EXT\n"
574 " string to append to segment files\n"
575 " (defaults to \".bz2\")\n"
576 " --signature-filter=COMMAND\n"
577 " program though which to filter descriptor\n"
578 " --scheme=NAME optional name for this snapshot\n",
583 int main(int argc, char *argv[])
585 string backup_dest = "";
586 string localdb_dir = "";
587 string backup_scheme = "";
588 string signature_filter = "";
591 static struct option long_options[] = {
592 {"localdb", 1, 0, 0}, // 0
593 {"exclude", 1, 0, 0}, // 1
594 {"filter", 1, 0, 0}, // 2
595 {"filter-extension", 1, 0, 0}, // 3
596 {"dest", 1, 0, 0}, // 4
597 {"scheme", 1, 0, 0}, // 5
598 {"signature-filter", 1, 0, 0}, // 6
603 int c = getopt_long(argc, argv, "", long_options, &long_index);
609 switch (long_index) {
611 localdb_dir = optarg;
614 if (optarg[0] != '/')
615 excludes.push_back(optarg);
617 excludes.push_back(optarg + 1);
620 filter_program = optarg;
622 case 3: // --filter-extension
623 filter_extension = optarg;
626 backup_dest = optarg;
629 backup_scheme = optarg;
631 case 6: // --signature-filter
632 signature_filter = optarg;
635 fprintf(stderr, "Unhandled long option!\n");
644 if (optind == argc) {
649 searches.push_back(".");
650 for (int i = optind; i < argc; i++)
651 add_include(argv[i]);
653 if (backup_dest == "") {
655 "Error: Backup destination must be specified with --dest=\n");
660 // Default for --localdb is the same as --dest
661 if (localdb_dir == "") {
662 localdb_dir = backup_dest;
665 // Dump paths for debugging/informational purposes
667 list<string>::const_iterator i;
669 printf("LBS Version: %s\n", lbs_version);
671 printf("--dest=%s\n--localdb=%s\n\n",
672 backup_dest.c_str(), localdb_dir.c_str());
674 printf("Includes:\n");
675 for (i = includes.begin(); i != includes.end(); ++i)
676 printf(" %s\n", i->c_str());
678 printf("Excludes:\n");
679 for (i = excludes.begin(); i != excludes.end(); ++i)
680 printf(" %s\n", i->c_str());
682 printf("Searching:\n");
683 for (i = searches.begin(); i != searches.end(); ++i)
684 printf(" %s\n", i->c_str());
687 block_buf = new char[LBS_BLOCK_SIZE];
689 /* Store the time when the backup started, so it can be included in the
695 localtime_r(&now, &time_buf);
696 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
698 /* Open the local database which tracks all objects that are stored
699 * remotely, for efficient incrementals. Provide it with the name of this
701 string database_path = localdb_dir + "/localdb.sqlite";
703 db->Open(database_path.c_str(), desc_buf,
704 backup_scheme.size() ? backup_scheme.c_str() : NULL);
706 tss = new TarSegmentStore(backup_dest, db);
708 /* Initialize the stat cache, for skipping over unchanged files. */
709 statcache = new StatCache;
710 statcache->Open(localdb_dir.c_str(), desc_buf,
711 backup_scheme.size() ? backup_scheme.c_str() : NULL);
713 scanfile(".", false);
716 const string md = metadata_root.str();
718 LbsObject *root = new LbsObject;
719 root->set_group("metadata");
720 root->set_data(md.data(), md.size());
723 segment_list.insert(root->get_ref().get_segment());
725 string backup_root = root->get_ref().to_string();
735 /* Write out a checksums file which lists the checksums for all the
736 * segments included in this snapshot. The format is designed so that it
737 * may be easily verified using the sha1sums command. */
738 const char csum_type[] = "sha1";
739 string checksum_filename = backup_dest + "/snapshot-";
740 if (backup_scheme.size() > 0)
741 checksum_filename += backup_scheme + "-";
742 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
743 FILE *checksums = fopen(checksum_filename.c_str(), "w");
744 if (checksums != NULL) {
745 for (std::set<string>::iterator i = segment_list.begin();
746 i != segment_list.end(); ++i) {
747 string seg_path, seg_csum;
748 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
749 const char *raw_checksum = NULL;
750 if (strncmp(seg_csum.c_str(), csum_type,
751 strlen(csum_type)) == 0) {
752 raw_checksum = seg_csum.c_str() + strlen(csum_type);
753 if (*raw_checksum == '=')
759 if (raw_checksum != NULL)
760 fprintf(checksums, "%s *%s\n",
761 raw_checksum, seg_path.c_str());
766 fprintf(stderr, "ERROR: Unable to write checksums file: %m\n");
771 /* Write a backup descriptor file, which says which segments are needed and
772 * where to start to restore this snapshot. The filename is based on the
773 * current time. If a signature filter program was specified, filter the
774 * data through that to give a chance to sign the descriptor contents. */
775 string desc_filename = backup_dest + "/snapshot-";
776 if (backup_scheme.size() > 0)
777 desc_filename += backup_scheme + "-";
778 desc_filename = desc_filename + desc_buf + ".lbs";
780 int descriptor_fd = open(desc_filename.c_str(), O_WRONLY | O_CREAT, 0666);
781 if (descriptor_fd < 0) {
782 fprintf(stderr, "Unable to open descriptor output file: %m\n");
785 pid_t signature_pid = 0;
786 if (signature_filter.size() > 0) {
787 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
789 close(descriptor_fd);
790 descriptor_fd = new_fd;
792 FILE *descriptor = fdopen(descriptor_fd, "w");
794 fprintf(descriptor, "Format: LBS Snapshot v0.2\n");
795 fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
796 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
797 fprintf(descriptor, "Date: %s\n", desc_buf);
798 if (backup_scheme.size() > 0)
799 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
800 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
802 SHA1Checksum checksum_csum;
803 if (checksum_csum.process_file(checksum_filename.c_str())) {
804 string csum = checksum_csum.checksum_str();
805 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
808 fprintf(descriptor, "Segments:\n");
809 for (std::set<string>::iterator i = segment_list.begin();
810 i != segment_list.end(); ++i) {
811 fprintf(descriptor, " %s\n", i->c_str());
818 waitpid(signature_pid, &status, 0);
820 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
821 throw IOException("Signature filter process error");