1 /* LBS: An LFS-inspired filesystem backup system
2 * Copyright (C) 2007 Michael Vrable
4 * Backup data is stored in a collection of objects, which are grouped together
5 * into segments for storage purposes. This implementation of the object store
6 * represents segments as TAR files and objects as files within them. */
11 #include <sys/types.h>
13 #include <sys/resource.h>
35 /* Default filter program is bzip2 */
36 const char *filter_program = "bzip2 -c";
37 const char *filter_extension = ".bz2";
39 static void cloexec(int fd)
41 long flags = fcntl(fd, F_GETFD);
46 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
49 Tarfile::Tarfile(const string &path, const string &segment)
53 assert(sizeof(struct tar_header) == TAR_BLOCK_SIZE);
55 real_fd = open(path.c_str(), O_WRONLY | O_CREAT, 0666);
57 throw IOException("Error opening output file");
59 filter_fd = spawn_filter(real_fd, filter_program, &filter_pid);
64 char buf[TAR_BLOCK_SIZE];
66 /* Append the EOF marker: two blocks filled with nulls. */
67 memset(buf, 0, sizeof(buf));
68 tar_write(buf, TAR_BLOCK_SIZE);
69 tar_write(buf, TAR_BLOCK_SIZE);
71 if (close(filter_fd) != 0)
72 throw IOException("Error closing Tarfile");
74 /* ...and wait for filter process to finish. */
76 waitpid(filter_pid, &status, 0);
78 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
79 throw IOException("Filter process error");
85 /* Launch a child process which can act as a filter (compress, encrypt, etc.)
86 * on the TAR output. The file descriptor to which output should be written
87 * must be specified; the return value is the file descriptor which will be
88 * attached to the standard input of the filter program. */
89 int spawn_filter(int fd_out, const char *program, pid_t *filter_pid)
94 /* Create a pipe for communicating with the filter process. */
96 throw IOException("Unable to create pipe for filter");
99 /* Create a child process which can exec() the filter program. */
102 throw IOException("Unable to fork filter process");
108 if (filter_pid != NULL)
111 /* Child process. Rearrange file descriptors. stdin is fds[0], stdout
112 * is fd_out, stderr is unchanged. */
115 if (dup2(fds[0], 0) < 0)
119 if (dup2(fd_out, 1) < 0)
123 /* Exec the filter program. */
124 execlp("/bin/sh", "/bin/sh", "-c", program, NULL);
126 /* Should not reach here except for error cases. */
127 fprintf(stderr, "Could not exec filter: %m\n");
134 void Tarfile::tar_write(const char *data, size_t len)
139 int res = write(filter_fd, data, len);
144 fprintf(stderr, "Write error: %m\n");
145 throw IOException("Write error");
153 void Tarfile::write_object(int id, const char *data, size_t len)
155 struct tar_header header;
156 memset(&header, 0, sizeof(header));
159 sprintf(buf, "%08x", id);
160 string path = segment_name + "/" + buf;
162 assert(path.size() < 100);
163 memcpy(header.name, path.data(), path.size());
164 sprintf(header.mode, "%07o", 0600);
165 sprintf(header.uid, "%07o", 0);
166 sprintf(header.gid, "%07o", 0);
167 sprintf(header.size, "%011o", len);
168 sprintf(header.mtime, "%011o", (int)time(NULL));
169 header.typeflag = '0';
170 strcpy(header.magic, "ustar ");
171 strcpy(header.uname, "root");
172 strcpy(header.gname, "root");
174 memset(header.chksum, ' ', sizeof(header.chksum));
176 for (int i = 0; i < TAR_BLOCK_SIZE; i++) {
177 checksum += ((uint8_t *)&header)[i];
179 sprintf(header.chksum, "%06o", checksum);
181 tar_write((const char *)&header, TAR_BLOCK_SIZE);
186 tar_write(data, len);
188 char padbuf[TAR_BLOCK_SIZE];
189 size_t blocks = (len + TAR_BLOCK_SIZE - 1) / TAR_BLOCK_SIZE;
190 size_t padding = blocks * TAR_BLOCK_SIZE - len;
191 memset(padbuf, 0, padding);
192 tar_write(padbuf, padding);
195 /* Estimate the size based on the size of the actual output file on disk.
196 * However, it might be the case that the filter program is buffering all its
197 * data, and might potentially not write a single byte until we have closed
198 * our end of the pipe. If we don't do so until we see data written, we have
199 * a problem. So, arbitrarily pick an upper bound on the compression ratio
200 * that the filter will achieve (128:1), and return a size estimate which is
201 * the larger of a) bytes actually seen written to disk, and b) input
203 size_t Tarfile::size_estimate()
207 if (fstat(real_fd, &statbuf) == 0)
208 return max((int64_t)statbuf.st_size, (int64_t)(size / 128));
210 /* Couldn't stat the file on disk, so just return the actual number of
211 * bytes, before compression. */
215 static const size_t SEGMENT_SIZE = 4 * 1024 * 1024;
217 static map<string, int64_t> group_sizes;
219 ObjectReference TarSegmentStore::write_object(const char *data, size_t len,
220 const std::string &group)
222 struct segment_info *segment;
224 // Find the segment into which the object should be written, looking up by
225 // group. If no segment exists yet, create one.
226 if (segments.find(group) == segments.end()) {
227 segment = new segment_info;
229 segment->name = generate_uuid();
230 segment->basename = segment->name + ".tar";
231 segment->basename += filter_extension;
232 segment->fullname = path + "/" + segment->basename;
233 segment->file = new Tarfile(segment->fullname, segment->name);
236 segments[group] = segment;
238 segment = segments[group];
241 int id = segment->count;
243 sprintf(id_buf, "%08x", id);
245 segment->file->write_object(id, data, len);
248 group_sizes[group] += len;
250 ObjectReference ref(segment->name, id_buf);
252 // If this segment meets or exceeds the size target, close it so that
253 // future objects will go into a new segment.
254 if (segment->file->size_estimate() >= SEGMENT_SIZE)
255 close_segment(group);
260 void TarSegmentStore::sync()
262 while (!segments.empty())
263 close_segment(segments.begin()->first);
266 void TarSegmentStore::dump_stats()
268 printf("Data written:\n");
269 for (map<string, int64_t>::iterator i = group_sizes.begin();
270 i != group_sizes.end(); ++i) {
271 printf(" %s: %lld\n", i->first.c_str(), i->second);
275 void TarSegmentStore::close_segment(const string &group)
277 struct segment_info *segment = segments[group];
279 delete segment->file;
282 SHA1Checksum segment_checksum;
283 if (segment_checksum.process_file(segment->fullname.c_str())) {
284 string checksum = segment_checksum.checksum_str();
285 db->SetSegmentChecksum(segment->name, segment->basename, checksum);
289 segments.erase(segments.find(group));
293 string TarSegmentStore::object_reference_to_segment(const string &object)
298 LbsObject::LbsObject()
299 : group(""), data(NULL), data_len(0), written(false)
303 LbsObject::~LbsObject()
307 void LbsObject::write(TarSegmentStore *store)
309 assert(data != NULL);
312 ref = store->write_object(data, data_len, group);
316 void LbsObject::checksum()
321 hash.process(data, data_len);
322 ref.set_checksum(hash.checksum_str());