Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.git] / lib / lockfile.c
1  /* Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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     HANDLE lock_handle;
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 ovs_mutex lock_table_mutex = OVS_MUTEX_INITIALIZER;
57 static struct hmap lock_table__ = HMAP_INITIALIZER(&lock_table__);
58 static struct hmap *const lock_table OVS_GUARDED_BY(lock_table_mutex)
59     = &lock_table__;
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     OVS_REQUIRES(&lock_table_mutex);
65 static void lockfile_do_unlock(struct lockfile * lockfile)
66     OVS_REQUIRES(&lock_table_mutex);
67
68 /* Returns the name of the lockfile that would be created for locking a file
69  * named 'filename_'.  The caller is responsible for freeing the returned name,
70  * with free(), when it is no longer needed. */
71 char *
72 lockfile_name(const char *filename_)
73 {
74     char *filename;
75     const char *slash;
76     char *lockname;
77
78     /* If 'filename_' is a symlink, base the name of the lockfile on the
79      * symlink's target rather than the name of the symlink.  That way, if a
80      * file is symlinked, but there is no symlink for its lockfile, then there
81      * is only a single lockfile for both the source and the target of the
82      * symlink, not one for each. */
83     filename = follow_symlinks(filename_);
84     slash = strrchr(filename, '/');
85     lockname = (slash
86                 ? xasprintf("%.*s/.%s.~lock~",
87                             (int) (slash - filename), filename, slash + 1)
88                 : xasprintf(".%s.~lock~", filename));
89     free(filename);
90
91     return lockname;
92 }
93
94 /* Locks the configuration file against modification by other processes and
95  * re-reads it from disk.
96  *
97  * Returns 0 on success, otherwise a positive errno value.  On success,
98  * '*lockfilep' is set to point to a new "struct lockfile *" that may be
99  * unlocked with lockfile_unlock().  On failure, '*lockfilep' is set to
100  * NULL.  Will not block if the lock cannot be immediately acquired. */
101 int
102 lockfile_lock(const char *file, struct lockfile **lockfilep)
103 {
104     /* Only exclusive ("write") locks are supported.  This is not a problem
105      * because the Open vSwitch code that currently uses lock files does so in
106      * stylized ways such that any number of readers may access a file while it
107      * is being written. */
108     char *lock_name;
109     pid_t pid;
110     int error;
111
112     COVERAGE_INC(lockfile_lock);
113
114     lock_name = lockfile_name(file);
115
116     ovs_mutex_lock(&lock_table_mutex);
117     error = lockfile_try_lock(lock_name, &pid, lockfilep);
118     ovs_mutex_unlock(&lock_table_mutex);
119
120     if (error) {
121         COVERAGE_INC(lockfile_error);
122         if (error == EACCES) {
123             error = EAGAIN;
124         }
125         if (pid == getpid()) {
126             VLOG_WARN("%s: cannot lock file because this process has already "
127                       "locked it", lock_name);
128         } else if (pid) {
129             VLOG_WARN("%s: cannot lock file because it is already locked by "
130                       "pid %ld", lock_name, (long int) pid);
131         } else {
132             VLOG_WARN("%s: failed to lock file: %s",
133                       lock_name, ovs_strerror(error));
134         }
135     }
136
137     free(lock_name);
138     return error;
139 }
140
141 /* Unlocks 'lockfile', which must have been created by a call to
142  * lockfile_lock(), and frees 'lockfile'. */
143 void
144 lockfile_unlock(struct lockfile *lockfile)
145 {
146     if (lockfile) {
147         ovs_mutex_lock(&lock_table_mutex);
148         lockfile_do_unlock(lockfile);
149         ovs_mutex_unlock(&lock_table_mutex);
150
151         COVERAGE_INC(lockfile_unlock);
152         free(lockfile->name);
153         free(lockfile);
154     }
155 }
156
157 /* Marks all the currently locked lockfiles as no longer locked.  It makes
158  * sense to call this function after fork(), because a child created by fork()
159  * does not hold its parents' locks. */
160 void
161 lockfile_postfork(void)
162 {
163     struct lockfile *lockfile;
164
165     ovs_mutex_lock(&lock_table_mutex);
166     HMAP_FOR_EACH (lockfile, hmap_node, lock_table) {
167         if (lockfile->fd >= 0) {
168             VLOG_WARN("%s: child does not inherit lock", lockfile->name);
169             lockfile_unhash(lockfile);
170         }
171     }
172     ovs_mutex_unlock(&lock_table_mutex);
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) OVS_REQUIRES(&lock_table_mutex)
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) OVS_REQUIRES(&lock_table_mutex)
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     OVS_REQUIRES(&lock_table_mutex)
209 {
210     struct lockfile *lockfile;
211
212     lockfile = lockfile_find(device, inode);
213     if (lockfile) {
214         VLOG_ERR("%s: lock file disappeared and reappeared!", name);
215         lockfile_unhash(lockfile);
216     }
217
218     lockfile = xmalloc(sizeof *lockfile);
219     lockfile->name = xstrdup(name);
220     lockfile->device = device;
221     lockfile->inode = inode;
222     lockfile->fd = fd;
223     hmap_insert(lock_table, &lockfile->hmap_node,
224                 lockfile_hash(device, inode));
225     return lockfile;
226 }
227
228 #ifdef _WIN32
229 static void
230 lockfile_do_unlock(struct lockfile *lockfile)
231     OVS_REQUIRES(&lock_table_mutex)
232 {
233     if (lockfile->fd >= 0) {
234         OVERLAPPED overl;
235         overl.hEvent = 0;
236         overl.Offset = 0;
237         overl.OffsetHigh = 0;
238         UnlockFileEx(lockfile->lock_handle, 0, 1, 0, &overl);
239
240         close(lockfile->fd);
241         lockfile->fd = -1;
242     }
243 }
244
245 static int
246 lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
247     OVS_REQUIRES(&lock_table_mutex)
248 {
249     HANDLE lock_handle;
250     BOOL retval;
251     OVERLAPPED overl;
252     struct lockfile *lockfile;
253     int fd;
254
255     *pidp = 0;
256
257     fd = open(name, O_RDWR | O_CREAT, 0600);
258     if (fd < 0) {
259         VLOG_WARN("%s: failed to open lock file: %s",
260                    name, ovs_strerror(errno));
261         return errno;
262     }
263
264     lock_handle = (HANDLE)_get_osfhandle(fd);
265     if (lock_handle < 0) {
266         VLOG_WARN("%s: failed to get the file handle: %s",
267                    name, ovs_strerror(errno));
268         return errno;
269     }
270
271     /* Lock the file 'name' for the region that includes just the first
272      * byte. */
273     overl.hEvent = 0;
274     overl.Offset = 0;
275     overl.OffsetHigh = 0;
276     retval = LockFileEx(lock_handle, LOCKFILE_EXCLUSIVE_LOCK
277                         | LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overl);
278     if (!retval) {
279         VLOG_WARN("Failed to lock file : %s", ovs_lasterror_to_string());
280         return EEXIST;
281     }
282
283     lockfile = xmalloc(sizeof *lockfile);
284     lockfile->name = xstrdup(name);
285     lockfile->fd = fd;
286     lockfile->lock_handle = lock_handle;
287
288     *lockfilep = lockfile;
289     return 0;
290 }
291 #else /* !_WIN32 */
292 static void
293 lockfile_do_unlock(struct lockfile *lockfile)
294 {
295     lockfile_unhash(lockfile);
296 }
297
298 static int
299 lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
300     OVS_REQUIRES(&lock_table_mutex)
301 {
302     struct flock l;
303     struct stat s;
304     int error;
305     int fd;
306
307     *lockfilep = NULL;
308     *pidp = 0;
309
310     /* Check whether we've already got a lock on that file. */
311     if (!stat(name, &s)) {
312         if (lockfile_find(s.st_dev, s.st_ino)) {
313             *pidp = getpid();
314             return EDEADLK;
315         }
316     } else if (errno != ENOENT) {
317         VLOG_WARN("%s: failed to stat lock file: %s",
318                   name, ovs_strerror(errno));
319         return errno;
320     }
321
322     /* Open the lock file. */
323     fd = open(name, O_RDWR | O_CREAT, 0600);
324     if (fd < 0) {
325         VLOG_WARN("%s: failed to open lock file: %s",
326                   name, ovs_strerror(errno));
327         return errno;
328     }
329
330     /* Get the inode and device number for the lock table. */
331     if (fstat(fd, &s)) {
332         VLOG_ERR("%s: failed to fstat lock file: %s",
333                  name, ovs_strerror(errno));
334         close(fd);
335         return errno;
336     }
337
338     /* Try to lock the file. */
339     memset(&l, 0, sizeof l);
340     l.l_type = F_WRLCK;
341     l.l_whence = SEEK_SET;
342     l.l_start = 0;
343     l.l_len = 0;
344
345     error = fcntl(fd, F_SETLK, &l) == -1 ? errno : 0;
346
347     if (!error) {
348         *lockfilep = lockfile_register(name, s.st_dev, s.st_ino, fd);
349     } else {
350         if (!fcntl(fd, F_GETLK, &l) && l.l_type != F_UNLCK) {
351             *pidp = l.l_pid;
352         }
353         close(fd);
354     }
355     return error;
356 }
357 #endif