1 /* Recursively descend the filesystem and visit each file. */
13 #include <sys/types.h>
35 static TarSegmentStore *tss = NULL;
37 /* Buffer for holding a single block of data read from a file. */
38 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
39 static char *block_buf;
41 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
43 /* Local database, which tracks objects written in this and previous
44 * invocations to help in creating incremental snapshots. */
47 /* Contents of the root object. This will contain a set of indirect links to
48 * the metadata objects. */
49 std::ostringstream metadata_root;
51 /* Buffer for building up metadata. */
52 std::ostringstream metadata;
54 /* Keep track of all segments which are needed to reconstruct the snapshot. */
55 std::set<string> segment_list;
57 void scandir(const string& path);
59 /* Selection of files to include/exclude in the snapshot. */
60 std::list<string> excludes;
62 /* Ensure contents of metadata are flushed to an object. */
65 string m = metadata.str();
69 /* Write current metadata information to a new object. */
70 LbsObject *meta = new LbsObject;
71 meta->set_group("metadata");
72 meta->set_data(m.data(), m.size());
76 /* Write a reference to this block in the root. */
77 ObjectReference ref = meta->get_ref();
78 metadata_root << "@" << ref.to_string() << "\n";
79 segment_list.insert(ref.get_segment());
86 /* Read data from a file descriptor and return the amount of data read. A
87 * short read (less than the requested size) will only occur if end-of-file is
89 size_t file_read(int fd, char *buf, size_t maxlen)
91 size_t bytes_read = 0;
94 ssize_t res = read(fd, buf, maxlen);
98 throw IOException("file_read: error reading");
99 } else if (res == 0) {
111 /* Read the contents of a file (specified by an open file descriptor) and copy
112 * the data to the store. Returns the size of the file (number of bytes
113 * dumped), or -1 on error. */
114 int64_t dumpfile(int fd, dictionary &file_info)
116 struct stat stat_buf;
117 fstat(fd, &stat_buf);
119 list<string> object_list;
121 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
122 fprintf(stderr, "file is no longer a regular file!\n");
126 /* The index data consists of a sequence of pointers to the data blocks
127 * that actually comprise the file data. This level of indirection is used
128 * so that the same data block can be used in multiple files, or multiple
129 * versions of the same file. */
132 size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
136 hash.process(block_buf, bytes);
138 // Either find a copy of this block in an already-existing segment, or
139 // index it so it can be re-used in the future
140 SHA1Checksum block_hash;
141 block_hash.process(block_buf, bytes);
142 string block_csum = block_hash.checksum_str();
143 ObjectReference ref = db->FindObject(block_csum, bytes);
145 // Store a copy of the object if one does not yet exist
146 if (ref.get_segment().size() == 0) {
147 LbsObject *o = new LbsObject;
149 /* We might still have seen this checksum before, if the object was
150 * stored at some time in the past, but we have decided to clean
151 * the segment the object was originally stored in (FindObject will
152 * not return such objects). When rewriting the object contents,
153 * put it in a separate group, so that old objects get grouped
154 * together. The hope is that these old objects will continue to
155 * be used in the future, and we obtain segments which will
156 * continue to be well-utilized. */
157 if (db->IsOldObject(block_csum, bytes))
158 o->set_group("compacted");
160 o->set_group("data");
162 o->set_data(block_buf, bytes);
165 db->StoreObject(ref, block_csum, bytes);
169 object_list.push_back(ref.to_string());
170 segment_list.insert(ref.get_segment());
175 file_info["checksum"] = hash.checksum_str();
177 /* For files that only need to be broken apart into a few objects, store
178 * the list of objects directly. For larger files, store the data
179 * out-of-line and provide a pointer to the indrect object. */
180 if (object_list.size() < 8) {
181 string blocklist = "";
182 for (list<string>::iterator i = object_list.begin();
183 i != object_list.end(); ++i) {
184 if (i != object_list.begin())
188 file_info["data"] = blocklist;
190 string blocklist = "";
191 for (list<string>::iterator i = object_list.begin();
192 i != object_list.end(); ++i) {
193 blocklist += *i + "\n";
196 LbsObject *i = new LbsObject;
197 i->set_group("metadata");
198 i->set_data(blocklist.data(), blocklist.size());
200 file_info["data"] = "@" + i->get_name();
201 segment_list.insert(i->get_ref().get_segment());
208 void scanfile(const string& path)
212 struct stat stat_buf;
218 // Set to true if the item is a directory and we should recursively scan
219 bool recurse = false;
221 // Check this file against the include/exclude list to see if it should be
223 for (list<string>::iterator i = excludes.begin();
224 i != excludes.end(); ++i) {
226 printf("Excluding %s\n", path.c_str());
231 dictionary file_info;
233 lstat(path.c_str(), &stat_buf);
235 printf("%s\n", path.c_str());
237 file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
238 file_info["mtime"] = encode_int(stat_buf.st_mtime);
239 file_info["user"] = encode_int(stat_buf.st_uid);
240 file_info["group"] = encode_int(stat_buf.st_gid);
242 struct passwd *pwd = getpwuid(stat_buf.st_uid);
244 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
247 struct group *grp = getgrgid(stat_buf.st_gid);
249 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
254 switch (stat_buf.st_mode & S_IFMT) {
270 /* Use the reported file size to allocate a buffer large enough to read
271 * the symlink. Allocate slightly more space, so that we ask for more
272 * bytes than we expect and so check for truncation. */
273 buf = new char[stat_buf.st_size + 2];
274 len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
276 fprintf(stderr, "error reading symlink: %m\n");
277 } else if (len <= stat_buf.st_size) {
279 file_info["contents"] = uri_encode(buf);
280 } else if (len > stat_buf.st_size) {
281 fprintf(stderr, "error reading symlink: name truncated\n");
289 /* Be paranoid when opening the file. We have no guarantee that the
290 * file was not replaced between the stat() call above and the open()
291 * call below, so we might not even be opening a regular file. That
292 * the file descriptor refers to a regular file is checked in
293 * dumpfile(). But we also supply flags to open to to guard against
294 * various conditions before we can perform that verification:
295 * - O_NOFOLLOW: in the event the file was replaced by a symlink
296 * - O_NONBLOCK: prevents open() from blocking if the file was
298 * We also add in O_NOATIME, since this may reduce disk writes (for
299 * inode updates). However, O_NOATIME may result in EPERM, so if the
300 * initial open fails, try again without O_NOATIME. */
301 fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
303 fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
306 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
310 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
312 flags = fcntl(fd, F_GETFL);
313 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
315 file_size = dumpfile(fd, file_info);
316 file_info["size"] = encode_int(file_size);
320 return; // error occurred; do not dump file
322 if (file_size != stat_buf.st_size) {
323 fprintf(stderr, "Warning: Size of %s changed during reading\n",
334 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
338 file_info["type"] = string(1, inode_type);
340 metadata << "name: " << uri_encode(path) << "\n";
341 dict_output(metadata, file_info);
344 // Break apart metadata listing if it becomes too large.
345 if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
348 // If we hit a directory, now that we've written the directory itself,
349 // recursively scan the directory.
354 void scandir(const string& path)
356 DIR *dir = opendir(path.c_str());
359 fprintf(stderr, "Error: %m\n");
364 vector<string> contents;
365 while ((ent = readdir(dir)) != NULL) {
366 string filename(ent->d_name);
367 if (filename == "." || filename == "..")
369 contents.push_back(filename);
372 sort(contents.begin(), contents.end());
374 for (vector<string>::iterator i = contents.begin();
375 i != contents.end(); ++i) {
376 const string& filename = *i;
380 scanfile(path + "/" + filename);
386 void usage(const char *program)
389 "Usage: %s [OPTION]... SOURCE DEST\n"
390 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
393 " --exclude=PATH exclude files in PATH from snapshot\n"
394 " --localdb=PATH local backup metadata is stored in PATH\n",
398 int main(int argc, char *argv[])
400 string backup_source = ".";
401 string backup_dest = ".";
402 string localdb_dir = "";
405 static struct option long_options[] = {
406 {"localdb", 1, 0, 0}, // 0
407 {"exclude", 1, 0, 0}, // 1
408 {"filter", 1, 0, 0}, // 2
409 {"filter-extension", 1, 0, 0}, // 3
414 int c = getopt_long(argc, argv, "", long_options, &long_index);
420 switch (long_index) {
422 localdb_dir = optarg;
425 excludes.push_back(optarg);
428 filter_program = optarg;
430 case 3: // --filter-extension
431 filter_extension = optarg;
434 fprintf(stderr, "Unhandled long option!\n");
443 if (argc < optind + 2) {
448 backup_source = argv[optind];
449 backup_dest = argv[argc - 1];
451 if (localdb_dir == "") {
452 localdb_dir = backup_dest;
455 printf("Source: %s, Dest: %s\n",
456 backup_source.c_str(), backup_dest.c_str());
458 tss = new TarSegmentStore(backup_dest);
459 block_buf = new char[LBS_BLOCK_SIZE];
461 /* Write a backup descriptor file, which says which segments are needed and
462 * where to start to restore this snapshot. The filename is based on the
468 localtime_r(&now, &time_buf);
469 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
470 string desc_filename = backup_dest + "/" + desc_buf + ".lbs";
471 std::ofstream descriptor(desc_filename.c_str());
473 /* Open the local database which tracks all objects that are stored
474 * remotely, for efficient incrementals. Provide it with the name of this
476 string database_path = backup_dest + "/localdb.sqlite";
478 db->Open(database_path.c_str(), desc_buf);
482 } catch (IOException e) {
483 fprintf(stderr, "IOException: %s\n", e.getError().c_str());
487 const string md = metadata_root.str();
489 LbsObject *root = new LbsObject;
490 root->set_group("metadata");
491 root->set_data(md.data(), md.size());
495 segment_list.insert(root->get_ref().get_segment());
496 descriptor << "Format: LBS Snapshot v0.1\n";
497 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
498 descriptor << "Date: " << desc_buf << "\n";
499 descriptor << "Root: " << root->get_ref().to_string() << "\n";
503 descriptor << "Segments:\n";
504 for (std::set<string>::iterator i = segment_list.begin();
505 i != segment_list.end(); ++i) {
506 descriptor << " " << *i << "\n";