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) {
360 /* Use the reported file size to allocate a buffer large enough to read
361 * the symlink. Allocate slightly more space, so that we ask for more
362 * bytes than we expect and so check for truncation. */
363 buf = new char[stat_buf.st_size + 2];
364 len = readlink(true_path.c_str(), buf, stat_buf.st_size + 1);
366 fprintf(stderr, "error reading symlink: %m\n");
367 } else if (len <= stat_buf.st_size) {
369 file_info["contents"] = uri_encode(buf);
370 } else if (len > stat_buf.st_size) {
371 fprintf(stderr, "error reading symlink: name truncated\n");
379 /* Be paranoid when opening the file. We have no guarantee that the
380 * file was not replaced between the stat() call above and the open()
381 * call below, so we might not even be opening a regular file. That
382 * the file descriptor refers to a regular file is checked in
383 * dumpfile(). But we also supply flags to open to to guard against
384 * various conditions before we can perform that verification:
385 * - O_NOFOLLOW: in the event the file was replaced by a symlink
386 * - O_NONBLOCK: prevents open() from blocking if the file was
388 * We also add in O_NOATIME, since this may reduce disk writes (for
389 * inode updates). However, O_NOATIME may result in EPERM, so if the
390 * initial open fails, try again without O_NOATIME. */
391 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
393 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
396 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
400 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
402 flags = fcntl(fd, F_GETFL);
403 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
405 file_size = dumpfile(fd, file_info, path);
406 file_info["size"] = encode_int(file_size);
410 return; // error occurred; do not dump file
412 if (file_size != stat_buf.st_size) {
413 fprintf(stderr, "Warning: Size of %s changed during reading\n",
424 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
428 file_info["type"] = string(1, inode_type);
430 metadata << "name: " << uri_encode(path) << "\n";
431 dict_output(metadata, file_info);
434 // Break apart metadata listing if it becomes too large.
435 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
438 // If we hit a directory, now that we've written the directory itself,
439 // recursively scan the directory.
441 scandir(path, include);
444 void scandir(const string& path, bool include)
450 true_path = "/" + path;
452 DIR *dir = opendir(true_path.c_str());
455 fprintf(stderr, "Error: %m\n");
460 vector<string> contents;
461 while ((ent = readdir(dir)) != NULL) {
462 string filename(ent->d_name);
463 if (filename == "." || filename == "..")
465 contents.push_back(filename);
468 sort(contents.begin(), contents.end());
470 for (vector<string>::iterator i = contents.begin();
471 i != contents.end(); ++i) {
472 const string& filename = *i;
474 scanfile(filename, include);
476 scanfile(path + "/" + filename, include);
482 /* Include the specified file path in the backups. Append the path to the
483 * includes list, and to ensure that we actually see the path when scanning the
484 * directory tree, add all the parent directories to the search list, which
485 * means we will scan through the directory listing even if the files
486 * themselves are excluded from being backed up. */
487 void add_include(const char *path)
489 printf("Add: %s\n", path);
490 /* Was an absolute path specified? If so, we'll need to start scanning
491 * from the root directory. Make sure that the user was consistent in
492 * providing either all relative paths or all absolute paths. */
493 if (path[0] == '/') {
494 if (includes.size() > 0 && relative_paths == true) {
496 "Error: Cannot mix relative and absolute paths!\n");
500 relative_paths = false;
502 // Skip over leading '/'
504 } else if (relative_paths == false && path[0] != '/') {
505 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
509 includes.push_back(path);
511 /* Split the specified path into directory components, and ensure that we
512 * descend into all the directories along the path. */
513 const char *slash = path;
518 while ((slash = strchr(slash + 1, '/')) != NULL) {
519 string component(path, slash - path);
520 searches.push_back(component);
524 void usage(const char *program)
528 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
529 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
532 " --dest=PATH path where backup is to be written [REQUIRED]\n"
533 " --exclude=PATH exclude files in PATH from snapshot\n"
534 " --localdb=PATH local backup metadata is stored in PATH\n"
535 " --filter=COMMAND program through which to filter segment data\n"
536 " (defaults to \"bzip2 -c\")\n"
537 " --filter-extension=EXT\n"
538 " string to append to segment files\n"
539 " (defaults to \".bz2\")\n",
544 int main(int argc, char *argv[])
546 string backup_source = ".";
547 string backup_dest = "";
548 string localdb_dir = "";
551 static struct option long_options[] = {
552 {"localdb", 1, 0, 0}, // 0
553 {"exclude", 1, 0, 0}, // 1
554 {"filter", 1, 0, 0}, // 2
555 {"filter-extension", 1, 0, 0}, // 3
556 {"dest", 1, 0, 0}, // 4
561 int c = getopt_long(argc, argv, "", long_options, &long_index);
567 switch (long_index) {
569 localdb_dir = optarg;
572 if (optarg[0] != '/')
573 excludes.push_back(optarg);
575 excludes.push_back(optarg + 1);
578 filter_program = optarg;
580 case 3: // --filter-extension
581 filter_extension = optarg;
584 backup_dest = optarg;
587 fprintf(stderr, "Unhandled long option!\n");
596 if (argc < optind + 2) {
601 searches.push_back(".");
602 if (optind == argc) {
605 for (int i = optind; i < argc; i++)
606 add_include(argv[i]);
609 backup_source = argv[optind];
611 if (backup_dest == "") {
613 "Error: Backup destination must be specified with --dest=\n");
618 // Default for --localdb is the same as --dest
619 if (localdb_dir == "") {
620 localdb_dir = backup_dest;
623 // Dump paths for debugging/informational purposes
625 list<string>::const_iterator i;
627 printf("LBS Version: %s\n", lbs_version);
629 printf("--dest=%s\n--localdb=%s\n\n",
630 backup_dest.c_str(), localdb_dir.c_str());
632 printf("Includes:\n");
633 for (i = includes.begin(); i != includes.end(); ++i)
634 printf(" %s\n", i->c_str());
636 printf("Excludes:\n");
637 for (i = excludes.begin(); i != excludes.end(); ++i)
638 printf(" %s\n", i->c_str());
640 printf("Searching:\n");
641 for (i = searches.begin(); i != searches.end(); ++i)
642 printf(" %s\n", i->c_str());
645 tss = new TarSegmentStore(backup_dest);
646 block_buf = new char[LBS_BLOCK_SIZE];
648 /* Store the time when the backup started, so it can be included in the
654 localtime_r(&now, &time_buf);
655 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
657 /* Open the local database which tracks all objects that are stored
658 * remotely, for efficient incrementals. Provide it with the name of this
660 string database_path = localdb_dir + "/localdb.sqlite";
662 db->Open(database_path.c_str(), desc_buf);
664 /* Initialize the stat cache, for skipping over unchanged files. */
665 statcache = new StatCache;
666 statcache->Open(localdb_dir.c_str(), desc_buf);
668 scanfile(".", false);
671 const string md = metadata_root.str();
673 LbsObject *root = new LbsObject;
674 root->set_group("metadata");
675 root->set_data(md.data(), md.size());
678 segment_list.insert(root->get_ref().get_segment());
680 string backup_root = root->get_ref().to_string();
692 /* Write a backup descriptor file, which says which segments are needed and
693 * where to start to restore this snapshot. The filename is based on the
695 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
696 std::ofstream descriptor(desc_filename.c_str());
698 descriptor << "Format: LBS Snapshot v0.1\n";
699 descriptor << "Producer: " << lbs_version << "\n";
700 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
701 descriptor << "Date: " << desc_buf << "\n";
702 descriptor << "Root: " << backup_root << "\n";
704 descriptor << "Segments:\n";
705 for (std::set<string>::iterator i = segment_list.begin();
706 i != segment_list.end(); ++i) {
707 descriptor << " " << *i << "\n";