KiCad PCB EDA Suite
Loading...
Searching...
No Matches
history_lock.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 <history_lock.h>
21#include <lockfile.h>
22#include <advanced_config.h>
23#include <pgm_base.h>
25#include <wx/filename.h>
26#include <wx/filefn.h>
27#include <wx/ffile.h>
28#include <wx/log.h>
29#include <wx/datetime.h>
30
31#include <git2.h>
32
33#define HISTORY_LOCK_TRACE wxT( "KICAD_HISTORY_LOCK" )
34
35
36static wxString historyPath( const wxString& aProjectPath )
37{
38 return Pgm().GetSettingsManager().GetLocalHistoryDirForPath( aProjectPath );
39}
40
41
42static wxString historyLockPath( const wxString& aProjectPath )
43{
44 // The lock must survive replacement of the history directory during trimming.
45 return historyPath( aProjectPath ) + wxS( ".repo" );
46}
47
48
49HISTORY_LOCK_MANAGER::HISTORY_LOCK_MANAGER( const wxString& aProjectPath, int aStaleTimeoutSec ) :
50 m_projectPath( aProjectPath ),
51 m_historyPath( historyPath( aProjectPath ) ),
52 m_repo( nullptr ),
53 m_index( nullptr ),
54 m_repoOwned( false ),
55 m_indexOwned( false ),
56 m_staleTimeoutSec( aStaleTimeoutSec <= 0 ? ADVANCED_CFG::GetCfg().m_HistoryLockStaleTimeout : aStaleTimeoutSec )
57{
58 wxLogTrace( HISTORY_LOCK_TRACE, "Attempting to acquire lock for project: %s (timeout: %d sec)",
59 aProjectPath, m_staleTimeoutSec );
60
61 // Layer 1: Acquire file-based lock to prevent cross-instance conflicts
62 if( !acquireFileLock() )
63 {
64 wxLogTrace( HISTORY_LOCK_TRACE, "Failed to acquire file lock: %s", m_lockError );
65 return;
66 }
67
68 // Layer 2: Open git repository
69 if( !openRepository() )
70 {
71 wxLogTrace( HISTORY_LOCK_TRACE, "Failed to open repository: %s", m_lockError );
72 return;
73 }
74
75 // Layer 3: Acquire git index lock for fine-grained operation safety
76 if( !acquireIndexLock() )
77 {
78 wxLogTrace( HISTORY_LOCK_TRACE, "Failed to acquire index lock: %s", m_lockError );
79 return;
80 }
81
82 wxLogTrace( HISTORY_LOCK_TRACE, "Successfully acquired all locks for project: %s", aProjectPath );
83}
84
85
87{
88 wxLogTrace( HISTORY_LOCK_TRACE, "Releasing locks for project: %s", m_projectPath );
89
90 // Release in reverse order of acquisition
91 if( m_indexOwned && m_index )
92 {
93 git_index_free( m_index );
94 m_index = nullptr;
95 }
96
97 if( m_repoOwned && m_repo )
98 {
99 git_repository_free( m_repo );
100 m_repo = nullptr;
101 }
102
103 // m_fileLock automatically releases via RAII destructor
104}
105
106
108{
109 return m_fileLock && m_fileLock->Locked() && m_repo && m_index;
110}
111
112
114{
115 return m_lockError;
116}
117
118
120{
121 if( m_fileLock && !m_fileLock->Locked() )
122 {
123 return wxString::Format( wxS( "%s@%s" ),
124 m_fileLock->GetUsername(),
125 m_fileLock->GetHostname() );
126 }
127 return wxEmptyString;
128}
129
130
132{
133 // Ensure history directory exists
134 if( !wxDirExists( m_historyPath ) )
135 {
136 wxLogNull suppressSysErrorPopups;
137
138 if( !wxFileName::Mkdir( m_historyPath, 0777, wxPATH_MKDIR_FULL ) )
139 {
140 m_lockError = wxString::Format(
141 _( "Cannot create history directory: %s" ), m_historyPath );
142 return false;
143 }
144 }
145
146 m_fileLock = std::make_unique<LOCKFILE>( historyLockPath( m_projectPath ), true );
147
148 if( !m_fileLock->Locked() )
149 {
150 m_lockError = wxString::Format(
151 _( "History repository is locked by %s@%s" ),
152 m_fileLock->GetUsername(),
153 m_fileLock->GetHostname() );
154 return false;
155 }
156
157 LOCKFILE legacyLock = LOCKFILE::Inspect( wxFileName( m_historyPath, wxS( ".repo" ) ).GetFullPath() );
158
159 if( !legacyLock.Valid() )
160 {
161 m_lockError = _( "History repository is locked by an older KiCad instance." );
162 return false;
163 }
164
165 return true;
166}
167
168
170{
171 if( !wxDirExists( m_historyPath ) )
172 {
173 m_lockError = wxString::Format(
174 _( "History directory does not exist: %s" ), m_historyPath );
175 return false;
176 }
177
178 // Attempt to open existing repository
179 int rc = git_repository_open( &m_repo, m_historyPath.mb_str().data() );
180
181 if( rc != 0 )
182 {
183 const git_error* err = git_error_last();
184 m_lockError = wxString::Format(
185 _( "Failed to open git repository: %s" ),
186 err ? wxString::FromUTF8( err->message ) : wxString( "Unknown error" ) );
187 return false;
188 }
189
190 // Attempt to set workdir
191 rc = git_repository_set_workdir( m_repo, m_projectPath.mb_str().data(), false );
192
193 if( rc != 0 )
194 {
195 const git_error* err = git_error_last();
196 m_lockError = wxString::Format( _( "Failed to set git repository workdir to %s: %s" ), m_projectPath,
197 err ? wxString::FromUTF8( err->message ) : wxString( "Unknown error" ) );
198 return false;
199 }
200
201 // libgit2 will not read .history/.gitignore on its own (it sits outside the workdir).
202 // Inject its rules so users can edit that file and have them honoured.
203 wxFileName ignoreFile( m_historyPath, wxS( ".gitignore" ) );
204
205 if( ignoreFile.FileExists() )
206 {
207 wxFFile f( ignoreFile.GetFullPath(), wxT( "rb" ) );
208 wxString content;
209
210 if( f.IsOpened() && f.ReadAll( &content ) )
211 git_ignore_add_rule( m_repo, content.utf8_str() );
212 }
213
214 m_repoOwned = true;
215 return true;
216}
217
218
220{
221 if( !m_repo )
222 {
223 m_lockError = _( "Cannot acquire index lock: repository not open" );
224 return false;
225 }
226
227 // git_repository_index will fail if another process has .git/index.lock
228 int rc = git_repository_index( &m_index, m_repo );
229
230 if( rc != 0 )
231 {
232 const git_error* err = git_error_last();
233 m_lockError = wxString::Format(
234 _( "Failed to acquire git index lock (another operation in progress?): %s" ),
235 err ? wxString::FromUTF8( err->message ) : wxString( "Unknown error" ) );
236 return false;
237 }
238
239 m_indexOwned = true;
240 return true;
241}
242
243
244bool HISTORY_LOCK_MANAGER::IsLockStale( const wxString& aProjectPath, int aStaleTimeoutSec )
245{
246 // Use config value if not explicitly specified
247 if( aStaleTimeoutSec <= 0 )
249
250 wxFileName lockPath( LOCKFILE::LockPathFor( historyLockPath( aProjectPath ) ) );
251
252 if( !lockPath.FileExists() )
253 return false; // No lock file exists
254
255 wxDateTime modTime;
256 if( !lockPath.GetTimes( nullptr, &modTime, nullptr ) )
257 return false; // Can't determine age
258
259 wxDateTime now = wxDateTime::Now();
260 wxTimeSpan age = now - modTime;
261
262 wxLogTrace( HISTORY_LOCK_TRACE, "Lock file age: %d seconds (stale threshold: %d)",
263 (int)age.GetSeconds().ToLong(), aStaleTimeoutSec );
264
265 return age.GetSeconds().ToLong() > aStaleTimeoutSec
266 && LOCKFILE::Inspect( historyLockPath( aProjectPath ) ).Valid();
267}
268
269
270bool HISTORY_LOCK_MANAGER::BreakStaleLock( const wxString& aProjectPath )
271{
272 // Claim the abandoned lock before removing it, so a concurrent owner cannot be unlinked.
273 LOCKFILE lock( historyLockPath( aProjectPath ), true );
274 return lock.Locked();
275}
276
277
279{
280 if( m_indexOwned && m_index )
281 {
282 git_index_free( m_index );
283 m_index = nullptr;
284 m_indexOwned = false;
285 }
286
287 if( m_repoOwned && m_repo )
288 {
289 git_repository_free( m_repo );
290 m_repo = nullptr;
291 m_repoOwned = false;
292 }
293}
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
wxString GetLockHolder() const
Get information about who currently holds the lock.
HISTORY_LOCK_MANAGER(const wxString &aProjectPath, int aStaleTimeoutSec=0)
Construct a lock manager and attempt to acquire locks.
void ReleaseRepository()
Release git repository and index handles early, but keep the file lock.
~HISTORY_LOCK_MANAGER()
Destructor releases all locks and closes git repository.
wxString GetLockError() const
Get error message describing why lock could not be acquired.
git_repository * m_repo
static bool BreakStaleLock(const wxString &aProjectPath)
Claim and remove an abandoned lock belonging to this user.
std::unique_ptr< LOCKFILE > m_fileLock
static bool IsLockStale(const wxString &aProjectPath, int aStaleTimeoutSec=0)
Check if a lock file exists and is stale (older than timeout).
bool IsLocked() const
Check if locks were successfully acquired.
Advisory lock over a file, taken by writing a sibling lock file and holding an exclusive lock on it f...
Definition lockfile.h:60
static wxString LockPathFor(const wxString &aFilename)
Definition lockfile.h:140
bool Valid() const
Definition lockfile.h:233
bool Locked() const
Definition lockfile.h:228
static LOCKFILE Inspect(const wxString &aFilename)
Look at a lock without taking it: nothing is created, nothing is claimed and nothing is removed on re...
Definition lockfile.h:119
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:123
wxString GetLocalHistoryDirForPath(const wxString &aProjectPath) const
Resolve the local-history directory for a project given by its on-disk path.
#define _(s)
int m_HistoryLockStaleTimeout
Stale lock timeout for local history repository locks, in seconds.
static wxString historyPath(const wxString &aProjectPath)
static wxString historyLockPath(const wxString &aProjectPath)
#define HISTORY_LOCK_TRACE
File locking utilities.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE