1 /* Recursively descend the filesystem and visit each file. */
13 #include <sys/sysmacros.h>
14 #include <sys/types.h>
29 #include "statcache.h"
37 /* Version information. This will be filled in by the Makefile. */
39 #define LBS_VERSION Unknown
41 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
42 #define LBS_STRINGIFY2(s) #s
43 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
45 static TarSegmentStore *tss = NULL;
47 /* Buffer for holding a single block of data read from a file. */
48 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
49 static char *block_buf;
51 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
53 /* Local database, which tracks objects written in this and previous
54 * invocations to help in creating incremental snapshots. */
57 /* Stat cache, which stored data locally to speed the backup process by quickly
58 * skipping files which have not changed. */
61 /* Contents of the root object. This will contain a set of indirect links to
62 * the metadata objects. */
63 std::ostringstream metadata_root;
65 /* Buffer for building up metadata. */
66 std::ostringstream metadata;
68 /* Keep track of all segments which are needed to reconstruct the snapshot. */
69 std::set<string> segment_list;
71 /* Selection of files to include/exclude in the snapshot. */
72 std::list<string> includes; // Paths in which files should be saved
73 std::list<string> excludes; // Paths which will not be saved
74 std::list<string> searches; // Directories we don't want to save, but
75 // do want to descend searching for data
78 bool relative_paths = true;
80 /* Ensure contents of metadata are flushed to an object. */
83 string m = metadata.str();
87 /* Write current metadata information to a new object. */
88 LbsObject *meta = new LbsObject;
89 meta->set_group("metadata");
90 meta->set_data(m.data(), m.size());
94 /* Write a reference to this block in the root. */
95 ObjectReference ref = meta->get_ref();
96 metadata_root << "@" << ref.to_string() << "\n";
97 segment_list.insert(ref.get_segment());
104 /* Read data from a file descriptor and return the amount of data read. A
105 * short read (less than the requested size) will only occur if end-of-file is
107 ssize_t file_read(int fd, char *buf, size_t maxlen)
109 size_t bytes_read = 0;
112 ssize_t res = read(fd, buf, maxlen);
116 fprintf(stderr, "error reading file: %m\n");
118 } else if (res == 0) {
130 /* Read the contents of a file (specified by an open file descriptor) and copy
131 * the data to the store. Returns the size of the file (number of bytes
132 * dumped), or -1 on error. */
133 int64_t dumpfile(int fd, dictionary &file_info, const string &path,
134 struct stat& stat_buf)
137 list<string> object_list;
138 const char *status = NULL; /* Status indicator printed out */
140 /* Look up this file in the old stat cache, if we can. If the stat
141 * information indicates that the file has not changed, do not bother
142 * re-reading the entire contents. */
145 if (statcache->Find(path, &stat_buf)) {
147 const list<ObjectReference> &blocks = statcache->get_blocks();
149 /* If any of the blocks in the object have been expired, then we should
150 * fall back to fully reading in the file. */
151 for (list<ObjectReference>::const_iterator i = blocks.begin();
152 i != blocks.end(); ++i) {
153 const ObjectReference &ref = *i;
154 if (!db->IsAvailable(ref)) {
161 /* If everything looks okay, use the cached information */
163 file_info["checksum"] = statcache->get_checksum();
164 for (list<ObjectReference>::const_iterator i = blocks.begin();
165 i != blocks.end(); ++i) {
166 const ObjectReference &ref = *i;
167 object_list.push_back(ref.to_string());
168 segment_list.insert(ref.get_segment());
171 size = stat_buf.st_size;
175 /* If the file is new or changed, we must read in the contents a block at a
180 ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
184 fprintf(stderr, "Backup contents for %s may be incorrect\n",
189 hash.process(block_buf, bytes);
191 // Either find a copy of this block in an already-existing segment,
192 // or index it so it can be re-used in the future
193 double block_age = 0.0;
194 SHA1Checksum block_hash;
195 block_hash.process(block_buf, bytes);
196 string block_csum = block_hash.checksum_str();
197 ObjectReference ref = db->FindObject(block_csum, bytes);
199 // Store a copy of the object if one does not yet exist
200 if (ref.get_segment().size() == 0) {
201 LbsObject *o = new LbsObject;
203 /* We might still have seen this checksum before, if the object
204 * was stored at some time in the past, but we have decided to
205 * clean the segment the object was originally stored in
206 * (FindObject will not return such objects). When rewriting
207 * the object contents, put it in a separate group, so that old
208 * objects get grouped together. The hope is that these old
209 * objects will continue to be used in the future, and we
210 * obtain segments which will continue to be well-utilized.
211 * Additionally, keep track of the age of the data by looking
212 * up the age of the block which was expired and using that
213 * instead of the current time. */
214 if (db->IsOldObject(block_csum, bytes, &block_age)) {
215 o->set_group("compacted");
219 o->set_group("data");
223 o->set_data(block_buf, bytes);
226 db->StoreObject(ref, block_csum, bytes, block_age);
230 object_list.push_back(ref.to_string());
231 segment_list.insert(ref.get_segment());
239 file_info["checksum"] = hash.checksum_str();
243 printf(" [%s]\n", status);
245 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
247 /* For files that only need to be broken apart into a few objects, store
248 * the list of objects directly. For larger files, store the data
249 * out-of-line and provide a pointer to the indrect object. */
250 if (object_list.size() < 8) {
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;
260 string blocklist = "";
261 for (list<string>::iterator i = object_list.begin();
262 i != object_list.end(); ++i) {
263 blocklist += *i + "\n";
266 LbsObject *i = new LbsObject;
267 i->set_group("metadata");
268 i->set_data(blocklist.data(), blocklist.size());
270 file_info["data"] = "@" + i->get_name();
271 segment_list.insert(i->get_ref().get_segment());
278 /* Dump a specified filesystem object (file, directory, etc.) based on its
279 * inode information. If the object is a regular file, an open filehandle is
281 void dump_inode(const string& path, // Path within snapshot
282 const string& fullpath, // Path to object in filesystem
283 struct stat& stat_buf, // Results of stat() call
284 int fd) // Open filehandle if regular file
287 dictionary file_info;
291 printf("%s\n", path.c_str());
293 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
294 file_info["mtime"] = encode_int(stat_buf.st_mtime);
295 file_info["user"] = encode_int(stat_buf.st_uid);
296 file_info["group"] = encode_int(stat_buf.st_gid);
298 struct passwd *pwd = getpwuid(stat_buf.st_uid);
300 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
303 struct group *grp = getgrgid(stat_buf.st_gid);
305 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
308 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
309 file_info["links"] = encode_int(stat_buf.st_nlink);
310 file_info["inode"] = encode_int(major(stat_buf.st_dev))
311 + "/" + encode_int(minor(stat_buf.st_dev))
312 + "/" + encode_int(stat_buf.st_ino);
317 switch (stat_buf.st_mode & S_IFMT) {
326 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
327 file_info["device"] = encode_int(major(stat_buf.st_rdev))
328 + "/" + encode_int(minor(stat_buf.st_rdev));
333 /* Use the reported file size to allocate a buffer large enough to read
334 * the symlink. Allocate slightly more space, so that we ask for more
335 * bytes than we expect and so check for truncation. */
336 buf = new char[stat_buf.st_size + 2];
337 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
339 fprintf(stderr, "error reading symlink: %m\n");
340 } else if (len <= stat_buf.st_size) {
342 file_info["contents"] = uri_encode(buf);
343 } else if (len > stat_buf.st_size) {
344 fprintf(stderr, "error reading symlink: name truncated\n");
352 file_size = dumpfile(fd, file_info, path, stat_buf);
353 file_info["size"] = encode_int(file_size);
356 return; // error occurred; do not dump file
358 if (file_size != stat_buf.st_size) {
359 fprintf(stderr, "Warning: Size of %s changed during reading\n",
369 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
373 file_info["type"] = string(1, inode_type);
375 metadata << "name: " << uri_encode(path) << "\n";
376 dict_output(metadata, file_info);
379 // Break apart metadata listing if it becomes too large.
380 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
384 void scanfile(const string& path, bool include)
388 struct stat stat_buf;
395 true_path = "/" + path;
397 // Set to true if we should scan through the contents of this directory,
398 // but not actually back files up
399 bool scan_only = false;
401 // Check this file against the include/exclude list to see if it should be
403 for (list<string>::iterator i = includes.begin();
404 i != includes.end(); ++i) {
406 printf("Including %s\n", path.c_str());
411 for (list<string>::iterator i = excludes.begin();
412 i != excludes.end(); ++i) {
414 printf("Excluding %s\n", path.c_str());
419 for (list<string>::iterator i = searches.begin();
420 i != searches.end(); ++i) {
422 printf("Scanning %s\n", path.c_str());
427 if (!include && !scan_only)
430 if (lstat(true_path.c_str(), &stat_buf) < 0) {
431 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
435 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
436 /* Be paranoid when opening the file. We have no guarantee that the
437 * file was not replaced between the stat() call above and the open()
438 * call below, so we might not even be opening a regular file. We
439 * supply flags to open to to guard against various conditions before
440 * we can perform an lstat to check that the file is still a regular
442 * - O_NOFOLLOW: in the event the file was replaced by a symlink
443 * - O_NONBLOCK: prevents open() from blocking if the file was
445 * We also add in O_NOATIME, since this may reduce disk writes (for
446 * inode updates). However, O_NOATIME may result in EPERM, so if the
447 * initial open fails, try again without O_NOATIME. */
448 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
450 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
453 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
457 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
459 flags = fcntl(fd, F_GETFL);
460 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
462 /* Perform the stat call again, and check that we still have a regular
464 if (fstat(fd, &stat_buf) < 0) {
465 fprintf(stderr, "fstat: %m\n");
470 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
471 fprintf(stderr, "file is no longer a regular file!\n");
477 dump_inode(path, true_path, stat_buf, fd);
482 // If we hit a directory, now that we've written the directory itself,
483 // recursively scan the directory.
484 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
485 DIR *dir = opendir(true_path.c_str());
488 fprintf(stderr, "Error: %m\n");
493 vector<string> contents;
494 while ((ent = readdir(dir)) != NULL) {
495 string filename(ent->d_name);
496 if (filename == "." || filename == "..")
498 contents.push_back(filename);
503 sort(contents.begin(), contents.end());
505 for (vector<string>::iterator i = contents.begin();
506 i != contents.end(); ++i) {
507 const string& filename = *i;
509 scanfile(filename, include);
511 scanfile(path + "/" + filename, include);
516 /* Include the specified file path in the backups. Append the path to the
517 * includes list, and to ensure that we actually see the path when scanning the
518 * directory tree, add all the parent directories to the search list, which
519 * means we will scan through the directory listing even if the files
520 * themselves are excluded from being backed up. */
521 void add_include(const char *path)
523 printf("Add: %s\n", path);
524 /* Was an absolute path specified? If so, we'll need to start scanning
525 * from the root directory. Make sure that the user was consistent in
526 * providing either all relative paths or all absolute paths. */
527 if (path[0] == '/') {
528 if (includes.size() > 0 && relative_paths == true) {
530 "Error: Cannot mix relative and absolute paths!\n");
534 relative_paths = false;
536 // Skip over leading '/'
538 } else if (relative_paths == false && path[0] != '/') {
539 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
543 includes.push_back(path);
545 /* Split the specified path into directory components, and ensure that we
546 * descend into all the directories along the path. */
547 const char *slash = path;
552 while ((slash = strchr(slash + 1, '/')) != NULL) {
553 string component(path, slash - path);
554 searches.push_back(component);
558 void usage(const char *program)
563 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
564 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
567 " --dest=PATH path where backup is to be written [REQUIRED]\n"
568 " --exclude=PATH exclude files in PATH from snapshot\n"
569 " --localdb=PATH local backup metadata is stored in PATH\n"
570 " --filter=COMMAND program through which to filter segment data\n"
571 " (defaults to \"bzip2 -c\")\n"
572 " --filter-extension=EXT\n"
573 " string to append to segment files\n"
574 " (defaults to \".bz2\")\n"
575 " --scheme=NAME optional name for this snapshot\n",
580 int main(int argc, char *argv[])
582 string backup_dest = "";
583 string localdb_dir = "";
584 string backup_scheme = "";
587 static struct option long_options[] = {
588 {"localdb", 1, 0, 0}, // 0
589 {"exclude", 1, 0, 0}, // 1
590 {"filter", 1, 0, 0}, // 2
591 {"filter-extension", 1, 0, 0}, // 3
592 {"dest", 1, 0, 0}, // 4
593 {"scheme", 1, 0, 0}, // 5
598 int c = getopt_long(argc, argv, "", long_options, &long_index);
604 switch (long_index) {
606 localdb_dir = optarg;
609 if (optarg[0] != '/')
610 excludes.push_back(optarg);
612 excludes.push_back(optarg + 1);
615 filter_program = optarg;
617 case 3: // --filter-extension
618 filter_extension = optarg;
621 backup_dest = optarg;
624 backup_scheme = optarg;
627 fprintf(stderr, "Unhandled long option!\n");
636 if (optind == argc) {
641 searches.push_back(".");
642 for (int i = optind; i < argc; i++)
643 add_include(argv[i]);
645 if (backup_dest == "") {
647 "Error: Backup destination must be specified with --dest=\n");
652 // Default for --localdb is the same as --dest
653 if (localdb_dir == "") {
654 localdb_dir = backup_dest;
657 // Dump paths for debugging/informational purposes
659 list<string>::const_iterator i;
661 printf("LBS Version: %s\n", lbs_version);
663 printf("--dest=%s\n--localdb=%s\n\n",
664 backup_dest.c_str(), localdb_dir.c_str());
666 printf("Includes:\n");
667 for (i = includes.begin(); i != includes.end(); ++i)
668 printf(" %s\n", i->c_str());
670 printf("Excludes:\n");
671 for (i = excludes.begin(); i != excludes.end(); ++i)
672 printf(" %s\n", i->c_str());
674 printf("Searching:\n");
675 for (i = searches.begin(); i != searches.end(); ++i)
676 printf(" %s\n", i->c_str());
679 block_buf = new char[LBS_BLOCK_SIZE];
681 /* Store the time when the backup started, so it can be included in the
687 localtime_r(&now, &time_buf);
688 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
690 /* Open the local database which tracks all objects that are stored
691 * remotely, for efficient incrementals. Provide it with the name of this
693 string database_path = localdb_dir + "/localdb.sqlite";
695 db->Open(database_path.c_str(), desc_buf,
696 backup_scheme.size() ? backup_scheme.c_str() : NULL);
698 tss = new TarSegmentStore(backup_dest, db);
700 /* Initialize the stat cache, for skipping over unchanged files. */
701 statcache = new StatCache;
702 statcache->Open(localdb_dir.c_str(), desc_buf,
703 backup_scheme.size() ? backup_scheme.c_str() : NULL);
705 scanfile(".", false);
708 const string md = metadata_root.str();
710 LbsObject *root = new LbsObject;
711 root->set_group("metadata");
712 root->set_data(md.data(), md.size());
715 segment_list.insert(root->get_ref().get_segment());
717 string backup_root = root->get_ref().to_string();
727 /* Write out a checksums file which lists the checksums for all the
728 * segments included in this snapshot. The format is designed so that it
729 * may be easily verified using the sha1sums command. */
730 const char csum_type[] = "sha1";
731 string checksum_filename = backup_dest + "/snapshot-";
732 if (backup_scheme.size() > 0)
733 checksum_filename += backup_scheme + "-";
734 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
735 FILE *checksums = fopen(checksum_filename.c_str(), "w");
736 if (checksums != NULL) {
737 for (std::set<string>::iterator i = segment_list.begin();
738 i != segment_list.end(); ++i) {
739 string seg_path, seg_csum;
740 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
741 const char *raw_checksum = NULL;
742 if (strncmp(seg_csum.c_str(), csum_type,
743 strlen(csum_type)) == 0) {
744 raw_checksum = seg_csum.c_str() + strlen(csum_type);
745 if (*raw_checksum == '=')
751 if (raw_checksum != NULL)
752 fprintf(checksums, "%s *%s\n",
753 raw_checksum, seg_path.c_str());
758 fprintf(stderr, "ERROR: Unable to write checksums file: %m\n");
763 /* Write a backup descriptor file, which says which segments are needed and
764 * where to start to restore this snapshot. The filename is based on the
766 string desc_filename = backup_dest + "/snapshot-";
767 if (backup_scheme.size() > 0)
768 desc_filename += backup_scheme + "-";
769 desc_filename = desc_filename + desc_buf + ".lbs";
770 std::ofstream descriptor(desc_filename.c_str());
772 descriptor << "Format: LBS Snapshot v0.2\n";
773 descriptor << "Producer: LBS " << lbs_version << "\n";
774 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
775 descriptor << "Date: " << desc_buf << "\n";
776 if (backup_scheme.size() > 0)
777 descriptor << "Scheme: " << backup_scheme << "\n";
778 descriptor << "Root: " << backup_root << "\n";
780 SHA1Checksum checksum_csum;
781 if (checksum_csum.process_file(checksum_filename.c_str())) {
782 descriptor << "Checksums: " << checksum_csum.checksum_str() << "\n";
785 descriptor << "Segments:\n";
786 for (std::set<string>::iterator i = segment_list.begin();
787 i != segment_list.end(); ++i) {
788 descriptor << " " << *i << "\n";