-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
114 lines (93 loc) · 2.34 KB
/
main.go
File metadata and controls
114 lines (93 loc) · 2.34 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
package winrm
import (
"context"
"fmt"
"strings"
"time"
"github.com/masterzen/winrm"
"github.com/scorify/schema"
)
type Schema struct {
Server string `key:"server"`
Port int `key:"port" default:"5985"`
Username string `key:"username"`
Password string `key:"password"`
Command string `key:"command"`
ExpectedOutput string `key:"expected_output"`
HTTPS bool `key:"https"`
Insecure bool `key:"insecure"`
}
func Validate(config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
if conf.Server == "" {
return fmt.Errorf("server is required, got %q", conf.Server)
}
if conf.Port >= 65536 || conf.Port <= 0 {
return fmt.Errorf("valid port is required, got %d", conf.Port)
}
if conf.Username == "" {
return fmt.Errorf("username is required; got %q", conf.Username)
}
if conf.Command == "" {
return fmt.Errorf("command is required; got %q", conf.Command)
}
if conf.ExpectedOutput == "" {
return fmt.Errorf("expected_output is required; got %q", conf.ExpectedOutput)
}
return nil
}
func Run(ctx context.Context, config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
deadline, ok := ctx.Deadline()
if !ok {
return fmt.Errorf("failed to get context deadline")
}
timeout := time.Until(deadline)
errChan := make(chan error, 1)
go func() {
endpoint := winrm.NewEndpoint(
conf.Server,
conf.Port,
conf.HTTPS,
conf.Insecure,
[]byte{},
[]byte{},
[]byte{},
timeout,
)
defer close(errChan)
client, err := winrm.NewClient(endpoint, conf.Username, conf.Password)
if err != nil {
errChan <- fmt.Errorf("failed to create client: %v", err)
return
}
stdout, stderr, _, err := client.RunCmdWithContext(ctx, conf.Command)
if err != nil {
errChan <- fmt.Errorf("failed to run command: %v", err)
return
}
if stderr != "" {
errChan <- fmt.Errorf("command returned error: %s", stderr)
return
}
if strings.TrimSpace(stdout) != strings.TrimSpace(conf.ExpectedOutput) {
errChan <- fmt.Errorf("expected output does not match actual output: %q != %q", conf.ExpectedOutput, stdout)
return
}
errChan <- nil
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
return err
}
}