是否有已知的限制在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获得小数点以下两位长度?
- 478浏览 收藏
-
- 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互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 185次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 183次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 185次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 192次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 205次使用
-
- 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浏览