| 1 | package locking |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/git-lfs/git-lfs/v3/config" |
| 13 | "github.com/git-lfs/git-lfs/v3/errors" |
| 14 | "github.com/git-lfs/git-lfs/v3/filepathfilter" |
| 15 | "github.com/git-lfs/git-lfs/v3/git" |
| 16 | "github.com/git-lfs/git-lfs/v3/lfsapi" |
| 17 | "github.com/git-lfs/git-lfs/v3/tools" |
| 18 | "github.com/git-lfs/git-lfs/v3/tools/kv" |
| 19 | "github.com/git-lfs/git-lfs/v3/tr" |
| 20 | "github.com/rubyist/tracerx" |
| 21 | ) |
| 22 | |
| 23 | var ( |
| 24 | // ErrNoMatchingLocks is an error returned when no matching locks were |
| 25 | // able to be resolved |
| 26 | ErrNoMatchingLocks = errors.New(tr.Tr.Get("no matching locks found")) |
| 27 | // ErrLockAmbiguous is an error returned when multiple matching locks |
| 28 | // were found |
| 29 | ErrLockAmbiguous = errors.New(tr.Tr.Get("multiple locks found; ambiguous")) |
| 30 | ) |
| 31 | |
| 32 | type LockCacher interface { |
| 33 | Add(l Lock) error |
| 34 | RemoveByPath(filePath string) error |
| 35 | RemoveById(id string) error |
| 36 | Locks() []Lock |
| 37 | Clear() |
| 38 | Save() error |
| 39 | } |
| 40 | |
| 41 | // Client is the main interface object for the locking package |
| 42 | type Client struct { |
| 43 | Remote string |
| 44 | RemoteRef *git.Ref |
| 45 | client lockClient |
| 46 | cache LockCacher |
| 47 | cacheDir string |
| 48 | cfg *config.Configuration |
| 49 | |
| 50 | lockablePatterns []string |
| 51 | lockableFilter *filepathfilter.Filter |
| 52 | lockableMutex sync.Mutex |
| 53 | |
| 54 | LocalWorkingDir string |
| 55 | LocalGitDir string |
| 56 | SetLockableFilesReadOnly bool |
| 57 | ModifyIgnoredFiles bool |
| 58 | } |
| 59 | |
| 60 | // NewClient creates a new locking client with the given configuration |
| 61 | // You must call the returned object's `Close` method when you are finished with |
| 62 | // it |
| 63 | func NewClient(remote string, lfsClient *lfsapi.Client, cfg *config.Configuration) *Client { |
| 64 | return &Client{ |
| 65 | Remote: remote, |
| 66 | client: newGenericLockClient(lfsClient), |
| 67 | cache: &nilLockCacher{}, |
| 68 | cfg: cfg, |
| 69 | ModifyIgnoredFiles: lfsClient.GitEnv().Bool("lfs.lockignoredfiles", false), |
| 70 | LocalWorkingDir: cfg.LocalWorkingDir(), |
| 71 | LocalGitDir: cfg.LocalGitDir(), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | func (c *Client) SetupFileCache(path string) error { |
| 76 | stat, err := os.Stat(path) |
| 77 | if err != nil { |
| 78 | return errors.Wrap(err, tr.Tr.Get("lock cache initialization")) |
| 79 | } |
| 80 | |
| 81 | lockFile := path |
| 82 | if stat.IsDir() { |
| 83 | lockFile = filepath.Join(path, "lockcache.db") |
| 84 | } |
| 85 | |
| 86 | cache, err := NewLockCache(lockFile) |
| 87 | if err != nil { |
| 88 | return errors.Wrap(err, tr.Tr.Get("lock cache initialization")) |
| 89 | } |
| 90 | |
| 91 | c.cache = cache |
| 92 | c.cacheDir = filepath.Join(path, "cache") |
| 93 | return nil |
| 94 | } |
| 95 | |
| 96 | // Close this client instance; must be called to dispose of resources |
| 97 | func (c *Client) Close() error { |
| 98 | return c.cache.Save() |
| 99 | } |
| 100 | |
| 101 | // LockFile attempts to lock a file on the current remote |
| 102 | // path must be relative to the root of the repository |
| 103 | // Returns the lock id if successful, or an error |
| 104 | func (c *Client) LockFile(path string) (Lock, error) { |
| 105 | lockRes, _, err := c.client.Lock(c.Remote, &lockRequest{ |
| 106 | Path: path, |
| 107 | Ref: &lockRef{Name: c.RemoteRef.Refspec()}, |
| 108 | }) |
| 109 | if err != nil { |
| 110 | return Lock{}, errors.Wrap(err, tr.Tr.Get("locking API")) |
| 111 | } |
| 112 | |
| 113 | if len(lockRes.Message) > 0 { |
| 114 | if len(lockRes.RequestID) > 0 { |
| 115 | tracerx.Printf("Server Request ID: %s", lockRes.RequestID) |
| 116 | } |
| 117 | return Lock{}, errors.New(tr.Tr.Get("server unable to create lock: %s", lockRes.Message)) |
| 118 | } |
| 119 | |
| 120 | lock := *lockRes.Lock |
| 121 | if err := c.cache.Add(lock); err != nil { |
| 122 | return Lock{}, errors.Wrap(err, tr.Tr.Get("lock cache")) |
| 123 | } |
| 124 | |
| 125 | abs, err := c.getAbsolutePath(path) |
| 126 | if err != nil { |
| 127 | return Lock{}, errors.Wrap(err, tr.Tr.Get("make lock path absolute")) |
| 128 | } |
| 129 | |
| 130 | // If the file exists, ensure that it's writeable on return |
| 131 | if tools.FileExists(abs) { |
| 132 | if err := tools.SetFileWriteFlag(abs, true); err != nil { |
| 133 | return Lock{}, errors.Wrap(err, tr.Tr.Get("set file write flag")) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | return lock, nil |
| 138 | } |
| 139 | |
| 140 | // getAbsolutePath takes a repository-relative path and makes it absolute. |
| 141 | // |
| 142 | // For instance, given a repository in /usr/local/src/my-repo and a file called |
| 143 | // dir/foo/bar.txt, getAbsolutePath will return: |
| 144 | // |
| 145 | // /usr/local/src/my-repo/dir/foo/bar.txt |
| 146 | func (c *Client) getAbsolutePath(p string) (string, error) { |
| 147 | return filepath.Join(c.LocalWorkingDir, p), nil |
| 148 | } |
| 149 | |
| 150 | // UnlockFile attempts to unlock a file on the current remote |
| 151 | // path must be relative to the root of the repository |
| 152 | // Force causes the file to be unlocked from other users as well |
| 153 | func (c *Client) UnlockFile(path string, force bool) error { |
| 154 | id, err := c.lockIdFromPath(path) |
| 155 | if err != nil { |
| 156 | return errors.New(tr.Tr.Get("unable to get lock ID: %v", err)) |
| 157 | } |
| 158 | |
| 159 | return c.UnlockFileById(id, force) |
| 160 | } |
| 161 | |
| 162 | // UnlockFileById attempts to unlock a lock with a given id on the current remote |
| 163 | // Force causes the file to be unlocked from other users as well |
| 164 | func (c *Client) UnlockFileById(id string, force bool) error { |
| 165 | unlockRes, _, err := c.client.Unlock(c.RemoteRef, c.Remote, id, force) |
| 166 | if err != nil { |
| 167 | return errors.Wrap(err, tr.Tr.Get("locking API")) |
| 168 | } |
| 169 | |
| 170 | if len(unlockRes.Message) > 0 { |
| 171 | if len(unlockRes.RequestID) > 0 { |
| 172 | tracerx.Printf("Server Request ID: %s", unlockRes.RequestID) |
| 173 | } |
| 174 | return errors.New(tr.Tr.Get("server unable to unlock: %s", unlockRes.Message)) |
| 175 | } |
| 176 | |
| 177 | if err := c.cache.RemoveById(id); err != nil { |
| 178 | return errors.New(tr.Tr.Get("error caching unlock information: %v", err)) |
| 179 | } |
| 180 | |
| 181 | if unlockRes.Lock != nil { |
| 182 | abs, err := c.getAbsolutePath(unlockRes.Lock.Path) |
| 183 | if err != nil { |
| 184 | return errors.Wrap(err, tr.Tr.Get("make lock path absolute")) |
| 185 | } |
| 186 | |
| 187 | // Make non-writeable if required |
| 188 | if c.SetLockableFilesReadOnly && c.IsFileLockable(unlockRes.Lock.Path) && tools.FileExists(abs) { |
| 189 | return tools.SetFileWriteFlag(abs, false) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | return nil |
| 194 | } |
| 195 | |
| 196 | // Lock is a record of a locked file |
| 197 | type Lock struct { |
| 198 | // Id is the unique identifier corresponding to this particular Lock. It |
| 199 | // must be consistent with the local copy, and the server's copy. |
| 200 | Id string `json:"id"` |
| 201 | // Path is an absolute path to the file that is locked as a part of this |
| 202 | // lock. |
| 203 | Path string `json:"path"` |
| 204 | // Owner is the identity of the user that created this lock. |
| 205 | Owner *User `json:"owner,omitempty"` |
| 206 | // LockedAt is the time at which this lock was acquired. |
| 207 | LockedAt time.Time `json:"locked_at"` |
| 208 | } |
| 209 | |
| 210 | // SearchLocks returns a channel of locks which match the given name/value filter |
| 211 | // If limit > 0 then search stops at that number of locks |
| 212 | // If localOnly = true, don't query the server & report only own local locks |
| 213 | func (c *Client) SearchLocks(filter map[string]string, limit int, localOnly bool, cached bool) ([]Lock, error) { |
| 214 | if localOnly { |
| 215 | return c.searchLocalLocks(filter, limit) |
| 216 | } else if cached { |
| 217 | if len(filter) > 0 || limit != 0 { |
| 218 | return []Lock{}, errors.New(tr.Tr.Get("can't search cached locks when filter or limit is set")) |
| 219 | } |
| 220 | |
| 221 | locks := []Lock{} |
| 222 | err := c.readLocksFromCacheFile("remote", func(decoder *json.Decoder) error { |
| 223 | return decoder.Decode(&locks) |
| 224 | }) |
| 225 | return locks, err |
| 226 | } else { |
| 227 | locks, err := c.searchRemoteLocks(filter, limit) |
| 228 | if err != nil { |
| 229 | return locks, err |
| 230 | } |
| 231 | |
| 232 | if len(filter) == 0 && limit == 0 { |
| 233 | err = c.writeLocksToCacheFile("remote", func(writer io.Writer) error { |
| 234 | return c.EncodeLocks(locks, writer) |
| 235 | }) |
| 236 | } |
| 237 | |
| 238 | return locks, err |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | func (c *Client) SearchLocksVerifiable(limit int, cached bool) (ourLocks, theirLocks []Lock, err error) { |
| 243 | ourLocks = make([]Lock, 0, limit) |
| 244 | theirLocks = make([]Lock, 0, limit) |
| 245 | |
| 246 | if cached { |
| 247 | if limit != 0 { |
| 248 | return []Lock{}, []Lock{}, errors.New(tr.Tr.Get("can't search cached locks when limit is set")) |
| 249 | } |
| 250 | |
| 251 | locks := &lockVerifiableList{} |
| 252 | err := c.readLocksFromCacheFile("verifiable", func(decoder *json.Decoder) error { |
| 253 | return decoder.Decode(&locks) |
| 254 | }) |
| 255 | return locks.Ours, locks.Theirs, err |
| 256 | } else { |
| 257 | var requestRef *lockRef |
| 258 | if c.RemoteRef != nil { |
| 259 | requestRef = &lockRef{Name: c.RemoteRef.Refspec()} |
| 260 | } |
| 261 | |
| 262 | body := &lockVerifiableRequest{ |
| 263 | Ref: requestRef, |
| 264 | Limit: limit, |
| 265 | } |
| 266 | |
| 267 | c.cache.Clear() |
| 268 | |
| 269 | for { |
| 270 | list, status, err := c.client.SearchVerifiable(c.Remote, body) |
| 271 | switch status { |
| 272 | case http.StatusNotFound, http.StatusNotImplemented: |
| 273 | return ourLocks, theirLocks, errors.NewNotImplementedError(err) |
| 274 | case http.StatusForbidden: |
| 275 | return ourLocks, theirLocks, errors.NewAuthError(err) |
| 276 | } |
| 277 | |
| 278 | if err != nil { |
| 279 | return ourLocks, theirLocks, err |
| 280 | } |
| 281 | |
| 282 | if list.Message != "" { |
| 283 | if len(list.RequestID) > 0 { |
| 284 | tracerx.Printf("Server Request ID: %s", list.RequestID) |
| 285 | } |
| 286 | return ourLocks, theirLocks, errors.New(tr.Tr.Get("server error searching locks: %s", list.Message)) |
| 287 | } |
| 288 | |
| 289 | for _, l := range list.Ours { |
| 290 | c.cache.Add(l) |
| 291 | ourLocks = append(ourLocks, l) |
| 292 | if limit > 0 && (len(ourLocks)+len(theirLocks)) >= limit { |
| 293 | return ourLocks, theirLocks, nil |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | for _, l := range list.Theirs { |
| 298 | c.cache.Add(l) |
| 299 | theirLocks = append(theirLocks, l) |
| 300 | if limit > 0 && (len(ourLocks)+len(theirLocks)) >= limit { |
| 301 | return ourLocks, theirLocks, nil |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | if list.NextCursor != "" { |
| 306 | body.Cursor = list.NextCursor |
| 307 | } else { |
| 308 | break |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | if limit == 0 { |
| 313 | err = c.writeLocksToCacheFile("verifiable", func(writer io.Writer) error { |
| 314 | return c.EncodeLocksVerifiable(ourLocks, theirLocks, writer) |
| 315 | }) |
| 316 | } |
| 317 | |
| 318 | return ourLocks, theirLocks, err |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | func (c *Client) searchLocalLocks(filter map[string]string, limit int) ([]Lock, error) { |
| 323 | cachedlocks := c.cache.Locks() |
| 324 | path, filterByPath := filter["path"] |
| 325 | id, filterById := filter["id"] |
| 326 | lockCount := 0 |
| 327 | locks := make([]Lock, 0, len(cachedlocks)) |
| 328 | for _, l := range cachedlocks { |
| 329 | // Manually filter by Path/Id |
| 330 | if (filterByPath && path != l.Path) || |
| 331 | (filterById && id != l.Id) { |
| 332 | continue |
| 333 | } |
| 334 | locks = append(locks, l) |
| 335 | lockCount++ |
| 336 | if limit > 0 && lockCount >= limit { |
| 337 | break |
| 338 | } |
| 339 | } |
| 340 | return locks, nil |
| 341 | } |
| 342 | |
| 343 | func (c *Client) searchRemoteLocks(filter map[string]string, limit int) ([]Lock, error) { |
| 344 | locks := make([]Lock, 0, limit) |
| 345 | |
| 346 | apifilters := make([]lockFilter, 0, len(filter)) |
| 347 | for k, v := range filter { |
| 348 | apifilters = append(apifilters, lockFilter{Property: k, Value: v}) |
| 349 | } |
| 350 | |
| 351 | query := &lockSearchRequest{ |
| 352 | Filters: apifilters, |
| 353 | Limit: limit, |
| 354 | Refspec: c.RemoteRef.Refspec(), |
| 355 | } |
| 356 | |
| 357 | for { |
| 358 | list, _, err := c.client.Search(c.Remote, query) |
| 359 | if err != nil { |
| 360 | return locks, errors.Wrap(err, tr.Tr.Get("locking")) |
| 361 | } |
| 362 | |
| 363 | if list.Message != "" { |
| 364 | if len(list.RequestID) > 0 { |
| 365 | tracerx.Printf("Server Request ID: %s", list.RequestID) |
| 366 | } |
| 367 | return locks, errors.New(tr.Tr.Get("server error searching for locks: %s", list.Message)) |
| 368 | } |
| 369 | |
| 370 | for _, l := range list.Locks { |
| 371 | locks = append(locks, l) |
| 372 | if limit > 0 && len(locks) >= limit { |
| 373 | // Exit outer loop too |
| 374 | return locks, nil |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | if list.NextCursor != "" { |
| 379 | query.Cursor = list.NextCursor |
| 380 | } else { |
| 381 | break |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | return locks, nil |
| 386 | } |
| 387 | |
| 388 | // lockIdFromPath makes a call to the LFS API and resolves the ID for the locked |
| 389 | // locked at the given path. |
| 390 | // |
| 391 | // If the API call failed, an error will be returned. If multiple locks matched |
| 392 | // the given path (should not happen during real-world usage), an error will be |
| 393 | // returned. If no locks matched the given path, an error will be returned. |
| 394 | // |
| 395 | // If the API call is successful, and only one lock matches the given filepath, |
| 396 | // then its ID will be returned, along with a value of "nil" for the error. |
| 397 | func (c *Client) lockIdFromPath(path string) (string, error) { |
| 398 | list, _, err := c.client.Search(c.Remote, &lockSearchRequest{ |
| 399 | Filters: []lockFilter{ |
| 400 | {Property: "path", Value: path}, |
| 401 | }, |
| 402 | Refspec: c.RemoteRef.Refspec(), |
| 403 | }) |
| 404 | |
| 405 | if err != nil { |
| 406 | return "", err |
| 407 | } |
| 408 | |
| 409 | switch len(list.Locks) { |
| 410 | case 0: |
| 411 | return "", ErrNoMatchingLocks |
| 412 | case 1: |
| 413 | return list.Locks[0].Id, nil |
| 414 | default: |
| 415 | return "", ErrLockAmbiguous |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // IsFileLockedByCurrentCommitter returns whether a file is locked by the |
| 420 | // current user, as cached locally |
| 421 | func (c *Client) IsFileLockedByCurrentCommitter(path string) bool { |
| 422 | filter := map[string]string{"path": path} |
| 423 | locks, err := c.searchLocalLocks(filter, 1) |
| 424 | if err != nil { |
| 425 | tracerx.Printf("Error searching cached locks: %s\nForcing remote search", err) |
| 426 | locks, _ = c.searchRemoteLocks(filter, 1) |
| 427 | } |
| 428 | return len(locks) > 0 |
| 429 | } |
| 430 | |
| 431 | func init() { |
| 432 | kv.RegisterTypeForStorage(&Lock{}) |
| 433 | } |
| 434 | |
| 435 | func (c *Client) prepareCacheDirectory(kind string) (string, error) { |
| 436 | cacheDir := filepath.Join(c.cacheDir, "locks") |
| 437 | if c.RemoteRef != nil { |
| 438 | cacheDir = filepath.Join(cacheDir, c.RemoteRef.Refspec()) |
| 439 | } |
| 440 | |
| 441 | stat, err := os.Stat(cacheDir) |
| 442 | if err == nil { |
| 443 | if !stat.IsDir() { |
| 444 | return cacheDir, errors.New(tr.Tr.Get("inititalization of cache directory %s failed: already exists, but is no directory", cacheDir)) |
| 445 | } |
| 446 | } else if os.IsNotExist(err) { |
| 447 | err = tools.MkdirAll(cacheDir, c.cfg) |
| 448 | if err != nil { |
| 449 | return cacheDir, errors.Wrap(err, tr.Tr.Get("initiailization of cache directory %s failed: directory creation failed", cacheDir)) |
| 450 | } |
| 451 | } else { |
| 452 | return cacheDir, errors.Wrap(err, tr.Tr.Get("initialization of cache directory %s failed", cacheDir)) |
| 453 | } |
| 454 | |
| 455 | return filepath.Join(cacheDir, kind), nil |
| 456 | } |
| 457 | |
| 458 | func (c *Client) readLocksFromCacheFile(kind string, decoder func(*json.Decoder) error) error { |
| 459 | cacheFile, err := c.prepareCacheDirectory(kind) |
| 460 | if err != nil { |
| 461 | return err |
| 462 | } |
| 463 | |
| 464 | _, err = os.Stat(cacheFile) |
| 465 | if err != nil { |
| 466 | if os.IsNotExist(err) { |
| 467 | return errors.New(tr.Tr.Get("no cached locks present")) |
| 468 | } |
| 469 | |
| 470 | return err |
| 471 | } |
| 472 | |
| 473 | file, err := os.Open(cacheFile) |
| 474 | if err != nil { |
| 475 | return err |
| 476 | } |
| 477 | |
| 478 | defer file.Close() |
| 479 | return decoder(json.NewDecoder(file)) |
| 480 | } |
| 481 | |
| 482 | func (c *Client) EncodeLocks(locks []Lock, writer io.Writer) error { |
| 483 | return json.NewEncoder(writer).Encode(locks) |
| 484 | } |
| 485 | |
| 486 | func (c *Client) EncodeLocksVerifiable(ourLocks, theirLocks []Lock, writer io.Writer) error { |
| 487 | return json.NewEncoder(writer).Encode(&lockVerifiableList{ |
| 488 | Ours: ourLocks, |
| 489 | Theirs: theirLocks, |
| 490 | }) |
| 491 | } |
| 492 | |
| 493 | func (c *Client) writeLocksToCacheFile(kind string, writer func(io.Writer) error) error { |
| 494 | cacheFile, err := c.prepareCacheDirectory(kind) |
| 495 | if err != nil { |
| 496 | return err |
| 497 | } |
| 498 | |
| 499 | file, err := os.Create(cacheFile) |
| 500 | if err != nil { |
| 501 | return err |
| 502 | } |
| 503 | |
| 504 | defer file.Close() |
| 505 | return writer(file) |
| 506 | } |
| 507 | |
| 508 | type nilLockCacher struct{} |
| 509 | |
| 510 | func (c *nilLockCacher) Add(l Lock) error { |
| 511 | return nil |
| 512 | } |
| 513 | func (c *nilLockCacher) RemoveByPath(filePath string) error { |
| 514 | return nil |
| 515 | } |
| 516 | func (c *nilLockCacher) RemoveById(id string) error { |
| 517 | return nil |
| 518 | } |
| 519 | func (c *nilLockCacher) Locks() []Lock { |
| 520 | return nil |
| 521 | } |
| 522 | func (c *nilLockCacher) Clear() {} |
| 523 | func (c *nilLockCacher) Save() error { |
| 524 | return nil |
| 525 | } |