-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
433 lines (371 loc) · 11.4 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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"github.com/fatih/color"
fastly "github.com/sethvargo/go-fastly"
)
// Version is the application version
const Version = "1.2.0"
// Fastly API doesn't return sorted data
type version struct {
Number int
Version *fastly.Version
}
type wrappedVersions []version
// Satisfy the Sort interface
func (v wrappedVersions) Len() int { return len(v) }
func (v wrappedVersions) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
func (v wrappedVersions) Less(i, j int) bool {
return v[i].Number < v[j].Number
}
type vclResponse struct {
Path string
Name string
Content string
Error bool
}
// Globals needed for sharing between functions
var fastlyServiceID string
var latestVersion string
var selectedVersion string
// List of VCL files to process
var vclFiles []string
// Regex used to define user specific filtering
var dirSkipRegex *regexp.Regexp
var dirMatchRegex *regexp.Regexp
// WaitGroup and Channel for storing responses from API
var wg sync.WaitGroup
var ch chan vclResponse
// Useful colour settings for printing messages
var yellow = color.New(color.FgYellow).SprintFunc()
var red = color.New(color.FgRed).SprintFunc()
var green = color.New(color.FgGreen).SprintFunc()
func main() {
help := flag.Bool("help", false, "show available flags")
appVersion := flag.Bool("version", false, "show application version")
useLatestVersion := flag.Bool("use-latest-version", false, "use latest Fastly service version to upload to (presumes not activated)")
getLatestVersion := flag.Bool("get-latest-version", false, "get latest Fastly service version and its active status")
getSettings := flag.String("get-settings", "", "get settings (Default TTL & Host) for specified Fastly service version (version number or latest)")
cloneVersion := flag.String("clone-version", "", "specify Fastly service 'version' to clone from before uploading to")
uploadVersion := flag.String("upload-version", "", "specify non-active Fastly service 'version' to upload to")
activateVersion := flag.String("activate-version", "", "specify Fastly service 'version' to activate")
statusVersion := flag.String("get-version-status", "", "retrieve status for the specified Fastly service 'version'")
service := flag.String("service", os.Getenv("FASTLY_SERVICE_ID"), "your service id (fallback: FASTLY_SERVICE_ID)")
token := flag.String("token", os.Getenv("FASTLY_API_TOKEN"), "your fastly api token (fallback: FASTLY_API_TOKEN)")
dir := flag.String("dir", os.Getenv("VCL_DIRECTORY"), "vcl directory to upload files from")
skip := flag.String("skip", "^____", "regex for skipping vcl directories (will also try: VCL_SKIP_DIRECTORY)")
match := flag.String("match", "", "regex for matching vcl directories (will also try: VCL_MATCH_DIRECTORY)")
flag.Parse()
if *help == true {
flag.PrintDefaults()
os.Exit(1)
}
if *appVersion == true {
fmt.Println(Version)
os.Exit(1)
}
envSkipDir := os.Getenv("VCL_SKIP_DIRECTORY")
envMatchDir := os.Getenv("VCL_MATCH_DIRECTORY")
if envSkipDir != "" {
*skip = envSkipDir
}
if envMatchDir != "" {
*match = envMatchDir
}
dirSkipRegex, _ = regexp.Compile(*skip)
dirMatchRegex, _ = regexp.Compile(*match)
client, err := fastly.NewClient(*token)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fastlyServiceID = *service
if *getSettings == "latest" {
latestVersion, _, err := getLatestServiceVersion(client)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
printSettingsFor(latestVersion, client)
return
}
if *getSettings != "" {
printSettingsFor(*getSettings, client)
return
}
if *getLatestVersion {
latestVersion, status, err := getLatestServiceVersion(client)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("\nLatest service version: %s (%s)\n\n", latestVersion, status)
return
}
// Activate Version
if *activateVersion != "" {
_, err := client.ActivateVersion(&fastly.ActivateVersionInput{
Service: fastlyServiceID,
Version: *activateVersion,
})
if err != nil {
fmt.Printf("\nThere was a problem activating version %s\n\n%s", yellow(*activateVersion), red(err))
os.Exit(1)
}
fmt.Printf("\nService '%s' now has version '%s' activated\n\n", yellow(fastlyServiceID), green(*activateVersion))
return
}
// Version Status Check
if *statusVersion != "" {
status, err := getStatusVersion(*statusVersion, client)
if err != nil {
fmt.Printf("\nThere was a problem getting the status for version %s\n\n%s\n\n", yellow(*statusVersion), red(err))
os.Exit(1)
}
fmt.Printf("\nService '%s' version '%s' is '%s'\n\n", yellow(fastlyServiceID), yellow(*statusVersion), status)
return
}
// Incorrect flags provided check
if *cloneVersion != "" && *uploadVersion != "" {
fmt.Println("Please do not provide both -clone-version and -upload-version flags")
os.Exit(1)
}
// Check if we should...
// A. clone the specified version before uploading files: `-clone-version`
// B. upload files to the specified version: `-upload-version`
// C. upload files to the latest version: `-use-latest-version`
// D. clone the latest version if it's already activated
// Clone from specified version and upload to that
if *cloneVersion != "" {
clonedVersion, err := cloneFromVersion(*cloneVersion, client)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Successfully created new version %s from existing version %s\n\n", clonedVersion.Number, *cloneVersion)
selectedVersion = *cloneVersion
} else if *uploadVersion != "" {
// Upload to the specified version (it can't be activated)
getVersion, err := client.GetVersion(&fastly.GetVersionInput{
Service: fastlyServiceID,
Version: *uploadVersion,
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if getVersion.Active {
fmt.Println("Sorry, the specified version is already activated")
os.Exit(1)
}
selectedVersion = *uploadVersion
} else {
latestVersion, err := getLatestVCLVersion(client)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
selectedVersion = latestVersion
// Upload to the latest version (it can't be activated)
if *useLatestVersion {
getVersion, err := client.GetVersion(&fastly.GetVersionInput{
Service: fastlyServiceID,
Version: latestVersion,
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if getVersion.Active {
fmt.Println("Sorry, the latest version is already activated")
os.Exit(1)
}
selectedVersion = latestVersion
} else {
// Otherwise clone the latest version and upload to that
clonedVersion, err := cloneFromVersion(latestVersion, client)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Successfully created new version %s from latest version %s\n\n", clonedVersion.Number, latestVersion)
selectedVersion = clonedVersion.Number
}
}
// Recursively walk the specified directory: `-dir` or `VCL_DIRECTORY`
walkError := filepath.Walk(*dir, aggregate)
if walkError != nil {
fmt.Printf("filepath.Walk() returned an error: %v\n", walkError)
}
// Concurrently handle the HTTP requests
ch = make(chan vclResponse, len(vclFiles))
for _, vclPath := range vclFiles {
wg.Add(1)
go uploadVCL(vclPath, client)
}
wg.Wait()
close(ch)
// Process the aggregated results
for vclFile := range ch {
if vclFile.Error {
fmt.Printf("\nWhoops, the file '%s' didn't upload because of the following error:\n\t%s\n", yellow(vclFile.Name), red(vclFile.Content))
} else {
fmt.Printf("\nYay, the file '%s' was updated successfully", green(vclFile.Name))
}
}
}
func printSettingsFor(serviceVersion string, client *fastly.Client) {
settings, err := client.GetSettings(&fastly.GetSettingsInput{
Service: fastlyServiceID,
Version: serviceVersion,
})
if err != nil {
fmt.Printf("\nThere was a problem getting the settings for version %s\n\n%s", yellow(serviceVersion), red(err))
os.Exit(1)
}
fmt.Printf(
"\nDefault Host: %s\nDefault TTL: %d (seconds)\n\n",
settings.DefaultHost,
settings.DefaultTTL,
)
}
func getStatusVersion(statusVersion string, client *fastly.Client) (string, error) {
versionStatus, err := client.GetVersion(&fastly.GetVersionInput{
Service: fastlyServiceID,
Version: statusVersion,
})
if err != nil {
return "", err
}
status := green("not activated")
if versionStatus.Active {
status = red("already activated")
}
return status, nil
}
func cloneFromVersion(version string, client *fastly.Client) (*fastly.Version, error) {
clonedVersion, err := client.CloneVersion(&fastly.CloneVersionInput{
Service: fastlyServiceID,
Version: version,
})
if err != nil {
return nil, err
}
return clonedVersion, nil
}
func getLatestVCLVersion(client *fastly.Client) (string, error) {
// We have to get all the versions and then sort them to find the actual latest
listVersions, err := client.ListVersions(&fastly.ListVersionsInput{
Service: fastlyServiceID,
})
if err != nil {
return "", err
}
wv := wrappedVersions{}
for _, v := range listVersions {
i, err := strconv.Atoi(v.Number)
if err != nil {
return "", err
}
wv = append(wv, version{i, v})
}
sort.Sort(wv)
return strconv.Itoa(wv[len(wv)-1].Number), nil
}
func aggregate(path string, f os.FileInfo, err error) error {
if validPathDefaults(path) && validPathUserDefined(path) && !invalidPathUserDefined(path) {
vclFiles = append(vclFiles, path)
}
return nil
}
func validPathDefaults(path string) bool {
return !strings.Contains(path, ".git") && strings.Contains(path, ".vcl")
}
func validPathUserDefined(path string) bool {
return dirMatchRegex.MatchString(path)
}
func invalidPathUserDefined(path string) bool {
return dirSkipRegex.MatchString(path)
}
func uploadVCL(path string, client *fastly.Client) {
defer wg.Done()
name := extractName(path)
content, err := getLocalVCL(path)
if err != nil {
ch <- vclResponse{
Path: path,
Name: name,
Content: fmt.Sprintf("get local vcl error: %s", err),
Error: true,
}
} else {
vclFile, err := client.CreateVCL(&fastly.CreateVCLInput{
Service: fastlyServiceID,
Version: selectedVersion,
Name: name,
Content: content,
})
if err != nil {
fmt.Printf("\nThere was an error creating the file '%s':\n%s\nWe'll now try updating this file instead of creating it\n", yellow(name), red(err))
vclFileUpdate, updateErr := client.UpdateVCL(&fastly.UpdateVCLInput{
Service: fastlyServiceID,
Version: selectedVersion,
Name: name,
Content: content,
})
if updateErr != nil {
ch <- vclResponse{
Path: path,
Name: name,
Content: fmt.Sprintf("error: %s", updateErr),
Error: true,
}
} else {
ch <- vclResponse{
Path: path,
Name: name,
Content: vclFileUpdate.Content,
Error: false,
}
}
} else {
ch <- vclResponse{
Path: path,
Name: name,
Content: vclFile.Content,
Error: false,
}
}
}
}
func extractName(path string) string {
_, file := filepath.Split(path)
return strings.Split(file, ".")[0]
}
func getLocalVCL(path string) (string, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(content), nil
}
func getLatestServiceVersion(client *fastly.Client) (string, string, error) {
latestVersion, err := getLatestVCLVersion(client)
if err != nil {
return "", "", err
}
status, err := getStatusVersion(latestVersion, client)
if err != nil {
return "", "", err
}
return latestVersion, status, nil
}