-
Notifications
You must be signed in to change notification settings - Fork 79
/
server_test.go
301 lines (270 loc) · 8.23 KB
/
server_test.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
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
292
293
294
295
296
297
298
299
300
301
package osquery
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"runtime/pprof"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/apache/thrift/lib/go/thrift"
"github.com/osquery/osquery-go/gen/osquery"
"github.com/osquery/osquery-go/plugin/logger"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Verify that an error in server.Start will return an error instead of deadlock.
func TestNoDeadlockOnError(t *testing.T) {
registry := make(map[string](map[string]OsqueryPlugin))
for reg := range validRegistryNames {
registry[reg] = make(map[string]OsqueryPlugin)
}
mut := sync.Mutex{}
mock := &MockExtensionManager{
RegisterExtensionFunc: func(info *osquery.InternalExtensionInfo, registry osquery.ExtensionRegistry) (*osquery.ExtensionStatus, error) {
mut.Lock()
defer mut.Unlock()
return nil, errors.New("boom!")
},
PingFunc: func() (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{}, nil
},
DeRegisterExtensionFunc: func(uuid osquery.ExtensionRouteUUID) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{}, nil
},
CloseFunc: func() {},
}
server := &ExtensionManagerServer{
serverClient: mock,
registry: registry,
serverClientShouldShutdown: true,
}
log := func(ctx context.Context, typ logger.LogType, logText string) error {
fmt.Printf("%s: %s\n", typ, logText)
return nil
}
server.RegisterPlugin(logger.NewPlugin("testLogger", log))
err := server.Run()
assert.Error(t, err)
mut.Lock()
defer mut.Unlock()
assert.True(t, mock.RegisterExtensionFuncInvoked)
}
// Ensure that the extension server will shutdown and return if the osquery
// instance it is talking to stops responding to pings.
func TestShutdownWhenPingFails(t *testing.T) {
tempPath, err := ioutil.TempFile("", "")
require.Nil(t, err)
defer os.Remove(tempPath.Name())
registry := make(map[string](map[string]OsqueryPlugin))
for reg := range validRegistryNames {
registry[reg] = make(map[string]OsqueryPlugin)
}
mock := &MockExtensionManager{
RegisterExtensionFunc: func(info *osquery.InternalExtensionInfo, registry osquery.ExtensionRegistry) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{}, nil
},
PingFunc: func() (*osquery.ExtensionStatus, error) {
// As if the socket was closed
return nil, syscall.EPIPE
},
DeRegisterExtensionFunc: func(uuid osquery.ExtensionRouteUUID) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{}, nil
},
CloseFunc: func() {},
}
server := &ExtensionManagerServer{
serverClient: mock,
registry: registry,
serverClientShouldShutdown: true,
pingInterval: 1 * time.Second,
sockPath: tempPath.Name(),
}
err = server.Run()
assert.Error(t, err)
assert.Contains(t, err.Error(), "broken pipe")
assert.True(t, mock.DeRegisterExtensionFuncInvoked)
assert.True(t, mock.CloseFuncInvoked)
}
// How many parallel tests to run (because sync issues do not occur on every
// run, this maximizes our chances of seeing any issue by quickly executing
// many runs of the test).
const parallelTestShutdownDeadlock = 20
func TestShutdownDeadlock(t *testing.T) {
for i := 0; i < parallelTestShutdownDeadlock; i++ {
i := i
t.Run("", func(t *testing.T) {
t.Parallel()
testShutdownDeadlock(t, i)
})
}
}
func testShutdownDeadlock(t *testing.T, uuid int) {
tempPath, err := ioutil.TempFile("", "")
require.Nil(t, err)
defer os.Remove(tempPath.Name())
retUUID := osquery.ExtensionRouteUUID(uuid)
mock := &MockExtensionManager{
RegisterExtensionFunc: func(info *osquery.InternalExtensionInfo, registry osquery.ExtensionRegistry) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{Code: 0, UUID: retUUID}, nil
},
DeRegisterExtensionFunc: func(uuid osquery.ExtensionRouteUUID) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{}, nil
},
CloseFunc: func() {},
}
server := ExtensionManagerServer{
serverClient: mock,
sockPath: tempPath.Name(),
timeout: defaultTimeout,
serverClientShouldShutdown: true,
}
var wait sync.WaitGroup
go func() {
// We do not wait for this routine to finish because thrift.TServer.Serve
// seems to sometimes hang after shutdowns. (This test is just testing
// the Shutdown doesn't hang.)
err := server.Start()
require.NoError(t, err)
}()
// Wait for server to be set up
server.waitStarted()
// Create a raw client to access the shutdown method that is not
// usually exposed.
listenPath := fmt.Sprintf("%s.%d", tempPath.Name(), retUUID)
addr, err := net.ResolveUnixAddr("unix", listenPath)
require.Nil(t, err)
timeout := 500 * time.Millisecond
opened := false
attempt := 0
var transport *thrift.TSocket
for !opened && attempt < 10 {
transport = thrift.NewTSocketFromAddrTimeout(addr, timeout, timeout)
err = transport.Open()
attempt++
if err != nil {
time.Sleep(1 * time.Second)
} else {
opened = true
}
}
require.NoError(t, err)
client := osquery.NewExtensionManagerClientFactory(transport,
thrift.NewTBinaryProtocolFactoryDefault())
// Simultaneously call shutdown through a request from the client and
// directly on the server object.
wait.Add(1)
go func() {
defer wait.Done()
client.Shutdown(context.Background())
}()
wait.Add(1)
go func() {
defer wait.Done()
err = server.Shutdown(context.Background())
require.NoError(t, err)
}()
// Track whether shutdown completed
completed := make(chan struct{})
go func() {
wait.Wait()
close(completed)
}()
// either indicate successful shutdown, or fatal the test because it
// hung
select {
case <-completed:
// Success. Do nothing.
case <-time.After(10 * time.Second):
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
t.Fatal("hung on shutdown")
}
}
func TestShutdownBasic(t *testing.T) {
dir := t.TempDir()
tempPath := func() string {
tmp, err := os.CreateTemp(dir, "")
require.NoError(t, err)
return tmp.Name()
}
retUUID := osquery.ExtensionRouteUUID(0)
mock := &MockExtensionManager{
RegisterExtensionFunc: func(info *osquery.InternalExtensionInfo, registry osquery.ExtensionRegistry) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{Code: 0, UUID: retUUID}, nil
},
DeRegisterExtensionFunc: func(uuid osquery.ExtensionRouteUUID) (*osquery.ExtensionStatus, error) {
return &osquery.ExtensionStatus{}, nil
},
CloseFunc: func() {},
}
for _, server := range []*ExtensionManagerServer{
// Create the extension manager without using NewExtensionManagerServer.
{serverClient: mock, sockPath: tempPath()},
// Create the extension manager using ExtensionManagerServer.
{serverClient: mock, sockPath: tempPath(), serverClientShouldShutdown: true},
} {
completed := make(chan struct{})
go func() {
err := server.Start()
require.NoError(t, err)
close(completed)
}()
server.waitStarted()
err := server.Shutdown(context.Background())
require.NoError(t, err)
// Test that server.Shutdown is idempotent.
err = server.Shutdown(context.Background())
require.NoError(t, err)
// Either indicate successful shutdown, or fatal the test because it
// hung
select {
case <-completed:
// Success. Do nothing.
case <-time.After(5 * time.Second):
t.Fatal("hung on shutdown")
}
}
}
func TestNewExtensionManagerServer(t *testing.T) {
t.Parallel()
type args struct {
name string
sockPath string
opts []ServerOption
}
tests := []struct {
name string
args args
want *ExtensionManagerServer
errContainsStr string
}{
{
name: "socket path too long",
args: args{
name: "socket_path_too_long",
sockPath: strings.Repeat("a", MaxSocketPathCharacters+1),
opts: []ServerOption{},
},
errContainsStr: "exceeded the maximum socket path character length",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := NewExtensionManagerServer(tt.args.name, tt.args.sockPath, tt.args.opts...)
if tt.errContainsStr != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tt.errContainsStr)
} else {
require.NoError(t, err)
require.NotNil(t, got)
}
})
}
}