Write backup descriptor to a file, not stdout.
[cumulus.git] / scandir.cc
1 /* Recursively descend the filesystem and visit each file. */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <dirent.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
12
13 #include <algorithm>
14 #include <string>
15 #include <list>
16 #include <vector>
17 #include <iostream>
18 #include <fstream>
19 #include <sstream>
20 #include <set>
21
22 #include "format.h"
23 #include "store.h"
24 #include "sha1.h"
25
26 using std::list;
27 using std::string;
28 using std::vector;
29 using std::ostream;
30
31 static TarSegmentStore *tss = NULL;
32
33 /* Buffer for holding a single block of data read from a file. */
34 static const size_t LBS_BLOCK_SIZE = 1024 * 1024;
35 static char *block_buf;
36
37 static const size_t LBS_METADATA_BLOCK_SIZE = 65536;
38
39 /* Contents of the root object.  This will contain a set of indirect links to
40  * the metadata objects. */
41 std::ostringstream metadata_root;
42
43 /* Buffer for building up metadata. */
44 std::ostringstream metadata;
45
46 /* Keep track of all segments which are needed to reconstruct the snapshot. */
47 std::set<string> segment_list;
48
49 void scandir(const string& path);
50
51 /* Ensure contents of metadata are flushed to an object. */
52 void metadata_flush()
53 {
54     string m = metadata.str();
55     if (m.size() == 0)
56         return;
57
58     /* Write current metadata information to a new object. */
59     LbsObject *meta = new LbsObject;
60     meta->set_group("root");
61     meta->set_data(m.data(), m.size());
62     meta->write(tss);
63     meta->checksum();
64
65     /* Write a reference to this block in the root. */
66     ObjectReference ref = meta->get_ref();
67     metadata_root << "@" << ref.to_string() << "\n";
68     segment_list.insert(ref.get_segment());
69
70     delete meta;
71
72     metadata.str("");
73 }
74
75 /* Read data from a file descriptor and return the amount of data read.  A
76  * short read (less than the requested size) will only occur if end-of-file is
77  * hit. */
78 size_t file_read(int fd, char *buf, size_t maxlen)
79 {
80     size_t bytes_read = 0;
81
82     while (true) {
83         ssize_t res = read(fd, buf, maxlen);
84         if (res < 0) {
85             if (errno == EINTR)
86                 continue;
87             throw IOException("file_read: error reading");
88         } else if (res == 0) {
89             break;
90         } else {
91             bytes_read += res;
92             buf += res;
93             maxlen -= res;
94         }
95     }
96
97     return bytes_read;
98 }
99
100 /* Read the contents of a file (specified by an open file descriptor) and copy
101  * the data to the store. */
102 void dumpfile(int fd, dictionary &file_info)
103 {
104     struct stat stat_buf;
105     fstat(fd, &stat_buf);
106     int64_t size = 0;
107     list<string> object_list;
108
109     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
110         fprintf(stderr, "file is no longer a regular file!\n");
111         return;
112     }
113
114     /* The index data consists of a sequence of pointers to the data blocks
115      * that actually comprise the file data.  This level of indirection is used
116      * so that the same data block can be used in multiple files, or multiple
117      * versions of the same file. */
118     SHA1Checksum hash;
119     while (true) {
120         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
121         if (bytes == 0)
122             break;
123
124         hash.process(block_buf, bytes);
125
126         // tarstore processing
127         LbsObject *o = new LbsObject;
128         o->set_group("data");
129         o->set_data(block_buf, bytes);
130         o->write(tss);
131         object_list.push_back(o->get_name());
132         segment_list.insert(o->get_ref().get_segment());
133         delete o;
134
135         size += bytes;
136     }
137
138     file_info["checksum"] = hash.checksum_str();
139
140     /* For files that only need to be broken apart into a few objects, store
141      * the list of objects directly.  For larger files, store the data
142      * out-of-line and provide a pointer to the indrect object. */
143     if (object_list.size() < 8) {
144         string blocklist = "";
145         for (list<string>::iterator i = object_list.begin();
146              i != object_list.end(); ++i) {
147             if (i != object_list.begin())
148                 blocklist += " ";
149             blocklist += *i;
150         }
151         file_info["data"] = blocklist;
152     } else {
153         string blocklist = "";
154         for (list<string>::iterator i = object_list.begin();
155              i != object_list.end(); ++i) {
156             blocklist += *i + "\n";
157         }
158
159         LbsObject *i = new LbsObject;
160         i->set_group("indirect");
161         i->set_data(blocklist.data(), blocklist.size());
162         i->write(tss);
163         file_info["data"] = "@" + i->get_name();
164         segment_list.insert(i->get_ref().get_segment());
165         delete i;
166     }
167 }
168
169 void scanfile(const string& path)
170 {
171     int fd;
172     long flags;
173     struct stat stat_buf;
174     char *buf;
175     ssize_t len;
176     list<string> refs;
177
178     // Set to true if the item is a directory and we should recursively scan
179     bool recurse = false;
180
181     dictionary file_info;
182
183     lstat(path.c_str(), &stat_buf);
184
185     printf("%s\n", path.c_str());
186
187     metadata << "name: " << uri_encode(path) << "\n";
188
189     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
190     file_info["atime"] = encode_int(stat_buf.st_atime);
191     file_info["ctime"] = encode_int(stat_buf.st_ctime);
192     file_info["mtime"] = encode_int(stat_buf.st_mtime);
193     file_info["user"] = encode_int(stat_buf.st_uid);
194     file_info["group"] = encode_int(stat_buf.st_gid);
195
196     char inode_type;
197
198     switch (stat_buf.st_mode & S_IFMT) {
199     case S_IFIFO:
200         inode_type = 'p';
201         break;
202     case S_IFSOCK:
203         inode_type = 's';
204         break;
205     case S_IFCHR:
206         inode_type = 'c';
207         break;
208     case S_IFBLK:
209         inode_type = 'b';
210         break;
211     case S_IFLNK:
212         inode_type = 'l';
213
214         /* Use the reported file size to allocate a buffer large enough to read
215          * the symlink.  Allocate slightly more space, so that we ask for more
216          * bytes than we expect and so check for truncation. */
217         buf = new char[stat_buf.st_size + 2];
218         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
219         if (len < 0) {
220             fprintf(stderr, "error reading symlink: %m\n");
221         } else if (len <= stat_buf.st_size) {
222             buf[len] = '\0';
223             file_info["contents"] = uri_encode(buf);
224         } else if (len > stat_buf.st_size) {
225             fprintf(stderr, "error reading symlink: name truncated\n");
226         }
227
228         delete[] buf;
229         break;
230     case S_IFREG:
231         inode_type = '-';
232
233         /* Be paranoid when opening the file.  We have no guarantee that the
234          * file was not replaced between the stat() call above and the open()
235          * call below, so we might not even be opening a regular file.  That
236          * the file descriptor refers to a regular file is checked in
237          * dumpfile().  But we also supply flags to open to to guard against
238          * various conditions before we can perform that verification:
239          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
240          *   - O_NONBLOCK: prevents open() from blocking if the file was
241          *     replaced by a fifo
242          * We also add in O_NOATIME, since this may reduce disk writes (for
243          * inode updates). */
244         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
245
246         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
247          * open. */
248         flags = fcntl(fd, F_GETFL);
249         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
250
251         file_info["size"] = encode_int(stat_buf.st_size);
252         dumpfile(fd, file_info);
253         close(fd);
254
255         break;
256     case S_IFDIR:
257         inode_type = 'd';
258         recurse = true;
259         break;
260
261     default:
262         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
263         return;
264     }
265
266     file_info["type"] = string(1, inode_type);
267
268     dict_output(metadata, file_info);
269     metadata << "\n";
270
271     // Break apart metadata listing if it becomes too large.
272     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
273         metadata_flush();
274
275     // If we hit a directory, now that we've written the directory itself,
276     // recursively scan the directory.
277     if (recurse)
278         scandir(path);
279 }
280
281 void scandir(const string& path)
282 {
283     DIR *dir = opendir(path.c_str());
284
285     if (dir == NULL) {
286         fprintf(stderr, "Error: %m\n");
287         return;
288     }
289
290     struct dirent *ent;
291     vector<string> contents;
292     while ((ent = readdir(dir)) != NULL) {
293         string filename(ent->d_name);
294         if (filename == "." || filename == "..")
295             continue;
296         contents.push_back(filename);
297     }
298
299     sort(contents.begin(), contents.end());
300
301     for (vector<string>::iterator i = contents.begin();
302          i != contents.end(); ++i) {
303         const string& filename = *i;
304         scanfile(path + "/" + filename);
305     }
306
307     closedir(dir);
308 }
309
310 int main(int argc, char *argv[])
311 {
312     block_buf = new char[LBS_BLOCK_SIZE];
313
314     string backup_dest = ".";
315
316     if (argc > 1)
317         backup_dest = argv[1];
318
319     tss = new TarSegmentStore(backup_dest);
320
321     string desc_filename = backup_dest + "/snapshot.lbs";
322     std::ofstream descriptor(desc_filename.c_str());
323
324     try {
325         scanfile(".");
326     } catch (IOException e) {
327         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
328     }
329
330     metadata_flush();
331     const string md = metadata_root.str();
332
333     LbsObject *root = new LbsObject;
334     root->set_group("root");
335     root->set_data(md.data(), md.size());
336     root->write(tss);
337     root->checksum();
338
339     segment_list.insert(root->get_ref().get_segment());
340     descriptor << "root: " << root->get_ref().to_string() << "\n\n";
341
342     delete root;
343
344     descriptor << "segments:\n";
345     for (std::set<string>::iterator i = segment_list.begin();
346          i != segment_list.end(); ++i) {
347         descriptor << "    " << *i << "\n";
348     }
349
350     tss->sync();
351     delete tss;
352
353     return 0;
354 }