/
tail.go
185 lines (161 loc) · 4.65 KB
/
tail.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
package cloudwatch
import (
"fmt"
"log"
"regexp"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/lucagrulla/cw/timeutil"
)
type eventCache struct {
seen map[string]bool
sync.RWMutex
}
func (c *eventCache) Has(eventID string) bool {
c.RLock()
defer c.RUnlock()
return c.seen[eventID]
}
func (c *eventCache) Add(eventID string) {
c.Lock()
defer c.Unlock()
c.seen[eventID] = true
}
func (c *eventCache) Size() int {
c.RLock()
defer c.RUnlock()
return len(c.seen)
}
func (c *eventCache) Reset() {
c.Lock()
defer c.Unlock()
c.seen = make(map[string]bool)
}
type logStreams struct {
groupStreams []*string
sync.RWMutex
}
func (s *logStreams) reset(groupStreams []*string) {
s.Lock()
defer s.Unlock()
s.groupStreams = groupStreams
}
func (s *logStreams) get() []*string {
s.Lock()
defer s.Unlock()
return s.groupStreams
}
func params(logGroupName string, streamNames []*string, startTimeInMillis int64, endTimeInMillis int64, grep *string, follow *bool) *cloudwatchlogs.FilterLogEventsInput {
params := &cloudwatchlogs.FilterLogEventsInput{
LogGroupName: &logGroupName,
Interleaved: aws.Bool(true),
StartTime: &startTimeInMillis}
if *grep != "" {
params.FilterPattern = grep
}
if streamNames != nil {
params.LogStreamNames = streamNames
}
if !*follow && endTimeInMillis != 0 {
params.EndTime = &endTimeInMillis
}
return params
}
//Tail tails the given stream names in the specified log group name
//To tail all the available streams logStreamName has to be '*'
//It returns a channel where logs line are published
//Unless the follow flag is true the channel is closed once there are no more events available
func (cwl *CW) Tail(logGroupName *string, logStreamName *string, follow *bool, startTime *time.Time, endTime *time.Time, grep *string, grepv *string) <-chan *cloudwatchlogs.FilteredLogEvent {
lastSeenTimestamp := timeutil.ParseTime(startTime.Format(timeutil.TimeFormat)).Unix() * 1000
var endTimeInMillis int64
if !endTime.IsZero() {
endTimeInMillis = timeutil.ParseTime(endTime.Format(timeutil.TimeFormat)).Unix() * 1000
}
ch := make(chan *cloudwatchlogs.FilteredLogEvent)
timer := time.NewTimer(time.Millisecond * 5)
cache := &eventCache{seen: make(map[string]bool)}
go func() { //check cache size every 250ms and eventually purge
cacheTicker := time.NewTicker(250 * time.Millisecond)
for range cacheTicker.C {
size := cache.Size()
if size >= 5000 {
// fmt.Printf(">>>cache reset:%d,\n ", size)
cache.Reset()
}
}
}()
logStreams := &logStreams{}
if *logStreamName != "*" {
getStreams := func(logGroupName *string, logStreamName *string) []*string {
var streams []*string
for stream := range cwl.LsStreams(logGroupName, logStreamName, lastSeenTimestamp, endTimeInMillis) {
streams = append(streams, stream)
}
if len(streams) == 0 {
fmt.Println("No such log stream(s).")
close(ch)
}
if len(streams) >= 100 { //FilterLogEventPages won't take more than 100 stream names
streams = streams[0:100]
}
return streams
}
logStreams.reset(getStreams(logGroupName, logStreamName))
go func() {
ticker := time.NewTicker(time.Second * 5)
for range ticker.C {
logStreams.reset(getStreams(logGroupName, logStreamName))
}
}()
}
re := regexp.MustCompile(*grepv)
pageHandler := func(res *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool {
for _, event := range res.Events {
if *grepv == "" || !re.MatchString(*event.Message) {
if !cache.Has(*event.EventId) {
eventTimestamp := *event.Timestamp
if eventTimestamp != lastSeenTimestamp {
if eventTimestamp < lastSeenTimestamp {
// fmt.Printf("OLD EVENT:%s, evTS:%d, lTS:%d, cache size:%d \n", event, eventTimestamp, lastSeenTimestamp, cache.Size())
}
lastSeenTimestamp = eventTimestamp
}
cache.Add(*event.EventId)
ch <- event
} else {
//fmt.Printf("%s already seen\n", *event.EventId)
}
}
}
if lastPage {
if !*follow {
close(ch)
} else {
//fmt.Println("LAST PAGE")
//AWS API accepts 5 reqs/sec
timer.Reset(time.Millisecond * 205)
}
}
return !lastPage
}
first := true
if *follow || first {
first = false
go func() {
for range timer.C {
//FilterLogEventPages won't take more than 100 stream names
logParam := params(*logGroupName, logStreams.get(), lastSeenTimestamp, endTimeInMillis, grep, follow)
error := cwl.awsClwClient.FilterLogEventsPages(logParam, pageHandler)
if error != nil {
if awsErr, ok := error.(awserr.Error); ok {
log.Fatalf(awsErr.Message())
}
}
}
}()
}
return ch
}