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 58 59
func (t *Agent) recoverRegister(r string) {
	var info trace
	err := json.Unmarshal([]byte(r), &info)
	if err == nil {
		if _, ok := t.registerCache.Load(info.Pid); !ok {
			t.registerCache.Store(info.Pid, registerCache{
				Version:    info.Version,
				AppId:      info.ApplicationId,
				InstanceId: info.ApplicationInstance,
				Uuid:       info.Uuid,
			})
		}
	}
}

H
heyanlong 已提交
60 61 62 63 64
func (t *Agent) doRegister(r *register) {

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

	pid := info.Pid
	if value, ok := t.registerCache.Load(pid); ok {
		bind := value.(registerCache)
H
heyanlong 已提交
73 74
		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 已提交
75 76 77 78 79 80 81 82 83 84
		return
	} else {
		r.c.Write([]byte(""))
	}

	t.registerCacheLock.Lock()
	defer t.registerCacheLock.Unlock()

	// if map not found pid.. start register
	if _, ok := t.registerCache.Load(pid); !ok {
H
heyanlong 已提交
85
		log.Infof("start register pid %d used SkyWalking v%d", pid, info.Version)
H
heyanlong 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
		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 已提交
105
					log.Error("register error:", regErr)
H
heyanlong 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
					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 已提交
131
					log.Error("register error:", regErr)
H
heyanlong 已提交
132 133 134 135 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
					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 已提交
177
						log.Error("register error:", instanceErr)
H
heyanlong 已提交
178 179 180 181 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 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 261 262
						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

				instances = append(instances, &register2.ServiceInstance{
					ServiceId:    appId,
					InstanceUUID: agentUUID,
					Time:         time.Now().UnixNano() / 1000000,
					Properties:   properties,
				})

				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",
					Value: string(pid),
				})

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

				for _, ip := range ip4s() {
					properties = append(properties, &common.KeyStringValuePair{
						Key:   "ipV4s",
						Value: ip,
					})
				}

				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 {
				t.registerCache.Store(pid, registerCache{
					Version:    info.Version,
					AppId:      appId,
					InstanceId: appInsId,
					Uuid:       agentUUID,
				})
H
heyanlong 已提交
263
				log.Infof("register pid %d appid %d insId %d", pid, appId, appInsId)
H
heyanlong 已提交
264 265
			}
		} else {
H
heyanlong 已提交
266
			log.Error("register error:", err)
H
heyanlong 已提交
267 268 269
		}
	}
}