-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbundle.go
More file actions
429 lines (347 loc) · 10 KB
/
bundle.go
File metadata and controls
429 lines (347 loc) · 10 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
// Copyright 2026 Flant JSC
//
// Licensed 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 utils
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/deckhouse/lib-dhctl/pkg/log"
"github.com/name212/govalue"
connection "github.com/deckhouse/lib-connection/pkg"
"github.com/deckhouse/lib-connection/pkg/settings"
"github.com/deckhouse/lib-connection/pkg/ssh/utils/tar"
)
var (
ErrBundleTimeout = errors.New("Timeout step running")
)
type BundleCmdProvider func(ctx context.Context, node connection.Interface, parentDir, bundleDir string) (connection.Command, error)
type (
CommandKiller func(connection.Command)
CommandPreparator func(connection.Command)
BundleOpt func(*Bundle)
)
func BundleWithStepHeader(r *regexp.Regexp) BundleOpt {
return func(b *Bundle) {
b.stepHeaderRegex = r
}
}
func BundleWithNoLogStepOutOnError(v bool) BundleOpt {
return func(b *Bundle) {
b.noLogStepOutOnError = v
}
}
func BundleWithShouldInfoOutChecker(c connection.BundlerShouldInfoOutChecker) BundleOpt {
return func(b *Bundle) {
b.shouldInfoOutCheck = c
}
}
func BundleWithStepsDelimiter(d string) BundleOpt {
return func(b *Bundle) {
b.stepsDelimiter = d
}
}
func BundleWithRetries(r int) BundleOpt {
return func(b *Bundle) {
if r > 0 {
b.retries = r
}
}
}
func BundleWithCommandKiller(k CommandKiller) BundleOpt {
return func(b *Bundle) {
b.commandKiller = k
}
}
func BundleWithCommandPreparator(p CommandPreparator) BundleOpt {
return func(b *Bundle) {
b.commandPreparator = p
}
}
func BundleWithProcessLogger(logger log.ProcessLogger) BundleOpt {
return func(b *Bundle) {
b.processLogger = logger
}
}
func UserBundleOptsOrBashible(inputOpts ...connection.BundlerOption) ([]BundleOpt, error) {
userOpts := make([]connection.BundlerOption, len(inputOpts))
copy(userOpts, inputOpts)
if len(userOpts) == 0 {
userOpts = BashibleBundleOpts()
}
return convertBundleOption(userOpts...)
}
type Bundle struct {
sett settings.Settings
node connection.Interface
scriptPath string
args []string
stepHeaderRegex *regexp.Regexp
shouldInfoOutCheck connection.BundlerShouldInfoOutChecker
noLogStepOutOnError bool
stepsDelimiter string
retries int
commandKiller CommandKiller
commandPreparator CommandPreparator
bundleCmdProvider BundleCmdProvider
processLogger log.ProcessLogger
}
func NewBundle(sett settings.Settings, client connection.Interface, scriptPath string, args []string, opts ...BundleOpt) (*Bundle, error) {
b := &Bundle{
sett: sett,
node: client,
scriptPath: scriptPath,
args: args,
retries: 10,
}
for _, opt := range opts {
opt(b)
}
if b.stepsDelimiter == "" {
return nil, fmt.Errorf("no steps delimiter")
}
if govalue.Nil(b.stepHeaderRegex) {
return nil, fmt.Errorf("no step header regex")
}
if govalue.Nil(b.shouldInfoOutCheck) {
b.shouldInfoOutCheck = shouldNotInfoOutChecker
}
return b, nil
}
func (b *Bundle) WithCmdProvider(provider BundleCmdProvider) *Bundle {
b.bundleCmdProvider = provider
return b
}
func (b *Bundle) Execute(ctx context.Context, parentDir, bundleDir string) ([]byte, error) {
bundleCmd, err := b.getBundleCmd(ctx, parentDir, bundleDir)
if err != nil {
return nil, err
}
bundleCmd.Sudo(ctx)
logger := b.sett.Logger()
processLogger := b.processLogger
if govalue.Nil(processLogger) {
processLogger = logger.ProcessLogger()
}
handler := newOutputHandler(b, bundleCmd, logger, processLogger)
bundleCmd.WithStdoutHandler(handler.getStdoutHandlerFunc())
bundleCmd.WithStderrHandler(handler.getStderrHandlerFunc())
if !govalue.Nil(b.commandPreparator) {
b.commandPreparator(bundleCmd)
}
err = bundleCmd.Run(ctx)
if err != nil {
if handler.lastStep != "" {
processLogger.ProcessFail()
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
// exitErr.Stderr is set in the "os/exec".Cmd.Output method from the Golang standard library.
// But we call the "os/exec".Cmd.Wait method, which does not set the Stderr field.
// We can reuse the exec.ExitError type when handling errors.
exitErr.Stderr = bundleCmd.StderrBytes()
}
err = fmt.Errorf("execute bundle: %w", err)
} else {
processLogger.ProcessEnd()
}
if handler.hasStepTimeout {
return bundleCmd.StdoutBytes(), ErrBundleTimeout
}
return bundleCmd.StdoutBytes(), err
}
func (b *Bundle) getBundleCmd(ctx context.Context, parentDir, bundleDir string) (connection.Command, error) {
if !govalue.Nil(b.bundleCmdProvider) {
return b.bundleCmdProvider(ctx, b.node, parentDir, bundleDir)
}
bundleName := fmt.Sprintf("bundle-%s.tar", time.Now().Format("20060102-150405"))
bundleLocalFilepath := filepath.Join(b.sett.TmpDir(), bundleName)
// tar cpf bundle.tar -C /tmp/dhctl.1231qd23/var/lib bashible
err := tar.CreateTar(bundleLocalFilepath, parentDir, bundleDir)
if err != nil {
return nil, fmt.Errorf("tar bundle: %v", err)
}
b.sett.RegisterOnShutdown(
"Delete bashible bundle folder",
func() { _ = os.Remove(bundleLocalFilepath) },
)
nodeTmp := b.sett.NodeTmpDir()
// upload to node's deckhouse tmp directory
err = b.node.File().Upload(ctx, bundleLocalFilepath, nodeTmp)
if err != nil {
return nil, fmt.Errorf("upload: %v", err)
}
// sudo:
// tar xpof ${app.DeckhouseNodeTmpPath}/bundle.tar -C /var/lib && /var/lib/bashible/bashible.sh args...
tarCmdline := fmt.Sprintf(
"tar xpof %s/%s -C /var/lib && /var/lib/%s/%s %s",
nodeTmp,
bundleName,
bundleDir,
b.scriptPath,
strings.Join(b.args, " "),
)
return b.node.Command(tarCmdline), nil
}
func (b *Bundle) killCommand(cmd connection.Command) {
if govalue.Nil(cmd) {
return
}
if govalue.Nil(b.commandKiller) {
return
}
b.commandKiller(cmd)
}
type outputHandler struct {
cmd connection.Command
processLogger log.ProcessLogger
logger log.Logger
bundler *Bundle
logsMu sync.Mutex
stepLogs []string
lastStep string
failsCounter int
hasStepTimeout bool
}
func newOutputHandler(bundler *Bundle, cmd connection.Command, logger log.Logger, processLogger log.ProcessLogger) *outputHandler {
return &outputHandler{
bundler: bundler,
cmd: cmd,
logger: logger,
processLogger: processLogger,
stepLogs: make([]string, 0),
}
}
func (h *outputHandler) getStdoutHandlerFunc() func(string) {
return func(line string) {
h.handleStdout(line)
}
}
func (h *outputHandler) getStderrHandlerFunc() func(string) {
return func(line string) {
h.appendLog(line)
}
}
func (h *outputHandler) appendLog(l string) {
h.logsMu.Lock()
defer h.logsMu.Unlock()
h.stepLogs = append(h.stepLogs, l)
}
func (h *outputHandler) flushLogs(onlyReset bool) string {
h.logsMu.Lock()
defer h.logsMu.Unlock()
res := ""
if !onlyReset {
res = strings.Join(h.stepLogs, "\n")
}
h.stepLogs = make([]string, 0)
return res
}
func (h *outputHandler) handleStdout(l string) {
if l == h.bundler.stepsDelimiter {
return
}
if !h.bundler.stepHeaderRegex.MatchString(l) {
outString := l
doLog := h.logger.DebugF
if infoOut := h.bundler.shouldInfoOutCheck(l); infoOut != "" {
outString = infoOut
doLog = h.logger.InfoF
}
h.appendLog(outString)
doLog("%s", outString)
return
}
match := h.bundler.stepHeaderRegex.FindStringSubmatch(l)
if len(match) < 2 {
return
}
stepName := match[1]
if h.lastStep == stepName {
logMessage := h.flushLogs(false)
switch {
case h.bundler.noLogStepOutOnError && h.failsCounter == 0:
h.logger.ErrorF("%s", logMessage)
case h.bundler.noLogStepOutOnError && h.failsCounter > 0:
h.logger.ErrorF("Run step %s finished with error^^^\n", stepName)
h.logger.DebugF("%s", logMessage)
default:
h.logger.ErrorF("%s", logMessage)
}
h.failsCounter++
if h.failsCounter > h.bundler.retries {
h.hasStepTimeout = true
h.bundler.killCommand(h.cmd)
return
}
h.processLogger.ProcessFail()
stepName = fmt.Sprintf("%s, retry attempt #%d of %d", stepName, h.failsCounter, h.bundler.retries)
} else if h.lastStep != "" {
_ = h.flushLogs(true)
h.processLogger.ProcessEnd()
h.failsCounter = 0
}
h.processLogger.ProcessStart("Run step " + stepName)
h.lastStep = match[1]
}
var (
bashibleStepsHeaderRegexp = regexp.MustCompile("^=== Step: /var/lib/bashible/bundle_steps/(.*)$")
bashibleStepOutputHeaderRegexp = regexp.MustCompile("^=== Step output: (.*)$")
)
func shouldNotInfoOutChecker(l string) string {
return ""
}
func bashibleShouldInfoOutChecker(l string) string {
if bashibleStepOutputHeaderRegexp.MatchString(l) {
match := bashibleStepOutputHeaderRegexp.FindStringSubmatch(l)
if len(match) >= 2 {
return match[1]
}
}
return ""
}
func BashibleBundleOpts() []connection.BundlerOption {
return []connection.BundlerOption{
connection.BundlerWithStepHeaderRegex(bashibleStepsHeaderRegexp),
connection.BundlerWithStepDelimiter("==="),
connection.BundlerWithRetries(10),
connection.BundlerWithShouldInfoOutChecker(bashibleShouldInfoOutChecker),
}
}
func convertBundleOption(opts ...connection.BundlerOption) ([]BundleOpt, error) {
if len(opts) == 0 {
return nil, nil
}
options := connection.BundlerOptions{}
for _, opt := range opts {
opt(&options)
}
if err := options.IsValid(); err != nil {
return nil, err
}
return []BundleOpt{
BundleWithRetries(options.Retries),
BundleWithStepHeader(options.StepHeaderRegex),
BundleWithStepsDelimiter(options.StepsDelimiter),
BundleWithNoLogStepOutOnError(options.NoLogStepOutOnError),
BundleWithShouldInfoOutChecker(options.ShouldInfoOutChecker),
BundleWithProcessLogger(options.ProcessLogger),
}, nil
}