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