@ -6,7 +6,6 @@ import (
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/grafana/loki/pkg/logproto"
"github.com/prometheus/common/model"
)
// batch holds pending log streams waiting to be sent to Loki, and it's used
@ -14,14 +13,14 @@ import (
// and entries in a single batch request. In case of multi-tenant Promtail, log
// streams for each tenant are stored in a dedicated batch.
type batch struct {
streams map [ model . Fingerprint ] * logproto . Stream
streams map [ string ] * logproto . Stream
bytes int
createdAt time . Time
}
func newBatch ( entries ... entry ) * batch {
b := & batch {
streams : map [ model . Fingerprint ] * logproto . Stream { } ,
streams : map [ string ] * logproto . Stream { } ,
bytes : 0 ,
createdAt : time . Now ( ) ,
}
@ -39,15 +38,15 @@ func (b *batch) add(entry entry) {
b . bytes += len ( entry . Line )
// Append the entry to an already existing stream (if any)
fp := entry . labels . FastFingerprint ( )
if stream , ok := b . streams [ fp ] ; ok {
labels := entry . labels . String ( )
if stream , ok := b . streams [ labels ] ; ok {
stream . Entries = append ( stream . Entries , entry . Entry )
return
}
// Add the entry as a new stream
b . streams [ fp ] = & logproto . Stream {
Labels : entry . labels . String ( ) ,
b . streams [ labels ] = & logproto . Stream {
Labels : labels ,
Entries : [ ] logproto . Entry { entry . Entry } ,
}
}
@ -71,6 +70,17 @@ func (b *batch) age() time.Duration {
// encode the batch as snappy-compressed push request, and returns
// the encoded bytes and the number of encoded entries
func ( b * batch ) encode ( ) ( [ ] byte , int , error ) {
req , entriesCount := b . createPushRequest ( )
buf , err := proto . Marshal ( req )
if err != nil {
return nil , 0 , err
}
buf = snappy . Encode ( nil , buf )
return buf , entriesCount , nil
}
// creates push request and returns it, together with number of entries
func ( b * batch ) createPushRequest ( ) ( * logproto . PushRequest , int ) {
req := logproto . PushRequest {
Streams : make ( [ ] * logproto . Stream , 0 , len ( b . streams ) ) ,
}
@ -80,11 +90,5 @@ func (b *batch) encode() ([]byte, int, error) {
req . Streams = append ( req . Streams , stream )
entriesCount += len ( stream . Entries )
}
buf , err := proto . Marshal ( & req )
if err != nil {
return nil , 0 , err
}
buf = snappy . Encode ( nil , buf )
return buf , entriesCount , nil
return & req , entriesCount
}