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