1 /* Recursively descend the filesystem and visit each file. */
13 #include <sys/types.h>
29 #include "statcache.h"
36 /* Version information. This will be filled in by the Makefile. */
38 #define LBS_VERSION Unknown
40 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
41 #define LBS_STRINGIFY2(s) #s
42 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
44 static TarSegmentStore *tss = NULL;
46 /* Buffer for holding a single block of data read from a file. */
47 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
48 static char *block_buf;
50 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
52 /* Local database, which tracks objects written in this and previous
53 * invocations to help in creating incremental snapshots. */
56 /* Stat cache, which stored data locally to speed the backup process by quickly
57 * skipping files which have not changed. */
60 /* Contents of the root object. This will contain a set of indirect links to
61 * the metadata objects. */
62 std::ostringstream metadata_root;
64 /* Buffer for building up metadata. */
65 std::ostringstream metadata;
67 /* Keep track of all segments which are needed to reconstruct the snapshot. */
68 std::set<string> segment_list;
70 void scandir(const string& path, bool include);
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 size_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 throw IOException("file_read: error reading");
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)
135 struct stat stat_buf;
136 fstat(fd, &stat_buf);
138 list<string> object_list;
140 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
141 fprintf(stderr, "file is no longer a regular file!\n");
145 /* Look up this file in the old stat cache, if we can. If the stat
146 * information indicates that the file has not changed, do not bother
147 * re-reading the entire contents. */
150 if (statcache->Find(path, &stat_buf)) {
152 const list<ObjectReference> &blocks = statcache->get_blocks();
154 /* If any of the blocks in the object have been expired, then we should
155 * fall back to fully reading in the file. */
156 for (list<ObjectReference>::const_iterator i = blocks.begin();
157 i != blocks.end(); ++i) {
158 const ObjectReference &ref = *i;
159 if (!db->IsAvailable(ref)) {
165 /* If everything looks okay, use the cached information */
167 file_info["checksum"] = statcache->get_checksum();
168 for (list<ObjectReference>::const_iterator i = blocks.begin();
169 i != blocks.end(); ++i) {
170 const ObjectReference &ref = *i;
171 object_list.push_back(ref.to_string());
172 segment_list.insert(ref.get_segment());
175 size = stat_buf.st_size;
179 /* If the file is new or changed, we must read in the contents a block at a
186 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
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");
218 o->set_group("data");
220 o->set_data(block_buf, bytes);
223 db->StoreObject(ref, block_csum, bytes, block_age);
227 object_list.push_back(ref.to_string());
228 segment_list.insert(ref.get_segment());
233 file_info["checksum"] = hash.checksum_str();
236 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
238 /* For files that only need to be broken apart into a few objects, store
239 * the list of objects directly. For larger files, store the data
240 * out-of-line and provide a pointer to the indrect object. */
241 if (object_list.size() < 8) {
242 string blocklist = "";
243 for (list<string>::iterator i = object_list.begin();
244 i != object_list.end(); ++i) {
245 if (i != object_list.begin())
249 file_info["data"] = blocklist;
251 string blocklist = "";
252 for (list<string>::iterator i = object_list.begin();
253 i != object_list.end(); ++i) {
254 blocklist += *i + "\n";
257 LbsObject *i = new LbsObject;
258 i->set_group("metadata");
259 i->set_data(blocklist.data(), blocklist.size());
261 file_info["data"] = "@" + i->get_name();
262 segment_list.insert(i->get_ref().get_segment());
269 void scanfile(const string& path, bool include)
273 struct stat stat_buf;
283 true_path = "/" + path;
285 // Set to true if the item is a directory and we should recursively scan
286 bool recurse = false;
288 // Set to true if we should scan through the contents of this directory,
289 // but not actually back files up
290 bool scan_only = false;
292 // Check this file against the include/exclude list to see if it should be
294 for (list<string>::iterator i = includes.begin();
295 i != includes.end(); ++i) {
297 printf("Including %s\n", path.c_str());
302 for (list<string>::iterator i = excludes.begin();
303 i != excludes.end(); ++i) {
305 printf("Excluding %s\n", path.c_str());
310 for (list<string>::iterator i = searches.begin();
311 i != searches.end(); ++i) {
313 printf("Scanning %s\n", path.c_str());
318 if (!include && !scan_only)
321 dictionary file_info;
323 lstat(true_path.c_str(), &stat_buf);
325 printf("%s\n", path.c_str());
327 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
328 file_info["mtime"] = encode_int(stat_buf.st_mtime);
329 file_info["user"] = encode_int(stat_buf.st_uid);
330 file_info["group"] = encode_int(stat_buf.st_gid);
332 struct passwd *pwd = getpwuid(stat_buf.st_uid);
334 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
337 struct group *grp = getgrgid(stat_buf.st_gid);
339 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
344 switch (stat_buf.st_mode & S_IFMT) {
353 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
354 file_info["device"] = encode_int(stat_buf.st_rdev);
359 /* Use the reported file size to allocate a buffer large enough to read
360 * the symlink. Allocate slightly more space, so that we ask for more
361 * bytes than we expect and so check for truncation. */
362 buf = new char[stat_buf.st_size + 2];
363 len = readlink(true_path.c_str(), buf, stat_buf.st_size + 1);
365 fprintf(stderr, "error reading symlink: %m\n");
366 } else if (len <= stat_buf.st_size) {
368 file_info["contents"] = uri_encode(buf);
369 } else if (len > stat_buf.st_size) {
370 fprintf(stderr, "error reading symlink: name truncated\n");
378 /* Be paranoid when opening the file. We have no guarantee that the
379 * file was not replaced between the stat() call above and the open()
380 * call below, so we might not even be opening a regular file. That
381 * the file descriptor refers to a regular file is checked in
382 * dumpfile(). But we also supply flags to open to to guard against
383 * various conditions before we can perform that verification:
384 * - O_NOFOLLOW: in the event the file was replaced by a symlink
385 * - O_NONBLOCK: prevents open() from blocking if the file was
387 * We also add in O_NOATIME, since this may reduce disk writes (for
388 * inode updates). However, O_NOATIME may result in EPERM, so if the
389 * initial open fails, try again without O_NOATIME. */
390 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
392 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
395 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
399 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
401 flags = fcntl(fd, F_GETFL);
402 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
404 file_size = dumpfile(fd, file_info, path);
405 file_info["size"] = encode_int(file_size);
409 return; // error occurred; do not dump file
411 if (file_size != stat_buf.st_size) {
412 fprintf(stderr, "Warning: Size of %s changed during reading\n",
423 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
427 file_info["type"] = string(1, inode_type);
429 metadata << "name: " << uri_encode(path) << "\n";
430 dict_output(metadata, file_info);
433 // Break apart metadata listing if it becomes too large.
434 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
437 // If we hit a directory, now that we've written the directory itself,
438 // recursively scan the directory.
440 scandir(path, include);
443 void scandir(const string& path, bool include)
449 true_path = "/" + path;
451 DIR *dir = opendir(true_path.c_str());
454 fprintf(stderr, "Error: %m\n");
459 vector<string> contents;
460 while ((ent = readdir(dir)) != NULL) {
461 string filename(ent->d_name);
462 if (filename == "." || filename == "..")
464 contents.push_back(filename);
467 sort(contents.begin(), contents.end());
469 for (vector<string>::iterator i = contents.begin();
470 i != contents.end(); ++i) {
471 const string& filename = *i;
473 scanfile(filename, include);
475 scanfile(path + "/" + filename, include);
481 /* Include the specified file path in the backups. Append the path to the
482 * includes list, and to ensure that we actually see the path when scanning the
483 * directory tree, add all the parent directories to the search list, which
484 * means we will scan through the directory listing even if the files
485 * themselves are excluded from being backed up. */
486 void add_include(const char *path)
488 printf("Add: %s\n", path);
489 /* Was an absolute path specified? If so, we'll need to start scanning
490 * from the root directory. Make sure that the user was consistent in
491 * providing either all relative paths or all absolute paths. */
492 if (path[0] == '/') {
493 if (includes.size() > 0 && relative_paths == true) {
495 "Error: Cannot mix relative and absolute paths!\n");
499 relative_paths = false;
501 // Skip over leading '/'
503 } else if (relative_paths == false && path[0] != '/') {
504 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
508 includes.push_back(path);
510 /* Split the specified path into directory components, and ensure that we
511 * descend into all the directories along the path. */
512 const char *slash = path;
517 while ((slash = strchr(slash + 1, '/')) != NULL) {
518 string component(path, slash - path);
519 searches.push_back(component);
523 void usage(const char *program)
527 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
528 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
531 " --dest=PATH path where backup is to be written [REQUIRED]\n"
532 " --exclude=PATH exclude files in PATH from snapshot\n"
533 " --localdb=PATH local backup metadata is stored in PATH\n"
534 " --filter=COMMAND program through which to filter segment data\n"
535 " (defaults to \"bzip2 -c\")\n"
536 " --filter-extension=EXT\n"
537 " string to append to segment files\n"
538 " (defaults to \".bz2\")\n",
543 int main(int argc, char *argv[])
545 string backup_source = ".";
546 string backup_dest = "";
547 string localdb_dir = "";
550 static struct option long_options[] = {
551 {"localdb", 1, 0, 0}, // 0
552 {"exclude", 1, 0, 0}, // 1
553 {"filter", 1, 0, 0}, // 2
554 {"filter-extension", 1, 0, 0}, // 3
555 {"dest", 1, 0, 0}, // 4
560 int c = getopt_long(argc, argv, "", long_options, &long_index);
566 switch (long_index) {
568 localdb_dir = optarg;
571 if (optarg[0] != '/')
572 excludes.push_back(optarg);
574 excludes.push_back(optarg + 1);
577 filter_program = optarg;
579 case 3: // --filter-extension
580 filter_extension = optarg;
583 backup_dest = optarg;
586 fprintf(stderr, "Unhandled long option!\n");
595 if (argc < optind + 2) {
600 searches.push_back(".");
601 if (optind == argc) {
604 for (int i = optind; i < argc; i++)
605 add_include(argv[i]);
608 backup_source = argv[optind];
610 if (backup_dest == "") {
612 "Error: Backup destination must be specified with --dest=\n");
617 // Default for --localdb is the same as --dest
618 if (localdb_dir == "") {
619 localdb_dir = backup_dest;
622 // Dump paths for debugging/informational purposes
624 list<string>::const_iterator i;
626 printf("LBS Version: %s\n", lbs_version);
628 printf("--dest=%s\n--localdb=%s\n\n",
629 backup_dest.c_str(), localdb_dir.c_str());
631 printf("Includes:\n");
632 for (i = includes.begin(); i != includes.end(); ++i)
633 printf(" %s\n", i->c_str());
635 printf("Excludes:\n");
636 for (i = excludes.begin(); i != excludes.end(); ++i)
637 printf(" %s\n", i->c_str());
639 printf("Searching:\n");
640 for (i = searches.begin(); i != searches.end(); ++i)
641 printf(" %s\n", i->c_str());
644 tss = new TarSegmentStore(backup_dest);
645 block_buf = new char[LBS_BLOCK_SIZE];
647 /* Store the time when the backup started, so it can be included in the
653 localtime_r(&now, &time_buf);
654 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
656 /* Open the local database which tracks all objects that are stored
657 * remotely, for efficient incrementals. Provide it with the name of this
659 string database_path = localdb_dir + "/localdb.sqlite";
661 db->Open(database_path.c_str(), desc_buf);
663 /* Initialize the stat cache, for skipping over unchanged files. */
664 statcache = new StatCache;
665 statcache->Open(localdb_dir.c_str(), desc_buf);
667 scanfile(".", false);
670 const string md = metadata_root.str();
672 LbsObject *root = new LbsObject;
673 root->set_group("metadata");
674 root->set_data(md.data(), md.size());
677 segment_list.insert(root->get_ref().get_segment());
679 string backup_root = root->get_ref().to_string();
691 /* Write a backup descriptor file, which says which segments are needed and
692 * where to start to restore this snapshot. The filename is based on the
694 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
695 std::ofstream descriptor(desc_filename.c_str());
697 descriptor << "Format: LBS Snapshot v0.1\n";
698 descriptor << "Producer: " << lbs_version << "\n";
699 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
700 descriptor << "Date: " << desc_buf << "\n";
701 descriptor << "Root: " << backup_root << "\n";
703 descriptor << "Segments:\n";
704 for (std::set<string>::iterator i = segment_list.begin();
705 i != segment_list.end(); ++i) {
706 descriptor << " " << *i << "\n";