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