标签 Git 下的文章

小厂内部私有Go module拉取方案

本文永久链接 – https://tonybai.com/2021/09/03/the-approach-to-go-get-private-go-module-in-house

1. 问题来由

Go 1.11版本引入Go module后,Go命令拉取依赖的公共go module不再是“痛点”。如下图所示:


图:从公司内部经由公共GOPROXY服务拉取公共go module

我们在公司/组织内部仅需要为环境变量GOPROXY配置一个公共GOPROXY服务即可轻松拉取所有公共go module(公共module即开源module)。

但随着公司内Go使用者增多以及Go项目的增多,“代码重复”问题就出现了。抽取公共代码放入一个独立的、可被复用的内部私有仓库成为必然。这样我们便有了拉取私有go module的需求!

一些公司或组织的所有代码都放在公共vcs托管服务商那里(比如github.com),私有go module则直接放在对应的公共vcs服务的private repository(私有仓库)中。如果你的公司也是如此,那么拉取托管在公共vcs私有仓库中的私有go module也很容易,见下图:


图:从公司内部直接拉取托管在公共vcs服务上的私有go module

当然这个方案的一个前提是:每个开发人员都需要具有访问公共vcs服务上的私有go module仓库的权限,凭证的形式不限,可以是basic auth的user和password,也可以是personal access token(类似github那种),只要按照公共vcs的身份认证要求提供即可。

但是如果私有go module放在公司内部的vcs服务器上,就像下面图中所示:


图:私有go module放在组织/公司内部的vcs服务器上

那么我们该如何让Go命令自动拉取内部服务器上的私有go module呢?

一些gopher会说:“这很简单啊! 这和拉取托管在公共vcs服务上的私有go module没有什么分别啊”。持这种观点的gopher多半来自大厂。大厂内部有完备的IT基础设施供开发使用,大厂内部的vcs服务器都可以通过域名访问(比如git.bat.com/user/repo),因此大厂内部员工可以像访问公共vcs服务那样访问内部vcs服务器上的私有go module,就像下面图中所示:


图:大厂方案:直接拉取内部vcs仓库上的私有go module

我们看到:在上面这个方案中,公司搭建了一个内部goproxy服务(即上图中的in-house goproxy),这样的目的一来是为那些无法直接访问外网的开发机器以及ci机器提供拉取外部go module的途径,二来由于in-house goproxy的cache的存在,还可以加速公共go module的拉取效率。对于私有go module,开发机将其配置到GOPRIVATE环境变量中,这样Go命令在拉取私有go module时不会再走GOPROXY,而会采用直接访问vcs(如上图中的git.bat.com)的方式拉取私有go module。

当然大厂还可能采用下图所示方案将外部go module与私有go module都交给内部统一的Goproxy服务去处理:


图:大厂方案: 统一代理方案

在这种方案中,开发者仅需要将GOPROXY配置为in-house goproxy便可以统一拉取外部go module与私有go module。但由于go命令默认会对所有通过goproxy拉取的go module进行sum校验(到sum.golang.org),而我们的私有go module在公共sum验证server中没有数据记录,因此,开发者需要将私有go module填到GONOSUMDB环境变量中,这样go命令就不会对其进行sum校验了。不过这种方案有一处要注意:那就是in-house goproxy需要拥有对所有private module所在repo的访问权限,这样才能保证每个私有go module的拉取成功!

好了,问题来了!对于那些没有完备内部IT基础设施,还想将私有go module放在公司内部的vcs服务器上的小厂应该如何实现私有go module的拉取方案呢?

2. 可供小厂参考的一个解决方案

小厂虽小,但目标不能低。小厂虽然IT基础设施薄弱或不够灵活,但也不能因此给开发人员带去太多额外的“负担”。因此,对比了上面的两个大厂可能采用的方案,我们更倾向于后者。这样,我们就可以将所有复杂性都交给in-house goproxy这个节点,开发人员就可以做的足够简单。但小厂没有DNS,无法用域名…,我们该怎么实现这个方案呢?在这一节中,我们就实现这个方案。

0. 方案示例环境拓扑

我们先为后续的方案实现准备一个示例环境,其拓扑如下图:

1. 选择一个goproxy实现

Go module proxy协议规范发布后,Go社区出现了很多成熟的Goproxy开源实现。从最初的athens,再到国内的两个优秀的开源实现:goproxy.cngoproxy.io。其中,goproxy.io在官方站点给出了企业内部部署的方法,基于这一点,我们就基于goproxy.io来实现我们的方案(其余的goproxy实现应该也都可以实现)。

我们在上图中的in-house goproxy节点上执行下面步骤安装goproxy:

$mkdir ~/.bin/goproxy
$cd ~/.bin/goproxy
$git clone https://github.com/goproxyio/goproxy.git
$cd goproxy
$make

编译后,会在当前的bin目录(~/.bin/goproxy/goproxy/bin)下看到名为goproxy的可执行文件。

建立goproxy cache目录:

$mkdir /root/.bin/goproxy/goproxy/bin/cache

启动goproxy:

$./goproxy -listen=0.0.0.0:8081 -cacheDir=/root/.bin/goproxy/goproxy/bin/cache -proxy https://goproxy.io
goproxy.io: ProxyHost https://goproxy.io

启动后goproxy在8081端口监听(即便不指定,goproxy的默认端口也是8081),指定的上游goproxy服务为goproxy.io。

注意:goproxy的这个启动参数并不是最终版本的,这里仅仅想验证一下goproxy是否能按预期工作。

接下来,我们来验证一下goproxy的工作是否如我们预期。

我们在开发机上配置GOPROXY环境变量指向10.10.20.20:8081:

// .bashrc
export GOPROXY=http://10.10.20.20:8081

生效环境变量后,执行下面命令:

$go get github.com/pkg/errors

结果如预期,开发机顺利下载了github.com/pkg/errors包。

在goproxy侧,我们看到了下面日志:

goproxy.io: ------ --- /github.com/pkg/@v/list [proxy]
goproxy.io: ------ --- /github.com/pkg/errors/@v/list [proxy]
goproxy.io: ------ --- /github.com/@v/list [proxy]
goproxy.io: 0.146s 404 /github.com/@v/list
goproxy.io: 0.156s 404 /github.com/pkg/@v/list
goproxy.io: 0.157s 200 /github.com/pkg/errors/@v/list

并且在goproxy的cache目录下,我们也看到了下载并缓存的github.com/pkg/errors包:

$cd /root/.bin/goproxy/goproxy/bin/cache
$tree
.
└── pkg
    └── mod
        └── cache
            └── download
                └── github.com
                    └── pkg
                        └── errors
                            └── @v
                                └── list

8 directories, 1 file

2. 自定义包导入路径并将其映射到内部的vcs仓库

小厂可能没有为vcs服务器分配域名,我们也不能在Go私有包的导入路径中放入ip地址,因此我们需要给我们的私有go module自定义一个路径,比如:mycompany.com/go/module1。我们统一将私有go module放在mycompany.com/go下面的代码仓库中。

接下来的问题是,当goproxy去拉取mycompany.com/go/module1时,应该得到mycompany.com/go/module1对应的内部vcs上module1 仓库的地址,这样goproxy才能从内部vcs代码服务器上下载到module1对应的代码。


图:goproxy如何得到mycompany.com/go/module1所对应的vcs仓库地址呢?

其实方案不止一种。这里我们使用一个名为govanityurls的工具,这个工具在我以前的文章中曾提到过。

结合govanityurls和nginx,我们就可以将私有go module的导入路径映射为其在vcs上的代码仓库的真实地址。下面的图解释了具体原理:

首先,goproxy要想将收到的拉取私有go module(mycompany.com/go/module1)的请求不转发给公共代理,需要在其启动参数上做一些手脚,如下面修改后的goproxy启动命令:

$./goproxy -listen=0.0.0.0:8081 -cacheDir=/root/.bin/goproxy/goproxy/bin/cache -proxy https://goproxy.io -exclude "mycompany.com/go"

这样凡是与-exclude后面的值匹配的go module拉取请求,goproxy都不会转给goproxy.io,而是直接请求go module的“源站”。而上面图中要做的就是将这个“源站”的地址转换为企业内部vcs服务中的一个仓库地址。由于mycompany.com这个域名并不存在,从图中我们看到:我们在goproxy所在节点的/etc/hosts中加了这样一条记录:

127.0.0.1 mycompany.com

这样goproxy发出的到mycompany.com的请求实则是发向了本机。而上图中所示,监听本机80端口的正是nginx,nginx关于mycompany.com这一主机的配置如下:

// /etc/nginx/conf.d/gomodule.conf

server {
        listen 80;
        server_name mycompany.com;

        location /go {
                proxy_pass http://127.0.0.1:8080;
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
}

我们看到对于路径为mycompany.com/go/xxx的请求,nginx将请求转发给了127.0.0.1:8080,而这个服务地址恰是govanityurls工具监听的地址。

govanityurls这个工具是前Go核心开发团队成员Jaana B.Dogan开源的一个工具,这个工具可以帮助gopher快速实现自定义Go包的go get导入路径

govanityurls本身就好比一个“导航”服务器。当go命令向自定义包地址发起请求时,实则是将请求发送给了govanityurls服务,之后govanityurls将请求中的包所在仓库的真实地址(从vanity.yaml配置文件中读取)返回给go命令,后续go命令再从真实的仓库地址获取包数据。

注:govanityurls的安装方法很简单,直接go install/go get github.com/GoogleCloudPlatform/govanityurls即可。

在我们的示例中,vanity.yaml的配置如下:

host: mycompany.com

paths:
  /go/module1:
      repo: ssh://admin@10.10.30.30/module1
      vcs: git

也就是说当govanityurls收到nginx转发的请求后,会将请求与vanity.yaml中配置的module路径相匹配,如果匹配ok,则会将该module的真实repo地址通过go命令期望的应答格式予以返回。在这里我们看到,module1对应的真实vcs上的仓库地址为:ssh://admin@10.10.30.30/module1。

于是goproxy会收到这个地址,并再次向这个真实地址发起请求,并最终将module1缓存到本地cache并返回给客户端。

注意:由于这个方案与大厂的第二个方案是一样的,因此goproxy需要有访问mycompany.com/go下面所有go module对应的真实vcs仓库的权限。

3. 开发机(客户端)的设置

前面示例中,我们已经将开发机的GOPROXY环境变量设置为goproxy的服务地址。但我们说过凡是通过GOPROXY拉取的go module,go命令默认都会将其sum值到公共GOSUM服务器上去校验。但我们实质上拉取的是私有go module,GOSUM服务器上并没有我们的go module的sum数据。这样会导致go build命令报错,无法继续构建过程。

因此,开发机客户端还需将mycompany.com/go作为一个值设置到GONOSUMDB环境变量中,这就告诉go命令,凡是与mycompany.com/go匹配的go module,都无需做sum校验了。

4. 方案的“不足”

当然上述方案也不是完美的,它也有自己的不足的地方:

  • 开发者还是需要额外配置GONOSUMDB变量

由于Go命令默认会对从GOPROXY拉取的go module进行sum校验,因此我们需要将私有go module配置到GONOSUMDB环境变量中,这给开发者带来了一个小小的“负担”。

缓解措施:小厂可以将私有go项目都放在一个特定域名下,这样就无需为每个go私有项目单独增加GONOSUMDB配置了,只需要配置一次即可。

  • 新增私有go module,vanity.yaml需要手工同步更新

这个是这个方案最不灵活的地方了,由于目前govanityurls功能有限,我们针对每个私有go module可能都需要单独配置其对应的vcs仓库地址以及获取方式(git, svn or hg)。

缓解方案:在一个vcs仓库中管理多个私有go module,就像etcd那样。相比于最初go官方建议的一个repo只管理一个module,新版本的go在一个repo管理多个go module方面已经有了长足的进步。

不过对于小厂来说,这点额外工作与得到的收益相比,应该也不算什么!^_^

  • 无法划分权限

在上面的方案说明时也提到过,goproxy所在节点需要具备访问所有私有go module所在vcs repo的权限,但又无法对go开发者端做出有差别授权,这样只要是goproxy能拉取到的私有go module,go开发者都能拉取到。

不过对于多数小厂而言,内部所有源码原则上都是企业内部公开的,这个问题似乎也不大。如果觉得这是个问题,那么只能使用上面的大厂的第一个方案了。

3. 小结

无论大厂小厂,当对Go的使用逐渐深入后,接纳的人增多,开发的项目增多且越来越复杂后,拉取私有go module这样的问题肯定会摆到桌面上来。

对于大厂的gopher来说,这可能不是问题,甚至对他们都是透明的。但对于小厂等内部IT基础设施不完备的组织而言,的确需要自己动手解决。

这篇文章为小厂搭建Go私有库以及从私有库拉取私有go module提供了一个思路以及一个参考实现。

如果觉得上面的安装配置步骤有些繁琐,有兴趣深入的朋友可以将上述几个程序(goproxy, nginx, govanityurls)打到一个容器镜像中,实现一键安装设置。


“Gopher部落”知识星球正式转正(从试运营星球变成了正式星球)!“gopher部落”旨在打造一个精品Go学习和进阶社群!高品质首发Go技术文章,“三天”首发阅读权,每年两期Go语言发展现状分析,每天提前1小时阅读到新鲜的Gopher日报,网课、技术专栏、图书内容前瞻,六小时内必答保证等满足你关于Go语言生态的所有需求!部落目前虽小,但持续力很强。在2021年上半年,部落将策划两个专题系列分享,并且是部落独享哦:

  • Go技术书籍的书摘和读书体会系列
  • Go与eBPF系列

欢迎大家加入!

Go技术专栏“改善Go语⾔编程质量的50个有效实践”正在慕课网火热热销中!本专栏主要满足广大gopher关于Go语言进阶的需求,围绕如何写出地道且高质量Go代码给出50条有效实践建议,上线后收到一致好评!欢迎大家订
阅!

img{512x368}

我的网课“Kubernetes实战:高可用集群搭建、配置、运维与应用”在慕课网热卖中,欢迎小伙伴们订阅学习!

img{512x368}

我爱发短信:企业级短信平台定制开发专家 https://tonybai.com/。smspush : 可部署在企业内部的定制化短信平台,三网覆盖,不惧大并发接入,可定制扩展; 短信内容你来定,不再受约束, 接口丰富,支持长短信,签名可选。2020年4月8日,中国三大电信运营商联合发布《5G消息白皮书》,51短信平台也会全新升级到“51商用消息平台”,全面支持5G RCS消息。

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格5$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻)归档仓库 – https://github.com/bigwhite/gopherdaily

我的联系方式:

  • 微博:https://weibo.com/bigwhite20xx
  • 微信公众号:iamtonybai
  • 博客:tonybai.com
  • github: https://github.com/bigwhite
  • “Gopher部落”知识星球:https://public.zsxq.com/groups/51284458844544

微信赞赏:
img{512x368}

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

使用functrace辅助进行Go项目源码分析

本文永久链接 – https://tonybai.com/2021/06/04/go-source-analysis-with-functrace

《像跟踪分布式服务调用那样跟踪Go函数调用链》一文中,我们介绍了一种跟踪函数调用链的思路,并给出了一种实现functrace:https://github.com/bigwhite/functrace。这个小工具不仅仅是分享给大家的,我自己在工作和学习时也在使用。最近发现这个小工具在阅读和分析某个Go项目源码时也能起到关键的辅助作用。这里就和大家简单讲解一下如何用functrace来辅助Go源码阅读和分析。

程序员的日常离不开“源码阅读和分析”,日常阅读代码的姿势无非是这么几种(或几种的组合):

  • 结合源码编辑器或IDE提供的强大的源码交叉索引和跳转功能在一个庞大的源码库中建立起代码间的联系;
  • 将代码跑起来,在代码中加上一些print输出,跟踪执行流并画出;
  • 也有人喜欢用调试器从一点(通常是main)开始单步跟踪执行流。

无论哪一种方式,最终只要时间够长,态度到位,总是会将代码分析出个七七八八的。

就笔者来看,无论是哪种范式:命令式、面向对象、函数式,最终梳理出来的源码脉络都是建立在执行基本单元(函数或方法)上,代码的执行主线(并发程序会有若干条)本质上就是一条函数/方法调用链。只要把这条链理出来,代码理解起来就不难了。上述的代码阅读方法实质也是参照这个逻辑的。只是对于调用层次较深,还伴随有回调的代码,梳理调用链难度高、效率低。

functrace最初用于跟踪函数调用链(得益于Go核心开发团队公开的抽象语法树AST API),但如果在阅读代码时直接用functrace输出函数调用链,那将大幅提高我们源码阅读分析的效率。下面我们就用一个样例项目来试试如何用functrace梳理出代码的执行主线。

我们以Go高性能、轻量级、非阻塞的事件驱动网络框架gnet为例,来看看如何阅读分析gnet的源码。首先我们需要安装functrace工具:

$go install github.com/bigwhite/functrace/cmd/gen@latest
go: downloading github.com/bigwhite/functrace v0.0.0-20210603024853-ccab68a2604c
go: downloading golang.org/x/tools v0.0.0-20201204062850-545788942d5f

$gen -h
[gen -h]
gen [-w] xxx.go
  -w    write result to (source) file instead of stdout

接下来,我们下载要进行源码分析的gnet源码:

$git clone git@github.com:panjf2000/gnet.git

我们进入gnet目录,现在我们可以使用gen命令为任意go源文件添加“跟踪设施”了,比如:

$gen -w gnet.go
[gen -w gnet.go]
add trace for gnet.go ok

$ git diff gnet.go
diff --git a/gnet.go b/gnet.go
index b4c04a5..a7afe2b 100644
--- a/gnet.go
+++ b/gnet.go
@@ -29,6 +29,7 @@ import (
        "sync"
        "time"

+       "github.com/bigwhite/functrace"
        "github.com/panjf2000/gnet/errors"
        "github.com/panjf2000/gnet/internal"
        "github.com/panjf2000/gnet/internal/logging"
... ...

我们可以这样根据自己的需要在特定的go源文件上添加“跟踪设施”,但是多数情况下,我们也可以通过脚本为项目内所有go源文件批量添加“跟踪设施”,functrace项目提供了一个简单的脚本batch_add_trace.sh,下面我们就来通过该脚本将gnet下的go源文件批量加上函数跟踪设施:

下载functrace源码:

$git clone https://github.com/bigwhite/functrace.git

将functrace/scripts/batch_add_trace.sh 拷贝到上面gnet目录下并执行下面命令:

# bash batch_add_trace.sh
... ...
[gen -w ./server_unix.go]
add trace for ./server_unix.go ok
[gen -w ./internal/socket/sockopts_posix.go]
add trace for ./internal/socket/sockopts_posix.go ok
... ...
[gen -w ./ringbuffer/ring_buffer_test.go]
add trace for ./ringbuffer/ring_buffer_test.go ok
[gen -w ./ringbuffer/ring_buffer.go]
add trace for ./ringbuffer/ring_buffer.go ok
[gen -w ./pool/bytebuffer/bytebuffer.go]
no trace added for ./pool/bytebuffer/bytebuffer.go
[gen -w ./pool/goroutine/goroutine.go]
add trace for ./pool/goroutine/goroutine.go ok
[gen -w ./pool/ringbuffer/ringbuffer.go]
add trace for ./pool/ringbuffer/ringbuffer.go ok
[gen -w ./loop_linux.go]
add trace for ./loop_linux.go ok
[gen -w ./server_windows.go]
add trace for ./server_windows.go ok

接下来我们编写一个基于gnet的程序,我们就使用gnet参加TechEmpower的那份代码:

//main.go
package main

import (
    "bytes"
    "flag"
    "fmt"
    "log"
    "runtime"
    "time"

    "github.com/panjf2000/gnet"
)

type httpServer struct {
    *gnet.EventServer
}

type httpCodec struct {
    delimiter []byte
}

func (hc *httpCodec) Encode(c gnet.Conn, buf []byte) (out []byte, err error) {
    return buf, nil
}

func (hc *httpCodec) Decode(c gnet.Conn) (out []byte, err error) {
    buf := c.Read()
    if buf == nil {
        return
    }
    c.ResetBuffer()

    // process the pipeline
    var i int
pipeline:
    if i = bytes.Index(buf, hc.delimiter); i != -1 {
        out = append(out, "HTTP/1.1 200 OK\r\nServer: gnet\r\nContent-Type: text/plain\r\nDate: "...)
        out = time.Now().AppendFormat(out, "Mon, 02 Jan 2006 15:04:05 GMT")
        out = append(out, "\r\nContent-Length: 13\r\n\r\nHello, World!"...)
        buf = buf[i+4:]
        goto pipeline
    }
    // request not ready, yet
    return
}

func (hs *httpServer) OnInitComplete(srv gnet.Server) (action gnet.Action) {
    log.Printf("HTTP server is listening on %s (multi-cores: %t, loops: %d)\n",
        srv.Addr.String(), srv.Multicore, srv.NumEventLoop)
    return
}

func (hs *httpServer) React(frame []byte, c gnet.Conn) (out []byte, action gnet.Action) {
    // handle the request
    out = frame
    return
}

func init() {
    runtime.GOMAXPROCS(runtime.NumCPU() * 2)
}

func main() {
    var port int
    var multicore bool

    // Example command: go run main.go --port 8080 --multicore=true
    flag.IntVar(&port, "port", 8080, "server port")
    flag.BoolVar(&multicore, "multicore", true, "multicore")
    flag.Parse()

    http := new(httpServer)
    hc := &httpCodec{delimiter: []byte("\r\n\r\n")}

    // Start serving!
    log.Fatal(gnet.Serve(http, fmt.Sprintf("tcp://:%d", port), gnet.WithMulticore(multicore), gnet.WithCodec(hc)))
}

构建这份代码:

$go mod init gnet-demo
$go get github.com/panjf2000/gnet
go: downloading github.com/panjf2000/gnet v1.4.5
go get: added github.com/panjf2000/gnet v1.4.5

//修改go.mod,使用replace让gnet-demo使用本地的gnet代码
$cat go.mod
module gnet-demo

go 1.16

replace github.com/panjf2000/gnet => /root/go/src/github.com/panjf2000/gnet

require (
        github.com/panjf2000/gnet v1.4.5
)

$go get github.com/bigwhite/functrace
go get: added github.com/bigwhite/functrace v0.0.0-20210603024853-ccab68a2604c

$go build -tags trace //-tags trace务必不能省略,这个是开启functrace的关键

构建后,我们来执行构建出的可执行程序:gnet-demo:

$ go build -tags trace
root@VM-0-12-ubuntu:~/test/go/gnet-demo# ./gnet-demo
g[01]:  ->github.com/panjf2000/gnet/internal/socket.maxListenerBacklog
g[01]:  <-github.com/panjf2000/gnet/internal/socket.maxListenerBacklog
g[01]:  ->github.com/panjf2000/gnet/ringbuffer.New
g[01]:  <-github.com/panjf2000/gnet/ringbuffer.New
g[01]:  ->github.com/panjf2000/gnet/internal/logging.init.0
g[01]:  <-github.com/panjf2000/gnet/internal/logging.init.0
g[01]:  ->github.com/panjf2000/gnet.WithMulticore
g[01]:  <-github.com/panjf2000/gnet.WithMulticore
g[01]:  ->github.com/panjf2000/gnet.WithCodec
g[01]:  <-github.com/panjf2000/gnet.WithCodec
g[01]:  ->github.com/panjf2000/gnet.Serve
g[01]:      ->github.com/panjf2000/gnet.loadOptions
g[01]:      <-github.com/panjf2000/gnet.loadOptions
g[01]:      ->github.com/panjf2000/gnet.parseProtoAddr
g[01]:      <-github.com/panjf2000/gnet.parseProtoAddr
g[01]:      ->github.com/panjf2000/gnet.initListener
g[01]:          ->github.com/panjf2000/gnet.(*listener).normalize
g[01]:              ->github.com/panjf2000/gnet/internal/socket.TCPSocket
g[01]:                  ->github.com/panjf2000/gnet/internal/socket.tcpSocket
g[01]:                      ->github.com/panjf2000/gnet/internal/socket.getTCPSockaddr
g[01]:                          ->github.com/panjf2000/gnet/internal/socket.determineTCPProto
g[01]:                          <-github.com/panjf2000/gnet/internal/socket.determineTCPProto
g[01]:                      <-github.com/panjf2000/gnet/internal/socket.getTCPSockaddr
g[01]:                      ->github.com/panjf2000/gnet/internal/socket.sysSocket
g[01]:                      <-github.com/panjf2000/gnet/internal/socket.sysSocket
g[01]:                      ->github.com/panjf2000/gnet/internal/socket.SetNoDelay
g[01]:                      <-github.com/panjf2000/gnet/internal/socket.SetNoDelay
g[01]:                  <-github.com/panjf2000/gnet/internal/socket.tcpSocket
g[01]:              <-github.com/panjf2000/gnet/internal/socket.TCPSocket
g[01]:          <-github.com/panjf2000/gnet.(*listener).normalize
g[01]:      <-github.com/panjf2000/gnet.initListener
g[01]:      ->github.com/panjf2000/gnet.serve
2021/06/03 14:53:30 HTTP server is listening on :8080 (multi-cores: true, loops: 1)
g[01]:          ->github.com/panjf2000/gnet.(*server).start
g[01]:              ->github.com/panjf2000/gnet.(*server).activateReactors
g[01]:                  ->github.com/panjf2000/gnet/internal/netpoll.OpenPoller
g[01]:                      ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[01]:                      <-github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[01]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.NewLockFreeQueue
g[01]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.NewLockFreeQueue
g[01]:                  <-github.com/panjf2000/gnet/internal/netpoll.OpenPoller
g[01]:                  ->github.com/panjf2000/gnet.(*roundRobinLoadBalancer).register
g[01]:                  <-github.com/panjf2000/gnet.(*roundRobinLoadBalancer).register
g[01]:                  ->github.com/panjf2000/gnet.(*server).startSubReactors
g[01]:                      ->github.com/panjf2000/gnet.(*roundRobinLoadBalancer).iterate
g[01]:                      <-github.com/panjf2000/gnet.(*roundRobinLoadBalancer).iterate
g[01]:                  <-github.com/panjf2000/gnet.(*server).startSubReactors
g[01]:                  ->github.com/panjf2000/gnet/internal/netpoll.OpenPoller
g[01]:                      ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[01]:                      <-github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[01]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.NewLockFreeQueue
g[01]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.NewLockFreeQueue
g[01]:                  <-github.com/panjf2000/gnet/internal/netpoll.OpenPoller
g[01]:                  ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[01]:                  <-github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[01]:              <-github.com/panjf2000/gnet.(*server).activateReactors
g[01]:          <-github.com/panjf2000/gnet.(*server).start
g[01]:          ->github.com/panjf2000/gnet.(*server).stop
g[01]:              ->github.com/panjf2000/gnet.(*server).waitForShutdown
g[07]:  ->github.com/panjf2000/gnet.(*server).activateMainReactor
g[07]:      ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).Polling
g[07]:          ->github.com/panjf2000/gnet/internal/netpoll.newEventList
g[07]:          <-github.com/panjf2000/gnet/internal/netpoll.newEventList
g[06]:  ->github.com/panjf2000/gnet.(*server).activateSubReactor
g[06]:      ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).Polling
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll.newEventList
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll.newEventList

我们看到gnet的执行主线被清晰的打印出来,通过输出的函数所在包我们可以轻松找到对应的源文件。g[01]这goroutine显然是main goroutine,整个程序的初始化线索通过跟踪g[01]的函数链便一目了然。

如果我们要看gnet是如何处理一个外部链接的,我们可以向gnet-demo建立一个连接,看看gnet-demo的输出。

我们通过curl命令向gnet-demo发起一个http请求:

$curl localhost:8080
Hello, World!

gnet-demo输出:

g[07]:          ->github.com/panjf2000/gnet.(*server).acceptNewConnection
g[07]:              ->github.com/panjf2000/gnet/internal/socket.SockaddrToTCPOrUnixAddr
g[07]:                  ->github.com/panjf2000/gnet/internal/socket.sockaddrInet6ToIPAndZone
g[07]:                      ->github.com/panjf2000/gnet/internal/socket.ip6ZoneToString
g[07]:                      <-github.com/panjf2000/gnet/internal/socket.ip6ZoneToString
g[07]:                  <-github.com/panjf2000/gnet/internal/socket.sockaddrInet6ToIPAndZone
g[07]:              <-github.com/panjf2000/gnet/internal/socket.SockaddrToTCPOrUnixAddr
g[07]:              ->github.com/panjf2000/gnet.(*roundRobinLoadBalancer).next
g[07]:              <-github.com/panjf2000/gnet.(*roundRobinLoadBalancer).next
g[07]:              ->github.com/panjf2000/gnet.newTCPConn
g[07]:                  ->github.com/panjf2000/gnet/pool/ringbuffer.Get
g[07]:                      ->github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Get
g[07]:                          ->github.com/panjf2000/gnet/ringbuffer.New
g[07]:                          <-github.com/panjf2000/gnet/ringbuffer.New
g[07]:                      <-github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Get
g[07]:                  <-github.com/panjf2000/gnet/pool/ringbuffer.Get
g[07]:                  ->github.com/panjf2000/gnet/pool/ringbuffer.Get
g[07]:                      ->github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Get
g[07]:                          ->github.com/panjf2000/gnet/ringbuffer.New
g[07]:                          <-github.com/panjf2000/gnet/ringbuffer.New
g[07]:                      <-github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Get
g[07]:                  <-github.com/panjf2000/gnet/pool/ringbuffer.Get
g[07]:              <-github.com/panjf2000/gnet.newTCPConn
g[07]:              ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).Trigger
g[07]:                  ->github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Enqueue
g[07]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[07]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[07]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[07]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[07]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[07]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[07]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.cas
g[07]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.cas
g[07]:                      ->github.com/panjf2000/gnet/internal/netpoll/queue.cas
g[07]:                      <-github.com/panjf2000/gnet/internal/netpoll/queue.cas
g[07]:                  <-github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Enqueue
g[07]:              <-github.com/panjf2000/gnet/internal/netpoll.(*Poller).Trigger
g[07]:          <-github.com/panjf2000/gnet.(*server).acceptNewConnection
g[07]:          ->github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[07]:          <-github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Dequeue
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.cas
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.cas
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Dequeue
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll.(*Poller).AddRead
g[06]:          ->github.com/panjf2000/gnet.(*eventloop).loopOpen
g[06]:              ->github.com/panjf2000/gnet.(*eventloop).addConn
g[06]:              <-github.com/panjf2000/gnet.(*eventloop).addConn
g[06]:              ->github.com/panjf2000/gnet.(*EventServer).OnOpened
g[06]:              <-github.com/panjf2000/gnet.(*EventServer).OnOpened
g[06]:              ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:              <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:              ->github.com/panjf2000/gnet.(*eventloop).handleAction
g[06]:              <-github.com/panjf2000/gnet.(*eventloop).handleAction
g[06]:          <-github.com/panjf2000/gnet.(*eventloop).loopOpen
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Dequeue
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              ->github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:              <-github.com/panjf2000/gnet/internal/netpoll/queue.load
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Dequeue
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Empty
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll/queue.(*lockFreeQueue).Empty
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[06]:          ->github.com/panjf2000/gnet.(*eventloop).loopRead
g[06]:              ->github.com/panjf2000/gnet.(*conn).read
g[06]:                  ->github.com/panjf2000/gnet.(*conn).Read
g[06]:                      ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                      <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                  <-github.com/panjf2000/gnet.(*conn).Read
g[06]:                  ->github.com/panjf2000/gnet.(*conn).ResetBuffer
g[06]:                      ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                      <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                  <-github.com/panjf2000/gnet.(*conn).ResetBuffer
g[06]:              <-github.com/panjf2000/gnet.(*conn).read
g[06]:              ->github.com/panjf2000/gnet.(*EventServer).PreWrite
g[06]:              <-github.com/panjf2000/gnet.(*EventServer).PreWrite
g[06]:              ->github.com/panjf2000/gnet.(*conn).write
g[06]:                  ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                  <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:              <-github.com/panjf2000/gnet.(*conn).write
g[06]:              ->github.com/panjf2000/gnet.(*conn).read
g[06]:                  ->github.com/panjf2000/gnet.(*conn).Read
g[06]:                      ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                      <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                  <-github.com/panjf2000/gnet.(*conn).Read
g[06]:                  ->github.com/panjf2000/gnet.(*conn).ResetBuffer
g[06]:                      ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                      <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                  <-github.com/panjf2000/gnet.(*conn).ResetBuffer
g[06]:              <-github.com/panjf2000/gnet.(*conn).read
g[06]:              ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Write
g[06]:              <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Write
g[06]:          <-github.com/panjf2000/gnet.(*eventloop).loopRead
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[06]:          ->github.com/panjf2000/gnet.(*eventloop).loopRead
g[06]:              ->github.com/panjf2000/gnet.(*eventloop).loopCloseConn
g[06]:                  ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                  <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).IsEmpty
g[06]:                  ->github.com/panjf2000/gnet/internal/netpoll.(*Poller).Delete
g[06]:                  <-github.com/panjf2000/gnet/internal/netpoll.(*Poller).Delete
g[06]:                  ->github.com/panjf2000/gnet.(*eventloop).addConn
g[06]:                  <-github.com/panjf2000/gnet.(*eventloop).addConn
g[06]:                  ->github.com/panjf2000/gnet.(*EventServer).OnClosed
g[06]:                  <-github.com/panjf2000/gnet.(*EventServer).OnClosed
g[06]:                  ->github.com/panjf2000/gnet.(*conn).releaseTCP
g[06]:                      ->github.com/panjf2000/gnet/pool/ringbuffer.Put
g[06]:                          ->github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Put
g[06]:                              ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Len
g[06]:                              <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Len
g[06]:                              ->github.com/panjf2000/gnet/pool/ringbuffer.index
g[06]:                              <-github.com/panjf2000/gnet/pool/ringbuffer.index
g[06]:                              ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                              <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                          <-github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Put
g[06]:                      <-github.com/panjf2000/gnet/pool/ringbuffer.Put
g[06]:                      ->github.com/panjf2000/gnet/pool/ringbuffer.Put
g[06]:                          ->github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Put
g[06]:                              ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Len
g[06]:                              <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Len
g[06]:                              ->github.com/panjf2000/gnet/pool/ringbuffer.index
g[06]:                              <-github.com/panjf2000/gnet/pool/ringbuffer.index
g[06]:                              ->github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                              <-github.com/panjf2000/gnet/ringbuffer.(*RingBuffer).Reset
g[06]:                          <-github.com/panjf2000/gnet/pool/ringbuffer.(*Pool).Put
g[06]:                      <-github.com/panjf2000/gnet/pool/ringbuffer.Put
g[06]:                  <-github.com/panjf2000/gnet.(*conn).releaseTCP
g[06]:              <-github.com/panjf2000/gnet.(*eventloop).loopCloseConn
g[06]:          <-github.com/panjf2000/gnet.(*eventloop).loopRead
g[06]:          ->github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink
g[06]:          <-github.com/panjf2000/gnet/internal/netpoll.(*eventList).shrink

通过gnet-demo输出,我们可以清晰看到gnet接收一个连接,在这个连接上读写以及关闭这个连接的函数调用链,有了这个链条,我们再来阅读gnet源码就轻松许多了,即便有回调函数也没有问题。

上面输出的函数调用链的内容已经很多了。但如果你还不满足于这些,比如我还要跟踪到gnet依赖的golang.org/x/sys中,那可以利用相同思路,将golang.org/x/sys下载到本地,并通过functrace添加跟踪设施,并在gnet-demo中用replace换掉golang.org/x/sys,让其指向本地的sys包代码。如果觉得信息太多,可以通过gen命令做单个必要go源文件的跟踪信息添加,而不必要用批量方式。进一步的跟踪sys包的函数调用链的作业就留给大家了,这里就不深入了。

代码阅读完成后,我们只需在gnet目录下执行如下命令便可以恢复gnet原来的面貌:

$git checkout .

“Gopher部落”知识星球正式转正(从试运营星球变成了正式星球)!“gopher部落”旨在打造一个精品Go学习和进阶社群!高品质首发Go技术文章,“三天”首发阅读权,每年两期Go语言发展现状分析,每天提前1小时阅读到新鲜的Gopher日报,网课、技术专栏、图书内容前瞻,六小时内必答保证等满足你关于Go语言生态的所有需求!部落目前虽小,但持续力很强。在2021年上半年,部落将策划两个专题系列分享,并且是部落独享哦:

  • Go技术书籍的书摘和读书体会系列
  • Go与eBPF系列

欢迎大家加入!

Go技术专栏“改善Go语⾔编程质量的50个有效实践”正在慕课网火热热销中!本专栏主要满足广大gopher关于Go语言进阶的需求,围绕如何写出地道且高质量Go代码给出50条有效实践建议,上线后收到一致好评!欢迎大家订
阅!

img{512x368}

我的网课“Kubernetes实战:高可用集群搭建、配置、运维与应用”在慕课网热卖中,欢迎小伙伴们订阅学习!

img{512x368}

我爱发短信:企业级短信平台定制开发专家 https://tonybai.com/。smspush : 可部署在企业内部的定制化短信平台,三网覆盖,不惧大并发接入,可定制扩展; 短信内容你来定,不再受约束, 接口丰富,支持长短信,签名可选。2020年4月8日,中国三大电信运营商联合发布《5G消息白皮书》,51短信平台也会全新升级到“51商用消息平台”,全面支持5G RCS消息。

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格5$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻)归档仓库 – https://github.com/bigwhite/gopherdaily

我的联系方式:

  • 微博:https://weibo.com/bigwhite20xx
  • 微信公众号:iamtonybai
  • 博客:tonybai.com
  • github: https://github.com/bigwhite
  • “Gopher部落”知识星球:https://public.zsxq.com/groups/51284458844544

微信赞赏:
img{512x368}

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言精进之路1 Go语言精进之路2 商务合作请联系bigwhite.cn AT aliyun.com

欢迎使用邮件订阅我的博客

输入邮箱订阅本站,只要有新文章发布,就会第一时间发送邮件通知你哦!

这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



View My Stats