-
Notifications
You must be signed in to change notification settings - Fork 833
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
Change default cookie session affinity format #1989
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
193d823
Add hash based cookie session affinity #1980
Tratcher 476c50e
Typo
Tratcher 4710ceb
PR feedback
Tratcher e568807
Add XxHash64 cookie
Tratcher 129cfb1
Update src/ReverseProxy/SessionAffinity/BaseHashCookieSessionAffinity…
Tratcher 1be5196
Apply suggestions from code review
Tratcher 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 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 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 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 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 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,27 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
using System; | ||
using Microsoft.AspNetCore.Http; | ||
using Yarp.ReverseProxy.Configuration; | ||
using Yarp.ReverseProxy.Utilities; | ||
|
||
namespace Yarp.ReverseProxy.SessionAffinity; | ||
|
||
internal static class AffinityHelpers | ||
{ | ||
internal static CookieOptions CreateCookieOptions(SessionAffinityCookieConfig? config, bool isHttps, IClock clock) | ||
{ | ||
return new CookieOptions | ||
{ | ||
Path = config?.Path ?? "/", | ||
SameSite = config?.SameSite ?? SameSiteMode.Unspecified, | ||
HttpOnly = config?.HttpOnly ?? true, | ||
MaxAge = config?.MaxAge, | ||
Domain = config?.Domain, | ||
IsEssential = config?.IsEssential ?? false, | ||
Secure = config?.SecurePolicy == CookieSecurePolicy.Always || (config?.SecurePolicy == CookieSecurePolicy.SameAsRequest && isHttps), | ||
Expires = config?.Expiration is not null ? clock.GetUtcNow().Add(config.Expiration.Value) : default(DateTimeOffset?), | ||
}; | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
src/ReverseProxy/SessionAffinity/ArrCookieSessionAffinityPolicy.cs
This file contains 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,35 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
using System; | ||
using System.Runtime.CompilerServices; | ||
using System.Security.Cryptography; | ||
using System.Text; | ||
using Microsoft.Extensions.Logging; | ||
using Yarp.ReverseProxy.Model; | ||
using Yarp.ReverseProxy.Utilities; | ||
|
||
namespace Yarp.ReverseProxy.SessionAffinity; | ||
|
||
internal sealed class ArrCookieSessionAffinityPolicy : BaseHashCookieSessionAffinityPolicy | ||
{ | ||
private readonly ConditionalWeakTable<DestinationState, string> _hashes = new(); | ||
|
||
public ArrCookieSessionAffinityPolicy( | ||
IClock clock, | ||
ILogger<ArrCookieSessionAffinityPolicy> logger) | ||
: base(clock, logger) { } | ||
|
||
public override string Name => SessionAffinityConstants.Policies.ArrCookie; | ||
|
||
protected override string GetDestinationHash(DestinationState d) | ||
{ | ||
return _hashes.GetValue(d, static d => | ||
{ | ||
// Matches the format used by ARR | ||
var destinationIdBytes = Encoding.Unicode.GetBytes(d.DestinationId.ToLowerInvariant()); | ||
var hashBytes = SHA256.HashData(destinationIdBytes); | ||
return Convert.ToHexString(hashBytes); | ||
}); | ||
} | ||
} |
This file contains 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
81 changes: 81 additions & 0 deletions
81
src/ReverseProxy/SessionAffinity/BaseHashCookieSessionAffinityPolicy.cs
This file contains 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,81 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Logging; | ||
using Yarp.ReverseProxy.Configuration; | ||
using Yarp.ReverseProxy.Model; | ||
using Yarp.ReverseProxy.Utilities; | ||
|
||
namespace Yarp.ReverseProxy.SessionAffinity; | ||
|
||
internal abstract class BaseHashCookieSessionAffinityPolicy : ISessionAffinityPolicy | ||
{ | ||
private static readonly object AffinityKeyId = new(); | ||
private readonly ILogger _logger; | ||
private readonly IClock _clock; | ||
|
||
public BaseHashCookieSessionAffinityPolicy(IClock clock, ILogger logger) | ||
{ | ||
_clock = clock ?? throw new ArgumentNullException(nameof(clock)); | ||
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
} | ||
|
||
public abstract string Name { get; } | ||
|
||
public void AffinitizeResponse(HttpContext context, ClusterState cluster, SessionAffinityConfig config, DestinationState destination) | ||
{ | ||
if (!config.Enabled.GetValueOrDefault()) | ||
{ | ||
throw new InvalidOperationException("Session affinity is disabled for cluster."); | ||
} | ||
|
||
// Affinity key is set on the response only if it's a new affinity. | ||
if (!context.Items.ContainsKey(AffinityKeyId)) | ||
{ | ||
var affinityKey = GetDestinationHash(destination); | ||
var affinityCookieOptions = AffinityHelpers.CreateCookieOptions(config.Cookie, context.Request.IsHttps, _clock); | ||
context.Response.Cookies.Append(config.AffinityKeyName, affinityKey, affinityCookieOptions); | ||
} | ||
} | ||
|
||
public AffinityResult FindAffinitizedDestinations(HttpContext context, ClusterState cluster, SessionAffinityConfig config, IReadOnlyList<DestinationState> destinations) | ||
{ | ||
if (!config.Enabled.GetValueOrDefault()) | ||
{ | ||
throw new InvalidOperationException($"Session affinity is disabled for cluster {cluster.ClusterId}."); | ||
} | ||
|
||
var affinityHash = context.Request.Cookies[config.AffinityKeyName]; | ||
if (affinityHash is null) | ||
{ | ||
return new(null, AffinityStatus.AffinityKeyNotSet); | ||
} | ||
|
||
foreach (var d in destinations) | ||
{ | ||
var hashValue = GetDestinationHash(d); | ||
|
||
if (affinityHash == hashValue) | ||
{ | ||
context.Items[AffinityKeyId] = affinityHash; | ||
Tratcher marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return new(d, AffinityStatus.OK); | ||
} | ||
} | ||
|
||
if (destinations.Count == 0) | ||
{ | ||
Log.AffinityCannotBeEstablishedBecauseNoDestinationsFound(_logger, cluster.ClusterId); | ||
} | ||
else | ||
{ | ||
Log.DestinationMatchingToAffinityKeyNotFound(_logger, cluster.ClusterId); | ||
} | ||
|
||
return new(null, AffinityStatus.DestinationNotFound); | ||
} | ||
|
||
protected abstract string GetDestinationHash(DestinationState d); | ||
} |
This file contains 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 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
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.
Am I misunderstanding this or is this just plain wrong? If the key is shared by more than 1 destination, we'll pick whichever one we happen to find first.
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.
The current policy implementations would pick the first one since we do a linear search, but the abstraction allows us to create keys that are not specific to a single destination. E.g. if you had sets of destinations a-1, a-2, b-1, b-2... you could make a policy that used the key
a
and returned both a-1 and a-2, then load balancing would choose between them.