Skip to content

Commit

Permalink
Merge pull request grafana#121 from grafana/main
Browse files Browse the repository at this point in the history
Update from upstream repository
  • Loading branch information
periklis authored Mar 21, 2023
2 parents 85825ba + ee371a8 commit 1bd2eee
Show file tree
Hide file tree
Showing 87 changed files with 30,409 additions and 493 deletions.
8 changes: 8 additions & 0 deletions .drone/drone.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,14 @@ local manifest_ecr(apps, archs) = pipeline('manifest-ecr') {
],
// Package and test the packages
steps: [
{
name: 'fetch-tags',
image: 'alpine',
commands: [
'apk add --no-cache bash git',
'git fetch origin --tags',
],
},
run('write-key',
commands=['printf "%s" "$NFPM_SIGNING_KEY" > $NFPM_SIGNING_KEY_FILE'],
env={
Expand Down
7 changes: 6 additions & 1 deletion .drone/drone.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1410,6 +1410,11 @@ services:
- name: cgroup
path: /sys/fs/cgroup
steps:
- commands:
- apk add --no-cache bash git
- git fetch origin --tags
image: alpine
name: fetch-tags
- commands:
- printf "%s" "$NFPM_SIGNING_KEY" > $NFPM_SIGNING_KEY_FILE
environment:
Expand Down Expand Up @@ -1727,6 +1732,6 @@ kind: secret
name: gpg_private_key
---
kind: signature
hmac: ae19447e0f2e91746c5b4e6a3dc469a08a63c44045f4b995a6980d0e401e071f
hmac: b5d3d292a9e1f7edc909dd0aa28664f1aa5794f4abe639dc1df8d9bbea5b5c13

...
4 changes: 2 additions & 2 deletions .github/workflows/operator-images.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ jobs:
- name: Build and publish image on quay.io
uses: docker/build-push-action@v4
with:
context: ./operator
file: ./operator/bundle.Dockerfile
context: ./operator/bundle/openshift
file: ./operator/bundle/openshift/bundle.Dockerfile
push: true
tags: "${{ steps.image_tags.outputs.IMAGE_TAGS }}"

Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

##### Enhancements

* [8848](https://github.com/grafana/loki/pull/8848) **dannykopping**: Ruler: add configurable rule evaluation jitter.
* [8752](https://github.com/grafana/loki/pull/8752) **chaudum**: Add query fairness control across actors within a tenant to scheduler, which can be enabled by passing the `X-Loki-Actor-Path` header to the HTTP request of the query.
* [8786](https://github.com/grafana/loki/pull/8786) **DylanGuedes**: Ingester: add new /ingester/prepare_shutdown endpoint.
* [8744](https://github.com/grafana/loki/pull/8744) **dannykopping**: Ruler: remote rule evaluation.
* [8727](https://github.com/grafana/loki/pull/8727) **cstyan** **jeschkies**: Propagate per-request limit header to querier.
* [8682](https://github.com/grafana/loki/pull/8682) **dannykopping**: Add fetched chunk size distribution metric `loki_chunk_fetcher_fetched_size_bytes`.
Expand Down Expand Up @@ -96,6 +99,7 @@
#### Jsonnet

* [7923](https://github.com/grafana/loki/pull/7923) **manohar-koukuntla**: Add zone aware ingesters in jsonnet deployment
* [8855](https://github.com/grafana/loki/pull/8855) **JoaoBraveCoding**: Add gRPC port to loki compactor mixin

##### Fixes

Expand Down
1 change: 0 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ BUILD_IMAGE_VERSION := 0.28.1
# Docker image info
IMAGE_PREFIX ?= grafana

FETCH_TAGS :=$(shell ./tools/fetch-tags)
IMAGE_TAG := $(shell ./tools/image-tag)

# Version info for binaries
Expand Down
113 changes: 113 additions & 0 deletions clients/pkg/logentry/stages/sampling.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package stages

import (
"math"
"math/rand"
"time"

"github.com/go-kit/log"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/uber/jaeger-client-go/utils"
)

const (
ErrSamplingStageInvalidRate = "sampling stage failed to parse rate,Sampling Rate must be between 0.0 and 1.0, received %f"
)
const maxRandomNumber = ^(uint64(1) << 63) // i.e. 0x7fffffffffffffff

var (
defaultSamplingpReason = "sampling_stage"
)

// SamplingConfig contains the configuration for a samplingStage
type SamplingConfig struct {
DropReason *string `mapstructure:"drop_counter_reason"`
//
SamplingRate float64 `mapstructure:"rate"`
}

// validateSamplingConfig validates the SamplingConfig for the sampleStage
func validateSamplingConfig(cfg *SamplingConfig) error {
if cfg.DropReason == nil || *cfg.DropReason == "" {
cfg.DropReason = &defaultSamplingpReason
}
if cfg.SamplingRate < 0.0 || cfg.SamplingRate > 1.0 {
return errors.Errorf(ErrSamplingStageInvalidRate, cfg.SamplingRate)
}

return nil
}

// newSamplingStage creates a SamplingStage from config
// code from jaeger project.
// github.com/uber/jaeger-client-go@v2.30.0+incompatible/tracer.go:126
func newSamplingStage(logger log.Logger, config interface{}, registerer prometheus.Registerer) (Stage, error) {
cfg := &SamplingConfig{}
err := mapstructure.WeakDecode(config, cfg)
if err != nil {
return nil, err
}
err = validateSamplingConfig(cfg)
if err != nil {
return nil, err
}

samplingRate := math.Max(0.0, math.Min(cfg.SamplingRate, 1.0))
samplingBoundary := uint64(float64(maxRandomNumber) * samplingRate)
seedGenerator := utils.NewRand(time.Now().UnixNano())
source := rand.NewSource(seedGenerator.Int63())
return &samplingStage{
logger: log.With(logger, "component", "stage", "type", "sampling"),
cfg: cfg,
dropCount: getDropCountMetric(registerer),
samplingBoundary: samplingBoundary,
source: source,
}, nil
}

type samplingStage struct {
logger log.Logger
cfg *SamplingConfig
dropCount *prometheus.CounterVec
samplingBoundary uint64
source rand.Source
}

func (m *samplingStage) Run(in chan Entry) chan Entry {
out := make(chan Entry)
go func() {
defer close(out)
for e := range in {
if m.isSampled() {
out <- e
continue
}
m.dropCount.WithLabelValues(*m.cfg.DropReason).Inc()
}
}()
return out
}

// code from jaeger project.
// github.com/uber/jaeger-client-go@v2.30.0+incompatible/sampler.go:144
// func (s *ProbabilisticSampler) IsSampled(id TraceID, operation string) (bool, []Tag)
func (m *samplingStage) isSampled() bool {
return m.samplingBoundary >= m.randomID()&maxRandomNumber
}
func (m *samplingStage) randomID() uint64 {
val := m.randomNumber()
for val == 0 {
val = m.randomNumber()
}
return val
}
func (m *samplingStage) randomNumber() uint64 {
return uint64(m.source.Int63())
}

// Name implements Stage
func (m *samplingStage) Name() string {
return StageTypeSampling
}
62 changes: 62 additions & 0 deletions clients/pkg/logentry/stages/sampling_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package stages

import (
"fmt"
"testing"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

util_log "github.com/grafana/loki/pkg/util/log"
)

var testSampingYaml = `
pipeline_stages:
- sampling:
rate: 0.5
`

func TestSamplingPipeline(t *testing.T) {
registry := prometheus.NewRegistry()
pl, err := NewPipeline(util_log.Logger, loadConfig(testSampingYaml), &plName, registry)
require.NoError(t, err)

entries := make([]Entry, 0)
for i := 0; i < 100; i++ {
entries = append(entries, newEntry(nil, nil, testMatchLogLineApp1, time.Now()))
}

out := processEntries(pl, entries...,
)
// sampling rate = 0.5,entries len = 100,
// The theoretical sample size is 50.
// 50>30 and 50<70
assert.GreaterOrEqual(t, len(out), 30)
assert.LessOrEqual(t, len(out), 70)

}

func Test_validateSamplingConfig(t *testing.T) {
tests := []struct {
name string
config *SamplingConfig
wantErr error
}{
{
name: "Invalid rate",
config: &SamplingConfig{
SamplingRate: 12,
},
wantErr: fmt.Errorf(ErrSamplingStageInvalidRate, 12.0),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := validateSamplingConfig(tt.config); ((err != nil) && (err.Error() != tt.wantErr.Error())) || (err == nil && tt.wantErr != nil) {
t.Errorf("validateDropConfig() error = %v, wantErr = %v", err, tt.wantErr)
}
})
}
}
6 changes: 6 additions & 0 deletions clients/pkg/logentry/stages/stage.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const (
StageTypePipeline = "pipeline"
StageTypeTenant = "tenant"
StageTypeDrop = "drop"
StageTypeSampling = "sampling"
StageTypeLimit = "limit"
StageTypeMultiline = "multiline"
StageTypePack = "pack"
Expand Down Expand Up @@ -187,6 +188,11 @@ func New(logger log.Logger, jobName *string, stageType string,
if err != nil {
return nil, err
}
case StageTypeSampling:
s, err = newSamplingStage(logger, cfg, registerer)
if err != nil {
return nil, err
}
case StageTypeLimit:
s, err = newLimitStage(logger, cfg, registerer)
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions clients/pkg/promtail/targets/syslog/syslogtarget_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,8 +361,8 @@ func TestSyslogTarget(t *testing.T) {
protocol string
fmtFunc formatFunc
}{
{"tpc newline separated", protocolTCP, fmtNewline},
{"tpc octetcounting", protocolTCP, fmtOctetCounting},
{"tcp newline separated", protocolTCP, fmtNewline},
{"tcp octetcounting", protocolTCP, fmtOctetCounting},
{"udp newline separated", protocolUDP, fmtNewline},
{"udp octetcounting", protocolUDP, fmtOctetCounting},
} {
Expand Down Expand Up @@ -478,8 +478,8 @@ func TestSyslogTarget_RFC5424Messages(t *testing.T) {
protocol string
fmtFunc formatFunc
}{
{"tpc newline separated", protocolTCP, fmtNewline},
{"tpc octetcounting", protocolTCP, fmtOctetCounting},
{"tcp newline separated", protocolTCP, fmtNewline},
{"tcp octetcounting", protocolTCP, fmtOctetCounting},
} {
tt := tt
t.Run(tt.name, func(t *testing.T) {
Expand Down
20 changes: 15 additions & 5 deletions docs/sources/rules/_index.md → docs/sources/alert/_index.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
---
title: Alerting and recording rules
menuTitle: Alert
description: Learn how the rule evaluates queries for alerting.

aliases:
- /alerting/
title: Alerting and Recording Rules
description: Alerting and Recording Rules
weight: 700
- /docs/loki/latest/rules/
- docs/loki/latest/alert/
- docs/loki/latest/alerting/

weight: 850
keywords:
- loki
- alert
- alerting
- ruler
---

# Alerting and Recording Rules
# Alerting and recording rules

Grafana Loki includes a component called the ruler. The ruler is responsible for continually evaluating a set of configurable queries and performing an action based on the result.

Expand Down
13 changes: 12 additions & 1 deletion docs/sources/api/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,17 @@ backing store. Mainly used for local testing.

In microservices mode, the `/flush` endpoint is exposed by the ingester.

### Tell ingester to release all resources on next SIGTERM

```
POST /ingester/prepare_shutdown
```

`/ingester/prepare_shutdown` will prepare the ingester to release resources on the next SIGTERM signal,
where releasing resources means flushing data and unregistering from the ingester ring.
This endpoint supersedes any YAML configurations and isn't necessary if the ingester is already
configured to unregister from the ring or to flush on shutdown.

## Flush in-memory chunks and shut down

```
Expand Down Expand Up @@ -1401,4 +1412,4 @@ $ curl -H "Content-Type: application/json" -XPOST -s "https://localhost:3100/api
This is helpful for scaling down WAL-enabled ingesters where we want to ensure old WAL directories are not orphaned,
but instead flushed to our chunk backend.

In microservices mode, the `/ingester/flush_shutdown` endpoint is exposed by the ingester.
In microservices mode, the `/ingester/flush_shutdown` endpoint is exposed by the ingester.
8 changes: 4 additions & 4 deletions docs/sources/clients/promtail/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ Where default_value is the value to use if the environment variable is undefined

**Note**: With `expand-env=true` the configuration will first run through
[envsubst](https://pkg.go.dev/github.com/drone/envsubst) which will replace double
slashes with single slashes. Because of this every use of a slash `\` needs to
be replaced with a double slash `\\`
backslashes with single backslashes. Because of this every use of a backslash `\` needs to
be replaced with a double backslash `\\`

### Generic placeholders

Expand Down Expand Up @@ -663,7 +663,7 @@ config:
# Must be either "inc" or "add" (case insensitive). If
# inc is chosen, the metric value will increase by 1 for each
# log line received that passed the filter. If add is chosen,
# the extracted value most be convertible to a positive float
# the extracted value must be convertible to a positive float
# and its value will be added to the metric.
action: <string>
```
Expand Down Expand Up @@ -720,7 +720,7 @@ config:
# Must be either "inc" or "add" (case insensitive). If
# inc is chosen, the metric value will increase by 1 for each
# log line received that passed the filter. If add is chosen,
# the extracted value most be convertible to a positive float
# the extracted value must be convertible to a positive float
# and its value will be added to the metric.
action: <string>
Expand Down
1 change: 1 addition & 0 deletions docs/sources/clients/promtail/stages/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Action stages:
- [labelallow]({{<relref "labelallow">}}): Allow label set for the log entry.
- [labels]({{<relref "labels">}}): Update the label set for the log entry.
- [limit]({{<relref "limit">}}): Limit the rate lines will be sent to Loki.
- [sampling]({{<relref "sampling">}}): Sampling the lines will be sent to Loki.
- [static_labels]({{<relref "static_labels">}}): Add static-labels to the log entry.
- [metrics]({{<relref "metrics">}}): Calculate metrics based on extracted data.
- [tenant]({{<relref "tenant">}}): Set the tenant ID value to use for the log entry.
Expand Down
4 changes: 2 additions & 2 deletions docs/sources/clients/promtail/stages/regex.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ But these are not:

If you run Promtail with the `--config.expand-env=true` flag the configuration
will run through [envsubst](https://pkg.go.dev/github.com/drone/envsubst) which will
replace double slashes with single slashes. Because of this when using
`expand-env=true` you need to use double slashes for each single slash. For
replace double backslashes with single backslashes. Because of this when using
`expand-env=true` you need to use double backslashes for each single backslash. For
example:

- `expression: '\w*'` must be `expression: '\\w*'`
Expand Down
Loading

0 comments on commit 1bd2eee

Please sign in to comment.