writer.go 7.3 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
}

可爱也可不爱's avatar
可爱也可不爱 已提交
50 51
var lock = sync.RWMutex{}

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

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

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

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

	return nil
}

type WritersType struct {
可爱也可不爱's avatar
可爱也可不爱 已提交
110 111 112 113
	globalOpt    GlobalOpt
	m            map[string]WriterType
	queue        *list.SafeListLimited
	IdentChanMap cmap.ConcurrentMap
U
UlricQin 已提交
114 115 116 117 118 119 120 121 122 123
}

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

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

可爱也可不爱's avatar
可爱也可不爱 已提交
124 125 126 127 128 129 130 131 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 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 207 208 209 210 211 212 213 214 215
//
// PushIdentChan 放入chan, 以ident分发
// @Author: quzhihao
// @Description:
// @receiver ws
// @param ident
// @param vs
//
func (ws *WritersType) PushIdentChan(ident string, vs interface{}) {
	if !ws.IdentChanMap.Has(ident) {
		lock.Lock()
		if !ws.IdentChanMap.Has(ident) {
			c := make(chan *prompb.TimeSeries, Writers.globalOpt.QueueMaxSize)
			ws.IdentChanMap.Set(ident, c)
			go func() {
				ws.InitIdentChanWorker(ident, c)
			}()
		}
		lock.Unlock()
	}
	// 往chan扔会导致内存不断增大,如果写入阻塞了,需要提示
	c, ok := ws.IdentChanMap.Get(ident)
	ch := c.(chan *prompb.TimeSeries)
	if ok {
		select {
		case ch <- vs.(*prompb.TimeSeries):
		case <-time.After(time.Duration(200) * time.Millisecond):
			logger.Warningf("[%s] Write IdentChanMap Full, DropSize: %d", ident, len(ch))
		}
	}
}

//
// InitIdentChanWorker 初始化ident消费者
// @Author: quzhihao
// @Description:
// @receiver ws
// @param ident
// @param data
//
func (ws *WritersType) InitIdentChanWorker(ident string, data chan *prompb.TimeSeries) {
	popCounter := 0
	batch := ws.globalOpt.QueuePopSize
	if batch <= 0 {
		batch = 1000
	}
	logger.Infof("[%s] Start Ident Chan Worker, MaxSize:%d, batchSize:%d", ident, ws.globalOpt.QueueMaxSize, batch)
	series := make([]*prompb.TimeSeries, 0, batch)
	closePrepareCounter := 0
	for {
		select {
		case item := <-data:
			closePrepareCounter = 0
			series = append(series, item)
			popCounter++
			if popCounter >= ws.globalOpt.QueuePopSize {
				popCounter = 0
				// 发送到prometheus
				ws.postPrometheus(ident, series)
				series = make([]*prompb.TimeSeries, 0, batch)
			}
		case <-time.After(10 * time.Second):
			// 10秒清空一下,如果有数据的话
			if len(series) > 0 {
				ws.postPrometheus(ident, series)
				series = make([]*prompb.TimeSeries, 0, batch)
				closePrepareCounter = 0
			} else {
				closePrepareCounter++
			}
			// 一小时没数据,就关闭chan
			if closePrepareCounter > 6*60 {
				logger.Infof("[%s] Ident Chan Closing. Reason: No Data For An Hour.", ident)
				lock.Lock()
				close(data)
				// 移除
				ws.IdentChanMap.Remove(ident)
				lock.Unlock()
				logger.Infof("[%s] Ident Chan Closed Success.", ident)
				return
			}
		}
	}
}

//
// postPrometheus 发送数据至prometheus
// @Author: quzhihao
//
func (ws *WritersType) postPrometheus(ident string, series []*prompb.TimeSeries) {
	wg := sync.WaitGroup{}
	wg.Add(len(ws.m))
U
Ulric Qin 已提交
216 217

	headers := map[string]string{"ident": ident}
可爱也可不爱's avatar
可爱也可不爱 已提交
218 219 220
	for key := range ws.m {
		go func(key string) {
			defer wg.Done()
U
Ulric Qin 已提交
221
			ws.m[key].Write(series, headers)
可爱也可不爱's avatar
可爱也可不爱 已提交
222 223
		}(key)
	}
U
Ulric Qin 已提交
224

可爱也可不爱's avatar
可爱也可不爱 已提交
225 226 227
	wg.Wait()
}

U
UlricQin 已提交
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 271 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 302 303 304
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)

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

	go Writers.Writes()

	return nil
}