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 void scandir(const string& path, bool include);
73 /* Selection of files to include/exclude in the snapshot. */
74 std::list<string> includes; // Paths in which files should be saved
75 std::list<string> excludes; // Paths which will not be saved
76 std::list<string> searches; // Directories we don't want to save, but
77 // do want to descend searching for data
80 bool relative_paths = true;
82 /* Ensure contents of metadata are flushed to an object. */
85 string m = metadata.str();
89 /* Write current metadata information to a new object. */
90 LbsObject *meta = new LbsObject;
91 meta->set_group("metadata");
92 meta->set_data(m.data(), m.size());
96 /* Write a reference to this block in the root. */
97 ObjectReference ref = meta->get_ref();
98 metadata_root << "@" << ref.to_string() << "\n";
99 segment_list.insert(ref.get_segment());
106 /* Read data from a file descriptor and return the amount of data read. A
107 * short read (less than the requested size) will only occur if end-of-file is
109 ssize_t file_read(int fd, char *buf, size_t maxlen)
111 size_t bytes_read = 0;
114 ssize_t res = read(fd, buf, maxlen);
118 fprintf(stderr, "error reading file: %m\n");
120 } else if (res == 0) {
132 /* Read the contents of a file (specified by an open file descriptor) and copy
133 * the data to the store. Returns the size of the file (number of bytes
134 * dumped), or -1 on error. */
135 int64_t dumpfile(int fd, dictionary &file_info, const string &path)
137 struct stat stat_buf;
139 if (fstat(fd, &stat_buf) < 0) {
140 fprintf(stderr, "fstat: %m\n");
145 list<string> object_list;
147 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
148 fprintf(stderr, "file is no longer a regular file!\n");
152 /* Look up this file in the old stat cache, if we can. If the stat
153 * information indicates that the file has not changed, do not bother
154 * re-reading the entire contents. */
157 if (statcache->Find(path, &stat_buf)) {
159 const list<ObjectReference> &blocks = statcache->get_blocks();
161 /* If any of the blocks in the object have been expired, then we should
162 * fall back to fully reading in the file. */
163 for (list<ObjectReference>::const_iterator i = blocks.begin();
164 i != blocks.end(); ++i) {
165 const ObjectReference &ref = *i;
166 if (!db->IsAvailable(ref)) {
172 /* If everything looks okay, use the cached information */
174 file_info["checksum"] = statcache->get_checksum();
175 for (list<ObjectReference>::const_iterator i = blocks.begin();
176 i != blocks.end(); ++i) {
177 const ObjectReference &ref = *i;
178 object_list.push_back(ref.to_string());
179 segment_list.insert(ref.get_segment());
182 size = stat_buf.st_size;
186 /* If the file is new or changed, we must read in the contents a block at a
193 ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
197 fprintf(stderr, "Backup contents for %s may be incorrect\n",
202 hash.process(block_buf, bytes);
204 // Either find a copy of this block in an already-existing segment,
205 // or index it so it can be re-used in the future
206 double block_age = 0.0;
207 SHA1Checksum block_hash;
208 block_hash.process(block_buf, bytes);
209 string block_csum = block_hash.checksum_str();
210 ObjectReference ref = db->FindObject(block_csum, bytes);
212 // Store a copy of the object if one does not yet exist
213 if (ref.get_segment().size() == 0) {
214 LbsObject *o = new LbsObject;
216 /* We might still have seen this checksum before, if the object
217 * was stored at some time in the past, but we have decided to
218 * clean the segment the object was originally stored in
219 * (FindObject will not return such objects). When rewriting
220 * the object contents, put it in a separate group, so that old
221 * objects get grouped together. The hope is that these old
222 * objects will continue to be used in the future, and we
223 * obtain segments which will continue to be well-utilized.
224 * Additionally, keep track of the age of the data by looking
225 * up the age of the block which was expired and using that
226 * instead of the current time. */
227 if (db->IsOldObject(block_csum, bytes, &block_age))
228 o->set_group("compacted");
230 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());
245 file_info["checksum"] = hash.checksum_str();
248 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
250 /* For files that only need to be broken apart into a few objects, store
251 * the list of objects directly. For larger files, store the data
252 * out-of-line and provide a pointer to the indrect object. */
253 if (object_list.size() < 8) {
254 string blocklist = "";
255 for (list<string>::iterator i = object_list.begin();
256 i != object_list.end(); ++i) {
257 if (i != object_list.begin())
261 file_info["data"] = blocklist;
263 string blocklist = "";
264 for (list<string>::iterator i = object_list.begin();
265 i != object_list.end(); ++i) {
266 blocklist += *i + "\n";
269 LbsObject *i = new LbsObject;
270 i->set_group("metadata");
271 i->set_data(blocklist.data(), blocklist.size());
273 file_info["data"] = "@" + i->get_name();
274 segment_list.insert(i->get_ref().get_segment());
281 void scanfile(const string& path, bool include)
285 struct stat stat_buf;
295 true_path = "/" + path;
297 // Set to true if the item is a directory and we should recursively scan
298 bool recurse = false;
300 // Set to true if we should scan through the contents of this directory,
301 // but not actually back files up
302 bool scan_only = false;
304 // Check this file against the include/exclude list to see if it should be
306 for (list<string>::iterator i = includes.begin();
307 i != includes.end(); ++i) {
309 printf("Including %s\n", path.c_str());
314 for (list<string>::iterator i = excludes.begin();
315 i != excludes.end(); ++i) {
317 printf("Excluding %s\n", path.c_str());
322 for (list<string>::iterator i = searches.begin();
323 i != searches.end(); ++i) {
325 printf("Scanning %s\n", path.c_str());
330 if (!include && !scan_only)
333 dictionary file_info;
335 if (lstat(true_path.c_str(), &stat_buf) < 0) {
336 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
340 printf("%s\n", path.c_str());
342 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
343 file_info["mtime"] = encode_int(stat_buf.st_mtime);
344 file_info["user"] = encode_int(stat_buf.st_uid);
345 file_info["group"] = encode_int(stat_buf.st_gid);
347 struct passwd *pwd = getpwuid(stat_buf.st_uid);
349 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
352 struct group *grp = getgrgid(stat_buf.st_gid);
354 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
359 switch (stat_buf.st_mode & S_IFMT) {
368 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
369 file_info["device"] = encode_int(major(stat_buf.st_rdev))
370 + "/" + encode_int(minor(stat_buf.st_rdev));
375 /* Use the reported file size to allocate a buffer large enough to read
376 * the symlink. Allocate slightly more space, so that we ask for more
377 * bytes than we expect and so check for truncation. */
378 buf = new char[stat_buf.st_size + 2];
379 len = readlink(true_path.c_str(), buf, stat_buf.st_size + 1);
381 fprintf(stderr, "error reading symlink: %m\n");
382 } else if (len <= stat_buf.st_size) {
384 file_info["contents"] = uri_encode(buf);
385 } else if (len > stat_buf.st_size) {
386 fprintf(stderr, "error reading symlink: name truncated\n");
394 /* Be paranoid when opening the file. We have no guarantee that the
395 * file was not replaced between the stat() call above and the open()
396 * call below, so we might not even be opening a regular file. That
397 * the file descriptor refers to a regular file is checked in
398 * dumpfile(). But we also supply flags to open to to guard against
399 * various conditions before we can perform that verification:
400 * - O_NOFOLLOW: in the event the file was replaced by a symlink
401 * - O_NONBLOCK: prevents open() from blocking if the file was
403 * We also add in O_NOATIME, since this may reduce disk writes (for
404 * inode updates). However, O_NOATIME may result in EPERM, so if the
405 * initial open fails, try again without O_NOATIME. */
406 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
408 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
411 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
415 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
417 flags = fcntl(fd, F_GETFL);
418 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
420 file_size = dumpfile(fd, file_info, path);
421 file_info["size"] = encode_int(file_size);
425 return; // error occurred; do not dump file
427 if (file_size != stat_buf.st_size) {
428 fprintf(stderr, "Warning: Size of %s changed during reading\n",
439 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
443 file_info["type"] = string(1, inode_type);
445 metadata << "name: " << uri_encode(path) << "\n";
446 dict_output(metadata, file_info);
449 // Break apart metadata listing if it becomes too large.
450 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
453 // If we hit a directory, now that we've written the directory itself,
454 // recursively scan the directory.
456 scandir(path, include);
459 void scandir(const string& path, bool include)
465 true_path = "/" + path;
467 DIR *dir = opendir(true_path.c_str());
470 fprintf(stderr, "Error: %m\n");
475 vector<string> contents;
476 while ((ent = readdir(dir)) != NULL) {
477 string filename(ent->d_name);
478 if (filename == "." || filename == "..")
480 contents.push_back(filename);
485 sort(contents.begin(), contents.end());
487 for (vector<string>::iterator i = contents.begin();
488 i != contents.end(); ++i) {
489 const string& filename = *i;
491 scanfile(filename, include);
493 scanfile(path + "/" + filename, include);
497 /* Include the specified file path in the backups. Append the path to the
498 * includes list, and to ensure that we actually see the path when scanning the
499 * directory tree, add all the parent directories to the search list, which
500 * means we will scan through the directory listing even if the files
501 * themselves are excluded from being backed up. */
502 void add_include(const char *path)
504 printf("Add: %s\n", path);
505 /* Was an absolute path specified? If so, we'll need to start scanning
506 * from the root directory. Make sure that the user was consistent in
507 * providing either all relative paths or all absolute paths. */
508 if (path[0] == '/') {
509 if (includes.size() > 0 && relative_paths == true) {
511 "Error: Cannot mix relative and absolute paths!\n");
515 relative_paths = false;
517 // Skip over leading '/'
519 } else if (relative_paths == false && path[0] != '/') {
520 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
524 includes.push_back(path);
526 /* Split the specified path into directory components, and ensure that we
527 * descend into all the directories along the path. */
528 const char *slash = path;
533 while ((slash = strchr(slash + 1, '/')) != NULL) {
534 string component(path, slash - path);
535 searches.push_back(component);
539 void usage(const char *program)
543 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
544 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
547 " --dest=PATH path where backup is to be written [REQUIRED]\n"
548 " --exclude=PATH exclude files in PATH from snapshot\n"
549 " --localdb=PATH local backup metadata is stored in PATH\n"
550 " --filter=COMMAND program through which to filter segment data\n"
551 " (defaults to \"bzip2 -c\")\n"
552 " --filter-extension=EXT\n"
553 " string to append to segment files\n"
554 " (defaults to \".bz2\")\n",
559 int main(int argc, char *argv[])
561 string backup_source = ".";
562 string backup_dest = "";
563 string localdb_dir = "";
566 static struct option long_options[] = {
567 {"localdb", 1, 0, 0}, // 0
568 {"exclude", 1, 0, 0}, // 1
569 {"filter", 1, 0, 0}, // 2
570 {"filter-extension", 1, 0, 0}, // 3
571 {"dest", 1, 0, 0}, // 4
576 int c = getopt_long(argc, argv, "", long_options, &long_index);
582 switch (long_index) {
584 localdb_dir = optarg;
587 if (optarg[0] != '/')
588 excludes.push_back(optarg);
590 excludes.push_back(optarg + 1);
593 filter_program = optarg;
595 case 3: // --filter-extension
596 filter_extension = optarg;
599 backup_dest = optarg;
602 fprintf(stderr, "Unhandled long option!\n");
611 if (argc < optind + 2) {
616 searches.push_back(".");
617 if (optind == argc) {
620 for (int i = optind; i < argc; i++)
621 add_include(argv[i]);
624 backup_source = argv[optind];
626 if (backup_dest == "") {
628 "Error: Backup destination must be specified with --dest=\n");
633 // Default for --localdb is the same as --dest
634 if (localdb_dir == "") {
635 localdb_dir = backup_dest;
638 // Dump paths for debugging/informational purposes
640 list<string>::const_iterator i;
642 printf("LBS Version: %s\n", lbs_version);
644 printf("--dest=%s\n--localdb=%s\n\n",
645 backup_dest.c_str(), localdb_dir.c_str());
647 printf("Includes:\n");
648 for (i = includes.begin(); i != includes.end(); ++i)
649 printf(" %s\n", i->c_str());
651 printf("Excludes:\n");
652 for (i = excludes.begin(); i != excludes.end(); ++i)
653 printf(" %s\n", i->c_str());
655 printf("Searching:\n");
656 for (i = searches.begin(); i != searches.end(); ++i)
657 printf(" %s\n", i->c_str());
660 tss = new TarSegmentStore(backup_dest);
661 block_buf = new char[LBS_BLOCK_SIZE];
663 /* Store the time when the backup started, so it can be included in the
669 localtime_r(&now, &time_buf);
670 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
672 /* Open the local database which tracks all objects that are stored
673 * remotely, for efficient incrementals. Provide it with the name of this
675 string database_path = localdb_dir + "/localdb.sqlite";
677 db->Open(database_path.c_str(), desc_buf);
679 /* Initialize the stat cache, for skipping over unchanged files. */
680 statcache = new StatCache;
681 statcache->Open(localdb_dir.c_str(), desc_buf);
683 scanfile(".", false);
686 const string md = metadata_root.str();
688 LbsObject *root = new LbsObject;
689 root->set_group("metadata");
690 root->set_data(md.data(), md.size());
693 segment_list.insert(root->get_ref().get_segment());
695 string backup_root = root->get_ref().to_string();
707 /* Write a backup descriptor file, which says which segments are needed and
708 * where to start to restore this snapshot. The filename is based on the
710 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
711 std::ofstream descriptor(desc_filename.c_str());
713 descriptor << "Format: LBS Snapshot v0.1\n";
714 descriptor << "Producer: LBS " << lbs_version << "\n";
715 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
716 descriptor << "Date: " << desc_buf << "\n";
717 descriptor << "Root: " << backup_root << "\n";
719 descriptor << "Segments:\n";
720 for (std::set<string>::iterator i = segment_list.begin();
721 i != segment_list.end(); ++i) {
722 descriptor << " " << *i << "\n";