-
Notifications
You must be signed in to change notification settings - Fork 8
/
local_client.go
69 lines (58 loc) · 1.49 KB
/
local_client.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
package salt
import (
"context"
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
)
type LocalClientReturn struct {
Jid string `json:"jid"`
Ret interface{} `json:"ret"`
Retcode int `json:"retcode"`
}
type localClientResponse struct {
Return []map[string]LocalClientReturn `json:"return"`
}
func (c *Client) LocalClient(ctx context.Context, fun string, arg []string, opts ...RunOption) (map[string]LocalClientReturn, error) {
payload := commandRequest{
Client: LocalClient,
Target: "*",
Function: fun,
Arguments: arg,
TargetType: Glob,
FullReturn: true,
}
for _, opt := range opts {
opt(&payload)
}
data, err := c.post(ctx, "", payload)
if err != nil {
return nil, err
}
var resp localClientResponse
if err := json.Unmarshal(data, &resp); err != nil {
return nil, err
}
return resp.Return[0], nil
}
func (c *Client) LocalClientAsync(ctx context.Context, tgt, fun string, arg []string, opts ...RunOption) (string, error) {
payload := commandRequest{
Client: LocalAsyncClient,
Target: tgt,
Function: fun,
Arguments: arg,
TargetType: Glob,
}
for _, opt := range opts {
opt(&payload)
}
data, err := c.post(ctx, "", payload)
if err != nil {
return "", err
}
if v := gjson.GetBytes(data, "status"); v.Value() != nil && v.Int() != 200 {
return "", fmt.Errorf("failed to run async command, error: %s", gjson.GetBytes(data, "return").String())
}
jid := gjson.GetBytes(data, "return.0.jid")
return jid.String(), nil
}