Preliminary support for external file upload scripts.
[cumulus.git] / scandir.cc
1 /* Recursively descend the filesystem and visit each file. */
2
3 #include <dirent.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <getopt.h>
7 #include <grp.h>
8 #include <pwd.h>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <sys/stat.h>
13 #include <sys/sysmacros.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
17
18 #include <algorithm>
19 #include <fstream>
20 #include <iostream>
21 #include <list>
22 #include <set>
23 #include <sstream>
24 #include <string>
25 #include <vector>
26
27 #include "localdb.h"
28 #include "metadata.h"
29 #include "remote.h"
30 #include "store.h"
31 #include "sha1.h"
32 #include "util.h"
33
34 using std::list;
35 using std::string;
36 using std::vector;
37 using std::ostream;
38
39 /* Version information.  This will be filled in by the Makefile. */
40 #ifndef LBS_VERSION
41 #define LBS_VERSION Unknown
42 #endif
43 #define LBS_STRINGIFY(s) LBS_STRINGIFY2(s)
44 #define LBS_STRINGIFY2(s) #s
45 static const char lbs_version[] = LBS_STRINGIFY(LBS_VERSION);
46
47 static RemoteStore *remote = NULL;
48 static TarSegmentStore *tss = NULL;
49 static MetadataWriter *metawriter = NULL;
50
51 /* Buffer for holding a single block of data read from a file. */
52 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
53 static char *block_buf;
54
55 /* Local database, which tracks objects written in this and previous
56  * invocations to help in creating incremental snapshots. */
57 LocalDb *db;
58
59 /* Keep track of all segments which are needed to reconstruct the snapshot. */
60 std::set<string> segment_list;
61
62 /* Snapshot intent: 1=daily, 7=weekly, etc.  This is not used directly, but is
63  * stored in the local database and can help guide segment cleaning and
64  * snapshot expiration policies. */
65 double snapshot_intent = 1.0;
66
67 /* Selection of files to include/exclude in the snapshot. */
68 std::list<string> includes;         // Paths in which files should be saved
69 std::list<string> excludes;         // Paths which will not be saved
70 std::list<string> searches;         // Directories we don't want to save, but
71                                     //   do want to descend searching for data
72                                     //   in included paths
73
74 bool relative_paths = true;
75
76 /* Ensure that the given segment is listed as a dependency of the current
77  * snapshot. */
78 void add_segment(const string& segment)
79 {
80     segment_list.insert(segment);
81 }
82
83 /* Read data from a file descriptor and return the amount of data read.  A
84  * short read (less than the requested size) will only occur if end-of-file is
85  * hit. */
86 ssize_t file_read(int fd, char *buf, size_t maxlen)
87 {
88     size_t bytes_read = 0;
89
90     while (true) {
91         ssize_t res = read(fd, buf, maxlen);
92         if (res < 0) {
93             if (errno == EINTR)
94                 continue;
95             fprintf(stderr, "error reading file: %m\n");
96             return -1;
97         } else if (res == 0) {
98             break;
99         } else {
100             bytes_read += res;
101             buf += res;
102             maxlen -= res;
103         }
104     }
105
106     return bytes_read;
107 }
108
109 /* Read the contents of a file (specified by an open file descriptor) and copy
110  * the data to the store.  Returns the size of the file (number of bytes
111  * dumped), or -1 on error. */
112 int64_t dumpfile(int fd, dictionary &file_info, const string &path,
113                  struct stat& stat_buf)
114 {
115     int64_t size = 0;
116     list<string> object_list;
117     const char *status = NULL;          /* Status indicator printed out */
118
119     /* Look up this file in the old stat cache, if we can.  If the stat
120      * information indicates that the file has not changed, do not bother
121      * re-reading the entire contents. */
122     bool cached = false;
123
124     if (metawriter->find(path) && metawriter->is_unchanged(&stat_buf)) {
125         cached = true;
126         list<ObjectReference> blocks = metawriter->get_blocks();
127
128         /* If any of the blocks in the object have been expired, then we should
129          * fall back to fully reading in the file. */
130         for (list<ObjectReference>::const_iterator i = blocks.begin();
131              i != blocks.end(); ++i) {
132             const ObjectReference &ref = *i;
133             if (!db->IsAvailable(ref)) {
134                 cached = false;
135                 status = "repack";
136                 break;
137             }
138         }
139
140         /* If everything looks okay, use the cached information */
141         if (cached) {
142             file_info["checksum"] = metawriter->get_checksum();
143             for (list<ObjectReference>::const_iterator i = blocks.begin();
144                  i != blocks.end(); ++i) {
145                 const ObjectReference &ref = *i;
146                 object_list.push_back(ref.to_string());
147                 if (ref.is_normal())
148                     add_segment(ref.get_segment());
149                 db->UseObject(ref);
150             }
151             size = stat_buf.st_size;
152         }
153     }
154
155     /* If the file is new or changed, we must read in the contents a block at a
156      * time. */
157     if (!cached) {
158         SHA1Checksum hash;
159         while (true) {
160             ssize_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
161             if (bytes == 0)
162                 break;
163             if (bytes < 0) {
164                 fprintf(stderr, "Backup contents for %s may be incorrect\n",
165                         path.c_str());
166                 break;
167             }
168
169             hash.process(block_buf, bytes);
170
171             // Sparse file processing: if we read a block of all zeroes, encode
172             // that explicitly.
173             bool all_zero = true;
174             for (int i = 0; i < bytes; i++) {
175                 if (block_buf[i] != 0) {
176                     all_zero = false;
177                     break;
178                 }
179             }
180
181             // Either find a copy of this block in an already-existing segment,
182             // or index it so it can be re-used in the future
183             double block_age = 0.0;
184             ObjectReference ref;
185
186             SHA1Checksum block_hash;
187             block_hash.process(block_buf, bytes);
188             string block_csum = block_hash.checksum_str();
189
190             if (all_zero) {
191                 ref = ObjectReference(ObjectReference::REF_ZERO);
192                 ref.set_range(0, bytes);
193             } else {
194                 ref = db->FindObject(block_csum, bytes);
195             }
196
197             // Store a copy of the object if one does not yet exist
198             if (ref.is_null()) {
199                 LbsObject *o = new LbsObject;
200                 int object_group;
201
202                 /* We might still have seen this checksum before, if the object
203                  * was stored at some time in the past, but we have decided to
204                  * clean the segment the object was originally stored in
205                  * (FindObject will not return such objects).  When rewriting
206                  * the object contents, put it in a separate group, so that old
207                  * objects get grouped together.  The hope is that these old
208                  * objects will continue to be used in the future, and we
209                  * obtain segments which will continue to be well-utilized.
210                  * Additionally, keep track of the age of the data by looking
211                  * up the age of the block which was expired and using that
212                  * instead of the current time. */
213                 if (db->IsOldObject(block_csum, bytes,
214                                     &block_age, &object_group)) {
215                     if (object_group == 0) {
216                         o->set_group("data");
217                     } else {
218                         char group[32];
219                         sprintf(group, "compacted-%d", object_group);
220                         o->set_group(group);
221                     }
222                     if (status == NULL)
223                         status = "partial";
224                 } else {
225                     o->set_group("data");
226                     status = "new";
227                 }
228
229                 o->set_data(block_buf, bytes);
230                 o->write(tss);
231                 ref = o->get_ref();
232                 db->StoreObject(ref, block_csum, bytes, block_age);
233                 ref.set_range(0, bytes);
234                 delete o;
235             }
236
237             object_list.push_back(ref.to_string());
238             if (ref.is_normal())
239                 add_segment(ref.get_segment());
240             db->UseObject(ref);
241             size += bytes;
242
243             if (status == NULL)
244                 status = "old";
245         }
246
247         file_info["checksum"] = hash.checksum_str();
248     }
249
250     if (status != NULL)
251         printf("    [%s]\n", status);
252
253     string blocklist = "";
254     for (list<string>::iterator i = object_list.begin();
255          i != object_list.end(); ++i) {
256         if (i != object_list.begin())
257             blocklist += "\n    ";
258         blocklist += *i;
259     }
260     file_info["data"] = blocklist;
261
262     return size;
263 }
264
265 /* Dump a specified filesystem object (file, directory, etc.) based on its
266  * inode information.  If the object is a regular file, an open filehandle is
267  * provided. */
268 void dump_inode(const string& path,         // Path within snapshot
269                 const string& fullpath,     // Path to object in filesystem
270                 struct stat& stat_buf,      // Results of stat() call
271                 int fd)                     // Open filehandle if regular file
272 {
273     char *buf;
274     dictionary file_info;
275     int64_t file_size;
276     ssize_t len;
277
278     printf("%s\n", path.c_str());
279     metawriter->find(path);
280
281     file_info["name"] = uri_encode(path);
282     file_info["mode"] = encode_int(stat_buf.st_mode & 07777, 8);
283     file_info["ctime"] = encode_int(stat_buf.st_ctime);
284     file_info["mtime"] = encode_int(stat_buf.st_mtime);
285     file_info["user"] = encode_int(stat_buf.st_uid);
286     file_info["group"] = encode_int(stat_buf.st_gid);
287
288     time_t now = time(NULL);
289     if (now - stat_buf.st_ctime < 30 || now - stat_buf.st_mtime < 30)
290         if ((stat_buf.st_mode & S_IFMT) != S_IFDIR)
291             file_info["volatile"] = "1";
292
293     struct passwd *pwd = getpwuid(stat_buf.st_uid);
294     if (pwd != NULL) {
295         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
296     }
297
298     struct group *grp = getgrgid(stat_buf.st_gid);
299     if (pwd != NULL) {
300         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
301     }
302
303     if (stat_buf.st_nlink > 1 && (stat_buf.st_mode & S_IFMT) != S_IFDIR) {
304         file_info["links"] = encode_int(stat_buf.st_nlink);
305     }
306
307     file_info["inode"] = encode_int(major(stat_buf.st_dev))
308         + "/" + encode_int(minor(stat_buf.st_dev))
309         + "/" + encode_int(stat_buf.st_ino);
310
311     char inode_type;
312
313     switch (stat_buf.st_mode & S_IFMT) {
314     case S_IFIFO:
315         inode_type = 'p';
316         break;
317     case S_IFSOCK:
318         inode_type = 's';
319         break;
320     case S_IFBLK:
321     case S_IFCHR:
322         inode_type = ((stat_buf.st_mode & S_IFMT) == S_IFBLK) ? 'b' : 'c';
323         file_info["device"] = encode_int(major(stat_buf.st_rdev))
324             + "/" + encode_int(minor(stat_buf.st_rdev));
325         break;
326     case S_IFLNK:
327         inode_type = 'l';
328
329         /* Use the reported file size to allocate a buffer large enough to read
330          * the symlink.  Allocate slightly more space, so that we ask for more
331          * bytes than we expect and so check for truncation. */
332         buf = new char[stat_buf.st_size + 2];
333         len = readlink(fullpath.c_str(), buf, stat_buf.st_size + 1);
334         if (len < 0) {
335             fprintf(stderr, "error reading symlink: %m\n");
336         } else if (len <= stat_buf.st_size) {
337             buf[len] = '\0';
338             file_info["target"] = uri_encode(buf);
339         } else if (len > stat_buf.st_size) {
340             fprintf(stderr, "error reading symlink: name truncated\n");
341         }
342
343         delete[] buf;
344         break;
345     case S_IFREG:
346         inode_type = 'f';
347
348         file_size = dumpfile(fd, file_info, path, stat_buf);
349         file_info["size"] = encode_int(file_size);
350
351         if (file_size < 0)
352             return;             // error occurred; do not dump file
353
354         if (file_size != stat_buf.st_size) {
355             fprintf(stderr, "Warning: Size of %s changed during reading\n",
356                     path.c_str());
357             file_info["volatile"] = "1";
358         }
359
360         break;
361     case S_IFDIR:
362         inode_type = 'd';
363         break;
364
365     default:
366         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
367         return;
368     }
369
370     file_info["type"] = string(1, inode_type);
371
372     metawriter->add(file_info);
373 }
374
375 void scanfile(const string& path, bool include)
376 {
377     int fd = -1;
378     long flags;
379     struct stat stat_buf;
380     list<string> refs;
381
382     string true_path;
383     if (relative_paths)
384         true_path = path;
385     else
386         true_path = "/" + path;
387
388     // Set to true if we should scan through the contents of this directory,
389     // but not actually back files up
390     bool scan_only = false;
391
392     // Check this file against the include/exclude list to see if it should be
393     // considered
394     for (list<string>::iterator i = includes.begin();
395          i != includes.end(); ++i) {
396         if (path == *i) {
397             printf("Including %s\n", path.c_str());
398             include = true;
399         }
400     }
401
402     for (list<string>::iterator i = excludes.begin();
403          i != excludes.end(); ++i) {
404         if (path == *i) {
405             printf("Excluding %s\n", path.c_str());
406             include = false;
407         }
408     }
409
410     for (list<string>::iterator i = searches.begin();
411          i != searches.end(); ++i) {
412         if (path == *i) {
413             printf("Scanning %s\n", path.c_str());
414             scan_only = true;
415         }
416     }
417
418     if (!include && !scan_only)
419         return;
420
421     if (lstat(true_path.c_str(), &stat_buf) < 0) {
422         fprintf(stderr, "lstat(%s): %m\n", path.c_str());
423         return;
424     }
425
426     if ((stat_buf.st_mode & S_IFMT) == S_IFREG) {
427         /* Be paranoid when opening the file.  We have no guarantee that the
428          * file was not replaced between the stat() call above and the open()
429          * call below, so we might not even be opening a regular file.  We
430          * supply flags to open to to guard against various conditions before
431          * we can perform an lstat to check that the file is still a regular
432          * file:
433          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
434          *   - O_NONBLOCK: prevents open() from blocking if the file was
435          *     replaced by a fifo
436          * We also add in O_NOATIME, since this may reduce disk writes (for
437          * inode updates).  However, O_NOATIME may result in EPERM, so if the
438          * initial open fails, try again without O_NOATIME.  */
439         fd = open(true_path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
440         if (fd < 0) {
441             fd = open(true_path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
442         }
443         if (fd < 0) {
444             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
445             return;
446         }
447
448         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
449          * open. */
450         flags = fcntl(fd, F_GETFL);
451         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
452
453         /* Perform the stat call again, and check that we still have a regular
454          * file. */
455         if (fstat(fd, &stat_buf) < 0) {
456             fprintf(stderr, "fstat: %m\n");
457             close(fd);
458             return;
459         }
460
461         if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
462             fprintf(stderr, "file is no longer a regular file!\n");
463             close(fd);
464             return;
465         }
466     }
467
468     dump_inode(path, true_path, stat_buf, fd);
469
470     if (fd >= 0)
471         close(fd);
472
473     // If we hit a directory, now that we've written the directory itself,
474     // recursively scan the directory.
475     if ((stat_buf.st_mode & S_IFMT) == S_IFDIR) {
476         DIR *dir = opendir(true_path.c_str());
477
478         if (dir == NULL) {
479             fprintf(stderr, "Error: %m\n");
480             return;
481         }
482
483         struct dirent *ent;
484         vector<string> contents;
485         while ((ent = readdir(dir)) != NULL) {
486             string filename(ent->d_name);
487             if (filename == "." || filename == "..")
488                 continue;
489             contents.push_back(filename);
490         }
491
492         closedir(dir);
493
494         sort(contents.begin(), contents.end());
495
496         for (vector<string>::iterator i = contents.begin();
497              i != contents.end(); ++i) {
498             const string& filename = *i;
499             if (path == ".")
500                 scanfile(filename, include);
501             else
502                 scanfile(path + "/" + filename, include);
503         }
504     }
505 }
506
507 /* Include the specified file path in the backups.  Append the path to the
508  * includes list, and to ensure that we actually see the path when scanning the
509  * directory tree, add all the parent directories to the search list, which
510  * means we will scan through the directory listing even if the files
511  * themselves are excluded from being backed up. */
512 void add_include(const char *path)
513 {
514     printf("Add: %s\n", path);
515     /* Was an absolute path specified?  If so, we'll need to start scanning
516      * from the root directory.  Make sure that the user was consistent in
517      * providing either all relative paths or all absolute paths. */
518     if (path[0] == '/') {
519         if (includes.size() > 0 && relative_paths == true) {
520             fprintf(stderr,
521                     "Error: Cannot mix relative and absolute paths!\n");
522             exit(1);
523         }
524
525         relative_paths = false;
526
527         // Skip over leading '/'
528         path++;
529     } else if (relative_paths == false && path[0] != '/') {
530         fprintf(stderr, "Error: Cannot mix relative and absolute paths!\n");
531         exit(1);
532     }
533
534     includes.push_back(path);
535
536     /* Split the specified path into directory components, and ensure that we
537      * descend into all the directories along the path. */
538     const char *slash = path;
539
540     if (path[0] == '\0')
541         return;
542
543     while ((slash = strchr(slash + 1, '/')) != NULL) {
544         string component(path, slash - path);
545         searches.push_back(component);
546     }
547 }
548
549 void usage(const char *program)
550 {
551     fprintf(
552         stderr,
553         "LBS %s\n\n"
554         "Usage: %s [OPTION]... --dest=DEST PATHS...\n"
555         "Produce backup snapshot of files in SOURCE and store to DEST.\n"
556         "\n"
557         "Options:\n"
558         "  --dest=PATH          path where backup is to be written\n"
559         "  --upload-script=COMMAND\n"
560         "                       program to invoke for each backup file generated\n"
561         "  --exclude=PATH       exclude files in PATH from snapshot\n"
562         "  --localdb=PATH       local backup metadata is stored in PATH\n"
563         "  --tmpdir=PATH        path for temporarily storing backup files\n"
564         "                           (defaults to TMPDIR environment variable or /tmp)\n"
565         "  --filter=COMMAND     program through which to filter segment data\n"
566         "                           (defaults to \"bzip2 -c\")\n"
567         "  --filter-extension=EXT\n"
568         "                       string to append to segment files\n"
569         "                           (defaults to \".bz2\")\n"
570         "  --signature-filter=COMMAND\n"
571         "                       program though which to filter descriptor\n"
572         "  --scheme=NAME        optional name for this snapshot\n"
573         "  --intent=FLOAT       intended backup type: 1=daily, 7=weekly, ...\n"
574         "                           (defaults to \"1\")\n"
575         "  --full-metadata      do not re-use metadata from previous backups\n"
576         "\n"
577         "Exactly one of --dest or --upload-script must be specified.\n",
578         lbs_version, program
579     );
580 }
581
582 int main(int argc, char *argv[])
583 {
584     string backup_dest = "", backup_script = "";
585     string localdb_dir = "";
586     string backup_scheme = "";
587     string signature_filter = "";
588
589     string tmp_dir = "/tmp";
590     if (getenv("TMPDIR") != NULL)
591         tmp_dir = getenv("TMPDIR");
592
593     while (1) {
594         static struct option long_options[] = {
595             {"localdb", 1, 0, 0},           // 0
596             {"exclude", 1, 0, 0},           // 1
597             {"filter", 1, 0, 0},            // 2
598             {"filter-extension", 1, 0, 0},  // 3
599             {"dest", 1, 0, 0},              // 4
600             {"scheme", 1, 0, 0},            // 5
601             {"signature-filter", 1, 0, 0},  // 6
602             {"intent", 1, 0, 0},            // 7
603             {"full-metadata", 0, 0, 0},     // 8
604             {"tmpdir", 1, 0, 0},            // 9
605             {"upload-script", 1, 0, 0},     // 10
606             {NULL, 0, 0, 0},
607         };
608
609         int long_index;
610         int c = getopt_long(argc, argv, "", long_options, &long_index);
611
612         if (c == -1)
613             break;
614
615         if (c == 0) {
616             switch (long_index) {
617             case 0:     // --localdb
618                 localdb_dir = optarg;
619                 break;
620             case 1:     // --exclude
621                 if (optarg[0] != '/')
622                     excludes.push_back(optarg);
623                 else
624                     excludes.push_back(optarg + 1);
625                 break;
626             case 2:     // --filter
627                 filter_program = optarg;
628                 break;
629             case 3:     // --filter-extension
630                 filter_extension = optarg;
631                 break;
632             case 4:     // --dest
633                 backup_dest = optarg;
634                 break;
635             case 5:     // --scheme
636                 backup_scheme = optarg;
637                 break;
638             case 6:     // --signature-filter
639                 signature_filter = optarg;
640                 break;
641             case 7:     // --intent
642                 snapshot_intent = atof(optarg);
643                 if (snapshot_intent <= 0)
644                     snapshot_intent = 1;
645                 break;
646             case 8:     // --full-metadata
647                 flag_full_metadata = true;
648                 break;
649             case 9:     // --tmpdir
650                 tmp_dir = optarg;
651                 break;
652             case 10:    // --upload-script
653                 backup_script = optarg;
654                 break;
655             default:
656                 fprintf(stderr, "Unhandled long option!\n");
657                 return 1;
658             }
659         } else {
660             usage(argv[0]);
661             return 1;
662         }
663     }
664
665     if (optind == argc) {
666         usage(argv[0]);
667         return 1;
668     }
669
670     searches.push_back(".");
671     for (int i = optind; i < argc; i++)
672         add_include(argv[i]);
673
674     if (backup_dest == "" && backup_script == "") {
675         fprintf(stderr,
676                 "Error: Backup destination must be specified using --dest= or --upload-script=\n");
677         usage(argv[0]);
678         return 1;
679     }
680
681     if (backup_dest != "" && backup_script != "") {
682         fprintf(stderr,
683                 "Error: Cannot specify both --dest= and --upload-script=\n");
684         usage(argv[0]);
685         return 1;
686     }
687
688     // Default for --localdb is the same as --dest
689     if (localdb_dir == "") {
690         localdb_dir = backup_dest;
691     }
692     if (localdb_dir == "") {
693         fprintf(stderr,
694                 "Error: Must specify local database path with --localdb=\n");
695         usage(argv[0]);
696         return 1;
697     }
698
699     // Dump paths for debugging/informational purposes
700     {
701         list<string>::const_iterator i;
702
703         printf("LBS Version: %s\n", lbs_version);
704
705         printf("--dest=%s\n--localdb=%s\n--upload-script=%s\n",
706                backup_dest.c_str(), localdb_dir.c_str(), backup_script.c_str());
707
708         printf("Includes:\n");
709         for (i = includes.begin(); i != includes.end(); ++i)
710             printf("    %s\n", i->c_str());
711
712         printf("Excludes:\n");
713         for (i = excludes.begin(); i != excludes.end(); ++i)
714             printf("    %s\n", i->c_str());
715
716         printf("Searching:\n");
717         for (i = searches.begin(); i != searches.end(); ++i)
718             printf("    %s\n", i->c_str());
719     }
720
721     block_buf = new char[LBS_BLOCK_SIZE];
722
723     /* Initialize the remote storage layer.  If using an upload script, create
724      * a temporary directory for staging files.  Otherwise, write backups
725      * directly to the destination directory. */
726     if (backup_script != "") {
727         tmp_dir = tmp_dir + "/lbs." + generate_uuid();
728         if (mkdir(tmp_dir.c_str(), 0700) < 0) {
729             fprintf(stderr, "Cannot create temporary directory %s: %m\n",
730                     tmp_dir.c_str());
731             return 1;
732         }
733         remote = new RemoteStore(tmp_dir);
734         remote->set_script(backup_script);
735     } else {
736         remote = new RemoteStore(backup_dest);
737     }
738
739     /* Store the time when the backup started, so it can be included in the
740      * snapshot name. */
741     time_t now;
742     struct tm time_buf;
743     char desc_buf[256];
744     time(&now);
745     localtime_r(&now, &time_buf);
746     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
747
748     /* Open the local database which tracks all objects that are stored
749      * remotely, for efficient incrementals.  Provide it with the name of this
750      * snapshot. */
751     string database_path = localdb_dir + "/localdb.sqlite";
752     db = new LocalDb;
753     db->Open(database_path.c_str(), desc_buf,
754              backup_scheme.size() ? backup_scheme.c_str() : NULL,
755              snapshot_intent);
756
757     tss = new TarSegmentStore(remote, db);
758
759     /* Initialize the stat cache, for skipping over unchanged files. */
760     metawriter = new MetadataWriter(tss, localdb_dir.c_str(), desc_buf,
761                                     backup_scheme.size()
762                                         ? backup_scheme.c_str()
763                                         : NULL);
764
765     scanfile(".", false);
766
767     ObjectReference root_ref = metawriter->close();
768     add_segment(root_ref.get_segment());
769     string backup_root = root_ref.to_string();
770
771     delete metawriter;
772
773     tss->sync();
774     tss->dump_stats();
775     delete tss;
776
777     /* Write out a checksums file which lists the checksums for all the
778      * segments included in this snapshot.  The format is designed so that it
779      * may be easily verified using the sha1sums command. */
780     const char csum_type[] = "sha1";
781     string checksum_filename = "snapshot-";
782     if (backup_scheme.size() > 0)
783         checksum_filename += backup_scheme + "-";
784     checksum_filename = checksum_filename + desc_buf + "." + csum_type + "sums";
785     RemoteFile *checksum_file = remote->alloc_file(checksum_filename);
786     FILE *checksums = fdopen(checksum_file->get_fd(), "w");
787
788     for (std::set<string>::iterator i = segment_list.begin();
789          i != segment_list.end(); ++i) {
790         string seg_path, seg_csum;
791         if (db->GetSegmentChecksum(*i, &seg_path, &seg_csum)) {
792             const char *raw_checksum = NULL;
793             if (strncmp(seg_csum.c_str(), csum_type,
794                         strlen(csum_type)) == 0) {
795                 raw_checksum = seg_csum.c_str() + strlen(csum_type);
796                 if (*raw_checksum == '=')
797                     raw_checksum++;
798                 else
799                     raw_checksum = NULL;
800             }
801
802             if (raw_checksum != NULL)
803                 fprintf(checksums, "%s *%s\n",
804                         raw_checksum, seg_path.c_str());
805         }
806     }
807     fclose(checksums);
808     checksum_file->send();
809
810     db->Close();
811
812     /* All other files should be flushed to remote storage before writing the
813      * backup descriptor below, so that it is not possible to have a backup
814      * descriptor written out depending on non-existent (not yet written)
815      * files. */
816     remote->sync();
817
818     /* Write a backup descriptor file, which says which segments are needed and
819      * where to start to restore this snapshot.  The filename is based on the
820      * current time.  If a signature filter program was specified, filter the
821      * data through that to give a chance to sign the descriptor contents. */
822     string desc_filename = "snapshot-";
823     if (backup_scheme.size() > 0)
824         desc_filename += backup_scheme + "-";
825     desc_filename = desc_filename + desc_buf + ".lbs";
826
827     RemoteFile *descriptor_file = remote->alloc_file(desc_filename);
828     int descriptor_fd = descriptor_file->get_fd();
829     if (descriptor_fd < 0) {
830         fprintf(stderr, "Unable to open descriptor output file: %m\n");
831         return 1;
832     }
833     pid_t signature_pid = 0;
834     if (signature_filter.size() > 0) {
835         int new_fd = spawn_filter(descriptor_fd, signature_filter.c_str(),
836                                   &signature_pid);
837         close(descriptor_fd);
838         descriptor_fd = new_fd;
839     }
840     FILE *descriptor = fdopen(descriptor_fd, "w");
841
842     fprintf(descriptor, "Format: LBS Snapshot v0.6\n");
843     fprintf(descriptor, "Producer: LBS %s\n", lbs_version);
844     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
845     fprintf(descriptor, "Date: %s\n", desc_buf);
846     if (backup_scheme.size() > 0)
847         fprintf(descriptor, "Scheme: %s\n", backup_scheme.c_str());
848     fprintf(descriptor, "Backup-Intent: %g\n", snapshot_intent);
849     fprintf(descriptor, "Root: %s\n", backup_root.c_str());
850
851     SHA1Checksum checksum_csum;
852     if (checksum_csum.process_file(checksum_filename.c_str())) {
853         string csum = checksum_csum.checksum_str();
854         fprintf(descriptor, "Checksums: %s\n", csum.c_str());
855     }
856
857     fprintf(descriptor, "Segments:\n");
858     for (std::set<string>::iterator i = segment_list.begin();
859          i != segment_list.end(); ++i) {
860         fprintf(descriptor, "    %s\n", i->c_str());
861     }
862
863     fclose(descriptor);
864
865     if (signature_pid) {
866         int status;
867         waitpid(signature_pid, &status, 0);
868
869         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
870             throw IOException("Signature filter process error");
871         }
872     }
873
874     descriptor_file->send();
875
876     remote->sync();
877     delete remote;
878
879     if (backup_script != "") {
880         if (rmdir(tmp_dir.c_str()) < 0) {
881             fprintf(stderr,
882                     "Warning: Cannot delete temporary directory %s: %m\n",
883                     tmp_dir.c_str());
884         }
885     }
886
887     return 0;
888 }