forked from Azure/azure-functions-host
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLanguageWorkerChannel.cs
420 lines (371 loc) · 16.4 KB
/
LanguageWorkerChannel.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks.Dataflow;
using Microsoft.Azure.WebJobs.Script.Description;
using Microsoft.Azure.WebJobs.Script.Eventing;
using Microsoft.Azure.WebJobs.Script.Eventing.Rpc;
using Microsoft.Azure.WebJobs.Script.Grpc.Messages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using FunctionMetadata = Microsoft.Azure.WebJobs.Script.Description.FunctionMetadata;
using MsgType = Microsoft.Azure.WebJobs.Script.Grpc.Messages.StreamingMessage.ContentOneofCase;
namespace Microsoft.Azure.WebJobs.Script.Rpc
{
internal class LanguageWorkerChannel : ILanguageWorkerChannel
{
private readonly TimeSpan timeoutStart = TimeSpan.FromSeconds(20);
private readonly TimeSpan timeoutInit = TimeSpan.FromSeconds(20);
private readonly ScriptHostConfiguration _scriptConfig;
private readonly IScriptEventManager _eventManager;
private readonly IWorkerProcessFactory _processFactory;
private readonly IProcessRegistry _processRegistry;
private readonly IObservable<FunctionRegistrationContext> _functionRegistrations;
private readonly WorkerConfig _workerConfig;
private readonly Uri _serverUri;
private readonly ILogger _logger;
private string _workerId;
private Process _process;
private IDictionary<string, BufferBlock<ScriptInvocationContext>> _functionInputBuffers = new Dictionary<string, BufferBlock<ScriptInvocationContext>>();
private IDictionary<string, Exception> _functionLoadErrors = new Dictionary<string, Exception>();
private ConcurrentDictionary<string, ScriptInvocationContext> _executingInvocations = new ConcurrentDictionary<string, ScriptInvocationContext>();
private IObservable<InboundEvent> _inboundWorkerEvents;
private List<IDisposable> _inputLinks = new List<IDisposable>();
private List<IDisposable> _eventSubscriptions = new List<IDisposable>();
private IDisposable _startSubscription;
private JsonSerializerSettings _verboseSerializerSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
Converters = new List<JsonConverter>()
{
new StringEnumConverter()
}
};
private bool disposedValue;
public LanguageWorkerChannel(
ScriptHostConfiguration scriptConfig,
IScriptEventManager eventManager,
IWorkerProcessFactory processFactory,
IProcessRegistry processRegistry,
IObservable<FunctionRegistrationContext> functionRegistrations,
WorkerConfig workerConfig,
Uri serverUri,
ILoggerFactory loggerFactory)
{
_workerId = Guid.NewGuid().ToString();
_scriptConfig = scriptConfig;
_eventManager = eventManager;
_processFactory = processFactory;
_processRegistry = processRegistry;
_functionRegistrations = functionRegistrations;
_workerConfig = workerConfig;
_serverUri = serverUri;
_logger = loggerFactory.CreateLogger($"Worker.{workerConfig.Language}.{_workerId}");
_inboundWorkerEvents = _eventManager.OfType<InboundEvent>()
.Where(msg => msg.WorkerId == _workerId);
_eventSubscriptions.Add(_inboundWorkerEvents
.Where(msg => msg.MessageType == MsgType.RpcLog)
.Subscribe(Log));
if (scriptConfig.LogFilter.Filter("Worker", LogLevel.Trace))
{
_eventSubscriptions.Add(_eventManager.OfType<RpcEvent>()
.Where(msg => msg.WorkerId == _workerId)
.Subscribe(msg =>
{
var jsonMsg = JsonConvert.SerializeObject(msg, _verboseSerializerSettings);
_logger.LogTrace(jsonMsg);
}));
}
_eventSubscriptions.Add(_eventManager.OfType<FileEvent>()
.Where(msg => Path.GetExtension(msg.FileChangeArguments.FullPath) == Config.Extension)
.Throttle(TimeSpan.FromMilliseconds(300)) // debounce
.Subscribe(msg => _eventManager.Publish(new HostRestartEvent())));
StartWorker();
}
public string Id => _workerId;
public WorkerConfig Config => _workerConfig;
// start worker process and wait for an rpc start stream response
internal void StartWorker()
{
_startSubscription = _inboundWorkerEvents.Where(msg => msg.MessageType == MsgType.StartStream)
.Timeout(timeoutStart)
.Take(1)
.Subscribe(InitWorker, HandleWorkerError);
var workerContext = new WorkerCreateContext()
{
RequestId = Guid.NewGuid().ToString(),
MaxMessageLength = _scriptConfig.MaxMessageLengthBytes,
WorkerId = _workerId,
Arguments = _workerConfig.Arguments,
WorkingDirectory = _scriptConfig.RootScriptPath,
ServerUri = _serverUri,
};
_process = _processFactory.CreateWorkerProcess(workerContext);
StartProcess(_workerId, _process);
_processRegistry?.Register(_process);
}
// send capabilities to worker, wait for WorkerInitResponse
internal void InitWorker(RpcEvent startEvent)
{
_inboundWorkerEvents.Where(msg => msg.MessageType == MsgType.WorkerInitResponse)
.Timeout(timeoutInit)
.Take(1)
.Subscribe(WorkerReady, HandleWorkerError);
Send(new StreamingMessage
{
WorkerInitRequest = new WorkerInitRequest()
{
HostVersion = ScriptHost.Version
}
});
}
internal void WorkerReady(RpcEvent initEvent)
{
var initMessage = initEvent.Message.WorkerInitResponse;
if (initMessage.Result.IsFailure(out Exception exc))
{
HandleWorkerError(exc);
return;
}
// subscript to all function registrations in order to load functions
_eventSubscriptions.Add(_functionRegistrations.Subscribe(Register));
_eventSubscriptions.Add(_inboundWorkerEvents.Where(msg => msg.MessageType == MsgType.FunctionLoadResponse)
.Subscribe((msg) => LoadResponse(msg.Message.FunctionLoadResponse)));
_eventSubscriptions.Add(_inboundWorkerEvents.Where(msg => msg.MessageType == MsgType.InvocationResponse)
.Subscribe((msg) => InvokeResponse(msg.Message.InvocationResponse)));
_eventManager.Publish(new WorkerReadyEvent
{
Id = _workerId,
Version = initMessage.WorkerVersion,
Capabilities = initMessage.Capabilities,
Config = _workerConfig,
});
}
public void Register(FunctionRegistrationContext context)
{
FunctionMetadata metadata = context.Metadata;
// associate the invocation input buffer with the function
_functionInputBuffers[context.Metadata.FunctionId] = context.InputBuffer;
// send a load request for the registered function
FunctionLoadRequest request = new FunctionLoadRequest()
{
FunctionId = metadata.FunctionId,
Metadata = new RpcFunctionMetadata()
{
Name = metadata.Name,
Directory = metadata.FunctionDirectory,
EntryPoint = metadata.EntryPoint ?? string.Empty,
ScriptFile = metadata.ScriptFile ?? string.Empty
}
};
foreach (var binding in metadata.Bindings)
{
request.Metadata.Bindings.Add(binding.Name, new BindingInfo
{
Direction = (BindingInfo.Types.Direction)binding.Direction,
Type = binding.Type
});
}
Send(new StreamingMessage
{
FunctionLoadRequest = request
});
}
internal void LoadResponse(FunctionLoadResponse loadResponse)
{
if (loadResponse.Result.IsFailure(out Exception ex))
{
//Cache function load errors to replay error messages on invoking failed functions
_functionLoadErrors[loadResponse.FunctionId] = ex;
}
var inputBuffer = _functionInputBuffers[loadResponse.FunctionId];
// link the invocation inputs to the invoke call
var invokeBlock = new ActionBlock<ScriptInvocationContext>(ctx => Invoke(ctx));
var disposableLink = inputBuffer.LinkTo(invokeBlock);
_inputLinks.Add(disposableLink);
}
public void Invoke(ScriptInvocationContext context)
{
if (_functionLoadErrors.ContainsKey(context.FunctionMetadata.FunctionId))
{
_logger.LogTrace($"Function {context.FunctionMetadata.Name} failed to load");
context.ResultSource.TrySetException(_functionLoadErrors[context.FunctionMetadata.FunctionId]);
_executingInvocations.TryRemove(context.ExecutionContext.InvocationId.ToString(), out ScriptInvocationContext _);
}
else
{
if (context.CancellationToken.IsCancellationRequested)
{
context.ResultSource.SetCanceled();
return;
}
var functionMetadata = context.FunctionMetadata;
InvocationRequest invocationRequest = new InvocationRequest()
{
FunctionId = functionMetadata.FunctionId,
InvocationId = context.ExecutionContext.InvocationId.ToString(),
};
foreach (var pair in context.BindingData)
{
invocationRequest.TriggerMetadata.Add(pair.Key, pair.Value.ToRpc());
}
foreach (var input in context.Inputs)
{
invocationRequest.InputData.Add(new ParameterBinding()
{
Name = input.name,
Data = input.val.ToRpc()
});
}
_executingInvocations.TryAdd(invocationRequest.InvocationId, context);
Send(new StreamingMessage
{
InvocationRequest = invocationRequest
});
}
}
internal void InvokeResponse(InvocationResponse invokeResponse)
{
if (_executingInvocations.TryRemove(invokeResponse.InvocationId, out ScriptInvocationContext context)
&& invokeResponse.Result.IsSuccess(context.ResultSource))
{
IDictionary<string, object> bindingsDictionary = invokeResponse.OutputData
.ToDictionary(binding => binding.Name, binding => binding.Data.ToObject());
var result = new ScriptInvocationResult()
{
Outputs = bindingsDictionary,
Return = invokeResponse?.ReturnValue?.ToObject()
};
context.ResultSource.SetResult(result);
}
}
internal void Log(RpcEvent msg)
{
var rpcLog = msg.Message.RpcLog;
LogLevel logLevel = (LogLevel)rpcLog.Level;
if (_executingInvocations.TryGetValue(rpcLog.InvocationId, out ScriptInvocationContext context))
{
// Restore the execution context from the original invocation. This allows AsyncLocal state to flow to loggers.
System.Threading.ExecutionContext.Run(context.AsyncExecutionContext, (s) =>
{
if (rpcLog.Exception != null)
{
var exception = new Rpc.RpcException(rpcLog.Message, rpcLog.Exception.Message, rpcLog.Exception.StackTrace);
context.Logger.Log(logLevel, new EventId(0, rpcLog.EventId), rpcLog.Message, exception, (state, exc) => state);
}
else
{
context.Logger.Log(logLevel, new EventId(0, rpcLog.EventId), rpcLog.Message, null, (state, exc) => state);
}
}, null);
}
else
{
_logger.Log(logLevel, new EventId(0, rpcLog.EventId), rpcLog.Message, null, (state, exc) => state);
}
}
internal void HandleWorkerError(Exception exc)
{
_startSubscription?.Dispose();
// unlink function inputs
foreach (var link in _inputLinks)
{
link.Dispose();
}
_logger.LogError(exc, $"Worker encountered an error.");
_eventManager.Publish(new WorkerErrorEvent(Id, exc));
}
// TODO: move this out of LanguageWorkerChannel to WorkerProcessFactory
internal void StartProcess(string workerId, Process process)
{
process.ErrorDataReceived += (sender, e) =>
{
// Java logs to stderr by default
// TODO: per language stdout/err parser?
if (e.Data != null)
{
if (e.Data.IndexOf("warn", StringComparison.OrdinalIgnoreCase) > -1)
{
_logger.LogWarning(e.Data);
}
else if (e.Data.IndexOf("error", StringComparison.OrdinalIgnoreCase) > -1)
{
_logger.LogError(e.Data);
}
else
{
_logger.LogInformation(e.Data);
}
}
};
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
_logger.LogInformation(e.Data);
}
};
process.EnableRaisingEvents = true;
process.Exited += (s, e) =>
{
try
{
if (process.ExitCode != 0)
{
HandleWorkerError(new Exception($"{process.StartInfo.FileName} process with pid {process.Id} exited with code {process.ExitCode}"));
}
process.WaitForExit();
process.Close();
}
catch
{
HandleWorkerError(new Exception("Worker process is not attached"));
}
};
_logger.LogInformation($"Starting language worker process: {process.StartInfo.FileName} {process.StartInfo.Arguments}");
process.Start();
_logger.LogInformation($"{process.StartInfo.FileName} process with Id: {process.Id} started");
process.BeginErrorReadLine();
process.BeginOutputReadLine();
}
private void Send(StreamingMessage msg)
{
_eventManager.Publish(new OutboundEvent(_workerId, msg));
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// best effort process disposal
try
{
_process?.Kill();
_process?.Dispose();
}
catch
{
}
foreach (var sub in _eventSubscriptions)
{
sub.Dispose();
}
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}