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
#include "lix/libstore/pathlocks.hh"
#include "lix/libutil/async.hh"
#include "lix/libutil/c-calls.hh"
#include "lix/libutil/file-descriptor.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/signals.hh"
#include "lix/libutil/types.hh"

#include <cerrno>

#include <fcntl.h>
#include <kj/common.h>
#include <optional>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>


namespace nix {


AutoCloseFD openLockFile(const Path & path, bool create)
{
    AutoCloseFD fd{sys::open(path, O_CLOEXEC | O_RDWR | (create ? O_CREAT : 0), 0600)};
    if (!fd && (create || errno != ENOENT))
        throw SysError("opening lock file '%1%'", path);

    return fd;
}


static int convertLockType(LockType lockType)
{
    if (lockType == ltRead) return LOCK_SH;
    else if (lockType == ltWrite) return LOCK_EX;
    else abort();
}

void lockFile(int fd, LockType lockType, NeverAsync)
{
    int type = convertLockType(lockType);

    while (flock(fd, type) != 0) {
        checkInterrupt();
        if (errno != EINTR)
            throw SysError("acquiring lock");
    }
}

static kj::Promise<Result<void>> lockFileAsyncInner(int fd, LockType lockType)
try {
    // start a thread to lock the file synchronously, waiting for an
    // INTERRUPT_NOTIFY_SIGNAL to signal that the call was canceled.

    int type = convertLockType(lockType);
    auto pfp = kj::newPromiseAndCrossThreadFulfiller<Result<void>>();

    std::thread locker([&] {
        while (flock(fd, type) != 0 && pfp.fulfiller->isWaiting()) {
            if (errno != EINTR) {
                pfp.fulfiller->fulfill(std::make_exception_ptr(SysError("acquiring lock")));
                return;
            }
        }
        pfp.fulfiller->fulfill(result::success());
    });
    auto cancel = kj::defer([&] {
        pthread_kill(locker.native_handle(), INTERRUPT_NOTIFY_SIGNAL);
        locker.join();
    });

    TRY_AWAIT(makeInterruptible(std::move(pfp.promise)));
    locker.join();
    cancel.cancel();
    co_return result::success();
} catch (...) {
    co_return result::current_exception();
}

kj::Promise<Result<void>> lockFileAsync(int fd, LockType lockType)
try {
    if (tryLockFile(fd, lockType)) {
        return {result::success()};
    }

    return lockFileAsyncInner(fd, lockType);
} catch (...) {
    return {result::current_exception()};
}

bool tryLockFile(int fd, LockType lockType)
{
    int type = convertLockType(lockType);

    while (flock(fd, type | LOCK_NB) != 0) {
        checkInterrupt();
        if (errno == EWOULDBLOCK) return false;
        if (errno != EINTR)
            throw SysError("acquiring lock");
    }

    return true;
}

void unlockFile(int fd)
{
    while (flock(fd, LOCK_UN) != 0) {
        if (errno != EINTR) {
            throw SysError("releasing lock");
        }
    }
}


static bool isPathLockValid(AutoCloseFD & fd, const Path & lockPath)
{
    /* Check that the lock file hasn't become stale (i.e.,
       hasn't been unlinked). */
    struct stat st;
    if (fstat(fd.get(), &st) == -1)
        throw SysError("statting lock file '%1%'", lockPath);
    if (st.st_nlink == 0) {
        /* This lock file has been unlinked, so we're holding
           a lock on a deleted file.  This means that other
           processes may create and acquire a lock on
           `lockPath', and proceed.  So we must retry. */
        debug("open lock file '%1%' has become stale", lockPath);
        return false;
    } else {
        return true;
    }
}

std::optional<PathLock>
PathLock::lockImpl(const Path & path, std::string_view waitMsg, bool wait, NeverAsync)
{
    Path lockPath = path + ".lock";

    debug("locking path '%1%'", path);

    while (1) {

        /* Open/create the lock file. */
        auto fd = openLockFile(lockPath, true);

        /* Acquire an exclusive lock. */
        if (!tryLockFile(fd.get(), ltWrite)) {
            if (wait) {
                if (waitMsg != "") {
                    printError("%1%", Uncolored(waitMsg));
                }
                lockFile(fd.get(), ltWrite);
            } else {
                return std::nullopt;
            }
        }

        debug("lock acquired on '%1%'", lockPath);
        if (isPathLockValid(fd, lockPath))
            return PathLock{std::move(fd), lockPath};
    }
}

kj::Promise<Result<PathLock>> lockPathAsync(const Path & path, std::string_view waitMsg)
try {
    Path lockPath = path + ".lock";
    debug("locking path '%1%'", path);

    while (1) {
        auto fd = openLockFile(lockPath, true);
        TRY_AWAIT(lockFileAsync(fd.get(), ltWrite));
        debug("lock acquired on '%1%'", lockPath);
        if (isPathLockValid(fd, lockPath))
            co_return PathLock{std::move(fd), lockPath};
    }
} catch (...) {
    co_return result::current_exception();
}

PathLock lockPath(const Path & path, std::string_view waitMsg, NeverAsync)
{
    return std::move(*PathLock::lockImpl(path, waitMsg, true));
}

std::optional<PathLock> tryLockPath(const Path & path)
{
    return PathLock::lockImpl(path, "", false, always_progresses);
}

static std::optional<PathLocks>
lockPathsImpl(const PathSet & paths, std::string_view waitMsg, bool wait, NeverAsync = {})
{
    PathLocks result;

    /* Acquire the lock for each path in sorted order. This ensures
       that locks are always acquired in the same order, thus
       preventing deadlocks. */
    for (auto & path : paths) {
        if (wait) {
            result.push_back(lockPath(path, waitMsg));
        } else if (auto p = tryLockPath(path); p) {
            result.push_back(std::move(*p));
        } else {
            return std::nullopt;
        }
    }

    return result;
}

PathLocks lockPaths(const PathSet & paths, std::string_view waitMsg, NeverAsync)
{
    return std::move(*lockPathsImpl(paths, waitMsg, true));
}

std::optional<PathLocks> tryLockPaths(const PathSet & paths)
{
    return lockPathsImpl(paths, "", false, always_progresses);
}


PathLock::~PathLock()
{
    try {
        unlock();
    } catch (...) {
        ignoreExceptionInDestructor();
    }
}


void PathLock::unlock()
{
    if (fd) {
        // delete the file. if another file descriptor is used to acquire a lock on
        // this file it will figure out that the file is stale once it calls stat()
        // and inspects the link count. if unlink fails we merely leave around some
        // stale lock file paths that can be reused or cleaned up by other threads.
        (void) sys::unlink(path);
        // clobber file contents for compatibility wither other nix implementations
        writeFull(fd.get(), "d");

        if (close(fd.release()) == -1) {
            printError("error (ignored): cannot close lock file on '%1%'", path);
        }

        debug("lock released on '%1%'", path);
    }
}


FdLock::FdLock(AutoCloseFD & fd, LockType lockType, DontWait)
{
    if (tryLockFile(fd.get(), lockType)) {
        this->fd.reset(&fd);
    }
}

FdLock::FdLock(AutoCloseFD & fd, LockType lockType, std::string_view waitMsg, NeverAsync)
{
    if (!tryLockFile(fd.get(), lockType)) {
        printInfo("%s", Uncolored(waitMsg));
        lockFile(fd.get(), lockType);
        this->fd.reset(&fd);
    }
}

kj::Promise<Result<FdLock>>
FdLock::lockAsync(AutoCloseFD & fd, LockType lockType, std::string_view waitMsg)
try {
    if (!tryLockFile(fd.get(), lockType)) {
        printInfo("%s", Uncolored(waitMsg));
        TRY_AWAIT(lockFileAsyncInner(fd.get(), lockType));
    }
    co_return FdLock{fd};
} catch (...) {
    co_return result::current_exception();
}

}