forked from koupleless/arkctl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.go
More file actions
474 lines (403 loc) · 13.6 KB
/
Copy pathdeploy.go
File metadata and controls
474 lines (403 loc) · 13.6 KB
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package deploy
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/koupleless/arkctl/common/cmdutil"
"github.com/koupleless/arkctl/common/contextutil"
"github.com/koupleless/arkctl/common/fileutil"
"github.com/koupleless/arkctl/common/osutil"
"github.com/koupleless/arkctl/common/runtime"
"github.com/koupleless/arkctl/common/style"
"github.com/koupleless/arkctl/v1/cmd/root"
"github.com/koupleless/arkctl/v1/service/ark"
"github.com/google/uuid"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
)
var (
bizModelVersionFlag string
portFlag int
subBundlePath string
defaultArg string
doBuild bool
podFlag string
podNamespace string // pre parsed pod namespace
podName string // pre parsed pod name
)
const (
ctxKeyArkBizBundlePathInSidePod = "arkBizBundlePathInSidePod"
ctxKeyArkService = "ark.Service"
ctxKeyBizModel = "ark.BizModel"
ctxKeyArkContainerRuntimeInfo = "ark.ContainerRuntimeInfo"
)
var DeployCommand = &cobra.Command{
Use: "deploy [flags] [path/to/your/project/or/bundle]",
Short: "deploy your biz module to running containers",
Long: `
The arkctl deploy subcommand can help you quickly deploy your biz module to running ark container.
We advice you to use this in local dev phase.
`,
Example: `
Scenario 0: Build bundle at current workspace and deploy it to a local running ark container with default port:
arkctl deploy
Scenario 1: Build bundle at given path and deploy it to local running ark container with given port:
arkctl deploy --port ${your ark container portFlag} ${path/to/your/project}
Scenario 2: Deploy a local pre-built bundle to local running ark container:
arkctl deploy ${path/to/your/pre/built/bundle.jar}
Scenario 3: Build and deploy a bundle at current dir to a remote running ark container in k8s cluster with default port:
arkctl deploy --pod ${namespace}/${name}
Scenario 4: Build and deploy a bundle at current dir to a remote running ark container in k8s cluster with biz model version witch is pod key from kubernetes:
arkctl deploy --pod ${namespace}/${name} --biz-model-version ${your-biz-model-version}
Scenario 5: Build an maven multi module project and deploy a sub module to a running ark container:
arkctl deploy --sub ${path/to/your/sub/module}
`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
defaultArg = runtime.MustReturnResult(os.Getwd())
} else {
defaultArg = args[len(args)-1]
if !filepath.IsAbs(defaultArg) {
defaultArg = filepath.Join(runtime.MustReturnResult(os.Getwd()), defaultArg)
}
}
doBuild = !strings.HasSuffix(defaultArg, ".jar")
if podFlag != "" && strings.Contains(podFlag, "/") {
podNamespace, podName = strings.Split(podFlag, "/")[0], strings.Split(podFlag, "/")[1]
} else {
podNamespace, podName = "default", podFlag
}
return nil
},
Run: executeDeploy,
}
func execMavenBuild(ctx *contextutil.Context) bool {
if !doBuild {
return true
}
style.InfoPrefix("Stage").Println("BuildBundle")
style.InfoPrefix("BuildDirectory").Println(defaultArg)
mvn := cmdutil.BuildCommandWithWorkDir(
ctx,
defaultArg,
"mvn",
"clean", "package", "-Dmaven.test.skip=true")
style.InfoPrefix("Command").Println(mvn.String())
if err := mvn.Exec(); err != nil {
pterm.Error.PrintOnErrorf("Build bundle failed: %s!", err)
printSuggestion(err)
return false
}
mvnOutput := []string{}
go func() {
for line := range mvn.Output() {
pterm.Println(line)
mvnOutput = append(mvnOutput, line)
}
}()
if err := <-mvn.Wait(); err != nil {
pterm.Error.PrintOnErrorf("Build bundle failed: %s!", err)
printSuggestion(err)
return false
}
if err := mvn.GetExitError(); err != nil {
pterm.Error.PrintOnErrorf("Build bundle failed: %s!", err)
printSuggestionWithMore(err, mvnOutput)
return false
}
pterm.Info.Printfln(pterm.Green("build bundle success!"))
pterm.Println()
return true
}
func execParseBizModel(ctx *contextutil.Context) bool {
style.InfoPrefix("Stage").Println("ParseBizModel")
bundlePath := osutil.GetLocalFileProtocol() + defaultArg
if doBuild {
searchdir := defaultArg
if subBundlePath != "" {
searchdir = filepath.Join(searchdir, subBundlePath)
}
filepath.Walk(searchdir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && strings.HasSuffix(info.Name(), "-ark-biz.jar") {
bundlePath = path
}
return nil
})
if !strings.HasSuffix(bundlePath, "-ark-biz.jar") {
pterm.Error.Println("can not find pre built biz bundle in build dir!")
return false
}
bundlePath = osutil.GetLocalFileProtocol() + bundlePath
}
bizModel, err := ark.ParseBizModel(ctx, fileutil.FileUrl(bundlePath))
if errors.Is(err, os.ErrNotExist) {
style.ErrorPrefix("File Not Exist").Println(defaultArg)
return false
}
if err != nil {
pterm.Error.PrintOnError(fmt.Errorf("failed to parse bundle: %s", err))
return false
}
if bizModelVersionFlag != "" {
bizModel.BizModelVersion = bizModelVersionFlag
}
ctx.Put(ctxKeyBizModel, bizModel)
style.InfoPrefix("BizBundleInfo").Println(string(runtime.MustReturnResult(json.Marshal(*bizModel))))
pterm.Info.Println(pterm.Green("parse biz bundle success!"))
pterm.Println()
return true
}
func execUploadBizBundle(ctx *contextutil.Context) bool {
bizModel := ctx.Value(ctxKeyBizModel).(*ark.BizModel)
if podFlag != "" && bizModel.BizUrl.GetFileUrlType() == fileutil.FileUrlTypeLocal {
targetPath := fmt.Sprintf("/tmp/%s",
bizModel.BizName+"-"+
bizModel.BizVersion+"-"+
runtime.MustReturnResult(uuid.NewUUID()).String()+"-"+
"ark-biz.jar",
)
kubecpcmd := cmdutil.BuildCommand(ctx,
"kubectl",
"-n",
podNamespace,
"cp",
string(bizModel.BizUrl)[7:],
podName+":"+targetPath,
)
style.InfoPrefix("Stage").Println("UploadBizBundle")
style.InfoPrefix("Command").Println(kubecpcmd.String())
if err := kubecpcmd.Exec(); err != nil {
pterm.Error.PrintOnError(err)
return false
}
go func() {
for line := range kubecpcmd.Output() {
pterm.DefaultLogger.Print(line)
}
}()
if err := <-kubecpcmd.Wait(); err != nil {
pterm.Error.PrintOnError(err)
return false
}
ctx.Put(ctxKeyArkBizBundlePathInSidePod, targetPath)
pterm.Info.Println(pterm.LightGreen("upload biz bundle to pod success!"))
pterm.Println()
}
return true
}
func execInstallInKubePod(ctx *contextutil.Context) bool {
bizModel := ctx.Value(ctxKeyBizModel).(*ark.BizModel)
kubeuninstallcmd := cmdutil.BuildCommand(ctx,
"kubectl",
"-n", podNamespace,
"exec", podName, "--",
"curl",
"-X",
"POST",
"-H",
"'Content-Type: application/json'",
"-d",
string(runtime.MustReturnResult(json.Marshal(ark.BizModel{
BizName: bizModel.BizName,
BizVersion: bizModel.BizVersion,
BizModelVersion: bizModel.BizModelVersion,
}))),
fmt.Sprintf("http://127.0.0.1:%v/uninstallBiz", portFlag),
)
style.InfoPrefix("Command").Println(kubeuninstallcmd.String())
if err := kubeuninstallcmd.Exec(); err != nil {
pterm.Error.PrintOnError(err)
return false
}
// somehow kubectl exec would pipe the pod's realtime output to stderror pipeline
// so we check command exit state directly, instead of judging by the stderror pipeline output
if stderrpipe := <-kubeuninstallcmd.Wait(); stderrpipe != nil {
realtimeoutputlines := stderrpipe.Error()
stdoutlines := &strings.Builder{}
for line := range kubeuninstallcmd.Output() {
stdoutlines.WriteString(line)
}
if err := kubeuninstallcmd.GetExitError(); err != nil {
pterm.Println(realtimeoutputlines)
pterm.Println(stdoutlines)
pterm.Error.PrintOnError(err)
return false
}
if strings.Contains(stdoutlines.String(), "\"code\":\"FAILED\"") &&
!strings.Contains(stdoutlines.String(), "\"code\":\"NOT_FOUND_BIZ\"") {
pterm.Println(realtimeoutputlines)
pterm.Println(stdoutlines)
pterm.Error.Println("uninstall biz failed!")
return false
}
}
kubeinstallcmd := cmdutil.BuildCommand(ctx,
"kubectl",
"-n", podNamespace,
"exec", podName, "--",
"curl",
"-X",
"POST",
"-H",
"'Content-Type: application/json'",
"-d",
string(runtime.MustReturnResult(json.Marshal(ark.BizModel{
BizName: bizModel.BizName,
BizVersion: bizModel.BizVersion,
BizUrl: fileutil.FileUrl(osutil.GetLocalFileProtocol() + ctx.Value(ctxKeyArkBizBundlePathInSidePod).(string)),
BizModelVersion: bizModel.BizModelVersion,
}))),
fmt.Sprintf("http://127.0.0.1:%v/installBiz", portFlag),
)
style.InfoPrefix("Command").Println(kubeinstallcmd.String())
if err := kubeinstallcmd.Exec(); err != nil {
pterm.Error.PrintOnError(err)
return false
}
// somehow kubectl exec would pipe the pod's realtime output to stderror pipeline
// so we check command exit state directly, instead of judging by the stderror pipeline output
if stderrpipe := <-kubeinstallcmd.Wait(); stderrpipe != nil {
realtimeoutputlines := stderrpipe.Error()
stdoutlines := &strings.Builder{}
for line := range kubeinstallcmd.Output() {
stdoutlines.WriteString(line)
}
if err := kubeinstallcmd.GetExitError(); err != nil {
pterm.Println(realtimeoutputlines)
pterm.Println(stdoutlines)
pterm.Error.PrintOnError(err)
return false
}
if strings.Contains(stdoutlines.String(), "\"code\":\"FAILED\"") {
pterm.Println(realtimeoutputlines)
pterm.Println(stdoutlines)
pterm.Error.Println("install biz failed!")
}
pterm.Println(stdoutlines)
}
pterm.Println()
return true
}
// install the given package in target ark container
func execInstallInLocal(ctx *contextutil.Context) bool {
return execUnInstallLocal(ctx) && execInstallLocal(ctx)
}
// install the given package in target ark container
func execInstall(ctx *contextutil.Context) (result bool) {
style.InfoPrefix("Stage").Println("Install")
switch {
case podFlag != "":
result = execInstallInKubePod(ctx)
default:
result = execInstallInLocal(ctx)
}
if result {
pterm.Info.Println(pterm.Green("install biz success!"))
pterm.Println()
}
return
}
// uninstall the given package in target ark container
func execUnInstallLocal(ctx *contextutil.Context) bool {
var (
arkService = ctx.Value(ctxKeyArkService).(ark.Service)
bizModel = ctx.Value(ctxKeyBizModel).(*ark.BizModel)
arkContainerRuntimeInfo = ctx.Value(ctxKeyArkContainerRuntimeInfo).(*ark.ArkContainerRuntimeInfo)
)
if err := arkService.UnInstallBiz(ctx, ark.UnInstallBizRequest{
BizModel: *bizModel,
TargetContainer: *arkContainerRuntimeInfo,
}); err != nil {
pterm.Error.PrintOnError(err)
printSuggestion(err)
return false
}
return true
}
// install the given package in target ark container
func execInstallLocal(ctx *contextutil.Context) bool {
var (
arkService = ctx.Value(ctxKeyArkService).(ark.Service)
bizModel = ctx.Value(ctxKeyBizModel).(*ark.BizModel)
arkContainerRuntimeInfo = ctx.Value(ctxKeyArkContainerRuntimeInfo).(*ark.ArkContainerRuntimeInfo)
)
if err := arkService.InstallBiz(ctx, ark.InstallBizRequest{
BizModel: *bizModel,
TargetContainer: *arkContainerRuntimeInfo,
}); err != nil {
pterm.Error.PrintOnError(err)
printSuggestion(err)
return false
}
return true
}
func generateContext(cmd *cobra.Command) *contextutil.Context {
ctx := contextutil.NewContext(context.Background())
arkService := ark.BuildService(ctx)
ctx.Put(ctxKeyArkService, arkService)
arkContainerRuntimeInfo := &ark.ArkContainerRuntimeInfo{
RunType: ark.ArkContainerRunTypeLocal,
Port: &portFlag,
}
// target is running inside of kubernetes
if podFlag != "" {
arkContainerRuntimeInfo.RunType = ark.ArkContainerRunTypeK8s
arkContainerRuntimeInfo.Coordinate = podFlag
}
ctx.Put(ctxKeyArkContainerRuntimeInfo, arkContainerRuntimeInfo)
return ctx
}
// executeDeploy will execute the deploy command
// 1. build the biz bundle
// 2. parse the biz model for further usage
// 3. uninstall the biz bundle in target ark container to prevent conflict
// 4. install the biz bundle in target ark container
func executeDeploy(cobracmd *cobra.Command, _ []string) {
c := generateContext(cobracmd)
todos := []func(context2 *contextutil.Context) bool{
execMavenBuild,
execParseBizModel,
execUploadBizBundle,
execInstall,
}
for _, todo := range todos {
if !todo(c) {
return
}
}
}
func init() {
root.RootCmd.AddCommand(DeployCommand)
DeployCommand.Flags().StringVar(&podFlag, "pod", "", `
If Provided, arkctl will try to deploy the bundle to the ark container running in given pod.
`)
DeployCommand.Flags().StringVar(&subBundlePath, "sub", "", `
If Provided, arkctl will try to build the project at current dir and deploy the bundle at subBundlePath.
`)
DeployCommand.Flags().IntVar(&portFlag, "port", 1238, `
The default port of ark container is 1238 if not provided.
`)
DeployCommand.Flags().StringVar(&bizModelVersionFlag, "biz-model-version", "", `
If provided, arkctl will use this biz model version to deploy the biz module.
`)
}