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