gRPC 无法连接到所有地址或服务的 DNS 解析失败

gRPC failed to connect to all addresses or DNS resolution failed for service

我目前正在尝试获取 gRPC 工作的示例。我正在使用 C# Asp.NET Core WebApi 作为服务器,我尝试通过 Python 客户端连接到它。

资源

我的原型文件:

syntax = "proto3";

service Example {
  rpc Insert (InsertRequest) returns (Empty);
  rpc Update (UpdateRequest) returns (Empty);
  rpc Delete (DeleteRequest) returns (Empty);
}

message InsertRequest {
    int32 Value = 1;
}

message UpdateRequest {
  string Id = 1;
  int32 Value = 2;
}

message DeleteRequest {
  string Id = 1;
}

message Empty { }

Python 客户:

import grpc

import example_pb2
import example_pb2_grpc

with grpc.insecure_channel('localhost:5001') as channel:
    stub = example_pb2_grpc.ExampleStub(channel)
    stub.Insert(example_pb2.InsertRequest(Value = 155))

问题

当我尝试 运行 我的 Python 客户端时,出现以下错误:

Traceback (most recent call last): File "gRPCExampleClient.py", line 10, in stub.Insert(example_pb2.InsertRequest(Value = 155)) File "C:\Python38\lib\site-packages\grpc_channel.py", line 923, in call return _end_unary_response_blocking(state, call, False, None) File "C:\Python38\lib\site-packages\grpc_channel.py", line 826, in _end_unary_response_blocking raise _InactiveRpcError(state) grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.UNAVAILABLE details = "failed to connect to all addresses" debug_error_string = "{"created":"@1612810257.299000000","description":"Failed to pick subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":5391,"referenced_errors":[{"created":"@1612810257.299000000","description":"failed to connect to all addresses","file":"src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc","file_line":398,"grpc_status":14}]}"

到目前为止我尝试了什么

    class Program
    {
        static void Main(string[] args)
        {
            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Example.ExampleClient(channel);

            client.Insert(new InsertRequest() { Value = 155 });

            Console.ReadKey(true);
        }
    }

Traceback (most recent call last): File "gRPCExampleClient.py", line 10, in stub.Insert(example_pb2.InsertRequest(Value = 155)) File "C:\Python38\lib\site-packages\grpc_channel.py", line 923, in call return _end_unary_response_blocking(state, call, False, None) File "C:\Python38\lib\site-packages\grpc_channel.py", line 826, in _end_unary_response_blocking raise _InactiveRpcError(state) grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.UNAVAILABLE details = "DNS resolution failed for service: https://localhost:5001" debug_error_string = "{"created":"@1612809227.889000000","description":"Resolver transient failure","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":2141,"referenced_errors":[{"created":"@1612809227.889000000","description":"DNS resolution failed for service: https://localhost:5001","file":"src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc","file_line":201,"grpc_status":14,"referenced_errors":[{"created":"@1612809227.889000000","description":"OS Error","file":"src/core/lib/iomgr/resolve_address_windows.cc","file_line":95,"os_error":"No such host is known.\r\n","syscall":"getaddrinfo","wsa_error":11001}]}]}"

from os import environ

environ["GRPC_DNS_RESOLVER"] = "native"

杂项信息

我希望我只是遗漏了一些明显的东西,感谢您阅读并考虑提供帮助。

请参阅https://github.com/grpc/grpc/blob/master/doc/naming.md

“https”的使用不正确

我终于想通了。根本问题是我的服务器配置不匹配。由于 C# 客户端会自动检测到由 dotnet 设置的 ASP.NET 核心开发证书,因此它将能够安全地连接到服务器。 python 和 go 等所有其他脚本语言将无法执行此操作并拒绝连接,因为无法验证证书。 (这是完全正确的,它仍然只是一个用于调试的自签名证书)

简而言之:您不能不安全地连接到 gRPC 服务器,除非它明确设置为通过 HTTP/2 提供不安全的 http 请求。

所以我们现在有两个选择:

  1. 明确向我们的脚本客户端提供证书 public 密钥,以便他们知道他们可以信任我们的服务器
  2. 使用 HTTP/2
  3. 以非 SSL 模式启动我们的服务器

1

导出我使用的 asp.net 核心开发证书 certmgr。 使用此工具,我们可以将开发证书的 public 密钥部分导出为 .cer 文件。 在此之后,我们只需要告诉我们的客户端建立安全连接并根据我们刚刚导出的 public 密钥进行验证:

with open('../dev-cert.cer', 'rb') as f: #manually import public key of localhost ASP.NET Core dev certioficate (exported with certmgr)
        credentials = grpc.ssl_channel_credentials(f.read())
with grpc.secure_channel('localhost:5001', credentials) as channel:
    stub = example_pb2_grpc.ExampleStub(channel)
    stub.Insert(example_pb2.InsertRequest(Value = 155))

我也在 go 中测试了所有这些(以验证它不仅仅是 python 库问题)

func main() {
    creds, err := credentials.NewClientTLSFromFile("../dev-cert.cer", "")
    if err != nil {
        log.Fatalf("could not process the credentials: %v", err)
    }

    conn, err := grpc.Dial("localhost:5001", grpc.WithTransportCredentials(creds))

    if err != nil {
        log.Fatalf("did not connect: %s", err)
    }
    defer conn.Close()

    request := example_grpc_client.InsertRequest{
        Value: 123,
    }

    client := example_grpc_client.NewExampleClient(conn)

    _, err = client.Insert(context.Background(), &request)
    if err != nil {
        log.Fatalf("error sending message: %s", err)
    }
}

2

这是我找到的第一个解决方案,但我不推荐使用这个,因为它只是一种解决方法。 通过配置我的服务器应用程序,我能够通过配置 kestrel 在 HTTP/2 中启动并支持不安全连接来获得不安全连接:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(options => 
                    {
                        options.ListenLocalhost(5001, o => o.Protocols = HttpProtocols.Http2);
                    });

                    webBuilder.UseStartup<Startup>();
                });