-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcplog.go
192 lines (169 loc) · 4.5 KB
/
gcplog.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
package gcplog
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"strings"
"time"
logging "cloud.google.com/go/logging/apiv2"
"cloud.google.com/go/logging/apiv2/loggingpb"
"github.com/Silicon-Ally/gcp-clf/combinedlog"
"github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
)
type Option func(*options)
type options struct {
startTime *time.Time
endTime *time.Time
}
func WithStartTime(t time.Time) Option {
return func(o *options) {
o.startTime = &t
}
}
func WithEndTime(t time.Time) Option {
return func(o *options) {
o.endTime = &t
}
}
func StreamLogs(ctx context.Context, projID string, fn func(combinedlog.RequestEntry)) error {
c, err := logging.NewClient(ctx, option.WithQuotaProject((projID)))
if err != nil {
return fmt.Errorf("failed to init logger: %w", err)
}
defer c.Close()
stream, err := c.TailLogEntries(ctx)
if err != nil {
return fmt.Errorf("failed to tail log entries: %w", err)
}
filters := []string{
`resource.type="firebase_domain"`,
fmt.Sprintf(`resource.labels.site_name=%q`, projID),
}
errChan := make(chan error)
go func() {
err = stream.Send(&loggingpb.TailLogEntriesRequest{
ResourceNames: []string{
"projects/" + projID,
},
Filter: strings.Join(filters, " AND "),
})
if err != nil {
errChan <- fmt.Errorf("failed to send tail request: %w", err)
}
}()
logChan := make(chan []*loggingpb.LogEntry)
go func() {
for {
resp, err := stream.Recv()
if err != nil {
errChan <- err
break
}
logChan <- resp.Entries
}
}()
for {
select {
case logs := <-logChan:
for _, l := range logs {
rl, err := toRequestEntry(l)
if err != nil {
return fmt.Errorf("failed to convert log entry: %w", err)
}
fn(rl)
}
case err := <-errChan:
if errors.Is(err, io.EOF) {
return nil
} else if err != nil {
return fmt.Errorf("failed to get logs: %w", err)
}
}
}
}
func GetLogs(ctx context.Context, projID string, logOpts ...Option) ([]combinedlog.RequestEntry, error) {
o := &options{}
for _, opt := range logOpts {
opt(o)
}
c, err := logging.NewClient(ctx, option.WithQuotaProject((projID)))
if err != nil {
return nil, fmt.Errorf("failed to init logger: %w", err)
}
defer c.Close()
callOpts := []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.ResourceExhausted,
}, gax.Backoff{})
}),
}
filters := []string{
`resource.type="firebase_domain"`,
fmt.Sprintf(`resource.labels.site_name=%q`, projID),
}
if o.startTime != nil {
filters = append(filters, fmt.Sprintf(`timestamp>=%q`, o.startTime.Format(time.RFC3339)))
}
if o.endTime != nil {
filters = append(filters, fmt.Sprintf(`timestamp<=%q`, o.endTime.Format(time.RFC3339)))
}
iter := c.ListLogEntries(ctx, &loggingpb.ListLogEntriesRequest{
ResourceNames: []string{
"projects/" + projID,
},
Filter: strings.Join(filters, " AND "),
// The idea here is that quotas for Cloud Logging are fairly low by default (60
// read reqs/minute), so if you have a decent amount of logs, you'll hit quota
// fairly quickly.
PageSize: 1000,
}, callOpts...)
var out []combinedlog.RequestEntry
for {
entry, err := iter.Next()
if errors.Is(err, iterator.Done) {
break
} else if err != nil {
return nil, fmt.Errorf("failed to load log entry: %w", err)
}
rEntry, err := toRequestEntry(entry)
if err != nil {
return nil, fmt.Errorf("failed to convert log entry: %w", err)
}
out = append(out, rEntry)
}
return out, nil
}
func toRequestEntry(entry *loggingpb.LogEntry) (combinedlog.RequestEntry, error) {
// We don't currently use anything in the payload.
// payload, ok := entry.Payload.(*loggingpb.LogEntry_JsonPayload)
// if !ok {
// return nil, fmt.Errorf("log entry payload was %T, expected JSON", entry.Payload)
// }
httpReq := entry.HttpRequest
reqUrl, err := url.Parse(httpReq.RequestUrl)
if err != nil {
return combinedlog.RequestEntry{}, fmt.Errorf("failed to parse request url: %w", err)
}
if reqUrl == nil {
return combinedlog.RequestEntry{}, errors.New("no URL in log request")
}
return combinedlog.RequestEntry{
RemoteAddr: httpReq.RemoteIp,
Identity: "",
User: "",
RequestedAt: entry.Timestamp.AsTime(),
Method: httpReq.RequestMethod,
Path: reqUrl.Path,
Protocol: httpReq.Protocol,
StatusCode: int(httpReq.Status),
ResponseSize: &httpReq.ResponseSize,
Referer: httpReq.Referer,
UserAgent: httpReq.UserAgent,
}, nil
}