This repository has been archived by the owner on Dec 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
autopilot.go
359 lines (300 loc) · 8.84 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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/url"
"os"
"strings"
"time"
"code.cloudfoundry.org/cli/cf/api/logs"
"code.cloudfoundry.org/cli/plugin"
"github.com/cloudfoundry/noaa/consumer"
"github.com/contraband/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, vars []string, varsFiles []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, vars, varsFiles, 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 getActionsForNewApp(appRepo *ApplicationRepo, appName, manifestPath, appPath, stackName string, vars []string, varsFiles []string, showLogs bool) []rewind.Action {
return []rewind.Action{
// push
{
Forward: func() error {
return appRepo.PushApplication(appName, manifestPath, appPath, stackName, vars, varsFiles, showLogs)
},
},
}
}
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, stackName, vars, varsFiles, showLogs, err := ParseArgs(args)
fatalIf(err)
fatalIf((&rewind.Actions{
Actions: getActionsForApp(appRepo, appName, manifestPath, appPath, stackName, vars, varsFiles, 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: 8,
},
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
}
func ParseArgs(args []string) (string, string, string, string, []string, []string, bool, error) {
flags := flag.NewFlagSet("zero-downtime-push", flag.ContinueOnError)
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")
showLogs := flags.Bool("show-app-log", false, "tail and show application log during application start")
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")
if len(args) < 2 || strings.HasPrefix(args[1], "-") {
return "", "", "", "", []string{}, []string{}, false, ErrNoArgs
}
err := flags.Parse(args[2:])
if err != nil {
return "", "", "", "", []string{}, []string{}, false, err
}
appName := args[1]
if *manifestPath == "" {
return "", "", "", "", []string{}, []string{}, false, ErrNoManifest
}
return appName, *manifestPath, *appPath, *stackName, vars, varsFiles, *showLogs, nil
}
var (
ErrNoArgs = errors.New("app name must be specified")
ErrNoManifest = errors.New("a manifest is required to push this application")
)
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, vars []string, varsFiles []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)
}
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
}
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
}
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
}