summaryrefslogtreecommitdiff
path: root/src/util/LockFile.cpp
blob: 2e5bef320e7da6483636f19ca80961c3a0cb2a65 (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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Copyright (C) 2020-2022 Joel Rosdahl and other contributors
//
// See doc/AUTHORS.adoc for a complete list of contributors.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

#include "LockFile.hpp"

#include "Logging.hpp"
#include "Util.hpp"
#include "Win32Util.hpp"
#include "fmtmacros.hpp"

#include <core/exceptions.hpp>
#include <core/wincompat.hpp>
#include <util/file.hpp>

#include "third_party/fmt/core.h"

#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif

#include <algorithm>
#include <random>
#include <sstream>

// Seconds.
const double k_min_sleep_time = 0.010;
const double k_max_sleep_time = 0.050;
#ifndef _WIN32
const util::Duration k_staleness_limit(2);
#endif

namespace {

class RandomNumberGenerator
{
public:
  RandomNumberGenerator(int32_t min, int32_t max)
    : m_random_engine(m_random_device()),
      m_distribution(min, max)
  {
  }

  int32_t
  get()
  {
    return m_distribution(m_random_engine);
  };

private:
  std::random_device m_random_device;
  std::default_random_engine m_random_engine;
  std::uniform_int_distribution<int32_t> m_distribution;
};

} // namespace

namespace util {

LockFile::LockFile(const std::string& path)
  : m_lock_file(path + ".lock"),
#ifndef _WIN32
    m_alive_file(path + ".alive"),
    m_acquired(false)
#else
    m_handle(INVALID_HANDLE_VALUE)
#endif
{
}

LockFile::LockFile(LockFile&& other) noexcept
  : m_lock_file(std::move(other.m_lock_file)),
#ifndef _WIN32
    m_lock_manager(other.m_lock_manager),
    m_alive_file(std::move(other.m_alive_file)),
    m_acquired(other.m_acquired)
#else
    m_handle(other.m_handle)
#endif
{
#ifndef _WIN32
  other.m_lock_manager = nullptr;
  other.m_acquired = false;
#else
  other.m_handle = INVALID_HANDLE_VALUE;
#endif
}

LockFile&
LockFile::operator=(LockFile&& other) noexcept
{
  if (&other != this) {
    m_lock_file = std::move(other.m_lock_file);
#ifndef _WIN32
    m_lock_manager = other.m_lock_manager;
    other.m_lock_manager = nullptr;
    m_alive_file = std::move(other.m_alive_file);
    m_acquired = other.m_acquired;
    other.m_acquired = false;
#else
    m_handle = other.m_handle;
    other.m_handle = INVALID_HANDLE_VALUE;
#endif
  }
  return *this;
}

void
LockFile::make_long_lived(
  [[maybe_unused]] LongLivedLockFileManager& lock_manager)
{
#ifndef _WIN32
  m_lock_manager = &lock_manager;
#endif
}

bool
LockFile::acquire()
{
  LOG("Acquiring {}", m_lock_file);
  return acquire(true);
}

bool
LockFile::try_acquire()
{
  LOG("Trying to acquire {}", m_lock_file);
  return acquire(false);
}

void
LockFile::release()
{
  if (!acquired()) {
    return;
  }

  LOG("Releasing {}", m_lock_file);
#ifndef _WIN32
  if (m_lock_manager) {
    m_lock_manager->deregister_alive_file(m_alive_file);
    Util::unlink_tmp(m_alive_file);
  }
  Util::unlink_tmp(m_lock_file);
#else
  CloseHandle(m_handle);
#endif
  LOG("Released {}", m_lock_file);
#ifndef _WIN32
  m_acquired = false;
#else
  m_handle = INVALID_HANDLE_VALUE;
#endif
}

bool
LockFile::acquired() const
{
#ifndef _WIN32
  return m_acquired;
#else
  return m_handle != INVALID_HANDLE_VALUE;
#endif
}

bool
LockFile::acquire(const bool blocking)
{
  ASSERT(!acquired());

#ifndef _WIN32
  m_acquired = do_acquire(blocking);
#else
  m_handle = do_acquire(blocking);
#endif

  if (acquired()) {
    LOG("Acquired {}", m_lock_file);
#ifndef _WIN32
    if (m_lock_manager) {
      const auto result = util::write_file(m_alive_file, "");
      if (!result) {
        LOG("Failed to write {}: {}", m_alive_file, result.error());
      }
      m_lock_manager->register_alive_file(m_alive_file);
    }
#endif
  } else {
    LOG("Failed to acquire lock {}", m_lock_file);
  }

  return acquired();
}

#ifndef _WIN32

bool
LockFile::do_acquire(const bool blocking)
{
  std::stringstream ss;
  ss << Util::get_hostname() << '-' << getpid() << '-'
     << std::this_thread::get_id();
  const auto content_prefix = ss.str();

  util::TimePoint last_seen_activity = [this] {
    const auto last_lock_update = get_last_lock_update();
    return last_lock_update ? *last_lock_update : util::TimePoint::now();
  }();

  std::string initial_content;
  RandomNumberGenerator sleep_ms_generator(k_min_sleep_time * 1000,
                                           k_max_sleep_time * 1000);

  while (true) {
    const auto now = util::TimePoint::now();
    const auto my_content =
      FMT("{}-{}.{}", content_prefix, now.sec(), now.nsec());

    if (symlink(my_content.c_str(), m_lock_file.c_str()) == 0) {
      // We got the lock.
      return true;
    }

    int saved_errno = errno;
    if (saved_errno == ENOENT) {
      // Directory doesn't exist?
      if (Util::create_dir(Util::dir_name(m_lock_file))) {
        // OK. Retry.
        continue;
      }
    }
    LOG("Could not acquire {}: {}", m_lock_file, strerror(saved_errno));

    if (saved_errno == EPERM) {
      // The file system does not support symbolic links. We have no choice but
      // to grant the lock anyway.
      return true;
    }

    if (saved_errno != EEXIST) {
      // Directory doesn't exist or isn't writable?
      return false;
    }

    std::string content = Util::read_link(m_lock_file);
    if (content.empty()) {
      if (errno == ENOENT) {
        // The symlink was removed after the symlink() call above, so retry
        // acquiring it.
        continue;
      } else {
        LOG("Could not read symlink {}: {}", m_lock_file, strerror(errno));
        return false;
      }
    }

    if (content == my_content) {
      // Lost NFS reply?
      LOG("Symlinking {} failed but we got the lock anyway", m_lock_file);
      return true;
    }

    LOG("Lock info for {}: {}", m_lock_file, content);

    if (initial_content.empty()) {
      initial_content = content;
    }

    const auto last_lock_update = get_last_lock_update();
    if (last_lock_update) {
      last_seen_activity = std::max(last_seen_activity, *last_lock_update);
    }

    const util::Duration inactive_duration =
      util::TimePoint::now() - last_seen_activity;

    if (inactive_duration < k_staleness_limit) {
      LOG("Lock {} held by another process active {}.{:03} seconds ago",
          m_lock_file,
          inactive_duration.sec(),
          inactive_duration.nsec() / 1'000'000);
      if (!blocking) {
        return false;
      }
    } else if (content == initial_content) {
      // The lock seems to be stale -- break it and try again.
      LOG("Breaking {} since it has been inactive for {}.{:03} seconds",
          m_lock_file,
          inactive_duration.sec(),
          inactive_duration.nsec() / 1'000'000);
      if (!Util::unlink_tmp(m_alive_file) || !Util::unlink_tmp(m_lock_file)) {
        return false;
      }

      // Note: There is an inherent race condition here where two processes may
      // believe they both acquired the lock after breaking it:
      //
      // 1. A decides to break the lock.
      // 2. B decides to break the lock.
      // 3. A removes the file and retries.
      // 4. A acquires the lock.
      // 5. B removes the file and retries.
      // 6. B acquires the lock.
      //
      // To reduce the risk we sleep for a while before retrying so that it's
      // likely that step 5 happens before step 4.
    } else {
      LOG("Lock {} reacquired by another process", m_lock_file);
      if (!blocking) {
        return false;
      }
      initial_content = content;
    }

    const std::chrono::milliseconds to_sleep{sleep_ms_generator.get()};
    LOG("Sleeping {} ms", to_sleep.count());
    std::this_thread::sleep_for(to_sleep);
  }
}

std::optional<util::TimePoint>
LockFile::get_last_lock_update()
{
  if (const auto stat = Stat::stat(m_alive_file); stat) {
    return stat.mtime();
  } else {
    return std::nullopt;
  }
}

#else // !_WIN32

void*
LockFile::do_acquire(const bool blocking)
{
  void* handle;
  RandomNumberGenerator sleep_ms_generator(k_min_sleep_time * 1000,
                                           k_max_sleep_time * 1000);

  while (true) {
    DWORD flags = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE;
    handle = CreateFile(m_lock_file.c_str(),
                        GENERIC_WRITE, // desired access
                        0,             // shared mode (0 = not shared)
                        nullptr,       // security attributes
                        CREATE_ALWAYS, // creation disposition
                        flags,         // flags and attributes
                        nullptr        // template file
    );
    if (handle != INVALID_HANDLE_VALUE) {
      break;
    }

    DWORD error = GetLastError();
    if (error == ERROR_PATH_NOT_FOUND) {
      // Directory doesn't exist?
      if (Util::create_dir(Util::dir_name(m_lock_file))) {
        // OK. Retry.
        continue;
      }
    }

    LOG("Could not acquire {}: {} ({})",
        m_lock_file,
        Win32Util::error_message(error),
        error);

    // ERROR_SHARING_VIOLATION: lock already held.
    // ERROR_ACCESS_DENIED: maybe pending delete.
    if (error != ERROR_SHARING_VIOLATION && error != ERROR_ACCESS_DENIED) {
      // Fatal error, give up.
      break;
    }

    LOG("Lock {} held by another process", m_lock_file);
    if (!blocking) {
      break;
    }

    const std::chrono::milliseconds to_sleep{sleep_ms_generator.get()};
    LOG("Sleeping {} ms", to_sleep.count());
    std::this_thread::sleep_for(to_sleep);
  }

  return handle;
}

#endif // !_WIN32

} // namespace util