Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ Task Initialize(string strProviderName,
/// indicating that the balance of queues has changed.
/// It should be implemented by components interested in stream queue load balancing.
/// When change notification is received, listener should request updated list of queues from the queue balancer.
/// This interface inherit from IAddressable for threading-safe concern
/// </summary>
public interface IStreamQueueBalanceListener :IAddressable
public interface IStreamQueueBalanceListener

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to remove IAddressable from the interface. Never really liked it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"This interface inherit from IAddressable for threading-safe concern"

It inherits from IAddressable so it can be implemented by system target and notification be called as grain call. The right and proper way to talk between components inside Orleans is via grain (system target) calls. Except for some small number of limited cases when we break isolation. But here is not such a case and thus I don't see a reason to avoid using grain calls for cross component communication and insist on breaking isolation (I call "invoking function directly, even if after that we enqueue an Task directly" as breaking isolation).

{
/// <summary>
/// Receive notifications about adapter queue responsibility changes.
Expand Down
19 changes: 8 additions & 11 deletions src/OrleansRuntime/Catalog/Catalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementRuntime, ISiloStatusListener
internal class Catalog : SystemTarget, ICatalog, IPlacementRuntime
{
[Serializable]
internal class NonExistentActivationException : Exception
Expand Down Expand Up @@ -169,6 +169,7 @@ public Catalog(
});
maxWarningRequestProcessingTime = this.config.ResponseTimeout.Multiply(5);
maxRequestProcessingTime = this.config.MaxRequestProcessingTime;
grainDirectory.SetSiloRemovedCatalogCallback(this.OnSiloStatusChange);
}

/// <summary>
Expand Down Expand Up @@ -1606,17 +1607,15 @@ private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addre

#endregion

#region Implementation of ISiloStatusListener

public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;

// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
// We may review the directory behavior in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
if (status == SiloStatus.Dead)
{
Expand All @@ -1639,20 +1638,20 @@ public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus sta

lock (activationData)
{
// adapted from InsideGarinClient.DeactivateOnIdle().
// adapted from InsideGrainClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
String.Format("Catalog has thrown an exception while executing OnSiloStatusChange of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.",
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partition to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
Expand All @@ -1664,7 +1663,5 @@ public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus sta
}
}
}

#endregion
}
}
34 changes: 34 additions & 0 deletions src/OrleansRuntime/Core/SystemTargetExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Threading.Tasks;
using Orleans.Runtime.Scheduler;

namespace Orleans.Runtime
{
/// <summary>
/// Extensions for <see cref="SystemTarget"/>.
/// </summary>
public static class SystemTargetExtensions
{
/// <summary>
/// Schedules the provided <paramref name="action"/> on the <see cref="SystemTarget"/>'s <see cref="ISchedulingContext"/>.
/// </summary>
/// <param name="self">The <see cref="SystemTarget"/>.</param>
/// <param name="action">The action.</param>
/// <returns>A <see cref="Task"/> which completes when the <paramref name="action"/> has completed.</returns>
public static Task ScheduleTask(this SystemTarget self, Func<Task> action)
{
return self.RuntimeClient.Scheduler.RunOrQueueTask(action, self.SchedulingContext);
}

/// <summary>
/// Schedules the provided <paramref name="action"/> on the <see cref="SystemTarget"/>'s <see cref="ISchedulingContext"/>.
/// </summary>
/// <param name="self">The <see cref="SystemTarget"/>.</param>
/// <param name="action">The action.</param>
/// <returns>A <see cref="Task"/> which completes when the <paramref name="action"/> has completed.</returns>
public static Task ScheduleTask(this SystemTarget self, Action action)
{
return self.RuntimeClient.Scheduler.RunOrQueueAction(action, self.SchedulingContext);
}
}
}
7 changes: 7 additions & 0 deletions src/OrleansRuntime/GrainDirectory/ILocalGrainDirectory.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.GrainDirectory;
Expand Down Expand Up @@ -122,5 +123,11 @@ interface ILocalGrainDirectory : IGrainDirectory
/// The id of this cluster
/// </summary>
string ClusterId { get; }

/// <summary>
/// Sets the callback to <see cref="Catalog"/> which is called when a silo is removed from membership.
/// </summary>
/// <param name="catalogOnSiloRemoved">The callback.</param>
void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> catalogOnSiloRemoved);
}
}
19 changes: 14 additions & 5 deletions src/OrleansRuntime/GrainDirectory/LocalGrainDirectory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ internal class LocalGrainDirectory :
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private readonly IInternalGrainFactory grainFactory;
private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved;

// Consider: move these constants into an apropriate place
internal const int HOP_LIMIT = 3; // forward a remote request no more than two times
Expand Down Expand Up @@ -58,8 +59,6 @@ internal class LocalGrainDirectory :

public string ClusterId { get; }

internal ISiloStatusListener CatalogSiloStatusListener { get; set; }

internal GlobalSingleInstanceActivationMaintainer GsiActivationMaintainer { get; private set; }

private readonly CounterStatistic localLookups;
Expand Down Expand Up @@ -261,6 +260,16 @@ internal void MarkStopPreparationFailed(Exception ex)
stopPreparationResolver.TrySetException(ex);
}

/// <inheritdoc />
public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
lock (membershipCache)
{
this.catalogOnSiloRemoved = callback;
}
}

#region Handling membership events
protected void AddServer(SiloAddress silo)
{
Expand Down Expand Up @@ -299,12 +308,12 @@ protected void RemoveServer(SiloAddress silo, SiloStatus status)
return;
}

if (CatalogSiloStatusListener != null)
if (this.catalogOnSiloRemoved != null)
{
try
{
// only call SiloStatusChangeNotification once on the catalog and the order is important: call BEFORE updating membershipRingList.
CatalogSiloStatusListener.SiloStatusChangeNotification(silo, status);
// Only notify the catalog once. Order is important: call BEFORE updating membershipRingList.
this.catalogOnSiloRemoved(silo, status);
}
catch (Exception exc)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public async Task InjectMultiClusterConfiguration(MultiClusterConfiguration conf
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// any status change can cause changes in gateway list
PublishChanges();
this.ScheduleTask(() => Utils.SafeExecute(() => this.PublishChanges())).Ignore();
}

public bool SubscribeToMultiClusterConfigurationEvents(GrainReference observer)
Expand Down
5 changes: 5 additions & 0 deletions src/OrleansRuntime/Placement/DeploymentLoadPublisher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@ private void NotifyAllStatisticsChangeEventsSubscribers(SiloAddress silo, SiloRu


public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
this.ScheduleTask(() => { Utils.SafeExecute(() => this.OnSiloStatusChange(updatedSilo, status), this.logger); }).Ignore();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the other example: when we were actually breaking isolation (as opposite to below, where we were not breaking isolation).
I get it that in theory it was wrong to break isolation. But before I go and try to dig up why we did it this way, I want to ask:
why do you want to change it now? what did not work correctly? What was actually wrong with that?
The data structures here are concurrent and handled correctly I believe, so I don't yet see any reason to change it here, unless you can show me one.

@ReubenBond ReubenBond Aug 17, 2017 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this breaking isolation? I'm not sure that SystemTargets ever had real isolation within a silo - isn't it more rare that we don't call using a mechanism similar to this one here? It seems that the vast majority of the time, calls to a system target follow this pattern:

scheduler.QueueTask(() => sysTarget.CallMethod(), sysTarget.SchedulingContext).WaitBlah();

Where scheduler = OrleansTaskScheduler and sysTarget is a direct .NET reference to the system target instance (not a proxy GrainReference).

I'm looking through the code now and unless I'm reading incorrectly, I can find 1 instance where we're not breaking isolation (streams related code) and maybe 40 or so instances where we are. Basing this on usages of IInternalGrainFactory.GetSystemTarget(...) where the local silo is being used vs usages of scheduler.QueueTask(task, context) and friends. I'm sure I'm wrong about at least some of those.

Regardless, the reason I took this approach is what I mentioned in this comment above: #3290 (comment)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do think that calling via some proxy is a better solution. The only problem is that GrainReference can only be used from an addressable context today (another Grain or SystemTarget) when running within the silo.

Maybe that restriction can be relaxed and we can convert all of the code to make proxied calls. The problem is that it's not relaxed today and I feel like that's a larger change than we could stomach in a patch release. That kind of thing requires more thought - I'm sure the exception which caused this issue was not added lightheartedly, it's likely there to make sure scheduling contexts are being used correctly.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh, now maybe I see.

Absolutely, definitely the original goal was to talk to system targets as grain - via grain ref, and not directly like here.
I am not sure about 1 vs 40. I am very doubtful it is indeed only 1. But it should be, at least according to the original vision, the vast majority.
There should be only 2 cases really:

  1. init in silo (since system target or parts of the runtime may not exist yet, so we cant rely on regular messaging to work yet)
  2. direct calls from membership, to ensure strict order under lock.

All the others can/should be replaced to grain calls to system targets. There may be some more exception, but I still think the rule is to use GR as much as possible.

}

private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status)
{
if (!status.IsTerminating()) return;

Expand Down
31 changes: 19 additions & 12 deletions src/OrleansRuntime/Silo/Silo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,11 @@ internal IReadOnlyCollection<IProvider> AllSiloProviders
/// Test hook connection for white-box testing of silo.
/// </summary>
internal TestHooksSystemTarget testHook;


private SchedulingContext membershipOracleContext;
private SchedulingContext multiClusterOracleContext;
private SchedulingContext reminderServiceContext;

/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
Expand Down Expand Up @@ -351,7 +355,6 @@ private void InjectDependencies()
healthCheckParticipants.Add(membershipOracle);

catalog.SiloStatusOracle = this.membershipOracle;
localGrainDirectory.CatalogSiloStatusListener = catalog;
this.membershipOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
messageCenter.SiloDeadOracle = this.membershipOracle.IsDeadSilo;

Expand Down Expand Up @@ -491,11 +494,12 @@ private void DoStart()
// Load and init grain services before silo becomes active.
CreateGrainServices(GlobalConfig.GrainServiceConfigurations);

ISchedulingContext statusOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext;
scheduler.QueueTask(() => this.membershipOracle.Start(), statusOracleContext)
this.membershipOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext ??
this.providerManagerSystemTarget.SchedulingContext;
scheduler.QueueTask(() => this.membershipOracle.Start(), this.membershipOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle created successfully."); }
scheduler.QueueTask(this.membershipOracle.BecomeActive, statusOracleContext)
scheduler.QueueTask(this.membershipOracle.BecomeActive, this.membershipOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle became active successfully."); }
scheduler.QueueTask(() => this.typeManager.Initialize(versionStore), this.typeManager.SchedulingContext)
Expand All @@ -507,8 +511,9 @@ private void DoStart()
logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.",
GlobalConfig.ServiceId, GlobalConfig.ClusterId);

ISchedulingContext clusterStatusContext = (multiClusterOracle as SystemTarget)?.SchedulingContext;
scheduler.QueueTask(() => multiClusterOracle.Start(), clusterStatusContext)
this.multiClusterOracleContext = (multiClusterOracle as SystemTarget)?.SchedulingContext ??
this.providerManagerSystemTarget.SchedulingContext;
scheduler.QueueTask(() => multiClusterOracle.Start(), multiClusterOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("multicluster oracle created successfully."); }
}
Expand All @@ -532,7 +537,9 @@ private void DoStart()
if (this.reminderService != null)
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.scheduler.QueueTask(this.reminderService.Start, (this.reminderService as SystemTarget)?.SchedulingContext)
this.reminderServiceContext = (this.reminderService as SystemTarget)?.SchedulingContext ??
this.providerManagerSystemTarget.SchedulingContext;
this.scheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose)
{
Expand Down Expand Up @@ -726,14 +733,14 @@ private void Terminate(bool gracefully)
{
logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()");
// 1: Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(this.membershipOracle.ShutDown, (this.membershipOracle as SystemTarget)?.SchedulingContext)
scheduler.QueueTask(this.membershipOracle.ShutDown, this.membershipOracleContext)
.WaitWithThrow(stopTimeout);
}
else
{
logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()");
// 1: Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(this.membershipOracle.Stop, (this.membershipOracle as SystemTarget)?.SchedulingContext)
scheduler.QueueTask(this.membershipOracle.Stop, this.membershipOracleContext)
.WaitWithThrow(stopTimeout);
}
}
Expand All @@ -746,7 +753,7 @@ private void Terminate(bool gracefully)
if (reminderService != null)
{
// 2: Stop reminder service
scheduler.QueueTask(reminderService.Stop, (reminderService as SystemTarget)?.SchedulingContext)
scheduler.QueueTask(reminderService.Stop, this.reminderServiceContext)
.WaitWithThrow(stopTimeout);
}

Expand Down Expand Up @@ -818,7 +825,7 @@ private void FastKill()
if (!GlobalConfig.LivenessType.Equals(GlobalConfiguration.LivenessProviderType.MembershipTableGrain))
{
// do not execute KillMyself if using MembershipTableGrain, since it will fail, as we've already stopped app scheduler turns.
SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, (this.membershipOracle as SystemTarget)?.SchedulingContext)
SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, this.membershipOracleContext)
.WaitWithThrow(stopTimeout));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ public async Task Initialize(Immutable<IQueueAdapter> qAdapter)
// Remove cast once we cleanup
queueAdapter = qAdapter.Value;
await this.queueBalancer.Initialize(this.streamProviderName, this.adapterFactory.GetStreamQueueMapper(), config.SiloMaturityPeriod, this.providerConfig);
var meAsQueueBalanceListener = this.AsReference<IStreamQueueBalanceListener>();
queueBalancer.SubscribeToQueueDistributionChangeEvents(meAsQueueBalanceListener);
queueBalancer.SubscribeToQueueDistributionChangeEvents(this);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why changing this? It used to be that the notification here were delivered as grain calls on this system target, which is the right way for system targets to communicate. There are some other examples when system targets call functions directly (breaking isolation), but this was not the case here. In this case it was done the right way.
So why doing it the wrong way now - call directly and then manually switch context?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you feel this general problem should be addressed?

  • OS Thread notifies some Orleans component of some event
  • That component propagates that notification to subscribers

Should the component marshal the notification onto an addressable context?
Alternatively, should the subscriber be responsible for ensuring that they execute on the correct context?

I am in favor of the latter approach, since the first is difficult without some publicly exposed mechanism for doing so (eg, SystemTarget - which the SF code does not currently have access to) and also because it's the subscriber which knows what its requirements are - not the publisher.

@gabikliot gabikliot Aug 19, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The former of course.
And the reason is not that it is better, but to be consistent with all the rest that we do already.
For regular grain on the same silo: do we call directly and ask the grain to ensure its own single threaded? We call via addressable context anywhere, always, and therefore we should simply be consistent and keep doing it.


List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues)));
Expand Down Expand Up @@ -140,6 +139,11 @@ public async Task StopAgents()
/// and don't execute an older notification if a newer one was already delivered.
/// </summary>
public Task QueueDistributionChangeNotification()
{
return this.ScheduleTask(() => this.HandleQueueDistributionChangeNotification());
}

public Task HandleQueueDistributionChangeNotification()
{
latestRingNotificationSequenceNumber++;
int notificationSeqNumber = latestRingNotificationSequenceNumber;
Expand Down