登录
首页 >  Golang >  Go问答

是否有已知的限制在Golang中设置网络命名空间后启动GRPC?

来源:stackoverflow

时间:2024-03-23 15:18:35 459浏览 收藏

在 Golang 中切换网络命名空间后,在 GRPC 客户端和服务器之间建立通信时,可能存在限制。当命名空间切换在客户端内部执行时,通信会失败,而当在服务器内部执行时,通信正常工作。问题可能与 GRPC 客户端是否会产生额外的 goroutine 有关,这些 goroutine 不会在与原始 goroutine 相同的命名空间中执行,因为命名空间切换需要锁定线程。

问题内容

在我的 golang 项目中切换网络命名空间后,我遇到了 grpc 客户端和服务器之间通信的问题。为了解决这个问题,我对grpc示例程序hello world进行了相应的修改,结果还是出现了同样的问题。在 golang 应用程序中切换命名空间后使用 grpc 是否有任何已知的限制?

我读过有关 golang 中切换命名空间的问题,但我想这取决于 grpc 行为是否会导致问题。

  1. grpc 客户端是否会产生任何额外的 goroutine?这样的 goroutine 不一定会在同一个命名空间中执行,因为原始 goroutine 由于命名空间切换而锁定了线程。

  2. 我假设 grpc 服务器为每个客户端生成 goroutine,但在生成新 goroutine 之前,它是否会在原始 goroutine 中创建套接字?这个问题还与生成的 goroutine 不必在调用 grpc.serve() 的同一命名空间中执行(命名空间切换需要 runtime.lockosthread())有关。

如果服务器和客户端在匹配的命名空间(ip netns exec...)中启动,则通信有效,但如果在客户端内部执行命名空间切换,则通信失败。当命名空间切换在服务器内部进行时,通信也能正常工作,所以问题应该出在客户端。

greeter_client/main.go:

package main

import (
    "fmt"
    "log"
    "os"
    "runtime"
    "syscall"
    "time"

    pb "grpctest/helloworld/helloworld"

    "github.com/vishvananda/netns"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
)

const (
    defaultname    = "world"
    defaultaddress = "localhost:50051"
    nsenv          = "namespace"
    addressenv     = "address"
    blockenv       = "dialblock"
)

func main() {
    fmt.printf("* client thread id before runtime.lockosthread(): %d\n", syscall.gettid())
    runtime.lockosthread()
    defer runtime.unlockosthread()
    fmt.printf("* client thread id after runtime.lockosthread(): %d\n", syscall.gettid())

    var dialopts []grpc.dialoption
    dialopts = append(dialopts, grpc.withinsecure())
    _, ok := os.lookupenv(blockenv)
    if ok == true {
        dialopts = append(dialopts, grpc.withblock())
        fmt.printf("* dial in blocked mode\n")
    } else {
        fmt.printf("* dial in unblocked mode\n")
    }

    address, ok := os.lookupenv(addressenv)
    if ok == false {
        address = defaultaddress
    }

    fmt.printf("* talk to server at %s\n", address)

    var origns netns.nshandle
    namespace, ok := os.lookupenv(nsenv)
    if ok {
        fmt.printf("* switch namespace to %s\n", namespace)
        origns, err := netns.get()
        if err != nil {
            log.fatal("failed to get current namespace")
        }

        defer origns.close()
        newns, err := netns.getfromname(namespace)
        if err != nil {
            log.fatalf("failed to get new namespace: %s", namespace)
        }

        err = netns.set(newns)
        if err != nil {
            log.fatalf("failed to set new namespace: %s", namespace)
        }

        defer newns.close()
    }

    fmt.printf("* client thread id before grpc.dial(): %d\n", syscall.gettid())
    // set up a connection to the server.
    conn, err := grpc.dial(address, dialopts...)
    if err != nil {
        log.fatalf("did not connect: %v", err)
    }
    defer conn.close()
    fmt.printf("* client thread id before pb.newgreeterclient(): %d\n", syscall.gettid())
    c := pb.newgreeterclient(conn)
    fmt.printf("* client thread id after pb.newgreeterclient(): %d\n", syscall.gettid())

    // contact the server and print out its response.
    name := defaultname
    if len(os.args) > 1 {
        name = os.args[1]
    }

    r, err := c.sayhello(context.background(), &pb.hellorequest{name: name})
    if err != nil {
        fmt.printf("could not greet: %v", err)
        select {}
        log.fatalf("could not greet: %v", err)
    }
    fmt.printf("* client thread id after c.sayhello(): %d\n", syscall.gettid())

    log.printf("greeting: %s", r.message)
    time.sleep(5 * time.second)

    if namespace != "" {
        netns.set(origns)
    }

    fmt.printf("* client thread id at exit: %d\n", syscall.gettid())
}

greeter_server/main.go:

package main

import (
    "fmt"
    "log"
    "net"
    "os"
    "runtime"
    "syscall"

    pb "grpctest/helloworld/helloworld"

    "github.com/vishvananda/netns"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"
)

const (
    port  = ":50051"
    nsEnv = "NAMESPACE"
)

// server is used to implement helloworld.GreeterServer.
type server struct{}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    fmt.Printf("* RPC call server thread id: %d\n", syscall.Gettid())
    return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

func main() {
    runtime.LockOSThread()
    defer runtime.UnlockOSThread()
    var origns netns.NsHandle

    namespace := os.Getenv(nsEnv)
    if namespace != "" {
        fmt.Printf("* Switch namespace to %s\n", namespace)
        origns, err := netns.Get()
        if err != nil {
            log.Fatal("failed to get current namespace")
        }

        defer origns.Close()
        newns, err := netns.GetFromName(namespace)
        if err != nil {
            log.Fatalf("failed to get new namespace: %s", namespace)
        }

        err = netns.Set(newns)
        if err != nil {
            log.Fatalf("failed to set new namespace: %s", namespace)
        }

        defer newns.Close()
    }

    fmt.Printf("* Main server thread id: %d\n", syscall.Gettid())
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    // Register reflection service on gRPC server.
    reflection.Register(s)

    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }

    if namespace != "" {
        netns.Set(origns)
    }

    fmt.Printf("* Main server exits (thread id: %d)\n", syscall.Gettid())
}

解决方案


我遇到了完全相同的问题,无论是否锁定操作系统线程,netns 都会在每个新 goroutine 上不断切换回原始名称空间。

我发现只要服务器在正确的网络中启动(我放弃尝试以编程方式执行此操作,只是通过 exec.command 生成服务器过程),您只需为 grpc 客户端设置一个自定义拨号器在连接到正确的netns期间恢复goroutine:

dialOpts = append(dialOpts, grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
        netns.Set(newns)
        return net.DialTimeout("tcp", addr, timeout)
    }))

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>