github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/agents/queue.go (about) 1 // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package agents 4 5 import ( 6 "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" 7 teaconst "github.com/TeaOSLab/EdgeNode/internal/const" 8 "github.com/TeaOSLab/EdgeNode/internal/events" 9 "github.com/TeaOSLab/EdgeNode/internal/goman" 10 "github.com/TeaOSLab/EdgeNode/internal/remotelogs" 11 "github.com/TeaOSLab/EdgeNode/internal/rpc" 12 "github.com/iwind/TeaGo/Tea" 13 "net" 14 ) 15 16 func init() { 17 if !teaconst.IsMain { 18 return 19 } 20 21 events.On(events.EventLoaded, func() { 22 goman.New(func() { 23 SharedQueue.Start() 24 }) 25 }) 26 } 27 28 var SharedQueue = NewQueue() 29 30 type Queue struct { 31 c chan string // chan ip 32 cacheMap *IPCacheMap 33 } 34 35 func NewQueue() *Queue { 36 return &Queue{ 37 c: make(chan string, 128), 38 cacheMap: NewIPCacheMap(65535), 39 } 40 } 41 42 func (this *Queue) Start() { 43 for ip := range this.c { 44 err := this.Process(ip) 45 if err != nil { 46 // 不需要上报错误 47 if Tea.IsTesting() { 48 remotelogs.Debug("SharedParseQueue", err.Error()) 49 } 50 continue 51 } 52 } 53 } 54 55 // Push 将IP加入到处理队列 56 func (this *Queue) Push(ip string) { 57 // 是否在处理中 58 if this.cacheMap.Contains(ip) { 59 return 60 } 61 this.cacheMap.Add(ip) 62 63 // 加入到队列 64 select { 65 case this.c <- ip: 66 default: 67 } 68 } 69 70 // Process 处理IP 71 func (this *Queue) Process(ip string) error { 72 // 是否已经在库中 73 if SharedManager.ContainsIP(ip) { 74 return nil 75 } 76 77 ptr, err := this.ParseIP(ip) 78 if err != nil { 79 return err 80 } 81 if len(ptr) == 0 || ptr == "." { 82 return nil 83 } 84 85 //remotelogs.Debug("AGENT", ip+" => "+ptr) 86 87 var agentCode = this.ParsePtr(ptr) 88 if len(agentCode) == 0 { 89 return nil 90 } 91 92 // 加入到本地 93 SharedManager.AddIP(ip, agentCode) 94 95 var pbAgentIP = &pb.CreateClientAgentIPsRequest_AgentIPInfo{ 96 AgentCode: agentCode, 97 Ip: ip, 98 Ptr: ptr, 99 } 100 rpcClient, err := rpc.SharedRPC() 101 if err != nil { 102 return err 103 } 104 _, err = rpcClient.ClientAgentIPRPC.CreateClientAgentIPs(rpcClient.Context(), &pb.CreateClientAgentIPsRequest{AgentIPs: []*pb.CreateClientAgentIPsRequest_AgentIPInfo{pbAgentIP}}) 105 if err != nil { 106 return err 107 } 108 109 return nil 110 } 111 112 // ParseIP 分析IP的PTR值 113 func (this *Queue) ParseIP(ip string) (ptr string, err error) { 114 if len(ip) == 0 { 115 return "", nil 116 } 117 118 names, err := net.LookupAddr(ip) 119 if err != nil { 120 return "", err 121 } 122 123 if len(names) == 0 { 124 return "", nil 125 } 126 127 return names[0], nil 128 } 129 130 // ParsePtr 分析PTR对应的Agent 131 func (this *Queue) ParsePtr(ptr string) (agentCode string) { 132 for _, agent := range AllAgents { 133 if agent.Match(ptr) { 134 return agent.Code 135 } 136 } 137 return "" 138 }