-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
220 lines (205 loc) · 6 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
package main
import (
"bytes"
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/kelseyhightower/envconfig"
"github.com/tidwall/gjson"
"golang.org/x/sync/semaphore"
"io"
"log"
"sync"
"time"
)
type appConfig struct {
EsHost string `split_words:"true"`
EsIndex string `split_words:"true"`
EsScrollTime time.Duration `split_words:"true" default:"30m"`
S3BucketName string `split_words:"true"`
S3BucketPrefix string `split_words:"true"`
S3AccessKeyID string `split_words:"true"`
S3SecretAccessKey string `split_words:"true"`
S3Region string `split_words:"true" default:"us-east-1"`
S3Endpoint string `split_words:"true"`
ScrollSize int `split_words:"true" default:"10000"`
ConcurrentUploads int `split_words:"true" default:"10"`
}
var Config appConfig
const (
fiveMBInBytes = 5 * 1024 * 1024
)
func main() {
if err := envconfig.Process("bowfin", &Config); err != nil {
log.Fatal(err)
}
es, err := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{Config.EsHost},
})
if err != nil {
log.Fatal(err)
}
if _, err = es.Ping(); err != nil {
log.Fatal("failed to connect to elasticsearch: ", err)
}
s3Client := s3.New(session.Must(session.NewSession(
&aws.Config{
Region: aws.String(Config.S3Region),
Endpoint: aws.String(Config.S3Endpoint),
Credentials: credentials.NewStaticCredentials(
Config.S3AccessKeyID,
Config.S3SecretAccessKey,
"",
),
},
)))
key := Config.S3BucketPrefix + Config.EsIndex + ".ndjson"
multipartUpload, err := s3Client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
Bucket: aws.String(Config.S3BucketName),
Key: aws.String(key),
})
if err != nil {
log.Fatal(err)
}
log.Println("starting upload", *multipartUpload.UploadId, "to key", key)
documents := make(chan []byte, Config.ScrollSize)
done := make(chan struct{})
go upload(documents, done, s3Client, multipartUpload)
docCount := 0
if err = scroll(es, func(key, value gjson.Result) bool {
documents <- []byte(value.String())
docCount++
return true
}); err != nil {
log.Fatal(err)
}
close(documents)
<-done
log.Println("successfully uploaded", docCount, "documents to key", key)
}
func upload(documents <-chan []byte, done chan<- struct{}, s3Client *s3.S3, multipartUpload *s3.CreateMultipartUploadOutput) {
uploadedParts := make(chan *s3.CompletedPart)
completedParts := make([]*s3.CompletedPart, 0)
s := semaphore.NewWeighted(int64(Config.ConcurrentUploads))
wg := &sync.WaitGroup{}
go func() {
for t := range uploadedParts {
completedParts = append(completedParts, t)
s.Release(1)
wg.Done()
}
}()
for part := 1; ; part++ {
batch, ok := batchDocuments(documents)
if !ok && len(batch) == 0 {
break
}
_ = s.Acquire(context.Background(), 1)
wg.Add(1)
go func(b []byte, p int) {
eTag, err := uploadPart(s3Client, multipartUpload, b, p)
if err != nil {
log.Fatal(err)
}
log.Printf("uploaded part %d (%d bytes)", p, len(b))
uploadedParts <- &s3.CompletedPart{
ETag: eTag,
PartNumber: aws.Int64(int64(p)),
}
}(batch, part)
}
wg.Wait()
close(uploadedParts)
if _, err := s3Client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: multipartUpload.Bucket,
Key: multipartUpload.Key,
UploadId: multipartUpload.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: completedParts,
},
}); err != nil {
log.Fatal("failed to complete upload: ", err)
}
done <- struct{}{}
}
func batchDocuments(documents <-chan []byte) ([]byte, bool) {
buf := bytes.NewBuffer(nil)
for doc := range documents {
if _, err := buf.Write(doc); err != nil {
log.Fatal("failed to write document to buffer:", err)
}
if _, err := buf.WriteRune('\n'); err != nil {
log.Fatal("failed to write newline to buffer:", err)
}
if buf.Len() >= fiveMBInBytes {
return buf.Bytes(), true
}
}
return buf.Bytes(), false
}
func uploadPart(s3Client *s3.S3, upload *s3.CreateMultipartUploadOutput, data []byte, part int) (*string, error) {
res, err := s3Client.UploadPart(&s3.UploadPartInput{
Body: bytes.NewReader(data),
Bucket: upload.Bucket,
Key: upload.Key,
PartNumber: aws.Int64(int64(part)),
UploadId: upload.UploadId,
ContentLength: aws.Int64(int64(len(data))),
})
if err != nil {
if _, abortErr := s3Client.AbortMultipartUpload(&s3.AbortMultipartUploadInput{
Bucket: upload.Bucket,
Key: upload.Key,
UploadId: upload.UploadId,
}); abortErr != nil {
return nil, fmt.Errorf("failed to abort multipart upload while handing err '%v': %w", err, abortErr)
}
return nil, fmt.Errorf("failed to upload part %d: %w", part, err)
}
return res.ETag, nil
}
func scroll(es *elasticsearch.Client, hitCallback func(key, value gjson.Result) bool) error {
data, err := doEsRequest(es.Search(
es.Search.WithIndex(Config.EsIndex),
es.Search.WithSize(Config.ScrollSize),
es.Search.WithScroll(Config.EsScrollTime),
))
if err != nil {
return err
}
hits := gjson.GetBytes(data, "hits.hits")
hits.ForEach(hitCallback)
scrollID := gjson.GetBytes(data, "_scroll_id").String()
for {
data, err = doEsRequest(es.Scroll(
es.Scroll.WithScroll(Config.EsScrollTime),
es.Scroll.WithScrollID(scrollID),
))
if err != nil {
return err
}
hits = gjson.GetBytes(data, "hits.hits")
if len(hits.Array()) == 0 {
log.Println("no more document hits")
break
}
hits.ForEach(hitCallback)
scrollID = gjson.GetBytes(data, "_scroll_id").String()
}
return nil
}
func doEsRequest(res *esapi.Response, err error) ([]byte, error) {
if err != nil {
return nil, err
}
if res.IsError() {
return nil, fmt.Errorf("got error response: %s", res)
}
defer res.Body.Close()
return io.ReadAll(res.Body)
}