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) {
418 printf("Including %s\n", path.c_str());
423 for (list<string>::iterator i = excludes.begin();
424 i != excludes.end(); ++i) {
426 printf("Excluding %s\n", path.c_str());
431 for (list<string>::iterator i = searches.begin();
432 i != searches.end(); ++i) {
434 printf("Scanning %s\n", path.c_str());
439 if (!include && !scan_only)
442 if (lstat(true_path.c_str(), &stat_buf) < 0) {
443 fprintf(stderr, "lstat(%s): %m\n", path.c_str());
447 if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
448 /* Be paranoid when opening the file. We have no guarantee that the
449 * file was not replaced between the stat() call above and the open()
450 * call below, so we might not even be opening a regular file. We
451 * supply flags to open to to guard against various conditions before
452 * we can perform an lstat to check that the file is still a regular
454 * - O_NOFOLLOW: in the event the file was replaced by a symlink
455 * - O_NONBLOCK: prevents open() from blocking if the file was
457 * We also add in O_NOATIME, since this may reduce disk writes (for
458 * inode updates). However, O_NOATIME may result in EPERM, so if the
459 * initial open fails, try again without O_NOATIME. */
460 fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
462 fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
465 fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
469 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
471 flags = fcntl(fd, F_GETFL);
472 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
474 /* Perform the stat call again, and check that we still have a regular
476 if (fstat(fd, &stat_buf) < 0) {
477 fprintf(stderr, "fstat: %m\n");
482 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
483 fprintf(stderr, "file is no longer a regular file!\n");
489 dump_inode(path, true_path, stat_buf, fd);
494 // If we hit a directory, now that we've written the directory itself,
495 // recursively scan the directory.
496 if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
497 DIR *dir = opendir(true_path.c_str());
500 fprintf(stderr, "Error: %m\n");
505 vector<string> contents;
506 while ((ent = readdir(dir)) != NULL) {
507 string filename(ent->d_name);
508 if (filename == "." || filename == "..")
510 contents.push_back(filename);
515 sort(contents.begin(), contents.end());
517 for (vector<string>::iterator i = contents.begin();
518 i != contents.end(); ++i) {
519 const string& filename = *i;
521 scanfile(filename, include);
523 scanfile(path + "/" + filename, include);
528 /* Include the specified file path in the backups. Append the path to the
529 * includes list, and to ensure that we actually see the path when scanning the
530 * directory tree, add all the parent directories to the search list, which
531 * means we will scan through the directory listing even if the files
532 * themselves are excluded from being backed up. */
533 void add_include(const char *path)
535 printf("Add: %s\n", path);
536 /* Was an absolute path specified? If so, we'll need to start scanning
537 * from the root directory. Make sure that the user was consistent in
538 * providing either all relative paths or all absolute paths. */
539 if (path[0] == '/') {
540 if (includes.size() > 0 && relative_paths == true) {
542 "Error: Cannot mix relative and absolute paths!\n");
546 relative_paths = false;
548 // Skip over leading '/'
550 } else if (relative_paths == false && path[0] != '/') {
551 fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
555 includes.push_back(path);
557 /* Split the specified path into directory components, and ensure that we
558 * descend into all the directories along the path. */
559 const char *slash = path;
564 while ((slash = strchr(slash + 1, '/')) != NULL) {
565 string component(path, slash - path);
566 searches.push_back(component);
570 void usage(const char *program)
575 "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
576 "Produce backup snapshot of files in SOURCE and store to DEST.\n"
579 " --dest=PATH path where backup is to be written\n"
580 " --upload-script=COMMAND\n"
581 " program to invoke for each backup file generated\n"
582 " --exclude=PATH exclude files in PATH from snapshot\n"
583 " --localdb=PATH local backup metadata is stored in PATH\n"
584 " --tmpdir=PATH path for temporarily storing backup files\n"
585 " (defaults to TMPDIR environment variable or /tmp)\n"
586 " --filter=COMMAND program through which to filter segment data\n"
587 " (defaults to \"bzip2 -c\")\n"
588 " --filter-extension=EXT\n"
589 " string to append to segment files\n"
590 " (defaults to \".bz2\")\n"
591 " --signature-filter=COMMAND\n"
592 " program though which to filter descriptor\n"
593 " --scheme=NAME optional name for this snapshot\n"
594 " --intent=FLOAT intended backup type: 1=daily, 7=weekly, ...\n"
595 " (defaults to \"1\")\n"
596 " --full-metadata do not re-use metadata from previous backups\n"
598 "Exactly one of --dest or --upload-script must be specified.\n",
603 int main(int argc, char *argv[])
605 string backup_dest = "", backup_script = "";
606 string localdb_dir = "";
607 string backup_scheme = "";
608 string signature_filter = "";
610 string tmp_dir = "/tmp";
611 if (getenv("TMPDIR") != NULL)
612 tmp_dir = getenv("TMPDIR");
615 static struct option long_options[] = {
616 {"localdb", 1, 0, 0}, // 0
617 {"exclude", 1, 0, 0}, // 1
618 {"filter", 1, 0, 0}, // 2
619 {"filter-extension", 1, 0, 0}, // 3
620 {"dest", 1, 0, 0}, // 4
621 {"scheme", 1, 0, 0}, // 5
622 {"signature-filter", 1, 0, 0}, // 6
623 {"intent", 1, 0, 0}, // 7
624 {"full-metadata", 0, 0, 0}, // 8
625 {"tmpdir", 1, 0, 0}, // 9
626 {"upload-script", 1, 0, 0}, // 10
631 int c = getopt_long(argc, argv, "", long_options, &long_index);
637 switch (long_index) {
639 localdb_dir = optarg;
642 if (optarg[0] != '/')
643 excludes.push_back(optarg);
645 excludes.push_back(optarg + 1);
648 filter_program = optarg;
650 case 3: // --filter-extension
651 filter_extension = optarg;
654 backup_dest = optarg;
657 backup_scheme = optarg;
659 case 6: // --signature-filter
660 signature_filter = optarg;
663 snapshot_intent = atof(optarg);
664 if (snapshot_intent <= 0)
667 case 8: // --full-metadata
668 flag_full_metadata = true;
673 case 10: // --upload-script
674 backup_script = optarg;
677 fprintf(stderr, "Unhandled long option!\n");
686 if (optind == argc) {
691 searches.push_back(".");
692 for (int i = optind; i < argc; i++)
693 add_include(argv[i]);
695 if (backup_dest == "" && backup_script == "") {
697 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
702 if (backup_dest != "" && backup_script != "") {
704 "Error: Cannot specify both --dest= and --upload-script=\n");
709 // Default for --localdb is the same as --dest
710 if (localdb_dir == "") {
711 localdb_dir = backup_dest;
713 if (localdb_dir == "") {
715 "Error: Must specify local database path with --localdb=\n");
720 // Dump paths for debugging/informational purposes
722 list<string>::const_iterator i;
724 printf("LBS Version: %s\n", lbs_version);
726 printf("--dest=%s\n--localdb=%s\n--upload-script=%s\n",
727 backup_dest.c_str(), localdb_dir.c_str(), backup_script.c_str());
729 printf("Includes:\n");
730 for (i = includes.begin(); i != includes.end(); ++i)
731 printf(" %s\n", i->c_str());
733 printf("Excludes:\n");
734 for (i = excludes.begin(); i != excludes.end(); ++i)
735 printf(" %s\n", i->c_str());
737 printf("Searching:\n");
738 for (i = searches.begin(); i != searches.end(); ++i)
739 printf(" %s\n", i->c_str());
742 block_buf = new char[LBS_BLOCK_SIZE];
744 /* Initialize the remote storage layer. If using an upload script, create
745 * a temporary directory for staging files. Otherwise, write backups
746 * directly to the destination directory. */
747 if (backup_script != "") {
748 tmp_dir = tmp_dir + "/lbs." + generate_uuid();
749 if (mkdir(tmp_dir.c_str(), 0700) < 0) {
750 fprintf(stderr, "Cannot create temporary directory %s: %m\n",
754 remote = new RemoteStore(tmp_dir);
755 remote->set_script(backup_script);
757 remote = new RemoteStore(backup_dest);
760 /* Store the time when the backup started, so it can be included in the
766 localtime_r(&now, &time_buf);
767 strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
769 /* Open the local database which tracks all objects that are stored
770 * remotely, for efficient incrementals. Provide it with the name of this
772 string database_path = localdb_dir + "/localdb.sqlite";
774 db->Open(database_path.c_str(), desc_buf,
775 backup_scheme.size() ? backup_scheme.c_str() : NULL,
778 tss = new TarSegmentStore(remote, db);
780 /* Initialize the stat cache, for skipping over unchanged files. */
781 metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
783 ? backup_scheme.c_str()
786 scanfile(".", false);
788 ObjectReference root_ref = metawriter->close();
789 add_segment(root_ref.get_segment());
790 string backup_root = root_ref.to_string();
798 /* Write out a checksums file which lists the checksums for all the
799 * segments included in this snapshot. The format is designed so that it
800 * may be easily verified using the sha1sums command. */
801 const char csum_type[] = "sha1";
802 string checksum_filename = "snapshot-";
803 if (backup_scheme.size() > 0)
804 checksum_filename += backup_scheme + "-";
805 checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
806 RemoteFile *checksum_file = remote->alloc_file(checksum_filename,
808 FILE *checksums = fdopen(checksum_file->get_fd(), "w");
810 for (std::set<string>::iterator i = segment_list.begin();
811 i != segment_list.end(); ++i) {
812 string seg_path, seg_csum;
813 if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
814 const char *raw_checksum = NULL;
815 if (strncmp(seg_csum.c_str(), csum_type,
816 strlen(csum_type)) == 0) {
817 raw_checksum = seg_csum.c_str() + strlen(csum_type);
818 if (*raw_checksum == '=')
824 if (raw_checksum != NULL)
825 fprintf(checksums, "%s *%s\n",
826 raw_checksum, seg_path.c_str());
830 checksum_file->send();
834 /* All other files should be flushed to remote storage before writing the
835 * backup descriptor below, so that it is not possible to have a backup
836 * descriptor written out depending on non-existent (not yet written)
840 /* Write a backup descriptor file, which says which segments are needed and
841 * where to start to restore this snapshot. The filename is based on the
842 * current time. If a signature filter program was specified, filter the
843 * data through that to give a chance to sign the descriptor contents. */
844 string desc_filename = "snapshot-";
845 if (backup_scheme.size() > 0)
846 desc_filename += backup_scheme + "-";
847 desc_filename = desc_filename + desc_buf + ".lbs";
849 RemoteFile *descriptor_file = remote->alloc_file(desc_filename,
851 int descriptor_fd = descriptor_file->get_fd();
852 if (descriptor_fd < 0) {
853 fprintf(stderr, "Unable to open descriptor output file: %m\n");
856 pid_t signature_pid = 0;
857 if (signature_filter.size() > 0) {
858 int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
860 close(descriptor_fd);
861 descriptor_fd = new_fd;
863 FILE *descriptor = fdopen(descriptor_fd, "w");
865 fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
866 fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
867 strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
868 fprintf(descriptor, "Date: %s\n", desc_buf);
869 if (backup_scheme.size() > 0)
870 fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
871 fprintf(descriptor, "Backup-Intent: %g\n", snapshot_intent);
872 fprintf(descriptor, "Root: %s\n", backup_root.c_str());
874 SHA1Checksum checksum_csum;
875 if (checksum_csum.process_file(checksum_filename.c_str())) {
876 string csum = checksum_csum.checksum_str();
877 fprintf(descriptor, "Checksums: %s\n", csum.c_str());
880 fprintf(descriptor, "Segments:\n");
881 for (std::set<string>::iterator i = segment_list.begin();
882 i != segment_list.end(); ++i) {
883 fprintf(descriptor, " %s\n", i->c_str());
890 waitpid(signature_pid, &status, 0);
892 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
893 throw IOException("Signature filter process error");
897 descriptor_file->send();
902 if (backup_script != "") {
903 if (rmdir(tmp_dir.c_str()) < 0) {
905 "Warning: Cannot delete temporary directory %s: %m\n",