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);
64 /* Selection of files to include/exclude in the snapshot. */
65 std::list<string> excludes;
67 /* Ensure contents of metadata are flushed to an object. */
70 string m = metadata.str();
74 /* Write current metadata information to a new object. */
75 LbsObject *meta = new LbsObject;
76 meta->set_group("metadata");
77 meta->set_data(m.data(), m.size());
81 /* Write a reference to this block in the root. */
82 ObjectReference ref = meta->get_ref();
83 metadata_root << "@" << ref.to_string() << "\n";
84 segment_list.insert(ref.get_segment());
91 /* Read data from a file descriptor and return the amount of data read. A
92 * short read (less than the requested size) will only occur if end-of-file is
94 size_t file_read(int fd, char *buf, size_t maxlen)
96 size_t bytes_read = 0;
99 ssize_t res = read(fd, buf, maxlen);
103 throw IOException("file_read: error reading");
104 } else if (res == 0) {
116 /* Read the contents of a file (specified by an open file descriptor) and copy
117 * the data to the store. Returns the size of the file (number of bytes
118 * dumped), or -1 on error. */
119 int64_t dumpfile(int fd, dictionary &file_info, const string &path)
121 struct stat stat_buf;
122 fstat(fd, &stat_buf);
124 list<string> object_list;
126 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
127 fprintf(stderr, "file is no longer a regular file!\n");
131 /* Look up this file in the old stat cache, if we can. If the stat
132 * information indicates that the file has not changed, do not bother
133 * re-reading the entire contents. */
136 if (statcache->Find(path, &stat_buf)) {
138 const list<ObjectReference> &blocks = statcache->get_blocks();
140 /* If any of the blocks in the object have been expired, then we should
141 * fall back to fully reading in the file. */
142 for (list<ObjectReference>::const_iterator i = blocks.begin();
143 i != blocks.end(); ++i) {
144 const ObjectReference &ref = *i;
145 if (!db->IsAvailable(ref)) {
151 /* If everything looks okay, use the cached information */
153 file_info["checksum"] = statcache->get_checksum();
154 for (list<ObjectReference>::const_iterator i = blocks.begin();
155 i != blocks.end(); ++i) {
156 const ObjectReference &ref = *i;
157 object_list.push_back(ref.to_string());
158 segment_list.insert(ref.get_segment());
161 size = stat_buf.st_size;
165 /* If the file is new or changed, we must read in the contents a block at a
172 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
176 hash.process(block_buf, bytes);
178 // Either find a copy of this block in an already-existing segment,
179 // or index it so it can be re-used in the future
180 double block_age = 0.0;
181 SHA1Checksum block_hash;
182 block_hash.process(block_buf, bytes);
183 string block_csum = block_hash.checksum_str();
184 ObjectReference ref = db->FindObject(block_csum, bytes);
186 // Store a copy of the object if one does not yet exist
187 if (ref.get_segment().size() == 0) {
188 LbsObject *o = new LbsObject;
190 /* We might still have seen this checksum before, if the object
191 * was stored at some time in the past, but we have decided to
192 * clean the segment the object was originally stored in
193 * (FindObject will not return such objects). When rewriting
194 * the object contents, put it in a separate group, so that old
195 * objects get grouped together. The hope is that these old
196 * objects will continue to be used in the future, and we
197 * obtain segments which will continue to be well-utilized.
198 * Additionally, keep track of the age of the data by looking
199 * up the age of the block which was expired and using that
200 * instead of the current time. */
201 if (db->IsOldObject(block_csum, bytes, &block_age))
202 o->set_group("compacted");
204 o->set_group("data");
206 o->set_data(block_buf, bytes);
209 db->StoreObject(ref, block_csum, bytes, block_age);
213 object_list.push_back(ref.to_string());
214 segment_list.insert(ref.get_segment());
219 file_info["checksum"] = hash.checksum_str();
222 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
224 /* For files that only need to be broken apart into a few objects, store
225 * the list of objects directly. For larger files, store the data
226 * out-of-line and provide a pointer to the indrect object. */
227 if (object_list.size() < 8) {
228 string blocklist = "";
229 for (list<string>::iterator i = object_list.begin();
230 i != object_list.end(); ++i) {
231 if (i != object_list.begin())
235 file_info["data"] = blocklist;
237 string blocklist = "";
238 for (list<string>::iterator i = object_list.begin();
239 i != object_list.end(); ++i) {
240 blocklist += *i + "\n";
243 LbsObject *i = new LbsObject;
244 i->set_group("metadata");
245 i->set_data(blocklist.data(), blocklist.size());
247 file_info["data"] = "@" + i->get_name();
248 segment_list.insert(i->get_ref().get_segment());
255 void scanfile(const string& path)
259 struct stat stat_buf;
265 // Set to true if the item is a directory and we should recursively scan
266 bool recurse = false;
268 // Check this file against the include/exclude list to see if it should be
270 for (list<string>::iterator i = excludes.begin();
271 i != excludes.end(); ++i) {
273 printf("Excluding %s\n", path.c_str());
278 dictionary file_info;
280 lstat(path.c_str(), &stat_buf);
282 printf("%s\n", path.c_str());
284 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
285 file_info["mtime"] = encode_int(stat_buf.st_mtime);
286 file_info["user"] = encode_int(stat_buf.st_uid);
287 file_info["group"] = encode_int(stat_buf.st_gid);
289 struct passwd *pwd = getpwuid(stat_buf.st_uid);
291 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
294 struct group *grp = getgrgid(stat_buf.st_gid);
296 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
301 switch (stat_buf.st_mode & S_IFMT) {
317 /* Use the reported file size to allocate a buffer large enough to read
318 * the symlink. Allocate slightly more space, so that we ask for more
319 * bytes than we expect and so check for truncation. */
320 buf = new char[stat_buf.st_size + 2];
321 len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
323 fprintf(stderr, "error reading symlink: %m\n");
324 } else if (len <= stat_buf.st_size) {
326 file_info["contents"] = uri_encode(buf);
327 } else if (len > stat_buf.st_size) {
328 fprintf(stderr, "error reading symlink: name truncated\n");
336 /* Be paranoid when opening the file. We have no guarantee that the
337 * file was not replaced between the stat() call above and the open()
338 * call below, so we might not even be opening a regular file. That
339 * the file descriptor refers to a regular file is checked in
340 * dumpfile(). But we also supply flags to open to to guard against
341 * various conditions before we can perform that verification:
342 * - O_NOFOLLOW: in the event the file was replaced by a symlink
343 * - O_NONBLOCK: prevents open() from blocking if the file was
345 * We also add in O_NOATIME, since this may reduce disk writes (for
346 * inode updates). However, O_NOATIME may result in EPERM, so if the
347 * initial open fails, try again without O_NOATIME. */
348 fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
350 fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
353 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
357 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
359 flags = fcntl(fd, F_GETFL);
360 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
362 file_size = dumpfile(fd, file_info, path);
363 file_info["size"] = encode_int(file_size);
367 return; // error occurred; do not dump file
369 if (file_size != stat_buf.st_size) {
370 fprintf(stderr, "Warning: Size of %s changed during reading\n",
381 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
385 file_info["type"] = string(1, inode_type);
387 metadata << "name: " << uri_encode(path) << "\n";
388 dict_output(metadata, file_info);
391 // Break apart metadata listing if it becomes too large.
392 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
395 // If we hit a directory, now that we've written the directory itself,
396 // recursively scan the directory.
401 void scandir(const string& path)
403 DIR *dir = opendir(path.c_str());
406 fprintf(stderr, "Error: %m\n");
411 vector<string> contents;
412 while ((ent = readdir(dir)) != NULL) {
413 string filename(ent->d_name);
414 if (filename == "." || filename == "..")
416 contents.push_back(filename);
419 sort(contents.begin(), contents.end());
421 for (vector<string>::iterator i = contents.begin();
422 i != contents.end(); ++i) {
423 const string& filename = *i;
427 scanfile(path + "/" + filename);
433 void usage(const char *program)
436 "Usage: %s [OPTION]... SOURCE DEST\n"
437 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
440 " --exclude=PATH exclude files in PATH from snapshot\n"
441 " --localdb=PATH local backup metadata is stored in PATH\n",
445 int main(int argc, char *argv[])
447 string backup_source = ".";
448 string backup_dest = ".";
449 string localdb_dir = "";
452 static struct option long_options[] = {
453 {"localdb", 1, 0, 0}, // 0
454 {"exclude", 1, 0, 0}, // 1
455 {"filter", 1, 0, 0}, // 2
456 {"filter-extension", 1, 0, 0}, // 3
461 int c = getopt_long(argc, argv, "", long_options, &long_index);
467 switch (long_index) {
469 localdb_dir = optarg;
472 excludes.push_back(optarg);
475 filter_program = optarg;
477 case 3: // --filter-extension
478 filter_extension = optarg;
481 fprintf(stderr, "Unhandled long option!\n");
490 if (argc < optind + 2) {
495 backup_source = argv[optind];
496 backup_dest = argv[argc - 1];
498 if (localdb_dir == "") {
499 localdb_dir = backup_dest;
502 printf("Source: %s\nDest: %s\nDatabase: %s\n\n",
503 backup_source.c_str(), backup_dest.c_str(), localdb_dir.c_str());
505 tss = new TarSegmentStore(backup_dest);
506 block_buf = new char[LBS_BLOCK_SIZE];
508 /* Store the time when the backup started, so it can be included in the
514 localtime_r(&now, &time_buf);
515 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
517 /* Open the local database which tracks all objects that are stored
518 * remotely, for efficient incrementals. Provide it with the name of this
520 string database_path = localdb_dir + "/localdb.sqlite";
522 db->Open(database_path.c_str(), desc_buf);
524 /* Initialize the stat cache, for skipping over unchanged files. */
525 statcache = new StatCache;
526 statcache->Open(localdb_dir.c_str(), desc_buf);
530 } catch (IOException e) {
531 fprintf(stderr, "IOException: %s\n", e.getError().c_str());
535 const string md = metadata_root.str();
537 LbsObject *root = new LbsObject;
538 root->set_group("metadata");
539 root->set_data(md.data(), md.size());
542 segment_list.insert(root->get_ref().get_segment());
544 string backup_root = root->get_ref().to_string();
555 /* Write a backup descriptor file, which says which segments are needed and
556 * where to start to restore this snapshot. The filename is based on the
558 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
559 std::ofstream descriptor(desc_filename.c_str());
561 descriptor << "Format: LBS Snapshot v0.1\n";
562 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
563 descriptor << "Date: " << desc_buf << "\n";
564 descriptor << "Root: " << backup_root << "\n";
566 descriptor << "Segments:\n";
567 for (std::set<string>::iterator i = segment_list.begin();
568 i != segment_list.end(); ++i) {
569 descriptor << " " << *i << "\n";