This repository has been archived by the owner on Feb 18, 2019. It is now read-only.
forked from contraband/autopilot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autopilot.go
405 lines (342 loc) · 10.6 KB
/
autopilot.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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"code.cloudfoundry.org/cli/cf/api/logs"
"code.cloudfoundry.org/cli/plugin"
"github.com/cloudfoundry/noaa/consumer"
"github.com/happytobi/autopilot/manifest"
"github.com/happytobi/autopilot/rewind"
)
func fatalIf(err error) {
if err != nil {
fmt.Fprintln(os.Stdout, "error:", err)
os.Exit(1)
}
}
func main() {
plugin.Start(&AutopilotPlugin{})
}
type AutopilotPlugin struct{}
func venerableAppName(appName string) string {
return fmt.Sprintf("%s-venerable", appName)
}
func getActionsForApp(appRepo *ApplicationRepo, appName, manifestPath, appPath, stackName string, timeout int, vars []string, varsFiles []string, envs []string, showLogs bool) []rewind.Action {
venName := venerableAppName(appName)
var err error
var curApp, venApp *AppEntity
var haveVenToCleanup bool
return []rewind.Action{
// get info about current app
{
Forward: func() error {
curApp, err = appRepo.GetAppMetadata(appName)
if err != ErrAppNotFound {
return err
}
curApp = nil
return nil
},
},
// get info about ven app
{
Forward: func() error {
venApp, err = appRepo.GetAppMetadata(venName)
if err != ErrAppNotFound {
return err
}
venApp = nil
return nil
},
},
// rename any existing app such so that next step can push to a clear space
{
Forward: func() error {
// Unless otherwise specified, go with our start state
haveVenToCleanup = (venApp != nil)
// If there is no current app running, that's great, we're done here
if curApp == nil {
return nil
}
// If current app isn't started, then we'll just delete it, and we're done
if curApp.State != "STARTED" {
return appRepo.DeleteApplication(appName)
}
// Do we have a ven app that will stop a rename?
if venApp != nil {
// Finally, since the current app claims to be healthy, we'll delete the venerable app, and rename the current over the top
err = appRepo.DeleteApplication(venName)
if err != nil {
return err
}
}
// Finally, rename
haveVenToCleanup = true
return appRepo.RenameApplication(appName, venName)
},
},
// push
{
Forward: func() error {
return appRepo.PushApplication(appName, manifestPath, appPath, stackName, timeout, vars, varsFiles, envs, showLogs)
},
ReversePrevious: func() error {
if !haveVenToCleanup {
return nil
}
// If the app cannot start we'll have a lingering application
// We delete this application so that the rename can succeed
appRepo.DeleteApplication(appName)
return appRepo.RenameApplication(venName, appName)
},
},
// delete
{
Forward: func() error {
if !haveVenToCleanup {
return nil
}
return appRepo.DeleteApplication(venName)
},
},
}
}
func (plugin AutopilotPlugin) Run(cliConnection plugin.CliConnection, args []string) {
// only handle if actually invoked, else it can't be uninstalled cleanly
if args[0] != "zero-downtime-push" {
return
}
appRepo := NewApplicationRepo(cliConnection)
appName, manifestPath, appPath, timeout, stackName, vars, varsFiles, envs, showLogs, err := ParseArgs(args)
fatalIf(err)
fatalIf((&rewind.Actions{
Actions: getActionsForApp(appRepo, appName, manifestPath, appPath, stackName, timeout, vars, varsFiles, envs, showLogs),
RewindFailureMessage: "Oh no. Something's gone wrong. I've tried to roll back but you should check to see if everything is OK.",
}).Execute())
fmt.Println()
fmt.Println("A new version of your application has successfully been pushed!")
fmt.Println()
_ = appRepo.ListApplications()
}
func (AutopilotPlugin) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "autopilot",
Version: plugin.VersionType{
Major: 0,
Minor: 0,
Build: 10,
},
Commands: []plugin.Command{
{
Name: "zero-downtime-push",
HelpText: "Perform a zero-downtime push of an application over the top of an old one",
UsageDetails: plugin.Usage{
Usage: "$ cf zero-downtime-push application-to-replace \\ \n \t-f path/to/new_manifest.yml \\ \n \t-p path/to/new/path",
},
},
},
}
}
type StringSlice []string
func (s *StringSlice) String() string {
return fmt.Sprint(*s)
}
func (s *StringSlice) Set(value string) error {
*s = append(*s, value)
return nil
}
//ParseArgs parse all cmd arguments
func ParseArgs(args []string) (string, string, string, int, string, []string, []string, []string, bool, error) {
flags := flag.NewFlagSet("zero-downtime-push", flag.ContinueOnError)
var envs StringSlice
var vars StringSlice
var varsFiles StringSlice
manifestPath := flags.String("f", "", "path to an application manifest")
appPath := flags.String("p", "", "path to application files")
stackName := flags.String("s", "", "name of the stack to use")
timeout := flags.Int("t", 60, "push timout in secounds defualt 60s")
showLogs := flags.Bool("show-app-log", false, "tail and show application log during application start")
flags.Var(&envs, "env", "Variable key value pair for adding dynamic environment variables; can specity multiple times")
flags.Var(&vars, "var", "Variable key value pair for variable substitution, (e.g., name=app1); can specify multiple times")
flags.Var(&varsFiles, "vars-file", "Path to a variable substitution file for manifest; can specify multiple times")
//default start index of parameters is 2 because 1 is the appName
argumentStartIndex := 2
//if first argument is not the appName we have to read the appName out of the manifest
noAppNameProvided, _ := regexp.MatchString("^-[a-z]{0,3}", args[1])
//noAppNameProvided := strings.Contains(args[1], "-")
if noAppNameProvided {
argumentStartIndex = 1
}
err := flags.Parse(args[argumentStartIndex:])
if err != nil {
return "", "", "", *timeout, "", []string{}, []string{}, []string{}, false, err
}
if *manifestPath == "" {
return "", "", "", *timeout, "", []string{}, []string{}, []string{}, false, ErrNoManifest
}
//parse first argument as appName
appName := args[1]
if noAppNameProvided {
manifest, err := manifest.ParseManifest(*manifestPath)
if err != nil {
return "", "", "", *timeout, "", []string{}, []string{}, []string{}, false, fmt.Errorf("error while parsing manifest %v", err)
}
appName = manifest.ApplicationManifests[0].Name
}
//validate var format
if len(envs) > 0 {
for _, envPair := range envs {
if strings.Contains(envPair, "=") == false {
return "", "", "", *timeout, "", []string{}, []string{}, []string{}, false, ErrWrongVarFormat
}
}
}
return appName, *manifestPath, *appPath, *timeout, *stackName, vars, varsFiles, envs, *showLogs, nil
}
var (
ErrNoManifest = errors.New("a manifest is required to push this application")
ErrManifest = errors.New("could not parse manifest")
ErrWrongVarFormat = errors.New("--var would be in wrong format, use the vars like key=value")
)
type ApplicationRepo struct {
conn plugin.CliConnection
}
func NewApplicationRepo(conn plugin.CliConnection) *ApplicationRepo {
return &ApplicationRepo{
conn: conn,
}
}
func (repo *ApplicationRepo) RenameApplication(oldName, newName string) error {
_, err := repo.conn.CliCommand("rename", oldName, newName)
return err
}
func (repo *ApplicationRepo) PushApplication(appName, manifestPath, appPath, stackName string, timeout int, vars []string, varsFiles []string, envs []string, showLogs bool) error {
args := []string{"push", appName, "-f", manifestPath, "--no-start"}
if appPath != "" {
args = append(args, "-p", appPath)
}
if stackName != "" {
args = append(args, "-s", stackName)
}
/* always append timout */
timeoutS := strconv.Itoa(timeout)
args = append(args, "-t", timeoutS)
for _, varPair := range vars {
args = append(args, "--var", varPair)
}
for _, varsFile := range varsFiles {
args = append(args, "--vars-file", varsFile)
}
_, err := repo.conn.CliCommand(args...)
if err != nil {
return err
}
envErr := repo.SetEnvironmentVariables(appName, envs)
if envErr != nil {
return envErr
}
if showLogs {
app, err := repo.conn.GetApp(appName)
if err != nil {
return err
}
dopplerEndpoint, err := repo.conn.DopplerEndpoint()
if err != nil {
return err
}
token, err := repo.conn.AccessToken()
if err != nil {
return err
}
cons := consumer.New(dopplerEndpoint, nil, nil)
defer cons.Close()
messages, errors := cons.TailingLogs(app.Guid, token)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for {
select {
case m := <-messages:
if m.GetSourceType() != "STG" { // skip STG messages as the cf tool already prints them
os.Stderr.WriteString(logs.NewNoaaLogMessage(m).ToLog(time.Local) + "\n")
}
case e := <-errors:
log.Println("error reading logs:", e)
case <-ctx.Done():
return
}
}
}()
}
_, err = repo.conn.CliCommand("start", appName)
if err != nil {
return err
}
return nil
}
//SetEnvironmentVariable set passed envs with set-env to set variables dynamically
func (repo *ApplicationRepo) SetEnvironmentVariables(appName string, envs []string) error {
varArgs := []string{"set-env", appName}
//set all variables passed by --var
for _, envPair := range envs {
tmpArgs := make([]string, len(varArgs))
copy(tmpArgs, varArgs)
newArgs := strings.Split(envPair, "=")
tmpArgs = append(tmpArgs, newArgs...)
_, err := repo.conn.CliCommand(tmpArgs...)
if err != nil {
return err
}
}
return nil
}
func (repo *ApplicationRepo) DeleteApplication(appName string) error {
_, err := repo.conn.CliCommand("delete", appName, "-f")
return err
}
func (repo *ApplicationRepo) ListApplications() error {
_, err := repo.conn.CliCommand("apps")
return err
}
type AppEntity struct {
State string `json:"state"`
}
var (
ErrAppNotFound = errors.New("application not found")
)
// GetAppMetadata returns metadata about an app with appName
func (repo *ApplicationRepo) GetAppMetadata(appName string) (*AppEntity, error) {
space, err := repo.conn.GetCurrentSpace()
if err != nil {
return nil, err
}
path := fmt.Sprintf(`v2/apps?q=name:%s&q=space_guid:%s`, url.QueryEscape(appName), space.Guid)
result, err := repo.conn.CliCommandWithoutTerminalOutput("curl", path)
if err != nil {
return nil, err
}
jsonResp := strings.Join(result, "")
output := struct {
Resources []struct {
Entity AppEntity `json:"entity"`
} `json:"resources"`
}{}
err = json.Unmarshal([]byte(jsonResp), &output)
if err != nil {
return nil, err
}
if len(output.Resources) == 0 {
return nil, ErrAppNotFound
}
return &output.Resources[0].Entity, nil
}