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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
|
package command
import (
"bytes"
"context"
"fmt"
"io"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus"
grpcmwtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v16/internal/cgroups"
"gitlab.com/gitlab-org/gitaly/v16/internal/structerr"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper"
"gitlab.com/gitlab-org/gitaly/v16/proto/go/gitalypb"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/types/known/durationpb"
)
func TestNew_environment(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
extraVar := "FOOBAR=123456"
var buf bytes.Buffer
cmd, err := New(ctx, []string{"/usr/bin/env"}, WithStdout(&buf), WithEnvironment([]string{extraVar}))
require.NoError(t, err)
require.NoError(t, cmd.Wait())
require.Contains(t, strings.Split(buf.String(), "\n"), extraVar)
}
func TestNew_exportedEnvironment(t *testing.T) {
ctx := testhelper.Context(t)
for _, tc := range []struct {
key string
value string
}{
{
key: "HOME",
value: "/home/git",
},
{
key: "PATH",
value: "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin",
},
{
key: "LD_LIBRARY_PATH",
value: "/path/to/your/lib",
},
{
key: "TZ",
value: "foobar",
},
{
key: "GIT_TRACE",
value: "true",
},
{
key: "GIT_TRACE_PACK_ACCESS",
value: "true",
},
{
key: "GIT_TRACE_PACKET",
value: "true",
},
{
key: "GIT_TRACE_PERFORMANCE",
value: "true",
},
{
key: "GIT_TRACE_SETUP",
value: "true",
},
{
key: "all_proxy",
value: "http://localhost:4000",
},
{
key: "http_proxy",
value: "http://localhost:5000",
},
{
key: "HTTP_PROXY",
value: "http://localhost:6000",
},
{
key: "https_proxy",
value: "https://localhost:5000",
},
{
key: "HTTPS_PROXY",
value: "https://localhost:6000",
},
{
key: "no_proxy",
value: "https://excluded:5000",
},
{
key: "NO_PROXY",
value: "https://excluded:5000",
},
} {
t.Run(tc.key, func(t *testing.T) {
if tc.key == "LD_LIBRARY_PATH" && runtime.GOOS == "darwin" {
t.Skip("System Integrity Protection prevents using dynamic linker (dyld) environment variables on macOS. https://apple.co/2XDH4iC")
}
t.Setenv(tc.key, tc.value)
var buf bytes.Buffer
cmd, err := New(ctx, []string{"/usr/bin/env"}, WithStdout(&buf))
require.NoError(t, err)
require.NoError(t, cmd.Wait())
expectedEnv := fmt.Sprintf("%s=%s", tc.key, tc.value)
require.Contains(t, strings.Split(buf.String(), "\n"), expectedEnv)
})
}
}
func TestNew_unexportedEnv(t *testing.T) {
ctx := testhelper.Context(t)
unexportedEnvKey, unexportedEnvVal := "GITALY_UNEXPORTED_ENV", "foobar"
t.Setenv(unexportedEnvKey, unexportedEnvVal)
var buf bytes.Buffer
cmd, err := New(ctx, []string{"/usr/bin/env"}, WithStdout(&buf))
require.NoError(t, err)
require.NoError(t, cmd.Wait())
require.NotContains(t, strings.Split(buf.String(), "\n"), fmt.Sprintf("%s=%s", unexportedEnvKey, unexportedEnvVal))
}
func TestNew_dontSpawnWithCanceledContext(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(testhelper.Context(t))
cancel()
cmd, err := New(ctx, nil)
require.Equal(t, err, ctx.Err())
require.Nil(t, cmd)
}
func TestNew_rejectContextWithoutDone(t *testing.T) {
t.Parallel()
require.PanicsWithValue(t, "command spawned with context without Done() channel", func() {
_, err := New(testhelper.ContextWithoutCancel(), []string{"true"})
require.NoError(t, err)
})
}
func TestNew_spawnTimeout(t *testing.T) {
ctx := testhelper.Context(t)
defer func(ch chan struct{}, t time.Duration) {
spawnTokens = ch
spawnConfig.Timeout = t
}(spawnTokens, spawnConfig.Timeout)
// This unbuffered channel will behave like a full/blocked buffered channel.
spawnTokens = make(chan struct{})
// Speed up the test by lowering the timeout
spawnTimeout := 200 * time.Millisecond
spawnConfig.Timeout = spawnTimeout
tick := time.After(spawnTimeout / 2)
errCh := make(chan error)
go func() {
_, err := New(ctx, []string{"true"})
errCh <- err
}()
select {
case <-errCh:
require.FailNow(t, "expected spawning to be delayed")
case <-tick:
// This is the happy case: we expect spawning of the command to be delayed by up to
// 200ms until it finally times out.
}
// And after some time we expect that spawning of the command fails due to the configured
// timeout.
err := <-errCh
var structErr structerr.Error
require.ErrorAs(t, err, &structErr)
details := structErr.Details()
require.Len(t, details, 1)
limitErr, ok := details[0].(*gitalypb.LimitError)
require.True(t, ok)
testhelper.RequireGrpcCode(t, err, codes.ResourceExhausted)
require.Equal(t, "process spawn timed out after 200ms", limitErr.ErrorMessage)
require.Equal(t, durationpb.New(0), limitErr.RetryAfter)
}
func TestCommand_Wait_contextCancellationKillsCommand(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(testhelper.Context(t))
cmd, err := New(ctx, []string{"cat", "/dev/urandom"})
require.NoError(t, err)
// Read one byte to ensure the process is running.
n, err := cmd.Read(make([]byte, 1))
require.NoError(t, err)
require.Equal(t, 1, n)
cancel()
err = cmd.Wait()
require.Equal(t, err, fmt.Errorf("signal: terminated: %w", context.Canceled))
require.ErrorIs(t, err, context.Canceled)
}
func TestNew_setupStdin(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
stdin := "Test value"
var buf bytes.Buffer
cmd, err := New(ctx, []string{"cat"}, WithSetupStdin(), WithStdout(&buf))
require.NoError(t, err)
_, err = fmt.Fprintf(cmd, "%s", stdin)
require.NoError(t, err)
require.NoError(t, cmd.Wait())
require.Equal(t, stdin, buf.String())
}
func TestCommand_read(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
cmd, err := New(ctx, []string{"echo", "test value"})
require.NoError(t, err)
output, err := io.ReadAll(cmd)
require.NoError(t, err)
require.Equal(t, "test value\n", string(output))
require.NoError(t, cmd.Wait())
}
func TestNew_nulByteInArgument(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
cmd, err := New(ctx, []string{"sh", "-c", "hello\x00world"})
require.Equal(t, fmt.Errorf("detected null byte in command argument %q", "hello\x00world"), err)
require.Nil(t, cmd)
}
func TestNew_missingBinary(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
cmd, err := New(ctx, []string{"command-non-existent"})
require.EqualError(t, err, "starting process [command-non-existent]: exec: \"command-non-existent\": executable file not found in $PATH")
require.Nil(t, cmd)
}
func TestCommand_stderrLogging(t *testing.T) {
t.Parallel()
binaryPath := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(`#!/usr/bin/env bash
for i in {1..5}
do
echo 'hello world' 1>&2
done
exit 1
`))
logger, hook := test.NewNullLogger()
ctx := testhelper.Context(t)
ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger))
var stdout bytes.Buffer
cmd, err := New(ctx, []string{binaryPath}, WithStdout(&stdout))
require.NoError(t, err)
require.EqualError(t, cmd.Wait(), "exit status 1")
require.Empty(t, stdout.Bytes())
require.Equal(t, strings.Repeat("hello world\n", 5), hook.LastEntry().Message)
}
func TestCommand_stderrLoggingTruncation(t *testing.T) {
t.Parallel()
binaryPath := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(`#!/usr/bin/env bash
for i in {1..1000}
do
printf '%06d zzzzzzzzzz\n' $i >&2
done
exit 1
`))
logger, hook := test.NewNullLogger()
ctx := testhelper.Context(t)
ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger))
var stdout bytes.Buffer
cmd, err := New(ctx, []string{binaryPath}, WithStdout(&stdout))
require.NoError(t, err)
require.Error(t, cmd.Wait())
require.Empty(t, stdout.Bytes())
require.Len(t, hook.LastEntry().Message, maxStderrBytes)
}
func TestCommand_stderrLoggingWithNulBytes(t *testing.T) {
t.Parallel()
binaryPath := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(`#!/usr/bin/env bash
dd if=/dev/zero bs=1000 count=1000 status=none >&2
exit 1
`))
logger, hook := test.NewNullLogger()
ctx := testhelper.Context(t)
ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger))
var stdout bytes.Buffer
cmd, err := New(ctx, []string{binaryPath}, WithStdout(&stdout))
require.NoError(t, err)
require.Error(t, cmd.Wait())
require.Empty(t, stdout.Bytes())
require.Equal(t, strings.Repeat("\x00", maxStderrLineLength), hook.LastEntry().Message)
}
func TestCommand_stderrLoggingLongLine(t *testing.T) {
t.Parallel()
binaryPath := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(`#!/usr/bin/env bash
printf 'a%.0s' {1..8192} >&2
printf '\n' >&2
printf 'b%.0s' {1..8192} >&2
exit 1
`))
logger, hook := test.NewNullLogger()
ctx := testhelper.Context(t)
ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger))
var stdout bytes.Buffer
cmd, err := New(ctx, []string{binaryPath}, WithStdout(&stdout))
require.NoError(t, err)
require.Error(t, cmd.Wait())
require.Empty(t, stdout.Bytes())
require.Equal(t,
strings.Join([]string{
strings.Repeat("a", maxStderrLineLength),
strings.Repeat("b", maxStderrLineLength),
}, "\n"),
hook.LastEntry().Message,
)
}
func TestCommand_stderrLoggingMaxBytes(t *testing.T) {
t.Parallel()
binaryPath := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(`#!/usr/bin/env bash
# This script is used to test that a command writes at most maxBytes to stderr. It
# simulates the edge case where the logwriter has already written MaxStderrBytes-1
# (9999) bytes
# This edge case happens when 9999 bytes are written. To simulate this,
# stderr_max_bytes_edge_case has 4 lines of the following format:
#
# line1: 3333 bytes long
# line2: 3331 bytes
# line3: 3331 bytes
# line4: 1 byte
#
# The first 3 lines sum up to 9999 bytes written, since we write a 2-byte escaped
# "\n" for each \n we see. The 4th line can be any data.
printf 'a%.0s' {1..3333} >&2
printf '\n' >&2
printf 'a%.0s' {1..3331} >&2
printf '\n' >&2
printf 'a%.0s' {1..3331} >&2
printf '\na\n' >&2
exit 1
`))
logger, hook := test.NewNullLogger()
ctx := testhelper.Context(t)
ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger))
var stdout bytes.Buffer
cmd, err := New(ctx, []string{binaryPath}, WithStdout(&stdout))
require.NoError(t, err)
require.Error(t, cmd.Wait())
require.Empty(t, stdout.Bytes())
require.Len(t, hook.LastEntry().Message, maxStderrBytes)
}
type mockCgroupManager struct {
cgroups.Manager
path string
}
func (m mockCgroupManager) AddCommand(*exec.Cmd, ...cgroups.AddCommandOption) (string, error) {
return m.path, nil
}
func TestCommand_logMessage(t *testing.T) {
t.Parallel()
logger, hook := test.NewNullLogger()
logger.SetLevel(logrus.DebugLevel)
ctx := ctxlogrus.ToContext(testhelper.Context(t), logrus.NewEntry(logger))
cmd, err := New(ctx, []string{"echo", "hello world"},
WithCgroup(mockCgroupManager{
path: "/sys/fs/cgroup/1",
}, nil),
)
require.NoError(t, err)
require.NoError(t, cmd.Wait())
logEntry := hook.LastEntry()
assert.Equal(t, cmd.Pid(), logEntry.Data["pid"])
assert.Equal(t, []string{"echo", "hello world"}, logEntry.Data["args"])
assert.Equal(t, 0, logEntry.Data["command.exitCode"])
assert.Equal(t, "/sys/fs/cgroup/1", logEntry.Data["command.cgroup_path"])
}
func TestNew_commandSpawnTokenMetrics(t *testing.T) {
defer func(old func(time.Time) float64) {
getSpawnTokenAcquiringSeconds = old
}(getSpawnTokenAcquiringSeconds)
getSpawnTokenAcquiringSeconds = func(t time.Time) float64 {
return 1
}
spawnTokenAcquiringSeconds.Reset()
ctx := testhelper.Context(t)
tags := grpcmwtags.NewTags()
tags.Set("grpc.request.fullMethod", "/test.Service/TestRPC")
ctx = grpcmwtags.SetInContext(ctx, tags)
cmd, err := New(ctx, []string{"echo", "goodbye, cruel world."})
require.NoError(t, err)
require.NoError(t, cmd.Wait())
expectedMetrics := `# HELP gitaly_command_spawn_token_acquiring_seconds_total Sum of time spent waiting for a spawn token
# TYPE gitaly_command_spawn_token_acquiring_seconds_total counter
gitaly_command_spawn_token_acquiring_seconds_total{cmd="echo",git_version="",grpc_method="TestRPC",grpc_service="test.Service"} 1
`
require.NoError(
t,
testutil.CollectAndCompare(
spawnTokenAcquiringSeconds,
bytes.NewBufferString(expectedMetrics),
),
)
}
func TestCommand_withFinalizer(t *testing.T) {
t.Parallel()
t.Run("context cancellation runs finalizer", func(t *testing.T) {
ctx, cancel := context.WithCancel(testhelper.Context(t))
finalizerCh := make(chan struct{})
_, err := New(ctx, []string{"echo"}, WithFinalizer(func(context.Context, *Command) {
close(finalizerCh)
}))
require.NoError(t, err)
cancel()
<-finalizerCh
})
t.Run("Wait runs finalizer", func(t *testing.T) {
ctx := testhelper.Context(t)
finalizerCh := make(chan struct{})
cmd, err := New(ctx, []string{"echo"}, WithFinalizer(func(context.Context, *Command) {
close(finalizerCh)
}))
require.NoError(t, err)
require.NoError(t, cmd.Wait())
<-finalizerCh
})
t.Run("Wait runs multiple finalizers", func(t *testing.T) {
ctx := testhelper.Context(t)
wg := sync.WaitGroup{}
wg.Add(2)
cmd, err := New(
ctx,
[]string{"echo"},
WithFinalizer(func(context.Context, *Command) { wg.Done() }),
WithFinalizer(func(context.Context, *Command) { wg.Done() }),
)
require.NoError(t, err)
require.NoError(t, cmd.Wait())
wg.Wait()
})
t.Run("Wait runs finalizer with the latest context", func(t *testing.T) {
ctx, cancel := context.WithCancel(testhelper.Context(t))
//nolint:staticcheck
ctx = context.WithValue(ctx, "hello", "world")
_, err := New(ctx, []string{"echo"}, WithFinalizer(func(ctx context.Context, _ *Command) {
require.Equal(t, "world", ctx.Value("hello"))
}))
require.NoError(t, err)
cancel()
})
t.Run("process exit does not run finalizer", func(t *testing.T) {
ctx := testhelper.Context(t)
finalizerCh := make(chan struct{})
_, err := New(ctx, []string{"echo"}, WithFinalizer(func(context.Context, *Command) {
close(finalizerCh)
}))
require.NoError(t, err)
select {
case <-finalizerCh:
// Command finalizers should only be running when we have either explicitly
// called `Wait()` on the command, or when the context has been cancelled.
// Otherwise we may run into the case where finalizers have already been ran
// on the exited process even though we may still be busy handling the
// output of that command, which may result in weird races.
require.FailNow(t, "finalizer should not have been ran")
case <-time.After(50 * time.Millisecond):
}
})
}
|