是否有已知的限制在Golang中设置网络命名空间后启动GRPC?
在 Golang 中切换网络命名空间后,在 GRPC 客户端和服务器之间建立通信时,可能存在限制。当命名空间切换在客户端内部执行时,通信会失败,而当在服务器内部执行时,通信正常工作。问题可能与 GRPC 客户端是否会产生额外的 goroutine 有关,这些 goroutine 不会在与原始 goroutine 相同的命名空间中执行,因为命名空间切换需要锁定线程。
在我的 golang 项目中切换网络命名空间后,我遇到了 grpc 客户端和服务器之间通信的问题。为了解决这个问题,我对grpc示例程序hello world进行了相应的修改,结果还是出现了同样的问题。在 golang 应用程序中切换命名空间后使用 grpc 是否有任何已知的限制?
我读过有关 golang 中切换命名空间的问题,但我想这取决于 grpc 行为是否会导致问题。
grpc 客户端是否会产生任何额外的 goroutine?这样的 goroutine 不一定会在同一个命名空间中执行,因为原始 goroutine 由于命名空间切换而锁定了线程。
我假设 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学习网公众号。

- 上一篇
- 数据验证功能出现错误:GIN发布

- 下一篇
- 分享安装PHP7的OAuth2扩展方法
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 93次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 100次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 105次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 99次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 98次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览