1 /* Recursively descend the filesystem and visit each file. */
13 #include <sys/types.h>
29 #include "statcache.h"
36 static TarSegmentStore *tss = NULL;
38 /* Buffer for holding a single block of data read from a file. */
39 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
40 static char *block_buf;
42 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
44 /* Local database, which tracks objects written in this and previous
45 * invocations to help in creating incremental snapshots. */
48 /* Stat cache, which stored data locally to speed the backup process by quickly
49 * skipping files which have not changed. */
52 /* Contents of the root object. This will contain a set of indirect links to
53 * the metadata objects. */
54 std::ostringstream metadata_root;
56 /* Buffer for building up metadata. */
57 std::ostringstream metadata;
59 /* Keep track of all segments which are needed to reconstruct the snapshot. */
60 std::set<string> segment_list;
62 void scandir(const string& path, bool include);
64 /* Selection of files to include/exclude in the snapshot. */
65 std::list<string> includes; // Paths in which files should be saved
66 std::list<string> excludes; // Paths which will not be saved
67 std::list<string> searches; // Directories we don't want to save, but
68 // do want to descend searching for data
71 bool relative_paths = true;
73 /* Ensure contents of metadata are flushed to an object. */
76 string m = metadata.str();
80 /* Write current metadata information to a new object. */
81 LbsObject *meta = new LbsObject;
82 meta->set_group("metadata");
83 meta->set_data(m.data(), m.size());
87 /* Write a reference to this block in the root. */
88 ObjectReference ref = meta->get_ref();
89 metadata_root << "@" << ref.to_string() << "\n";
90 segment_list.insert(ref.get_segment());
97 /* Read data from a file descriptor and return the amount of data read. A
98 * short read (less than the requested size) will only occur if end-of-file is
100 size_t file_read(int fd, char *buf, size_t maxlen)
102 size_t bytes_read = 0;
105 ssize_t res = read(fd, buf, maxlen);
109 throw IOException("file_read: error reading");
110 } else if (res == 0) {
122 /* Read the contents of a file (specified by an open file descriptor) and copy
123 * the data to the store. Returns the size of the file (number of bytes
124 * dumped), or -1 on error. */
125 int64_t dumpfile(int fd, dictionary &file_info, const string &path)
127 struct stat stat_buf;
128 fstat(fd, &stat_buf);
130 list<string> object_list;
132 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
133 fprintf(stderr, "file is no longer a regular file!\n");
137 /* Look up this file in the old stat cache, if we can. If the stat
138 * information indicates that the file has not changed, do not bother
139 * re-reading the entire contents. */
142 if (statcache->Find(path, &stat_buf)) {
144 const list<ObjectReference> &blocks = statcache->get_blocks();
146 /* If any of the blocks in the object have been expired, then we should
147 * fall back to fully reading in the file. */
148 for (list<ObjectReference>::const_iterator i = blocks.begin();
149 i != blocks.end(); ++i) {
150 const ObjectReference &ref = *i;
151 if (!db->IsAvailable(ref)) {
157 /* If everything looks okay, use the cached information */
159 file_info["checksum"] = statcache->get_checksum();
160 for (list<ObjectReference>::const_iterator i = blocks.begin();
161 i != blocks.end(); ++i) {
162 const ObjectReference &ref = *i;
163 object_list.push_back(ref.to_string());
164 segment_list.insert(ref.get_segment());
167 size = stat_buf.st_size;
171 /* If the file is new or changed, we must read in the contents a block at a
178 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
182 hash.process(block_buf, bytes);
184 // Either find a copy of this block in an already-existing segment,
185 // or index it so it can be re-used in the future
186 double block_age = 0.0;
187 SHA1Checksum block_hash;
188 block_hash.process(block_buf, bytes);
189 string block_csum = block_hash.checksum_str();
190 ObjectReference ref = db->FindObject(block_csum, bytes);
192 // Store a copy of the object if one does not yet exist
193 if (ref.get_segment().size() == 0) {
194 LbsObject *o = new LbsObject;
196 /* We might still have seen this checksum before, if the object
197 * was stored at some time in the past, but we have decided to
198 * clean the segment the object was originally stored in
199 * (FindObject will not return such objects). When rewriting
200 * the object contents, put it in a separate group, so that old
201 * objects get grouped together. The hope is that these old
202 * objects will continue to be used in the future, and we
203 * obtain segments which will continue to be well-utilized.
204 * Additionally, keep track of the age of the data by looking
205 * up the age of the block which was expired and using that
206 * instead of the current time. */
207 if (db->IsOldObject(block_csum, bytes, &block_age))
208 o->set_group("compacted");
210 o->set_group("data");
212 o->set_data(block_buf, bytes);
215 db->StoreObject(ref, block_csum, bytes, block_age);
219 object_list.push_back(ref.to_string());
220 segment_list.insert(ref.get_segment());
225 file_info["checksum"] = hash.checksum_str();
228 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
230 /* For files that only need to be broken apart into a few objects, store
231 * the list of objects directly. For larger files, store the data
232 * out-of-line and provide a pointer to the indrect object. */
233 if (object_list.size() < 8) {
234 string blocklist = "";
235 for (list<string>::iterator i = object_list.begin();
236 i != object_list.end(); ++i) {
237 if (i != object_list.begin())
241 file_info["data"] = blocklist;
243 string blocklist = "";
244 for (list<string>::iterator i = object_list.begin();
245 i != object_list.end(); ++i) {
246 blocklist += *i + "\n";
249 LbsObject *i = new LbsObject;
250 i->set_group("metadata");
251 i->set_data(blocklist.data(), blocklist.size());
253 file_info["data"] = "@" + i->get_name();
254 segment_list.insert(i->get_ref().get_segment());
261 void scanfile(const string& path, bool include)
265 struct stat stat_buf;
275 true_path = "/" + path;
277 // Set to true if the item is a directory and we should recursively scan
278 bool recurse = false;
280 // Set to true if we should scan through the contents of this directory,
281 // but not actually back files up
282 bool scan_only = false;
284 // Check this file against the include/exclude list to see if it should be
286 for (list<string>::iterator i = includes.begin();
287 i != includes.end(); ++i) {
289 printf("Including %s\n", path.c_str());
294 for (list<string>::iterator i = excludes.begin();
295 i != excludes.end(); ++i) {
297 printf("Excluding %s\n", path.c_str());
302 for (list<string>::iterator i = searches.begin();
303 i != searches.end(); ++i) {
305 printf("Scanning %s\n", path.c_str());
310 if (!include && !scan_only)
313 dictionary file_info;
315 lstat(true_path.c_str(), &stat_buf);
317 printf("%s\n", path.c_str());
319 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
320 file_info["mtime"] = encode_int(stat_buf.st_mtime);
321 file_info["user"] = encode_int(stat_buf.st_uid);
322 file_info["group"] = encode_int(stat_buf.st_gid);
324 struct passwd *pwd = getpwuid(stat_buf.st_uid);
326 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
329 struct group *grp = getgrgid(stat_buf.st_gid);
331 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
336 switch (stat_buf.st_mode & S_IFMT) {
352 /* Use the reported file size to allocate a buffer large enough to read
353 * the symlink. Allocate slightly more space, so that we ask for more
354 * bytes than we expect and so check for truncation. */
355 buf = new char[stat_buf.st_size + 2];
356 len = readlink(true_path.c_str(), buf, stat_buf.st_size + 1);
358 fprintf(stderr, "error reading symlink: %m\n");
359 } else if (len <= stat_buf.st_size) {
361 file_info["contents"] = uri_encode(buf);
362 } else if (len > stat_buf.st_size) {
363 fprintf(stderr, "error reading symlink: name truncated\n");
371 /* Be paranoid when opening the file. We have no guarantee that the
372 * file was not replaced between the stat() call above and the open()
373 * call below, so we might not even be opening a regular file. That
374 * the file descriptor refers to a regular file is checked in
375 * dumpfile(). But we also supply flags to open to to guard against
376 * various conditions before we can perform that verification:
377 * - O_NOFOLLOW: in the event the file was replaced by a symlink
378 * - O_NONBLOCK: prevents open() from blocking if the file was
380 * We also add in O_NOATIME, since this may reduce disk writes (for
381 * inode updates). However, O_NOATIME may result in EPERM, so if the
382 * initial open fails, try again without O_NOATIME. */
383 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
385 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
388 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
392 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
394 flags = fcntl(fd, F_GETFL);
395 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
397 file_size = dumpfile(fd, file_info, path);
398 file_info["size"] = encode_int(file_size);
402 return; // error occurred; do not dump file
404 if (file_size != stat_buf.st_size) {
405 fprintf(stderr, "Warning: Size of %s changed during reading\n",
416 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
420 file_info["type"] = string(1, inode_type);
422 metadata << "name: " << uri_encode(path) << "\n";
423 dict_output(metadata, file_info);
426 // Break apart metadata listing if it becomes too large.
427 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
430 // If we hit a directory, now that we've written the directory itself,
431 // recursively scan the directory.
433 scandir(path, include);
436 void scandir(const string& path, bool include)
442 true_path = "/" + path;
444 DIR *dir = opendir(true_path.c_str());
447 fprintf(stderr, "Error: %m\n");
452 vector<string> contents;
453 while ((ent = readdir(dir)) != NULL) {
454 string filename(ent->d_name);
455 if (filename == "." || filename == "..")
457 contents.push_back(filename);
460 sort(contents.begin(), contents.end());
462 for (vector<string>::iterator i = contents.begin();
463 i != contents.end(); ++i) {
464 const string& filename = *i;
466 scanfile(filename, include);
468 scanfile(path + "/" + filename, include);
474 /* Include the specified file path in the backups. Append the path to the
475 * includes list, and to ensure that we actually see the path when scanning the
476 * directory tree, add all the parent directories to the search list, which
477 * means we will scan through the directory listing even if the files
478 * themselves are excluded from being backed up. */
479 void add_include(const char *path)
481 printf("Add: %s\n", path);
482 /* Was an absolute path specified? If so, we'll need to start scanning
483 * from the root directory. Make sure that the user was consistent in
484 * providing either all relative paths or all absolute paths. */
485 if (path[0] == '/') {
486 if (includes.size() > 0 && relative_paths == true) {
488 "Error: Cannot mix relative and absolute paths!\n");
492 relative_paths = false;
494 // Skip over leading '/'
496 } else if (relative_paths == false && path[0] != '/') {
497 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
501 includes.push_back(path);
503 /* Split the specified path into directory components, and ensure that we
504 * descend into all the directories along the path. */
505 const char *slash = path;
510 while ((slash = strchr(slash + 1, '/')) != NULL) {
511 string component(path, slash - path);
512 searches.push_back(component);
516 void usage(const char *program)
520 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
521 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
524 " --dest=PATH path where backup is to be written [REQUIRED]\n"
525 " --exclude=PATH exclude files in PATH from snapshot\n"
526 " --localdb=PATH local backup metadata is stored in PATH\n"
527 " --filter=COMMAND program through which to filter segment data\n"
528 " (defaults to \"bzip2 -c\")\n"
529 " --filter-extension=EXT\n"
530 " string to append to segment files\n"
531 " (defaults to \".bz2\")\n",
536 int main(int argc, char *argv[])
538 string backup_source = ".";
539 string backup_dest = "";
540 string localdb_dir = "";
543 static struct option long_options[] = {
544 {"localdb", 1, 0, 0}, // 0
545 {"exclude", 1, 0, 0}, // 1
546 {"filter", 1, 0, 0}, // 2
547 {"filter-extension", 1, 0, 0}, // 3
548 {"dest", 1, 0, 0}, // 4
553 int c = getopt_long(argc, argv, "", long_options, &long_index);
559 switch (long_index) {
561 localdb_dir = optarg;
564 if (optarg[0] != '/')
565 excludes.push_back(optarg);
567 excludes.push_back(optarg + 1);
570 filter_program = optarg;
572 case 3: // --filter-extension
573 filter_extension = optarg;
576 backup_dest = optarg;
579 fprintf(stderr, "Unhandled long option!\n");
588 if (argc < optind + 2) {
593 searches.push_back(".");
594 if (optind == argc) {
597 for (int i = optind; i < argc; i++)
598 add_include(argv[i]);
601 backup_source = argv[optind];
603 if (backup_dest == "") {
605 "Error: Backup destination must be specified with --dest=\n");
610 // Default for --localdb is the same as --dest
611 if (localdb_dir == "") {
612 localdb_dir = backup_dest;
615 // Dump paths for debugging/informational purposes
617 list<string>::const_iterator i;
619 printf("--dest=%s\n--localdb=%s\n\n",
620 backup_dest.c_str(), localdb_dir.c_str());
622 printf("Includes:\n");
623 for (i = includes.begin(); i != includes.end(); ++i)
624 printf(" %s\n", i->c_str());
626 printf("Excludes:\n");
627 for (i = excludes.begin(); i != excludes.end(); ++i)
628 printf(" %s\n", i->c_str());
630 printf("Searching:\n");
631 for (i = searches.begin(); i != searches.end(); ++i)
632 printf(" %s\n", i->c_str());
635 tss = new TarSegmentStore(backup_dest);
636 block_buf = new char[LBS_BLOCK_SIZE];
638 /* Store the time when the backup started, so it can be included in the
644 localtime_r(&now, &time_buf);
645 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
647 /* Open the local database which tracks all objects that are stored
648 * remotely, for efficient incrementals. Provide it with the name of this
650 string database_path = localdb_dir + "/localdb.sqlite";
652 db->Open(database_path.c_str(), desc_buf);
654 /* Initialize the stat cache, for skipping over unchanged files. */
655 statcache = new StatCache;
656 statcache->Open(localdb_dir.c_str(), desc_buf);
658 scanfile(".", false);
661 const string md = metadata_root.str();
663 LbsObject *root = new LbsObject;
664 root->set_group("metadata");
665 root->set_data(md.data(), md.size());
668 segment_list.insert(root->get_ref().get_segment());
670 string backup_root = root->get_ref().to_string();
682 /* Write a backup descriptor file, which says which segments are needed and
683 * where to start to restore this snapshot. The filename is based on the
685 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
686 std::ofstream descriptor(desc_filename.c_str());
688 descriptor << "Format: LBS Snapshot v0.1\n";
689 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
690 descriptor << "Date: " << desc_buf << "\n";
691 descriptor << "Root: " << backup_root << "\n";
693 descriptor << "Segments:\n";
694 for (std::set<string>::iterator i = segment_list.begin();
695 i != segment_list.end(); ++i) {
696 descriptor << " " << *i << "\n";