forked from k0sproject/rig
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
291 lines (257 loc) · 7.61 KB
/
Copy pathexample_test.go
File metadata and controls
291 lines (257 loc) · 7.61 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
package rig_test
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
rig "github.com/k0sproject/rig/v2"
"github.com/k0sproject/rig/v2/cmd"
"github.com/k0sproject/rig/v2/initsystem"
rigos "github.com/k0sproject/rig/v2/os"
"github.com/k0sproject/rig/v2/packagemanager"
"github.com/k0sproject/rig/v2/remotefs"
"github.com/k0sproject/rig/v2/rigtest"
)
// ExampleNewClient_localhost demonstrates connecting to the local machine via
// the localhost protocol and running a command.
func ExampleNewClient_localhost() {
client, err := rig.NewClient(
rig.WithConnectionFactory(&rig.CompositeConfig{Localhost: true}),
)
if err != nil {
fmt.Println("create client:", err)
return
}
if err := client.Connect(context.Background()); err != nil {
fmt.Println("connect:", err)
return
}
defer client.Disconnect()
out, err := client.ExecOutput("echo hello")
if err != nil {
fmt.Println("exec:", err)
return
}
fmt.Println(out)
// Output:
// hello
}
// ExampleClient_Exec demonstrates running a simple command and checking its
// exit status.
func ExampleClient_Exec() {
runner := rigtest.NewMockRunner()
runner.AddCommand(rigtest.Equal("true"), func(_ *rigtest.A) error { return nil })
runner.AddCommand(rigtest.Equal("false"), func(_ *rigtest.A) error {
return errors.New("exit status 1")
})
if err := runner.Exec("true"); err != nil {
fmt.Println("unexpected error:", err)
return
}
fmt.Println("true: ok")
if err := runner.Exec("false"); err != nil {
fmt.Println("false: failed as expected")
}
// Output:
// true: ok
// false: failed as expected
}
// ExampleClient_ExecOutput demonstrates capturing stdout from a command.
func ExampleClient_ExecOutput() {
runner := rigtest.NewMockRunner()
runner.AddCommandOutput(rigtest.Equal("hostname"), "node-01.example.com\n")
out, err := runner.ExecOutput("hostname")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(out)
// Output:
// node-01.example.com
}
// ExampleClient_Proc demonstrates using cmd.Proc to attach stdin and stdout
// streams before starting a command — similar to configuring os/exec.Cmd.
func ExampleClient_Proc() {
runner := rigtest.NewMockRunner()
runner.AddCommand(rigtest.Equal("cat"), func(a *rigtest.A) error {
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(a.Stdin)
_, _ = fmt.Fprint(a.Stdout, buf.String())
return nil
})
var out strings.Builder
proc := runner.Proc("cat")
proc.Stdin = strings.NewReader("hello from proc\n")
proc.Stdout = &out
if err := proc.Run(context.Background()); err != nil {
fmt.Println(err)
return
}
fmt.Print(out.String())
// Output:
// hello from proc
}
// ExampleClient_Sudo demonstrates obtaining a sudo-decorated client and using
// it to run a privileged command.
func ExampleClient_Sudo() {
conn := rigtest.NewMockConnection()
// Accept the sudo probe ("sudo -n -- ... true").
conn.AddCommand(rigtest.HasSuffix("true'"), func(_ *rigtest.A) error { return nil })
// The actual command runs wrapped in sudo.
conn.AddCommand(rigtest.Contains("id"), func(a *rigtest.A) error {
fmt.Fprintln(a.Stdout, "uid=0(root)")
return nil
})
client, err := rig.NewClient(rig.WithConnection(conn))
if err != nil {
fmt.Println(err)
return
}
out, err := client.Sudo().ExecOutput("id")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(out)
// Output:
// uid=0(root)
}
// ExampleWithConfirmFunc demonstrates gating every command behind a
// confirmation callback. The callback receives the host and the redacted
// command; returning false aborts the command with [cmd.ErrCommandRejected]
// before it reaches the host. This applies to the client and every runner it
// derives (sudo, filesystem, services).
func ExampleWithConfirmFunc() {
conn := rigtest.NewMockConnection()
conn.AddCommand(rigtest.Match("."), func(_ *rigtest.A) error { return nil })
client, err := rig.NewClient(
rig.WithConnection(conn),
rig.WithConfirmFunc(func(_, command string) bool {
allowed := !strings.Contains(command, "rm -rf")
fmt.Printf("confirm %q -> %v\n", command, allowed)
return allowed
}),
)
if err != nil {
fmt.Println(err)
return
}
// An approved command runs normally.
if err := client.Exec("systemctl restart nginx"); err != nil {
fmt.Println("restart:", err)
}
// A rejected command never reaches the host.
if err := client.Exec("rm -rf /important"); errors.Is(err, cmd.ErrCommandRejected) {
fmt.Println("blocked")
}
// Output:
// confirm "systemctl restart nginx" -> true
// confirm "rm -rf /important" -> false
// blocked
}
// ExampleClient_FS demonstrates using Client.FS to read a file from the remote
// host via the fs.FS interface.
func ExampleClient_FS() {
conn := rigtest.NewMockConnection()
// PosixFS reads file content by running a cat-like command.
conn.AddCommandOutput(rigtest.Contains("cat"), "node-01\n")
client, err := rig.NewClient(rig.WithConnection(conn))
if err != nil {
fmt.Println(err)
return
}
data, err := client.FS().ReadFile("etc/hostname")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(strings.TrimSpace(string(data)))
// Output:
// node-01
}
// ExampleWithOSReleaseProvider demonstrates injecting a custom OS release
// provider that bypasses remote detection.
func ExampleWithOSReleaseProvider() {
conn := rigtest.NewMockConnection()
client, err := rig.NewClient(
rig.WithConnection(conn),
rig.WithOSReleaseProvider(func(_ cmd.SimpleRunner) (*rigos.Release, error) {
return &rigos.Release{ID: "alpine", Name: "Alpine Linux", Version: "3.18.0"}, nil
}),
)
if err != nil {
fmt.Println(err)
return
}
release, err := client.OS()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s %s\n", release.ID, release.Version)
// Output:
// alpine 3.18.0
}
// ExampleWithRemoteFSProvider demonstrates injecting a custom filesystem
// provider so that Client.FS returns a specific implementation.
func ExampleWithRemoteFSProvider() {
conn := rigtest.NewMockConnection()
client, err := rig.NewClient(
rig.WithConnection(conn),
rig.WithRemoteFSProvider(func(_ cmd.Runner) (remotefs.FS, error) {
return nil, errors.New("filesystem access disabled")
}),
)
if err != nil {
fmt.Println(err)
return
}
_, err = client.RemoteFSProvider.FS()
if err != nil {
fmt.Println("fs:", err)
}
// Output:
// fs: get filesystem: filesystem access disabled
}
// ExampleWithPackageManagerProvider demonstrates injecting a custom package
// manager so that Client.PackageManager returns a known implementation.
func ExampleWithPackageManagerProvider() {
conn := rigtest.NewMockConnection()
client, err := rig.NewClient(
rig.WithConnection(conn),
rig.WithPackageManagerProvider(func(_ cmd.ContextRunner) (packagemanager.PackageManager, error) {
return &packagemanager.NullPackageManager{Err: errors.New("no package manager")}, nil
}),
)
if err != nil {
fmt.Println(err)
return
}
pm := client.PackageManager()
if err := pm.Install(context.Background(), "curl"); err != nil {
fmt.Println("install:", err)
}
// Output:
// install: install packages (curl): no package manager
}
// ExampleWithInitSystemProvider demonstrates injecting a custom init system
// provider so that Client.ServiceManager returns a known result.
func ExampleWithInitSystemProvider() {
conn := rigtest.NewMockConnection()
client, err := rig.NewClient(
rig.WithConnection(conn),
rig.WithInitSystemProvider(func(_ cmd.ContextRunner) (initsystem.ServiceManager, error) {
return nil, errors.New("no init system detected")
}),
)
if err != nil {
fmt.Println(err)
return
}
if _, err := client.ServiceManager(); err != nil {
fmt.Println("service manager:", err)
}
// Output:
// service manager: get service manager: no init system detected
}