-
Notifications
You must be signed in to change notification settings - Fork 6
/
daemon_shutdown.go
110 lines (101 loc) · 2.4 KB
/
daemon_shutdown.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
package omcmd
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/opensvc/om3/core/client"
"github.com/opensvc/om3/core/clientcontext"
"github.com/opensvc/om3/core/nodeselector"
"github.com/opensvc/om3/daemon/api"
"github.com/opensvc/om3/util/hostname"
)
type (
CmdDaemonShutdown struct {
OptsGlobal
NodeSelector string
// Timeout is the maximum duration for shutdown
Timeout time.Duration
}
)
func (t *CmdDaemonShutdown) Run() error {
if t.Local {
t.NodeSelector = hostname.Hostname()
}
if !clientcontext.IsSet() && t.NodeSelector == "" {
t.NodeSelector = hostname.Hostname()
}
if t.NodeSelector == "" {
return fmt.Errorf("--node must be specified")
}
return t.doNodes()
}
func (t *CmdDaemonShutdown) doNodes() error {
c, err := client.New(client.WithURL(t.Server), client.WithTimeout(t.Timeout))
if err != nil {
return err
}
duration := t.Timeout.String()
params := api.PostDaemonShutdownParams{
Duration: &duration,
}
nodenames, err := nodeselector.New(t.NodeSelector, nodeselector.WithClient(c)).Expand()
if err != nil {
return err
}
errC := make(chan error)
ctx := context.Background()
needDoLocal := false
running := 0
for _, nodename := range nodenames {
if nodename == hostname.Hostname() {
needDoLocal = true
continue
}
running++
go func(nodename string) {
_, _ = fmt.Fprintf(os.Stderr, "shutting down daemon on remote %s\n", nodename)
err := t.doRemote(ctx, c, nodename, params)
errC <- err
}(nodename)
}
var (
errs error
)
for {
if running == 0 {
break
}
err := <-errC
errs = errors.Join(errs, err)
running--
}
// make sure the local host is shutdown last, as it relays the api calls
if needDoLocal {
_, _ = fmt.Fprintf(os.Stderr, "shutting down daemon on localhost\n")
err := t.doRemote(ctx, c, hostname.Hostname(), params)
errs = errors.Join(errs, err)
}
return errs
}
func (t *CmdDaemonShutdown) doRemote(ctx context.Context, c *client.T, nodename string, params api.PostDaemonShutdownParams) (err error) {
if resp, e := c.PostDaemonShutdownWithResponse(ctx, nodename, ¶ms); e != nil {
err = e
} else {
switch resp.StatusCode() {
case http.StatusOK:
case 401:
err = fmt.Errorf("%s", resp.JSON401)
case 403:
err = fmt.Errorf("%s", resp.JSON403)
case 500:
err = fmt.Errorf("%s", resp.JSON500)
}
}
if err != nil {
err = fmt.Errorf("daemon shutdown failed: %w", err)
}
return
}