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