writer.go 6.0 KB
Newer Older
U
UlricQin 已提交
1 2 3 4 5
package writer

import (
	"bytes"
	"context"
U
Ulric Qin 已提交
6
	"fmt"
U
UlricQin 已提交
7 8
	"net"
	"net/http"
可爱也可不爱's avatar
可爱也可不爱 已提交
9
	"sync"
U
UlricQin 已提交
10 11
	"time"

U
Ulric Qin 已提交
12 13
	cmap "github.com/orcaman/concurrent-map"

U
UlricQin 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
	"github.com/golang/protobuf/proto"
	"github.com/golang/snappy"
	"github.com/prometheus/client_golang/api"
	"github.com/prometheus/prometheus/prompb"
	"github.com/toolkits/pkg/logger"
)

type Options struct {
	Url           string
	BasicAuthUser string
	BasicAuthPass string

	Timeout               int64
	DialTimeout           int64
	TLSHandshakeTimeout   int64
	ExpectContinueTimeout int64
	IdleConnTimeout       int64
	KeepAlive             int64

	MaxConnsPerHost     int
	MaxIdleConns        int
	MaxIdleConnsPerHost int
}

type GlobalOpt struct {
U
Ulric Qin 已提交
39 40
	QueueMaxSize int
	QueuePopSize int
U
UlricQin 已提交
41 42 43 44 45 46 47
}

type WriterType struct {
	Opts   Options
	Client api.Client
}

U
Ulric Qin 已提交
48
func (w WriterType) Write(items []*prompb.TimeSeries, headers ...map[string]string) {
U
Ulric Qin 已提交
49 50 51 52
	if len(items) == 0 {
		return
	}

U
UlricQin 已提交
53 54 55 56 57 58 59 60 61 62
	req := &prompb.WriteRequest{
		Timeseries: items,
	}

	data, err := proto.Marshal(req)
	if err != nil {
		logger.Warningf("marshal prom data to proto got error: %v, data: %+v", err, items)
		return
	}

U
Ulric Qin 已提交
63
	if err := w.Post(snappy.Encode(nil, data), headers...); err != nil {
可爱也可不爱's avatar
可爱也可不爱 已提交
64 65 66 67 68
		logger.Warningf("post to %s got error: %v", w.Opts.Url, err)
		logger.Warning("example timeseries:", items[0].String())
	}
}

U
Ulric Qin 已提交
69
func (w WriterType) Post(req []byte, headers ...map[string]string) error {
U
UlricQin 已提交
70 71 72 73 74 75 76 77 78 79 80
	httpReq, err := http.NewRequest("POST", w.Opts.Url, bytes.NewReader(req))
	if err != nil {
		logger.Warningf("create remote write request got error: %s", err.Error())
		return err
	}

	httpReq.Header.Add("Content-Encoding", "snappy")
	httpReq.Header.Set("Content-Type", "application/x-protobuf")
	httpReq.Header.Set("User-Agent", "n9e")
	httpReq.Header.Set("X-Prometheus-Remote-Write-Version", "0.1.0")

U
Ulric Qin 已提交
81 82
	if len(headers) > 0 {
		for k, v := range headers[0] {
可爱也可不爱's avatar
可爱也可不爱 已提交
83 84 85 86
			httpReq.Header.Set(k, v)
		}
	}

U
UlricQin 已提交
87 88 89 90 91 92 93 94 95 96 97
	if w.Opts.BasicAuthUser != "" {
		httpReq.SetBasicAuth(w.Opts.BasicAuthUser, w.Opts.BasicAuthPass)
	}

	resp, body, err := w.Client.Do(context.Background(), httpReq)
	if err != nil {
		logger.Warningf("push data with remote write request got error: %v, response body: %s", err, string(body))
		return err
	}

	if resp.StatusCode >= 400 {
U
Ulric Qin 已提交
98
		err = fmt.Errorf("push data with remote write request got status code: %v, response body: %s", resp.StatusCode, string(body))
U
UlricQin 已提交
99 100 101 102 103 104 105
		return err
	}

	return nil
}

type WritersType struct {
106
	globalOpt GlobalOpt
107
	backends  map[string]WriterType
108 109
	chans     cmap.ConcurrentMap
	sync.RWMutex
U
UlricQin 已提交
110 111 112
}

func (ws *WritersType) Put(name string, writer WriterType) {
113
	ws.backends[name] = writer
U
UlricQin 已提交
114 115
}

116
// PushSample Push one sample to chan, hash by ident
可爱也可不爱's avatar
可爱也可不爱 已提交
117
// @Author: quzhihao
118 119 120 121 122
func (ws *WritersType) PushSample(ident string, v interface{}) {
	if !ws.chans.Has(ident) {
		ws.Lock()
		// important: check twice
		if !ws.chans.Has(ident) {
可爱也可不爱's avatar
可爱也可不爱 已提交
123
			c := make(chan *prompb.TimeSeries, Writers.globalOpt.QueueMaxSize)
124 125
			ws.chans.Set(ident, c)
			go ws.StartConsumer(ident, c)
可爱也可不爱's avatar
可爱也可不爱 已提交
126
		}
127
		ws.Unlock()
可爱也可不爱's avatar
可爱也可不爱 已提交
128
	}
129 130

	c, ok := ws.chans.Get(ident)
可爱也可不爱's avatar
可爱也可不爱 已提交
131
	if ok {
132
		ch := c.(chan *prompb.TimeSeries)
可爱也可不爱's avatar
可爱也可不爱 已提交
133
		select {
134 135 136
		case ch <- v.(*prompb.TimeSeries):
		default:
			logger.Warningf("Write channel(%s) full, current channel size: %d", ident, len(ch))
可爱也可不爱's avatar
可爱也可不爱 已提交
137 138 139 140
		}
	}
}

141
// StartConsumer every ident channel has a consumer, start it
可爱也可不爱's avatar
可爱也可不爱 已提交
142
// @Author: quzhihao
143 144 145 146 147 148 149 150 151 152 153
func (ws *WritersType) StartConsumer(ident string, ch chan *prompb.TimeSeries) {
	var (
		batch        = ws.globalOpt.QueuePopSize
		max          = ws.globalOpt.QueueMaxSize
		batchCounter int
		closeCounter int
		series       = make([]*prompb.TimeSeries, 0, batch)
	)

	logger.Infof("Starting channel(%s) consumer, max size:%d, batch:%d", ident, max, batch)

可爱也可不爱's avatar
可爱也可不爱 已提交
154 155
	for {
		select {
156 157 158
		case item := <-ch:
			// has data, no need to close
			closeCounter = 0
可爱也可不爱's avatar
可爱也可不爱 已提交
159
			series = append(series, item)
160 161 162 163 164 165 166

			batchCounter++
			if batchCounter >= ws.globalOpt.QueuePopSize {
				ws.post(ident, series)

				// reset
				batchCounter = 0
可爱也可不爱's avatar
可爱也可不爱 已提交
167 168
				series = make([]*prompb.TimeSeries, 0, batch)
			}
169
		case <-time.After(time.Second):
可爱也可不爱's avatar
可爱也可不爱 已提交
170
			if len(series) > 0 {
171 172 173 174 175 176 177
				// has data, no need to close
				closeCounter = 0

				ws.post(ident, series)

				// reset
				batchCounter = 0
可爱也可不爱's avatar
可爱也可不爱 已提交
178 179
				series = make([]*prompb.TimeSeries, 0, batch)
			} else {
180
				closeCounter++
可爱也可不爱's avatar
可爱也可不爱 已提交
181
			}
182 183 184 185 186 187 188 189 190 191 192

			if closeCounter > 3600 {
				logger.Infof("Closing channel(%s) reason: no data for an hour", ident)

				ws.Lock()
				close(ch)
				ws.chans.Remove(ident)
				ws.Unlock()

				logger.Infof("Closed channel(%s) reason: no data for an hour", ident)

可爱也可不爱's avatar
可爱也可不爱 已提交
193 194 195 196 197 198
				return
			}
		}
	}
}

199
// post post series to TSDB
可爱也可不爱's avatar
可爱也可不爱 已提交
200
// @Author: quzhihao
201 202
func (ws *WritersType) post(ident string, series []*prompb.TimeSeries) {
	// maybe as backend hashstring
U
Ulric Qin 已提交
203
	headers := map[string]string{"ident": ident}
204
	for key := range ws.backends {
205
		go ws.backends[key].Write(series, headers)
可爱也可不爱's avatar
可爱也可不爱 已提交
206 207 208
	}
}

U
UlricQin 已提交
209 210
func NewWriters() WritersType {
	return WritersType{
211
		backends: make(map[string]WriterType),
U
UlricQin 已提交
212 213 214 215 216 217 218
	}
}

var Writers = NewWriters()

func Init(opts []Options, globalOpt GlobalOpt) error {
	Writers.globalOpt = globalOpt
219
	Writers.chans = cmap.New()
U
UlricQin 已提交
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

	for i := 0; i < len(opts); i++ {
		cli, err := api.NewClient(api.Config{
			Address: opts[i].Url,
			RoundTripper: &http.Transport{
				// TLSClientConfig: tlsConfig,
				Proxy: http.ProxyFromEnvironment,
				DialContext: (&net.Dialer{
					Timeout:   time.Duration(opts[i].DialTimeout) * time.Millisecond,
					KeepAlive: time.Duration(opts[i].KeepAlive) * time.Millisecond,
				}).DialContext,
				ResponseHeaderTimeout: time.Duration(opts[i].Timeout) * time.Millisecond,
				TLSHandshakeTimeout:   time.Duration(opts[i].TLSHandshakeTimeout) * time.Millisecond,
				ExpectContinueTimeout: time.Duration(opts[i].ExpectContinueTimeout) * time.Millisecond,
				MaxConnsPerHost:       opts[i].MaxConnsPerHost,
				MaxIdleConns:          opts[i].MaxIdleConns,
				MaxIdleConnsPerHost:   opts[i].MaxIdleConnsPerHost,
				IdleConnTimeout:       time.Duration(opts[i].IdleConnTimeout) * time.Millisecond,
			},
		})

		if err != nil {
			return err
		}

		writer := WriterType{
			Opts:   opts[i],
			Client: cli,
		}

U
Ulric Qin 已提交
250
		Writers.Put(opts[i].Url, writer)
U
UlricQin 已提交
251 252 253 254
	}

	return nil
}