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