1 /* Cumulus: Smart Filesystem Backup to Dumb Servers
3 * Copyright (C) 2006-2008 The Regents of the University of California
4 * Written by Michael Vrable <mvrable@cs.ucsd.edu>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 /* Main entry point for LBS. Contains logic for traversing the filesystem and
22 * constructing a backup. */
34 #include <sys/sysmacros.h>
35 #include <sys/types.h>
60 /* Version information. This will be filled in by the Makefile. */
62 #define LBS_VERSION Unknown
64 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
65 #define LBS_STRINGIFY2(s) #s
66 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
68 static RemoteStore *remote = NULL;
69 static TarSegmentStore *tss = NULL;
70 static MetadataWriter *metawriter = NULL;
72 /* Buffer for holding a single block of data read from a file. */
73 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
74 static char *block_buf;
76 /* Local database, which tracks objects written in this and previous
77 * invocations to help in creating incremental snapshots. */
80 /* Keep track of all segments which are needed to reconstruct the snapshot. */
81 std::set<string> segment_list;
83 /* Snapshot intent: 1=daily, 7=weekly, etc. This is not used directly, but is
84 * stored in the local database and can help guide segment cleaning and
85 * snapshot expiration policies. */
86 double snapshot_intent = 1.0;
88 /* Selection of files to include/exclude in the snapshot. */
89 std::list<string> includes; // Paths in which files should be saved
90 std::list<string> excludes; // Paths which will not be saved
91 std::list<string> searches; // Directories we don't want to save, but
92 // do want to descend searching for data
95 bool relative_paths = true;
97 /* Ensure that the given segment is listed as a dependency of the current
99 void add_segment(const string& segment)
101 segment_list.insert(segment);
104 /* Read data from a file descriptor and return the amount of data read. A
105 * short read (less than the requested size) will only occur if end-of-file is
107 ssize_t file_read(int fd, char *buf, size_t maxlen)
109 size_t bytes_read = 0;
112 ssize_t res = read(fd, buf, maxlen);
116 fprintf(stderr, "error reading file: %m\n");
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,
134 struct stat& stat_buf)
137 list<string> object_list;
138 const char *status = NULL; /* Status indicator printed out */
140 /* Look up this file in the old stat cache, if we can. If the stat
141 * information indicates that the file has not changed, do not bother
142 * re-reading the entire contents. */
145 if (metawriter->find(path) && metawriter->is_unchanged(&stat_buf)) {
147 list<ObjectReference> blocks = metawriter->get_blocks();
149 /* If any of the blocks in the object have been expired, then we should
150 * fall back to fully reading in the file. */
151 for (list<ObjectReference>::const_iterator i = blocks.begin();
152 i != blocks.end(); ++i) {
153 const ObjectReference &ref = *i;
154 if (!db->IsAvailable(ref)) {
161 /* If everything looks okay, use the cached information */
163 file_info["checksum"] = metawriter->get_checksum();
164 for (list<ObjectReference>::const_iterator i = blocks.begin();
165 i != blocks.end(); ++i) {
166 const ObjectReference &ref = *i;
167 object_list.push_back(ref.to_string());
169 add_segment(ref.get_segment());
172 size = stat_buf.st_size;
176 /* If the file is new or changed, we must read in the contents a block at a
181 ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
185 fprintf(stderr, "Backup contents for %s may be incorrect\n",
190 hash.process(block_buf, bytes);
192 // Sparse file processing: if we read a block of all zeroes, encode
194 bool all_zero = true;
195 for (int i = 0; i < bytes; i++) {
196 if (block_buf[i] != 0) {
202 // Either find a copy of this block in an already-existing segment,
203 // or index it so it can be re-used in the future
204 double block_age = 0.0;
207 SHA1Checksum block_hash;
208 block_hash.process(block_buf, bytes);
209 string block_csum = block_hash.checksum_str();
212 ref = ObjectReference(ObjectReference::REF_ZERO);
213 ref.set_range(0, bytes);
215 ref = db->FindObject(block_csum, bytes);
218 // Store a copy of the object if one does not yet exist
220 LbsObject *o = new LbsObject;
223 /* We might still have seen this checksum before, if the object
224 * was stored at some time in the past, but we have decided to
225 * clean the segment the object was originally stored in
226 * (FindObject will not return such objects). When rewriting
227 * the object contents, put it in a separate group, so that old
228 * objects get grouped together. The hope is that these old
229 * objects will continue to be used in the future, and we
230 * obtain segments which will continue to be well-utilized.
231 * Additionally, keep track of the age of the data by looking
232 * up the age of the block which was expired and using that
233 * instead of the current time. */
234 if (db->IsOldObject(block_csum, bytes,
235 &block_age, &object_group)) {
236 if (object_group == 0) {
237 o->set_group("data");
240 sprintf(group, "compacted-%d", object_group);
246 o->set_group("data");
250 o->set_data(block_buf, bytes);
253 db->StoreObject(ref, block_csum, bytes, block_age);
254 ref.set_range(0, bytes);
258 object_list.push_back(ref.to_string());
260 add_segment(ref.get_segment());
268 file_info["checksum"] = hash.checksum_str();
272 printf(" [%s]\n", status);
274 string blocklist = "";
275 for (list<string>::iterator i = object_list.begin();
276 i != object_list.end(); ++i) {
277 if (i != object_list.begin())
281 file_info["data"] = blocklist;
286 /* Dump a specified filesystem object (file, directory, etc.) based on its
287 * inode information. If the object is a regular file, an open filehandle is
289 void dump_inode(const string& path, // Path within snapshot
290 const string& fullpath, // Path to object in filesystem
291 struct stat& stat_buf, // Results of stat() call
292 int fd) // Open filehandle if regular file
295 dictionary file_info;
299 printf("%s\n", path.c_str());
300 metawriter->find(path);
302 file_info["name"] = uri_encode(path);
303 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
304 file_info["ctime"] = encode_int(stat_buf.st_ctime);
305 file_info["mtime"] = encode_int(stat_buf.st_mtime);
306 file_info["user"] = encode_int(stat_buf.st_uid);
307 file_info["group"] = encode_int(stat_buf.st_gid);
309 time_t now = time(NULL);
310 if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
311 if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
312 file_info["volatile"] = "1";
314 struct passwd *pwd = getpwuid(stat_buf.st_uid);
316 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
319 struct group *grp = getgrgid(stat_buf.st_gid);
321 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
324 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
325 file_info["links"] = encode_int(stat_buf.st_nlink);
328 file_info["inode"] = encode_int(major(stat_buf.st_dev))
329 + "/" + encode_int(minor(stat_buf.st_dev))
330 + "/" + encode_int(stat_buf.st_ino);
334 switch (stat_buf.st_mode & S_IFMT) {
343 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
344 file_info["device"] = encode_int(major(stat_buf.st_rdev))
345 + "/" + encode_int(minor(stat_buf.st_rdev));
350 /* Use the reported file size to allocate a buffer large enough to read
351 * the symlink. Allocate slightly more space, so that we ask for more
352 * bytes than we expect and so check for truncation. */
353 buf = new char[stat_buf.st_size + 2];
354 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
356 fprintf(stderr, "error reading symlink: %m\n");
357 } else if (len <= stat_buf.st_size) {
359 file_info["target"] = uri_encode(buf);
360 } else if (len > stat_buf.st_size) {
361 fprintf(stderr, "error reading symlink: name truncated\n");
369 file_size = dumpfile(fd, file_info, path, stat_buf);
370 file_info["size"] = encode_int(file_size);
373 return; // error occurred; do not dump file
375 if (file_size != stat_buf.st_size) {
376 fprintf(stderr, "Warning: Size of %s changed during reading\n",
378 file_info["volatile"] = "1";
387 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
391 file_info["type"] = string(1, inode_type);
393 metawriter->add(file_info);
396 void scanfile(const string& path, bool include)
400 struct stat stat_buf;
407 true_path = "/" + path;
409 // Set to true if we should scan through the contents of this directory,
410 // but not actually back files up
411 bool scan_only = false;
413 // Check this file against the include/exclude list to see if it should be
415 for (list<string>::iterator i = includes.begin();
416 i != includes.end(); ++i) {
422 for (list<string>::iterator i = excludes.begin();
423 i != excludes.end(); ++i) {
429 for (list<string>::iterator i = searches.begin();
430 i != searches.end(); ++i) {
436 if (!include && !scan_only)
439 if (lstat(true_path.c_str(), &stat_buf) < 0) {
440 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
444 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
445 /* Be paranoid when opening the file. We have no guarantee that the
446 * file was not replaced between the stat() call above and the open()
447 * call below, so we might not even be opening a regular file. We
448 * supply flags to open to to guard against various conditions before
449 * we can perform an lstat to check that the file is still a regular
451 * - O_NOFOLLOW: in the event the file was replaced by a symlink
452 * - O_NONBLOCK: prevents open() from blocking if the file was
454 * We also add in O_NOATIME, since this may reduce disk writes (for
455 * inode updates). However, O_NOATIME may result in EPERM, so if the
456 * initial open fails, try again without O_NOATIME. */
457 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
459 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
462 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
466 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
468 flags = fcntl(fd, F_GETFL);
469 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
471 /* Perform the stat call again, and check that we still have a regular
473 if (fstat(fd, &stat_buf) < 0) {
474 fprintf(stderr, "fstat: %m\n");
479 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
480 fprintf(stderr, "file is no longer a regular file!\n");
486 dump_inode(path, true_path, stat_buf, fd);
491 // If we hit a directory, now that we've written the directory itself,
492 // recursively scan the directory.
493 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
494 DIR *dir = opendir(true_path.c_str());
497 fprintf(stderr, "Error: %m\n");
502 vector<string> contents;
503 while ((ent = readdir(dir)) != NULL) {
504 string filename(ent->d_name);
505 if (filename == "." || filename == "..")
507 contents.push_back(filename);
512 sort(contents.begin(), contents.end());
514 for (vector<string>::iterator i = contents.begin();
515 i != contents.end(); ++i) {
516 const string& filename = *i;
518 scanfile(filename, include);
520 scanfile(path + "/" + filename, include);
525 /* Include the specified file path in the backups. Append the path to the
526 * includes list, and to ensure that we actually see the path when scanning the
527 * directory tree, add all the parent directories to the search list, which
528 * means we will scan through the directory listing even if the files
529 * themselves are excluded from being backed up. */
530 void add_include(const char *path)
532 /* Was an absolute path specified? If so, we'll need to start scanning
533 * from the root directory. Make sure that the user was consistent in
534 * providing either all relative paths or all absolute paths. */
535 if (path[0] == '/') {
536 if (includes.size() > 0 && relative_paths == true) {
538 "Error: Cannot mix relative and absolute paths!\n");
542 relative_paths = false;
544 // Skip over leading '/'
546 } else if (relative_paths == false && path[0] != '/') {
547 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
551 includes.push_back(path);
553 /* Split the specified path into directory components, and ensure that we
554 * descend into all the directories along the path. */
555 const char *slash = path;
560 while ((slash = strchr(slash + 1, '/')) != NULL) {
561 string component(path, slash - path);
562 searches.push_back(component);
566 void usage(const char *program)
571 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
572 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
575 " --dest=PATH path where backup is to be written\n"
576 " --upload-script=COMMAND\n"
577 " program to invoke for each backup file generated\n"
578 " --exclude=PATH exclude files in PATH from snapshot\n"
579 " --localdb=PATH local backup metadata is stored in PATH\n"
580 " --tmpdir=PATH path for temporarily storing backup files\n"
581 " (defaults to TMPDIR environment variable or /tmp)\n"
582 " --filter=COMMAND program through which to filter segment data\n"
583 " (defaults to \"bzip2 -c\")\n"
584 " --filter-extension=EXT\n"
585 " string to append to segment files\n"
586 " (defaults to \".bz2\")\n"
587 " --signature-filter=COMMAND\n"
588 " program though which to filter descriptor\n"
589 " --scheme=NAME optional name for this snapshot\n"
590 " --intent=FLOAT intended backup type: 1=daily, 7=weekly, ...\n"
591 " (defaults to \"1\")\n"
592 " --full-metadata do not re-use metadata from previous backups\n"
594 "Exactly one of --dest or --upload-script must be specified.\n",
599 int main(int argc, char *argv[])
601 string backup_dest = "", backup_script = "";
602 string localdb_dir = "";
603 string backup_scheme = "";
604 string signature_filter = "";
606 string tmp_dir = "/tmp";
607 if (getenv("TMPDIR") != NULL)
608 tmp_dir = getenv("TMPDIR");
611 static struct option long_options[] = {
612 {"localdb", 1, 0, 0}, // 0
613 {"exclude", 1, 0, 0}, // 1
614 {"filter", 1, 0, 0}, // 2
615 {"filter-extension", 1, 0, 0}, // 3
616 {"dest", 1, 0, 0}, // 4
617 {"scheme", 1, 0, 0}, // 5
618 {"signature-filter", 1, 0, 0}, // 6
619 {"intent", 1, 0, 0}, // 7
620 {"full-metadata", 0, 0, 0}, // 8
621 {"tmpdir", 1, 0, 0}, // 9
622 {"upload-script", 1, 0, 0}, // 10
627 int c = getopt_long(argc, argv, "", long_options, &long_index);
633 switch (long_index) {
635 localdb_dir = optarg;
638 if (optarg[0] != '/')
639 excludes.push_back(optarg);
641 excludes.push_back(optarg + 1);
644 filter_program = optarg;
646 case 3: // --filter-extension
647 filter_extension = optarg;
650 backup_dest = optarg;
653 backup_scheme = optarg;
655 case 6: // --signature-filter
656 signature_filter = optarg;
659 snapshot_intent = atof(optarg);
660 if (snapshot_intent <= 0)
663 case 8: // --full-metadata
664 flag_full_metadata = true;
669 case 10: // --upload-script
670 backup_script = optarg;
673 fprintf(stderr, "Unhandled long option!\n");
682 if (optind == argc) {
687 searches.push_back(".");
688 for (int i = optind; i < argc; i++)
689 add_include(argv[i]);
691 if (backup_dest == "" && backup_script == "") {
693 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
698 if (backup_dest != "" && backup_script != "") {
700 "Error: Cannot specify both --dest= and --upload-script=\n");
705 // Default for --localdb is the same as --dest
706 if (localdb_dir == "") {
707 localdb_dir = backup_dest;
709 if (localdb_dir == "") {
711 "Error: Must specify local database path with --localdb=\n");
716 block_buf = new char[LBS_BLOCK_SIZE];
718 /* Initialize the remote storage layer. If using an upload script, create
719 * a temporary directory for staging files. Otherwise, write backups
720 * directly to the destination directory. */
721 if (backup_script != "") {
722 tmp_dir = tmp_dir + "/lbs." + generate_uuid();
723 if (mkdir(tmp_dir.c_str(), 0700) < 0) {
724 fprintf(stderr, "Cannot create temporary directory %s: %m\n",
728 remote = new RemoteStore(tmp_dir);
729 remote->set_script(backup_script);
731 remote = new RemoteStore(backup_dest);
734 /* Store the time when the backup started, so it can be included in the
740 localtime_r(&now, &time_buf);
741 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
743 /* Open the local database which tracks all objects that are stored
744 * remotely, for efficient incrementals. Provide it with the name of this
746 string database_path = localdb_dir + "/localdb.sqlite";
748 db->Open(database_path.c_str(), desc_buf,
749 backup_scheme.size() ? backup_scheme.c_str() : NULL,
752 tss = new TarSegmentStore(remote, db);
754 /* Initialize the stat cache, for skipping over unchanged files. */
755 metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
757 ? backup_scheme.c_str()
760 scanfile(".", false);
762 ObjectReference root_ref = metawriter->close();
763 add_segment(root_ref.get_segment());
764 string backup_root = root_ref.to_string();
772 /* Write out a checksums file which lists the checksums for all the
773 * segments included in this snapshot. The format is designed so that it
774 * may be easily verified using the sha1sums command. */
775 const char csum_type[] = "sha1";
776 string checksum_filename = "snapshot-";
777 if (backup_scheme.size() > 0)
778 checksum_filename += backup_scheme + "-";
779 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
780 RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
782 FILE *checksums = fdopen(checksum_file->get_fd(), "w");
784 for (std::set<string>::iterator i = segment_list.begin();
785 i != segment_list.end(); ++i) {
786 string seg_path, seg_csum;
787 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
788 const char *raw_checksum = NULL;
789 if (strncmp(seg_csum.c_str(), csum_type,
790 strlen(csum_type)) == 0) {
791 raw_checksum = seg_csum.c_str() + strlen(csum_type);
792 if (*raw_checksum == '=')
798 if (raw_checksum != NULL)
799 fprintf(checksums, "%s *%s\n",
800 raw_checksum, seg_path.c_str());
804 checksum_file->send();
808 /* All other files should be flushed to remote storage before writing the
809 * backup descriptor below, so that it is not possible to have a backup
810 * descriptor written out depending on non-existent (not yet written)
814 /* Write a backup descriptor file, which says which segments are needed and
815 * where to start to restore this snapshot. The filename is based on the
816 * current time. If a signature filter program was specified, filter the
817 * data through that to give a chance to sign the descriptor contents. */
818 string desc_filename = "snapshot-";
819 if (backup_scheme.size() > 0)
820 desc_filename += backup_scheme + "-";
821 desc_filename = desc_filename + desc_buf + ".lbs";
823 RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
825 int descriptor_fd = descriptor_file->get_fd();
826 if (descriptor_fd < 0) {
827 fprintf(stderr, "Unable to open descriptor output file: %m\n");
830 pid_t signature_pid = 0;
831 if (signature_filter.size() > 0) {
832 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
834 close(descriptor_fd);
835 descriptor_fd = new_fd;
837 FILE *descriptor = fdopen(descriptor_fd, "w");
839 fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
840 fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
841 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
842 fprintf(descriptor, "Date: %s\n", desc_buf);
843 if (backup_scheme.size() > 0)
844 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
845 fprintf(descriptor, "Backup-Intent: %g\n", snapshot_intent);
846 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
848 SHA1Checksum checksum_csum;
849 if (checksum_csum.process_file(checksum_filename.c_str())) {
850 string csum = checksum_csum.checksum_str();
851 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
854 fprintf(descriptor, "Segments:\n");
855 for (std::set<string>::iterator i = segment_list.begin();
856 i != segment_list.end(); ++i) {
857 fprintf(descriptor, " %s\n", i->c_str());
864 waitpid(signature_pid, &status, 0);
866 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
867 throw IOException("Signature filter process error");
871 descriptor_file->send();
876 if (backup_script != "") {
877 if (rmdir(tmp_dir.c_str()) < 0) {
879 "Warning: Cannot delete temporary directory %s: %m\n",