forked from barnybug/cli53
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
308 lines (279 loc) · 6.54 KB
/
util.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
package cli53
import (
"fmt"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/urfave/cli"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
)
// Qualify names, if relative
func qualifyName(name, origin string) string {
if name == "" || name == "@" {
// root
return origin
} else if !strings.HasSuffix(name, ".") {
// unqualified
return name + "." + origin
} else {
// qualified
return name
}
}
func getConfig(c *cli.Context) (*aws.Config, error) {
debug := c.Bool("debug")
endpoint := c.String("endpoint-url")
region := os.Getenv("AWS_REGION")
// SDK requires region to be set when endpoint-url is set
if endpoint != "" && region == "" {
return nil, cli.NewExitError("AWS_REGION must be set when using --endpoint-url", 4)
}
config := aws.Config{
Endpoint: &endpoint,
Region: ®ion,
Logger: aws.LoggerFunc(func(args ...interface{}) {
fmt.Fprintln(os.Stderr, args...)
}),
}
// ensures throttled requests are retried
config.MaxRetries = aws.Int(100)
if debug {
config.LogLevel = aws.LogLevel(aws.LogDebug)
}
return &config, nil
}
func getService(c *cli.Context) (*route53.Route53, error) {
config, err := getConfig(c)
if err != nil {
return nil, err
}
options := session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: *config,
Profile: c.String("profile"),
}
sess, err := session.NewSessionWithOptions(options)
if err != nil {
return nil, err
}
roleARN := c.String("role-arn")
if roleARN != "" {
roleCreds := stscreds.NewCredentials(sess, roleARN)
if err != nil {
return nil, err
}
config.Credentials = roleCreds
}
return route53.New(sess, config), nil
}
func fatalIfErr(err error) {
if err != nil {
errorAndExit(fmt.Sprint(err))
}
}
func errorAndExit(msg string) {
fmt.Fprintln(os.Stderr, "Error: "+msg)
os.Exit(1)
}
var seeded sync.Once
func uniqueReference() string {
seeded.Do(func() {
rand.Seed(time.Now().UnixNano())
})
return fmt.Sprintf("%0x", rand.Int())
}
var unescaper = strings.NewReplacer(`\057`, "/", `\052`, "*")
func zoneName(s string) string {
return unescaper.Replace(strings.TrimRight(s, "."))
}
var reZoneId = regexp.MustCompile("^(/hostedzone/)?Z[A-Z0-9]{10,}$")
func isZoneId(s string) bool {
return reZoneId.MatchString(s)
}
func lookupZone(nameOrId string) *route53.HostedZone {
if isZoneId(nameOrId) {
// lookup by id
id := nameOrId
if !strings.HasPrefix(nameOrId, "/hostedzone/") {
id = "/hostedzone/" + id
}
req := route53.GetHostedZoneInput{
Id: aws.String(id),
}
resp, err := r53.GetHostedZone(&req)
if err, ok := err.(awserr.Error); ok && err.Code() == "NoSuchHostedZone" {
errorAndExit(fmt.Sprintf("Zone '%s' not found", nameOrId))
}
fatalIfErr(err)
return resp.HostedZone
} else {
// lookup by name
matches := []route53.HostedZone{}
req := route53.ListHostedZonesByNameInput{
DNSName: aws.String(nameOrId),
}
resp, err := r53.ListHostedZonesByName(&req)
fatalIfErr(err)
for _, zone := range resp.HostedZones {
if zoneName(*zone.Name) == zoneName(nameOrId) {
matches = append(matches, *zone)
}
}
switch len(matches) {
case 0:
errorAndExit(fmt.Sprintf("Zone '%s' not found", nameOrId))
case 1:
return &matches[0]
default:
errorAndExit("Multiple zones match - you will need to use Zone ID to uniquely identify the zone")
}
}
return nil
}
func waitForChange(change *route53.ChangeInfo) {
fmt.Printf("Waiting for sync")
for {
req := route53.GetChangeInput{Id: change.Id}
resp, err := r53.GetChange(&req)
fatalIfErr(err)
if *resp.ChangeInfo.Status == "INSYNC" {
fmt.Println("\nCompleted")
break
} else if *resp.ChangeInfo.Status == "PENDING" {
fmt.Printf(".")
} else {
fmt.Printf("\nFailed: %s\n", *resp.ChangeInfo.Status)
break
}
time.Sleep(1 * time.Second)
}
}
// Use shortened form of name with origin removed/abbreviated.
func shortenName(name, origin string) string {
if name == origin {
return "@"
}
return strings.TrimSuffix(name, "."+origin)
}
var reQuotedValue = regexp.MustCompile(`"((?:\\"|[^"])*)"`)
var reBackslashed = regexp.MustCompile(`\\(.)`)
func splitValues(s string) []string {
ret := []string{}
for _, m := range reQuotedValue.FindAllStringSubmatch(s, -1) {
val := reBackslashed.ReplaceAllString(m[1], "$1")
ret = append(ret, val)
}
return ret
}
var quoter = strings.NewReplacer(`\`, `\\`, `"`, `\"`)
func quote(s string) string {
return `"` + quoter.Replace(s) + `"`
}
type KeyValues []interface{}
func (kvs KeyValues) GetOptString(key string) *string {
for i := 0; i < len(kvs); i += 2 {
if kvs[i] == key {
if value, ok := kvs[i+1].(string); ok {
return &value
}
}
}
return nil
}
func (kvs KeyValues) GetString(key string) string {
val := kvs.GetOptString(key)
if val != nil {
return *val
}
return ""
}
func (kvs KeyValues) GetInt(key string) int {
for i := 0; i < len(kvs); i += 2 {
if kvs[i] == key {
if value, ok := kvs[i+1].(int); ok {
return value
}
}
}
return 0
}
func (kvs KeyValues) String() string {
var ret string
for i := 0; i < len(kvs); i += 2 {
key := kvs[i]
value := kvs[i+1]
if ret != "" {
ret += " "
}
switch value := value.(type) {
case string:
ret += fmt.Sprintf("%s=%s", key, quote(value))
case int64, int:
ret += fmt.Sprintf("%s=%v", key, value)
}
}
return ret
}
func ParseKeyValues(input string) (result KeyValues, err error) {
// result = append(result, "a", 2)
l := lex(input)
for {
// alpha key
key := l.acceptRun(unicode.IsLetter)
if key == "" {
err = l.Error("Expected key")
return
}
// equals separator
if !l.accept("=") {
err = l.Error("Expected =")
return
}
// value (string or int)
var value interface{}
if l.accept(`"`) {
// quoted string
str := ""
for {
if l.eof() {
err = l.Error("Unterminated quoted string")
return
} else if l.accept(`\`) {
str += l.acceptAny()
} else if l.accept(`"`) {
break
} else {
str += l.acceptAny()
}
}
value = str
} else if num := l.acceptRun(unicode.IsDigit); num != "" {
value, err = strconv.Atoi(num)
if err != nil {
return
}
} else {
err = l.Error("Unexpected token")
return
}
result = append(result, key, value)
if l.eof() {
break
}
// whitespace between multiple key values
if l.acceptRun(unicode.IsSpace) == "" {
err = l.Error("Expected whitespace")
return
}
}
return
}