Merge "next" branch into "master".
[cascardo/ovs.git] / ovsdb / log.c
1 /* Copyright (c) 2009, 2010 Nicira Networks
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "log.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include "json.h"
28 #include "lockfile.h"
29 #include "ovsdb.h"
30 #include "ovsdb-error.h"
31 #include "sha1.h"
32 #include "socket-util.h"
33 #include "transaction.h"
34 #include "util.h"
35
36 #define THIS_MODULE VLM_ovsdb_log
37 #include "vlog.h"
38
39 enum ovsdb_log_mode {
40     OVSDB_LOG_READ,
41     OVSDB_LOG_WRITE
42 };
43
44 struct ovsdb_log {
45     off_t offset;
46     char *name;
47     struct lockfile *lockfile;
48     FILE *stream;
49     struct ovsdb_error *read_error;
50     struct ovsdb_error *write_error;
51     enum ovsdb_log_mode mode;
52 };
53
54 /* Attempts to open 'name' with the specified 'open_mode'.  On success, stores
55  * the new log into '*filep' and returns NULL; otherwise returns NULL and
56  * stores NULL into '*filep'.
57  *
58  * Whether the file will be locked using lockfile_lock() depends on 'locking':
59  * use true to lock it, false not to lock it, or -1 to lock it only if
60  * 'open_mode' is a mode that allows writing.
61  */
62 struct ovsdb_error *
63 ovsdb_log_open(const char *name, enum ovsdb_log_open_mode open_mode,
64                int locking, struct ovsdb_log **filep)
65 {
66     struct lockfile *lockfile;
67     struct ovsdb_error *error;
68     struct ovsdb_log *file;
69     struct stat s;
70     FILE *stream;
71     int flags;
72     int fd;
73
74     *filep = NULL;
75
76     assert(locking == -1 || locking == false || locking == true);
77     if (locking < 0) {
78         locking = open_mode != OVSDB_LOG_READ_ONLY;
79     }
80     if (locking) {
81         int retval = lockfile_lock(name, 0, &lockfile);
82         if (retval) {
83             error = ovsdb_io_error(retval, "%s: failed to lock lockfile",
84                                    name);
85             goto error;
86         }
87     } else {
88         lockfile = NULL;
89     }
90
91     if (open_mode == OVSDB_LOG_READ_ONLY) {
92         flags = O_RDONLY;
93     } else if (open_mode == OVSDB_LOG_READ_WRITE) {
94         flags = O_RDWR;
95     } else if (open_mode == OVSDB_LOG_CREATE) {
96         flags = O_RDWR | O_CREAT | O_EXCL;
97     } else {
98         NOT_REACHED();
99     }
100     fd = open(name, flags, 0666);
101     if (fd < 0) {
102         const char *op = open_mode == OVSDB_LOG_CREATE ? "create" : "open";
103         error = ovsdb_io_error(errno, "%s: %s failed", op, name);
104         goto error_unlock;
105     }
106
107     if (!fstat(fd, &s) && s.st_size == 0) {
108         /* It's (probably) a new file so fsync() its parent directory to ensure
109          * that its directory entry is committed to disk. */
110         fsync_parent_dir(name);
111     }
112
113     stream = fdopen(fd, open_mode == OVSDB_LOG_READ_ONLY ? "rb" : "w+b");
114     if (!stream) {
115         error = ovsdb_io_error(errno, "%s: fdopen failed", name);
116         goto error_close;
117     }
118
119     file = xmalloc(sizeof *file);
120     file->name = xstrdup(name);
121     file->lockfile = lockfile;
122     file->stream = stream;
123     file->offset = 0;
124     file->read_error = NULL;
125     file->write_error = NULL;
126     file->mode = OVSDB_LOG_READ;
127     *filep = file;
128     return NULL;
129
130 error_close:
131     close(fd);
132 error_unlock:
133     lockfile_unlock(lockfile);
134 error:
135     return error;
136 }
137
138 void
139 ovsdb_log_close(struct ovsdb_log *file)
140 {
141     if (file) {
142         free(file->name);
143         fclose(file->stream);
144         lockfile_unlock(file->lockfile);
145         ovsdb_error_destroy(file->read_error);
146         ovsdb_error_destroy(file->write_error);
147         free(file);
148     }
149 }
150
151 static const char magic[] = "OVSDB JSON ";
152
153 static bool
154 parse_header(char *header, unsigned long int *length,
155              uint8_t sha1[SHA1_DIGEST_SIZE])
156 {
157     char *p;
158
159     /* 'header' must consist of a magic string... */
160     if (strncmp(header, magic, strlen(magic))) {
161         return false;
162     }
163
164     /* ...followed by a length in bytes... */
165     *length = strtoul(header + strlen(magic), &p, 10);
166     if (!*length || *length == ULONG_MAX || *p != ' ') {
167         return false;
168     }
169     p++;
170
171     /* ...followed by a SHA-1 hash... */
172     if (!sha1_from_hex(sha1, p)) {
173         return false;
174     }
175     p += SHA1_HEX_DIGEST_LEN;
176
177     /* ...and ended by a new-line. */
178     if (*p != '\n') {
179         return false;
180     }
181
182     return true;
183 }
184
185 struct ovsdb_log_read_cbdata {
186     char input[4096];
187     struct ovsdb_log *file;
188     int error;
189     unsigned long length;
190 };
191
192 static struct ovsdb_error *
193 parse_body(struct ovsdb_log *file, off_t offset, unsigned long int length,
194            uint8_t sha1[SHA1_DIGEST_SIZE], struct json **jsonp)
195 {
196     struct json_parser *parser;
197     struct sha1_ctx ctx;
198
199     sha1_init(&ctx);
200     parser = json_parser_create(JSPF_TRAILER);
201
202     while (length > 0) {
203         char input[BUFSIZ];
204         int chunk;
205
206         chunk = MIN(length, sizeof input);
207         if (fread(input, 1, chunk, file->stream) != chunk) {
208             json_parser_abort(parser);
209             return ovsdb_io_error(ferror(file->stream) ? errno : EOF,
210                                   "%s: error reading %lu bytes "
211                                   "starting at offset %lld", file->name,
212                                   length, (long long int) offset);
213         }
214         sha1_update(&ctx, input, chunk);
215         json_parser_feed(parser, input, chunk);
216         length -= chunk;
217     }
218
219     sha1_final(&ctx, sha1);
220     *jsonp = json_parser_finish(parser);
221     return NULL;
222 }
223
224 struct ovsdb_error *
225 ovsdb_log_read(struct ovsdb_log *file, struct json **jsonp)
226 {
227     uint8_t expected_sha1[SHA1_DIGEST_SIZE];
228     uint8_t actual_sha1[SHA1_DIGEST_SIZE];
229     struct ovsdb_error *error;
230     off_t data_offset;
231     unsigned long data_length;
232     struct json *json;
233     char header[128];
234
235     *jsonp = json = NULL;
236
237     if (file->read_error) {
238         return ovsdb_error_clone(file->read_error);
239     } else if (file->mode == OVSDB_LOG_WRITE) {
240         return OVSDB_BUG("reading file in write mode");
241     }
242
243     if (!fgets(header, sizeof header, file->stream)) {
244         if (feof(file->stream)) {
245             error = NULL;
246         } else {
247             error = ovsdb_io_error(errno, "%s: read failed", file->name);
248         }
249         goto error;
250     }
251
252     if (!parse_header(header, &data_length, expected_sha1)) {
253         error = ovsdb_syntax_error(NULL, NULL, "%s: parse error at offset "
254                                    "%lld in header line \"%.*s\"",
255                                    file->name, (long long int) file->offset,
256                                    (int) strcspn(header, "\n"), header);
257         goto error;
258     }
259
260     data_offset = file->offset + strlen(header);
261     error = parse_body(file, data_offset, data_length, actual_sha1, &json);
262     if (error) {
263         goto error;
264     }
265
266     if (memcmp(expected_sha1, actual_sha1, SHA1_DIGEST_SIZE)) {
267         error = ovsdb_syntax_error(NULL, NULL, "%s: %lu bytes starting at "
268                                    "offset %lld have SHA-1 hash "SHA1_FMT" "
269                                    "but should have hash "SHA1_FMT,
270                                    file->name, data_length,
271                                    (long long int) data_offset,
272                                    SHA1_ARGS(actual_sha1),
273                                    SHA1_ARGS(expected_sha1));
274         goto error;
275     }
276
277     if (json->type == JSON_STRING) {
278         error = ovsdb_syntax_error(NULL, NULL, "%s: %lu bytes starting at "
279                                    "offset %lld are not valid JSON (%s)",
280                                    file->name, data_length,
281                                    (long long int) data_offset,
282                                    json->u.string);
283         goto error;
284     }
285
286     file->offset = data_offset + data_length;
287     *jsonp = json;
288     return 0;
289
290 error:
291     file->read_error = ovsdb_error_clone(error);
292     json_destroy(json);
293     return error;
294 }
295
296 struct ovsdb_error *
297 ovsdb_log_write(struct ovsdb_log *file, struct json *json)
298 {
299     uint8_t sha1[SHA1_DIGEST_SIZE];
300     struct ovsdb_error *error;
301     char *json_string;
302     char header[128];
303     size_t length;
304
305     json_string = NULL;
306
307     if (file->write_error) {
308         return ovsdb_error_clone(file->write_error);
309     } else if (file->mode == OVSDB_LOG_READ) {
310         file->mode = OVSDB_LOG_WRITE;
311         if (fseeko(file->stream, file->offset, SEEK_SET)) {
312             error = ovsdb_io_error(errno, "%s: cannot seek to offset %lld",
313                                    file->name, (long long int) file->offset);
314             goto error;
315         }
316         if (ftruncate(fileno(file->stream), file->offset)) {
317             error = ovsdb_io_error(errno, "%s: cannot truncate to length %lld",
318                                    file->name, (long long int) file->offset);
319             goto error;
320         }
321     }
322
323     if (json->type != JSON_OBJECT && json->type != JSON_ARRAY) {
324         error = OVSDB_BUG("bad JSON type");
325         goto error;
326     }
327
328     /* Compose content.  Add a new-line (replacing the null terminator) to make
329      * the file easier to read, even though it has no semantic value.  */
330     json_string = json_to_string(json, 0);
331     length = strlen(json_string) + 1;
332     json_string[length - 1] = '\n';
333
334     /* Compose header. */
335     sha1_bytes(json_string, length, sha1);
336     snprintf(header, sizeof header, "%s%zu "SHA1_FMT"\n",
337              magic, length, SHA1_ARGS(sha1));
338
339     /* Write. */
340     if (fwrite(header, strlen(header), 1, file->stream) != 1
341         || fwrite(json_string, length, 1, file->stream) != 1
342         || fflush(file->stream))
343     {
344         error = ovsdb_io_error(errno, "%s: write failed", file->name);
345
346         /* Remove any partially written data, ignoring errors since there is
347          * nothing further we can do. */
348         ignore(ftruncate(fileno(file->stream), file->offset));
349
350         goto error;
351     }
352
353     file->offset += strlen(header) + length;
354     free(json_string);
355     return 0;
356
357 error:
358     file->write_error = ovsdb_error_clone(error);
359     free(json_string);
360     return error;
361 }
362
363 struct ovsdb_error *
364 ovsdb_log_commit(struct ovsdb_log *file)
365 {
366     if (fsync(fileno(file->stream))) {
367         return ovsdb_io_error(errno, "%s: fsync failed", file->name);
368     }
369     return 0;
370 }
371