socket.go 15 KB

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