- 
                Notifications
    You must be signed in to change notification settings 
- Fork 2.1k
Silo Metadata and Placement Filtering #9271
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
      
      
            ReubenBond
  merged 20 commits into
  dotnet:main
from
rkargMsft:silo-metadata-and-placement-filtering
  
      
      
   
  Feb 27, 2025 
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            20 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      7395b99
              
                Initial implementation
              
              
                rkargMsft 8aa83aa
              
                Remove dead silos from metadata cache
              
              
                rkargMsft d65153c
              
                Allow overwriting of metadata values
              
              
                rkargMsft 3ee780a
              
                Adding Silo Metadata tests
              
              
                rkargMsft 47899c1
              
                Tests for Grain Placement Filter
              
              
                rkargMsft 9f4f60d
              
                Tests for silo metadata placement filters
              
              
                rkargMsft d715fdd
              
                Adding test category
              
              
                rkargMsft 814a3ba
              
                Testing loading silo metadata from config
              
              
                rkargMsft d969a85
              
                Required and Preferred match filtering unit tests
              
              
                rkargMsft 9b44825
              
                Testing multiple metadata keys in attribute
              
              
                rkargMsft 49e12bd
              
                Ordering support for filters
              
              
                rkargMsft 6aa01d5
              
                Moving reusable types to Core projects
              
              
                rkargMsft 27ddb5e
              
                Correct comment
              
              
                rkargMsft c6905be
              
                Correcting documentation
              
              
                rkargMsft 0bc5ded
              
                Allowing chaining extension method
              
              
                rkargMsft 3c8a962
              
                #nullable enable for new files
              
              
                rkargMsft 005d8c6
              
                Review suggestions
              
              
                ReubenBond 9aae9d0
              
                Fixups
              
              
                ReubenBond ec8a407
              
                Add PlacementFilterContext
              
              
                ReubenBond ac45d1e
              
                rename file
              
              
                ReubenBond 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
    
  
  
    
              
              
        
          
          
            29 changes: 29 additions & 0 deletions
          
          29 
        
  src/Orleans.Core.Abstractions/Placement/PlacementFilterAttribute.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,29 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using Orleans.Metadata; | ||
| using Orleans.Runtime; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Placement; | ||
|  | ||
| /// <summary> | ||
| /// Base for all placement filter marker attributes. | ||
| /// </summary> | ||
| [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] | ||
| public abstract class PlacementFilterAttribute : Attribute, IGrainPropertiesProviderAttribute | ||
| { | ||
| /// <summary> | ||
| /// Gets the placement filter strategy. | ||
| /// </summary> | ||
| public PlacementFilterStrategy PlacementFilterStrategy { get; private set; } | ||
|  | ||
| protected PlacementFilterAttribute(PlacementFilterStrategy placement) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(placement); | ||
| PlacementFilterStrategy = placement; | ||
| } | ||
|  | ||
| /// <inheritdoc /> | ||
| public virtual void Populate(IServiceProvider services, Type grainClass, GrainType grainType, Dictionary<string, string> properties) | ||
| => PlacementFilterStrategy?.PopulateGrainProperties(services, grainClass, grainType, properties); | ||
| } | 
        
          
          
            80 changes: 80 additions & 0 deletions
          
          80 
        
  src/Orleans.Core.Abstractions/Placement/PlacementFilterStrategy.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,80 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using Orleans.Metadata; | ||
| using Orleans.Runtime; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Placement; | ||
|  | ||
| /// <summary> | ||
| /// Represents a strategy for filtering silos which a grain can be placed on. | ||
| /// </summary> | ||
| public abstract class PlacementFilterStrategy | ||
| { | ||
| public int Order { get; private set; } | ||
|  | ||
| protected PlacementFilterStrategy(int order) | ||
| { | ||
| Order = order; | ||
| } | ||
|  | ||
| /// <summary> | ||
| /// Initializes an instance of this type using the provided grain properties. | ||
| /// </summary> | ||
| /// <param name="properties"> | ||
| /// The grain properties. | ||
| /// </param> | ||
| public void Initialize(GrainProperties properties) | ||
| { | ||
| var orderProperty = GetPlacementFilterGrainProperty("order", properties); | ||
| if (!int.TryParse(orderProperty, out var parsedOrder)) | ||
| { | ||
| throw new ArgumentException("Invalid order property value."); | ||
| } | ||
|  | ||
| Order = parsedOrder; | ||
|  | ||
| AdditionalInitialize(properties); | ||
| } | ||
|  | ||
| public virtual void AdditionalInitialize(GrainProperties properties) | ||
| { | ||
| } | ||
|  | ||
| /// <summary> | ||
| /// Populates grain properties to specify the preferred placement strategy. | ||
| /// </summary> | ||
| /// <param name="services">The service provider.</param> | ||
| /// <param name="grainClass">The grain class.</param> | ||
| /// <param name="grainType">The grain type.</param> | ||
| /// <param name="properties">The grain properties which will be populated by this method call.</param> | ||
| public void PopulateGrainProperties(IServiceProvider services, Type grainClass, GrainType grainType, Dictionary<string, string> properties) | ||
| { | ||
| var typeName = GetType().Name; | ||
| if (properties.TryGetValue(WellKnownGrainTypeProperties.PlacementFilter, out var existingValue)) | ||
| { | ||
| properties[WellKnownGrainTypeProperties.PlacementFilter] = $"{existingValue},{typeName}"; | ||
| } | ||
| else | ||
| { | ||
| properties[WellKnownGrainTypeProperties.PlacementFilter] = typeName; | ||
| } | ||
|  | ||
| properties[$"{WellKnownGrainTypeProperties.PlacementFilter}.{typeName}.order"] = Order.ToString(CultureInfo.InvariantCulture); | ||
|  | ||
| foreach (var additionalGrainProperty in GetAdditionalGrainProperties(services, grainClass, grainType, properties)) | ||
| { | ||
| properties[$"{WellKnownGrainTypeProperties.PlacementFilter}.{typeName}.{additionalGrainProperty.Key}"] = additionalGrainProperty.Value; | ||
| } | ||
| } | ||
|  | ||
| protected string? GetPlacementFilterGrainProperty(string key, GrainProperties properties) | ||
| { | ||
| var typeName = GetType().Name; | ||
| return properties.Properties.TryGetValue($"{WellKnownGrainTypeProperties.PlacementFilter}.{typeName}.{key}", out var value) ? value : null; | ||
| } | ||
|  | ||
| protected virtual IEnumerable<KeyValuePair<string, string>> GetAdditionalGrainProperties(IServiceProvider services, Type grainClass, GrainType grainType, IReadOnlyDictionary<string, string> existingProperties) | ||
| => Array.Empty<KeyValuePair<string, string>>(); | ||
| } | 
  
    
      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,11 @@ | ||
| using System.Collections.Generic; | ||
| using Orleans.Runtime; | ||
| using Orleans.Runtime.Placement; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Placement; | ||
|  | ||
| public interface IPlacementFilterDirector | ||
| { | ||
| IEnumerable<SiloAddress> Filter(PlacementFilterStrategy filterStrategy, PlacementFilterContext context, IEnumerable<SiloAddress> silos); | ||
| } | 
  
    
      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,6 @@ | ||
| using Orleans.Runtime; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Placement; | ||
|  | ||
| public readonly record struct PlacementFilterContext(GrainType GrainType, GrainInterfaceType InterfaceType, ushort InterfaceVersion); | 
  
    
      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,26 @@ | ||
| using Microsoft.Extensions.DependencyInjection; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Placement; | ||
|  | ||
| public static class PlacementFilterExtensions | ||
| { | ||
| /// <summary> | ||
| /// Configures a <typeparamref name="TFilter"/> for filtering candidate grain placements. | ||
| /// </summary> | ||
| /// <typeparam name="TFilter">The placement filter.</typeparam> | ||
| /// <typeparam name="TDirector">The placement filter director.</typeparam> | ||
| /// <param name="services">The service collection.</param> | ||
| /// <param name="strategyLifetime">The lifetime of the placement strategy.</param> | ||
| /// <returns>The service collection.</returns> | ||
| public static IServiceCollection AddPlacementFilter<TFilter, TDirector>(this IServiceCollection services, ServiceLifetime strategyLifetime) | ||
| where TFilter : PlacementFilterStrategy | ||
| where TDirector : class, IPlacementFilterDirector | ||
| { | ||
| services.Add(ServiceDescriptor.DescribeKeyed(typeof(PlacementFilterStrategy), typeof(TFilter).Name, typeof(TFilter), strategyLifetime)); | ||
| services.AddKeyedSingleton<IPlacementFilterDirector, TDirector>(typeof(TFilter)); | ||
|  | ||
| return services; | ||
| } | ||
|  | ||
| } | 
  
    
      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
    
  
  
    
              
  
    
      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
    
  
  
    
              
        
          
          
            8 changes: 8 additions & 0 deletions
          
          8 
        
  src/Orleans.Runtime/MembershipService/SiloMetadata/ISiloMetadataCache.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,8 @@ | ||
| #nullable enable | ||
|  | ||
| namespace Orleans.Runtime.MembershipService.SiloMetadata; | ||
|  | ||
| public interface ISiloMetadataCache | ||
| { | ||
| SiloMetadata GetSiloMetadata(SiloAddress siloAddress); | ||
| } | 
        
          
          
            9 changes: 9 additions & 0 deletions
          
          9 
        
  src/Orleans.Runtime/MembershipService/SiloMetadata/ISiloMetadataClient.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,9 @@ | ||
| using System.Threading.Tasks; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Runtime.MembershipService.SiloMetadata; | ||
|  | ||
| internal interface ISiloMetadataClient | ||
| { | ||
| Task<SiloMetadata> GetSiloMetadata(SiloAddress siloAddress); | ||
| } | 
        
          
          
            11 changes: 11 additions & 0 deletions
          
          11 
        
  src/Orleans.Runtime/MembershipService/SiloMetadata/ISiloMetadataSystemTarget.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,11 @@ | ||
| using System.Threading.Tasks; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Runtime.MembershipService.SiloMetadata; | ||
|  | ||
| [Alias("Orleans.Runtime.MembershipService.SiloMetadata.ISiloMetadataSystemTarget")] | ||
| internal interface ISiloMetadataSystemTarget : ISystemTarget | ||
| { | ||
| [Alias("GetSiloMetadata")] | ||
| Task<SiloMetadata> GetSiloMetadata(); | ||
| } | 
        
          
          
            105 changes: 105 additions & 0 deletions
          
          105 
        
  src/Orleans.Runtime/MembershipService/SiloMetadata/SiloMetadaCache.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,105 @@ | ||
| using System; | ||
| using System.Collections.Concurrent; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Logging; | ||
|  | ||
| #nullable enable | ||
| namespace Orleans.Runtime.MembershipService.SiloMetadata; | ||
|  | ||
| internal class SiloMetadataCache( | ||
| ISiloMetadataClient siloMetadataClient, | ||
| MembershipTableManager membershipTableManager, | ||
| ILogger<SiloMetadataCache> logger) | ||
| : ISiloMetadataCache, ILifecycleParticipant<ISiloLifecycle>, IDisposable | ||
| { | ||
| private readonly ConcurrentDictionary<SiloAddress, SiloMetadata> _metadata = new(); | ||
| private readonly CancellationTokenSource _cts = new(); | ||
|  | ||
| void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle) | ||
| { | ||
| Task? task = null; | ||
| Task OnStart(CancellationToken _) | ||
| { | ||
| task = Task.Run(() => this.ProcessMembershipUpdates(_cts.Token)); | ||
| return Task.CompletedTask; | ||
| } | ||
|  | ||
| async Task OnStop(CancellationToken ct) | ||
| { | ||
| await _cts.CancelAsync().ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); | ||
| if (task is not null) | ||
| { | ||
| await task.WaitAsync(ct).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); | ||
| } | ||
| } | ||
|  | ||
| lifecycle.Subscribe( | ||
| nameof(ClusterMembershipService), | ||
| ServiceLifecycleStage.RuntimeServices, | ||
| OnStart, | ||
| OnStop); | ||
| } | ||
|  | ||
| private async Task ProcessMembershipUpdates(CancellationToken ct) | ||
| { | ||
| try | ||
| { | ||
| if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Starting to process membership updates."); | ||
| await foreach (var update in membershipTableManager.MembershipTableUpdates.WithCancellation(ct)) | ||
| { | ||
| // Add entries for members that aren't already in the cache | ||
| foreach (var membershipEntry in update.Entries.Where(e => e.Value.Status is SiloStatus.Active or SiloStatus.Joining)) | ||
| { | ||
| if (!_metadata.ContainsKey(membershipEntry.Key)) | ||
| { | ||
| try | ||
| { | ||
| var metadata = await siloMetadataClient.GetSiloMetadata(membershipEntry.Key).WaitAsync(ct); | ||
| _metadata.TryAdd(membershipEntry.Key, metadata); | ||
| } | ||
| catch(Exception exception) | ||
| { | ||
| logger.LogError(exception, "Error fetching metadata for silo {Silo}", membershipEntry.Key); | ||
| } | ||
| } | ||
| } | ||
|  | ||
| // Remove entries for members that are now dead | ||
| foreach (var membershipEntry in update.Entries.Where(e => e.Value.Status == SiloStatus.Dead)) | ||
| { | ||
| _metadata.TryRemove(membershipEntry.Key, out _); | ||
| } | ||
|  | ||
| // Remove entries for members that are no longer in the table | ||
| foreach (var silo in _metadata.Keys.ToList()) | ||
| { | ||
| if (!update.Entries.ContainsKey(silo)) | ||
| { | ||
| _metadata.TryRemove(silo, out _); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| catch (OperationCanceledException) when (ct.IsCancellationRequested) | ||
| { | ||
| // Ignore and continue shutting down. | ||
| } | ||
| catch (Exception exception) | ||
| { | ||
| logger.LogError(exception, "Error processing membership updates"); | ||
| } | ||
| finally | ||
| { | ||
| if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Stopping membership update processor"); | ||
| } | ||
| } | ||
|  | ||
| public SiloMetadata GetSiloMetadata(SiloAddress siloAddress) => _metadata.GetValueOrDefault(siloAddress) ?? SiloMetadata.Empty; | ||
|  | ||
| public void SetMetadata(SiloAddress siloAddress, SiloMetadata metadata) => _metadata.TryAdd(siloAddress, metadata); | ||
|  | ||
| public void Dispose() => _cts.Cancel(); | ||
| } | ||
      
      Oops, something went wrong.
        
    
  
      
      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.
This previous code was copied from DistributedGrainDirectory. Should there be a follow up issue to update usages of the prior pattern with this one?
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.
Yes, we should clean up the other instances.
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.
Created #9360