writer.go 7.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 39 40 41 42 43 44 45 46 47 48 49
	"github.com/golang/protobuf/proto"
	"github.com/golang/snappy"
	"github.com/prometheus/client_golang/api"
	"github.com/prometheus/prometheus/prompb"
	"github.com/toolkits/pkg/container/list"
	"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 {
	QueueMaxSize  int
	QueuePopSize  int
	SleepInterval int64
}

type WriterType struct {
	Opts   Options
	Client api.Client
}

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

U
UlricQin 已提交
55 56 57 58 59 60 61 62 63 64
	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 已提交
65
	if err := w.Post(snappy.Encode(nil, data), headers...); err != nil {
可爱也可不爱's avatar
可爱也可不爱 已提交
66 67 68 69 70
		logger.Warningf("post to %s got error: %v", w.Opts.Url, err)
		logger.Warning("example timeseries:", items[0].String())
	}
}

U
Ulric Qin 已提交
71
func (w WriterType) Post(req []byte, headers ...map[string]string) error {
U
UlricQin 已提交
72 73 74 75 76 77 78 79 80 81 82
	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 已提交
83 84
	if len(headers) > 0 {
		for k, v := range headers[0] {
可爱也可不爱's avatar
可爱也可不爱 已提交
85 86 87 88
			httpReq.Header.Set(k, v)
		}
	}

U
UlricQin 已提交
89 90 91 92 93 94 95 96 97 98 99
	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 已提交
100
		err = fmt.Errorf("push data with remote write request got status code: %v, response body: %s", resp.StatusCode, string(body))
U
UlricQin 已提交
101 102 103 104 105 106 107
		return err
	}

	return nil
}

type WritersType struct {
108 109 110 111 112
	globalOpt GlobalOpt
	m         map[string]WriterType
	queue     *list.SafeListLimited
	chans     cmap.ConcurrentMap
	sync.RWMutex
U
UlricQin 已提交
113 114 115 116 117 118 119 120 121 122
}

func (ws *WritersType) Put(name string, writer WriterType) {
	ws.m[name] = writer
}

func (ws *WritersType) PushQueue(vs []interface{}) bool {
	return ws.queue.PushFrontBatch(vs)
}

123
// PushSample Push one sample to chan, hash by ident
可爱也可不爱's avatar
可爱也可不爱 已提交
124
// @Author: quzhihao
125 126 127 128 129
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
可爱也可不爱 已提交
130
			c := make(chan *prompb.TimeSeries, Writers.globalOpt.QueueMaxSize)
131 132
			ws.chans.Set(ident, c)
			go ws.StartConsumer(ident, c)
可爱也可不爱's avatar
可爱也可不爱 已提交
133
		}
134
		ws.Unlock()
可爱也可不爱's avatar
可爱也可不爱 已提交
135
	}
136 137

	c, ok := ws.chans.Get(ident)
可爱也可不爱's avatar
可爱也可不爱 已提交
138
	if ok {
139
		ch := c.(chan *prompb.TimeSeries)
可爱也可不爱's avatar
可爱也可不爱 已提交
140
		select {
141 142 143
		case ch <- v.(*prompb.TimeSeries):
		default:
			logger.Warningf("Write channel(%s) full, current channel size: %d", ident, len(ch))
可爱也可不爱's avatar
可爱也可不爱 已提交
144 145 146 147
		}
	}
}

148
// StartConsumer every ident channel has a consumer, start it
可爱也可不爱's avatar
可爱也可不爱 已提交
149
// @Author: quzhihao
150 151 152 153 154 155 156 157 158 159 160
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
可爱也可不爱 已提交
161 162
	for {
		select {
163 164 165
		case item := <-ch:
			// has data, no need to close
			closeCounter = 0
可爱也可不爱's avatar
可爱也可不爱 已提交
166
			series = append(series, item)
167 168 169 170 171 172 173

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

				// reset
				batchCounter = 0
可爱也可不爱's avatar
可爱也可不爱 已提交
174 175
				series = make([]*prompb.TimeSeries, 0, batch)
			}
176
		case <-time.After(time.Second):
可爱也可不爱's avatar
可爱也可不爱 已提交
177
			if len(series) > 0 {
178 179 180 181 182 183 184
				// has data, no need to close
				closeCounter = 0

				ws.post(ident, series)

				// reset
				batchCounter = 0
可爱也可不爱's avatar
可爱也可不爱 已提交
185 186
				series = make([]*prompb.TimeSeries, 0, batch)
			} else {
187
				closeCounter++
可爱也可不爱's avatar
可爱也可不爱 已提交
188
			}
189 190 191 192 193 194 195 196 197 198 199

			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
可爱也可不爱 已提交
200 201 202 203 204 205
				return
			}
		}
	}
}

206
// post post series to TSDB
可爱也可不爱's avatar
可爱也可不爱 已提交
207
// @Author: quzhihao
208
func (ws *WritersType) post(ident string, series []*prompb.TimeSeries) {
可爱也可不爱's avatar
可爱也可不爱 已提交
209 210
	wg := sync.WaitGroup{}
	wg.Add(len(ws.m))
U
Ulric Qin 已提交
211

212
	// maybe as backend hashstring
U
Ulric Qin 已提交
213
	headers := map[string]string{"ident": ident}
可爱也可不爱's avatar
可爱也可不爱 已提交
214 215 216
	for key := range ws.m {
		go func(key string) {
			defer wg.Done()
U
Ulric Qin 已提交
217
			ws.m[key].Write(series, headers)
可爱也可不爱's avatar
可爱也可不爱 已提交
218 219
		}(key)
	}
U
Ulric Qin 已提交
220

可爱也可不爱's avatar
可爱也可不爱 已提交
221 222 223
	wg.Wait()
}

U
UlricQin 已提交
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 270
func (ws *WritersType) Writes() {
	batch := ws.globalOpt.QueuePopSize
	if batch <= 0 {
		batch = 2000
	}

	duration := time.Duration(ws.globalOpt.SleepInterval) * time.Millisecond

	for {
		items := ws.queue.PopBackBy(batch)
		count := len(items)
		if count == 0 {
			time.Sleep(duration)
			continue
		}

		series := make([]*prompb.TimeSeries, 0, count)
		for i := 0; i < count; i++ {
			item, ok := items[i].(*prompb.TimeSeries)
			if !ok {
				// in theory, it can be converted successfully
				continue
			}
			series = append(series, item)
		}

		if len(series) == 0 {
			continue
		}

		for key := range ws.m {
			go ws.m[key].Write(series)
		}
	}
}

func NewWriters() WritersType {
	return WritersType{
		m: make(map[string]WriterType),
	}
}

var Writers = NewWriters()

func Init(opts []Options, globalOpt GlobalOpt) error {
	Writers.globalOpt = globalOpt
	Writers.queue = list.NewSafeListLimited(globalOpt.QueueMaxSize)
271
	Writers.chans = cmap.New()
U
UlricQin 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

	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 已提交
302
		Writers.Put(opts[i].Url, writer)
U
UlricQin 已提交
303 304 305 306 307 308
	}

	go Writers.Writes()

	return nil
}