-
Notifications
You must be signed in to change notification settings - Fork 116
Implement Script Isolation #1803
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
a5c54e5
Add script isolation enforcement
rhysparry 5761616
Test exclusive blocks other exclusive + shared
rhysparry 3abb2cb
Add tests to verify isolation will wait for lock
rhysparry 2b77070
Improve LockOptions validation and logging
rhysparry 1105a97
Don't log error if timeout not specified
rhysparry 8e90250
Enforce filename validation in mutex name
rhysparry 04d1e1a
Remove extraneous Exists check
rhysparry d01a670
Add integration tests for script isolation
rhysparry ebabd6c
More specific IOException handling
rhysparry 68bd278
Add tests that validate timeout
rhysparry 0de995b
Support timeout > 24 hours
rhysparry 8647e7d
Assign test categories
rhysparry a9eb219
Add missing test category
rhysparry 3a7f692
Remove TestCategory across tests to run linux/win
rhysparry 12b00b8
Move ScriptIsolationAsyncIntegrationFixture
rhysparry bf8c894
Revert "Move ScriptIsolationAsyncIntegrationFixture"
rhysparry de4b343
Add missing newline at end of file
rhysparry File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
source/Calamari.Common/Features/Processes/ScriptIsolation/FileLock.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| using System; | ||
| using System.IO; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Calamari.Common.Features.Processes.ScriptIsolation; | ||
|
|
||
| public static class FileLock | ||
| { | ||
| public static ILockHandle Acquire(LockOptions lockOptions) | ||
| { | ||
| var fileShareMode = GetFileShareMode(lockOptions.Type); | ||
| try | ||
| { | ||
| var fileStream = lockOptions.LockFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, fileShareMode); | ||
| return new LockHandle(fileStream); | ||
| } | ||
| catch (IOException e) when (IsFileLocked(e)) | ||
| { | ||
| throw new LockRejectedException(e); | ||
| } | ||
| } | ||
|
|
||
| const int WindowsErrorSharingViolation = unchecked((int)0x80070020); // ERROR_SHARING_VIOLATION | ||
| const int LinuxErrorAgainWouldBlock = 11; // EAGAIN / EWOULDBLOCK | ||
| const int MacOsErrorAgainWouldBlock = 35; // EAGAIN / EWOULDBLOCK | ||
|
|
||
| static bool IsFileLocked(IOException ioException) | ||
| { | ||
| if (OperatingSystem.IsWindows()) | ||
| { | ||
| return ioException.HResult == WindowsErrorSharingViolation; | ||
| } | ||
|
|
||
| if (OperatingSystem.IsLinux()) | ||
| { | ||
| return ioException.HResult == LinuxErrorAgainWouldBlock; | ||
| } | ||
|
|
||
| if (OperatingSystem.IsMacOS()) | ||
| { | ||
| return ioException.HResult == MacOsErrorAgainWouldBlock; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| static FileShare GetFileShareMode(LockType isolationLevel) | ||
| { | ||
| return isolationLevel switch | ||
| { | ||
| LockType.Exclusive => FileShare.None, | ||
| LockType.Shared => FileShare.ReadWrite, | ||
| _ => throw new ArgumentOutOfRangeException(nameof(isolationLevel), isolationLevel, null) | ||
| }; | ||
| } | ||
|
|
||
| sealed class LockHandle(FileStream fileStream) : ILockHandle | ||
| { | ||
| public void Dispose() | ||
| { | ||
| fileStream.Dispose(); | ||
| } | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| await fileStream.DisposeAsync(); | ||
| } | ||
| } | ||
| } | ||
5 changes: 5 additions & 0 deletions
5
source/Calamari.Common/Features/Processes/ScriptIsolation/ILockHandle.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| using System; | ||
|
|
||
| namespace Calamari.Common.Features.Processes.ScriptIsolation; | ||
|
|
||
| public interface ILockHandle : IAsyncDisposable, IDisposable; |
69 changes: 69 additions & 0 deletions
69
source/Calamari.Common/Features/Processes/ScriptIsolation/Isolation.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| using System; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Calamari.Common.Plumbing.Commands; | ||
| using Calamari.Common.Plumbing.Logging; | ||
|
|
||
| namespace Calamari.Common.Features.Processes.ScriptIsolation; | ||
|
|
||
| public static class Isolation | ||
| { | ||
| public static ILockHandle Enforce(CommonOptions.ScriptIsolationOptions scriptIsolationOptions) | ||
| { | ||
| var lockOptions = LockOptions.FromScriptIsolationOptionsOrNull(scriptIsolationOptions); | ||
| if (lockOptions is null) | ||
| { | ||
| return new NoLock(); | ||
| } | ||
|
|
||
| var pipeline = lockOptions.BuildLockAcquisitionPipeline(); | ||
| LogIsolation(lockOptions); | ||
| try | ||
| { | ||
| return pipeline.Execute(FileLock.Acquire, lockOptions); | ||
| } | ||
| catch (Exception exception) | ||
| { | ||
| LockRejectedException.Throw(exception); | ||
| throw; // Satisfy the compiler | ||
| } | ||
| } | ||
|
|
||
| public static async Task<ILockHandle> EnforceAsync( | ||
| CommonOptions.ScriptIsolationOptions scriptIsolationOptions, | ||
| CancellationToken cancellationToken | ||
| ) | ||
| { | ||
| var lockOptions = LockOptions.FromScriptIsolationOptionsOrNull(scriptIsolationOptions); | ||
| if (lockOptions is null) | ||
| { | ||
| return new NoLock(); | ||
| } | ||
|
|
||
| var pipeline = lockOptions.BuildLockAcquisitionPipeline(); | ||
| LogIsolation(lockOptions); | ||
| try | ||
| { | ||
| return await pipeline.ExecuteAsync(static (o, _) => ValueTask.FromResult(FileLock.Acquire(o)), lockOptions, cancellationToken); | ||
| } | ||
| catch (Exception exception) | ||
| { | ||
| LockRejectedException.Throw(exception); | ||
| throw; // Satisfy the compiler | ||
| } | ||
| } | ||
|
|
||
| static void LogIsolation(LockOptions lockOptions) | ||
| { | ||
| Log.Verbose($"Acquiring script isolation mutex {lockOptions.Name} with {lockOptions.Type} lock"); | ||
| } | ||
|
|
||
| class NoLock : ILockHandle | ||
| { | ||
| public ValueTask DisposeAsync() => ValueTask.CompletedTask; | ||
|
|
||
| public void Dispose() | ||
| { | ||
| } | ||
| } | ||
| } |
145 changes: 145 additions & 0 deletions
145
source/Calamari.Common/Features/Processes/ScriptIsolation/LockOptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Threading.Tasks; | ||
| using Calamari.Common.Plumbing.Commands; | ||
| using Calamari.Common.Plumbing.Logging; | ||
| using Polly; | ||
| using Polly.Timeout; | ||
|
|
||
| namespace Calamari.Common.Features.Processes.ScriptIsolation; | ||
|
|
||
| public sealed record LockOptions( | ||
| LockType Type, | ||
| string Name, | ||
| FileInfo LockFile, | ||
| TimeSpan Timeout | ||
| ) | ||
| { | ||
| static readonly TimeSpan RetryInitialDelay = TimeSpan.FromMilliseconds(10); | ||
| static readonly TimeSpan RetryMaxDelay = TimeSpan.FromMilliseconds(500); | ||
|
|
||
| public ResiliencePipeline<ILockHandle> BuildLockAcquisitionPipeline() | ||
| { | ||
| var builder = new ResiliencePipelineBuilder<ILockHandle>(); | ||
| return AddLockOptions(builder).Build(); | ||
| } | ||
|
|
||
| public ResiliencePipelineBuilder<ILockHandle> AddLockOptions(ResiliencePipelineBuilder<ILockHandle> builder) | ||
| { | ||
| // If it's 10ms or less, we'll skip timeout and limit retries | ||
| var retryAttempts = Timeout <= TimeSpan.FromMilliseconds(10) && Timeout != System.Threading.Timeout.InfiniteTimeSpan | ||
| ? 1 | ||
| : int.MaxValue; | ||
| if (Timeout > TimeSpan.FromMilliseconds(10)) | ||
| { | ||
| builder.AddTimeout( | ||
| new TimeoutStrategyOptions | ||
| { | ||
| // Using a timeout generator does not constrain the timeout to | ||
| // a maximum of 1 day | ||
| TimeoutGenerator = _ => ValueTask.FromResult(Timeout) | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| builder.AddRetry( | ||
| new() | ||
| { | ||
| BackoffType = DelayBackoffType.Exponential, | ||
| Delay = RetryInitialDelay, | ||
| MaxDelay = RetryMaxDelay, | ||
| MaxRetryAttempts = retryAttempts, | ||
| ShouldHandle = new PredicateBuilder<ILockHandle>().Handle<LockRejectedException>(), | ||
| UseJitter = true | ||
| } | ||
| ); | ||
| return builder; | ||
| } | ||
|
|
||
| public static LockOptions? FromScriptIsolationOptionsOrNull(CommonOptions.ScriptIsolationOptions options) | ||
| { | ||
| if (!options.FullyConfigured) | ||
| { | ||
| LogIfPartiallyConfigured(options); | ||
| return null; | ||
|
gb-8 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| var lockType = MapScriptIsolationLevelToLockTypeOrNull(options.Level); | ||
| if (lockType == null) | ||
| { | ||
| Log.Verbose($"Failed to map script isolation level '{options.Level}' to a valid LockType. Expected 'FullIsolation' or 'NoIsolation' (case-insensitive)."); | ||
| LogIsolationWillNotBeEnforced(); | ||
| return null; | ||
| } | ||
|
|
||
| TimeSpan timeout; | ||
|
|
||
| if (string.IsNullOrWhiteSpace(options.Timeout)) | ||
| { | ||
| timeout = System.Threading.Timeout.InfiniteTimeSpan; | ||
| } | ||
| else if (!TimeSpan.TryParse(options.Timeout, out timeout)) | ||
| { | ||
| Log.Verbose($"Failed to parse mutex timeout value '{options.Timeout}' as TimeSpan. Defaulting to Infinite."); | ||
| timeout = System.Threading.Timeout.InfiniteTimeSpan; | ||
| } | ||
|
|
||
| var lockFileInfo = GetLockFileInfo(options.TentacleHome, options.MutexName); | ||
| return new LockOptions(lockType.Value, options.MutexName, lockFileInfo, timeout); | ||
| } | ||
|
|
||
| static void LogIfPartiallyConfigured(CommonOptions.ScriptIsolationOptions options) | ||
| { | ||
| if (!options.PartiallyConfigured) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var missingOptions = new List<string>(); | ||
| if (string.IsNullOrWhiteSpace(options.Level)) | ||
| { | ||
| missingOptions.Add("scriptIsolationLevel"); | ||
| } | ||
|
|
||
| if (string.IsNullOrWhiteSpace(options.MutexName)) | ||
| { | ||
| missingOptions.Add("scriptIsolationMutexName"); | ||
| } | ||
|
|
||
| if (string.IsNullOrWhiteSpace(options.TentacleHome)) | ||
| { | ||
| missingOptions.Add("TentacleHome (Environment Variable)"); | ||
| } | ||
|
|
||
| var optionIsOrAre = missingOptions.Count > 1 ? "options are" : "option is"; | ||
| Log.Verbose($"Some script isolation options were provided, but the following required {optionIsOrAre} missing: {string.Join(", ", missingOptions)}"); | ||
| LogIsolationWillNotBeEnforced(); | ||
| } | ||
|
|
||
| static void LogIsolationWillNotBeEnforced() | ||
| { | ||
| Log.Verbose("Script isolation will not be enforced."); | ||
| } | ||
|
|
||
| static FileInfo GetLockFileInfo(string tentacleHome, string mutexName) | ||
| { | ||
| foreach (var invalidChar in Path.GetInvalidFileNameChars()) | ||
| { | ||
| if (mutexName.Contains(invalidChar)) | ||
| { | ||
| throw new ArgumentException($"Invalid mutex name '{mutexName}'."); | ||
| } | ||
| } | ||
|
|
||
| return new FileInfo(Path.Combine(tentacleHome, $"ScriptIsolation.{mutexName}.lock")); | ||
| } | ||
|
|
||
| static LockType? MapScriptIsolationLevelToLockTypeOrNull(string isolationLevel) => | ||
| isolationLevel.ToLowerInvariant() switch | ||
| { | ||
| "fullisolation" => LockType.Exclusive, | ||
| "noisolation" => LockType.Shared, | ||
| _ => null | ||
| }; | ||
| } | ||
30 changes: 30 additions & 0 deletions
30
source/Calamari.Common/Features/Processes/ScriptIsolation/LockRejectedException.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| using System; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using Polly.Timeout; | ||
|
|
||
| namespace Calamari.Common.Features.Processes.ScriptIsolation; | ||
|
|
||
| public sealed class LockRejectedException(string message, Exception? innerException = null) | ||
| : Exception(message, innerException) | ||
| { | ||
| public LockRejectedException(Exception innerException) : this("Lock acquisition failed", innerException) | ||
| { | ||
| } | ||
|
|
||
| [DoesNotReturn] | ||
| public static void Throw(Exception innerException) | ||
| { | ||
| if (innerException is LockRejectedException lockRejectedException) | ||
| { | ||
| throw lockRejectedException; | ||
| } | ||
|
|
||
| if (innerException is TimeoutRejectedException timeoutRejectedException) | ||
| { | ||
| var message = $"Lock acquisition failed after {timeoutRejectedException.Timeout}"; | ||
| throw new LockRejectedException(message, timeoutRejectedException); | ||
| } | ||
|
|
||
| throw new LockRejectedException("Lock acquisition failed", innerException); | ||
| } | ||
| } |
7 changes: 7 additions & 0 deletions
7
source/Calamari.Common/Features/Processes/ScriptIsolation/LockType.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| namespace Calamari.Common.Features.Processes.ScriptIsolation; | ||
|
|
||
| public enum LockType | ||
| { | ||
| Shared, | ||
| Exclusive | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I opted to use a custom enum to map to the appropriate
FileSharevalue used in the underlying lock. This keeps the intended usage clearer.