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;
139 /* Look up this file in the old stat cache, if we can. If the stat
140 * information indicates that the file has not changed, do not bother
141 * re-reading the entire contents. */
144 if (statcache->Find(path, &stat_buf)) {
146 const list<ObjectReference> &blocks = statcache->get_blocks();
148 /* If any of the blocks in the object have been expired, then we should
149 * fall back to fully reading in the file. */
150 for (list<ObjectReference>::const_iterator i = blocks.begin();
151 i != blocks.end(); ++i) {
152 const ObjectReference &ref = *i;
153 if (!db->IsAvailable(ref)) {
159 /* If everything looks okay, use the cached information */
161 file_info["checksum"] = statcache->get_checksum();
162 for (list<ObjectReference>::const_iterator i = blocks.begin();
163 i != blocks.end(); ++i) {
164 const ObjectReference &ref = *i;
165 object_list.push_back(ref.to_string());
166 segment_list.insert(ref.get_segment());
169 size = stat_buf.st_size;
173 /* 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");
217 o->set_group("data");
219 o->set_data(block_buf, bytes);
222 db->StoreObject(ref, block_csum, bytes, block_age);
226 object_list.push_back(ref.to_string());
227 segment_list.insert(ref.get_segment());
232 file_info["checksum"] = hash.checksum_str();
235 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
237 /* For files that only need to be broken apart into a few objects, store
238 * the list of objects directly. For larger files, store the data
239 * out-of-line and provide a pointer to the indrect object. */
240 if (object_list.size() < 8) {
241 string blocklist = "";
242 for (list<string>::iterator i = object_list.begin();
243 i != object_list.end(); ++i) {
244 if (i != object_list.begin())
248 file_info["data"] = blocklist;
250 string blocklist = "";
251 for (list<string>::iterator i = object_list.begin();
252 i != object_list.end(); ++i) {
253 blocklist += *i + "\n";
256 LbsObject *i = new LbsObject;
257 i->set_group("metadata");
258 i->set_data(blocklist.data(), blocklist.size());
260 file_info["data"] = "@" + i->get_name();
261 segment_list.insert(i->get_ref().get_segment());
268 /* Dump a specified filesystem object (file, directory, etc.) based on its
269 * inode information. If the object is a regular file, an open filehandle is
271 void dump_inode(const string& path, // Path within snapshot
272 const string& fullpath, // Path to object in filesystem
273 struct stat& stat_buf, // Results of stat() call
274 int fd) // Open filehandle if regular file
277 dictionary file_info;
281 printf("%s\n", path.c_str());
283 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
284 file_info["mtime"] = encode_int(stat_buf.st_mtime);
285 file_info["user"] = encode_int(stat_buf.st_uid);
286 file_info["group"] = encode_int(stat_buf.st_gid);
288 struct passwd *pwd = getpwuid(stat_buf.st_uid);
290 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
293 struct group *grp = getgrgid(stat_buf.st_gid);
295 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
300 switch (stat_buf.st_mode & S_IFMT) {
309 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
310 file_info["device"] = encode_int(major(stat_buf.st_rdev))
311 + "/" + encode_int(minor(stat_buf.st_rdev));
316 /* Use the reported file size to allocate a buffer large enough to read
317 * the symlink. Allocate slightly more space, so that we ask for more
318 * bytes than we expect and so check for truncation. */
319 buf = new char[stat_buf.st_size + 2];
320 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
322 fprintf(stderr, "error reading symlink: %m\n");
323 } else if (len <= stat_buf.st_size) {
325 file_info["contents"] = uri_encode(buf);
326 } else if (len > stat_buf.st_size) {
327 fprintf(stderr, "error reading symlink: name truncated\n");
335 file_size = dumpfile(fd, file_info, path, stat_buf);
336 file_info["size"] = encode_int(file_size);
340 return; // error occurred; do not dump file
342 if (file_size != stat_buf.st_size) {
343 fprintf(stderr, "Warning: Size of %s changed during reading\n",
353 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
357 file_info["type"] = string(1, inode_type);
359 metadata << "name: " << uri_encode(path) << "\n";
360 dict_output(metadata, file_info);
363 // Break apart metadata listing if it becomes too large.
364 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
368 void scanfile(const string& path, bool include)
372 struct stat stat_buf;
379 true_path = "/" + path;
381 // Set to true if we should scan through the contents of this directory,
382 // but not actually back files up
383 bool scan_only = false;
385 // Check this file against the include/exclude list to see if it should be
387 for (list<string>::iterator i = includes.begin();
388 i != includes.end(); ++i) {
390 printf("Including %s\n", path.c_str());
395 for (list<string>::iterator i = excludes.begin();
396 i != excludes.end(); ++i) {
398 printf("Excluding %s\n", path.c_str());
403 for (list<string>::iterator i = searches.begin();
404 i != searches.end(); ++i) {
406 printf("Scanning %s\n", path.c_str());
411 if (!include && !scan_only)
414 if (lstat(true_path.c_str(), &stat_buf) < 0) {
415 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
419 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
420 /* Be paranoid when opening the file. We have no guarantee that the
421 * file was not replaced between the stat() call above and the open()
422 * call below, so we might not even be opening a regular file. We
423 * supply flags to open to to guard against various conditions before
424 * we can perform an lstat to check that the file is still a regular
426 * - O_NOFOLLOW: in the event the file was replaced by a symlink
427 * - O_NONBLOCK: prevents open() from blocking if the file was
429 * We also add in O_NOATIME, since this may reduce disk writes (for
430 * inode updates). However, O_NOATIME may result in EPERM, so if the
431 * initial open fails, try again without O_NOATIME. */
432 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
434 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
437 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
441 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
443 flags = fcntl(fd, F_GETFL);
444 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
446 /* Perform the stat call again, and check that we still have a regular
448 if (fstat(fd, &stat_buf) < 0) {
449 fprintf(stderr, "fstat: %m\n");
454 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
455 fprintf(stderr, "file is no longer a regular file!\n");
461 dump_inode(path, true_path, stat_buf, fd);
466 // If we hit a directory, now that we've written the directory itself,
467 // recursively scan the directory.
468 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
469 DIR *dir = opendir(true_path.c_str());
472 fprintf(stderr, "Error: %m\n");
477 vector<string> contents;
478 while ((ent = readdir(dir)) != NULL) {
479 string filename(ent->d_name);
480 if (filename == "." || filename == "..")
482 contents.push_back(filename);
487 sort(contents.begin(), contents.end());
489 for (vector<string>::iterator i = contents.begin();
490 i != contents.end(); ++i) {
491 const string& filename = *i;
493 scanfile(filename, include);
495 scanfile(path + "/" + filename, include);
500 /* Include the specified file path in the backups. Append the path to the
501 * includes list, and to ensure that we actually see the path when scanning the
502 * directory tree, add all the parent directories to the search list, which
503 * means we will scan through the directory listing even if the files
504 * themselves are excluded from being backed up. */
505 void add_include(const char *path)
507 printf("Add: %s\n", path);
508 /* Was an absolute path specified? If so, we'll need to start scanning
509 * from the root directory. Make sure that the user was consistent in
510 * providing either all relative paths or all absolute paths. */
511 if (path[0] == '/') {
512 if (includes.size() > 0 && relative_paths == true) {
514 "Error: Cannot mix relative and absolute paths!\n");
518 relative_paths = false;
520 // Skip over leading '/'
522 } else if (relative_paths == false && path[0] != '/') {
523 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
527 includes.push_back(path);
529 /* Split the specified path into directory components, and ensure that we
530 * descend into all the directories along the path. */
531 const char *slash = path;
536 while ((slash = strchr(slash + 1, '/')) != NULL) {
537 string component(path, slash - path);
538 searches.push_back(component);
542 void usage(const char *program)
546 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
547 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
550 " --dest=PATH path where backup is to be written [REQUIRED]\n"
551 " --exclude=PATH exclude files in PATH from snapshot\n"
552 " --localdb=PATH local backup metadata is stored in PATH\n"
553 " --filter=COMMAND program through which to filter segment data\n"
554 " (defaults to \"bzip2 -c\")\n"
555 " --filter-extension=EXT\n"
556 " string to append to segment files\n"
557 " (defaults to \".bz2\")\n"
558 " --name=NAME optional name for this snapshot\n",
563 int main(int argc, char *argv[])
565 string backup_source = ".";
566 string backup_dest = "";
567 string localdb_dir = "";
568 string backup_name = "";
571 static struct option long_options[] = {
572 {"localdb", 1, 0, 0}, // 0
573 {"exclude", 1, 0, 0}, // 1
574 {"filter", 1, 0, 0}, // 2
575 {"filter-extension", 1, 0, 0}, // 3
576 {"dest", 1, 0, 0}, // 4
577 {"name", 1, 0, 0}, // 5
582 int c = getopt_long(argc, argv, "", long_options, &long_index);
588 switch (long_index) {
590 localdb_dir = optarg;
593 if (optarg[0] != '/')
594 excludes.push_back(optarg);
596 excludes.push_back(optarg + 1);
599 filter_program = optarg;
601 case 3: // --filter-extension
602 filter_extension = optarg;
605 backup_dest = optarg;
608 backup_name = optarg;
611 fprintf(stderr, "Unhandled long option!\n");
620 if (argc < optind + 2) {
625 searches.push_back(".");
626 if (optind == argc) {
629 for (int i = optind; i < argc; i++)
630 add_include(argv[i]);
633 backup_source = argv[optind];
635 if (backup_dest == "") {
637 "Error: Backup destination must be specified with --dest=\n");
642 // Default for --localdb is the same as --dest
643 if (localdb_dir == "") {
644 localdb_dir = backup_dest;
647 // Dump paths for debugging/informational purposes
649 list<string>::const_iterator i;
651 printf("LBS Version: %s\n", lbs_version);
653 printf("--dest=%s\n--localdb=%s\n\n",
654 backup_dest.c_str(), localdb_dir.c_str());
656 printf("Includes:\n");
657 for (i = includes.begin(); i != includes.end(); ++i)
658 printf(" %s\n", i->c_str());
660 printf("Excludes:\n");
661 for (i = excludes.begin(); i != excludes.end(); ++i)
662 printf(" %s\n", i->c_str());
664 printf("Searching:\n");
665 for (i = searches.begin(); i != searches.end(); ++i)
666 printf(" %s\n", i->c_str());
669 tss = new TarSegmentStore(backup_dest);
670 block_buf = new char[LBS_BLOCK_SIZE];
672 /* Store the time when the backup started, so it can be included in the
678 localtime_r(&now, &time_buf);
679 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
681 /* Open the local database which tracks all objects that are stored
682 * remotely, for efficient incrementals. Provide it with the name of this
684 string database_path = localdb_dir + "/localdb.sqlite";
686 db->Open(database_path.c_str(), desc_buf);
688 /* Initialize the stat cache, for skipping over unchanged files. */
689 statcache = new StatCache;
690 statcache->Open(localdb_dir.c_str(), desc_buf);
692 scanfile(".", false);
695 const string md = metadata_root.str();
697 LbsObject *root = new LbsObject;
698 root->set_group("metadata");
699 root->set_data(md.data(), md.size());
702 segment_list.insert(root->get_ref().get_segment());
704 string backup_root = root->get_ref().to_string();
716 /* Write a backup descriptor file, which says which segments are needed and
717 * where to start to restore this snapshot. The filename is based on the
719 string desc_filename = backup_dest + "/snapshot-";
720 if (backup_name.size() > 0)
721 desc_filename += backup_name + "-";
722 desc_filename = desc_filename + desc_buf + ".lbs";
723 std::ofstream descriptor(desc_filename.c_str());
725 descriptor << "Format: LBS Snapshot v0.1\n";
726 descriptor << "Producer: LBS " << lbs_version << "\n";
727 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
728 descriptor << "Date: " << desc_buf << "\n";
729 if (backup_name.size() > 0)
730 descriptor << "Name: " << backup_name << "\n";
731 descriptor << "Root: " << backup_root << "\n";
733 descriptor << "Segments:\n";
734 for (std::set<string>::iterator i = segment_list.begin();
735 i != segment_list.end(); ++i) {
736 descriptor << " " << *i << "\n";