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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
|
//go:build !integration
// +build !integration
package kubernetes
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"sync"
"testing"
"time"
"github.com/jpillora/backoff"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
)
type log struct {
line string
offset int64
}
func (l log) String() string {
if l.offset < 0 {
return l.line
}
return fmt.Sprintf("%d %s", l.offset, l.line)
}
type brokenReaderError struct{}
func (e *brokenReaderError) Error() string {
return "broken"
}
type brokenReader struct {
err error
}
func newBrokenReader(err error) *brokenReader {
return &brokenReader{err: err}
}
func (b *brokenReader) Read([]byte) (n int, err error) {
return 0, b.err
}
func (b *brokenReader) Close() error {
return nil
}
func TestNewKubernetesLogProcessor(t *testing.T) {
client := new(kubernetes.Clientset)
testBackoff := new(backoff.Backoff)
logger := logrus.New()
clientConfig := new(restclient.Config)
p := newKubernetesLogProcessor(client, clientConfig, testBackoff, logger, kubernetesLogProcessorPodConfig{
namespace: "namespace",
pod: "pod",
container: "container",
logPath: "logPath",
})
assert.Equal(t, testBackoff, p.backoff)
assert.Equal(t, logger, p.logger)
require.NotNil(t, p.logStreamer)
k, ok := p.logStreamer.(*kubernetesLogStreamer)
assert.True(t, ok)
assert.Equal(t, "namespace", k.namespace)
assert.Equal(t, "pod", k.pod)
assert.Equal(t, "container", k.container)
assert.Equal(t, "namespace/pod/container:logPath", p.logStreamer.String())
}
func TestKubernetesLogStreamProviderLogStream(t *testing.T) {
abortErr := errors.New("abort")
namespace := "k8s_namespace"
pod := "k8s_pod_name"
container := "k8s_container_name"
logPath := "log_path"
client := mockKubernetesClientWithHost("", "", nil)
cfg := new(restclient.Config)
output := new(bytes.Buffer)
offset := 15
waitFileTimeout := time.Minute
executor := new(MockRemoteExecutor)
urlMatcher := mock.MatchedBy(func(url *url.URL) bool {
query := url.Query()
assert.Equal(t, container, query.Get("container"))
assert.Equal(t, "true", query.Get("stdout"))
assert.Equal(t, "true", query.Get("stderr"))
command := query["command"]
assert.Equal(t, []string{
"gitlab-runner-helper",
"read-logs",
"--path",
logPath,
"--offset",
strconv.Itoa(offset),
"--wait-file-timeout",
waitFileTimeout.String(),
}, command)
return true
})
executor.On("Execute", http.MethodPost, urlMatcher, cfg, nil, output, output, false).Return(abortErr)
s := kubernetesLogStreamer{}
s.client = client
s.clientConfig = cfg
s.executor = executor
s.namespace = namespace
s.pod = pod
s.container = container
s.logPath = logPath
s.waitLogFileTimeout = waitFileTimeout
err := s.Stream(int64(offset), output)
assert.ErrorIs(t, err, abortErr)
}
func TestReadLogsBrokenReader(t *testing.T) {
proc := new(kubernetesLogProcessor)
logger := logrus.New()
logger.SetLevel(logrus.DebugLevel)
proc.logger = logger
output := make(chan string)
err := proc.readLogs(context.Background(), newBrokenReader(new(brokenReaderError)), output)
assert.ErrorIs(t, err, new(brokenReaderError))
}
func TestProcessedOffsetSet(t *testing.T) {
proc := new(kubernetesLogProcessor)
logger := logrus.New()
logger.SetLevel(logrus.DebugLevel)
proc.logger = logger
ch := make(chan string)
go func() {
for range ch {
}
}()
logs := logsToReader(
log{line: "line 1", offset: 10},
log{line: "line 1", offset: 20},
)
err := proc.readLogs(context.Background(), logs, ch)
assert.NoError(t, err)
assert.Equal(t, int64(20), proc.logsOffset)
}
func logsToReader(logs ...log) io.Reader {
b := new(bytes.Buffer)
for _, l := range logs {
b.WriteString(l.String() + "\n")
}
return b
}
func TestParseLogs(t *testing.T) {
tests := map[string]struct {
line string
expectedOffset int64
expectedText string
}{
"with offset": {
line: "20 line",
expectedOffset: 20,
expectedText: "line",
},
"with no offset": {
line: "line",
expectedOffset: -1,
expectedText: "line",
},
"starts with space": {
line: " 20 line",
expectedOffset: -1,
expectedText: " 20 line",
},
"multiple spaces after offset": {
line: "20 line",
expectedOffset: 20,
expectedText: " line",
},
"empty log": {
line: "",
expectedOffset: -1,
expectedText: "",
},
}
for tn, tt := range tests {
t.Run(tn, func(t *testing.T) {
p := new(kubernetesLogProcessor)
offset, line := p.parseLogLine(tt.line)
assert.Equal(t, tt.expectedOffset, offset)
assert.Equal(t, tt.expectedText, line)
})
}
}
func TestListenReadLines(t *testing.T) {
expectedLines := []string{"line 1", "line 2"}
ctx, cancel := context.WithCancel(context.Background())
mockLogStreamer := newMockLogStreamer()
defer mockLogStreamer.AssertExpectations(t)
logs := []log{
{line: expectedLines[0], offset: 10},
{line: expectedLines[1], offset: 20},
}
var wg sync.WaitGroup
wg.Add(len(logs))
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
writeLogs(
args.Get(1).(io.Writer),
logs...,
)
// after writing the logs, this method must wait for them to be send out through the channel
// otherwise it will exit early and cancel the inner context responsible for receiving/sending
wg.Wait()
cancel()
}).
Return(nil).
Once()
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
t.Log(args)
assert.FailNow(t, "unexpected call to Stream()")
}).
Return(nil).
Maybe()
processor := newTestKubernetesLogProcessor()
processor.logStreamer = mockLogStreamer
ch, _ := processor.Process(ctx)
receivedLogs := make([]string, 0)
for log := range ch {
wg.Done()
receivedLogs = append(receivedLogs, log)
}
assert.Equal(t, expectedLines, receivedLogs)
}
func newMockLogStreamer() *mockLogStreamer {
s := new(mockLogStreamer)
s.On("String").Return("mockLogStreamer").Maybe()
return s
}
func writeLogs(to io.Writer, logs ...log) {
for _, l := range logs {
_, _ = to.Write([]byte(l.String() + "\n"))
}
}
func newTestKubernetesLogProcessor() *kubernetesLogProcessor {
logger := logrus.New()
logger.SetLevel(logrus.DebugLevel)
return &kubernetesLogProcessor{
logger: logger,
backoff: newDefaultMockBackoffCalculator(),
}
}
func newDefaultMockBackoffCalculator() *mockBackoffCalculator {
c := new(mockBackoffCalculator)
c.On("ForAttempt", mock.Anything).Return(50 * time.Millisecond).Maybe()
return c
}
func TestListenCancelContext(t *testing.T) {
mockLogStreamer := newMockLogStreamer()
defer mockLogStreamer.AssertExpectations(t)
ctx, _ := context.WithTimeout(context.Background(), 200*time.Millisecond)
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(mock.Arguments) {
<-ctx.Done()
}).
Return(io.EOF)
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
t.Log(args)
assert.FailNow(t, "unexpected call to Stream()")
}).
Return(nil).
Maybe()
processor := newTestKubernetesLogProcessor()
processor.logStreamer = mockLogStreamer
ch, errCh := processor.Process(ctx)
assert.NoError(t, drainProcessLogsChannels(ch, errCh), "No error should be returned!")
}
func TestAttachReconnectLogStream(t *testing.T) {
const expectedConnectCount = 5
ctx, cancel := context.WithCancel(context.Background())
mockLogStreamer := newMockLogStreamer()
defer mockLogStreamer.AssertExpectations(t)
var connects int
mockLogStreamer.
On("Stream", mock.Anything, mock.Anything).
Run(func(mock.Arguments) {
connects++
if connects == expectedConnectCount {
cancel()
}
}).
Return(io.EOF).
Times(expectedConnectCount)
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
t.Log(args)
assert.FailNow(t, "unexpected call to Stream()")
}).
Return(nil).
Maybe()
processor := newTestKubernetesLogProcessor()
processor.logStreamer = mockLogStreamer
ch, errCh := processor.Process(ctx)
_ = drainProcessLogsChannels(ch, errCh)
}
func TestAttachReconnectReadLogs(t *testing.T) {
const expectedConnectCount = 5
ctx, cancel := context.WithCancel(context.Background())
mockLogStreamer := newMockLogStreamer()
defer mockLogStreamer.AssertExpectations(t)
var connects int
mockLogStreamer.
On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
_ = args.Get(1).(*io.PipeWriter).Close()
connects++
if connects == expectedConnectCount {
cancel()
}
}).
Return(nil).
Times(expectedConnectCount)
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
t.Log(args)
assert.FailNow(t, "unexpected call to Stream()")
}).
Return(nil).
Maybe()
processor := newTestKubernetesLogProcessor()
processor.logStreamer = mockLogStreamer
ch, errCh := processor.Process(ctx)
assert.NoError(t, drainProcessLogsChannels(ch, errCh), "No error should be returned!")
}
func drainProcessLogsChannels(ch <-chan string, errCh <-chan error) error {
var firstErr error
for {
select {
case _, ok := <-ch:
if !ok {
return firstErr
}
case err, ok := <-errCh:
if !ok {
continue
}
if firstErr == nil {
firstErr = err
}
}
}
}
func TestAttachCorrectOffset(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
mockLogStreamer := newMockLogStreamer()
defer mockLogStreamer.AssertExpectations(t)
logs := []log{
{line: "line", offset: 10},
{line: "line", offset: 20},
}
var wg sync.WaitGroup
wg.Add(len(logs))
mockLogStreamer.
On("Stream", int64(0), mock.Anything).
Run(func(args mock.Arguments) {
writeLogs(
args.Get(1).(io.Writer),
logs...,
)
// after writing the logs, this method must wait for them to be send out through the channel
// otherwise it will exit early and cancel the inner context responsible for receiving/sending
wg.Wait()
}).
Return(nil).
Once()
mockLogStreamer.
On("Stream", int64(20), mock.Anything).
Run(func(mock.Arguments) {
cancel()
}).
Return(new(brokenReaderError)).
Once()
mockLogStreamer.On("Stream", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
t.Log(args)
assert.FailNow(t, "unexpected call to Stream()")
}).
Return(nil).
Maybe()
processor := newTestKubernetesLogProcessor()
processor.logStreamer = mockLogStreamer
ch, _ := processor.Process(ctx)
for range ch {
wg.Done()
}
}
func TestScanHandlesStreamError(t *testing.T) {
closedErr := errors.New("closed")
processor := new(kubernetesLogProcessor)
tests := map[string]struct {
readerError error
expectedError error
}{
"reader EOF": {
readerError: io.EOF,
// EOF is handled specially. Since it means that the stream
// reached its end, a nil is returned by scanner.Err()
expectedError: nil,
},
"custom error": {
readerError: closedErr,
expectedError: closedErr,
},
}
for tn, tt := range tests {
t.Run(tn, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
scanner, ch := processor.scan(ctx, newBrokenReader(tt.readerError))
line, more := <-ch
assert.Empty(t, line)
assert.False(t, more)
assert.ErrorIs(t, scanner.Err(), tt.expectedError)
})
}
}
func TestScanHandlesCancelledContext(t *testing.T) {
processor := new(kubernetesLogProcessor)
ctx, cancel := context.WithCancel(context.Background())
cancel()
scanner, ch := processor.scan(ctx, logsToReader(log{}))
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// Block the channel, so there's no consumers
time.Sleep(time.Second)
// Assert that the channel is closed
line, more := <-ch
assert.Empty(t, line)
assert.False(t, more)
// Assert that the scanner had no error
assert.Nil(t, scanner.Err())
}()
wg.Wait()
}
|