-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathmain.go
271 lines (223 loc) · 7.72 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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strings"
"code.cloudfoundry.org/cli/plugin"
"code.cloudfoundry.org/cli/plugin/models"
"github.com/bluemixgaragelondon/cf-blue-green-deploy/manifest"
)
var PluginVersion string
type CfPlugin struct {
Connection plugin.CliConnection
Deployer BlueGreenDeployer
}
func (p *CfPlugin) Run(cliConnection plugin.CliConnection, args []string) {
if len(args) > 0 && args[0] == "CLI-MESSAGE-UNINSTALL" {
return
}
argsStruct := NewArgs(args)
p.Connection = cliConnection
cfDomains := manifest.CfDomains{}
var err error
cfDomains.SharedDomains, err = p.SharedDomains()
if err != nil {
log.Fatalf("Failed to get shared domains: %v", err)
}
if len(cfDomains.SharedDomains) < 1 {
log.Fatalf("Failed to get default shared domain (no shared domains defined)")
} else {
cfDomains.DefaultDomain = cfDomains.SharedDomains[0]
}
cfDomains.PrivateDomains, err = p.PrivateDomains()
if err != nil {
log.Fatalf("Failed to get private domains: %v", err)
}
p.Deployer.Setup(cliConnection)
if argsStruct.AppName == "" {
log.Fatal("App name was empty, must be provided.")
}
reader := manifest.FileManifestReader{argsStruct.ManifestPath}
if !p.Deploy(cfDomains, &reader, argsStruct) {
log.Fatal("Smoke tests failed")
}
}
func (p *CfPlugin) Deploy(cfDomains manifest.CfDomains, manifestReader manifest.ManifestReader, args Args) bool {
appName := args.AppName
p.Deployer.DeleteAllAppsExceptLiveApp(appName)
liveAppName, liveAppRoutes := p.Deployer.LiveApp(appName)
manifestScaleParameters := p.GetScaleFromManifest(appName, cfDomains, manifestReader)
// TODO We're overloading 'new' here for both the staging app and the 'finished' app, which is confusing
newAppRoutes := p.GetNewAppRoutes(args.AppName, cfDomains, manifestReader, liveAppRoutes)
newAppName := appName + "-new"
// Add route so that we can run the smoke tests
tempRouteDomain := newAppRoutes[0].Domain
tempRoute := plugin_models.GetApp_RouteSummary{Host: newAppName, Domain: tempRouteDomain}
// If deploy is unsuccessful, p.ErrorFunc will be called which exits.
p.Deployer.PushNewApp(newAppName, tempRoute, args.ManifestPath, manifestScaleParameters)
if liveAppName != "" {
p.Deployer.SetSshAccess(newAppName, p.Deployer.CheckSshEnablement(appName))
}
promoteNewApp := true
smokeTestScript := args.SmokeTestPath
if smokeTestScript != "" {
promoteNewApp = p.Deployer.RunSmokeTests(smokeTestScript, FQDN(tempRoute))
}
p.Deployer.UnmapRoutesFromApp(newAppName, tempRoute)
p.Deployer.DeleteRoutes(tempRoute)
if promoteNewApp {
// If there is a live app, we want to disassociate the routes with the old version of the app
// and instead update the routes to use the new version.
if liveAppName != "" {
p.Deployer.MapRoutesToApp(newAppName, newAppRoutes...)
p.Deployer.RenameApp(liveAppName, appName+"-old")
p.Deployer.RenameApp(newAppName, appName)
p.Deployer.UnmapRoutesFromApp(appName+"-old", liveAppRoutes...)
} else {
// If there is no live app, we only need to add our new routes.
p.Deployer.MapRoutesToApp(newAppName, newAppRoutes...)
p.Deployer.RenameApp(newAppName, appName)
}
if args.DeleteOldApps {
p.Deployer.DeleteAllAppsExceptLiveAndFailedApp(appName)
}
return true
} else {
// We don't want to promote. Instead mark it as failed.
p.Deployer.RenameApp(newAppName, appName+"-failed")
return false
}
}
func (p *CfPlugin) GetNewAppRoutes(appName string, cfDomains manifest.CfDomains, manifestReader manifest.ManifestReader, liveAppRoutes []plugin_models.GetApp_RouteSummary) []plugin_models.GetApp_RouteSummary {
newAppRoutes := []plugin_models.GetApp_RouteSummary{}
parsedManifest, err := manifestReader.Read()
if err != nil {
// This error should be handled properly
fmt.Println(err)
}
if parsedManifest != nil {
if appParams := parsedManifest.GetAppParams(appName, cfDomains); appParams != nil && appParams.Routes != nil {
newAppRoutes = appParams.Routes
}
}
uniqueRoutes := p.UnionRouteLists(newAppRoutes, liveAppRoutes)
if len(uniqueRoutes) == 0 {
uniqueRoutes = append(uniqueRoutes, plugin_models.GetApp_RouteSummary{Host: appName, Domain: plugin_models.GetApp_DomainFields{Name: cfDomains.DefaultDomain}})
}
return uniqueRoutes
}
func (p *CfPlugin) GetScaleFromManifest(appName string, cfDomains manifest.CfDomains,
manifestReader manifest.ManifestReader) (scaleParameters ScaleParameters) {
parsedManifest, err := manifestReader.Read()
if err != nil {
// TODO: Handle this error nicely
fmt.Println(err)
}
if parsedManifest != nil {
manifestScaleParameters := parsedManifest.GetAppParams(appName, cfDomains)
if manifestScaleParameters != nil {
scaleParameters = ScaleParameters{
Memory: manifestScaleParameters.Memory,
InstanceCount: manifestScaleParameters.InstanceCount,
DiskQuota: manifestScaleParameters.DiskQuota,
}
}
}
return
}
func (p *CfPlugin) contains(list []plugin_models.GetApp_RouteSummary, value plugin_models.GetApp_RouteSummary) bool {
for _, v := range list {
if (v == value) {
return true;
}
}
return false;
}
func (p *CfPlugin) UnionRouteLists(listA []plugin_models.GetApp_RouteSummary, listB []plugin_models.GetApp_RouteSummary) []plugin_models.GetApp_RouteSummary {
duplicateList := append(listA, listB...)
uniqueRoutes := []plugin_models.GetApp_RouteSummary{}
for _, route := range duplicateList {
if (! p.contains(uniqueRoutes, route)) {
uniqueRoutes = append(uniqueRoutes, route)
}
}
return uniqueRoutes
}
func (p *CfPlugin) GetMetadata() plugin.PluginMetadata {
var major, minor, build int
fmt.Sscanf(PluginVersion, "%d.%d.%d", &major, &minor, &build)
return plugin.PluginMetadata{
Name: "blue-green-deploy",
Version: plugin.VersionType{
Major: major,
Minor: minor,
Build: build,
},
Commands: []plugin.Command{
{
Name: "blue-green-deploy",
Alias: "bgd",
HelpText: "Zero-downtime deploys with smoke tests",
UsageDetails: plugin.Usage{
// TODO for manifests with multiple apps, a different smoke test is needed. The approach below would not work.
// Perhaps we could name the smoke test in the manifest?
Usage: "blue-green-deploy APP_NAME [--smoke-test TEST_SCRIPT] [-f MANIFEST_FILE] [--delete-old-apps]",
Options: map[string]string{
"smoke-test": "The test script to run.",
"f": "Path to manifest",
"delete-old-apps": "Delete old app instance(s)",
},
},
},
},
}
}
func (p *CfPlugin) PrivateDomains() (domains []string, apiErr error) {
path := "/v2/private_domains"
return p.listCfDomains(path)
}
func (p *CfPlugin) SharedDomains() (domains []string, apiErr error) {
path := "/v2/shared_domains"
return p.listCfDomains(path)
}
func (p *CfPlugin) listCfDomains(cfPath string) (domains []string, err error) {
var res []string
if res, err = p.Connection.CliCommandWithoutTerminalOutput("curl", cfPath); err != nil {
return
}
response := struct {
Resources []struct {
Entity struct {
Name string
}
}
}{}
var jsonString string
jsonString = strings.Join(res, "\n")
if err = json.Unmarshal([]byte(jsonString), &response); err != nil {
return
}
for i, _ := range response.Resources {
domains = append(domains, response.Resources[i].Entity.Name)
}
return
}
func FQDN(r plugin_models.GetApp_RouteSummary) string {
return fmt.Sprintf("%v.%v", r.Host, r.Domain.Name)
}
func main() {
log.SetFlags(0)
p := CfPlugin{
Deployer: &BlueGreenDeploy{
ErrorFunc: func(message string, err error) {
log.Fatalf("%v - %v", message, err)
},
Out: os.Stdout,
},
}
// TODO issue #24 - (Rufus) - not sure if I'm using the plugin correctly, but if I build (go build) and run without arguments
// I expected to see available arguments but instead the code panics.
plugin.Start(&p)
}