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 /* The index data consists of a sequence of pointers to the data blocks
132 * that actually comprise the file data. This level of indirection is used
133 * so that the same data block can be used in multiple files, or multiple
134 * versions of the same file. */
137 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
141 hash.process(block_buf, bytes);
143 // Either find a copy of this block in an already-existing segment, or
144 // index it so it can be re-used in the future
145 double block_age = 0.0;
146 SHA1Checksum block_hash;
147 block_hash.process(block_buf, bytes);
148 string block_csum = block_hash.checksum_str();
149 ObjectReference ref = db->FindObject(block_csum, bytes);
151 // Store a copy of the object if one does not yet exist
152 if (ref.get_segment().size() == 0) {
153 LbsObject *o = new LbsObject;
155 /* We might still have seen this checksum before, if the object was
156 * stored at some time in the past, but we have decided to clean
157 * the segment the object was originally stored in (FindObject will
158 * not return such objects). When rewriting the object contents,
159 * put it in a separate group, so that old objects get grouped
160 * together. The hope is that these old objects will continue to
161 * be used in the future, and we obtain segments which will
162 * continue to be well-utilized. Additionally, keep track of the
163 * age of the data by looking up the age of the block which was
164 * expired and using that instead of the current time. */
165 if (db->IsOldObject(block_csum, bytes, &block_age))
166 o->set_group("compacted");
168 o->set_group("data");
170 o->set_data(block_buf, bytes);
173 db->StoreObject(ref, block_csum, bytes, block_age);
177 object_list.push_back(ref.to_string());
178 segment_list.insert(ref.get_segment());
183 file_info["checksum"] = hash.checksum_str();
185 statcache->Save(path, &stat_buf, file_info["checksum"], object_list);
187 /* For files that only need to be broken apart into a few objects, store
188 * the list of objects directly. For larger files, store the data
189 * out-of-line and provide a pointer to the indrect object. */
190 if (object_list.size() < 8) {
191 string blocklist = "";
192 for (list<string>::iterator i = object_list.begin();
193 i != object_list.end(); ++i) {
194 if (i != object_list.begin())
198 file_info["data"] = blocklist;
200 string blocklist = "";
201 for (list<string>::iterator i = object_list.begin();
202 i != object_list.end(); ++i) {
203 blocklist += *i + "\n";
206 LbsObject *i = new LbsObject;
207 i->set_group("metadata");
208 i->set_data(blocklist.data(), blocklist.size());
210 file_info["data"] = "@" + i->get_name();
211 segment_list.insert(i->get_ref().get_segment());
218 void scanfile(const string& path)
222 struct stat stat_buf;
228 // Set to true if the item is a directory and we should recursively scan
229 bool recurse = false;
231 // Check this file against the include/exclude list to see if it should be
233 for (list<string>::iterator i = excludes.begin();
234 i != excludes.end(); ++i) {
236 printf("Excluding %s\n", path.c_str());
241 dictionary file_info;
243 lstat(path.c_str(), &stat_buf);
245 printf("%s\n", path.c_str());
247 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
248 file_info["mtime"] = encode_int(stat_buf.st_mtime);
249 file_info["user"] = encode_int(stat_buf.st_uid);
250 file_info["group"] = encode_int(stat_buf.st_gid);
252 struct passwd *pwd = getpwuid(stat_buf.st_uid);
254 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
257 struct group *grp = getgrgid(stat_buf.st_gid);
259 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
264 switch (stat_buf.st_mode & S_IFMT) {
280 /* Use the reported file size to allocate a buffer large enough to read
281 * the symlink. Allocate slightly more space, so that we ask for more
282 * bytes than we expect and so check for truncation. */
283 buf = new char[stat_buf.st_size + 2];
284 len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
286 fprintf(stderr, "error reading symlink: %m\n");
287 } else if (len <= stat_buf.st_size) {
289 file_info["contents"] = uri_encode(buf);
290 } else if (len > stat_buf.st_size) {
291 fprintf(stderr, "error reading symlink: name truncated\n");
299 /* Be paranoid when opening the file. We have no guarantee that the
300 * file was not replaced between the stat() call above and the open()
301 * call below, so we might not even be opening a regular file. That
302 * the file descriptor refers to a regular file is checked in
303 * dumpfile(). But we also supply flags to open to to guard against
304 * various conditions before we can perform that verification:
305 * - O_NOFOLLOW: in the event the file was replaced by a symlink
306 * - O_NONBLOCK: prevents open() from blocking if the file was
308 * We also add in O_NOATIME, since this may reduce disk writes (for
309 * inode updates). However, O_NOATIME may result in EPERM, so if the
310 * initial open fails, try again without O_NOATIME. */
311 fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
313 fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
316 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
320 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
322 flags = fcntl(fd, F_GETFL);
323 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
325 file_size = dumpfile(fd, file_info, path);
326 file_info["size"] = encode_int(file_size);
330 return; // error occurred; do not dump file
332 if (file_size != stat_buf.st_size) {
333 fprintf(stderr, "Warning: Size of %s changed during reading\n",
344 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
348 file_info["type"] = string(1, inode_type);
350 metadata << "name: " << uri_encode(path) << "\n";
351 dict_output(metadata, file_info);
354 // Break apart metadata listing if it becomes too large.
355 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
358 // If we hit a directory, now that we've written the directory itself,
359 // recursively scan the directory.
364 void scandir(const string& path)
366 DIR *dir = opendir(path.c_str());
369 fprintf(stderr, "Error: %m\n");
374 vector<string> contents;
375 while ((ent = readdir(dir)) != NULL) {
376 string filename(ent->d_name);
377 if (filename == "." || filename == "..")
379 contents.push_back(filename);
382 sort(contents.begin(), contents.end());
384 for (vector<string>::iterator i = contents.begin();
385 i != contents.end(); ++i) {
386 const string& filename = *i;
390 scanfile(path + "/" + filename);
396 void usage(const char *program)
399 "Usage: %s [OPTION]... SOURCE DEST\n"
400 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
403 " --exclude=PATH exclude files in PATH from snapshot\n"
404 " --localdb=PATH local backup metadata is stored in PATH\n",
408 int main(int argc, char *argv[])
410 string backup_source = ".";
411 string backup_dest = ".";
412 string localdb_dir = "";
415 static struct option long_options[] = {
416 {"localdb", 1, 0, 0}, // 0
417 {"exclude", 1, 0, 0}, // 1
418 {"filter", 1, 0, 0}, // 2
419 {"filter-extension", 1, 0, 0}, // 3
424 int c = getopt_long(argc, argv, "", long_options, &long_index);
430 switch (long_index) {
432 localdb_dir = optarg;
435 excludes.push_back(optarg);
438 filter_program = optarg;
440 case 3: // --filter-extension
441 filter_extension = optarg;
444 fprintf(stderr, "Unhandled long option!\n");
453 if (argc < optind + 2) {
458 backup_source = argv[optind];
459 backup_dest = argv[argc - 1];
461 if (localdb_dir == "") {
462 localdb_dir = backup_dest;
465 printf("Source: %s\nDest: %s\nDatabase: %s\n\n",
466 backup_source.c_str(), backup_dest.c_str(), localdb_dir.c_str());
468 tss = new TarSegmentStore(backup_dest);
469 block_buf = new char[LBS_BLOCK_SIZE];
471 /* Store the time when the backup started, so it can be included in the
477 localtime_r(&now, &time_buf);
478 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
480 /* Open the local database which tracks all objects that are stored
481 * remotely, for efficient incrementals. Provide it with the name of this
483 string database_path = localdb_dir + "/localdb.sqlite";
485 db->Open(database_path.c_str(), desc_buf);
487 /* Initialize the stat cache, for skipping over unchanged files. */
488 statcache = new StatCache;
489 statcache->Open(localdb_dir.c_str(), desc_buf);
493 } catch (IOException e) {
494 fprintf(stderr, "IOException: %s\n", e.getError().c_str());
498 const string md = metadata_root.str();
500 LbsObject *root = new LbsObject;
501 root->set_group("metadata");
502 root->set_data(md.data(), md.size());
505 segment_list.insert(root->get_ref().get_segment());
507 string backup_root = root->get_ref().to_string();
518 /* Write a backup descriptor file, which says which segments are needed and
519 * where to start to restore this snapshot. The filename is based on the
521 string desc_filename = backup_dest + "/snapshot-" + desc_buf + ".lbs";
522 std::ofstream descriptor(desc_filename.c_str());
524 descriptor << "Format: LBS Snapshot v0.1\n";
525 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
526 descriptor << "Date: " << desc_buf << "\n";
527 descriptor << "Root: " << backup_root << "\n";
529 descriptor << "Segments:\n";
530 for (std::set<string>::iterator i = segment_list.begin();
531 i != segment_list.end(); ++i) {
532 descriptor << " " << *i << "\n";