Make segment compression/encryption filter to command-line-selectable.
[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/types.h>
14 #include <unistd.h>
15
16 #include <algorithm>
17 #include <fstream>
18 #include <iostream>
19 #include <list>
20 #include <set>
21 #include <sstream>
22 #include <string>
23 #include <vector>
24
25 #include "format.h"
26 #include "localdb.h"
27 #include "store.h"
28 #include "sha1.h"
29
30 using std::list;
31 using std::string;
32 using std::vector;
33 using std::ostream;
34
35 static TarSegmentStore *tss = NULL;
36
37 /* Buffer for holding a single block of data read from a file. */
38 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
39 static char *block_buf;
40
41 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
42
43 /* Local database, which tracks objects written in this and previous
44  * invocations to help in creating incremental snapshots. */
45 LocalDb *db;
46
47 /* Contents of the root object.  This will contain a set of indirect links to
48  * the metadata objects. */
49 std::ostringstream metadata_root;
50
51 /* Buffer for building up metadata. */
52 std::ostringstream metadata;
53
54 /* Keep track of all segments which are needed to reconstruct the snapshot. */
55 std::set<string> segment_list;
56
57 void scandir(const string& path);
58
59 /* Selection of files to include/exclude in the snapshot. */
60 std::list<string> excludes;
61
62 /* Ensure contents of metadata are flushed to an object. */
63 void metadata_flush()
64 {
65     string m = metadata.str();
66     if (m.size() == 0)
67         return;
68
69     /* Write current metadata information to a new object. */
70     LbsObject *meta = new LbsObject;
71     meta->set_group("metadata");
72     meta->set_data(m.data(), m.size());
73     meta->write(tss);
74     meta->checksum();
75
76     /* Write a reference to this block in the root. */
77     ObjectReference ref = meta->get_ref();
78     metadata_root << "@" << ref.to_string() << "\n";
79     segment_list.insert(ref.get_segment());
80
81     delete meta;
82
83     metadata.str("");
84 }
85
86 /* Read data from a file descriptor and return the amount of data read.  A
87  * short read (less than the requested size) will only occur if end-of-file is
88  * hit. */
89 size_t file_read(int fd, char *buf, size_t maxlen)
90 {
91     size_t bytes_read = 0;
92
93     while (true) {
94         ssize_t res = read(fd, buf, maxlen);
95         if (res < 0) {
96             if (errno == EINTR)
97                 continue;
98             throw IOException("file_read: error reading");
99         } else if (res == 0) {
100             break;
101         } else {
102             bytes_read += res;
103             buf += res;
104             maxlen -= res;
105         }
106     }
107
108     return bytes_read;
109 }
110
111 /* Read the contents of a file (specified by an open file descriptor) and copy
112  * the data to the store.  Returns the size of the file (number of bytes
113  * dumped), or -1 on error. */
114 int64_t dumpfile(int fd, dictionary &file_info)
115 {
116     struct stat stat_buf;
117     fstat(fd, &stat_buf);
118     int64_t size = 0;
119     list<string> object_list;
120
121     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
122         fprintf(stderr, "file is no longer a regular file!\n");
123         return -1;
124     }
125
126     /* The index data consists of a sequence of pointers to the data blocks
127      * that actually comprise the file data.  This level of indirection is used
128      * so that the same data block can be used in multiple files, or multiple
129      * versions of the same file. */
130     SHA1Checksum hash;
131     while (true) {
132         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
133         if (bytes == 0)
134             break;
135
136         hash.process(block_buf, bytes);
137
138         // Either find a copy of this block in an already-existing segment, or
139         // index it so it can be re-used in the future
140         SHA1Checksum block_hash;
141         block_hash.process(block_buf, bytes);
142         string block_csum = block_hash.checksum_str();
143         ObjectReference ref = db->FindObject(block_csum, bytes);
144
145         // Store a copy of the object if one does not yet exist
146         if (ref.get_segment().size() == 0) {
147             LbsObject *o = new LbsObject;
148
149             /* We might still have seen this checksum before, if the object was
150              * stored at some time in the past, but we have decided to clean
151              * the segment the object was originally stored in (FindObject will
152              * not return such objects).  When rewriting the object contents,
153              * put it in a separate group, so that old objects get grouped
154              * together.  The hope is that these old objects will continue to
155              * be used in the future, and we obtain segments which will
156              * continue to be well-utilized. */
157             if (db->IsOldObject(block_csum, bytes))
158                 o->set_group("compacted");
159             else
160                 o->set_group("data");
161
162             o->set_data(block_buf, bytes);
163             o->write(tss);
164             ref = o->get_ref();
165             db->StoreObject(ref, block_csum, bytes);
166             delete o;
167         }
168
169         object_list.push_back(ref.to_string());
170         segment_list.insert(ref.get_segment());
171         db->UseObject(ref);
172         size += bytes;
173     }
174
175     file_info["checksum"] = hash.checksum_str();
176
177     /* For files that only need to be broken apart into a few objects, store
178      * the list of objects directly.  For larger files, store the data
179      * out-of-line and provide a pointer to the indrect object. */
180     if (object_list.size() < 8) {
181         string blocklist = "";
182         for (list<string>::iterator i = object_list.begin();
183              i != object_list.end(); ++i) {
184             if (i != object_list.begin())
185                 blocklist += " ";
186             blocklist += *i;
187         }
188         file_info["data"] = blocklist;
189     } else {
190         string blocklist = "";
191         for (list<string>::iterator i = object_list.begin();
192              i != object_list.end(); ++i) {
193             blocklist += *i + "\n";
194         }
195
196         LbsObject *i = new LbsObject;
197         i->set_group("metadata");
198         i->set_data(blocklist.data(), blocklist.size());
199         i->write(tss);
200         file_info["data"] = "@" + i->get_name();
201         segment_list.insert(i->get_ref().get_segment());
202         delete i;
203     }
204
205     return size;
206 }
207
208 void scanfile(const string& path)
209 {
210     int fd;
211     long flags;
212     struct stat stat_buf;
213     char *buf;
214     ssize_t len;
215     int64_t file_size;
216     list<string> refs;
217
218     // Set to true if the item is a directory and we should recursively scan
219     bool recurse = false;
220
221     // Check this file against the include/exclude list to see if it should be
222     // considered
223     for (list<string>::iterator i = excludes.begin();
224          i != excludes.end(); ++i) {
225         if (path == *i) {
226             printf("Excluding %s\n", path.c_str());
227             return;
228         }
229     }
230
231     dictionary file_info;
232
233     lstat(path.c_str(), &stat_buf);
234
235     printf("%s\n", path.c_str());
236
237     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
238     file_info["mtime"] = encode_int(stat_buf.st_mtime);
239     file_info["user"] = encode_int(stat_buf.st_uid);
240     file_info["group"] = encode_int(stat_buf.st_gid);
241
242     struct passwd *pwd = getpwuid(stat_buf.st_uid);
243     if (pwd != NULL) {
244         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
245     }
246
247     struct group *grp = getgrgid(stat_buf.st_gid);
248     if (pwd != NULL) {
249         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
250     }
251
252     char inode_type;
253
254     switch (stat_buf.st_mode & S_IFMT) {
255     case S_IFIFO:
256         inode_type = 'p';
257         break;
258     case S_IFSOCK:
259         inode_type = 's';
260         break;
261     case S_IFCHR:
262         inode_type = 'c';
263         break;
264     case S_IFBLK:
265         inode_type = 'b';
266         break;
267     case S_IFLNK:
268         inode_type = 'l';
269
270         /* Use the reported file size to allocate a buffer large enough to read
271          * the symlink.  Allocate slightly more space, so that we ask for more
272          * bytes than we expect and so check for truncation. */
273         buf = new char[stat_buf.st_size + 2];
274         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
275         if (len < 0) {
276             fprintf(stderr, "error reading symlink: %m\n");
277         } else if (len <= stat_buf.st_size) {
278             buf[len] = '\0';
279             file_info["contents"] = uri_encode(buf);
280         } else if (len > stat_buf.st_size) {
281             fprintf(stderr, "error reading symlink: name truncated\n");
282         }
283
284         delete[] buf;
285         break;
286     case S_IFREG:
287         inode_type = '-';
288
289         /* Be paranoid when opening the file.  We have no guarantee that the
290          * file was not replaced between the stat() call above and the open()
291          * call below, so we might not even be opening a regular file.  That
292          * the file descriptor refers to a regular file is checked in
293          * dumpfile().  But we also supply flags to open to to guard against
294          * various conditions before we can perform that verification:
295          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
296          *   - O_NONBLOCK: prevents open() from blocking if the file was
297          *     replaced by a fifo
298          * We also add in O_NOATIME, since this may reduce disk writes (for
299          * inode updates).  However, O_NOATIME may result in EPERM, so if the
300          * initial open fails, try again without O_NOATIME.  */
301         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
302         if (fd < 0) {
303             fd = open(path.c_str(), O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
304         }
305         if (fd < 0) {
306             fprintf(stderr, "Unable to open file %s: %m\n", path.c_str());
307             return;
308         }
309
310         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
311          * open. */
312         flags = fcntl(fd, F_GETFL);
313         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
314
315         file_size = dumpfile(fd, file_info);
316         file_info["size"] = encode_int(file_size);
317         close(fd);
318
319         if (file_size < 0)
320             return;             // error occurred; do not dump file
321
322         if (file_size != stat_buf.st_size) {
323             fprintf(stderr, "Warning: Size of %s changed during reading\n",
324                     path.c_str());
325         }
326
327         break;
328     case S_IFDIR:
329         inode_type = 'd';
330         recurse = true;
331         break;
332
333     default:
334         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
335         return;
336     }
337
338     file_info["type"] = string(1, inode_type);
339
340     metadata << "name: " << uri_encode(path) << "\n";
341     dict_output(metadata, file_info);
342     metadata << "\n";
343
344     // Break apart metadata listing if it becomes too large.
345     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
346         metadata_flush();
347
348     // If we hit a directory, now that we've written the directory itself,
349     // recursively scan the directory.
350     if (recurse)
351         scandir(path);
352 }
353
354 void scandir(const string& path)
355 {
356     DIR *dir = opendir(path.c_str());
357
358     if (dir == NULL) {
359         fprintf(stderr, "Error: %m\n");
360         return;
361     }
362
363     struct dirent *ent;
364     vector<string> contents;
365     while ((ent = readdir(dir)) != NULL) {
366         string filename(ent->d_name);
367         if (filename == "." || filename == "..")
368             continue;
369         contents.push_back(filename);
370     }
371
372     sort(contents.begin(), contents.end());
373
374     for (vector<string>::iterator i = contents.begin();
375          i != contents.end(); ++i) {
376         const string& filename = *i;
377         if (path == ".")
378             scanfile(filename);
379         else
380             scanfile(path + "/" + filename);
381     }
382
383     closedir(dir);
384 }
385
386 void usage(const char *program)
387 {
388     fprintf(stderr,
389             "Usage: %s [OPTION]... SOURCE DEST\n"
390             "Produce backup snapshot of files in SOURCE and store to DEST.\n"
391             "\n"
392             "Options:\n"
393             "  --exclude=PATH       exclude files in PATH from snapshot\n"
394             "  --localdb=PATH       local backup metadata is stored in PATH\n",
395             program);
396 }
397
398 int main(int argc, char *argv[])
399 {
400     string backup_source = ".";
401     string backup_dest = ".";
402     string localdb_dir = "";
403
404     while (1) {
405         static struct option long_options[] = {
406             {"localdb", 1, 0, 0},           // 0
407             {"exclude", 1, 0, 0},           // 1
408             {"filter", 1, 0, 0},            // 2
409             {"filter-extension", 1, 0, 0},  // 3
410             {NULL, 0, 0, 0},
411         };
412
413         int long_index;
414         int c = getopt_long(argc, argv, "", long_options, &long_index);
415
416         if (c == -1)
417             break;
418
419         if (c == 0) {
420             switch (long_index) {
421             case 0:     // --localdb
422                 localdb_dir = optarg;
423                 break;
424             case 1:     // --exclude
425                 excludes.push_back(optarg);
426                 break;
427             case 2:     // --filter
428                 filter_program = optarg;
429                 break;
430             case 3:     // --filter-extension
431                 filter_extension = optarg;
432                 break;
433             default:
434                 fprintf(stderr, "Unhandled long option!\n");
435                 return 1;
436             }
437         } else {
438             usage(argv[0]);
439             return 1;
440         }
441     }
442
443     if (argc < optind + 2) {
444         usage(argv[0]);
445         return 1;
446     }
447
448     backup_source = argv[optind];
449     backup_dest = argv[argc - 1];
450
451     if (localdb_dir == "") {
452         localdb_dir = backup_dest;
453     }
454
455     printf("Source: %s, Dest: %s\n",
456            backup_source.c_str(), backup_dest.c_str());
457
458     tss = new TarSegmentStore(backup_dest);
459     block_buf = new char[LBS_BLOCK_SIZE];
460
461     /* Write a backup descriptor file, which says which segments are needed and
462      * where to start to restore this snapshot.  The filename is based on the
463      * current time. */
464     time_t now;
465     struct tm time_buf;
466     char desc_buf[256];
467     time(&now);
468     localtime_r(&now, &time_buf);
469     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
470     string desc_filename = backup_dest + "/" + desc_buf + ".lbs";
471     std::ofstream descriptor(desc_filename.c_str());
472
473     /* Open the local database which tracks all objects that are stored
474      * remotely, for efficient incrementals.  Provide it with the name of this
475      * snapshot. */
476     string database_path = backup_dest + "/localdb.sqlite";
477     db = new LocalDb;
478     db->Open(database_path.c_str(), desc_buf);
479
480     try {
481         scanfile(".");
482     } catch (IOException e) {
483         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
484     }
485
486     metadata_flush();
487     const string md = metadata_root.str();
488
489     LbsObject *root = new LbsObject;
490     root->set_group("metadata");
491     root->set_data(md.data(), md.size());
492     root->write(tss);
493     root->checksum();
494
495     segment_list.insert(root->get_ref().get_segment());
496     descriptor << "Format: LBS Snapshot v0.1\n";
497     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
498     descriptor << "Date: " << desc_buf << "\n";
499     descriptor << "Root: " << root->get_ref().to_string() << "\n";
500
501     delete root;
502
503     descriptor << "Segments:\n";
504     for (std::set<string>::iterator i = segment_list.begin();
505          i != segment_list.end(); ++i) {
506         descriptor << "    " << *i << "\n";
507     }
508
509     db->Close();
510
511     tss->sync();
512     delete tss;
513
514     return 0;
515 }