d8f3952fb0be9a2d555d9e1ddd7acc3070822eee
[sliver-openvswitch.git] / lib / lockfile.c
1  /* Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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 "lockfile.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 "coverage.h"
28 #include "hash.h"
29 #include "hmap.h"
30 #include "ovs-thread.h"
31 #include "timeval.h"
32 #include "util.h"
33 #include "vlog.h"
34
35 VLOG_DEFINE_THIS_MODULE(lockfile);
36
37 COVERAGE_DEFINE(lockfile_lock);
38 COVERAGE_DEFINE(lockfile_error);
39 COVERAGE_DEFINE(lockfile_unlock);
40
41 struct lockfile {
42     struct hmap_node hmap_node;
43     char *name;
44     dev_t device;
45     ino_t inode;
46     int fd;
47 };
48
49 /* Lock table.
50  *
51  * We have to do this stupid dance because POSIX says that closing *any* file
52  * descriptor for a file on which a process holds a lock drops *all* locks on
53  * that file.  That means that we can't afford to open a lockfile more than
54  * once. */
55 static struct ovs_mutex lock_table_mutex = OVS_MUTEX_INITIALIZER;
56 static struct hmap lock_table__ = HMAP_INITIALIZER(&lock_table__);
57 static struct hmap *const lock_table OVS_GUARDED_BY(lock_table_mutex)
58     = &lock_table__;
59
60 static void lockfile_unhash(struct lockfile *);
61 static int lockfile_try_lock(const char *name, pid_t *pidp,
62                              struct lockfile **lockfilep);
63
64 /* Returns the name of the lockfile that would be created for locking a file
65  * named 'filename_'.  The caller is responsible for freeing the returned name,
66  * with free(), when it is no longer needed. */
67 char *
68 lockfile_name(const char *filename_)
69 {
70     char *filename;
71     const char *slash;
72     char *lockname;
73
74     /* If 'filename_' is a symlink, base the name of the lockfile on the
75      * symlink's target rather than the name of the symlink.  That way, if a
76      * file is symlinked, but there is no symlink for its lockfile, then there
77      * is only a single lockfile for both the source and the target of the
78      * symlink, not one for each. */
79     filename = follow_symlinks(filename_);
80     slash = strrchr(filename, '/');
81     lockname = (slash
82                 ? xasprintf("%.*s/.%s.~lock~",
83                             (int) (slash - filename), filename, slash + 1)
84                 : xasprintf(".%s.~lock~", filename));
85     free(filename);
86
87     return lockname;
88 }
89
90 /* Locks the configuration file against modification by other processes and
91  * re-reads it from disk.
92  *
93  * Returns 0 on success, otherwise a positive errno value.  On success,
94  * '*lockfilep' is set to point to a new "struct lockfile *" that may be
95  * unlocked with lockfile_unlock().  On failure, '*lockfilep' is set to
96  * NULL.  Will not block if the lock cannot be immediately acquired. */
97 int
98 lockfile_lock(const char *file, struct lockfile **lockfilep)
99 {
100     /* Only exclusive ("write") locks are supported.  This is not a problem
101      * because the Open vSwitch code that currently uses lock files does so in
102      * stylized ways such that any number of readers may access a file while it
103      * is being written. */
104     char *lock_name;
105     pid_t pid;
106     int error;
107
108     COVERAGE_INC(lockfile_lock);
109
110     lock_name = lockfile_name(file);
111
112     ovs_mutex_lock(&lock_table_mutex);
113     error = lockfile_try_lock(lock_name, &pid, lockfilep);
114     ovs_mutex_unlock(&lock_table_mutex);
115
116     if (error) {
117         COVERAGE_INC(lockfile_error);
118         if (error == EACCES) {
119             error = EAGAIN;
120         }
121         if (pid) {
122             VLOG_WARN("%s: cannot lock file because it is already locked by "
123                       "pid %ld", lock_name, (long int) pid);
124         } else {
125             VLOG_WARN("%s: failed to lock file: %s",
126                       lock_name, ovs_strerror(error));
127         }
128     }
129
130     free(lock_name);
131     return error;
132 }
133
134 /* Unlocks 'lockfile', which must have been created by a call to
135  * lockfile_lock(), and frees 'lockfile'. */
136 void
137 lockfile_unlock(struct lockfile *lockfile)
138 {
139     if (lockfile) {
140         ovs_mutex_lock(&lock_table_mutex);
141         lockfile_unhash(lockfile);
142         ovs_mutex_unlock(&lock_table_mutex);
143
144         COVERAGE_INC(lockfile_unlock);
145         free(lockfile->name);
146         free(lockfile);
147     }
148 }
149
150 /* Marks all the currently locked lockfiles as no longer locked.  It makes
151  * sense to call this function after fork(), because a child created by fork()
152  * does not hold its parents' locks. */
153 void
154 lockfile_postfork(void)
155 {
156     struct lockfile *lockfile;
157
158     ovs_mutex_lock(&lock_table_mutex);
159     HMAP_FOR_EACH (lockfile, hmap_node, lock_table) {
160         if (lockfile->fd >= 0) {
161             VLOG_WARN("%s: child does not inherit lock", lockfile->name);
162             lockfile_unhash(lockfile);
163         }
164     }
165     ovs_mutex_unlock(&lock_table_mutex);
166 }
167 \f
168 static uint32_t
169 lockfile_hash(dev_t device, ino_t inode)
170 {
171     return hash_bytes(&device, sizeof device,
172                       hash_bytes(&inode, sizeof inode, 0));
173 }
174
175 static struct lockfile *
176 lockfile_find(dev_t device, ino_t inode) OVS_REQUIRES(&lock_table_mutex)
177 {
178     struct lockfile *lockfile;
179
180     HMAP_FOR_EACH_WITH_HASH (lockfile, hmap_node,
181                              lockfile_hash(device, inode), lock_table) {
182         if (lockfile->device == device && lockfile->inode == inode) {
183             return lockfile;
184         }
185     }
186     return NULL;
187 }
188
189 static void
190 lockfile_unhash(struct lockfile *lockfile) OVS_REQUIRES(&lock_table_mutex)
191 {
192     if (lockfile->fd >= 0) {
193         close(lockfile->fd);
194         lockfile->fd = -1;
195         hmap_remove(lock_table, &lockfile->hmap_node);
196     }
197 }
198
199 static struct lockfile *
200 lockfile_register(const char *name, dev_t device, ino_t inode, int fd)
201     OVS_REQUIRES(&lock_table_mutex)
202 {
203     struct lockfile *lockfile;
204
205     lockfile = lockfile_find(device, inode);
206     if (lockfile) {
207         VLOG_ERR("%s: lock file disappeared and reappeared!", name);
208         lockfile_unhash(lockfile);
209     }
210
211     lockfile = xmalloc(sizeof *lockfile);
212     lockfile->name = xstrdup(name);
213     lockfile->device = device;
214     lockfile->inode = inode;
215     lockfile->fd = fd;
216     hmap_insert(lock_table, &lockfile->hmap_node,
217                 lockfile_hash(device, inode));
218     return lockfile;
219 }
220
221 static int
222 lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
223     OVS_REQUIRES(&lock_table_mutex)
224 {
225     struct flock l;
226     struct stat s;
227     int error;
228     int fd;
229
230     *lockfilep = NULL;
231     *pidp = 0;
232
233     /* Check whether we've already got a lock on that file. */
234     if (!stat(name, &s)) {
235         if (lockfile_find(s.st_dev, s.st_ino)) {
236             return EDEADLK;
237         }
238     } else if (errno != ENOENT) {
239         VLOG_WARN("%s: failed to stat lock file: %s",
240                   name, ovs_strerror(errno));
241         return errno;
242     }
243
244     /* Open the lock file. */
245     fd = open(name, O_RDWR | O_CREAT, 0600);
246     if (fd < 0) {
247         VLOG_WARN("%s: failed to open lock file: %s",
248                   name, ovs_strerror(errno));
249         return errno;
250     }
251
252     /* Get the inode and device number for the lock table. */
253     if (fstat(fd, &s)) {
254         VLOG_ERR("%s: failed to fstat lock file: %s",
255                  name, ovs_strerror(errno));
256         close(fd);
257         return errno;
258     }
259
260     /* Try to lock the file. */
261     memset(&l, 0, sizeof l);
262     l.l_type = F_WRLCK;
263     l.l_whence = SEEK_SET;
264     l.l_start = 0;
265     l.l_len = 0;
266
267     error = fcntl(fd, F_SETLK, &l) == -1 ? errno : 0;
268
269     if (!error) {
270         *lockfilep = lockfile_register(name, s.st_dev, s.st_ino, fd);
271     } else {
272         if (!fcntl(fd, F_GETLK, &l) && l.l_type != F_UNLCK) {
273             *pidp = l.l_pid;
274         }
275         close(fd);
276     }
277     return error;
278 }
279