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