Add checksums to tarstore, and partially migrate to using it for storage.
[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 <vector>
16 #include <iostream>
17 #include <sstream>
18
19 #include "store.h"
20 #include "tarstore.h"
21 #include "sha1.h"
22
23 using std::string;
24 using std::vector;
25 using std::ostream;
26
27 static SegmentStore *segment_store;
28 static OutputStream *info_dump = NULL;
29
30 static TarSegmentStore *tss = NULL;
31
32 static SegmentPartitioner *index_segment, *data_segment;
33
34 /* Buffer for holding a single block of data read from a file. */
35 static const int LBS_BLOCK_SIZE = 1024 * 1024;
36 static char *block_buf;
37
38 void scandir(const string& path, std::ostream& metadata);
39
40 /* Converts time to microseconds since the epoch. */
41 int64_t encode_time(time_t time)
42 {
43     return (int64_t)time * 1000000;
44 }
45
46 /* Read data from a file descriptor and return the amount of data read.  A
47  * short read (less than the requested size) will only occur if end-of-file is
48  * hit. */
49 size_t file_read(int fd, char *buf, size_t maxlen)
50 {
51     size_t bytes_read = 0;
52
53     while (true) {
54         ssize_t res = read(fd, buf, maxlen);
55         if (res < 0) {
56             if (errno == EINTR)
57                 continue;
58             throw IOException("file_read: error reading");
59         } else if (res == 0) {
60             break;
61         } else {
62             bytes_read += res;
63             buf += res;
64             maxlen -= res;
65         }
66     }
67
68     return bytes_read;
69 }
70
71 /* Read the contents of a file (specified by an open file descriptor) and copy
72  * the data to the store. */
73 void dumpfile(int fd, dictionary &file_info, ostream &metadata)
74 {
75     struct stat stat_buf;
76     fstat(fd, &stat_buf);
77     int64_t size = 0;
78     string segment_list = "data:";
79
80     if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
81         printf("file is no longer a regular file!\n");
82         return;
83     }
84
85     /* The index data consists of a sequence of pointers to the data blocks
86      * that actually comprise the file data.  This level of indirection is used
87      * so that the same data block can be used in multiple files, or multiple
88      * versions of the same file. */
89     struct uuid segment_uuid;
90     int object_id;
91     OutputStream *index_data = index_segment->new_object(&segment_uuid,
92                                                          &object_id,
93                                                          "DREF");
94
95     SHA1Checksum hash;
96     while (true) {
97         struct uuid block_segment_uuid;
98         int block_object_id;
99
100         size_t bytes = file_read(fd, block_buf, LBS_BLOCK_SIZE);
101         if (bytes == 0)
102             break;
103
104         hash.process(block_buf, bytes);
105         OutputStream *block = data_segment->new_object(&block_segment_uuid,
106                                                        &block_object_id,
107                                                        "DATA");
108         block->write(block_buf, bytes);
109         index_data->write_uuid(block_segment_uuid);
110         index_data->write_u32(block_object_id);
111
112         // tarstore processing
113         string blockid = tss->write_object(block_buf, bytes, "data");
114         segment_list += " " + blockid;
115
116         size += bytes;
117     }
118
119     file_info["sha1"] = string((const char *)hash.checksum(),
120                                hash.checksum_size());
121     file_info["data"] = encode_objref(segment_uuid, object_id);
122
123     metadata << segment_list << "\n";
124 }
125
126 void scanfile(const string& path, ostream &metadata)
127 {
128     int fd;
129     long flags;
130     struct stat stat_buf;
131     char *buf;
132     ssize_t len;
133
134     // Set to true if the item is a directory and we should recursively scan
135     bool recurse = false;
136
137     dictionary file_info;
138
139     lstat(path.c_str(), &stat_buf);
140
141     printf("%s\n", path.c_str());
142
143     metadata << "name: " << path << "\n";
144     metadata << "mode: " << (stat_buf.st_mode & 07777) << "\n";
145     metadata << "atime: " << stat_buf.st_atime << "\n";
146     metadata << "ctime: " << stat_buf.st_ctime << "\n";
147     metadata << "mtime: " << stat_buf.st_mtime << "\n";
148     metadata << "user: " << stat_buf.st_uid << "\n";
149     metadata << "group: " << stat_buf.st_gid << "\n";
150
151     file_info["mode"] = encode_u16(stat_buf.st_mode & 07777);
152     file_info["atime"] = encode_u64(encode_time(stat_buf.st_atime));
153     file_info["ctime"] = encode_u64(encode_time(stat_buf.st_ctime));
154     file_info["mtime"] = encode_u64(encode_time(stat_buf.st_mtime));
155     file_info["user"] = encode_u32(stat_buf.st_uid);
156     file_info["group"] = encode_u32(stat_buf.st_gid);
157
158     char inode_type;
159
160     switch (stat_buf.st_mode & S_IFMT) {
161     case S_IFIFO:
162         inode_type = 'p';
163         break;
164     case S_IFSOCK:
165         inode_type = 's';
166         break;
167     case S_IFCHR:
168         inode_type = 'c';
169         break;
170     case S_IFBLK:
171         inode_type = 'b';
172         break;
173     case S_IFLNK:
174         inode_type = 'l';
175
176         /* Use the reported file size to allocate a buffer large enough to read
177          * the symlink.  Allocate slightly more space, so that we ask for more
178          * bytes than we expect and so check for truncation. */
179         buf = new char[stat_buf.st_size + 2];
180         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
181         if (len < 0) {
182             printf("error reading symlink: %m\n");
183         } else if (len <= stat_buf.st_size) {
184             buf[len] = '\0';
185             printf("    contents=%s\n", buf);
186         } else if (len > stat_buf.st_size) {
187             printf("error reading symlink: name truncated\n");
188         }
189
190         file_info["contents"] = buf;
191
192         delete[] buf;
193         break;
194     case S_IFREG:
195         inode_type = '-';
196
197         /* Be paranoid when opening the file.  We have no guarantee that the
198          * file was not replaced between the stat() call above and the open()
199          * call below, so we might not even be opening a regular file.  That
200          * the file descriptor refers to a regular file is checked in
201          * dumpfile().  But we also supply flags to open to to guard against
202          * various conditions before we can perform that verification:
203          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
204          *   - O_NONBLOCK: prevents open() from blocking if the file was
205          *     replaced by a fifo
206          * We also add in O_NOATIME, since this may reduce disk writes (for
207          * inode updates). */
208         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
209
210         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
211          * open. */
212         flags = fcntl(fd, F_GETFL);
213         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
214
215         file_info["size"] = encode_u64(stat_buf.st_size);
216         dumpfile(fd, file_info, metadata);
217         close(fd);
218
219         break;
220     case S_IFDIR:
221         inode_type = 'd';
222         recurse = true;
223         break;
224
225     default:
226         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
227         return;
228     }
229
230     file_info["type"] = string(1, inode_type);
231     metadata << "type: " << inode_type << "\n";
232
233     info_dump->write_string(path);
234     info_dump->write_dictionary(file_info);
235
236     metadata << "\n";
237
238     // If we hit a directory, now that we've written the directory itself,
239     // recursively scan the directory.
240     if (recurse)
241         scandir(path, metadata);
242 }
243
244 void scandir(const string& path, ostream &metadata)
245 {
246     DIR *dir = opendir(path.c_str());
247
248     if (dir == NULL) {
249         printf("Error: %m\n");
250         return;
251     }
252
253     struct dirent *ent;
254     vector<string> contents;
255     while ((ent = readdir(dir)) != NULL) {
256         string filename(ent->d_name);
257         if (filename == "." || filename == "..")
258             continue;
259         contents.push_back(filename);
260     }
261
262     sort(contents.begin(), contents.end());
263
264     for (vector<string>::iterator i = contents.begin();
265          i != contents.end(); ++i) {
266         const string& filename = *i;
267         scanfile(path + "/" + filename, metadata);
268     }
269
270     closedir(dir);
271 }
272
273 int main(int argc, char *argv[])
274 {
275     block_buf = new char[LBS_BLOCK_SIZE];
276
277     tss = new TarSegmentStore(".");
278     segment_store = new SegmentStore(".");
279     SegmentWriter *sw = segment_store->new_segment();
280     info_dump = sw->new_object(NULL, "ROOT");
281
282     index_segment = new SegmentPartitioner(segment_store);
283     data_segment = new SegmentPartitioner(segment_store);
284
285     string uuid = SegmentWriter::format_uuid(sw->get_uuid());
286     printf("Backup UUID: %s\n", uuid.c_str());
287
288     std::ostringstream metadata;
289
290     try {
291         scanfile(".", metadata);
292     } catch (IOException e) {
293         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
294     }
295
296     const char testdata[] = "Test string.";
297     tss->write_object(testdata, strlen(testdata));
298     tss->write_object(testdata, strlen(testdata));
299     tss->write_object(testdata, strlen(testdata));
300
301     const string md = metadata.str();
302     string root = tss->write_object(md.data(), md.size(), "root");
303
304     fprintf(stderr, "Metadata root is at %s\n", root.c_str());
305
306     tss->sync();
307     delete tss;
308
309     delete index_segment;
310     delete data_segment;
311     delete sw;
312
313     return 0;
314 }