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