/
common.go
97 lines (72 loc) · 2.35 KB
/
common.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
package action
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2021 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"fmt"
"os/exec"
"syscall"
"time"
"pkg.re/essentialkaos/ek.v12/mathutil"
"pkg.re/essentialkaos/ek.v12/timeutil"
"github.com/essentialkaos/bibop/recipe"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// Handler is action handler function
type Handler func(action *recipe.Action) error
// ////////////////////////////////////////////////////////////////////////////////// //
// Wait is action processor for "exit"
func Wait(action *recipe.Action) error {
durSec, err := action.GetF(0)
if err != nil {
return err
}
durSec = mathutil.BetweenF64(durSec, 0.01, 3600.0)
time.Sleep(timeutil.SecondsToDuration(durSec))
return nil
}
// Exit is action processor for "exit"
func Exit(action *recipe.Action, cmd *exec.Cmd) error {
if cmd == nil {
return nil
}
var err error
var start time.Time
var exitCode int
var timeout float64
exitCode, err = action.GetI(0)
if err != nil {
return err
}
if action.Has(1) {
timeout, err = action.GetF(1)
if err != nil {
return err
}
} else {
timeout = 60.0
}
start = time.Now()
for range time.NewTicker(25 * time.Millisecond).C {
if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
break
}
if time.Since(start) > timeutil.SecondsToDuration(timeout) {
return fmt.Errorf("Reached timeout (%g sec)", timeout)
}
}
status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus)
if !ok {
return fmt.Errorf("Can't get exit code from process state")
}
switch {
case !action.Negative && status.ExitStatus() != exitCode:
return fmt.Errorf("The process has exited with invalid exit code (%d ≠ %d)", status.ExitStatus(), exitCode)
case action.Negative && status.ExitStatus() == exitCode:
return fmt.Errorf("The process has exited with invalid exit code (%d)", status.ExitStatus())
}
return nil
}