| | | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Text; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | |
| | | 10 | | namespace Azure.Identity |
| | | 11 | | { |
| | | 12 | | internal class SentinelFileLock : IDisposable |
| | | 13 | | { |
| | | 14 | | private FileStream _lockFileStream; |
| | | 15 | | private const int DefaultFileBufferSize = 4096; |
| | | 16 | | |
| | 0 | 17 | | private SentinelFileLock(FileStream lockFileStream) |
| | | 18 | | { |
| | 0 | 19 | | _lockFileStream = lockFileStream; |
| | 0 | 20 | | } |
| | | 21 | | |
| | | 22 | | public static async Task<SentinelFileLock> AcquireAsync(string lockfilePath, int lockFileRetryCount, TimeSpan lo |
| | | 23 | | { |
| | 0 | 24 | | Exception exception = null; |
| | 0 | 25 | | FileStream fileStream = null; |
| | | 26 | | |
| | | 27 | | // Create lock file dir if it doesn't already exist |
| | 0 | 28 | | Directory.CreateDirectory(Path.GetDirectoryName(lockfilePath)); |
| | | 29 | | |
| | 0 | 30 | | for (int tryCount = 0; tryCount < lockFileRetryCount; tryCount++) |
| | | 31 | | { |
| | | 32 | | try |
| | | 33 | | { |
| | | 34 | | // We are using the file locking to synchronize the store, do not allow multiple writers for the fil |
| | | 35 | | // Note: this only works on windows if we extend to work on unix systems we need to set FileShare.No |
| | 0 | 36 | | fileStream = new FileStream(lockfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Rea |
| | | 37 | | |
| | 0 | 38 | | using (var writer = new StreamWriter(fileStream, Encoding.UTF8, DefaultFileBufferSize, leaveOpen: tr |
| | | 39 | | { |
| | 0 | 40 | | await writer.WriteLineAsync($"{Process.GetCurrentProcess().Id} {Process.GetCurrentProcess().Proc |
| | 0 | 41 | | } |
| | 0 | 42 | | break; |
| | | 43 | | } |
| | 0 | 44 | | catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) |
| | | 45 | | { |
| | 0 | 46 | | exception = ex; |
| | 0 | 47 | | await Task.Delay(lockFileRetryDelay).ConfigureAwait(false); |
| | | 48 | | } |
| | | 49 | | } |
| | | 50 | | |
| | 0 | 51 | | return (fileStream != null) ? new SentinelFileLock(fileStream) : throw new InvalidOperationException("Could |
| | 0 | 52 | | } |
| | | 53 | | |
| | | 54 | | public void Dispose() |
| | | 55 | | { |
| | 0 | 56 | | _lockFileStream?.Dispose(); |
| | 0 | 57 | | _lockFileStream = null; |
| | 0 | 58 | | } |
| | | 59 | | } |
| | | 60 | | } |