/
stacks.go
292 lines (231 loc) · 6.56 KB
/
stacks.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
package main
import (
"bufio"
"context"
"crypto/rand"
"errors"
"fmt"
"math/big"
"net/http"
"os"
"strconv"
"github.com/function61/gokit/ezhttp"
"github.com/function61/gokit/osutil"
"github.com/function61/james/pkg/jamestypes"
"github.com/function61/james/pkg/portainerclient"
"github.com/function61/james/pkg/servicespec"
"github.com/sergi/go-diff/diffmatchpatch"
"github.com/spf13/cobra"
)
func stackDeploy(path string, dryRun bool, stackName string, retriesLeft int) error {
ctx := context.TODO() // take from caller
if retriesLeft <= 0 {
return errors.New("stackDeploy retries exceeded")
}
jctx, err := readJamesfile()
if err != nil {
return err
}
updated, err := servicespec.SpecToComposeByPath(path)
if err != nil {
return err
}
portainer, err := makePortainerClient2(ctx, *jctx)
if err != nil {
return err
}
// "prod5:stacks/hellohttp.hcl"
jamesRef := jctx.ClusterID + ":" + path
stacks, err := portainer.ListStacks(ctx)
if err != nil {
return err
}
diffAndAck := func(previous string, needAck bool) error {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(previous, updated, false)
// or DiffCleanupSemantic?
diffs = dmp.DiffCleanupMerge(diffs)
fmt.Println(dmp.DiffPrettyText(diffs))
if !needAck {
return nil
}
fmt.Printf("deploy y/n: ")
line, _, err := bufio.NewReader(os.Stdin).ReadLine()
if err != nil {
return err
}
if string(line) != "y" {
return fmt.Errorf("ack not 'y'; got %s", line)
}
fmt.Println("HOLD ON TO YOUR BUTTS")
return nil
}
stack := findPortainerStackByRef(jamesRef, jctx.Cluster.PortainerEndpointId, stacks)
if stack == nil { // new stack
if stackName == "" {
return errors.New("creation of new stack requires --name CLI arg")
}
fmt.Printf("NOTE! stack by JAMES_REF=%s not found - creating new\n", jamesRef)
if err := diffAndAck("", !dryRun); err != nil {
return err
}
if dryRun {
return nil
}
if err := portainer.CreateStack(context.TODO(), stackName, jamesRef, updated); err != nil {
return err
}
} else { // update existing stack
stackId := fmt.Sprintf("%d", stack.Id)
previous, err := portainer.StackFile(context.TODO(), stackId)
if err != nil {
return err
}
if err := diffAndAck(previous, !dryRun); err != nil {
return err
}
if dryRun {
return nil
}
if err := portainer.UpdateStack(context.TODO(), stackId, jamesRef, updated); err != nil {
return err
}
}
fmt.Println("✓ p.s. " + randomJurassicParkQuote())
return nil
}
func stackRm(path string) error {
jctx, err := readJamesfile()
if err != nil {
return err
}
portainer, err := makePortainerClient(*jctx, false)
if err != nil {
return err
}
// "prod5:stacks/hellohttp.hcl"
jamesRef := jctx.ClusterID + ":" + path
stacks, err := portainer.ListStacks(context.TODO())
if err != nil {
return err
}
stack := findPortainerStackByRef(jamesRef, jctx.Cluster.PortainerEndpointId, stacks)
if stack == nil {
return fmt.Errorf("stack to delete not found: %s", path)
}
return portainer.DeleteStack(context.TODO(), stack.Id)
}
func stackDeployEntry() *cobra.Command {
dry := false
name := ""
cmd := &cobra.Command{
Use: "deploy <path to .hcl>",
Short: "Deploys a stack",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
osutil.ExitIfError(stackDeploy(args[0], dry, name, 2))
},
}
cmd.Flags().StringVarP(&name, "name", "n", name, "Name of the stack (needed when deploying new stack)")
cmd.Flags().BoolVarP(&dry, "dry", "d", dry, "Instead of deploying, just make a dry run (do a diff)")
return cmd
}
func stackRmEntry() *cobra.Command {
cmd := &cobra.Command{
Use: "rm <stackId>",
Short: "Removes a stack",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
osutil.ExitIfError(stackRm(args[0]))
},
}
return cmd
}
func stackEntry() *cobra.Command {
cmd := &cobra.Command{
Use: "stack",
Short: "Stack related commands",
}
cmd.AddCommand(stackDeployEntry())
cmd.AddCommand(stackRmEntry())
return cmd
}
func makePortainerClient(
jctx jamestypes.JamesfileCtx,
missingTokOk bool,
) (*portainerclient.Client, error) {
if jctx.File.PortainerBaseUrl == "" {
return nil, errors.New("PortainerBaseUrl not defined")
}
tok := ""
if jctx.File.Credentials.PortainerTok != nil {
tok = string(*jctx.File.Credentials.PortainerTok)
} else {
if !missingTokOk {
return nil, errors.New("missing PortainerTok")
}
}
return portainerclient.New(jctx.File.PortainerBaseUrl, tok, jctx.Cluster.PortainerEndpointId)
}
// same as 1, but renews auth token
func makePortainerClient2(
ctx context.Context,
jctx jamestypes.JamesfileCtx,
) (*portainerclient.Client, error) {
client, err := makePortainerClient(jctx, false)
if err != nil {
return nil, err
}
_, err = client.ListStacks(ctx)
if err == nil {
return client, nil
}
// was error
rse := &ezhttp.ResponseStatusError{}
if isResponseStatusError := errors.As(err, &rse); !isResponseStatusError || rse.StatusCode() != http.StatusUnauthorized {
return nil, err // some other unexpected error
}
// was unauthorized error => try to renew the token
if err := portainerRenewAuthToken(); err != nil {
return nil, err
}
// conf got updated
refreshedJctx, err := readJamesfile()
if err != nil {
return nil, err
}
// now assuming it's all good and we don't need further checks
return makePortainerClient(*refreshedJctx, false)
}
func findPortainerStackByRef(ref string, endpointID string, stacks []portainerclient.Stack) *portainerclient.Stack {
for _, stack := range stacks {
if strconv.Itoa(stack.EndpointID) != endpointID {
continue
}
for _, envPair := range stack.Env {
if envPair.Name == "JAMES_REF" && envPair.Value == ref {
return &stack
}
}
}
return nil
}
var jurassicParkQuotes = []string{
"I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy?",
"You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job?",
"Access main program. Access main security. Access main program grid.",
"Don't get cheap on me, Dodgson. That was Hammond's mistake.",
"It’s a UNIX system! I know this!",
}
func randomJurassicParkQuote() string {
return randomString(jurassicParkQuotes)
}
func randomString(strs []string) string {
// regular math/rand would suffice but I hate its "seeding needed" API
// rand.Int(.., 3) // can return 0 | 1 | 2
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(strs))))
if err != nil {
panic(err)
}
return strs[int(n.Int64())]
}