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