summaryrefslogtreecommitdiff
path: root/lib/lockfile.c
blob: 864d3eff0906fe75f5a077bf4e5f911a6c83fae1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
 /* Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <config.h>

#include "lockfile.h"

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "coverage.h"
#include "hash.h"
#include "hmap.h"
#include "ovs-thread.h"
#include "timeval.h"
#include "util.h"
#include "openvswitch/vlog.h"

VLOG_DEFINE_THIS_MODULE(lockfile);

COVERAGE_DEFINE(lockfile_lock);
COVERAGE_DEFINE(lockfile_error);
COVERAGE_DEFINE(lockfile_unlock);

struct lockfile {
    struct hmap_node hmap_node;
    char *name;
    dev_t device;
    ino_t inode;
    int fd;
    HANDLE lock_handle;
};

/* Lock table.
 *
 * We have to do this stupid dance because POSIX says that closing *any* file
 * descriptor for a file on which a process holds a lock drops *all* locks on
 * that file.  That means that we can't afford to open a lockfile more than
 * once. */
static struct ovs_mutex lock_table_mutex = OVS_MUTEX_INITIALIZER;
static struct hmap lock_table__ = HMAP_INITIALIZER(&lock_table__);
static struct hmap *const lock_table OVS_GUARDED_BY(lock_table_mutex)
    = &lock_table__;

static void lockfile_unhash(struct lockfile *);
static int lockfile_try_lock(const char *name, pid_t *pidp,
                             struct lockfile **lockfilep)
    OVS_REQUIRES(&lock_table_mutex);
static void lockfile_do_unlock(struct lockfile * lockfile)
    OVS_REQUIRES(&lock_table_mutex);

/* Returns the name of the lockfile that would be created for locking a file
 * named 'filename_'.  The caller is responsible for freeing the returned name,
 * with free(), when it is no longer needed. */
char *
lockfile_name(const char *filename_)
{
    char *filename;
    const char *slash;
    char *lockname;

    /* If 'filename_' is a symlink, base the name of the lockfile on the
     * symlink's target rather than the name of the symlink.  That way, if a
     * file is symlinked, but there is no symlink for its lockfile, then there
     * is only a single lockfile for both the source and the target of the
     * symlink, not one for each. */
    filename = follow_symlinks(filename_);
    slash = strrchr(filename, '/');

#ifdef _WIN32
    char *backslash = strrchr(filename, '\\');
    if (backslash && (!slash || backslash > slash)) {
        slash = backslash;
    }
#endif

    lockname = (slash
                ? xasprintf("%.*s/.%s.~lock~",
                            (int) (slash - filename), filename, slash + 1)
                : xasprintf(".%s.~lock~", filename));
    free(filename);

    return lockname;
}

/* Locks the configuration file against modification by other processes and
 * re-reads it from disk.
 *
 * Returns 0 on success, otherwise a positive errno value.  On success,
 * '*lockfilep' is set to point to a new "struct lockfile *" that may be
 * unlocked with lockfile_unlock().  On failure, '*lockfilep' is set to
 * NULL.  Will not block if the lock cannot be immediately acquired. */
int
lockfile_lock(const char *file, struct lockfile **lockfilep)
{
    /* Only exclusive ("write") locks are supported.  This is not a problem
     * because the Open vSwitch code that currently uses lock files does so in
     * stylized ways such that any number of readers may access a file while it
     * is being written. */
    char *lock_name;
    pid_t pid;
    int error;

    COVERAGE_INC(lockfile_lock);

    lock_name = lockfile_name(file);

    ovs_mutex_lock(&lock_table_mutex);
    error = lockfile_try_lock(lock_name, &pid, lockfilep);
    ovs_mutex_unlock(&lock_table_mutex);

    if (error) {
        COVERAGE_INC(lockfile_error);
        if (error == EACCES) {
            error = EAGAIN;
        }
        if (pid == getpid()) {
            VLOG_WARN("%s: cannot lock file because this process has already "
                      "locked it", lock_name);
        } else if (pid) {
            VLOG_WARN("%s: cannot lock file because it is already locked by "
                      "pid %ld", lock_name, (long int) pid);
        } else {
            VLOG_WARN("%s: failed to lock file: %s",
                      lock_name, ovs_strerror(error));
        }
    }

    free(lock_name);
    return error;
}

/* Unlocks 'lockfile', which must have been created by a call to
 * lockfile_lock(), and frees 'lockfile'. */
void
lockfile_unlock(struct lockfile *lockfile)
{
    if (lockfile) {
        ovs_mutex_lock(&lock_table_mutex);
        lockfile_do_unlock(lockfile);
        ovs_mutex_unlock(&lock_table_mutex);

        COVERAGE_INC(lockfile_unlock);
        free(lockfile->name);
        free(lockfile);
    }
}

/* Marks all the currently locked lockfiles as no longer locked.  It makes
 * sense to call this function after fork(), because a child created by fork()
 * does not hold its parents' locks. */
void
lockfile_postfork(void)
{
    struct lockfile *lockfile;

    ovs_mutex_lock(&lock_table_mutex);
    HMAP_FOR_EACH (lockfile, hmap_node, lock_table) {
        if (lockfile->fd >= 0) {
            VLOG_WARN("%s: child does not inherit lock", lockfile->name);
            lockfile_unhash(lockfile);
        }
    }
    ovs_mutex_unlock(&lock_table_mutex);
}

static uint32_t
lockfile_hash(dev_t device, ino_t inode)
{
    return hash_bytes(&device, sizeof device,
                      hash_bytes(&inode, sizeof inode, 0));
}

static struct lockfile *
lockfile_find(dev_t device, ino_t inode) OVS_REQUIRES(&lock_table_mutex)
{
    struct lockfile *lockfile;

    HMAP_FOR_EACH_WITH_HASH (lockfile, hmap_node,
                             lockfile_hash(device, inode), lock_table) {
        if (lockfile->device == device && lockfile->inode == inode) {
            return lockfile;
        }
    }
    return NULL;
}

static void
lockfile_unhash(struct lockfile *lockfile) OVS_REQUIRES(&lock_table_mutex)
{
    if (lockfile->fd >= 0) {
        close(lockfile->fd);
        lockfile->fd = -1;
        hmap_remove(lock_table, &lockfile->hmap_node);
    }
}

static struct lockfile *
lockfile_register(const char *name, dev_t device, ino_t inode, int fd)
    OVS_REQUIRES(&lock_table_mutex)
{
    struct lockfile *lockfile;

    lockfile = lockfile_find(device, inode);
    if (lockfile) {
        VLOG_ERR("%s: lock file disappeared and reappeared!", name);
        lockfile_unhash(lockfile);
    }

    lockfile = xmalloc(sizeof *lockfile);
    lockfile->name = xstrdup(name);
    lockfile->device = device;
    lockfile->inode = inode;
    lockfile->fd = fd;
    hmap_insert(lock_table, &lockfile->hmap_node,
                lockfile_hash(device, inode));
    return lockfile;
}

#ifdef _WIN32
static void
lockfile_do_unlock(struct lockfile *lockfile)
    OVS_REQUIRES(&lock_table_mutex)
{
    if (lockfile->fd >= 0) {
        OVERLAPPED overl;
        overl.hEvent = 0;
        overl.Offset = 0;
        overl.OffsetHigh = 0;
        UnlockFileEx(lockfile->lock_handle, 0, 1, 0, &overl);

        close(lockfile->fd);
        lockfile->fd = -1;
    }
}

static int
lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
    OVS_REQUIRES(&lock_table_mutex)
{
    HANDLE lock_handle;
    BOOL retval;
    OVERLAPPED overl;
    struct lockfile *lockfile;
    int fd;

    *pidp = 0;

    fd = open(name, O_RDWR | O_CREAT, 0600);
    if (fd < 0) {
        VLOG_WARN("%s: failed to open lock file: %s",
                   name, ovs_strerror(errno));
        return errno;
    }

    lock_handle = (HANDLE)_get_osfhandle(fd);
    if (lock_handle < 0) {
        VLOG_WARN("%s: failed to get the file handle: %s",
                   name, ovs_strerror(errno));
        return errno;
    }

    /* Lock the file 'name' for the region that includes just the first
     * byte. */
    overl.hEvent = 0;
    overl.Offset = 0;
    overl.OffsetHigh = 0;
    retval = LockFileEx(lock_handle, LOCKFILE_EXCLUSIVE_LOCK
                        | LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overl);
    if (!retval) {
        VLOG_DBG("Failed to lock file : %s", ovs_lasterror_to_string());
        *pidp = getpid();
        return EDEADLK;
    }

    lockfile = xmalloc(sizeof *lockfile);
    lockfile->name = xstrdup(name);
    lockfile->fd = fd;
    lockfile->lock_handle = lock_handle;

    *lockfilep = lockfile;
    return 0;
}
#else /* !_WIN32 */
static void
lockfile_do_unlock(struct lockfile *lockfile)
{
    lockfile_unhash(lockfile);
}

static int
lockfile_try_lock(const char *name, pid_t *pidp, struct lockfile **lockfilep)
    OVS_REQUIRES(&lock_table_mutex)
{
    struct flock l;
    struct stat s;
    int error;
    int fd;

    *lockfilep = NULL;
    *pidp = 0;

    /* Check whether we've already got a lock on that file. */
    if (!stat(name, &s)) {
        if (lockfile_find(s.st_dev, s.st_ino)) {
            *pidp = getpid();
            return EDEADLK;
        }
    } else if (errno != ENOENT) {
        VLOG_WARN("%s: failed to stat lock file: %s",
                  name, ovs_strerror(errno));
        return errno;
    }

    /* Open the lock file. */
    fd = open(name, O_RDWR | O_CREAT, 0600);
    if (fd < 0) {
        VLOG_WARN("%s: failed to open lock file: %s",
                  name, ovs_strerror(errno));
        return errno;
    }

    /* Get the inode and device number for the lock table. */
    if (fstat(fd, &s)) {
        VLOG_ERR("%s: failed to fstat lock file: %s",
                 name, ovs_strerror(errno));
        close(fd);
        return errno;
    }

    /* Try to lock the file. */
    memset(&l, 0, sizeof l);
    l.l_type = F_WRLCK;
    l.l_whence = SEEK_SET;
    l.l_start = 0;
    l.l_len = 0;

    error = fcntl(fd, F_SETLK, &l) == -1 ? errno : 0;

    if (!error) {
        *lockfilep = lockfile_register(name, s.st_dev, s.st_ino, fd);
    } else {
        if (!fcntl(fd, F_GETLK, &l) && l.l_type != F_UNLCK) {
            *pidp = l.l_pid;
        }
        close(fd);
    }
    return error;
}
#endif