7ac34659b36f0637f9fd83d2c2a84c33d30e5197
[sliver-openvswitch.git] / lib / lockfile.c
1  /* Copyright (c) 2008, 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 "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 "timeval.h"
31 #include "util.h"
32 #include "vlog.h"
33
34 VLOG_DEFINE_THIS_MODULE(lockfile);
35
36 COVERAGE_DEFINE(lockfile_lock);
37 COVERAGE_DEFINE(lockfile_timeout);
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 hmap lock_table = HMAP_INITIALIZER(&lock_table);
56
57 static void lockfile_unhash(struct lockfile *);
58 static int lockfile_try_lock(const char *name, bool block,
59                              struct lockfile **lockfilep);
60
61 /* Returns the name of the lockfile that would be created for locking a file
62  * named 'filename_'.  The caller is responsible for freeing the returned name,
63  * with free(), when it is no longer needed. */
64 char *
65 lockfile_name(const char *filename_)
66 {
67     char *filename;
68     const char *slash;
69     char *lockname;
70
71     /* If 'filename_' is a symlink, base the name of the lockfile on the
72      * symlink's target rather than the name of the symlink.  That way, if a
73      * file is symlinked, but there is no symlink for its lockfile, then there
74      * is only a single lockfile for both the source and the target of the
75      * symlink, not one for each. */
76     filename = follow_symlinks(filename_);
77     slash = strrchr(filename, '/');
78     lockname = (slash
79                 ? xasprintf("%.*s/.%s.~lock~",
80                             (int) (slash - filename), filename, slash + 1)
81                 : xasprintf(".%s.~lock~", filename));
82     free(filename);
83
84     return lockname;
85 }
86
87 /* Locks the configuration file against modification by other processes and
88  * re-reads it from disk.
89  *
90  * The 'timeout' specifies the maximum number of milliseconds to wait for the
91  * config file to become free.  Use 0 to avoid waiting or INT_MAX to wait
92  * forever.
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. */
98 int
99 lockfile_lock(const char *file, int timeout, 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     long long int warn_elapsed = 1000;
106     long long int start, elapsed;
107     char *lock_name;
108     int error;
109
110     COVERAGE_INC(lockfile_lock);
111
112     lock_name = lockfile_name(file);
113     time_refresh();
114     start = time_msec();
115
116     do {
117         error = lockfile_try_lock(lock_name, timeout > 0, lockfilep);
118         time_refresh();
119         elapsed = time_msec() - start;
120         if (elapsed > warn_elapsed) {
121             warn_elapsed *= 2;
122             VLOG_WARN("%s: waiting for lock file, %lld ms elapsed",
123                       lock_name, elapsed);
124         }
125     } while (error == EINTR && (timeout == INT_MAX || elapsed < timeout));
126
127     if (error == EINTR) {
128         COVERAGE_INC(lockfile_timeout);
129         VLOG_WARN("%s: giving up on lock file after %lld ms",
130                   lock_name, elapsed);
131         error = ETIMEDOUT;
132     } else if (error) {
133         COVERAGE_INC(lockfile_error);
134         if (error == EACCES) {
135             error = EAGAIN;
136         }
137         VLOG_WARN("%s: failed to lock file "
138                   "(after %lld ms, with %d-ms timeout): %s",
139                   lock_name, elapsed, timeout, strerror(error));
140     }
141
142     free(lock_name);
143     return error;
144 }
145
146 /* Unlocks 'lockfile', which must have been created by a call to
147  * lockfile_lock(), and frees 'lockfile'. */
148 void
149 lockfile_unlock(struct lockfile *lockfile)
150 {
151     if (lockfile) {
152         COVERAGE_INC(lockfile_unlock);
153         lockfile_unhash(lockfile);
154         free(lockfile->name);
155         free(lockfile);
156     }
157 }
158
159 /* Marks all the currently locked lockfiles as no longer locked.  It makes
160  * sense to call this function after fork(), because a child created by fork()
161  * does not hold its parents' locks. */
162 void
163 lockfile_postfork(void)
164 {
165     struct lockfile *lockfile;
166
167     HMAP_FOR_EACH (lockfile, hmap_node, &lock_table) {
168         if (lockfile->fd >= 0) {
169             VLOG_WARN("%s: child does not inherit lock", lockfile->name);
170             lockfile_unhash(lockfile);
171         }
172     }
173 }
174 \f
175 static uint32_t
176 lockfile_hash(dev_t device, ino_t inode)
177 {
178     return hash_bytes(&device, sizeof device,
179                       hash_bytes(&inode, sizeof inode, 0));
180 }
181
182 static struct lockfile *
183 lockfile_find(dev_t device, ino_t inode)
184 {
185     struct lockfile *lockfile;
186
187     HMAP_FOR_EACH_WITH_HASH (lockfile, hmap_node,
188                              lockfile_hash(device, inode), &lock_table) {
189         if (lockfile->device == device && lockfile->inode == inode) {
190             return lockfile;
191         }
192     }
193     return NULL;
194 }
195
196 static void
197 lockfile_unhash(struct lockfile *lockfile)
198 {
199     if (lockfile->fd >= 0) {
200         close(lockfile->fd);
201         lockfile->fd = -1;
202         hmap_remove(&lock_table, &lockfile->hmap_node);
203     }
204 }
205
206 static struct lockfile *
207 lockfile_register(const char *name, dev_t device, ino_t inode, int fd)
208 {
209     struct lockfile *lockfile;
210
211     lockfile = lockfile_find(device, inode);
212     if (lockfile) {
213         VLOG_ERR("%s: lock file disappeared and reappeared!", name);
214         lockfile_unhash(lockfile);
215     }
216
217     lockfile = xmalloc(sizeof *lockfile);
218     lockfile->name = xstrdup(name);
219     lockfile->device = device;
220     lockfile->inode = inode;
221     lockfile->fd = fd;
222     hmap_insert(&lock_table, &lockfile->hmap_node,
223                 lockfile_hash(device, inode));
224     return lockfile;
225 }
226
227 static int
228 lockfile_try_lock(const char *name, bool block, struct lockfile **lockfilep)
229 {
230     struct flock l;
231     struct stat s;
232     int error;
233     int fd;
234
235     *lockfilep = NULL;
236
237     /* Check whether we've already got a lock on that file. */
238     if (!stat(name, &s)) {
239         if (lockfile_find(s.st_dev, s.st_ino)) {
240             return EDEADLK;
241         }
242     } else if (errno != ENOENT) {
243         VLOG_WARN("%s: failed to stat lock file: %s",
244                   name, strerror(errno));
245         return errno;
246     }
247
248     /* Open the lock file. */
249     fd = open(name, O_RDWR | O_CREAT, 0600);
250     if (fd < 0) {
251         VLOG_WARN("%s: failed to open lock file: %s",
252                   name, strerror(errno));
253         return errno;
254     }
255
256     /* Get the inode and device number for the lock table. */
257     if (fstat(fd, &s)) {
258         VLOG_ERR("%s: failed to fstat lock file: %s", name, strerror(errno));
259         close(fd);
260         return errno;
261     }
262
263     /* Try to lock the file. */
264     memset(&l, 0, sizeof l);
265     l.l_type = F_WRLCK;
266     l.l_whence = SEEK_SET;
267     l.l_start = 0;
268     l.l_len = 0;
269
270     time_disable_restart();
271     error = fcntl(fd, block ? F_SETLKW : F_SETLK, &l) == -1 ? errno : 0;
272     time_enable_restart();
273
274     if (!error) {
275         *lockfilep = lockfile_register(name, s.st_dev, s.st_ino, fd);
276     } else {
277         close(fd);
278     }
279     return error;
280 }
281