socket.go 15 KB

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