3

I know that there's RoleEnvironment events for detecting when a role instance is shutting down or starting, but, is there a way to detect when the last role instance shuts down? (i.e. the entire role is shutting down)

I realize this will not be full-proof in instances of a hardware crash, but I have some cleanup to do when a role is being terminated to get rid of no longer needed Service Bus subscriptions.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202

2 Answers2

1

One idea: If you have an OnStop() event handler in your role instance, you can enumerate the role's instances (RoleEnvironment.CurrentRoleInstance.Role.Instances) to see if it's the only one in the list. This could be slightly problematic, as two instances could be handling OnStop() simultaneously, but it should at least get you going in the right direction.

David Makogon
  • 69,407
  • 21
  • 141
  • 189
1

Note: the initial alternative here is theoretical only: I've not tried it.

Another option is to have code in the start up and shut down that gets a lease on a BLOB that contains the names of all instances of the roll. When an instance starts up it gets a lease and sees if the list already contains it's name. If the list doesn't have the instance name it adds to the list, saves and then releases the lease on the BLOB.

On shut down each instance when running OnStop could get the list and then remove it's own name, and as well, it could do a quick check using the RoleEnvironment.CurrentRoleInstance.Role.Instances collection that David mentions to "clean out" any instance names that might be now dead but didn't have a chance to clean up after themselves. If the list is empty by the time you are done then you're the last instance.

I still think this is isn't fool proof, but at least it gets around the concerns that David mentioned as only a single client can obtain a lease at a time on the BLOB. It also still depends heavily on the Instances collection which could be in flux at times.

In my opinion, the better approach is to use something completely outside the role itself that uses the service management API to determine if the role is running, and if not, to perform your clean up. Of course, you'd want to do some extra checking to be 100% sure the role is off before removing the subscriptions as some folks have reported inaccurate/conflicting data coming from the API from time to time. At a minimum some mechanism outside of the role itself should be used to provide you a warning that perhaps the shut down code you have didn't work. Some 3rd party providers out there that monitor your Azure services for you may even be able to detect the role has shut down and let your run a script.

MikeWo
  • 10,887
  • 1
  • 38
  • 44