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