socket.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package tracer
  2. import (
  3. "fmt"
  4. "github.com/cilium/ebpf"
  5. "github.com/cilium/ebpf/btf"
  6. "github.com/coroot/coroot-node-agent/utils"
  7. "k8s.io/klog/v2"
  8. "net"
  9. "os"
  10. "runtime"
  11. "syscall"
  12. "time"
  13. )
  14. func init() {
  15. enable_ebpf_protocol(PROTO_HTTP1)
  16. enable_ebpf_protocol(PROTO_HTTP2)
  17. enable_ebpf_protocol(PROTO_TLS_HTTP1)
  18. enable_ebpf_protocol(PROTO_TLS_HTTP2)
  19. enable_ebpf_protocol(PROTO_DUBBO)
  20. enable_ebpf_protocol(PROTO_SOFARPC)
  21. enable_ebpf_protocol(PROTO_MYSQL)
  22. enable_ebpf_protocol(PROTO_POSTGRESQL)
  23. enable_ebpf_protocol(PROTO_REDIS)
  24. enable_ebpf_protocol(PROTO_KAFKA)
  25. enable_ebpf_protocol(PROTO_MQTT)
  26. enable_ebpf_protocol(PROTO_DNS)
  27. }
  28. func MapInit(collectionSpec *ebpf.CollectionSpec, opts *ebpf.CollectionOptions) {
  29. set_offset_map(collectionSpec, opts)
  30. set_conf_map_default(collectionSpec, opts)
  31. //offsetData := make([]any, runtime.NumCPU())
  32. //for i := range offsetData {
  33. // offsetData[i] = testStruct{
  34. // test_id: 99999,
  35. // }
  36. //}
  37. //if bpf_table_set_value(collectionSpec, opts, "test_heap", offsetData) != ETR_OK {}
  38. //insert_output_prog_to_map(collectionSpec, opts)
  39. }
  40. func MapInsert(collection *ebpf.Collection) {
  41. insert_output_prog_to_map(collection)
  42. insert_adapt_kern_uid_to_map(collection)
  43. // Update go offsets to eBPF "proc_info_map"
  44. //update_proc_info_to_map(collection)
  45. // Update protocol filter array
  46. update_protocol_filter_array(collection)
  47. }
  48. func insert_output_prog_to_map(collection *ebpf.Collection) {
  49. // jmp for tracepoints
  50. __insert_output_prog_to_map(collection, MAP_PROGS_JMP_TP_NAME, PROG_DATA_SUBMIT_NAME_FOR_TP, PROG_DATA_SUBMIT_TP_IDX)
  51. __insert_output_prog_to_map(collection, MAP_PROGS_JMP_TP_NAME, PROG_OUTPUT_DATA_NAME_FOR_TP, PROG_OUTPUT_DATA_TP_IDX)
  52. __insert_output_prog_to_map(collection, MAP_PROGS_JMP_TP_NAME, PROG_IO_EVENT_NAME_FOR_TP, PROG_IO_EVENT_TP_IDX)
  53. // jmp for kprobe/uprobe
  54. __insert_output_prog_to_map(collection, MAP_PROGS_JMP_KP_NAME, PROG_DATA_SUBMIT_NAME_FOR_KP, PROG_DATA_SUBMIT_KP_IDX)
  55. __insert_output_prog_to_map(collection, MAP_PROGS_JMP_KP_NAME, PROG_OUTPUT_DATA_NAME_FOR_KP, PROG_OUTPUT_DATA_KP_IDX)
  56. }
  57. func __insert_output_prog_to_map(collection *ebpf.Collection, mapName string, progName string, key uint32) {
  58. // find in programs
  59. prog, ok := collection.Programs[progName]
  60. fmt.Println(prog, ok)
  61. if ok {
  62. progFd := prog.FD()
  63. code, err := bpf_table_set_value(collection, mapName, key, uint32(progFd))
  64. if err != nil {
  65. klog.Error(err, code)
  66. }
  67. }
  68. }
  69. func update_protocol_filter_array(collection *ebpf.Collection) {
  70. for i := 0; i < PROTO_NUM; i++ {
  71. code, err := bpf_table_set_value(collection, MAP_PROTO_FILTER_NAME, uint32(i), EbpfConfigProtocolFilter[i])
  72. if err != nil || code != ETR_OK {
  73. klog.Error(err, code)
  74. }
  75. }
  76. }
  77. //func update_allow_port_bitmap(collection *ebpf.Collection) {
  78. // for i := 0; i < PROTO_NUM; i++ {
  79. // if bpf_table_set_value(collection, MAP_ALLOW_PORT_BITMAP_NAME, 0, &allow_port_bitmap) != ETR_OK {
  80. // fmt.Println("no")
  81. // } else {
  82. // fmt.Println("ok")
  83. // }
  84. // }
  85. //}
  86. func insert_adapt_kern_uid_to_map(collection *ebpf.Collection) {
  87. pid := os.Getpid()
  88. tid := syscall.Gettid()
  89. adaptKernUID := uint64(pid)<<32 | uint64(tid)
  90. code, err := bpf_table_set_value(collection, MAP_ADAPT_KERN_UID_NAME, 0, uint32(adaptKernUID))
  91. if err != nil || code != ETR_OK {
  92. klog.Error(err, code)
  93. }
  94. }
  95. func enable_ebpf_protocol(protocol int) {
  96. if protocol < PROTO_NUM {
  97. EbpfConfigProtocolFilter[protocol] = 1
  98. }
  99. }
  100. func Offset() {
  101. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", offsetInferServerAddr, offsetInferServerPort))
  102. if err != nil {
  103. fmt.Errorf("failed to create server listener: %v", err)
  104. return
  105. }
  106. if err := kernelOffsetInferServer(listener); err != nil {
  107. fmt.Printf("Error in kernel_offset_infer_server: %v\n", err)
  108. }
  109. if err := kernelOffsetInferClient(); err != nil {
  110. fmt.Printf("Error in kernel_offset_infer_client: %v\n", err)
  111. }
  112. defer listener.Close()
  113. }
  114. func set_offset_map(collectionSpec *ebpf.CollectionSpec, opts *ebpf.CollectionOptions) {
  115. // 解析BTF数据
  116. if update_offset_map_from_btf_vmlinux(collectionSpec, opts) != ETR_OK {
  117. klog.Infof("[eBPF Kernel Adapt] Set offsets map from btf_vmlinux, not support.\n")
  118. if update_offset_map_default(collectionSpec, opts) != ETR_OK {
  119. klog.Infof("Fatal error, failed to update default offset\n")
  120. }
  121. } else {
  122. klog.Infof("[eBPF Kernel Adapt] Set offsets map from btf_vmlinux, success.\n")
  123. }
  124. }
  125. // __u64 socket_id; // 会话标识
  126. // __u64 coroutine_trace_id; // 同一协程的数据转发关联
  127. // __u64 thread_trace_id; // 同一进程/线程的数据转发关联,用于多事务流转场景
  128. // __u64 data_limit_max; // Maximum number of data transfers
  129. // __u64 go_tracing_timeout;
  130. // __u64 io_event_collect_mode;
  131. // __u64 io_event_minimal_duration;
  132. func set_conf_map_default(collectionSpec *ebpf.CollectionSpec, opts *ebpf.CollectionOptions) {
  133. fmt.Println("GetHostID")
  134. _, charHostID := utils.GetHostID()
  135. _, charAppID := utils.GetAppID()
  136. uidBase := uint64(time.Now().UnixNano()/int64(time.Millisecond)) & 0xffffffffffffff
  137. numCPU := runtime.NumCPU()
  138. tConf := make([]any, numCPU)
  139. for i := range tConf {
  140. socketID := uint64(i)<<56 | uint64(uidBase)
  141. tracerConf := traceConf{
  142. SocketID: socketID,
  143. CoroutineTraceID: socketID,
  144. ThreadTraceID: socketID,
  145. DataLimitMax: 4096,
  146. GoTracingTimeout: 120,
  147. IOEventCollectMode: 1,
  148. IOEventMinimalDuartion: 1000000,
  149. HostID: charHostID,
  150. APPID: charAppID,
  151. }
  152. tConf[i] = tracerConf
  153. }
  154. if bpf_table_pre_set_value(collectionSpec, opts, MAP_TRACE_CONF_NAME, tConf) != ETR_OK {
  155. klog.Infof("[eBPF Kernel Adapt] Set config map from btf_vmlinux, not support.\n")
  156. } else {
  157. klog.Infof("[eBPF Kernel Adapt] Set config map from btf_vmlinux, success.\n")
  158. }
  159. }
  160. // 解析BTF数据
  161. func update_offset_map_from_btf_vmlinux(collectionSpec *ebpf.CollectionSpec, opts *ebpf.CollectionOptions) int {
  162. btfSpec, err := btf.LoadKernelSpec()
  163. if err != nil || btfSpec == nil {
  164. return ETR_NOTSUPP
  165. }
  166. copied_seq_offs := kernel_struct_field_offset(btfSpec, "tcp_sock", "copied_seq")
  167. write_seq_offs := kernel_struct_field_offset(btfSpec, "tcp_sock", "write_seq")
  168. files_offs := kernel_struct_field_offset(btfSpec, "task_struct", "files")
  169. sk_flags_offs := kernel_struct_field_offset(btfSpec, "sock", "__sk_flags_offset")
  170. if sk_flags_offs == ETR_NOTEXIST {
  171. sk_flags_offs = kernel_struct_field_offset(btfSpec, "sock", "sk_pacing_shift")
  172. if sk_flags_offs > 0 {
  173. sk_flags_offs -= 1
  174. }
  175. }
  176. struct_files_struct_fdt_offset := kernel_struct_field_offset(btfSpec, "files_struct", "fdt")
  177. struct_files_private_data_offset := kernel_struct_field_offset(btfSpec, "file", "private_data")
  178. struct_file_f_inode_offset := kernel_struct_field_offset(btfSpec, "file", "f_inode")
  179. struct_inode_i_mode_offset := kernel_struct_field_offset(btfSpec, "inode", "i_mode")
  180. struct_file_dentry_offset_1 := kernel_struct_field_offset(btfSpec, "file", "f_path")
  181. struct_file_dentry_offset_2 := kernel_struct_field_offset(btfSpec, "path", "dentry")
  182. if struct_file_dentry_offset_1 < 0 ||
  183. struct_file_dentry_offset_2 < 0 {
  184. return ETR_NOTSUPP
  185. }
  186. struct_file_dentry_offset := struct_file_dentry_offset_1 + struct_file_dentry_offset_2
  187. struct_dentry_name_offset_1 := kernel_struct_field_offset(btfSpec, "dentry", "d_name")
  188. struct_dentry_name_offset_2 := kernel_struct_field_offset(btfSpec, "qstr", "name")
  189. if struct_dentry_name_offset_1 < 0 ||
  190. struct_dentry_name_offset_2 < 0 {
  191. return ETR_NOTSUPP
  192. }
  193. struct_dentry_name_offset := struct_dentry_name_offset_1 + struct_dentry_name_offset_2
  194. struct_sock_family_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_family")
  195. struct_sock_saddr_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_rcv_saddr")
  196. struct_sock_daddr_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_daddr")
  197. struct_sock_ip6saddr_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_v6_rcv_saddr")
  198. struct_sock_ip6daddr_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_v6_daddr")
  199. struct_sock_dport_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_dport")
  200. struct_sock_sport_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_num")
  201. struct_sock_skc_state_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_state")
  202. struct_sock_common_ipv6only_offset := kernel_struct_field_offset(btfSpec, "sock_common", "skc_flags")
  203. klog.Infof("Offsets from BTF vmlinux:\n")
  204. klog.Infof(" copied_seq_offs: 0x%x\n", copied_seq_offs)
  205. klog.Infof(" write_seq_offs: 0x%x\n", write_seq_offs)
  206. klog.Infof(" files_offs: 0x%x\n", files_offs)
  207. klog.Infof(" sk_flags_offs: 0x%x\n", sk_flags_offs)
  208. klog.Infof(" struct_files_struct_fdt_offset: 0x%x\n", struct_files_struct_fdt_offset)
  209. klog.Infof(" struct_files_private_data_offset: 0x%x\n", struct_files_private_data_offset)
  210. klog.Infof(" struct_file_f_inode_offset: 0x%x\n", struct_file_f_inode_offset)
  211. klog.Infof(" struct_inode_i_mode_offset: 0x%x\n", struct_inode_i_mode_offset)
  212. klog.Infof(" struct_file_dentry_offset: 0x%x\n", struct_file_dentry_offset)
  213. klog.Infof(" struct_dentry_name_offset: 0x%x\n", struct_dentry_name_offset)
  214. klog.Infof(" struct_sock_family_offset: 0x%x\n", struct_sock_family_offset)
  215. klog.Infof(" struct_sock_saddr_offset: 0x%x\n", struct_sock_saddr_offset)
  216. klog.Infof(" struct_sock_daddr_offset: 0x%x\n", struct_sock_daddr_offset)
  217. klog.Infof(" struct_sock_ip6saddr_offset: 0x%x\n", struct_sock_ip6saddr_offset)
  218. klog.Infof(" struct_sock_ip6daddr_offset: 0x%x\n", struct_sock_ip6daddr_offset)
  219. klog.Infof(" struct_sock_dport_offset: 0x%x\n", struct_sock_dport_offset)
  220. klog.Infof(" struct_sock_sport_offset: 0x%x\n", struct_sock_sport_offset)
  221. klog.Infof(" struct_sock_skc_state_offset: 0x%x\n", struct_sock_skc_state_offset)
  222. klog.Infof(" struct_sock_common_ipv6only_offset: 0x%x\n", struct_sock_common_ipv6only_offset)
  223. if copied_seq_offs < 0 || write_seq_offs < 0 || files_offs < 0 ||
  224. sk_flags_offs < 0 || struct_files_struct_fdt_offset < 0 ||
  225. struct_files_private_data_offset < 0 ||
  226. struct_file_f_inode_offset < 0 || struct_inode_i_mode_offset < 0 ||
  227. struct_inode_i_mode_offset < 0 || struct_file_dentry_offset < 0 ||
  228. struct_dentry_name_offset < 0 || struct_sock_family_offset < 0 ||
  229. struct_sock_saddr_offset < 0 || struct_sock_daddr_offset < 0 ||
  230. struct_sock_ip6saddr_offset < 0 ||
  231. struct_sock_ip6daddr_offset < 0 || struct_sock_dport_offset < 0 ||
  232. struct_sock_sport_offset < 0 || struct_sock_skc_state_offset < 0 ||
  233. struct_sock_common_ipv6only_offset < 0 {
  234. return ETR_NOTSUPP
  235. }
  236. offset := bpfOffsetParam{}
  237. offset.Ready = 1
  238. offset.TaskFilesOffset = uint32(files_offs)
  239. offset.SockFlagsOffset = uint32(sk_flags_offs)
  240. offset.TcpSockCopiedSeqOffset = uint32(copied_seq_offs)
  241. offset.TcpSockWriteSeqOffset = uint32(write_seq_offs)
  242. offset.StructFilesStructFdtOffset = uint32(struct_files_struct_fdt_offset)
  243. offset.StructFilesPrivateDataOffset = uint32(struct_files_private_data_offset)
  244. offset.StructFileFInodeOffset = uint32(struct_file_f_inode_offset)
  245. offset.StructInodeIModeOffset = uint32(struct_inode_i_mode_offset)
  246. offset.StructFileDentryOffset = uint32(struct_file_dentry_offset)
  247. offset.StructDentryNameOffset = uint32(struct_dentry_name_offset)
  248. offset.StructSockFamilyOffset = uint32(struct_sock_family_offset)
  249. offset.StructSockSaddrOffset = uint32(struct_sock_saddr_offset)
  250. offset.StructSockDaddrOffset = uint32(struct_sock_daddr_offset)
  251. offset.StructSockIp6saddrOffset = uint32(struct_sock_ip6saddr_offset)
  252. offset.StructSockIp6daddrOffset = uint32(struct_sock_ip6daddr_offset)
  253. offset.StructSockDportOffset = uint32(struct_sock_dport_offset)
  254. offset.StructSockSportOffset = uint32(struct_sock_sport_offset)
  255. offset.StructSockSkcStateOffset = uint32(struct_sock_skc_state_offset)
  256. offset.StructSockCommonIpv6onlyOffset = uint32(struct_sock_common_ipv6only_offset)
  257. if update_offsets_table(collectionSpec, opts, offset) != ETR_OK {
  258. return ETR_UPDATE_MAP_FAILD
  259. }
  260. return ETR_OK
  261. }
  262. func update_offset_map_default(collectionSpec *ebpf.CollectionSpec, opts *ebpf.CollectionOptions) int {
  263. offset := bpfOffsetParam{}
  264. offset.StructFilesStructFdtOffset = 0x20
  265. offset.StructFilesPrivateDataOffset = 0xc8
  266. offset.StructFileFInodeOffset = 0x20
  267. offset.StructInodeIModeOffset = 0x00
  268. offset.StructFileDentryOffset = 0x18
  269. offset.StructDentryNameOffset = 0x28
  270. offset.StructSockFamilyOffset = 0x10
  271. offset.StructSockSaddrOffset = 0x4
  272. offset.StructSockDaddrOffset = 0x0
  273. offset.StructSockIp6saddrOffset = 0x48
  274. offset.StructSockIp6daddrOffset = 0x38
  275. offset.StructSockDportOffset = 0xc
  276. offset.StructSockSportOffset = 0xe
  277. offset.StructSockSkcStateOffset = 0x12
  278. offset.StructSockCommonIpv6onlyOffset = 0x13
  279. if update_offsets_table(collectionSpec, opts, offset) != ETR_OK {
  280. return ETR_UPDATE_MAP_FAILD
  281. }
  282. return ETR_OK
  283. }
  284. func update_offsets_table(collectionSpec *ebpf.CollectionSpec, opts *ebpf.CollectionOptions, offset bpfOffsetParam) int {
  285. numCPU := runtime.NumCPU()
  286. offsetData := make([]any, numCPU)
  287. for i := range offsetData {
  288. offsetData[i] = offset
  289. }
  290. if bpf_table_pre_set_value(collectionSpec, opts, MAP_MEMBERS_OFFSET_NAME, offsetData) != ETR_OK {
  291. return ETR_UPDATE_MAP_FAILD
  292. }
  293. return ETR_OK
  294. }
  295. func SetConstants(collectionSpec *ebpf.CollectionSpec) {
  296. consts := map[string]interface{}{
  297. // TODO go Process
  298. "buckets_ptr_pos": int64(16),
  299. "ctx_ptr_pos": int64(232),
  300. "headers_ptr_pos": int64(56),
  301. "host_pos": int64(128),
  302. "request_host_pos": int64(128),
  303. "is_registers_abi": true,
  304. "method_ptr_pos": int64(0),
  305. "path_ptr_pos": int64(56),
  306. "proto_pos": int64(24),
  307. "remote_addr_pos": int64(176),
  308. "req_ptr_pos": int64(8),
  309. "status_code_pos": int64(120),
  310. "url_ptr_pos": int64(16),
  311. // TODO in process ***
  312. "start_addr": int64(139627412217856),
  313. "end_addr": int64(139627412283392),
  314. // TODO 全局 ***
  315. "total_cpus": int64(2),
  316. //"apm_app_id": int64(0),
  317. //"apm_host_id": int64(0),
  318. }
  319. err := collectionSpec.RewriteConstants(consts)
  320. fmt.Println("err----------------", err)
  321. fmt.Println("err", consts)
  322. }