-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathutils.go
109 lines (95 loc) · 2.11 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"fmt"
"log"
"sort"
"strings"
"time"
"github.com/fatih/color"
"github.com/grafana/loki/pkg/logproto"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql"
)
// print a log entry
func printLogEntry(ts time.Time, lbls string, line string) {
fmt.Println(
color.BlueString(ts.Format(time.RFC3339)),
color.RedString(lbls),
strings.TrimSpace(line),
)
}
// add some padding after labels
func padLabel(ls labels.Labels, maxLabelsLen int) string {
labels := ls.String()
if len(labels) < maxLabelsLen {
labels += strings.Repeat(" ", maxLabelsLen-len(labels))
}
return labels
}
// parse labels from string
func mustParseLabels(labels string) labels.Labels {
ls, err := promql.ParseMetric(labels)
if err != nil {
log.Fatalf("Failed to parse labels: %+v", err)
}
return ls
}
// parse labels from response stream
func parseLabels(resp *logproto.QueryResponse) (map[string]labels.Labels, []labels.Labels) {
cache := make(map[string]labels.Labels, len(resp.Streams))
lss := make([]labels.Labels, 0, len(resp.Streams))
for _, stream := range resp.Streams {
ls := mustParseLabels(stream.Labels)
cache[stream.Labels] = ls
lss = append(lss, ls)
}
return cache, lss
}
// return common labels between given lavels set
func commonLabels(lss []labels.Labels) labels.Labels {
if len(lss) == 0 {
return nil
}
result := lss[0]
for i := 1; i < len(lss); i++ {
result = intersect(result, lss[i])
}
return result
}
// intersect two labels set
func intersect(a, b labels.Labels) labels.Labels {
set := labels.Labels{}
ma := a.Map()
mb := b.Map()
for ka, va := range ma {
if vb, ok := mb[ka]; ok {
if vb == va {
set = append(set, labels.Label{
Name: ka,
Value: va,
})
}
}
}
sort.Sort(set)
return set
}
// subtract labels set b from labels set a
func subtract(a, b labels.Labels) labels.Labels {
set := labels.Labels{}
ma := a.Map()
mb := b.Map()
for ka, va := range ma {
if vb, ok := mb[ka]; ok {
if vb == va {
continue
}
}
set = append(set, labels.Label{
Name: ka,
Value: va,
})
}
sort.Sort(set)
return set
}