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