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. */
35 #include <sys/sysmacros.h>
36 #include <sys/types.h>
62 /* Version information. This will be filled in by the Makefile. */
63 #ifndef CUMULUS_VERSION
64 #define CUMULUS_VERSION Unknown
66 #define CUMULUS_STRINGIFY(s) CUMULUS_STRINGIFY2(s)
67 #define CUMULUS_STRINGIFY2(s) #s
68 static const char cumulus_version[] = CUMULUS_STRINGIFY(CUMULUS_VERSION);
70 static RemoteStore *remote = NULL;
71 static TarSegmentStore *tss = NULL;
72 static MetadataWriter *metawriter = NULL;
74 /* Buffer for holding a single block of data read from a file. */
75 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
76 static char *block_buf;
78 /* Local database, which tracks objects written in this and previous
79 * invocations to help in creating incremental snapshots. */
82 /* Keep track of all segments which are needed to reconstruct the snapshot. */
83 std::set<string> segment_list;
85 /* Snapshot intent: 1=daily, 7=weekly, etc. This is not used directly, but is
86 * stored in the local database and can help guide segment cleaning and
87 * snapshot expiration policies. */
88 double snapshot_intent = 1.0;
90 /* Selection of files to include/exclude in the snapshot. */
91 std::list<string> includes; // Paths in which files should be saved
92 std::list<string> excludes; // Paths which will not be saved
93 std::list<string> searches; // Directories we don't want to save, but
94 // do want to descend searching for data
97 bool relative_paths = true;
99 bool flag_rebuild_statcache = false;
101 /* Whether verbose output is enabled. */
102 bool verbose = false;
104 /* Ensure that the given segment is listed as a dependency of the current
106 void add_segment(const string& segment)
108 segment_list.insert(segment);
111 /* Read data from a file descriptor and return the amount of data read. A
112 * short read (less than the requested size) will only occur if end-of-file is
114 ssize_t file_read(int fd, char *buf, size_t maxlen)
116 size_t bytes_read = 0;
119 ssize_t res = read(fd, buf, maxlen);
123 fprintf(stderr, "error reading file: %m\n");
125 } else if (res == 0) {
137 /* Read the contents of a file (specified by an open file descriptor) and copy
138 * the data to the store. Returns the size of the file (number of bytes
139 * dumped), or -1 on error. */
140 int64_t dumpfile(int fd, dictionary &file_info, const string &path,
141 struct stat& stat_buf)
144 list<string> object_list;
145 const char *status = NULL; /* Status indicator printed out */
147 /* Look up this file in the old stat cache, if we can. If the stat
148 * information indicates that the file has not changed, do not bother
149 * re-reading the entire contents. Even if the information has been
150 * changed, we can use the list of old blocks in the search for a sub-block
151 * incremental representation. */
153 list<ObjectReference> old_blocks;
155 bool found = metawriter->find(path);
157 old_blocks = metawriter->get_blocks();
160 && !flag_rebuild_statcache
161 && metawriter->is_unchanged(&stat_buf)) {
164 /* If any of the blocks in the object have been expired, then we should
165 * fall back to fully reading in the file. */
166 for (list<ObjectReference>::const_iterator i = old_blocks.begin();
167 i != old_blocks.end(); ++i) {
168 const ObjectReference &ref = *i;
169 if (!db->IsAvailable(ref)) {
176 /* If everything looks okay, use the cached information */
178 file_info["checksum"] = metawriter->get_checksum();
179 for (list<ObjectReference>::const_iterator i = old_blocks.begin();
180 i != old_blocks.end(); ++i) {
181 const ObjectReference &ref = *i;
182 object_list.push_back(ref.to_string());
184 add_segment(ref.get_segment());
187 size = stat_buf.st_size;
191 /* If the file is new or changed, we must read in the contents a block at a
196 subfile.load_old_blocks(old_blocks);
199 ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
203 fprintf(stderr, "Backup contents for %s may be incorrect\n",
208 hash.process(block_buf, bytes);
210 // Sparse file processing: if we read a block of all zeroes, encode
212 bool all_zero = true;
213 for (int i = 0; i < bytes; i++) {
214 if (block_buf[i] != 0) {
220 // Either find a copy of this block in an already-existing segment,
221 // or index it so it can be re-used in the future
222 double block_age = 0.0;
225 SHA1Checksum block_hash;
226 block_hash.process(block_buf, bytes);
227 string block_csum = block_hash.checksum_str();
230 ref = ObjectReference(ObjectReference::REF_ZERO);
231 ref.set_range(0, bytes);
233 ref = db->FindObject(block_csum, bytes);
236 list<ObjectReference> refs;
238 // Store a copy of the object if one does not yet exist
240 LbsObject *o = new LbsObject;
243 /* We might still have seen this checksum before, if the object
244 * was stored at some time in the past, but we have decided to
245 * clean the segment the object was originally stored in
246 * (FindObject will not return such objects). When rewriting
247 * the object contents, put it in a separate group, so that old
248 * objects get grouped together. The hope is that these old
249 * objects will continue to be used in the future, and we
250 * obtain segments which will continue to be well-utilized.
251 * Additionally, keep track of the age of the data by looking
252 * up the age of the block which was expired and using that
253 * instead of the current time. */
254 if (db->IsOldObject(block_csum, bytes,
255 &block_age, &object_group)) {
256 if (object_group == 0) {
257 o->set_group("data");
260 sprintf(group, "compacted-%d", object_group);
266 o->set_group("data");
270 subfile.analyze_new_block(block_buf, bytes);
271 refs = subfile.create_incremental(tss, o, block_age);
276 while (!refs.empty()) {
277 ref = refs.front(); refs.pop_front();
278 object_list.push_back(ref.to_string());
280 add_segment(ref.get_segment());
289 file_info["checksum"] = hash.checksum_str();
292 // Sanity check: if we are rebuilding the statcache, but the file looks
293 // like it hasn't changed, then the newly-computed checksum should match
294 // the checksum in the statcache. If not, we have possible disk corruption
295 // and report a warning.
296 if (flag_rebuild_statcache) {
298 && metawriter->is_unchanged(&stat_buf)
299 && file_info["checksum"] != metawriter->get_checksum()) {
301 "Warning: Checksum for %s does not match expected value\n"
305 metawriter->get_checksum().c_str(),
306 file_info["checksum"].c_str());
310 if (verbose && status != NULL)
311 printf(" [%s]\n", status);
313 string blocklist = "";
314 for (list<string>::iterator i = object_list.begin();
315 i != object_list.end(); ++i) {
316 if (i != object_list.begin())
320 file_info["data"] = blocklist;
325 /* Dump a specified filesystem object (file, directory, etc.) based on its
326 * inode information. If the object is a regular file, an open filehandle is
328 void dump_inode(const string& path, // Path within snapshot
329 const string& fullpath, // Path to object in filesystem
330 struct stat& stat_buf, // Results of stat() call
331 int fd) // Open filehandle if regular file
334 dictionary file_info;
339 printf("%s\n", path.c_str());
340 metawriter->find(path);
342 file_info["name"] = uri_encode(path);
343 file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
344 file_info["ctime"] = encode_int(stat_buf.st_ctime);
345 file_info["mtime"] = encode_int(stat_buf.st_mtime);
346 file_info["user"] = encode_int(stat_buf.st_uid);
347 file_info["group"] = encode_int(stat_buf.st_gid);
349 time_t now = time(NULL);
350 if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
351 if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
352 file_info["volatile"] = "1";
354 struct passwd *pwd = getpwuid(stat_buf.st_uid);
356 file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
359 struct group *grp = getgrgid(stat_buf.st_gid);
361 file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
364 if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
365 file_info["links"] = encode_int(stat_buf.st_nlink);
368 file_info["inode"] = encode_int(major(stat_buf.st_dev))
369 + "/" + encode_int(minor(stat_buf.st_dev))
370 + "/" + encode_int(stat_buf.st_ino);
374 switch (stat_buf.st_mode & S_IFMT) {
383 inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
384 file_info["device"] = encode_int(major(stat_buf.st_rdev))
385 + "/" + encode_int(minor(stat_buf.st_rdev));
390 /* Use the reported file size to allocate a buffer large enough to read
391 * the symlink. Allocate slightly more space, so that we ask for more
392 * bytes than we expect and so check for truncation. */
393 buf = new char[stat_buf.st_size + 2];
394 len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
396 fprintf(stderr, "error reading symlink: %m\n");
397 } else if (len <= stat_buf.st_size) {
399 file_info["target"] = uri_encode(buf);
400 } else if (len > stat_buf.st_size) {
401 fprintf(stderr, "error reading symlink: name truncated\n");
409 file_size = dumpfile(fd, file_info, path, stat_buf);
410 file_info["size"] = encode_int(file_size);
413 return; // error occurred; do not dump file
415 if (file_size != stat_buf.st_size) {
416 fprintf(stderr, "Warning: Size of %s changed during reading\n",
418 file_info["volatile"] = "1";
427 fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
431 file_info["type"] = string(1, inode_type);
433 metawriter->add(file_info);
436 void scanfile(const string& path, bool include)
440 struct stat stat_buf;
447 true_path = "/" + path;
449 // Set to true if we should scan through the contents of this directory,
450 // but not actually back files up
451 bool scan_only = false;
453 // Check this file against the include/exclude list to see if it should be
455 for (list<string>::iterator i = includes.begin();
456 i != includes.end(); ++i) {
462 for (list<string>::iterator i = excludes.begin();
463 i != excludes.end(); ++i) {
469 for (list<string>::iterator i = searches.begin();
470 i != searches.end(); ++i) {
476 if (!include && !scan_only)
479 if (lstat(true_path.c_str(), &stat_buf) < 0) {
480 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
484 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
485 /* Be paranoid when opening the file. We have no guarantee that the
486 * file was not replaced between the stat() call above and the open()
487 * call below, so we might not even be opening a regular file. We
488 * supply flags to open to to guard against various conditions before
489 * we can perform an lstat to check that the file is still a regular
491 * - O_NOFOLLOW: in the event the file was replaced by a symlink
492 * - O_NONBLOCK: prevents open() from blocking if the file was
494 * We also add in O_NOATIME, since this may reduce disk writes (for
495 * inode updates). However, O_NOATIME may result in EPERM, so if the
496 * initial open fails, try again without O_NOATIME. */
497 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
499 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
502 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
506 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
508 flags = fcntl(fd, F_GETFL);
509 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
511 /* Perform the stat call again, and check that we still have a regular
513 if (fstat(fd, &stat_buf) < 0) {
514 fprintf(stderr, "fstat: %m\n");
519 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
520 fprintf(stderr, "file is no longer a regular file!\n");
526 dump_inode(path, true_path, stat_buf, fd);
531 // If we hit a directory, now that we've written the directory itself,
532 // recursively scan the directory.
533 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
534 DIR *dir = opendir(true_path.c_str());
537 fprintf(stderr, "Error: %m\n");
542 vector<string> contents;
543 while ((ent = readdir(dir)) != NULL) {
544 string filename(ent->d_name);
545 if (filename == "." || filename == "..")
547 contents.push_back(filename);
552 sort(contents.begin(), contents.end());
554 for (vector<string>::iterator i = contents.begin();
555 i != contents.end(); ++i) {
556 const string& filename = *i;
558 scanfile(filename, include);
560 scanfile(path + "/" + filename, include);
565 /* Include the specified file path in the backups. Append the path to the
566 * includes list, and to ensure that we actually see the path when scanning the
567 * directory tree, add all the parent directories to the search list, which
568 * means we will scan through the directory listing even if the files
569 * themselves are excluded from being backed up. */
570 void add_include(const char *path)
572 /* Was an absolute path specified? If so, we'll need to start scanning
573 * from the root directory. Make sure that the user was consistent in
574 * providing either all relative paths or all absolute paths. */
575 if (path[0] == '/') {
576 if (includes.size() > 0 && relative_paths == true) {
578 "Error: Cannot mix relative and absolute paths!\n");
582 relative_paths = false;
584 // Skip over leading '/'
586 } else if (relative_paths == false && path[0] != '/') {
587 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
591 includes.push_back(path);
593 /* Split the specified path into directory components, and ensure that we
594 * descend into all the directories along the path. */
595 const char *slash = path;
600 while ((slash = strchr(slash + 1, '/')) != NULL) {
601 string component(path, slash - path);
602 searches.push_back(component);
606 void usage(const char *program)
611 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
612 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
615 " --dest=PATH path where backup is to be written\n"
616 " --upload-script=COMMAND\n"
617 " program to invoke for each backup file generated\n"
618 " --exclude=PATH exclude files in PATH from snapshot\n"
619 " --localdb=PATH local backup metadata is stored in PATH\n"
620 " --tmpdir=PATH path for temporarily storing backup files\n"
621 " (defaults to TMPDIR environment variable or /tmp)\n"
622 " --filter=COMMAND program through which to filter segment data\n"
623 " (defaults to \"bzip2 -c\")\n"
624 " --filter-extension=EXT\n"
625 " string to append to segment files\n"
626 " (defaults to \".bz2\")\n"
627 " --signature-filter=COMMAND\n"
628 " program though which to filter descriptor\n"
629 " --scheme=NAME optional name for this snapshot\n"
630 " --intent=FLOAT intended backup type: 1=daily, 7=weekly, ...\n"
631 " (defaults to \"1\")\n"
632 " --full-metadata do not re-use metadata from previous backups\n"
633 " --rebuild-statcache re-read all file data to verify statcache\n"
634 " -v --verbose list files as they are backed up\n"
636 "Exactly one of --dest or --upload-script must be specified.\n",
637 cumulus_version, program
641 int main(int argc, char *argv[])
643 string backup_dest = "", backup_script = "";
644 string localdb_dir = "";
645 string backup_scheme = "";
646 string signature_filter = "";
648 string tmp_dir = "/tmp";
649 if (getenv("TMPDIR") != NULL)
650 tmp_dir = getenv("TMPDIR");
653 static struct option long_options[] = {
654 {"localdb", 1, 0, 0}, // 0
655 {"exclude", 1, 0, 0}, // 1
656 {"filter", 1, 0, 0}, // 2
657 {"filter-extension", 1, 0, 0}, // 3
658 {"dest", 1, 0, 0}, // 4
659 {"scheme", 1, 0, 0}, // 5
660 {"signature-filter", 1, 0, 0}, // 6
661 {"intent", 1, 0, 0}, // 7
662 {"full-metadata", 0, 0, 0}, // 8
663 {"tmpdir", 1, 0, 0}, // 9
664 {"upload-script", 1, 0, 0}, // 10
665 {"rebuild-statcache", 0, 0, 0}, // 11
666 // Aliases for short options
667 {"verbose", 0, 0, 'v'},
672 int c = getopt_long(argc, argv, "v", long_options, &long_index);
678 switch (long_index) {
680 localdb_dir = optarg;
683 if (optarg[0] != '/')
684 excludes.push_back(optarg);
686 excludes.push_back(optarg + 1);
689 filter_program = optarg;
691 case 3: // --filter-extension
692 filter_extension = optarg;
695 backup_dest = optarg;
698 backup_scheme = optarg;
700 case 6: // --signature-filter
701 signature_filter = optarg;
704 snapshot_intent = atof(optarg);
705 if (snapshot_intent <= 0)
708 case 8: // --full-metadata
709 flag_full_metadata = true;
714 case 10: // --upload-script
715 backup_script = optarg;
717 case 11: // --rebuild-statcache
718 flag_rebuild_statcache = true;
721 fprintf(stderr, "Unhandled long option!\n");
736 if (optind == argc) {
741 searches.push_back(".");
742 for (int i = optind; i < argc; i++)
743 add_include(argv[i]);
745 if (backup_dest == "" && backup_script == "") {
747 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
752 if (backup_dest != "" && backup_script != "") {
754 "Error: Cannot specify both --dest= and --upload-script=\n");
759 // Default for --localdb is the same as --dest
760 if (localdb_dir == "") {
761 localdb_dir = backup_dest;
763 if (localdb_dir == "") {
765 "Error: Must specify local database path with --localdb=\n");
770 block_buf = new char[LBS_BLOCK_SIZE];
772 /* Initialize the remote storage layer. If using an upload script, create
773 * a temporary directory for staging files. Otherwise, write backups
774 * directly to the destination directory. */
775 if (backup_script != "") {
776 tmp_dir = tmp_dir + "/lbs." + generate_uuid();
777 if (mkdir(tmp_dir.c_str(), 0700) < 0) {
778 fprintf(stderr, "Cannot create temporary directory %s: %m\n",
782 remote = new RemoteStore(tmp_dir);
783 remote->set_script(backup_script);
785 remote = new RemoteStore(backup_dest);
788 /* Store the time when the backup started, so it can be included in the
794 localtime_r(&now, &time_buf);
795 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
797 /* Open the local database which tracks all objects that are stored
798 * remotely, for efficient incrementals. Provide it with the name of this
800 string database_path = localdb_dir + "/localdb.sqlite";
802 db->Open(database_path.c_str(), desc_buf, backup_scheme.c_str(),
805 tss = new TarSegmentStore(remote, db);
807 /* Initialize the stat cache, for skipping over unchanged files. */
808 metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
809 backup_scheme.c_str());
811 scanfile(".", false);
813 ObjectReference root_ref = metawriter->close();
814 add_segment(root_ref.get_segment());
815 string backup_root = root_ref.to_string();
823 /* Write out a checksums file which lists the checksums for all the
824 * segments included in this snapshot. The format is designed so that it
825 * may be easily verified using the sha1sums command. */
826 const char csum_type[] = "sha1";
827 string checksum_filename = "snapshot-";
828 if (backup_scheme.size() > 0)
829 checksum_filename += backup_scheme + "-";
830 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
831 RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
833 FILE *checksums = fdopen(checksum_file->get_fd(), "w");
835 for (std::set<string>::iterator i = segment_list.begin();
836 i != segment_list.end(); ++i) {
837 string seg_path, seg_csum;
838 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
839 const char *raw_checksum = NULL;
840 if (strncmp(seg_csum.c_str(), csum_type,
841 strlen(csum_type)) == 0) {
842 raw_checksum = seg_csum.c_str() + strlen(csum_type);
843 if (*raw_checksum == '=')
849 if (raw_checksum != NULL)
850 fprintf(checksums, "%s *%s\n",
851 raw_checksum, seg_path.c_str());
856 SHA1Checksum checksum_csum;
858 checksum_filename = checksum_file->get_local_path();
859 if (checksum_csum.process_file(checksum_filename.c_str())) {
860 csum = checksum_csum.checksum_str();
863 checksum_file->send();
867 /* All other files should be flushed to remote storage before writing the
868 * backup descriptor below, so that it is not possible to have a backup
869 * descriptor written out depending on non-existent (not yet written)
873 /* Write a backup descriptor file, which says which segments are needed and
874 * where to start to restore this snapshot. The filename is based on the
875 * current time. If a signature filter program was specified, filter the
876 * data through that to give a chance to sign the descriptor contents. */
877 string desc_filename = "snapshot-";
878 if (backup_scheme.size() > 0)
879 desc_filename += backup_scheme + "-";
880 desc_filename = desc_filename + desc_buf + ".lbs";
882 RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
884 int descriptor_fd = descriptor_file->get_fd();
885 if (descriptor_fd < 0) {
886 fprintf(stderr, "Unable to open descriptor output file: %m\n");
889 pid_t signature_pid = 0;
890 if (signature_filter.size() > 0) {
891 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
893 close(descriptor_fd);
894 descriptor_fd = new_fd;
896 FILE *descriptor = fdopen(descriptor_fd, "w");
898 fprintf(descriptor, "Format: LBS Snapshot v0.8\n");
899 fprintf(descriptor, "Producer: Cumulus %s\n", cumulus_version);
900 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
901 fprintf(descriptor, "Date: %s\n", desc_buf);
902 if (backup_scheme.size() > 0)
903 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
904 fprintf(descriptor, "Backup-Intent: %g\n", snapshot_intent);
905 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
907 if (csum.size() > 0) {
908 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
911 fprintf(descriptor, "Segments:\n");
912 for (std::set<string>::iterator i = segment_list.begin();
913 i != segment_list.end(); ++i) {
914 fprintf(descriptor, " %s\n", i->c_str());
921 waitpid(signature_pid, &status, 0);
923 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
924 throw IOException("Signature filter process error");
928 descriptor_file->send();
933 if (backup_script != "") {
934 if (rmdir(tmp_dir.c_str()) < 0) {
936 "Warning: Cannot delete temporary directory %s: %m\n",