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 size_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 throw IOException("file_read: error reading");
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)
136 struct stat stat_buf;
137 fstat(fd, &stat_buf);
139 list<string> object_list;
141 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
142 fprintf(stderr, "file is no longer a regular file!\n");
146 /* Look up this file in the old stat cache, if we can. If the stat
147 * information indicates that the file has not changed, do not bother
148 * re-reading the entire contents. */
151 if (statcache->Find(path, &stat_buf)) {
153 const list<ObjectReference> &blocks = statcache->get_blocks();
155 /* If any of the blocks in the object have been expired, then we should
156 * fall back to fully reading in the file. */
157 for (list<ObjectReference>::const_iterator i = blocks.begin();
158 i != blocks.end(); ++i) {
159 const ObjectReference &ref = *i;
160 if (!db->IsAvailable(ref)) {
166 /* If everything looks okay, use the cached information */
168 file_info["checksum"] = statcache->get_checksum();
169 for (list<ObjectReference>::const_iterator i = blocks.begin();
170 i != blocks.end(); ++i) {
171 const ObjectReference &ref = *i;
172 object_list.push_back(ref.to_string());
173 segment_list.insert(ref.get_segment());
176 size = stat_buf.st_size;
180 /* If the file is new or changed, we must read in the contents a block at a
187 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
191 hash.process(block_buf, bytes);
193 // Either find a copy of this block in an already-existing segment,
194 // or index it so it can be re-used in the future
195 double block_age = 0.0;
196 SHA1Checksum block_hash;
197 block_hash.process(block_buf, bytes);
198 string block_csum = block_hash.checksum_str();
199 ObjectReference ref = db->FindObject(block_csum, bytes);
201 // Store a copy of the object if one does not yet exist
202 if (ref.get_segment().size() == 0) {
203 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, &block_age))
217 o->set_group("compacted");
219 o->set_group("data");
221 o->set_data(block_buf, bytes);
224 db->StoreObject(ref, block_csum, bytes, block_age);
228 object_list.push_back(ref.to_string());
229 segment_list.insert(ref.get_segment());
234 file_info["checksum"] = hash.checksum_str();
237 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
239 /* For files that only need to be broken apart into a few objects, store
240 * the list of objects directly. For larger files, store the data
241 * out-of-line and provide a pointer to the indrect object. */
242 if (object_list.size() < 8) {
243 string blocklist = "";
244 for (list<string>::iterator i = object_list.begin();
245 i != object_list.end(); ++i) {
246 if (i != object_list.begin())
250 file_info["data"] = blocklist;
252 string blocklist = "";
253 for (list<string>::iterator i = object_list.begin();
254 i != object_list.end(); ++i) {
255 blocklist += *i + "\n";
258 LbsObject *i = new LbsObject;
259 i->set_group("metadata");
260 i->set_data(blocklist.data(), blocklist.size());
262 file_info["data"] = "@" + i->get_name();
263 segment_list.insert(i->get_ref().get_segment());
270 void scanfile(const string& path, bool include)
274 struct stat stat_buf;
284 true_path = "/" + path;
286 // Set to true if the item is a directory and we should recursively scan
287 bool recurse = false;
289 // Set to true if we should scan through the contents of this directory,
290 // but not actually back files up
291 bool scan_only = false;
293 // Check this file against the include/exclude list to see if it should be
295 for (list<string>::iterator i = includes.begin();
296 i != includes.end(); ++i) {
298 printf("Including %s\n", path.c_str());
303 for (list<string>::iterator i = excludes.begin();
304 i != excludes.end(); ++i) {
306 printf("Excluding %s\n", path.c_str());
311 for (list<string>::iterator i = searches.begin();
312 i != searches.end(); ++i) {
314 printf("Scanning %s\n", path.c_str());
319 if (!include && !scan_only)
322 dictionary file_info;
324 lstat(true_path.c_str(), &stat_buf);
326 printf("%s\n", path.c_str());
328 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
329 file_info["mtime"] = encode_int(stat_buf.st_mtime);
330 file_info["user"] = encode_int(stat_buf.st_uid);
331 file_info["group"] = encode_int(stat_buf.st_gid);
333 struct passwd *pwd = getpwuid(stat_buf.st_uid);
335 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
338 struct group *grp = getgrgid(stat_buf.st_gid);
340 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
345 switch (stat_buf.st_mode & S_IFMT) {
354 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
355 file_info["device"] = encode_int(major(stat_buf.st_rdev))
356 + "/" + encode_int(minor(stat_buf.st_rdev));
361 /* Use the reported file size to allocate a buffer large enough to read
362 * the symlink. Allocate slightly more space, so that we ask for more
363 * bytes than we expect and so check for truncation. */
364 buf = new char[stat_buf.st_size + 2];
365 len = readlink(true_path.c_str(), buf, stat_buf.st_size + 1);
367 fprintf(stderr, "error reading symlink: %m\n");
368 } else if (len <= stat_buf.st_size) {
370 file_info["contents"] = uri_encode(buf);
371 } else if (len > stat_buf.st_size) {
372 fprintf(stderr, "error reading symlink: name truncated\n");
380 /* Be paranoid when opening the file. We have no guarantee that the
381 * file was not replaced between the stat() call above and the open()
382 * call below, so we might not even be opening a regular file. That
383 * the file descriptor refers to a regular file is checked in
384 * dumpfile(). But we also supply flags to open to to guard against
385 * various conditions before we can perform that verification:
386 * - O_NOFOLLOW: in the event the file was replaced by a symlink
387 * - O_NONBLOCK: prevents open() from blocking if the file was
389 * We also add in O_NOATIME, since this may reduce disk writes (for
390 * inode updates). However, O_NOATIME may result in EPERM, so if the
391 * initial open fails, try again without O_NOATIME. */
392 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
394 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
397 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
401 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
403 flags = fcntl(fd, F_GETFL);
404 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
406 file_size = dumpfile(fd, file_info, path);
407 file_info["size"] = encode_int(file_size);
411 return; // error occurred; do not dump file
413 if (file_size != stat_buf.st_size) {
414 fprintf(stderr, "Warning: Size of %s changed during reading\n",
425 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
429 file_info["type"] = string(1, inode_type);
431 metadata << "name: " << uri_encode(path) << "\n";
432 dict_output(metadata, file_info);
435 // Break apart metadata listing if it becomes too large.
436 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
439 // If we hit a directory, now that we've written the directory itself,
440 // recursively scan the directory.
442 scandir(path, include);
445 void scandir(const string& path, bool include)
451 true_path = "/" + path;
453 DIR *dir = opendir(true_path.c_str());
456 fprintf(stderr, "Error: %m\n");
461 vector<string> contents;
462 while ((ent = readdir(dir)) != NULL) {
463 string filename(ent->d_name);
464 if (filename == "." || filename == "..")
466 contents.push_back(filename);
469 sort(contents.begin(), contents.end());
471 for (vector<string>::iterator i = contents.begin();
472 i != contents.end(); ++i) {
473 const string& filename = *i;
475 scanfile(filename, include);
477 scanfile(path + "/" + filename, include);
483 /* Include the specified file path in the backups. Append the path to the
484 * includes list, and to ensure that we actually see the path when scanning the
485 * directory tree, add all the parent directories to the search list, which
486 * means we will scan through the directory listing even if the files
487 * themselves are excluded from being backed up. */
488 void add_include(const char *path)
490 printf("Add: %s\n", path);
491 /* Was an absolute path specified? If so, we'll need to start scanning
492 * from the root directory. Make sure that the user was consistent in
493 * providing either all relative paths or all absolute paths. */
494 if (path[0] == '/') {
495 if (includes.size() > 0 && relative_paths == true) {
497 "Error: Cannot mix relative and absolute paths!\n");
501 relative_paths = false;
503 // Skip over leading '/'
505 } else if (relative_paths == false && path[0] != '/') {
506 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
510 includes.push_back(path);
512 /* Split the specified path into directory components, and ensure that we
513 * descend into all the directories along the path. */
514 const char *slash = path;
519 while ((slash = strchr(slash + 1, '/')) != NULL) {
520 string component(path, slash - path);
521 searches.push_back(component);
525 void usage(const char *program)
529 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
530 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
533 " --dest=PATH path where backup is to be written [REQUIRED]\n"
534 " --exclude=PATH exclude files in PATH from snapshot\n"
535 " --localdb=PATH local backup metadata is stored in PATH\n"
536 " --filter=COMMAND program through which to filter segment data\n"
537 " (defaults to \"bzip2 -c\")\n"
538 " --filter-extension=EXT\n"
539 " string to append to segment files\n"
540 " (defaults to \".bz2\")\n",
545 int main(int argc, char *argv[])
547 string backup_source = ".";
548 string backup_dest = "";
549 string localdb_dir = "";
552 static struct option long_options[] = {
553 {"localdb", 1, 0, 0}, // 0
554 {"exclude", 1, 0, 0}, // 1
555 {"filter", 1, 0, 0}, // 2
556 {"filter-extension", 1, 0, 0}, // 3
557 {"dest", 1, 0, 0}, // 4
562 int c = getopt_long(argc, argv, "", long_options, &long_index);
568 switch (long_index) {
570 localdb_dir = optarg;
573 if (optarg[0] != '/')
574 excludes.push_back(optarg);
576 excludes.push_back(optarg + 1);
579 filter_program = optarg;
581 case 3: // --filter-extension
582 filter_extension = optarg;
585 backup_dest = optarg;
588 fprintf(stderr, "Unhandled long option!\n");
597 if (argc < optind + 2) {
602 searches.push_back(".");
603 if (optind == argc) {
606 for (int i = optind; i < argc; i++)
607 add_include(argv[i]);
610 backup_source = argv[optind];
612 if (backup_dest == "") {
614 "Error: Backup destination must be specified with --dest=\n");
619 // Default for --localdb is the same as --dest
620 if (localdb_dir == "") {
621 localdb_dir = backup_dest;
624 // Dump paths for debugging/informational purposes
626 list<string>::const_iterator i;
628 printf("LBS Version: %s\n", lbs_version);
630 printf("--dest=%s\n--localdb=%s\n\n",
631 backup_dest.c_str(), localdb_dir.c_str());
633 printf("Includes:\n");
634 for (i = includes.begin(); i != includes.end(); ++i)
635 printf(" %s\n", i->c_str());
637 printf("Excludes:\n");
638 for (i = excludes.begin(); i != excludes.end(); ++i)
639 printf(" %s\n", i->c_str());
641 printf("Searching:\n");
642 for (i = searches.begin(); i != searches.end(); ++i)
643 printf(" %s\n", i->c_str());
646 tss = new TarSegmentStore(backup_dest);
647 block_buf = new char[LBS_BLOCK_SIZE];
649 /* Store the time when the backup started, so it can be included in the
655 localtime_r(&now, &time_buf);
656 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
658 /* Open the local database which tracks all objects that are stored
659 * remotely, for efficient incrementals. Provide it with the name of this
661 string database_path = localdb_dir + "/localdb.sqlite";
663 db->Open(database_path.c_str(), desc_buf);
665 /* Initialize the stat cache, for skipping over unchanged files. */
666 statcache = new StatCache;
667 statcache->Open(localdb_dir.c_str(), desc_buf);
669 scanfile(".", false);
672 const string md = metadata_root.str();
674 LbsObject *root = new LbsObject;
675 root->set_group("metadata");
676 root->set_data(md.data(), md.size());
679 segment_list.insert(root->get_ref().get_segment());
681 string backup_root = root->get_ref().to_string();
693 /* Write a backup descriptor file, which says which segments are needed and
694 * where to start to restore this snapshot. The filename is based on the
696 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
697 std::ofstream descriptor(desc_filename.c_str());
699 descriptor << "Format: LBS Snapshot v0.1\n";
700 descriptor << "Producer: " << lbs_version << "\n";
701 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
702 descriptor << "Date: " << desc_buf << "\n";
703 descriptor << "Root: " << backup_root << "\n";
705 descriptor << "Segments:\n";
706 for (std::set<string>::iterator i = segment_list.begin();
707 i != segment_list.end(); ++i) {
708 descriptor << " " << *i << "\n";