orleans icon indicating copy to clipboard operation
orleans copied to clipboard

Fail to unsubscribe from SMS Provider streams

Open richcorless opened this issue 9 years ago • 7 comments

Hi,

Within my application I use streams to broadcast changes to other grains to avoid having to keep a cache of grain IDs. This works very well in normal operation, however, I am currently looking to make the system as robust as possible so I want it to recover from an ungraceful shutdown (i.e. kill the processes).

The basic set up is an Orleans server process and an Orleans client process that acts as a gateway which endpoints connect to via WCF to use the system. There is a grain per connected endpoint that is used to cache the services the endpoint has available and this needs to be cleaned up after an ungraceful shutdown if the endpoint disconnected while the Orleans server was down.

When the Orleans client connects once more after recovery, it notifies which endpoints are still connected, if any are no longer connected then the grains need to have a stream unsubscribed. During this process, the OnActivateAsync method executes for the endpoint grain where it resumes the stream subscription without issue, it then calls to cancel the grain (clear state, etc...) to properly unsubscribe from it and I get:

Extension not installed on grain OrleansStreamTest.Grains.PublisherGrain attempting to invoke type Orleans.Streams.OrleansCodeGenStreamProducerExtensionMethodInvoker from invokable Orleans.Runtime.ActivationData Exception = Orleans.Runtime.GrainExtensionNotInstalledException: Extension not installed on grain OrleansStreamTest.Grains.PublisherGrain attempting to invoke type Orleans.Streams.OrleansCodeGenStreamProducerExtensionMethodInvoker from invokable Orleans.Runtime.ActivationData

I have a test application that replicates the issue, code snippets below. Configuration wise I am using the Azure Storage Emulator for the GrainStore and the PubSubStore and Simple Message Streams. With this test application I have also found that it affects streams used only by grains, streams used by clients and/or grains unsubscribe with no issues.

Publisher Grain

public class PublisherGrain : Grain, IPublisherGrain
{
	private IAsyncStream<double> clientStream;

	private IAsyncStream<double> grainStream;

	public override Task OnActivateAsync()
	{
		var streamProvider = this.GetStreamProvider("SMSProvider");
		this.clientStream = streamProvider.GetStream<double>(Guid.Empty, "TestClientStream");
		this.grainStream = streamProvider.GetStream<double>(Guid.Empty, "TestGrainStream");
		return base.OnActivateAsync();
	}

	public async Task PublishAsync(double data)
	{
		Console.WriteLine($"Sending data: {data}");
		await this.clientStream.OnNextAsync(data);
		await this.grainStream.OnNextAsync(data);
	}
}

Subscriber Grain Changing this to use the TestClientStream prevents the issue from occurring.

[StorageProvider(ProviderName = "GrainStore")]
public class SubscriberGrain : Grain<SubscriberState>, ISubscriberGrain
{
	public override async Task OnActivateAsync()
	{
		if (this.State.StreamHandle != null)
		{
			this.State.StreamHandle = await this.State.StreamHandle.ResumeAsync((payload, token) => this.MessageReceivedAsync(payload));
			await this.WriteStateAsync();
		}

		await base.OnActivateAsync();
	}

	public async Task SubscribeAsync()
	{
		var streamProvider = this.GetStreamProvider("SMSProvider");
		var stream = streamProvider.GetStream<double>(Guid.Empty, "TestGrainStream");
		this.State.StreamHandle = await stream.SubscribeAsync((payload, token) => this.MessageReceivedAsync(payload));
		await this.WriteStateAsync();
	}

	public async Task UnsubscribeAsync()
	{
		if (this.State.StreamHandle != null)
		{
			await this.State.StreamHandle.UnsubscribeAsync();  // error occurs here
		}

		await this.ClearStateAsync();
		this.DeactivateOnIdle();
	}

	private Task MessageReceivedAsync(double payload)
	{
		Console.WriteLine($"Message Received: {payload}");
		return Task.CompletedTask;
	}
}

Client

private class Runner
{
	private StreamSubscriptionHandle<double> handle;

	private CancellationTokenSource cts; 

	public async void Start()
	{
		var streamProvider = GrainClient.GetStreamProvider("SMSProvider");
		var stream = streamProvider.GetStream<double>(Guid.Empty, "TestGrainStream");
		this.handle = await stream.SubscribeAsync((payload, token) =>
		{
			Console.WriteLine($"Received data: {payload}");
			return Task.CompletedTask;
		});

		this.cts = new CancellationTokenSource();
		this.StartBackground();
	}

	public async void Stop()
	{
		this.cts.Cancel();
		await this.handle.UnsubscribeAsync();
	}

	private void StartBackground()
	{
		Task.Run(async () =>
		{
			var data = 1;
			var subscriberGrain = GrainClient.GrainFactory.GetGrain<ISubscriberGrain>(Guid.Empty);

			await subscriberGrain.UnsubscribeAsync();  //this mimics the clean up code the real application does

			await subscriberGrain.SubscribeAsync();
			while (!this.cts.IsCancellationRequested)
			{
				var publisherGrain = GrainClient.GrainFactory.GetGrain<IPublisherGrain>(Guid.Empty);
				await publisherGrain.PublishAsync(data++);
				await Task.Delay(10);
			}

			await subscriberGrain.UnsubscribeAsync();
		}, this.cts.Token);
	}
}

Any feedback on what I have done wrong or step I have missed would be appreciated.

Thank you in advance, Rich

richcorless avatar May 08 '17 10:05 richcorless

@richcorless, what version of Orleans are you running?

jason-bragg avatar May 08 '17 15:05 jason-bragg

@jason-bragg: 1.4.1

richcorless avatar May 08 '17 15:05 richcorless

Ah. So this is interesting, and I'm surprised we've not seen this sooner.

When we get a stream from the stream provider, we don't know if it's being used for consumption or production of events, so we don't install the grain extension until we know this. In the case of consumption this is done when the SubscribeAsync or ResumeAsync is called, in the case of production it's when the first OnNextAsync is called.

So here's the problem, the publisher get's the streams in its on activate, but the grain extensions for streaming are not installed until it actually publishes an event. Until it installs this extension it can't take part in the streaming infrastructure, so unsubscribe calls that have it registered as a producer on the stream will fail with the 'extension not installed' exception you're seeing.

To test this theory (an as a possible mitigation until we can get this fixed), have the publisher grain publish a dummy event to a dummy stream in it's on activate. This will force the installation of the producer extension whenever the grain activates.

public override async Task OnActivateAsync()
{
	var streamProvider = this.GetStreamProvider("SMSProvider");
	this.clientStream = streamProvider.GetStream<double>(Guid.Empty, "TestClientStream");
	this.grainStream = streamProvider.GetStream<double>(Guid.Empty, "TestGrainStream");

	//  TODO: hack! - kill this code when Orleans team fixes this
	var hack= streamProvider.GetStream<bool>(Guid.Empty, "hack");
	await hack.OnNextAsync(false);

	await base.OnActivateAsync();
}

jason-bragg avatar May 08 '17 16:05 jason-bragg

Perfect, that works in the test app and the real one.

Thank you for the quick response with a work around and explanation; makes sense as to why it is occurring. Will be nice when I can delete those lines :)

richcorless avatar May 08 '17 16:05 richcorless

We have a fix for this in 1.5 :)

see #3003

xiazen avatar May 09 '17 21:05 xiazen

Excellent, thanks for the quick fix. Looking forward to 1.5 :)

richcorless avatar May 10 '17 08:05 richcorless

I still got the same error message as reported, and it seems to have disappeared when I applied the suggested hack above. This is using version 1.5.3.

The error message would log to console, but the stream would to the best of my knowledge work as expected.

denstad avatar Dec 26 '17 12:12 denstad