-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
334 lines (304 loc) · 12.1 KB
/
main.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package main
import (
"cloudwatch-log-aggregator/modules/files"
"cloudwatch-log-aggregator/modules/helpers"
"cloudwatch-log-aggregator/modules/logs"
"cloudwatch-log-aggregator/modules/memutils"
"cloudwatch-log-aggregator/modules/types"
"cloudwatch-log-aggregator/modules/validations"
"fmt"
"math"
"math/big"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
cloudWatchSession *cloudwatchlogs.CloudWatchLogs
waitGroup = &sync.WaitGroup{}
startQueryChannel = make(chan []int64)
getQueryOpChannel = make(chan []interface{})
mapMutex = sync.RWMutex{}
programInput types.ProgramInputTOML
inputDateFormat = "2006-01-02T15:04:05"
dayInSeconds = int64(24 * 60 * 60)
queryOutputMap = map[string]string{}
firstQuerycounter = 0
secondQuerycounter = 0
totalTasks = 0
completedTasks = 0
totalRecordsMatched = 0.0
totalRecordsScanned = big.NewFloat(0.0)
clearANSISequence = "\033[H\033[2J\033[3J"
fieldHeaderString string
emptyHeaderString bool
isWindows bool
)
// Variables to hold data from command line flags and args
var (
app = kingpin.New("cloudwatch-log-aggregator", "A CLI tool to fetch all cloudwatch logs within given timeframe")
maxConcurrentCallsToAWS = app.Flag("concurrency", "Max concurrent calls to aws (Default value: 4) Min: 1 Max: 9").Short('c').PlaceHolder("4").Default("4").Int()
debugMode = app.Flag("debug", "Enable debug mode").Default("false").Bool()
)
func main() {
helpers.PrintBanner()
app.HelpFlag.Short('h')
kingpin.MustParse(app.Parse(os.Args[1:]))
validateCommandLineArgs()
memutils.CheckSystemMemory()
fmt.Println("Started Program Execution")
fmt.Println("AWS Concurrency set to ", *maxConcurrentCallsToAWS)
programStartTime := time.Now()
initVariablesForSubModules()
validations.DoValidations()
go logs.Init()
//starting a goroutine which takes care of the logging process. Initialzing a head for high availability
go printProgressToTerminal(false)
newSession := session.Must(session.NewSession())
cloudWatchSession = cloudwatchlogs.New(newSession, aws.NewConfig().WithRegion(programInput.AWSRegion))
startTime, err := time.Parse(inputDateFormat, programInput.StartTime)
if err != nil {
logs.LogError("Error: Invalid StartTime format. Please use yyyy-mm-ddThh:mm:ss format in config.toml file")
os.Exit(1)
}
endTime, err := time.Parse(inputDateFormat, programInput.EndTime)
if err != nil {
logs.LogError("Error: Invalid EndTime format. Please use yyyy-mm-ddThh:mm:ss format in config.toml file")
os.Exit(1)
}
if startTime.After(endTime) || startTime.Equal(endTime) {
logs.LogError("Error: Invalid Input Time. StartTime should be less than EndTime")
os.Exit(1)
}
startTimeEpoch := startTime.Unix()
endTimeEpoch := endTime.Unix()
//initiate go routines
go initializeGoRoutines()
for startTimeEpoch+dayInSeconds-1 <= endTimeEpoch {
startQueryChannel <- []int64{startTimeEpoch, startTimeEpoch + dayInSeconds}
startTimeEpoch += dayInSeconds
totalTasks++
}
if startTimeEpoch+dayInSeconds > endTimeEpoch && startTimeEpoch < endTimeEpoch {
startQueryChannel <- []int64{startTimeEpoch, endTimeEpoch}
totalTasks++
}
//this call is blocking and it prevents the main gorutine from exiting untill all others finishes
waitGroup.Wait()
//log complete progress to terminal
printProgressToTerminal(true)
files.WriteOutputToFiles()
fmt.Println("Completed fetching logs from clodwatch for the given time span")
fmt.Printf("Execution Stats:\n\tTotal Time Taken: %v\n\tTotal Records Scanned: %.2f\n\tTotal Records Matched: %v\n", time.Since(programStartTime), totalRecordsScanned, totalRecordsMatched)
}
func initVariablesForSubModules() {
validations.ProgramInput = &programInput
logs.Debug = *debugMode
files.MapMutex = &mapMutex
files.QueryOutputMap = &queryOutputMap
files.InputDateFormat = &inputDateFormat
files.FieldHeaderString = &fieldHeaderString
if runtime.GOOS == "windows" {
isWindows = true
}
}
func clearTerminal() {
if isWindows {
cmd := exec.Command("cmd", "/c", "cls")
cmd.Stdout = os.Stdout
cmd.Run()
} else {
fmt.Print(clearANSISequence)
}
}
func printProgressToTerminal(isCompleted bool) {
for completedTasks < totalTasks || totalTasks == 0 {
if totalTasks != 0 {
clearTerminal()
helpers.PrintBanner()
fmt.Print(memutils.GetMemUsageString() + "\n" + getProgressString(false))
}
if isWindows {
time.Sleep(time.Second * 2)
} else {
time.Sleep(time.Second * 1)
}
}
if isCompleted {
clearTerminal()
helpers.PrintBanner()
fmt.Print(memutils.GetMemUsageString() + "\n" + getProgressString(true))
}
}
func getProgressString(isCompleted bool) string {
currentProgress := ((float64(completedTasks) / float64(totalTasks)) * 100)
var text string
if isCompleted {
text = "Completed ["
} else {
text = "Ongoing ["
}
for i := 0; i <= int(math.Floor(currentProgress)); i++ {
text += "="
}
text += ">"
for i := 0; i < 100-int(math.Floor(currentProgress)); i++ {
text += " "
}
text += "] " + strconv.Itoa(int(math.Floor(currentProgress))) + "%\n"
return text
}
func initializeGoRoutines() {
go func() {
for {
val, _ := <-startQueryChannel
// add 1 to waitGroup counter as one goroutine is going to be initialized
waitGroup.Add(1)
go func() {
logs.LogToFile(fmt.Sprintf("counter1 %v, %v", firstQuerycounter, secondQuerycounter))
for firstQuerycounter >= *maxConcurrentCallsToAWS-1 {
time.Sleep(time.Millisecond * 300)
}
firstQuerycounter++
defer func() {
waitGroup.Done()
}()
startLogsQuery(val)
}()
}
}()
go func() {
for {
val, _ := <-getQueryOpChannel
// add 1 to waitGroup counter as one goroutine is going to be initialized
waitGroup.Add(1)
go func() {
logs.LogToFile(fmt.Sprintf("counter1 %v, %v", firstQuerycounter, secondQuerycounter))
secondQuerycounter++
defer func() {
secondQuerycounter--
waitGroup.Done()
}()
getLogsQueryOutput(val)
}()
}
}()
}
func startLogsQuery(queryInputData []int64) {
if queryInputData[0] == 0 || queryInputData[1] == 0 {
panic("Invalid input recieved through channel")
}
logs.LogToFile(fmt.Sprintf("Querying from %v to %v", time.Unix(queryInputData[0], 0).UTC().Format(inputDateFormat), time.Unix(queryInputData[1], 0).UTC().Format(inputDateFormat)))
queryInputStruct := &cloudwatchlogs.StartQueryInput{
LogGroupName: aws.String(programInput.LogGroupName),
StartTime: aws.Int64(queryInputData[0]),
EndTime: aws.Int64(queryInputData[1]),
QueryString: aws.String(programInput.LogQuery + "\n| limit 10000"),
}
queryOutput, err := cloudWatchSession.StartQuery(queryInputStruct)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == credentials.ErrNoValidProvidersFoundInChain.Code() {
logs.LogError("AWS authentication failed. Please configure aws-cli in the system or load the access_key_id, aws_secret_access_key to AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY environment variables.\nPlease refer to https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html#specifying-credentials for more info")
} else if awsErr.Code() == cloudwatchlogs.ErrCodeResourceNotFoundException {
logs.LogError("No Resource found with the given LogGroupName. Please make sure the LogGroupName and AWSRegion are correctly mentioned in the config.toml file")
} else if awsErr.Code() == cloudwatchlogs.ErrCodeMalformedQueryException {
logs.LogError("Invalid LogQuery. Please double check the LogQuery in the config.toml file")
} else if awsErr.Code() == cloudwatchlogs.ErrCodeLimitExceededException {
logs.LogError("AWS Concurrency Limit Exceeded. Might be some other people are using queries through aws dashboard. Please try again")
} else {
logs.LogError("Error: " + awsErr.Code() + " " + awsErr.Message())
}
os.Exit(1)
} else {
//99 percent it will never hit this block but leaving it as suggested by aws sdk docs
panic(err.Error())
}
}
getQueryOpChannel <- []interface{}{queryOutput.QueryId, []int64{queryInputData[0], queryInputData[1]}, 0}
//this sleep command here is a sort of wierd fix to prevent race condition to delay the return of this function thereby delaying the defer statement in initializeGoRoutines method first anonymous block
time.Sleep(time.Millisecond * 100)
}
func getLogsQueryOutput(queryOutputData []interface{}) {
queryInputStruct := &cloudwatchlogs.GetQueryResultsInput{
QueryId: queryOutputData[0].(*string),
}
queryOutput, err := cloudWatchSession.GetQueryResults(queryInputStruct)
if err != nil {
panic(err.Error())
}
if *queryOutput.Status != "Complete" && *queryOutput.Status != "Failed" {
time.Sleep(time.Millisecond * 500)
//if the query status is not complete we push the value back to channel after waiting for some time
getQueryOpChannel <- []interface{}{queryOutputData[0].(*string), []int64{queryOutputData[1].([]int64)[0], queryOutputData[1].([]int64)[1]}}
//this sleep command here is a sort of wierd fix to prevent race condition to delay the return of this function thereby delaying the defer statement in initializeGoRoutines method first anonymous block
time.Sleep(time.Millisecond * 100)
return
}
logs.LogToFile(fmt.Sprintf("Query Output Recieved %v to %v, length: %v", time.Unix(queryOutputData[1].([]int64)[0], 0).UTC().Format(inputDateFormat), time.Unix(queryOutputData[1].([]int64)[1], 0).UTC().Format(inputDateFormat), len(queryOutput.Results)))
if *queryOutput.Statistics.RecordsMatched > float64(10000) || *queryOutput.Status == "Failed" {
//if number of output records are more than 10000 then split the timeframe to half and push to channel
difference := queryOutputData[1].([]int64)[1] - queryOutputData[1].([]int64)[0]
if difference < 5 {
panic("Error: Too many records are present in a shorttime frame of 5 seconds. Please query manually..")
}
startQueryChannel <- []int64{queryOutputData[1].([]int64)[0], int64(math.Floor(float64(queryOutputData[1].([]int64)[1] - (difference / 2))))}
startQueryChannel <- []int64{int64(math.Floor(float64(queryOutputData[1].([]int64)[1] - (difference / 2)))), queryOutputData[1].([]int64)[1]}
//this sleep command here is a sort of wierd fix to prevent race condition to delay the return of this function thereby delaying the defer statement in initializeGoRoutines method first anonymous block
time.Sleep(time.Millisecond * 100)
totalTasks = totalTasks + 2
} else {
//proceed if query status is completed
totalRecordsMatched += *queryOutput.Statistics.RecordsMatched
totalRecordsScanned = totalRecordsScanned.Add(big.NewFloat(*queryOutput.Statistics.RecordsScanned), totalRecordsScanned)
var dataString string
var date string
for _, eachRecord := range queryOutput.Results {
// var emptyHeaderString bool
for sindex, field := range eachRecord {
if *field.Field == "@ptr" {
//skip this type ones as we dont need them
continue
}
if *field.Field == "@timestamp" {
date = strings.Split(*field.Value, " ")[0]
}
if fieldHeaderString == "" || emptyHeaderString {
emptyHeaderString = true
fieldHeaderString += *field.Field + ","
if sindex == len(eachRecord)-2 {
fieldHeaderString = fieldHeaderString[:len(fieldHeaderString)-1] + "\n"
emptyHeaderString = false
}
}
dataString += *field.Value + ","
// here we are subtracting 2 considering @ptr recorded as unnecessary
if sindex == len(eachRecord)-2 {
dataString = dataString[:len(dataString)-1] + "\n"
}
}
}
mapMutex.Lock()
queryOutputMap[date] += dataString
mapMutex.Unlock()
}
//we are considering the task as completed only upon recieving the actual outut for the submitted query id
firstQuerycounter--
completedTasks++
}
func validateCommandLineArgs() {
if *maxConcurrentCallsToAWS < 1 || *maxConcurrentCallsToAWS > 9 {
fmt.Println("concurrency value should be between 1 and 9")
os.Exit(1)
}
}