forked from hashicorp/go-getter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_s3.go
194 lines (162 loc) · 4.44 KB
/
get_s3.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
package getter
import (
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// S3Getter is a Getter implementation that will download a module from
// a S3 bucket.
type S3Getter struct{}
func (g *S3Getter) Get(dst string, u *url.URL) error {
// Parse URL
region, bucket, path, _, creds, err := g.parseUrl(u)
if err != nil {
return err
}
// Remove destination if it already exists
_, err = os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
// Remove the destination
if err := os.RemoveAll(dst); err != nil {
return err
}
}
// Create all the parent directories
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return err
}
config := g.getAWSConfig(region, creds)
sess := session.New(config)
client := s3.New(sess)
// List files in path, keep listing until no more objects are found
lastMarker := ""
hasMore := true
for hasMore {
req := &s3.ListObjectsInput{
Bucket: aws.String(bucket),
Prefix: aws.String(path),
}
if lastMarker != "" {
req.Marker = aws.String(lastMarker)
}
resp, err := client.ListObjects(req)
if err != nil {
return err
}
hasMore = aws.BoolValue(resp.IsTruncated)
// Get each object storing each file relative to the destination path
for _, object := range resp.Contents {
lastMarker = aws.StringValue(object.Key)
objPath := aws.StringValue(object.Key)
// If the key ends with a backslash assume it is a directory and ignore
if strings.HasSuffix(objPath, "/") {
continue
}
// Get the object destination path
objDst, err := filepath.Rel(path, objPath)
if err != nil {
return err
}
objDst = filepath.Join(dst, objDst)
if err := g.getObject(client, objDst, bucket, objPath, ""); err != nil {
return err
}
}
}
return nil
}
func (g *S3Getter) GetFile(dst string, u *url.URL) error {
region, bucket, path, version, creds, err := g.parseUrl(u)
if err != nil {
return err
}
config := g.getAWSConfig(region, creds)
sess := session.New(config)
client := s3.New(sess)
return g.getObject(client, dst, bucket, path, version)
}
func (g *S3Getter) getObject(client *s3.S3, dst, bucket, key, version string) error {
req := &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
if version != "" {
req.VersionId = aws.String(version)
}
resp, err := client.GetObject(req)
if err != nil {
return err
}
// Create all the parent directories
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return err
}
f, err := os.Create(dst)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}
func (g *S3Getter) getAWSConfig(region string, creds *credentials.Credentials) *aws.Config {
conf := &aws.Config{}
if creds == nil {
creds = credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
})
}
conf.Credentials = creds
if region != "" {
conf.Region = aws.String(region)
}
return conf
}
func (g *S3Getter) parseUrl(u *url.URL) (region, bucket, path, version string, creds *credentials.Credentials, err error) {
// Expected host style: s3.amazonaws.com. They always have 3 parts,
// although the first may differ if we're accessing a specific region.
hostParts := strings.Split(u.Host, ".")
if len(hostParts) != 3 {
err = fmt.Errorf("URL is not a valid S3 URL")
return
}
// Parse the region out of the first part of the host
region = strings.TrimPrefix(strings.TrimPrefix(hostParts[0], "s3-"), "s3")
if region == "" {
region = "us-east-1"
}
pathParts := strings.SplitN(u.Path, "/", 3)
if len(pathParts) != 3 {
err = fmt.Errorf("URL is not a valid S3 URL")
return
}
bucket = pathParts[1]
path = pathParts[2]
version = u.Query().Get("version")
_, hasAwsId := u.Query()["aws_access_key_id"]
_, hasAwsSecret := u.Query()["aws_access_key_secret"]
_, hasAwsToken := u.Query()["aws_access_token"]
if hasAwsId || hasAwsSecret || hasAwsToken {
creds = credentials.NewStaticCredentials(
u.Query().Get("aws_access_key_id"),
u.Query().Get("aws_access_key_secret"),
u.Query().Get("aws_access_token"),
)
}
return
}