forked from pkallberg/cx
/
stack-create.go
291 lines (247 loc) · 7.48 KB
/
stack-create.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/cloud66/cloud66"
"github.com/cloud66/cx/term"
"github.com/cloud66/cli"
)
func runCreateStack(c *cli.Context) {
name := c.String("name")
environment := c.String("environment")
serviceYamlFile := c.String("service_yaml")
manifestYamlFile := c.String("manifest_yaml")
manifestYaml := ""
if len(name) < 5 {
printFatal("name is required and must be at least 5 characters long")
}
if environment == "" {
printFatal("environment is required")
}
// handle service yaml file
if serviceYamlFile == "" {
printFatal("service_yaml file path is required")
} else {
serviceYamlFile = expandPath(serviceYamlFile)
}
serviceYamlBytes, err := ioutil.ReadFile(serviceYamlFile)
must(err)
serviceYaml := string(serviceYamlBytes)
accountInfo, err := currentAccountInfo()
must(err)
fmt.Printf("Using account: %s\n", accountInfo.Owner)
targetOptions := make(map[string]string)
if manifestYamlFile != "" {
fmt.Println("Using supplied manifest file")
manifestYamlFile = expandPath(manifestYamlFile)
manifestYamlBytes, err := ioutil.ReadFile(manifestYamlFile)
must(err)
manifestYaml = string(manifestYamlBytes)
} else {
fmt.Println("Note: No manifest provided; for additional options you can provide your own manifest with this command")
targetCloud, err := askForCloud(*accountInfo)
must(err)
targetOptions["cloud"] = targetCloud.Id
targetOptions["key_name"] = targetCloud.KeyName
targetRegion, targetSize, err := askForSizeAndRegion(*targetCloud)
must(err)
targetOptions["region"] = targetRegion
targetOptions["size"] = targetSize
targetBuildType, err := askForBuildType()
must(err)
targetOptions["build_type"] = targetBuildType
}
asyncId, err := startCreateStack(name, environment, serviceYaml, manifestYaml, targetOptions)
must(err)
// now we fetch the corresponding stack
stack, err := client.StackInfoWithEnvironment(name, environment)
must(err)
// wait for the stack analysis to complete
_, err = endCreateStack(*asyncId, stack.Uid)
must(err)
fmt.Printf("\nStack created; Build starting...\n\n")
err = initiateStackBuild(stack.Uid)
must(err)
// logging output
go StartListen(stack)
stack, err = WaitStackBuild(stack.Uid, false)
must(err)
fmt.Println("Stack build completed successfully!")
}
func startCreateStack(name, environment, serviceYaml, manifestYaml string, targetOptions map[string]string) (*int, error) {
asyncRes, err := client.CreateStack(name, environment, serviceYaml, manifestYaml, targetOptions)
if err != nil {
return nil, err
}
return &asyncRes.Id, err
}
func endCreateStack(asyncId int, stackUid string) (*cloud66.GenericResponse, error) {
return client.WaitStackAsyncAction(asyncId, stackUid, 5*time.Second, 20*time.Minute, false)
}
func initiateStackBuild(stackUid string) error {
_, err := client.RedeployStack(stackUid, "", nil)
return err
}
func askForCloud(accountInfo cloud66.Account) (*cloud66.Cloud, error) {
cloudsInfo, err := client.GetCloudsInfo()
if err != nil {
return nil, errors.New("No available cloud providers in current account, please add via the Cloud 66 UI")
}
fmt.Println("\nPlease select your target cloud:")
cloudMap := make(map[string]cloud66.Cloud)
for index, usedCloud := range cloudsInfo {
stringIndex := strconv.Itoa(index + 1)
cloudMap[stringIndex] = usedCloud
fmt.Printf("%s. %s (%s)\n", stringIndex, usedCloud.Id, usedCloud.KeyName)
}
if term.IsTerminal(os.Stdin) {
fmt.Printf("> ")
}
var selection string
if _, err := fmt.Scanln(&selection); err != nil {
printFatal(err.Error())
}
cloudInfo := cloudMap[selection]
if cloudInfo.Id == "" {
return nil, errors.New("Invalid selection!")
}
return &cloudInfo, nil
}
func askForSizeAndRegion(cloudInfo cloud66.Cloud) (string, string, error) {
fmt.Println("\nPlease select your cloud region:")
regionMap := make(map[string]string)
for index, region := range cloudInfo.Regions {
stringIndex := strconv.Itoa(index + 1)
regionMap[stringIndex] = region.Id
fmt.Printf("%s. %s\n", stringIndex, region.Name)
}
if term.IsTerminal(os.Stdin) {
fmt.Printf("> ")
}
var selection string
if _, err := fmt.Scanln(&selection); err != nil {
printFatal(err.Error())
}
if regionMap[selection] == "" {
return "", "", errors.New("Invalid selection!")
}
// store for return
region := regionMap[selection]
fmt.Println("\nPlease select your server size:")
sizeMap := make(map[string]string)
for index, serverSize := range cloudInfo.ServerSizes {
stringIndex := strconv.Itoa(index + 1)
sizeMap[stringIndex] = serverSize.Id
fmt.Printf("%s. %s\n", stringIndex, serverSize.Name)
}
if term.IsTerminal(os.Stdin) {
fmt.Printf("> ")
}
if _, err := fmt.Scanln(&selection); err != nil {
printFatal(err.Error())
}
if sizeMap[selection] == "" {
return "", "", errors.New("Invalid selection!")
}
// store for return
size := sizeMap[selection]
return region, size, nil
}
// values are standalone or dedicated
func askForBuildType() (string, error) {
fmt.Println("\nPlease select your server build type: ")
serverMap := make(map[string]string)
serverMap["1"] = "multi"
fmt.Printf("1. %s\n", "Each database type on its own server")
serverMap["2"] = "single"
fmt.Printf("2. %s\n", "Everything on a single server (not recommended for production)")
if term.IsTerminal(os.Stdin) {
fmt.Printf("> ")
}
var selection string
if _, err := fmt.Scanln(&selection); err != nil {
printFatal(err.Error())
}
if serverMap[selection] == "" {
return "", errors.New("Invalid selection!")
}
return serverMap[selection], nil
}
func currentAccountInfo() (*cloud66.Account, error) {
accountInfos, err := client.AccountInfos()
if err != nil {
return nil, err
}
if len(accountInfos) < 1 {
printFatal("User associated with this request has no accounts")
}
for _, accountInfo := range accountInfos {
if accountInfo.CurrentAccount {
return &accountInfo, nil
}
}
return nil, errors.New("No account found for current user")
}
func WaitStackBuild(stackUid string, visualFeedback bool) (*cloud66.Stack, error) {
// timout timer
timeout := 3 * time.Hour
timeoutTimer := time.NewTimer(timeout)
defer timeoutTimer.Stop()
// handle interrupts
termChan := make(chan os.Signal, 1)
signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
// perform checks
updateTicker := time.NewTicker(1 * time.Minute)
defer updateTicker.Stop()
// perform visual feedbacks
visualTicker := time.NewTicker(20 * time.Second)
defer visualTicker.Stop()
// capture results
completeChan := make(chan *cloud66.Stack)
errorChan := make(chan error)
go func() {
for {
select {
case <-visualTicker.C:
if visualFeedback {
fmt.Printf(".")
}
case <-updateTicker.C:
// fetch the current status of the async action
stack, err := client.FindStackByUid(stackUid)
if err != nil {
errorChan <- err
return
}
// check for a result!
if (stack.StatusCode == 1 || stack.StatusCode == 2 || stack.StatusCode == 7) &&
(stack.HealthCode == 2 || stack.HealthCode == 3 || stack.HealthCode == 4) {
completeChan <- stack
return
}
case <-timeoutTimer.C:
// too late! abort!
errorChan <- errors.New("timed-out after " + strconv.FormatInt(int64(timeout)/int64(time.Second), 10) + " second(s)")
return
case <-termChan:
// too late! abort!
errorChan <- errors.New("Aborted!")
return
}
}
}()
for {
select {
case stack := <-completeChan:
return stack, nil
case err := <-errorChan:
return nil, err
}
}
}