-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3grep.go
217 lines (187 loc) · 5.52 KB
/
s3grep.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
package main
import (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"net/url"
"os"
"strings"
)
// Print an error message then quit.
func exitErrorf(msg string, args ...interface{}) {
_, _ = fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
// Get the S3 client.
func getS3() *s3.S3 {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := s3.New(sess)
return svc
}
// Utility to trim off first slash if it exists
func trimInitialSlash(s string) string {
if strings.HasPrefix(s, "/") {
return s[1:]
} else {
return s
}
}
// Parse an S3 path into the bucket and prefix.
func parseS3Path(path string) (error, string, string) {
u, err := url.Parse(path)
if err != nil {
return err, "", ""
} else if u.Scheme != "s3" {
return fmt.Errorf("scheme '%s' is not s3", u.Scheme), "", ""
} else {
return nil, u.Host, trimInitialSlash(u.Path)
}
}
// Return the compression type for S3 select based on the object suffix.
func getCompression(key string) string {
if strings.HasSuffix(key, ".gz") {
return "GZIP"
} else if strings.HasSuffix(key, ".bz2") {
return "BZIP2"
} else {
return "NONE"
}
}
// Get the parameters to scan an object using S3 select for a static string.
func scanObjectParams(bucket string, key string, exp string) *s3.SelectObjectContentInput {
compression := getCompression(key)
return &s3.SelectObjectContentInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
ExpressionType: aws.String(s3.ExpressionTypeSql),
Expression: aws.String("select * from s3object s where s._1 like '%" + exp + "%'"),
InputSerialization: &s3.InputSerialization{
CSV: &s3.CSVInput{
FieldDelimiter: aws.String("\000"),
RecordDelimiter: aws.String("\n"),
FileHeaderInfo: aws.String(s3.FileHeaderInfoNone),
},
CompressionType: aws.String(compression),
},
OutputSerialization: &s3.OutputSerialization{
CSV: &s3.CSVOutput{
QuoteCharacter: aws.String(""),
QuoteEscapeCharacter: aws.String(""),
FieldDelimiter: aws.String(""),
},
},
}
}
// Check for special case where we have a "folder"
// TODO: Figure out a less hacky way to detect this - S3 isn't supposed to have a concept of folders...
func isFolderKey(key string) bool {
return strings.HasSuffix(key, "/")
}
// Iterate over items at an S3 prefix. If the process function returns `false`, then break the loop.
// This function currently won't return "folder" keys ending in `/`.
func iterObjects(svc *s3.S3, bucket string, prefix string, process func(key string) bool) error {
params := &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
Prefix: aws.String(prefix),
}
keepGoing := true
err := svc.ListObjectsV2Pages(params,
func(page *s3.ListObjectsV2Output, lastPage bool) bool {
objects := page.Contents
for _, object := range objects {
if !isFolderKey(*object.Key) {
keepGoing = process(*object.Key)
if !keepGoing {
break
}
}
}
return keepGoing
})
return err
}
// Given an S3 bucket / key and expression, scan the file and print out all matching lines.
func matchS3(svc *s3.S3, bucket string, key string, exp string, printKey bool) error {
// Special case where we try to scan a "folder"
if isFolderKey(key) {
return awserr.New(s3.ErrCodeNoSuchKey, "Considering ending in '/' to not be a real key", nil)
}
params := scanObjectParams(bucket, key, exp)
// Issue S3 Select
resp, err := svc.SelectObjectContent(params)
if err != nil {
return err
}
// TODO print key before each match line
if printKey {
fmt.Println("=== " + key + " ===")
}
// Loop over results
for event := range resp.EventStream.Events() {
switch v := event.(type) {
case *s3.RecordsEvent:
// s3.RecordsEvent.Records is a byte slice of select records
fmt.Println(string(v.Payload))
}
}
// Close and report all errors
if err := resp.EventStream.Close(); err != nil {
return fmt.Errorf("failed to read from SelectObjectContent EventStream, %v", err)
}
return nil
}
// Iterate over all objects under a prefix, and scan them
func scanAndMatchS3(svc *s3.S3, bucket string, key string, exp string) error {
var internalError error = nil
err := iterObjects(svc, bucket, key, func(objKey string) bool {
internalError = matchS3(svc, bucket, objKey, exp, true)
if internalError != nil {
return false
}
return true
})
if internalError != nil {
return internalError
} else {
return err
}
}
func main() {
svc := getS3()
path := flag.String("path", "", "The S3 path to scan.")
match := flag.String("match", "", "The text to match on.")
flag.Parse()
if *path == "" {
exitErrorf("You must specify a path. See -help")
}
if *match == "" {
exitErrorf("You must specify text to match on. See -help")
}
err, bucket, key := parseS3Path(*path)
if err != nil {
exitErrorf("Unable to parse path: %v", err)
}
// Convoluted way of falling back to prefix scanning ahead
err = matchS3(svc, bucket, key, *match, false)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case s3.ErrCodeNoSuchKey:
// Let's try again, but this time scanning a prefix first
err = scanAndMatchS3(svc, bucket, key, *match)
if err != nil {
exitErrorf("AWS Client Error listing prefixes and scanning: %v", err)
}
default:
exitErrorf("AWS Client Error scanning: %v", err)
}
} else {
exitErrorf("Generic Error scanning: %v", err)
}
}
}