forked from dotnet/orleans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrainClient.cs
377 lines (345 loc) · 15.4 KB
/
GrainClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
namespace Orleans
{
/// <summary>
/// Client runtime for connecting to Orleans system
/// </summary>
/// TODO: Make this class non-static and inject it where it is needed.
[Obsolete(DeprecationMessage)]
public static class GrainClient
{
private const string DeprecationMessage = "Deprecated in favor of ClientBuilder.";
/// <summary>
/// Whether the client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
[Obsolete(DeprecationMessage)]
public static bool IsInitialized => isFullyInitialized && client.IsInitialized;
internal static ClientConfiguration CurrentConfig => client.Configuration();
internal static bool TestOnlyNoConnect { get; set; }
private static bool isFullyInitialized = false;
private static IInternalClusterClient client;
private static readonly object initLock = new Object();
[Obsolete(DeprecationMessage)]
public static IClusterClient Instance => client;
[Obsolete(DeprecationMessage)]
public static IGrainFactory GrainFactory => GetGrainFactory();
/// <summary>delegate to configure logging, default to none logger configured</summary>
[Obsolete(DeprecationMessage)]
public static Action<ILoggingBuilder> ConfigureLoggingDelegate { get; set; } = builder => { };
private static IGrainFactory GetGrainFactory()
{
if (!IsInitialized)
{
throw new OrleansException("You must initialize the Grain Client before accessing the GrainFactory");
}
return client;
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file.
/// </summary>
[Obsolete(DeprecationMessage)]
public static void Initialize()
{
ClientConfiguration config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
var orleansClient = (IInternalClusterClient)new ClientBuilder()
.ConfigureApplicationParts(parts => parts.ConfigureDefaults())
.UseConfiguration(config)
.ConfigureLogging(ConfigureLoggingDelegate)
.Build();
InternalInitialize(orleansClient);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFilePath">A relative or absolute pathname for the client configuration file.</param>
[Obsolete(DeprecationMessage)]
public static void Initialize(string configFilePath)
{
Initialize(new FileInfo(configFilePath));
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFile">The client configuration file.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[Obsolete(DeprecationMessage)]
public static void Initialize(FileInfo configFile)
{
ClientConfiguration config;
try
{
config = ClientConfiguration.LoadFromFile(configFile.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error loading client configuration file {0}: {1}", configFile.FullName, ex);
throw;
}
if (config == null)
{
Console.WriteLine("Error loading client configuration file {0}:", configFile.FullName);
throw new ArgumentException(string.Format("Error loading client configuration file {0}:", configFile.FullName), nameof(configFile));
}
var orleansClient = (IInternalClusterClient)new ClientBuilder()
.ConfigureApplicationParts(parts => parts.ConfigureDefaults())
.UseConfiguration(config)
.ConfigureLogging(ConfigureLoggingDelegate)
.Build();
InternalInitialize(orleansClient);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
[Obsolete(DeprecationMessage)]
public static void Initialize(ClientConfiguration config)
{
if (config == null)
{
Console.WriteLine("Initialize was called with null ClientConfiguration object.");
throw new ArgumentException("Initialize was called with null ClientConfiguration object.", nameof(config));
}
var orleansClient = (IInternalClusterClient)new ClientBuilder()
.ConfigureApplicationParts(parts => parts.ConfigureDefaults())
.UseConfiguration(config)
.ConfigureLogging(ConfigureLoggingDelegate)
.Build();
InternalInitialize(orleansClient);
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file using the provided gateway address.
/// Any gateway addresses specified in the config file will be ignored and the provided gateway address wil be used instead.
/// </summary>
/// <param name="gatewayAddress">IP address and port of the gateway silo</param>
/// <param name="overrideConfig">Whether the specified gateway endpoint should override / replace the values from config file, or be additive</param>
[Obsolete(
"This method is obsolete and will be removed in a future release. If it is needed, reimplement this method "
+ "according to its source: "
+ "https://github.com/dotnet/orleans/blob/8f067e77f115c0599eff00c2bdc6f37f2adbc58d/src/Orleans/Core/GrainClient.cs#L173"
)]
public static void Initialize(IPEndPoint gatewayAddress, bool overrideConfig = true)
{
var config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
if (overrideConfig)
{
config.Gateways = new List<IPEndPoint>(new[] { gatewayAddress });
}
else if (!config.Gateways.Contains(gatewayAddress))
{
config.Gateways.Add(gatewayAddress);
}
config.PreferedGatewayIndex = config.Gateways.IndexOf(gatewayAddress);
var orleansClient = (IInternalClusterClient)new ClientBuilder()
.ConfigureApplicationParts(parts => parts.ConfigureDefaults())
.UseConfiguration(config)
.ConfigureLogging(ConfigureLoggingDelegate)
.Build();
InternalInitialize(orleansClient);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void InternalInitialize(IInternalClusterClient clusterClient)
{
if (TestOnlyNoConnect)
{
Trace.TraceInformation("TestOnlyNoConnect - Returning before connecting to cluster.");
}
else
{
// Finish initializing this client connection to the Orleans cluster
DoInternalInitialize(clusterClient);
}
}
/// <summary>
/// Initializes client runtime from client configuration object.
/// </summary>
private static void DoInternalInitialize(IInternalClusterClient clusterClient)
{
if (IsInitialized)
return;
lock (initLock)
{
if (!IsInitialized)
{
try
{
// this is probably overkill, but this ensures isFullyInitialized false
// before we make a call that makes RuntimeClient.Current not null
isFullyInitialized = false;
client = clusterClient; // Keep reference, to avoid GC problems
client.Connect().GetAwaiter().GetResult();
// this needs to be the last successful step inside the lock so
// IsInitialized doesn't return true until we're fully initialized
isFullyInitialized = true;
}
catch (Exception exc)
{
// just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize.
Console.WriteLine("Initialization failed. {0}", exc);
InternalUninitialize();
throw;
}
}
}
}
/// <summary>
/// Uninitializes client runtime.
/// </summary>
[Obsolete(DeprecationMessage)]
public static void Uninitialize()
{
lock (initLock)
{
InternalUninitialize();
}
}
/// <summary>
/// Test hook to uninitialize client without cleanup
/// </summary>
[Obsolete(DeprecationMessage)]
public static void HardKill()
{
lock (initLock)
{
InternalUninitialize(false);
}
}
/// <summary>
/// This is the lock free version of uninitilize so we can share
/// it between the public method and error paths inside initialize.
/// This should only be called inside a lock(initLock) block.
/// </summary>
private static void InternalUninitialize(bool cleanup = true)
{
// Update this first so IsInitialized immediately begins returning
// false. Since this method should be protected externally by
// a lock(initLock) we should be able to reset everything else
// before the next init attempt.
isFullyInitialized = false;
try
{
if (cleanup)
{
client?.Close().GetAwaiter().GetResult();
}
else
{
client?.Abort();
}
}
catch (Exception)
{
}
finally
{
client?.Dispose();
client = null;
}
}
/// <summary>
/// Check that the runtime is intialized correctly, and throw InvalidOperationException if not
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
private static void CheckInitialized()
{
if (!IsInitialized)
throw new InvalidOperationException("Runtime is not initialized. Call Client.Initialize method to initialize the runtime.");
}
/// <summary>
/// Set a timeout for responses on this Orleans client.
/// </summary>
/// <param name="timeout"></param>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
[Obsolete(DeprecationMessage)]
public static void SetResponseTimeout(TimeSpan timeout)
{
CheckInitialized();
RuntimeClient.SetResponseTimeout(timeout);
}
/// <summary>
/// Get a timeout of responses on this Orleans client.
/// </summary>
/// <returns>The response timeout.</returns>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
[Obsolete(DeprecationMessage)]
public static TimeSpan GetResponseTimeout()
{
CheckInitialized();
return RuntimeClient.GetResponseTimeout();
}
/// <summary>
/// Global pre-call interceptor function
/// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain.
/// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings
/// such as <c>Orleans.RequestContext</c> will be picked up.
/// The action receives an InvokeMethodRequest with details of the method to be invoked, including InterfaceId and MethodId,
/// and a <see cref="IGrain"/> which is the GrainReference this request is being sent through
/// </summary>
/// <remarks>This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.</remarks>
[Obsolete(DeprecationMessage + " Please use the AddClientInvokeCallback extension method on IClientBuilder.")]
public static ClientInvokeCallback ClientInvokeCallback
{
get
{
CheckInitialized();
return RuntimeClient.ClientInvokeCallback;
}
set
{
CheckInitialized();
RuntimeClient.ClientInvokeCallback = value;
}
}
internal static IStreamProviderRuntime CurrentStreamProviderRuntime
{
get
{
CheckInitialized();
return client.StreamProviderRuntime;
}
}
[Obsolete(DeprecationMessage)]
public static IStreamProvider GetStreamProvider(string name)
{
CheckInitialized();
return client.GetStreamProvider(name);
}
[Obsolete(DeprecationMessage + " Please use the AddClusterConnectionLostHandler extension method on IClientBuilder.")]
public static event ConnectionToClusterLostHandler ClusterConnectionLost
{
add
{
CheckInitialized();
RuntimeClient.ClusterConnectionLost += value;
}
remove
{
CheckInitialized();
RuntimeClient.ClusterConnectionLost -= value;
}
}
private static OutsideRuntimeClient RuntimeClient => client.ServiceProvider.GetRequiredService<OutsideRuntimeClient>();
}
}