Keep an index of old stored blocks, using sqlite3.
[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         // tarstore processing
135         LbsObject *o = new LbsObject;
136         o->set_group("data");
137         o->set_data(block_buf, bytes);
138         o->write(tss);
139         object_list.push_back(o->get_name());
140         segment_list.insert(o->get_ref().get_segment());
141
142         // Index this block so it can be used by future snapshots
143         SHA1Checksum block_hash;
144         block_hash.process(block_buf, bytes);
145         db->StoreObject(o->get_ref(), block_hash.checksum_str(), bytes);
146
147         size += bytes;
148
149         delete o;
150     }
151
152     file_info["checksum"] = hash.checksum_str();
153
154     /* For files that only need to be broken apart into a few objects, store
155      * the list of objects directly.  For larger files, store the data
156      * out-of-line and provide a pointer to the indrect object. */
157     if (object_list.size() < 8) {
158         string blocklist = "";
159         for (list<string>::iterator i = object_list.begin();
160              i != object_list.end(); ++i) {
161             if (i != object_list.begin())
162                 blocklist += " ";
163             blocklist += *i;
164         }
165         file_info["data"] = blocklist;
166     } else {
167         string blocklist = "";
168         for (list<string>::iterator i = object_list.begin();
169              i != object_list.end(); ++i) {
170             blocklist += *i + "\n";
171         }
172
173         LbsObject *i = new LbsObject;
174         i->set_group("indirect");
175         i->set_data(blocklist.data(), blocklist.size());
176         i->write(tss);
177         file_info["data"] = "@" + i->get_name();
178         segment_list.insert(i->get_ref().get_segment());
179         delete i;
180     }
181
182     return size;
183 }
184
185 void scanfile(const string& path)
186 {
187     int fd;
188     long flags;
189     struct stat stat_buf;
190     char *buf;
191     ssize_t len;
192     int64_t file_size;
193     list<string> refs;
194
195     // Set to true if the item is a directory and we should recursively scan
196     bool recurse = false;
197
198     dictionary file_info;
199
200     lstat(path.c_str(), &stat_buf);
201
202     printf("%s\n", path.c_str());
203
204     metadata << "name: " << uri_encode(path) << "\n";
205
206     file_info["mode"] = encode_int(stat_buf.st_mode & 07777);
207     file_info["mtime"] = encode_int(stat_buf.st_mtime);
208     file_info["user"] = encode_int(stat_buf.st_uid);
209     file_info["group"] = encode_int(stat_buf.st_gid);
210
211     struct passwd *pwd = getpwuid(stat_buf.st_uid);
212     if (pwd != NULL) {
213         file_info["user"] += " (" + uri_encode(pwd->pw_name) + ")";
214     }
215
216     struct group *grp = getgrgid(stat_buf.st_gid);
217     if (pwd != NULL) {
218         file_info["group"] += " (" + uri_encode(grp->gr_name) + ")";
219     }
220
221     char inode_type;
222
223     switch (stat_buf.st_mode & S_IFMT) {
224     case S_IFIFO:
225         inode_type = 'p';
226         break;
227     case S_IFSOCK:
228         inode_type = 's';
229         break;
230     case S_IFCHR:
231         inode_type = 'c';
232         break;
233     case S_IFBLK:
234         inode_type = 'b';
235         break;
236     case S_IFLNK:
237         inode_type = 'l';
238
239         /* Use the reported file size to allocate a buffer large enough to read
240          * the symlink.  Allocate slightly more space, so that we ask for more
241          * bytes than we expect and so check for truncation. */
242         buf = new char[stat_buf.st_size + 2];
243         len = readlink(path.c_str(), buf, stat_buf.st_size + 1);
244         if (len < 0) {
245             fprintf(stderr, "error reading symlink: %m\n");
246         } else if (len <= stat_buf.st_size) {
247             buf[len] = '\0';
248             file_info["contents"] = uri_encode(buf);
249         } else if (len > stat_buf.st_size) {
250             fprintf(stderr, "error reading symlink: name truncated\n");
251         }
252
253         delete[] buf;
254         break;
255     case S_IFREG:
256         inode_type = '-';
257
258         /* Be paranoid when opening the file.  We have no guarantee that the
259          * file was not replaced between the stat() call above and the open()
260          * call below, so we might not even be opening a regular file.  That
261          * the file descriptor refers to a regular file is checked in
262          * dumpfile().  But we also supply flags to open to to guard against
263          * various conditions before we can perform that verification:
264          *   - O_NOFOLLOW: in the event the file was replaced by a symlink
265          *   - O_NONBLOCK: prevents open() from blocking if the file was
266          *     replaced by a fifo
267          * We also add in O_NOATIME, since this may reduce disk writes (for
268          * inode updates). */
269         fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
270
271         /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
272          * open. */
273         flags = fcntl(fd, F_GETFL);
274         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
275
276         file_size = dumpfile(fd, file_info);
277         file_info["size"] = encode_int(file_size);
278         close(fd);
279
280         if (file_size < 0)
281             return;             // error occurred; do not dump file
282
283         if (file_size != stat_buf.st_size) {
284             fprintf(stderr, "Warning: Size of %s changed during reading\n",
285                     path.c_str());
286         }
287
288         break;
289     case S_IFDIR:
290         inode_type = 'd';
291         recurse = true;
292         break;
293
294     default:
295         fprintf(stderr, "Unknown inode type: mode=%x\n", stat_buf.st_mode);
296         return;
297     }
298
299     file_info["type"] = string(1, inode_type);
300
301     dict_output(metadata, file_info);
302     metadata << "\n";
303
304     // Break apart metadata listing if it becomes too large.
305     if (metadata.str().size() > LBS_METADATA_BLOCK_SIZE)
306         metadata_flush();
307
308     // If we hit a directory, now that we've written the directory itself,
309     // recursively scan the directory.
310     if (recurse)
311         scandir(path);
312 }
313
314 void scandir(const string& path)
315 {
316     DIR *dir = opendir(path.c_str());
317
318     if (dir == NULL) {
319         fprintf(stderr, "Error: %m\n");
320         return;
321     }
322
323     struct dirent *ent;
324     vector<string> contents;
325     while ((ent = readdir(dir)) != NULL) {
326         string filename(ent->d_name);
327         if (filename == "." || filename == "..")
328             continue;
329         contents.push_back(filename);
330     }
331
332     sort(contents.begin(), contents.end());
333
334     for (vector<string>::iterator i = contents.begin();
335          i != contents.end(); ++i) {
336         const string& filename = *i;
337         scanfile(path + "/" + filename);
338     }
339
340     closedir(dir);
341 }
342
343 int main(int argc, char *argv[])
344 {
345     block_buf = new char[LBS_BLOCK_SIZE];
346
347     string backup_dest = ".";
348
349     if (argc > 1)
350         backup_dest = argv[1];
351
352     tss = new TarSegmentStore(backup_dest);
353
354     string database_path = backup_dest + "/localdb.sqlite";
355     db = new LocalDb;
356     db->Open(database_path.c_str());
357
358     /* Write a backup descriptor file, which says which segments are needed and
359      * where to start to restore this snapshot.  The filename is based on the
360      * current time. */
361     time_t now;
362     struct tm time_buf;
363     char desc_buf[256];
364     time(&now);
365     localtime_r(&now, &time_buf);
366     strftime(desc_buf, sizeof(desc_buf), "%Y%m%dT%H%M%S", &time_buf);
367     string desc_filename = backup_dest + "/" + desc_buf + ".lbs";
368     std::ofstream descriptor(desc_filename.c_str());
369
370     try {
371         scanfile(".");
372     } catch (IOException e) {
373         fprintf(stderr, "IOException: %s\n", e.getError().c_str());
374     }
375
376     metadata_flush();
377     const string md = metadata_root.str();
378
379     LbsObject *root = new LbsObject;
380     root->set_group("root");
381     root->set_data(md.data(), md.size());
382     root->write(tss);
383     root->checksum();
384
385     segment_list.insert(root->get_ref().get_segment());
386     descriptor << "Root: " << root->get_ref().to_string() << "\n";
387     strftime(desc_buf, sizeof(desc_buf), "%Y-%m-%d %H:%M:%S %z", &time_buf);
388     descriptor << "Date: " << desc_buf << "\n";
389
390     delete root;
391
392     descriptor << "Segments:\n";
393     for (std::set<string>::iterator i = segment_list.begin();
394          i != segment_list.end(); ++i) {
395         descriptor << "    " << *i << "\n";
396     }
397
398     db->Close();
399
400     tss->sync();
401     delete tss;
402
403     return 0;
404 }