-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
202 lines (182 loc) · 5.5 KB
/
client.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
package stackdriver
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
"google.golang.org/api/option"
"cloud.google.com/go/logging"
"cloud.google.com/go/logging/logadmin"
"github.com/mike1808/ax/pkg/backend/common"
"google.golang.org/api/iterator"
)
const QueryLogTimeout = 20 * time.Second
type StackdriverClient struct {
stackdriverClient *logadmin.Client
projectName string
logName string
}
// This is some crazy-ass structure in which the stackdriver APIs
// return its JSON values that we have to decode
type payloadValue struct {
Fields map[string]payloadEntry
}
type payloadEntry struct {
Kind struct {
StringValue *string
NumberValue *int64
BoolValue *bool
ListValue *struct {
Values []payloadEntry
}
StructValue *payloadValue
}
}
func payloadValueToJSONValue(plVal payloadValue) map[string]interface{} {
m := make(map[string]interface{})
for k, v := range plVal.Fields {
m[k] = payloadEntryToJSONValue(v)
}
return m
}
func payloadEntryToJSONValue(plEntry payloadEntry) interface{} {
kind := plEntry.Kind
if kind.StringValue != nil {
return *plEntry.Kind.StringValue
} else if kind.NumberValue != nil {
return *kind.NumberValue
} else if kind.BoolValue != nil {
return *kind.BoolValue
} else if kind.ListValue != nil {
list := make([]interface{}, len((*kind.ListValue).Values))
for idx, val := range (*kind.ListValue).Values {
list[idx] = payloadEntryToJSONValue(val)
}
return list
} else if kind.StructValue != nil {
return payloadValueToJSONValue(*kind.StructValue)
} else {
return nil
}
}
func payloadToAttributes(buf []byte) map[string]interface{} {
var plValue payloadValue
if err := json.Unmarshal(buf, &plValue); err != nil {
fmt.Printf("Could not unmarshall value: %s", string(buf))
return nil
}
return payloadValueToJSONValue(plValue)
}
func entryToLogMessage(entry *logging.Entry) common.LogMessage {
message := common.NewLogMessage()
message.Timestamp = entry.Timestamp
message.ID = entry.InsertID
switch v := entry.Payload.(type) {
case string:
message.Attributes[message.MessageKey] = v
case map[string]interface{}:
message.Attributes = v
default:
buf, err := json.Marshal(entry.Payload)
if err != nil {
fmt.Printf("Could not marshall value: %v of type %v", entry.Payload, reflect.TypeOf(entry))
break
}
message.Attributes = payloadToAttributes(buf)
}
return message
}
func queryToFilter(query common.Query, projectName string, logName string) string {
pieces := []string{fmt.Sprintf(`logName = "projects/%s/logs/%s"`, projectName, logName)}
if query.QueryString != "" {
pieces = append(pieces, fmt.Sprintf(`"%s"`, query.QueryString))
}
for _, filter := range query.EqualityFilters {
pieces = append(pieces, fmt.Sprintf(`jsonPayload.%s %s "%s"`, filter.FieldName, filter.Operator, filter.Value))
}
if query.After != nil {
pieces = append(pieces, fmt.Sprintf(`timestamp > "%s"`, (*query.After).Format(time.RFC3339)))
}
if query.Before != nil {
pieces = append(pieces, fmt.Sprintf(`timestamp < "%s"`, (*query.Before).Format(time.RFC3339)))
}
return strings.Join(pieces, " AND ")
}
func (client *StackdriverClient) ImplementsAdvancedFilters() bool {
return false
}
func (client *StackdriverClient) readLogBatch(ctx context.Context, query common.Query) ([]common.LogMessage, error) {
ctx, cancel := context.WithTimeout(ctx, QueryLogTimeout)
defer cancel()
it := client.stackdriverClient.Entries(ctx, logadmin.Filter(queryToFilter(query, client.projectName, client.logName)))
messages := make([]common.LogMessage, 0, 20)
entry, err := it.Next()
// Somehow, if no results can be found, it.Next() just runs forever, hence the adding a timeout to the context
if ctx.Err() == context.DeadlineExceeded {
return messages, ctx.Err()
}
if err != nil && err != iterator.Done {
return nil, err
}
resultCounter := 1
for err != iterator.Done && resultCounter <= query.MaxResults {
msg := entryToLogMessage(entry)
msg.Attributes = common.Project(msg.Attributes, query.SelectFields)
messages = append(messages, msg)
entry, err = it.Next()
resultCounter++
}
return messages, nil
}
func (client *StackdriverClient) Query(ctx context.Context, query common.Query) <-chan common.LogMessage {
if query.Follow {
return common.ReQueryFollow(ctx, func() ([]common.LogMessage, error) {
return client.readLogBatch(ctx, query)
})
}
resultChan := make(chan common.LogMessage)
go func() {
messages, err := client.readLogBatch(ctx, query)
if err != nil {
fmt.Printf("Error while fetching logs: %s\n", err)
close(resultChan)
return
}
for _, message := range messages {
resultChan <- message
}
close(resultChan)
}()
return resultChan
}
func New(credentialsFile, projectName, logName string) *StackdriverClient {
client, err := logadmin.NewClient(context.Background(), projectName, option.WithCredentialsFile(credentialsFile))
if err != nil {
fmt.Printf("Error creating stack driver client: %v\n", err)
return nil
}
return &StackdriverClient{
stackdriverClient: client,
projectName: projectName,
logName: logName,
}
}
func (client *StackdriverClient) ListLogs() ([]string, error) {
logNames := make([]string, 0, 10)
it := client.stackdriverClient.Logs(context.Background())
s, err := it.Next()
if err != nil && err != iterator.Done {
return nil, err
}
for err != iterator.Done {
logNames = append(logNames, s)
s, err = it.Next()
if err != nil && err != iterator.Done {
return nil, err
}
}
return logNames, nil
}
var _ common.Client = &StackdriverClient{}