{"id":13841837,"url":"https://github.com/chenjiandongx/bpfpinger","last_synced_at":"2025-04-22T03:33:18.873Z","repository":{"id":54889819,"uuid":"330717337","full_name":"chenjiandongx/bpfpinger","owner":"chenjiandongx","description":"🚥 A high-performance ICMP ping implementation build on top of BPF technology.","archived":false,"fork":false,"pushed_at":"2024-05-27T13:14:40.000Z","size":53,"stargazers_count":53,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-08-26T12:23:50.046Z","etag":null,"topics":["bpf","go","network","ping","pinger","tcpdump"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chenjiandongx.png","metadata":{"files":{"readme":"README-CN.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-18T16:00:19.000Z","updated_at":"2024-05-27T12:00:16.000Z","dependencies_parsed_at":"2024-06-19T02:02:17.526Z","dependency_job_id":"2d73d5c9-a74b-4eea-885b-9370f7f7c801","html_url":"https://github.com/chenjiandongx/bpfpinger","commit_stats":null,"previous_names":["chenjiandongx/bpfpinger","chenjiandongx/yap"],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chenjiandongx%2Fbpfpinger","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chenjiandongx%2Fbpfpinger/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chenjiandongx%2Fbpfpinger/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chenjiandongx%2Fbpfpinger/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chenjiandongx","download_url":"https://codeload.github.com/chenjiandongx/bpfpinger/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223888483,"owners_count":17220080,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bpf","go","network","ping","pinger","tcpdump"],"created_at":"2024-08-04T17:01:22.492Z","updated_at":"2024-11-09T21:47:35.111Z","avatar_url":"https://github.com/chenjiandongx.png","language":"Go","funding_links":[],"categories":["Go"],"sub_categories":[],"readme":"# bpfpinger\n\n[![GoDoc](https://godoc.org/github.com/chenjiandongx/bpfpinger?status.svg)](https://godoc.org/github.com/chenjiandongx/bpfpinger)\n[![Go Report Card](https://goreportcard.com/badge/github.com/chenjiandongx/bpfpinger)](https://goreportcard.com/report/github.com/chenjiandongx/bpfpinger)\n[![License](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)\n\n\u003e BPF 技术最初诞生就是为了高效地处理网络包。\n\nBPF 利用其虚拟机技术，可以在一个比较靠前的位置处理网络包（cBPF 其实是在内核中过滤处理，相对 XDP 这种 eBPF 技术算靠后的了），减少从内核态到用户态的网络包的数量，**本质上也就是减少数据从内核态复制到用户态的开销以及两者上下文切换的开销**。\n\n[bpfpinger](https://github.com/chenjiandongx/bpfpinger) 是一个 Golang 高性能的 ICMP PING 工具，其整体的实现思路是利用 `syscall.Sendto` 系统调用将自己封装好的 ICMP 包发送至网卡，然后再利用 [gopacket](https://github.com/google/gopacket) 库监听网卡并自己接收和处理 ICMP 包，这种设计模式使得 ICMP 的通信模式就变成了异步非阻塞的。\n\n原生 ICMP 的同步通讯模型，在单个 goroutine 内，每一个 request 包需要等待上一个 reply 包到来才会继续发送，这也就导致了程序的大多数时间都需要等待一次 RTT（Round Trip Time）的时间。\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://user-images.githubusercontent.com/19553554/107472251-94801880-6ba9-11eb-85c2-71b5497394ec.png\" width=\"50%\"\u003e\n\u003c/br\u003e\u003ci\u003e图 1：同步阻塞模型\u003c/i\u003e\n\u003c/p\u003e\n\nbpfpinger 使用的异步通信模型，所有一个 ICMP 包只由全局唯一一个 goroutine 负责发送，然后使用 gopacket 监听网卡，将数据包进行处理和计算耗时，这样管理发送的 Sender 就可以持续不断的工作，无需同步地等待回包，大大提高了效率。\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://user-images.githubusercontent.com/19553554/107473130-22103800-6bab-11eb-9a0e-31494bf5fcb0.png\" width=\"50%\"\u003e\n\u003c/br\u003e\u003ci\u003e图 2：异步非阻塞模型\u003c/i\u003e\n\u003c/p\u003e\n\n### 优化细节\n\n1）**更小的数据包**：icmp 包的 body 尽量的小。bpfpinger 使用的 ICMP 包整体大小约为 46 bytes，为什么是大约呢？因为在开发的过程中，我发现在 MacOS 上和在 CentOS 上使用同样的代码，最后计算的包的大小是不一样的，差了个 2 个 bytes。🤔 目前还不知道是操作系统本身实现不同导致的差异，还是因为我是开的虚拟机做开发，网卡虚拟化本身会导致的差异。\n\n```golang\nmsg := icmp.Message{\n\tType: ipv4.ICMPTypeEcho,\n\tCode: 0,\n\tBody: \u0026icmp.Echo{ID: req.id, Seq: i, Data: []byte(\"yap\")},\n}\n```\n\nPS：这里补充一下 Echo Request 协议数据包描述。\n```bash\n// Echo or Echo Reply Message\n\n//    0                   1                   2                   3\n//    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n//   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//   |     Type      |     Code      |          Checksum             |\n//   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//   |           Identifier          |        Sequence Number        |\n//   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//   |     Data ...\n//   +-+-+-+-+-\n//\n//   IP Fields:\n//\n//   Type:\n//      8 for echo message;\n//      0 for echo reply message.\n//\n//   Code:\n//      0\n//\n//   Checksum:\n//      The checksum is the 16-bit ones's complement of the one's\n//      complement sum of the ICMP message starting with the ICMP Type.\n//      For computing the checksum , the checksum field should be zero.\n//      If the total length is odd, the received data is padded with one\n//      octet of zeros for computing the checksum.  This checksum may be\n//      replaced in the future.\n//\n//   Identifier:\n//      If code = 0, an identifier to aid in matching echos and replies,\n//      may be zero.\n//\n//   Sequence Number\n//\n```\n\n2）**更严格的包过滤规则**：过滤包的规则越严格，从内核空间到用户空间的包就更少。当且仅当接收小于 48 bytes 的 icmp 的回显包。这样基本上接收到的所有包都是自己想要的了。\n\n```golang\ndefaultFilter = \"less 48 and icmp[icmptype] == icmp-echoreply\"\n```\n\n不同的请求类型对应着不同的协议 ID\n```bash\n// Summary of Message Types\n\n//  0  Echo Reply   \u003c- notice\n//  3  Destination Unreachable\n//  4  Source Quench\n//  5  Redirect\n//  8  Echo\n// 11  Time Exceeded\n// 12  Parameter Problem\n// 13  Timestamp\n// 14  Timestamp Reply\n// 15  Information Request\n// 16  Information Reply\n```\n\n3）**更唯一的请求标识**：为了避免不同进程同时使用 bpfpinger 进行 ping 操作而导致的数据误差，bpfpinger 使用了随机初始化 Identifier + dstip 作为独立标识。最大程度上的降低数据误差的可能性。\n\n```golang\n// 随机初始化 counter\nrand.Seed(time.Now().UnixNano())\npg.counter = int(rand.Int31n(int32(math.MaxUint16)))\n\n// id+ + dstip 作为唯一标识\npg.rspMutex.Lock()\nr, ok := pg.echoRsps[genid(icmpPkg.Id, ipv4pkg.SrcIP.String())]\nif !ok {\n\tpg.rspMutex.Unlock()\n\tcontinue\n}\n\nr \u003c- echoRsp{\n\tid:   icmpPkg.Id,\n\tseq:  icmpPkg.Seq,\n\tcode: icmpPkg.TypeCode.Code(),\n\tt:    microsecond(),\n}\npg.rspMutex.Unlock()\n```\n\n### 性能对比\n\n\u003e 对比实验操作系统：CentOS7\n\n在写 bpfpinger 之前，我也曾经写过另外一个 ICMP ping 库，[pinger](https://github.com/chenjiandongx/pinger)，这个刚好就是上面所描述的同步模型的设计方案。所以就用这个库来跟 bpfpinger 做性能对比。\n\n`/root/golang/src/pingtest/pinger/main.go`\n```golang\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/chenjiandongx/pinger\"\n\t\"github.com/shirou/gopsutil/process\"\n)\n\nconst (\n\tPingCount    = 100000\n\tPingInterval = 50\n\tPingTimeout  = 3000\n\tConcurrency  = 20\n)\n\nfunc main() {\n\tgo func() {\n\t\tif err := http.ListenAndServe(\"localhost:9999\", nil); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tproc, err := process.NewProcess(int32(os.Getpid()))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t\tbusy, err := proc.CPUPercent()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tfmt.Println(\"pinger cpu.busy: \", busy)\n\t\t}\n\t}()\n\n\topt := pinger.DefaultICMPPingOpts()\n\topt.Interval = func() time.Duration { return time.Duration(PingInterval) * time.Millisecond }\n\topt.PingTimeout = time.Duration(PingTimeout) * time.Millisecond\n\topt.PingCount = PingCount\n\topt.FailOver = 20\n\topt.MaxConcurrency = Concurrency\n\n\tstart := time.Now()\n\tstats, err := pinger.ICMPPing(\u0026opt, []string{\"www.huya.com\"}...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, stat := range stats {\n\t\tfmt.Printf(\"Target: %s, PkgLoss: %v, RTTMin: %v, RTTMean: %v, RTTMax: %v\\n\", stat.Host, stat.PktLossRate, stat.Best, stat.Mean, stat.Mean)\n\t}\n\tfmt.Printf(\"PING Costs: %v\\n\", time.Since(start))\n}\n```\n\n`/root/golang/src/pingtest/bpfpinger/main.go`\n```golang\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/chenjiandongx/bpfpinger\"\n\t\"github.com/shirou/gopsutil/process\"\n)\n\nconst (\n\tPingCount    = 100000\n\tPingInterval = 50\n\tPingTimeout  = 3000\n)\n\nfunc main() {\n\tgo func() {\n\t\tif err := http.ListenAndServe(\"localhost:8888\", nil); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tproc, err := process.NewProcess(int32(os.Getpid()))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t\tbusy, err := proc.CPUPercent()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tfmt.Println(\"bpfpinger cpu.busy: \", busy)\n\t\t}\n\t}()\n\n\n\tpg, err := bpfpinger.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer pg.Close()\n\n\tstart := time.Now()\n\tresponse := pg.Call(bpfpinger.Request{Target: \"www.huya.com\", Count: PingCount, Timeout: PingTimeout, Interval: PingInterval})\n\tif response.Error != nil {\n\t\tpanic(response.Error)\n\t}\n\n\tfmt.Println(response.String())\n\tfmt.Printf(\"PING costs: %v\\n\", time.Since(start))\n}\n```\n\n出于调试目的，我将两个进程都开启了 pprof 服务，分别暴露在 9999 和 8888 端口。接下来将两个程序同时跑起来。\n\n![image](https://user-images.githubusercontent.com/19553554/107476803-8df59f00-6bb1-11eb-8e2e-6c0c4ec60b76.png)\n\n可以看到，两者的 CPU 消耗是差不多的，约为 ~2%。\n\n**但是**\n\n既然是压测，那我们就需要模拟一下极端的环境，使用下面 bash 命令向 localhost 无情地不间断地发送 2000w 个 ICMP 包。\n```shell\necho -n \"\u003e\u003e\u003e\u003e\u003e\u003e start: \";date;time for i in {0..2000};do ping 127.0.0.1 -c 10000 -i0|awk '{print $7}'|awk -F '=' '{if($2\u003e2) system(\"date\");if($2\u003e2) print $0 \"ms\"}';done\n```\n\n我们再看看这种极端网络环境下两者的 CPU 表现。\n\n![image](https://user-images.githubusercontent.com/19553554/107477054-0fe5c800-6bb2-11eb-95ab-7571b47f6cb3.png)\n\n**喔嚯，bpfpinger 进程依旧稳如老狗，而 pinger 进程的 CPU 使用率已经飙升到了 50% 以上....**\n\n刚才讲到，为了调试我对两者均开启了 pprof 服务，那就来看看这段时间两个进程到底在干什么会产生如此大的性能差异。\n\n#### pinger pprof\n\n我悟了！进程在系统调用上花费了太多资源了，flat 高达 4.89s。\n\n```bash\n(pprof) top 20\nShowing nodes accounting for 13.09s, 81.86% of 15.99s total\nDropped 140 nodes (cum \u003c= 0.08s)\nShowing top 20 nodes out of 84\n      flat  flat%   sum%        cum   cum%\n     4.89s 30.58% 30.58%      6.01s 37.59%  syscall.Syscall6\n     2.63s 16.45% 47.03%      2.63s 16.45%  runtime.epollwait\n     1.62s 10.13% 57.16%      1.62s 10.13%  runtime.futex\n     0.76s  4.75% 61.91%      0.76s  4.75%  runtime.usleep\n     0.51s  3.19% 65.10%      1.61s 10.07%  runtime.mallocgc\n     0.34s  2.13% 67.23%      0.36s  2.25%  time.now\n     0.32s  2.00% 69.23%      0.32s  2.00%  runtime.madvise\n     0.26s  1.63% 70.86%      0.26s  1.63%  runtime.nextFreeFast\n     0.23s  1.44% 72.30%      0.29s  1.81%  runtime.heapBitsSetType\n     0.19s  1.19% 73.48%      3.41s 21.33%  runtime.findrunnable\n     0.18s  1.13% 74.61%      0.18s  1.13%  runtime.casgstatus\n     0.18s  1.13% 75.73%      0.18s  1.13%  runtime.memclrNoHeapPointers\n     0.18s  1.13% 76.86%      1.51s  9.44%  runtime.newobject\n     0.14s  0.88% 77.74%      0.34s  2.13%  runtime.mapaccess2\n     0.14s  0.88% 78.61%      1.52s  9.51%  runtime.sysmon\n     0.12s  0.75% 79.36%      7.55s 47.22%  net.(*IPConn).readFrom\n     0.11s  0.69% 80.05%      0.17s  1.06%  time.Now\n     0.10s  0.63% 80.68%      2.79s 17.45%  runtime.netpoll\n     0.10s  0.63% 81.30%      0.86s  5.38%  runtime.reentersyscall\n     0.09s  0.56% 81.86%      6.88s 43.03%  net.(*netFD).readFrom\n```\n\n我们知道，三层 IP 包传输在 Linux 对应的系统调用分别是 `syscall.Sendto` 和 `syscall.recvFrom`，接下来我们就验证一下上面的系统调用是不是主要耗在这两个方法上。\n\n```bash\n(pprof) peek syscall\nShowing nodes accounting for 15.99s, 100% of 15.99s total\n----------------------------------------------------------+-------------\n      flat  flat%   sum%        cum   cum%   calls calls% + context\n----------------------------------------------------------+-------------\n                                             5.96s 99.17% |   syscall.recvfrom\n                                             0.05s  0.83% |   syscall.sendto\n     4.89s 30.58% 30.58%      6.01s 37.59%                | syscall.Syscall6\n                                             0.90s 14.98% |   runtime.entersyscall\n                                             0.22s  3.66% |   runtime.exitsyscall\n----------------------------------------------------------+-------------\n                                             0.86s   100% |   runtime.entersyscall\n     0.10s  0.63% 31.21%      0.86s  5.38%                | runtime.reentersyscall\n                                             0.67s 77.91% |   runtime.systemstack\n                                             0.08s  9.30% |   runtime.casgstatus\n                                             0.01s  1.16% |   runtime.save\n```\n\n这下就非常明显了吧，大多数的开销都在 `revcFrom` 系统调用上，因为我们刚才压测的时候往本地的网卡灌入了海量的 ICMP 包，**所以进程需要不断地陷入到内核态去将所有的这些 ICMP 包复制到用户态来进行验证处理。**\n\n#### bpfpinger pprof\n\n虽然 syscall 的开销也是占大头，但是进程总体的 CPU 开销是极小的（相比于上面的 pinger）。\n\n```bash\n(pprof) top 20\nShowing nodes accounting for 210ms, 100% of 210ms total\nShowing top 20 nodes out of 28\n      flat  flat%   sum%        cum   cum%\n     120ms 57.14% 57.14%      120ms 57.14%  runtime.usleep\n      40ms 19.05% 76.19%       40ms 19.05%  runtime.cgocall\n      30ms 14.29% 90.48%       30ms 14.29%  syscall.Syscall6\n      10ms  4.76% 95.24%       10ms  4.76%  runtime.lock\n      10ms  4.76%   100%      140ms 66.67%  runtime.sysmon\n         0     0%   100%       30ms 14.29%  github.com/chenjiandongx/bpfpinger.(*Pinger).Call\n         0     0%   100%       40ms 19.05%  github.com/google/gopacket.(*PacketSource).NextPacket\n         0     0%   100%       40ms 19.05%  github.com/google/gopacket.(*PacketSource).packetsToChannel\n         0     0%   100%       40ms 19.05%  github.com/google/gopacket/pcap.(*Handle).ReadPacketData\n         0     0%   100%       40ms 19.05%  github.com/google/gopacket/pcap.(*Handle).getNextBufPtrLocked\n         0     0%   100%       10ms  4.76%  github.com/google/gopacket/pcap.(*Handle).pcapNextPacketEx\n         0     0%   100%       10ms  4.76%  github.com/google/gopacket/pcap.(*Handle).pcapNextPacketEx.func1\n         0     0%   100%       30ms 14.29%  github.com/google/gopacket/pcap.(*Handle).waitForPacket\n         0     0%   100%       30ms 14.29%  github.com/google/gopacket/pcap.(*Handle).waitForPacket.func1\n         0     0%   100%       10ms  4.76%  github.com/google/gopacket/pcap._Cfunc_pcap_next_ex_escaping\n         0     0%   100%       30ms 14.29%  github.com/google/gopacket/pcap._Cfunc_pcap_wait\n         0     0%   100%       30ms 14.29%  golang.org/x/net/icmp.(*PacketConn).WriteTo\n         0     0%   100%       30ms 14.29%  internal/poll.(*FD).WriteTo\n         0     0%   100%       30ms 14.29%  main.main\n         0     0%   100%       30ms 14.29%  net.(*IPConn).WriteTo\n```\n\n看下具体的系统调用情况，符合预期，主要都是 `sendto`，没有 `revcfrom`。\n\n```bash\n(pprof) peek syscall\nShowing nodes accounting for 210ms, 100% of 210ms total\n----------------------------------------------------------+-------------\n      flat  flat%   sum%        cum   cum%   calls calls% + context\n----------------------------------------------------------+-------------\n                                              30ms   100% |   syscall.sendto\n      30ms 14.29% 14.29%       30ms 14.29%                | syscall.Syscall6\n----------------------------------------------------------+-------------\n                                              30ms   100% |   internal/poll.(*FD).WriteTo\n         0     0% 14.29%       30ms 14.29%                | syscall.Sendto\n                                              30ms   100% |   syscall.sendto\n```\n\n#### 小结\n1）bpfpinger 相比于 pinger 有着更优的执行效率，且性能受网络环境的影响极小，即使的同时收发海量的数据包，bpfpinger 的开销基本上是维持在一个常数。这本质上还是得益于 BPF 在内核态就将大量的数据包给过滤掉了，减小用户进程处理包的压力。\n\n2）bpfpinger 的整体执行时间是可控的，它的异步模型并不需要同步等待回包，这也就意味着它的发包完全不受网络抖动的影响，而 pinger 如果再网络质量比较差的时候，即使多开 goroutine 也避免不了需要长时间等待 RTT 的尴尬局面。\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchenjiandongx%2Fbpfpinger","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchenjiandongx%2Fbpfpinger","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchenjiandongx%2Fbpfpinger/lists"}