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