grpc.go 6.4 KB
Newer Older
G
Gao Hongtao 已提交
1 2 3 4 5
package reporter

import (
	"context"
	"errors"
G
Gao Hongtao 已提交
6
	"github.com/golang/protobuf/proto"
G
Gao Hongtao 已提交
7 8
	"log"
	"os"
G
Gao Hongtao 已提交
9
	"time"
G
Gao Hongtao 已提交
10 11 12 13

	"google.golang.org/grpc"

	"github.com/tetratelabs/go2sky"
G
Gao Hongtao 已提交
14 15 16
	"github.com/tetratelabs/go2sky/pkg"
	"github.com/tetratelabs/go2sky/reporter/grpc/common"
	v2 "github.com/tetratelabs/go2sky/reporter/grpc/language-agent-v2"
G
Gao Hongtao 已提交
17 18 19
	"github.com/tetratelabs/go2sky/reporter/grpc/register"
)

G
Gao Hongtao 已提交
20 21 22 23 24
const (
	maxSendQueueSize    int32 = 30000
	defaultPingInterval       = 20 * time.Second
)

G
Gao Hongtao 已提交
25
var (
G
Gao Hongtao 已提交
26 27
	errServiceRegister  = errors.New("fail to register service")
	errInstanceRegister = errors.New("fail to instance service")
G
Gao Hongtao 已提交
28 29 30 31 32
)

// NewGRPCReporter create a new reporter to send data to gRPC oap server
func NewGRPCReporter(serverAddr string, opts ...GRPCReporterOption) (go2sky.Reporter, error) {
	r := &gRPCReporter{
G
Gao Hongtao 已提交
33 34 35
		logger:       log.New(os.Stderr, "go2sky", log.LstdFlags),
		sendCh:       make(chan *common.UpstreamSegment, maxSendQueueSize),
		pingInterval: defaultPingInterval,
G
Gao Hongtao 已提交
36 37 38 39 40 41 42 43 44
	}
	for _, o := range opts {
		o(r)
	}
	conn, err := grpc.Dial(serverAddr, grpc.WithInsecure()) //TODO add TLS
	if err != nil {
		return nil, err
	}
	r.conn = conn
G
Gao Hongtao 已提交
45 46 47
	r.registerClient = register.NewRegisterClient(conn)
	r.pingClient = register.NewServiceInstancePingClient(conn)
	r.traceClient = v2.NewTraceSegmentReportServiceClient(r.conn)
G
Gao Hongtao 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61
	return r, nil
}

// GRPCReporterOption allows for functional options to adjust behaviour
// of a gRPC reporter to be created by NewGRPCReporter
type GRPCReporterOption func(r *gRPCReporter)

// WithLogger setup logger for gRPC reporter
func WithLogger(logger *log.Logger) GRPCReporterOption {
	return func(r *gRPCReporter) {
		r.logger = logger
	}
}

G
Gao Hongtao 已提交
62 63 64 65 66 67 68
// WithPingInterval setup ping interval
func WithPingInterval(interval time.Duration) GRPCReporterOption {
	return func(r *gRPCReporter) {
		r.pingInterval = interval
	}
}

G
Gao Hongtao 已提交
69
type gRPCReporter struct {
G
Gao Hongtao 已提交
70 71 72 73 74 75 76 77 78 79
	serviceID      int32
	instanceID     int32
	instanceName   string
	logger         *log.Logger
	sendCh         chan *common.UpstreamSegment
	registerClient register.RegisterClient
	conn           *grpc.ClientConn
	traceClient    v2.TraceSegmentReportServiceClient
	pingClient     register.ServiceInstancePingClient
	pingInterval   time.Duration
G
Gao Hongtao 已提交
80 81
}

G
Gao Hongtao 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
func (r *gRPCReporter) Register(service string, instance string) (int32, int32, error) {
	r.retryRegister(func() error {
		return r.registerService(service)
	})
	r.retryRegister(func() error {
		return r.registerInstance(instance)
	})
	r.initSendPipeline()
	r.ping()
	return r.serviceID, r.instanceID, nil
}

type retryFunction func() error

func (r *gRPCReporter) retryRegister(f retryFunction) {
	for {
		err := f()
		if err == nil {
			break
		}
		r.logger.Printf("register error %v \n", err)
		time.Sleep(time.Second)
G
Gao Hongtao 已提交
104 105 106 107 108 109 110 111 112 113 114
	}
}

func (r *gRPCReporter) registerService(name string) error {
	in := &register.Services{
		Services: []*register.Service{
			{
				ServiceName: name,
			},
		},
	}
G
Gao Hongtao 已提交
115
	mapping, err := r.registerClient.DoServiceRegister(context.Background(), in)
G
Gao Hongtao 已提交
116 117 118 119
	if err != nil {
		return err
	}
	if len(mapping.Services) < 1 {
G
Gao Hongtao 已提交
120
		return errServiceRegister
G
Gao Hongtao 已提交
121 122
	}
	r.serviceID = mapping.Services[0].Value
G
Gao Hongtao 已提交
123
	r.logger.Printf("the id of service '%s' is %d", name, r.serviceID)
G
Gao Hongtao 已提交
124 125 126 127 128 129 130 131 132
	return nil
}

func (r *gRPCReporter) registerInstance(name string) error {
	in := &register.ServiceInstances{
		Instances: []*register.ServiceInstance{
			{
				ServiceId:    r.serviceID,
				InstanceUUID: name,
G
Gao Hongtao 已提交
133
				Time:         pkg.Millisecond(time.Now()),
G
Gao Hongtao 已提交
134 135 136
			},
		},
	}
G
Gao Hongtao 已提交
137
	mapping, err := r.registerClient.DoServiceInstanceRegister(context.Background(), in)
G
Gao Hongtao 已提交
138 139 140 141
	if err != nil {
		return err
	}
	if len(mapping.ServiceInstances) < 1 {
G
Gao Hongtao 已提交
142
		return errInstanceRegister
G
Gao Hongtao 已提交
143 144
	}
	r.instanceID = mapping.ServiceInstances[0].Value
G
Gao Hongtao 已提交
145 146
	r.instanceName = name
	r.logger.Printf("the id of instance '%s' id is %d", name, r.instanceID)
G
Gao Hongtao 已提交
147 148 149
	return nil
}

G
Gao Hongtao 已提交
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 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
func (r *gRPCReporter) Send(spans []go2sky.ReportedSpan) {
	spanSize := len(spans)
	if spanSize < 1 {
		return
	}
	rootSpan := spans[spanSize-1]
	segment := &common.UpstreamSegment{
		GlobalTraceIds: []*common.UniqueId{
			{
				IdParts: rootSpan.Context().TraceID,
			},
		},
	}
	segmentObject := &v2.SegmentObject{
		ServiceId:         r.serviceID,
		ServiceInstanceId: r.instanceID,
		TraceSegmentId: &common.UniqueId{
			IdParts: rootSpan.Context().SegmentID,
		},
		Spans: make([]*v2.SpanObjectV2, spanSize),
	}
	for i, s := range spans {
		segmentObject.Spans[i] = &v2.SpanObjectV2{
			SpanId:        s.Context().SpanID,
			ParentSpanId:  s.Context().ParentSpanID,
			StartTime:     s.StartTime(),
			EndTime:       s.EndTime(),
			OperationName: s.OperationName(),
			Peer:          s.Peer(),
			SpanType:      s.SpanType(),
			SpanLayer:     s.SpanLayer(),
			IsError:       s.IsError(),
			Tags:          s.Tags(),
			Logs:          s.Logs(),
		}
		srr := make([]*v2.SegmentReference, 0)
		if i == 0 && s.Context().ParentSpanID > -1 {
			srr = append(srr, &v2.SegmentReference{
				ParentSpanId: s.Context().ParentSpanID,
				ParentTraceSegmentId: &common.UniqueId{
					IdParts: s.Context().ParentSegmentID,
				},
				ParentServiceInstanceId: r.instanceID,
			})
		}
	}
	b, err := proto.Marshal(segmentObject)
	if err != nil {
		log.Printf("marshal segment object err %v", err)
		return
	}
	segment.Segment = b
	select {
	case r.sendCh <- segment:
	default:
		log.Printf("reach max send buffer")
	}
G
Gao Hongtao 已提交
207 208 209
}

func (r *gRPCReporter) Close() {
G
Gao Hongtao 已提交
210
	close(r.sendCh)
G
Gao Hongtao 已提交
211 212 213 214 215
	err := r.conn.Close()
	if err != nil {
		r.logger.Print(err)
	}
}
G
Gao Hongtao 已提交
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 263 264 265 266 267 268 269

func (r *gRPCReporter) initSendPipeline() {
	if r.traceClient == nil {
		return
	}
	go func() {
	StreamLoop:
		for {
			stream, err := r.traceClient.Collect(context.Background())
			for {
				select {
				case s, ok := <-r.sendCh:
					if !ok {
						r.closeStream(stream)
						return
					}
					err = stream.Send(s)
					if err != nil {
						r.logger.Printf("send segment error %v", err)
						r.closeStream(stream)
						continue StreamLoop
					}
				}
			}
		}
	}()
}

func (r *gRPCReporter) closeStream(stream v2.TraceSegmentReportService_CollectClient) {
	err := stream.CloseSend()
	if err != nil {
		r.logger.Printf("send closing error %v", err)
	}
}

func (r *gRPCReporter) ping() {
	if r.pingInterval < 0 || r.pingClient == nil {
		return
	}
	go func() {
		for {
			_, err := r.pingClient.DoPing(context.Background(), &register.ServiceInstancePingPkg{
				Time:                pkg.Millisecond(time.Now()),
				ServiceInstanceId:   r.instanceID,
				ServiceInstanceUUID: r.instanceName,
			})
			if err != nil {
				r.logger.Printf("pinging error %v", err)
			}
			time.Sleep(r.pingInterval)
		}
	}()

}