KiCad PCB EDA Suite
Loading...
Searching...
No Matches
kigit_lock_retry.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "kigit_lock_retry.h"
21
23
24#include <algorithm>
25#include <cerrno>
26#include <cstdint>
27#include <optional>
28#include <system_error>
29#include <random>
30#include <string>
31#include <thread>
32#include <utility>
33#include <vector>
34
35#ifdef _WIN32
36#include <io.h>
37#include <sys/locking.h>
38#include <sys/stat.h>
39#else
40#include <sys/file.h>
41#include <sys/stat.h>
42#include <unistd.h>
43#endif
44
45#include <fcntl.h>
46
47namespace fs = std::filesystem;
48
49
50namespace
51{
52
53// The base delay before retry aAttempt (0-based), 25, 50, 100, 200, 400, then 800 ms
54std::chrono::milliseconds LockRetryDelay( int aAttempt )
55{
56 return std::chrono::milliseconds( 25 << std::min( std::max( aAttempt, 0 ), 5 ) );
57}
58
61class FILE_LOCK
62{
63public:
64 explicit FILE_LOCK( const fs::path& aTarget ) :
65 m_target( aTarget ),
66 m_lock( aTarget.native() + fs::path( ".lock" ).native() )
67 {
68#ifdef _WIN32
69 m_fd = _wopen( m_lock.c_str(), _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE );
70#else
71 m_fd = open( m_lock.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666 );
72#endif
73
74 if( m_fd < 0 )
75 {
76 m_result = errno == EEXIST ? GIT_ELOCKED : GIT_ERROR;
77 git_error_set_str( m_result == GIT_ELOCKED ? GIT_ERROR_OS : GIT_ERROR_FILESYSTEM,
78 "cannot create the lock file" );
79 }
80 }
81
82 ~FILE_LOCK()
83 {
84 closeFile();
85
86 if( m_result == 0 && !m_committed )
87 {
88 std::error_code ec;
89 fs::remove( m_lock, ec );
90 }
91 }
92
93 FILE_LOCK( const FILE_LOCK& ) = delete;
94 FILE_LOCK& operator=( const FILE_LOCK& ) = delete;
95
97 int Result() const { return m_result; }
98
100 int Commit( const fs::path& aContents )
101 {
102 if( m_result != 0 || m_committed )
103 {
104 git_error_set_str( GIT_ERROR_INVALID, "the lock is not held" );
105 return GIT_ERROR;
106 }
107
108 closeFile();
109
110 std::error_code ec;
111
112 // Two renames, so the target only ever holds the old contents or the whole new ones
113 fs::rename( aContents, m_lock, ec );
114
115 if( !ec )
116 fs::rename( m_lock, m_target, ec );
117
118 // Set as libgit2 would, so a sharing violation on Windows is retried like libgit2's own
119 if( ec )
120 {
121 git_error_set_str( GIT_ERROR_OS, ec.message().c_str() );
122 return GIT_ERROR;
123 }
124
125 m_committed = true;
126 return 0;
127 }
128
129private:
130 void closeFile()
131 {
132 if( m_fd < 0 )
133 return;
134
135#ifdef _WIN32
136 _close( m_fd );
137#else
138 close( m_fd );
139#endif
140
141 m_fd = -1;
142 }
143
144 fs::path m_target;
145 fs::path m_lock;
146 int m_fd = -1;
147 int m_result = 0;
148 bool m_committed = false;
149};
150
151
153std::optional<std::int64_t> mtimeSeconds( const fs::path& aPath )
154{
155#ifdef _WIN32
156 struct _stat64 st;
157
158 if( _wstat64( aPath.c_str(), &st ) != 0 )
159 return std::nullopt;
160#else
161 struct stat st;
162
163 if( stat( aPath.c_str(), &st ) != 0 )
164 return std::nullopt;
165#endif
166
167 return static_cast<std::int64_t>( st.st_mtime );
168}
169
170
173int smudgeRacyEntries( git_index* aIndex, std::int64_t aStamp )
174{
175 std::vector<std::pair<std::string, git_index_entry>> racy;
176
177 for( size_t i = 0; i < git_index_entrycount( aIndex ); ++i )
178 {
179 const git_index_entry* entry = git_index_get_byindex( aIndex, i );
180
181 if( entry && GIT_INDEX_ENTRY_STAGE( entry ) == 0 && entry->mode != GIT_FILEMODE_COMMIT
182 && entry->mtime.seconds >= static_cast<std::int32_t>( aStamp ) )
183 {
184 racy.emplace_back( entry->path, *entry );
185 }
186 }
187
188 for( auto& [path, entry] : racy )
189 {
190 entry.path = path.c_str();
191 entry.file_size = 0;
192
193 // A size of zero alone matches a file emptied in that second
194 entry.mtime.seconds = 0;
195 entry.mtime.nanoseconds = 0;
196
197 if( int rc = git_index_add( aIndex, &entry ) )
198 return rc;
199 }
200
201 return 0;
202}
203
204
206struct SCRATCH_FILE
207{
208 fs::path path;
209
210 ~SCRATCH_FILE()
211 {
212 std::error_code ignored;
213 fs::remove( path, ignored );
214 }
215};
216
217} // namespace
218
219
220namespace KIGIT
221{
222
223int EditIndexLocked( git_repository* aRepo, const std::function<int( git_index* aIndex )>& aEdit )
224{
225 git_index* repoIndex = nullptr;
226
227 if( !aRepo )
228 return GIT_EINVALIDSPEC;
229
230 if( int rc = git_repository_index( &repoIndex, aRepo ) )
231 return rc;
232
233 std::unique_ptr<git_index, decltype( &git_index_free )> repoIndexPtr( repoIndex, &git_index_free );
234 const char* indexPathUtf8 = git_index_path( repoIndex );
235
236 if( !indexPathUtf8 )
237 return GIT_ENOTFOUND;
238
239 const fs::path indexPath( reinterpret_cast<const char8_t*>( indexPathUtf8 ) );
240 int result = 0;
241
242 {
243 FILE_LOCK lock( indexPath );
244
245 if( lock.Result() )
246 return lock.Result();
247
248 SCRATCH_FILE scratch{ indexPath.native() + fs::path( ".kicad-new" ).native() };
249 std::error_code ec;
250 const std::optional<std::int64_t> stamp = mtimeSeconds( indexPath );
251
252 // No index file yet reads as an empty index
253 if( fs::exists( indexPath, ec ) )
254 fs::copy_file( indexPath, scratch.path, fs::copy_options::overwrite_existing, ec );
255
256 if( ec )
257 {
258 git_error_set_str( GIT_ERROR_OS, ec.message().c_str() );
259 return GIT_ERROR;
260 }
261
262 git_index* copy = nullptr;
263 const std::u8string scratchUtf8 = scratch.path.u8string();
264
265 if( int rc = git_index_open( &copy, reinterpret_cast<const char*>( scratchUtf8.c_str() ) ) )
266 return rc;
267
268 std::unique_ptr<git_index, decltype( &git_index_free )> copyPtr( copy, &git_index_free );
269
270 result = aEdit( copy );
271
272 // The new index is stamped later, which would vouch for entries the old one could not
273 if( result == 0 && stamp )
274 result = smudgeRacyEntries( copy, *stamp );
275
276 if( result == 0 )
277 result = git_index_write( copy );
278
279 if( result == 0 )
280 result = lock.Commit( scratch.path );
281 }
282
283 git_index_read( repoIndex, 1 );
284 return result;
285}
286
287
288bool IsLockContention( int aGitError )
289{
290 if( aGitError == GIT_ELOCKED || aGitError == GIT_EMODIFIED )
291 return true;
292
293#ifdef _WIN32
294 // libgit2 clears the thread's Win32 error once it records its own, so the class is all that is left
295 const git_error* error = git_error_last();
296
297 if( aGitError == GIT_ERROR && error && error->klass == GIT_ERROR_OS )
298 return true;
299#endif
300
301 return false;
302}
303
304
305int WithLockRetry( std::chrono::milliseconds aBudget, const std::function<int()>& aOp )
306{
307 using CLOCK = std::chrono::steady_clock;
308
309 thread_local std::minstd_rand jitter( std::random_device{}() );
310
311 CLOCK::time_point deadline = CLOCK::now() + aBudget;
312
313 for( int attempt = 0;; ++attempt )
314 {
315 int result = aOp();
316
317 if( !IsLockContention( result ) )
318 return result;
319
320 std::chrono::milliseconds base = LockRetryDelay( attempt );
321 std::chrono::milliseconds delay = base / 2 + std::chrono::milliseconds( jitter() % ( base.count() + 1 ) );
322
323 if( CLOCK::now() + delay > deadline )
324 return result;
325
326 std::this_thread::sleep_for( delay );
327 }
328}
329
330
331REPO_ACTION_LOCK::REPO_ACTION_LOCK( const fs::path& aCommonDir, const char* aName ) :
332 m_path( aCommonDir / aName )
333{
334}
335
336
337std::unique_ptr<REPO_ACTION_LOCK> RepoActionLock( git_repository* aRepo, const char* aName )
338{
339 const char* commonDir = aRepo ? git_repository_commondir( aRepo ) : nullptr;
340
341 if( !commonDir )
342 return nullptr;
343
344 return std::make_unique<REPO_ACTION_LOCK>( fs::path( reinterpret_cast<const char8_t*>( commonDir ) ), aName );
345}
346
347
352
353
355{
356 if( m_held )
357 return 0;
358
359 m_error.clear();
360
361 if( m_fd < 0 )
362 {
363#ifdef _WIN32
364 m_fd = _wopen( m_path.c_str(), _O_CREAT | _O_RDWR | _O_BINARY | _O_NOINHERIT, _S_IREAD | _S_IWRITE );
365
366 // Another user's lock file may be read only to us, which still locks
367 if( m_fd < 0 )
368 m_fd = _wopen( m_path.c_str(), _O_RDONLY | _O_BINARY | _O_NOINHERIT );
369#else
370 m_fd = open( m_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666 );
371
372 // Another user's lock file may be read only to us, which still locks
373 if( m_fd < 0 )
374 m_fd = open( m_path.c_str(), O_RDONLY | O_CLOEXEC );
375#endif
376
377 if( m_fd < 0 )
378 {
379 m_error = std::generic_category().message( errno );
380 git_error_set_str( GIT_ERROR_FILESYSTEM, ( "cannot create the repository lock file: " + m_error ).c_str() );
381 return GIT_ERROR;
382 }
383 }
384
385#ifdef _WIN32
386 _lseek( m_fd, 0, SEEK_SET );
387 int locked = _locking( m_fd, _LK_NBLCK, 1 );
388 int contended = EACCES;
389#else
390 int locked = flock( m_fd, LOCK_EX | LOCK_NB );
391 int contended = EWOULDBLOCK;
392#endif
393
394 if( locked != 0 )
395 {
396 int error = errno;
397
398 if( error == contended )
399 {
400 git_error_set_str( GIT_ERROR_OS, "another git operation holds the repository" );
401 return GIT_ELOCKED;
402 }
403
404 m_error = std::generic_category().message( error );
405 git_error_set_str( GIT_ERROR_FILESYSTEM, ( "cannot lock the repository lock file: " + m_error ).c_str() );
406 return GIT_ERROR;
407 }
408
409 m_held = true;
410 return 0;
411}
412
413
414int REPO_ACTION_LOCK::Acquire( std::chrono::milliseconds aBudget )
415{
416 return WithLockRetry( aBudget,
417 [this]()
418 {
419 return TryAcquire();
420 } );
421}
422
423
425{
426 if( m_fd < 0 )
427 return;
428
429#ifdef _WIN32
430 if( m_held )
431 {
432 _lseek( m_fd, 0, SEEK_SET );
433 _locking( m_fd, _LK_UNLCK, 1 );
434 }
435
436 _close( m_fd );
437#else
438 close( m_fd );
439#endif
440
441 m_fd = -1;
442 m_held = false;
443}
444
445} // namespace KIGIT
REPO_ACTION_LOCK(const std::filesystem::path &aCommonDir, const char *aName="kicad-action")
aCommonDir is as git_repository_commondir gives it. aName picks an independent lock in that directory...
std::filesystem::path m_path
int TryAcquire()
Try once without waiting. 0 once held, GIT_ELOCKED while another holder has it, GIT_ERROR otherwise.
int Acquire(std::chrono::milliseconds aBudget=BACKEND_LOCK_BUDGET)
TryAcquire again after each contention until it is held, fails otherwise, or aBudget is spent.
std::chrono::steady_clock CLOCK
Retrying short git writes that lost a race with another process.
bool IsLockContention(int aGitError)
True when aGitError says another writer held a lock or moved a ref first.
int EditIndexLocked(git_repository *aRepo, const std::function< int(git_index *aIndex)> &aEdit)
Rewrite aRepo's index the way git does, holding index.lock from a fresh read of the file to the renam...
int WithLockRetry(std::chrono::milliseconds aBudget, const std::function< int()> &aOp)
Run aOp, which returns 0 or a libgit2 error code, again after each lock contention until it succeeds,...
std::unique_ptr< REPO_ACTION_LOCK > RepoActionLock(git_repository *aRepo, const char *aName)
The lock aName in aRepo's common git directory, which every worktree of the repository shares.
std::string path
wxString result
Test unit parsing edge cases and error handling.