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
|
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"testing"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v16/internal/bootstrap"
"gitlab.com/gitlab-org/gitaly/v16/internal/helper/perm"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper/testcfg"
)
// TestStolenPid tests for regressions in https://gitlab.com/gitlab-org/gitaly/issues/1661
func TestStolenPid(t *testing.T) {
t.Parallel()
tempDir := testhelper.TempDir(t)
pidFile, err := os.Create(filepath.Join(tempDir, "pidfile"))
require.NoError(t, err)
ctx, cancel := context.WithCancel(testhelper.Context(t))
cmd := exec.CommandContext(ctx, "tail", "-f")
require.NoError(t, cmd.Start())
defer func() {
cancel()
_ = cmd.Wait()
}()
_, err = pidFile.WriteString(strconv.Itoa(cmd.Process.Pid))
require.NoError(t, err)
require.NoError(t, pidFile.Close())
tail, err := findProcess(pidFile.Name())
require.NoError(t, err)
require.NotNil(t, tail)
require.Equal(t, cmd.Process.Pid, tail.Pid)
t.Run("stolen", func(t *testing.T) {
require.False(t, isExpectedProcess(tail, "/path/to/gitaly"))
})
t.Run("not stolen", func(t *testing.T) {
require.True(t, isExpectedProcess(tail, "/path/to/tail"))
})
}
func TestFindProcess(t *testing.T) {
t.Parallel()
t.Run("nonexistent PID file", func(t *testing.T) {
t.Parallel()
_, err := findProcess("does-not-exist")
require.True(t, os.IsNotExist(err))
})
t.Run("PID file with garbage", func(t *testing.T) {
t.Parallel()
path := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(path, []byte("garbage"), perm.SharedFile))
_, err := findProcess(path)
_, expectedErr := strconv.Atoi("garbage")
require.Equal(t, expectedErr, err)
})
t.Run("nonexistent process", func(t *testing.T) {
t.Parallel()
// The below PID can exist, but chances are sufficiently low to hopefully not matter
// in practice.
path := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(path, []byte("7777777"), perm.SharedFile))
// The process isn't alive, so we expect neither an error nor a process to be
// returned.
process, err := findProcess(path)
require.Nil(t, process)
require.Nil(t, err)
})
t.Run("running process", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
// The process will exit immediately, but that's not much of a problem given that
// `findProcess()` also works with zombies.
executable := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "noop"), []byte(
`#!/usr/bin/env bash
echo ready
`))
cmd := exec.CommandContext(ctx, executable)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
defer func() {
require.NoError(t, cmd.Wait())
}()
// Wait for the process to be ready such that we know it's started up successfully
// and is executing the bash shell.
_, err = stdout.Read(make([]byte, 10))
require.NoError(t, err)
path := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(path, []byte(strconv.FormatInt(int64(cmd.Process.Pid), 10)), perm.SharedFile))
process, err := findProcess(path)
require.NotNil(t, process)
require.Equal(t, cmd.Process.Pid, process.Pid)
require.Equal(t, nil, err)
})
}
func TestIsRecoverable(t *testing.T) {
t.Parallel()
_, numericError := strconv.Atoi("")
tests := []struct {
name string
err error
want bool
}{
{
name: "file doesn't exist",
err: os.ErrNotExist,
want: true,
},
{
name: "numeric error",
err: numericError,
want: true,
},
{
name: "generic error",
err: errors.New("generic error"),
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isRecoverable(tt.err); got != tt.want {
t.Errorf("isRecoverable() = %v, want %v", got, tt.want)
}
})
}
}
func TestReadPIDFile(t *testing.T) {
t.Parallel()
t.Run("nonexistent", func(t *testing.T) {
t.Parallel()
_, err := readPIDFile("does-not-exist")
require.True(t, os.IsNotExist(err))
})
t.Run("empty", func(t *testing.T) {
t.Parallel()
path := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(path, nil, perm.SharedFile))
_, err := readPIDFile(path)
_, expectedErr := strconv.Atoi("")
require.Equal(t, expectedErr, err)
})
t.Run("invalid contents", func(t *testing.T) {
t.Parallel()
path := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(path, []byte("invalid"), perm.SharedFile))
_, err := readPIDFile(path)
_, expectedErr := strconv.Atoi("invalid")
require.Equal(t, expectedErr, err)
})
t.Run("valid", func(t *testing.T) {
t.Parallel()
path := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(path, []byte("12345"), perm.SharedFile))
pid, err := readPIDFile(path)
require.NoError(t, err)
require.Equal(t, 12345, pid)
})
}
func TestIsExpectedProcess(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
executable := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "noop"), []byte(
`#!/usr/bin/env bash
echo ready
read wait_until_killed
`))
cmd := exec.CommandContext(ctx, executable)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
stdin, err := cmd.StdinPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
defer func() {
testhelper.MustClose(t, stdin)
require.Error(t, cmd.Wait())
}()
// Wait for the process to be ready such that we know it's started up successfully
// and is executing the bash shell.
_, err = stdout.Read(make([]byte, 10))
require.NoError(t, err)
require.False(t, isExpectedProcess(cmd.Process, "does not match"))
require.True(t, isExpectedProcess(cmd.Process, "bash"))
}
func TestIsProcessAlive(t *testing.T) {
t.Parallel()
t.Run("nonexistent process", func(t *testing.T) {
t.Parallel()
// And now let's check with a nonexistent process. FindProcess never returns an
// error on Unix systems even if the process doesn't exist, so this is fine.
process, err := os.FindProcess(77777777)
require.NoError(t, err)
require.False(t, isProcessAlive(process))
})
t.Run("existing process", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
executable := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "noop"), []byte(
`#!/usr/bin/env bash
echo ready
read wait_until_killed
`))
cmd := exec.CommandContext(ctx, executable)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
_, err = cmd.StdinPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
// Wait for the process to be ready such that we know it's started up successfully
// and is executing the bash shell.
_, err = stdout.Read(make([]byte, 10))
require.NoError(t, err)
t.Run("running", func(t *testing.T) {
require.True(t, isProcessAlive(cmd.Process))
})
t.Run("zombie", func(t *testing.T) {
// The process will be considered alive as long as it hasn't been reaped yet.
require.NoError(t, cmd.Process.Kill())
require.True(t, isProcessAlive(cmd.Process))
})
t.Run("reaped", func(t *testing.T) {
require.Error(t, cmd.Wait())
require.False(t, isProcessAlive(cmd.Process))
})
})
}
func TestRun(t *testing.T) {
t.Parallel()
binary := testcfg.BuildGitalyWrapper(t, testcfg.Build(t))
t.Run("missing arguments", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
output, err := exec.CommandContext(ctx, binary).CombinedOutput()
require.Error(t, err)
require.Contains(t, string(output), "usage: ")
})
t.Run("missing PID file envvar", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
output, err := exec.CommandContext(ctx, binary, "binary").CombinedOutput()
require.Error(t, err)
require.Contains(t, string(output), "missing pid file ENV variable")
})
t.Run("invalid executable", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
pidPath := filepath.Join(testhelper.TempDir(t), "pid")
cmd := exec.CommandContext(ctx, binary, "does-not-exist")
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", bootstrap.EnvPidFile, pidPath))
output, err := cmd.CombinedOutput()
require.Error(t, err)
require.Contains(t, string(output), "executable file not found in $PATH")
})
t.Run("adopting executable", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
script := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(
`#!/usr/bin/env bash
echo ready
read wait_until_closed
`))
scriptCmd := exec.CommandContext(ctx, script)
scriptStdout, err := scriptCmd.StdoutPipe()
require.NoError(t, err)
scriptStdin, err := scriptCmd.StdinPipe()
require.NoError(t, err)
require.NoError(t, scriptCmd.Start())
// Read the first byte such that we know the process has been spawned.
_, err = scriptStdout.Read(make([]byte, 10))
require.NoError(t, err)
// Write the PID of the running process into the PID file. As a result, it should
// get adopted by gitaly-wrapper, which means it wouldn't try to execute it anew.
pidPath := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(pidPath, []byte(strconv.FormatInt(int64(scriptCmd.Process.Pid), 10)), perm.SharedFile))
// Run gitaly-script with a binary path whose basename matches, but which ultimately
// doesn't exist. This proves that it doesn't try to execute the script again.
wrapperCmd := exec.CommandContext(ctx, binary, "/does/not/exist/bash")
wrapperCmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", bootstrap.EnvPidFile, pidPath))
wrapperStdout, err := wrapperCmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, wrapperCmd.Start())
// We're now waiting for gitaly-wrapper to adopt the running script.
reader := bufio.NewReader(wrapperStdout)
for _, expectedLine := range []string{
"Wrapper started",
"finding process",
"adopting a process",
} {
line, err := reader.ReadBytes('\n')
require.NoError(t, err, "reading expected line %q",
expectedLine)
require.Contains(t, string(line), expectedLine)
}
// The script has been adopted, so we can now close its stdin and thus cause it to
// exit.
testhelper.MustClose(t, scriptStdin)
require.Error(t, scriptCmd.Wait())
// As a result, the wrapper should also exit successfully.
require.NoError(t, wrapperCmd.Wait())
})
t.Run("spawning executable", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
script := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(
`#!/usr/bin/env bash
echo "I have been executed"
`))
pidPath := filepath.Join(testhelper.TempDir(t), "pid")
cmd := exec.CommandContext(ctx, binary, script)
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", bootstrap.EnvPidFile, pidPath))
output, err := cmd.CombinedOutput()
require.NoError(t, err)
require.Contains(t, string(output), "spawning a process")
require.Contains(t, string(output), "I have been executed")
require.NoFileExists(t, pidPath)
})
t.Run("spawning executable with missing process", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
script := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(
`#!/usr/bin/env bash
echo "I have been executed"
`))
pidPath := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(pidPath, []byte("12345"), perm.SharedFile))
cmd := exec.CommandContext(ctx, binary, script)
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", bootstrap.EnvPidFile, pidPath))
output, err := cmd.CombinedOutput()
require.NoError(t, err)
require.Contains(t, string(output), "spawning a process")
require.Contains(t, string(output), "I have been executed")
})
t.Run("spawning executable with zombie process", func(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
script := testhelper.WriteExecutable(t, filepath.Join(testhelper.TempDir(t), "script"), []byte(
`#!/usr/bin/env bash
echo "I have been executed"
`))
scriptCmd := exec.CommandContext(ctx, script)
scriptStdout, err := scriptCmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, scriptCmd.Start())
// Read until we get an EOF, which means that the script has terminated. It's now in
// a zombie state because we don't call `Wait()`.
_, err = io.ReadAll(scriptStdout)
require.NoError(t, err)
pidPath := filepath.Join(testhelper.TempDir(t), "pid")
require.NoError(t, os.WriteFile(pidPath, []byte(strconv.FormatInt(int64(scriptCmd.Process.Pid), 10)), perm.SharedFile))
cmd := exec.CommandContext(ctx, binary, script)
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", bootstrap.EnvPidFile, pidPath))
output, err := cmd.CombinedOutput()
require.NoError(t, err)
require.Contains(t, string(output), "spawning a process")
require.Contains(t, string(output), "I have been executed")
require.NoError(t, scriptCmd.Wait())
})
}
|