YARP Docsv2.3
Documentação/Operações/Diagnosticando proxies baseados em YARP

Diagnosticando proxies baseados em YARP

Ao usar um proxy reverso, há um salto adicional do cliente para o proxy e depois

Ao usar um proxy reverso, há um salto adicional do cliente para o proxy e, em seguida, do proxy para o destino, o que aumenta as chances de algo dar errado. Este tópico traz algumas dicas e sugestões sobre como depurar e diagnosticar problemas quando eles ocorrem. Ele pressupõe que o proxy já esteja em execução e, portanto, não aborda problemas de inicialização, como erros de configuração.

Registro em log

O primeiro passo para conseguir identificar o que está acontecendo com o YARP é habilitar o registro em log. Trata-se de um sinalizador de configuração, portanto pode ser alterado em tempo real. O YARP é implementado como um componente de middleware para o ASP.NET Core, então é necessário habilitar o registro em log tanto para o YARP quanto para o ASP.NET a fim de obter o panorama completo do que está acontecendo.

Por padrão, o ASP.NET registra logs no console, e o arquivo de configuração pode ser usado para controlar o nível de registro em log.

JSON       //Sets the Logging level for ASP.NET
       "Logging": {
          "LogLevel": {
             "Default": "Information",
             // Uncomment to hide diagnostic messages from runtime and proxy
             // "Microsoft": "Warning",
             // "Yarp" : "Warning",
             "Microsoft.Hosting.Lifetime": "Information"
          }
       },
You want logging information from the Microsoft.AspNetCore.\* and Yarp.ReverseProxy.\*
providers. The preceding example emits Information -level events from both providers to the
console. Changing the level to Debug shows additional entries. ASP.NET implements change
detection for configuration files, so you can edit the appsettings.json file (or
appsettings.development.json for the Development environment) while the project is running
and observe changes to the log output.
 Note
Settings in the appsettings.development.json file override settings in appsettings.json
when running in the Development environment, so make sure that if you are editing
appsettings.json that the values aren't overridden.

Entendendo as entradas de log

A saída do registro em log está diretamente ligada à forma como o ASP.NET Core processa as solicitações. É importante perceber que, como middleware, o YARP depende de boa parte da funcionalidade do ASP.NET para processar as solicitações; a seguir está, por exemplo, o processamento de uma solicitação com o modo "Debug" habilitado:

Level Log Message Description

dbug Microsoft.AspNetCore.Server.Kestrel.Connections[39] Connections are Connection id "0HMCD0JK7K51U" accepted. independent of requests, so this is a new connection

dbug Microsoft.AspNetCore.Server.Kestrel.Connections[1] Connection id "0HMCD0JK7K51U" started.

info Microsoft.AspNetCore.Hosting.Diagnostics[1] This is the incoming Request starting HTTP/1.1 GET http://localhost:5000/ - - request to ASP.NET

dbug Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[0] My configuration does Wildcard detected, all requests with hosts will be allowed. not tie endpoints to specific hostnames

dbug Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1001] This shows what 1 candidate(s) found for the request path '/' possible matches there are for the route

dbug Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1005] The minimum route Endpoint 'minimumroute' with route pattern '{**catch-all}' is valid for from YARPs the request path '/' configuration has matched

dbug Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware[1] Request matched endpoint 'minimumroute'

info Microsoft.AspNetCore.Routing.EndpointMiddleware[0] Executing endpoint 'minimumroute'

info Yarp.ReverseProxy.Forwarder.HttpForwarder[9] YARP is proxying the Proxying to http://www.example.com/ request to example.com

info Microsoft.AspNetCore.Routing.EndpointMiddleware[1] Executed endpoint 'minimumroute'

Level Log Message Description

dbug Microsoft.AspNetCore.Server.Kestrel.Connections[9] The response has Connection id "0HMCD0JK7K51U" completed keep alive response. finished, but connection can be kept alive.

info Microsoft.AspNetCore.Hosting.Diagnostics[2] The response completed Request finished HTTP/1.1 GET http://localhost:5000/ - - - 200 1256 with status code 200, text/html;+charset=utf-8 12.7797ms responding with 1256 bytes as text/html in ~13ms.

dbug Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[6] Diagnostic information Connection id "0HMCD0JK7K51U" received FIN. about the connection to determine who closed it and how cleanly

dbug Microsoft.AspNetCore.Server.Kestrel.Connections[10] Connection id "0HMCD0JK7K51U" disconnecting.

dbug Microsoft.AspNetCore.Server.Kestrel.Connections[2] Connection id "0HMCD0JK7K51U" stopped.

dbug Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[7] Connection id "0HMCD0JK7K51U" sending FIN because: "The Socket transport's send loop completed gracefully."

O texto acima fornece informações gerais sobre a solicitação e como ela foi processada.

Usando o registro em log de solicitações do ASP.NET

O ASP.NET inclui um componente de middleware que pode ser usado para fornecer mais detalhes sobre a solicitação e a resposta. O componente UseHttpLogging pode ser adicionado ao pipeline de solicitações, o que adiciona entradas extras ao log detalhando os cabeçalhos de solicitação de entrada e saída.

C#   app.UseHttpLogging();
   // Enable endpoint routing, required for the reverse proxy
   app.UseRouting();
   // Register the reverse proxy routes
   app.MapReverseProxy();
For example:
Consoleinfo: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1]
         Request:
         Protocol: HTTP/1.1
         Method: GET
         Scheme: http
         PathBase:
         Path: /
         Accept: */*
         Host: localhost:5000
         User-Agent: curl/7.55.1
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2]
         Response:
         StatusCode: 200
         Content-Type: text/html; charset=utf-8
         Date: Tue, 12 Oct 2021 23:29:20 GMT
         Server: ECS,(sec/97A5)
         Age: 113258
         Cache-Control: [Redacted]
         ETag: [Redacted]
         Expires: Tue, 19 Oct 2021 23:29:20 GMT
         Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
         Vary: [Redacted]
         Content-Length: 1256
         X-Cache: [Redacted]

Usando eventos de telemetria

Recomendamos a leitura de Networking telemetry in .NET como uma introdução sobre como consumir telemetria de rede no .NET.

O exemplo do Metrics mostra como escutar os eventos dos diferentes provedores que coletam telemetria como parte do YARP. Os mais importantes do ponto de vista de diagnóstico são:

ForwarderTelemetryConsumer HttpClientTelemetryConsumer

Para usar qualquer um deles, crie uma classe que implemente uma interface Yarp.Telemetry.Consumption, como IForwarderTelemetryConsumer:

C#public class ForwarderTelemetry : IForwarderTelemetryConsumer
{
      /// Called before forwarding a request.
      public void OnForwarderStart(DateTime timestamp, string destinationPrefix)
      {
             Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
                   $"OnForwarderStart :: Destination prefix: {destinationPrefix}");
                 }
/// Called after forwarding a request.
public void OnForwarderStop(DateTime timestamp, int statusCode)
{
      Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
             $"OnForwarderStop :: Status: {statusCode}");
}
      /// Called before <see cref="OnForwarderStop(DateTime, int)"/> if forwarding
the request failed.
      public void OnForwarderFailed(DateTime timestamp, ForwarderError error)
      {
             Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
                   $"OnForwarderFailed :: Error: {error.ToString()}");
      }
/// Called when reaching a given stage of forwarding a request.
public void OnForwarderStage(DateTime timestamp, ForwarderStage stage)
{
      Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
             $"OnForwarderStage :: Stage: {stage.ToString()}");
}
      /// Called periodically while a content transfer is active.
      public void OnContentTransferring(DateTime timestamp, bool isRequest, long
contentLength,
             long iops, TimeSpan readTime, TimeSpan writeTime)
      {
             Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
                   $"OnContentTransferring :: Is request: {isRequest}, Content length:
{contentLength}, " +
                   $"IOps: {iops}, Read time: {readTime:s\\.fff}, Write time:
{writeTime:s\\.fff}");
      }
      /// Called after transferring the request or response content.
      public void OnContentTransferred(DateTime timestamp, bool isRequest, long con-
tentLength,
             long iops, TimeSpan readTime, TimeSpan writeTime, TimeSpan firstReadTime)
      {
             Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
                   $"OnContentTransferred :: Is request: {isRequest}, Content length:
{contentLength}, " +
                   $"IOps: {iops}, Read time: {readTime:s\\.fff}, Write time:
{writeTime:s\\.fff}");
      }
      /// Called before forwarding a request from `ForwarderMiddleware`, therefore
is not called for direct forwarding scenarios.
      public void OnForwarderInvoke(DateTime timestamp, string clusterId, string
routeId,
             string destinationId)
      {
             Console.WriteLine($"Forwarder Telemetry [{timestamp:HH:mm:ss.fff}] => " +
                   $"OnForwarderInvoke:: Cluster id: {clusterId}, Route Id: {routeId},
Destination: {destinationId}");
   }
}
Register the class as part of services, for example:
C#   services.AddTelemetryConsumer<ForwarderTelemetry>();
   // Add the reverse proxy to capability to the server
   var proxyBuilder = services.AddReverseProxy();
   // Initialize the reverse proxy from the "ReverseProxy" section of configuration
   proxyBuilder.LoadFromConfig(Configuration.GetSection("ReverseProxy"));
Details are logged on each part of the request, for example:
Console   Forwarder Telemetry [06:40:48.186] => OnForwarderInvoke::
          Cluster id: minimumcluster, Route Id: minimumroute, Destination: example.com
   Forwarder Telemetry [06:41:00.269] => OnForwarderStart ::
          Destination prefix: http://www.example.com/
   Forwarder Telemetry [06:41:00.298] => OnForwarderStage :: Stage: SendAsyncStart
   Forwarder Telemetry [06:41:00.507] => OnForwarderStage :: Stage: SendAsyncStop
   Forwarder Telemetry [06:41:00.530] => OnForwarderStage :: Stage:
          ResponseContentTransferStart
   Forwarder Telemetry [06:41:03.655] => OnForwarderStop :: Status: 200
The events for telemetry are fired as they occur, so you can obtain the HttpContext and the
YARP feature from it:
C#   services.AddTelemetryConsumer<ForwarderTelemetry>();
   services.AddHttpContextAccessor();
   ...
   public void OnForwarderInvoke(DateTime timestamp, string clusterId, string
   routeId,
          string destinationId)
   {
          var context = new HttpContextAccessor().HttpContext;
          var YarpFeature = context.GetReverseProxyFeature();
          var dests = from d in YarpFeature.AvailableDestinations
                 select d.Model.Config.Address;
   Console.WriteLine($"Destinations: {string.Join(", ", dests)}");
}

Usando middleware personalizado

Outra forma de inspecionar o estado das solicitações é inserir middleware adicional no pipeline de solicitações. É possível inserir esse middleware entre os outros estágios para ver o estado da solicitação.

C#   // We can customize the proxy pipeline and add/remove/replace steps
   app.MapReverseProxy(proxyPipeline =>
   {
          // Use a custom proxy middleware, defined below
          proxyPipeline.Use(MyCustomProxyStep);
          // Don't forget to include these two middleware when you make a custom proxy
   pipeline (if you need them).
          proxyPipeline.UseSessionAffinity();
          proxyPipeline.UseLoadBalancing();
   });
   ...
   public Task MyCustomProxyStep(HttpContext context, Func<Task> next)
   {
          // Can read data from the request via the context
          foreach (var header in context.Request.Headers)
          {
                 Console.WriteLine($"{header.Key}: {header.Value}");
          }
          // The context also stores a ReverseProxyFeature which holds proxy specific
   data such as the cluster, route and destinations
          var proxyFeature = context.GetReverseProxyFeature();
   Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(proxyFeature.Route.Con
   fig));
          // Important - required to move to the next step in the proxy pipeline
          return next();
   }
You can also use ASP.NET middleware within Configure that will enable you to inspect the
request before the proxy pipeline.
 Note
The proxy streams the response from the destination server back to the client, so the
response headers and body aren't readily accessible via middleware.

Usando o depurador

Um depurador, como o Visual Studio, pode ser anexado ao processo do proxy. No entanto, a menos que você já tenha middleware existente, não há um bom lugar no código do aplicativo para interromper a execução e inspecionar o estado da solicitação. Por isso, o ideal é usar o depurador em conjunto com uma das técnicas anteriores, de modo a ter pontos específicos para inserir pontos de interrupção.

Rastreamento de rede

Pode parecer atraente usar ferramentas de rastreamento de rede, como Fiddler ou Wireshark, para tentar monitorar o que está acontecendo em ambos os lados do proxy. No entanto, é preciso cautela ao usar essas ferramentas:

O Fiddler se registra como um proxy e depende de os aplicativos usarem o proxy padrão para conseguir monitorar o tráfego. Isso funciona para o tráfego de entrada de um navegador até o YARP, mas não captura as solicitações de saída, já que o YARP é configurado para não usar as configurações de proxy no tráfego de saída. No Windows, o Wireshark usa o Npcap para capturar dados de pacotes do tráfego de rede, portanto captura tanto o tráfego de entrada quanto o de saída e pode ser usado para monitorar o tráfego HTTP. O tráfego HTTPS é criptografado e não pode ser descriptografado automaticamente por ferramentas de monitoramento de rede. Cada ferramenta tem soluções alternativas que podem permitir o monitoramento do tráfego, mas elas exigem o uso arriscado de certificados e alterações nas relações de confiança. Como o YARP está fazendo solicitações de saída, as técnicas usadas para enganar navegadores não se aplicam ao processo do YARP.

A escolha do protocolo para o tráfego de saída é feita com base na URL de destino na configuração do cluster. Se o monitoramento de tráfego for usado para diagnóstico, alterar as URLs de saída para http://, quando possível, pode ser a abordagem mais simples para permitir que as ferramentas de monitoramento funcionem, desde que os problemas diagnosticados não estejam relacionados ao protocolo de transporte.

Nota

O autor criou este artigo com a ajuda de IA. Saiba mais

Adaptado do Microsoft Learn , licenciado sob CC BY 4.0 .