This repository has been archived by the owner on Jul 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (89 loc) · 2.3 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/CreditCardsCom/bushwack/bushwack"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
var esUrl string
func init() {
host := os.Getenv("ES_HOST")
if host == "" {
log.Fatalln("No ES_HOST defined in the environment!")
}
esUrl = fmt.Sprintf("%s/_bulk", host)
}
func main() {
lambda.Start(EventHandler)
}
func EventHandler(event events.S3Event) {
// TODO: Use S3Event region instead of hardcoded
sess, err := session.NewSession(&aws.Config{Region: aws.String("us-west-2")})
if err != nil {
log.Fatal(err)
}
dlManager := s3manager.NewDownloader(sess)
var objects []s3manager.BatchDownloadObject
var files []string
// Build a batch download of all objects send in the event
for _, r := range event.Records {
e := r.S3
// Verify we have what we thing we have...
if !strings.HasSuffix(e.Object.Key, ".log.gz") {
continue
}
tf, err := ioutil.TempFile("", "")
if err != nil {
log.Fatal(err)
}
defer tf.Close()
defer os.Remove(tf.Name())
o := s3manager.BatchDownloadObject{
Writer: tf,
Object: &s3.GetObjectInput{
Bucket: &e.Bucket.Name,
Key: &e.Object.Key,
},
}
files = append(files, tf.Name())
objects = append(objects, o)
log.Printf("Processing s3://%s/%s\n", e.Bucket.Name, e.Object.Key)
}
it := &s3manager.DownloadObjectsIterator{Objects: objects}
ctx := aws.BackgroundContext()
if err := dlManager.DownloadWithIterator(ctx, it); err != nil {
log.Fatal(err)
}
for _, f := range files {
handleLogfile(f)
}
}
func handleLogfile(filename string) {
num, body, err := bushwack.ProcessLog(filename)
if err != nil {
log.Fatalf("Error file processing log: %s\n", err)
}
if num == 0 {
log.Println("No bulk body to send.")
return
}
resp, err := http.Post(esUrl, "application/x-ndjson", strings.NewReader(body))
if err != nil {
log.Fatal(err)
}
if resp.StatusCode != 200 {
log.Printf("Received unexpected status code %d.\n", resp.StatusCode)
reason, _ := ioutil.ReadAll(resp.Body)
log.Fatalf("Reason: %s", reason)
}
log.Printf("Sent off %d log entries.", num)
}