Skip to content

Commit ba112b7

Browse files
authored
Improve logging when a InvocationRequest is cancelled (#8987)
1 parent 8c97df8 commit ba112b7

File tree

2 files changed

+46
-42
lines changed

2 files changed

+46
-42
lines changed

src/WebJobs.Script.Grpc/Channel/GrpcWorkerChannel.cs

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ public async Task<WorkerStatus> GetWorkerStatusAsync()
297297
await tcs.Task;
298298
var elapsed = sw.GetElapsedTime();
299299
workerStatus.Latency = elapsed;
300-
_workerChannelLogger.LogDebug($"[HostMonitor] Worker status request took {elapsed.TotalMilliseconds}ms");
300+
_workerChannelLogger.LogDebug("[HostMonitor] Worker status request took {totalMs}ms", elapsed.TotalMilliseconds);
301301
}
302302
}
303303

@@ -373,14 +373,14 @@ internal void WorkerInitResponse(GrpcEvent initEvent)
373373

374374
_workerChannelLogger.LogDebug("Received WorkerInitResponse. Worker process initialized");
375375
_initMessage = initEvent.Message.WorkerInitResponse;
376-
_workerChannelLogger.LogDebug($"Worker capabilities: {_initMessage.Capabilities}");
376+
_workerChannelLogger.LogDebug("Worker capabilities: {capabilities}", _initMessage.Capabilities);
377377

378378
if (_initMessage.WorkerMetadata != null)
379379
{
380380
_initMessage.UpdateWorkerMetadata(_workerConfig);
381381
var workerMetadata = _initMessage.WorkerMetadata.ToString();
382382
_metricsLogger.LogEvent(MetricEventNames.WorkerMetadata, functionName: null, workerMetadata);
383-
_workerChannelLogger.LogDebug($"Worker metadata: {workerMetadata}");
383+
_workerChannelLogger.LogDebug("Worker metadata: {workerMetadata}", workerMetadata);
384384
}
385385

386386
if (_initMessage.Result.IsFailure(out Exception exc))
@@ -472,7 +472,7 @@ internal void SendFunctionLoadRequestCollection(IEnumerable<FunctionMetadata> fu
472472

473473
FunctionLoadRequestCollection functionLoadRequestCollection = GetFunctionLoadRequestCollection(functions, managedDependencyOptions);
474474

475-
_workerChannelLogger.LogDebug("Sending FunctionLoadRequestCollection with number of functions:'{count}'", functionLoadRequestCollection.FunctionLoadRequests.Count);
475+
_workerChannelLogger.LogDebug("Sending FunctionLoadRequestCollection with number of functions: '{count}'", functionLoadRequestCollection.FunctionLoadRequests.Count);
476476

477477
// send load requests for the registered functions
478478
SendStreamingMessage(new StreamingMessage
@@ -540,7 +540,7 @@ internal FunctionEnvironmentReloadRequest GetFunctionEnvironmentReloadRequest(ID
540540
internal void SendFunctionLoadRequest(FunctionMetadata metadata, ManagedDependencyOptions managedDependencyOptions)
541541
{
542542
_functionLoadRequestResponseEvent = _metricsLogger.LatencyEvent(MetricEventNames.FunctionLoadRequestResponse);
543-
_workerChannelLogger.LogDebug("Sending FunctionLoadRequest for function:'{functionName}' with functionId:'{functionId}'", metadata.Name, metadata.GetFunctionId());
543+
_workerChannelLogger.LogDebug("Sending FunctionLoadRequest for function: '{functionName}' with functionId: '{functionId}'", metadata.Name, metadata.GetFunctionId());
544544

545545
// send a load request for the registered function
546546
SendStreamingMessage(new StreamingMessage
@@ -566,7 +566,7 @@ internal FunctionLoadRequest GetFunctionLoadRequest(FunctionMetadata metadata, M
566566

567567
if (managedDependencyOptions != null && managedDependencyOptions.Enabled)
568568
{
569-
_workerChannelLogger?.LogDebug($"Adding dependency download request to {_workerConfig.Description.Language} language worker");
569+
_workerChannelLogger?.LogDebug("Adding dependency download request to {language} language worker", _workerConfig.Description.Language);
570570
request.ManagedDependencyEnabled = managedDependencyOptions.Enabled;
571571
}
572572

@@ -595,19 +595,19 @@ internal void LoadResponse(FunctionLoadResponse loadResponse)
595595
{
596596
if (functionLoadEx == null)
597597
{
598-
_workerChannelLogger?.LogError("Worker failed to to load function: '{functionName}' with function id: '{functionId}'. Function load exception is not set by the worker.", functionName, loadResponse.FunctionId);
598+
_workerChannelLogger?.LogError("Worker failed to to load function: '{functionName}' with functionId: '{functionId}'. Function load exception is not set by the worker.", functionName, loadResponse.FunctionId);
599599
}
600600
else
601601
{
602-
_workerChannelLogger?.LogError(functionLoadEx, "Worker failed to load function: '{functionName}' with function id: '{functionId}'.", functionName, loadResponse.FunctionId);
602+
_workerChannelLogger?.LogError(functionLoadEx, "Worker failed to load function: '{functionName}' with functionId: '{functionId}'.", functionName, loadResponse.FunctionId);
603603
}
604604
//Cache function load errors to replay error messages on invoking failed functions
605605
_functionLoadErrors[loadResponse.FunctionId] = functionLoadEx;
606606
}
607607

608608
if (loadResponse.IsDependencyDownloaded)
609609
{
610-
_workerChannelLogger?.LogDebug($"Managed dependency successfully downloaded by the {_workerConfig.Description.Language} language worker");
610+
_workerChannelLogger?.LogDebug("Managed dependency successfully downloaded by the {workerLanguage} language worker", _workerConfig.Description.Language);
611611
}
612612

613613
// link the invocation inputs to the invoke call
@@ -631,44 +631,47 @@ internal async Task SendInvocationRequest(ScriptInvocationContext context)
631631
{
632632
try
633633
{
634-
// do not send invocation requests for functions that failed to load or could not be indexed by the worker
634+
var invocationId = context.ExecutionContext.InvocationId.ToString();
635+
636+
// do not send an invocation request for functions that failed to load or could not be indexed by the worker
635637
if (_functionLoadErrors.ContainsKey(context.FunctionMetadata.GetFunctionId()))
636638
{
637-
_workerChannelLogger.LogDebug($"Function {context.FunctionMetadata.Name} failed to load");
639+
_workerChannelLogger.LogDebug("Function {functionName} failed to load", context.FunctionMetadata.Name);
638640
context.ResultSource.TrySetException(_functionLoadErrors[context.FunctionMetadata.GetFunctionId()]);
639-
_executingInvocations.TryRemove(context.ExecutionContext.InvocationId.ToString(), out ScriptInvocationContext _);
641+
_executingInvocations.TryRemove(invocationId, out ScriptInvocationContext _);
640642
return;
641643
}
642644
else if (_metadataRequestErrors.ContainsKey(context.FunctionMetadata.GetFunctionId()))
643645
{
644-
_workerChannelLogger.LogDebug($"Worker failed to load metadata for {context.FunctionMetadata.Name}");
646+
_workerChannelLogger.LogDebug("Worker failed to load metadata for {functionName}", context.FunctionMetadata.Name);
645647
context.ResultSource.TrySetException(_metadataRequestErrors[context.FunctionMetadata.GetFunctionId()]);
646-
_executingInvocations.TryRemove(context.ExecutionContext.InvocationId.ToString(), out ScriptInvocationContext _);
648+
_executingInvocations.TryRemove(invocationId, out ScriptInvocationContext _);
647649
return;
648650
}
649651

652+
// do not send an invocation request if cancellation has been requested
650653
if (context.CancellationToken.IsCancellationRequested)
651654
{
652-
_workerChannelLogger.LogDebug("Cancellation has been requested, cancelling invocation request");
653-
context.ResultSource.SetCanceled();
655+
_workerChannelLogger.LogWarning("Cancellation has been requested. The invocation request with id '{invocationId}' is cancelled and will not be sent to the worker.", invocationId);
656+
context.ResultSource.TrySetCanceled();
654657
return;
655658
}
656659

657660
var invocationRequest = await context.ToRpcInvocationRequest(_workerChannelLogger, _workerCapabilities, _isSharedMemoryDataTransferEnabled, _sharedMemoryManager);
658661
AddAdditionalTraceContext(invocationRequest.TraceContext.Attributes, context);
659662
_executingInvocations.TryAdd(invocationRequest.InvocationId, context);
660663

661-
if (_cancelCapabilityEnabled)
662-
{
663-
context.CancellationToken.Register(() => SendInvocationCancel(invocationRequest.InvocationId));
664-
}
665-
666664
_metricsLogger.LogEvent(string.Format(MetricEventNames.WorkerInvoked, Id), functionName: context.FunctionMetadata.Name);
667665

668666
await SendStreamingMessageAsync(new StreamingMessage
669667
{
670668
InvocationRequest = invocationRequest
671669
});
670+
671+
if (_cancelCapabilityEnabled)
672+
{
673+
context.CancellationToken.Register(() => SendInvocationCancel(invocationRequest.InvocationId));
674+
}
672675
}
673676
catch (Exception invokeEx)
674677
{
@@ -678,7 +681,7 @@ await SendStreamingMessageAsync(new StreamingMessage
678681

679682
internal void SendInvocationCancel(string invocationId)
680683
{
681-
_workerChannelLogger.LogDebug($"Sending invocation cancel request for InvocationId {invocationId}");
684+
_workerChannelLogger.LogDebug("Sending InvocationCancel request for invocation: '{invocationId}'", invocationId);
682685

683686
var invocationCancel = new InvocationCancel
684687
{
@@ -740,7 +743,7 @@ internal void ProcessFunctionMetadataResponses(FunctionMetadataResponse function
740743
}
741744
if (metadata.Status != null && metadata.Status.IsFailure(out Exception metadataRequestEx))
742745
{
743-
_workerChannelLogger.LogError($"Worker failed to index function {metadata.FunctionId}");
746+
_workerChannelLogger.LogError("Worker failed to index function {functionId}", metadata.FunctionId);
744747
_metadataRequestErrors[metadata.FunctionId] = metadataRequestEx;
745748
}
746749

@@ -824,7 +827,8 @@ private IList<string> GetOutputMaps(IList<ParameterBinding> bindings)
824827

825828
internal async Task InvokeResponse(InvocationResponse invokeResponse)
826829
{
827-
_workerChannelLogger.LogDebug("InvocationResponse received for invocation id: '{invocationId}'", invokeResponse.InvocationId);
830+
_workerChannelLogger.LogDebug("InvocationResponse received for invocation: '{invocationId}'", invokeResponse.InvocationId);
831+
828832
// Check if the worker supports logging user-code-thrown exceptions to app insights
829833
bool capabilityEnabled = !string.IsNullOrEmpty(_workerCapabilities.GetCapabilityState(RpcWorkerConstants.EnableUserCodeException));
830834

@@ -854,7 +858,7 @@ internal async Task InvokeResponse(InvocationResponse invokeResponse)
854858

855859
if (usedSharedMemory)
856860
{
857-
_workerChannelLogger.LogDebug("Shared memory usage for response of invocation Id: {Id} is {SharedMemoryUsage}", invokeResponse.InvocationId, logBuilder.ToString());
861+
_workerChannelLogger.LogDebug("Shared memory usage for response of invocation '{invocationId}' is {SharedMemoryUsage}", invokeResponse.InvocationId, logBuilder.ToString());
858862
}
859863

860864
IDictionary<string, object> bindingsDictionary = await invokeResponse.OutputData
@@ -876,7 +880,7 @@ internal async Task InvokeResponse(InvocationResponse invokeResponse)
876880
// Free memory allocated by the host (for input bindings) which was needed only for the duration of this invocation
877881
if (!_sharedMemoryManager.TryFreeSharedMemoryMapsForInvocation(invokeResponse.InvocationId))
878882
{
879-
_workerChannelLogger.LogWarning($"Cannot free all shared memory resources for invocation: {invokeResponse.InvocationId}");
883+
_workerChannelLogger.LogWarning("Cannot free all shared memory resources for invocation: {invocationId}", invokeResponse.InvocationId);
880884
}
881885

882886
// List of shared memory maps that were produced by the worker (for output bindings)
@@ -1152,7 +1156,7 @@ private void StopWorkerProcess()
11521156
GracePeriod = Duration.FromTimeSpan(TimeSpan.FromSeconds(gracePeriod))
11531157
};
11541158

1155-
_workerChannelLogger.LogDebug($"Sending WorkerTerminate message with grace period {gracePeriod} seconds.");
1159+
_workerChannelLogger.LogDebug("Sending WorkerTerminate message with grace period of {gracePeriod} seconds.", gracePeriod);
11561160

11571161
SendStreamingMessage(new StreamingMessage
11581162
{
@@ -1164,7 +1168,7 @@ private void StopWorkerProcess()
11641168

11651169
public async Task DrainInvocationsAsync()
11661170
{
1167-
_workerChannelLogger.LogDebug($"Count of in-buffer invocations waiting to be drained out: {_executingInvocations.Count}");
1171+
_workerChannelLogger.LogDebug("Count of in-buffer invocations waiting to be drained out: {invocationCount}", _executingInvocations.Count);
11681172
foreach (ScriptInvocationContext currContext in _executingInvocations.Values)
11691173
{
11701174
await currContext.ResultSource.Task;
@@ -1186,7 +1190,7 @@ public bool TryFailExecutions(Exception workerException)
11861190
foreach (ScriptInvocationContext currContext in _executingInvocations?.Values)
11871191
{
11881192
string invocationId = currContext?.ExecutionContext?.InvocationId.ToString();
1189-
_workerChannelLogger.LogDebug("Worker '{workerId}' encountered a fatal error. Failing invocation id: '{invocationId}'", _workerId, invocationId);
1193+
_workerChannelLogger.LogDebug("Worker '{workerId}' encountered a fatal error. Failing invocation: '{invocationId}'", _workerId, invocationId);
11901194
currContext?.ResultSource?.TrySetException(workerException);
11911195
_executingInvocations.TryRemove(invocationId, out ScriptInvocationContext _);
11921196
}

0 commit comments

Comments
 (0)