register.go 6.6 KB
Newer Older
H
heyanlong 已提交
1 2
package service

H
heyanlong 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16
import (
	"agent/agent/pb/agent"
	"agent/agent/pb/common"
	"agent/agent/pb/register2"
	"context"
	"encoding/json"
	"github.com/google/uuid"
	"net"
	"os"
	"runtime"
	"strconv"
	"time"
)

H
heyanlong 已提交
17 18 19 20 21 22
type registerCache struct {
	Version    int
	AppId      int32
	InstanceId int32
	Uuid       string
}
H
heyanlong 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

type registerReq struct {
	AppCode string `json:"app_code"`
	Pid     int    `json:"pid"`
	Version int    `json:"version"`
}

func ip4s() []string {
	ipv4s, addErr := net.InterfaceAddrs()
	var ips []string
	if addErr == nil {
		for _, i := range ipv4s {
			if ipnet, ok := i.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					ips = append(ips, ipnet.IP.String())
				}
			}
		}
	}
	return ips
}

H
heyanlong 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57
func (t *Agent) recoverRegister(info trace) {

	t.registerCacheLock.RLock()
	_, ok := t.registerCache[info.Pid]
	t.registerCacheLock.RUnlock()

	if !ok {
		t.registerCacheLock.Lock()
		t.registerCache[info.Pid] = registerCache{
			Version:    info.Version,
			AppId:      info.ApplicationId,
			InstanceId: info.ApplicationInstance,
			Uuid:       info.Uuid,
H
heyanlong 已提交
58
		}
H
heyanlong 已提交
59
		t.registerCacheLock.Unlock()
H
heyanlong 已提交
60 61 62
	}
}

H
heyanlong 已提交
63 64 65 66 67
func (t *Agent) doRegister(r *register) {

	info := registerReq{}
	err := json.Unmarshal([]byte(r.body), &info)
	if err != nil {
H
heyanlong 已提交
68
		log.Error("register json decode error", err)
H
heyanlong 已提交
69 70 71 72 73
		r.c.Write([]byte(""))
		return
	}

	pid := info.Pid
H
heyanlong 已提交
74 75 76 77
	t.registerCacheLock.RLock()
	bind, ok := t.registerCache[pid]
	t.registerCacheLock.RUnlock()
	if ok {
H
heyanlong 已提交
78 79
		log.Infof("register => pid %d appid %d insId %d", pid, bind.AppId, bind.InstanceId)
		r.c.Write([]byte(strconv.FormatInt(int64(bind.AppId), 10) + "," + strconv.FormatInt(int64(bind.InstanceId), 10) + "," + bind.Uuid))
H
heyanlong 已提交
80 81 82 83 84 85 86 87
		return
	} else {
		r.c.Write([]byte(""))
	}

	t.registerCacheLock.Lock()
	defer t.registerCacheLock.Unlock()
	// if map not found pid.. start register
H
heyanlong 已提交
88
	if _, ok := t.registerCache[pid]; !ok {
H
heyanlong 已提交
89
		log.Infof("start register pid %d used SkyWalking v%d", pid, info.Version)
H
heyanlong 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
		var regAppStatus = false
		var appId int32 = 0
		var appInsId int32 = 0
		var regErr error
		agentUUID := uuid.New().String()

		if info.Version == 5 {
			c := agent.NewApplicationRegisterServiceClient(t.grpcConn)
			ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
			defer cancel()

			var regResp *agent.ApplicationMapping

			// loop register
			for {
				regResp, regErr = c.ApplicationCodeRegister(ctx, &agent.Application{
					ApplicationCode: info.AppCode,
				})
				if regErr != nil {
H
heyanlong 已提交
109
					log.Error("register error:", regErr)
H
heyanlong 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
					break
				}
				if regResp.GetApplication() != nil {
					regAppStatus = true
					appId = regResp.GetApplication().GetValue()
					break
				}
				time.Sleep(time.Second)
			}
		} else if info.Version == 6 {
			c := register2.NewRegisterClient(t.grpcConn)
			ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
			defer cancel()

			var regResp *register2.ServiceRegisterMapping
			var services []*register2.Service
			services = append(services, &register2.Service{
				ServiceName: info.AppCode,
			})
			// loop register
			for {
				regResp, regErr = c.DoServiceRegister(ctx, &register2.Services{
					Services: services,
				})
				if regErr != nil {
H
heyanlong 已提交
135
					log.Error("register error:", regErr)
H
heyanlong 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
					break
				}

				if regResp.GetServices() != nil {
					for _, v := range regResp.GetServices() {
						if v.GetKey() == info.AppCode {
							regAppStatus = true
							appId = v.GetValue()
							break
						}
					}
				}

				if regAppStatus {
					break
				}
				time.Sleep(time.Second)
			}
		}

		if regAppStatus {
			// start reg instance
			if info.Version == 5 {
				instanceClient := agent.NewInstanceDiscoveryServiceClient(t.grpcConn)
				instanceCtx, instanceCancel := context.WithTimeout(context.Background(), time.Second*3)
				defer instanceCancel()

				var instanceErr error
				var instanceResp *agent.ApplicationInstanceMapping
				hostName, _ := os.Hostname()

				instanceReq := &agent.ApplicationInstance{
					ApplicationId: appId,
					AgentUUID:     agentUUID,
					RegisterTime:  time.Now().UnixNano() / 1000000,
					Osinfo: &agent.OSInfo{
						OsName:    runtime.GOOS,
						Hostname:  hostName,
						ProcessNo: int32(pid),
						Ipv4S:     ip4s(),
					},
				}
				for {
					instanceResp, instanceErr = instanceClient.RegisterInstance(instanceCtx, instanceReq)
					if instanceErr != nil {
H
heyanlong 已提交
181
						log.Error("register error:", instanceErr)
H
heyanlong 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
						break
					}
					if instanceResp.GetApplicationInstanceId() != 0 {
						appInsId = instanceResp.GetApplicationInstanceId()
						break
					}
					time.Sleep(time.Second)
				}
			} else if info.Version == 6 {
				instanceClient := register2.NewRegisterClient(t.grpcConn)
				instanceCtx, instanceCancel := context.WithTimeout(context.Background(), time.Second*3)
				defer instanceCancel()

				var instanceErr error
				var instanceResp *register2.ServiceInstanceRegisterMapping
				hostName, _ := os.Hostname()

				var instances []*register2.ServiceInstance
				var properties []*common.KeyStringValuePair

				properties = append(properties, &common.KeyStringValuePair{
					Key:   "os_name",
					Value: runtime.GOOS,
				})

				properties = append(properties, &common.KeyStringValuePair{
					Key:   "host_name",
					Value: hostName,
				})

				properties = append(properties, &common.KeyStringValuePair{
					Key:   "process_no",
H
heyanlong 已提交
214
					Value: strconv.Itoa(pid),
H
heyanlong 已提交
215 216 217 218 219 220 221 222 223
				})

				properties = append(properties, &common.KeyStringValuePair{
					Key:   "language",
					Value: "php",
				})

				for _, ip := range ip4s() {
					properties = append(properties, &common.KeyStringValuePair{
H
heyanlong 已提交
224
						Key:   "ipv4",
H
heyanlong 已提交
225 226 227 228
						Value: ip,
					})
				}

H
heyanlong 已提交
229 230 231 232 233 234 235
				instances = append(instances, &register2.ServiceInstance{
					ServiceId:    appId,
					InstanceUUID: agentUUID,
					Time:         time.Now().UnixNano() / 1000000,
					Properties:   properties,
				})

H
heyanlong 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
				instanceReq := &register2.ServiceInstances{
					Instances: instances,
				}
				for {
					instanceResp, instanceErr = instanceClient.DoServiceInstanceRegister(instanceCtx, instanceReq)
					if instanceErr != nil {
						log.Error(instanceErr)
						break
					}
					if instanceResp.GetServiceInstances() != nil {
						for _, v := range instanceResp.GetServiceInstances() {
							if v.GetKey() == agentUUID {
								appInsId = v.GetValue()
								break
							}
						}
					}
					if appInsId != 0 {
						break
					}
					time.Sleep(time.Second)
				}
			}

			if appInsId != 0 {
H
heyanlong 已提交
261
				t.registerCache[pid] = registerCache{
H
heyanlong 已提交
262 263 264 265
					Version:    info.Version,
					AppId:      appId,
					InstanceId: appInsId,
					Uuid:       agentUUID,
H
heyanlong 已提交
266
				}
H
heyanlong 已提交
267
				log.Infof("register pid %d appid %d insId %d", pid, appId, appInsId)
H
heyanlong 已提交
268 269
			}
		} else {
H
heyanlong 已提交
270
			log.Error("register error:", err)
H
heyanlong 已提交
271 272 273
		}
	}
}