-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
labels.go
108 lines (91 loc) · 2.19 KB
/
labels.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
package loghttp
import (
"errors"
"net/http"
"sort"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/grafana/jsonparser"
"github.com/grafana/loki/v3/pkg/logproto"
)
// LabelResponse represents the http json response to a label query
type LabelResponse struct {
Status string `json:"status"`
Data []string `json:"data,omitempty"`
}
// LabelSet is a key/value pair mapping of labels
type LabelSet map[string]string
func (l *LabelSet) UnmarshalJSON(data []byte) error {
if *l == nil {
*l = make(LabelSet)
}
return jsonparser.ObjectEach(data, func(key, val []byte, _ jsonparser.ValueType, _ int) error {
v, err := jsonparser.ParseString(val)
if err != nil {
return err
}
k, err := jsonparser.ParseString(key)
if err != nil {
return err
}
(*l)[k] = v
return nil
})
}
// Map coerces LabelSet into a map[string]string. This is useful for working with adapter types.
func (l LabelSet) Map() map[string]string {
return l
}
// String implements the Stringer interface. It returns a formatted/sorted set of label key/value pairs.
func (l LabelSet) String() string {
var b strings.Builder
keys := make([]string, 0, len(l))
for k := range l {
keys = append(keys, k)
}
sort.Strings(keys)
b.WriteByte('{')
for i, k := range keys {
if i > 0 {
b.WriteByte(',')
b.WriteByte(' ')
}
b.WriteString(k)
b.WriteByte('=')
b.WriteString(strconv.Quote(l[k]))
}
b.WriteByte('}')
return b.String()
}
// ParseLabelQuery parses a LabelRequest request from an http request.
func ParseLabelQuery(r *http.Request) (*logproto.LabelRequest, error) {
name, ok := mux.Vars(r)["name"]
req := &logproto.LabelRequest{
Values: ok,
Name: name,
}
start, end, err := bounds(r)
if err != nil {
return nil, err
}
req.Start = &start
req.End = &end
req.Query = query(r)
return req, nil
}
func ParseDetectedLabelsQuery(r *http.Request) (*logproto.DetectedLabelsRequest, error) {
var err error
start, end, err := bounds(r)
if err != nil {
return nil, err
}
if end.Before(start) {
return nil, errors.New("end timestamp must not be before or equal to start time")
}
return &logproto.DetectedLabelsRequest{
Start: start,
End: end,
Query: query(r),
}, nil
}