跳至正文

Processes ​

Introduction ​

Laravel's process package runs external programs (such as ffmpeg to generate a video thumbnail or git during a deploy) and gives you their output and exit code. It stops a program that exceeds its timeout or whose request has ended, and lets you fake processes in tests so your suite never depends on binaries installed on the host machine.

Every process takes a context, which carries your application. A handler passes r, and a job, listener, or command passes the ctx it received. Because each process runs through your application, your tests' fakes can answer every one of them.

Running processes ​

To run a program and wait for it to finish, call process.Run with the context, the program, and its arguments. No shell runs in between, so the program receives each argument exactly as you wrote it. For example, this handler shows the commit that the server is running:

go
package deploys

import (
	"go.laravel.com/process"
	"go.laravel.com/web"
)

func Show(r *web.Request) *web.Response {
	res, err := process.Run(r, "git", "log", "-1", "--format=%h %s")
	if err != nil {
		return web.Fail(err)
	}

	return web.Text(res.Output)
}

Run returns a *process.Result, which describes how the process ended and what it wrote:

Field or methodWhat it holds
CommandThe command line, such as git log -1 '--format=%h %s'
ExitCodeThe exit code, or -1 when the process was killed
OutputStandard output
ErrorOutputStandard error
Successful()Whether the exit code is 0
Failed()Whether the process exited with another code, or was killed
EnsureSuccessful()A *process.ExitError unless the process succeeded

Output and ErrorOutput are strings, and a Go string may hold binary data as well as text. For a program that writes an image, convert the output with []byte(res.Output).

Failed processes ​

A non-zero exit code isn't an error by itself, because some programs use one during normal operation, such as grep exiting with 1 when no lines match. When a non-zero exit code should count as a failure, start with EnsureSuccessful, and Run returns a *process.ExitError instead of the *process.Result:

go
_, err := process.EnsureSuccessful().Run(ctx, "git", "pull")

You may also call res.EnsureSuccessful() on a result you already have. The error's message names the command and its exit code, followed by the end of the command's output, so your logs show why the process failed. Returning the error from a handler with web.Fail gives the user a 500 response.

Run returns these errors:

ErrorWhen
*process.StartErrorThe program couldn't start, such as when it isn't installed. errors.Is(err, exec.ErrNotFound) reports a missing program
*process.ExitErrorThe process failed, with EnsureSuccessful. Its Result field holds the *process.Result
*process.TimeoutErrorThe process ran past its timeout and was killed
An error that wraps the context's errorThe context ended first, such as when the client disconnected, and the process was killed. errors.Is(err, context.Canceled) reports it

To handle particular failures, such as a missing program or an image the program can't read, match the error with errors.Is and errors.As:

go
res, err := process.EnsureSuccessful().Run(r, "convert", path, "thumbnail.png")

var failed *process.ExitError
switch {
case errors.Is(err, exec.ErrNotFound):
	return web.Text("ImageMagick isn't installed.").WithStatus(http.StatusServiceUnavailable)
case errors.As(err, &failed) && failed.Result.ExitCode == 1:
	return web.Text("That image can't be converted.").WithStatus(http.StatusUnprocessableEntity)
case err != nil:
	return web.Fail(err)
}

Shell commands ​

Sometimes you need features that only a shell has, such as pipes, redirects, or globs. Shell runs a command line with the system's shell, which is sh -c on Unix and cmd /C on Windows:

go
res, err := process.Shell(r, "cat storage/logs/*.log | grep -c ERROR")

警告

Never build a shell command from user input. Shell(ctx, "convert "+name+" thumbnail.png") lets a crafted file name run commands of its own. Pass user input to Run as an argument instead, where it stays one argument whatever it contains.

Process options ​

To change how a process runs, such as its working directory, its time limit, its environment variables, or its standard input, chain options before you call Run. Each option returns a new runner and leaves the runner you called it on unchanged, so you may keep a runner as a template and run it again. For example, this importer runs the same script for users and then for posts:

go
importer := process.Dir("scripts").
	Timeout(2*time.Minute).
	Env("IMPORT_PATH", "storage/imports")

users, err := importer.Run(ctx, "bash", "import.sh", "users")
posts, err := importer.Run(ctx, "bash", "import.sh", "posts")

Working directory ​

Processes start in your application's base path. To run a process somewhere else, such as a frontend directory that holds your build scripts, pass the directory to Dir. Dir resolves a relative path against the base path, and you may also give an absolute path:

go
res, err := process.Dir("frontend").Run(ctx, "npm", "run", "build")

res, err = process.Dir("/tmp/builds").Run(ctx, "git", "status")

Timeouts ​

Laravel kills a process that runs longer than 60 seconds, and Run returns a *process.TimeoutError. You may change the limit with Timeout, or remove it with Timeout(0). You may also set IdleTimeout, which kills a process that goes too long without writing any output. An idle timeout catches a script that's stuck waiting on a network call, even when you allow the script to run for a long time:

go
res, err := process.Timeout(10*time.Minute).
	IdleTimeout(30*time.Second).
	Run(ctx, "bash", "import.sh")

The error's Result holds what the process wrote before Laravel killed it, and the error's Idle field is true when the process hit the idle timeout.

Environment variables ​

Processes inherit your application's environment, including the values from your .env file. A script may need a variable of its own, such as the directory to import from. Env sets a variable, replacing an inherited variable with the same name, and UnsetEnv removes an inherited variable:

go
res, err := process.Env("IMPORT_PATH", "storage/imports").
	Env("BATCH_SIZE", "500").
	UnsetEnv("AWS_SECRET_ACCESS_KEY").
	Run(ctx, "bash", "import.sh")

When you run a program you don't fully trust, keep secrets such as APP_KEY away from the program. WithoutInheritingEnv gives the process only the variables you set. Most programs need a PATH to find the programs they call, so set PATH too:

go
res, err := process.WithoutInheritingEnv().
	Env("NODE_ENV", "production").
	Env("PATH", "/usr/local/bin:/usr/bin:/bin").
	Run(ctx, "node", "render.js")

Input ​

Some programs read their input from standard input, such as wc counting lines. Input writes your text to the process's standard input, then closes it. Without Input, standard input is empty, so a program that reads it gets no input rather than waiting for some:

go
res, err := process.Input("Taylor\nAbigail\n").Run(r, "wc", "-l")

Reading output while a process runs ​

A long build or import may take minutes, and you may want to show its progress as it goes, such as in a console command. Give Stdout and Stderr a writer, and the runner copies the process's output to the writer as the process writes it. For example, this command shows a build's output in the terminal:

go
func (*Build) Run(ctx context.Context, c *console.Console) error {
	_, err := process.Stdout(c.Stdout()).
		Stderr(c.Stderr()).
		Timeout(10*time.Minute).
		EnsureSuccessful().
		Run(ctx, "npm", "run", "build")

	return err
}

The writer may be any io.Writer, such as a file. A write that fails doesn't stop the process, and Run returns the write's error once the process finishes.

When a process writes more output than you want to keep in memory, such as a database dump that you write to a file, Quietly leaves the output out of the *process.Result. The writers still receive all of the output:

go
dump, err := os.Create(config.From(ctx).App.StoragePath("backups", "database.sql"))
if err != nil {
	return err
}
defer dump.Close()

_, err = process.Stdout(dump).
	Quietly().
	Timeout(0).
	EnsureSuccessful().
	Run(ctx, "pg_dump", "forge")

Starting processes ​

Run waits for the process to finish. When your code has other work to do in the meantime, Start starts the process and returns a *process.Running right away. When you need the process's *process.Result, call Wait:

go
importing, err := process.Timeout(0).Start(ctx, "bash", "import.sh")
if err != nil {
	return err
}

// Do other work while the import runs...

res, err := importing.Wait()

The process stops when the context you give Start ends, so a process that a handler starts stops when the request ends. PID returns the operating system's process ID. Done returns a channel that Laravel closes once the process has finished, so you may wait for the process in a select. To start a shell command instead, use StartShell.

Reading output as it arrives ​

Sometimes you want to act on each piece of a started process's output while your code keeps control, such as to record an import's progress in your database as each line arrives. Chunks returns an iterator over the output, which you range over. The loop ends when the process closes its output, or when the context you give Chunks ends:

go
importing, err := process.Timeout(0).Start(ctx, "bash", "import.sh")
if err != nil {
	return err
}

for chunk := range importing.Chunks(ctx) {
	// Record the progress in chunk...
}

res, err := importing.Wait()

Chunks yields what the process wrote to standard output and standard error since it started, and a second loop picks up where the first one stopped. A chunk is whatever the process wrote at once, and may hold part of a line or several lines, so split the text on line breaks yourself when you need whole lines.

Waiting for output ​

Some programs keep running once they're ready, such as a server, and you need to know when the server is ready before you use it. WaitUntil passes each chunk of output to your function until the function returns true, such as for the chunk where the server says it's listening. WaitUntil returns true when a chunk matches, and false when the context ends first or the program exits before it's ready:

go
server, err := process.Timeout(0).Start(ctx, "node", "bootstrap/ssr/app.js")
if err != nil {
	return err
}

ready, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()

listening := func(chunk string) bool {
	return strings.Contains(chunk, "Listening")
}

if !server.WaitUntil(ready, listening) {
	_, err := server.Stop(time.Second)

	return errors.Join(errors.New("the SSR server didn't start"), err)
}

WaitUntil reads the same chunks as Chunks, from the moment the process started, so a server that says it's listening before you call WaitUntil still matches. Keep the text you match short, since longer text may be split across two chunks.

Signals and stopping ​

When you're done with a process that keeps running, such as the server above, stop it with Stop and a grace period. On Unix, Stop sends the process SIGTERM so it can clean up, and kills the process if it's still running when the grace period ends. On Windows, Stop kills the process at once. Like Wait, Stop returns the process's *process.Result:

go
res, err := server.Stop(10 * time.Second)

Some programs react to other signals, such as a server that reloads its configuration on SIGUSR2. On Unix, Signal sends any signal to the process:

go
err := server.Signal(syscall.SIGUSR2)

On Unix, signals, Stop, timeouts, and the end of the context also reach the programs that the process started, such as the programs that a shell command runs.

Concurrent processes ​

Sometimes you have several processes that don't depend on each other, such as two import scripts. Running them one after another takes as long as both together. Instead, pass a function for each process to task.Run, which runs the functions at once and returns when they've all returned. Each function runs its process with the ctx it receives:

go
var users, posts *process.Result
err := task.Run(ctx,
	func(ctx context.Context) (err error) {
		users, err = process.EnsureSuccessful().Run(ctx, "bash", "import-users.sh")
		return err
	},
	func(ctx context.Context) (err error) {
		posts, err = process.EnsureSuccessful().Run(ctx, "bash", "import-posts.sh")
		return err
	},
)
if err != nil {
	return err
}

When one process fails, task.Run ends the other function's context, so Laravel kills the other process rather than letting it run for nothing. task.Run then returns the failed process's error.

Testing ​

A test shouldn't depend on ffmpeg being installed or change your Git checkout. processtest.New installs a fake in your test's application, which records the application's processes instead of running them. By default, every process gets an empty, successful result:

go
package feature_test

import (
	"testing"

	"go.laravel.com/processtest"

	"app/tests"
)

func TestImportingRunsTheScript(t *testing.T) {
	client := tests.New(t)
	processes := processtest.New(client)

	client.Post("/imports", nil).AssertOK()

	processes.AssertRan("bash import.sh")
}

Each test's application gets its own fake, so tests that run in parallel never share one. The fake also answers processes that your test runs with client.Context(), such as when it calls a job's Handle directly.

说明

The scheduler runs its Exec and Shell tasks without the process package, so a process fake doesn't cover them.

Faking results ​

To fake the commands that match a pattern, pass the pattern to Respond, where * matches anything. A pattern matches the whole command line, such as git status for Run(ctx, "git", "status"), and the first pattern that matches answers the command. Each pattern takes one of three answers:

  • A processtest.Result gives the command that output and exit code.
  • processtest.NewSequence gives a different result each time the command runs, in turn.
  • processtest.AnswerFunc calls your function with the command, and the function returns the answer.

This fake uses all three:

go
processes := processtest.New(client).
	Respond("git rev-parse *", processtest.Result{Output: "a1b2c3\n"}).
	Respond("bash import.sh", processtest.Result{
		Output:      "Importing...\n",
		ErrorOutput: "No such file\n",
		ExitCode:    1,
	}).
	Respond("ls *", processtest.NewSequence(
		processtest.Result{Output: "first\n"},
		processtest.Result{Output: "second\n"},
	)).
	Respond("wc -l", processtest.AnswerFunc(func(cmd *process.Command) processtest.Answer {
		lines := strings.Count(cmd.Input, "\n")

		return processtest.Result{Output: fmt.Sprintf("%d\n", lines)}
	}))

A faked failure behaves like a real one, so EnsureSuccessful returns a *process.ExitError for the bash import.sh result above. Once a sequence runs out, the next run fails with process.ErrNotFaked, unless you give the sequence a final answer with WhenEmpty. When your code reads output with the Stdout and Stderr writers, Chunks, or WaitUntil, Laravel delivers faked output one line at a time.

Faking failures ​

Your code should also handle a process that never finishes or never starts. processtest.TimedOut makes the run fail with a *process.TimeoutError, whose Result holds the output you give TimedOut. processtest.FailedToStart makes the run fail with a *process.StartError that wraps the error you give it, such as exec.ErrNotFound for a program that isn't installed:

go
processes := processtest.New(client).
	Respond("ffmpeg *", processtest.TimedOut(processtest.Result{Output: "frame=120\n"})).
	Respond("convert *", processtest.FailedToStart(exec.ErrNotFound)).
	Respond("rsync *", processtest.NewSequence(
		processtest.TimedOut(processtest.Result{}),
		processtest.Result{},
	))

Putting a failure before a success in a sequence, as the rsync pattern does, lets you test code that retries.

Preventing stray processes ​

A process that no pattern matches gets an empty, successful result. To make sure your test fakes every process it expects, call PreventStrayProcesses. A process that no pattern matches then fails with process.ErrNotFaked, and the error names the command:

go
processes := processtest.New(client).
	Respond("git *", processtest.Result{}).
	PreventStrayProcesses()

Available assertions ​

Once your test has run your code, check which processes it ran. These assertions match exact command lines:

go
processes.AssertRan("git pull")
processes.AssertRanTimes("git pull", 1)
processes.AssertNotRan("git push")
processes.AssertRanInOrder("git pull", "bash import.sh")
processes.AssertNothingRan()

To check more than the command line, such as the timeout a process ran with, use AssertRanWhere. Its function receives each *process.Command, and the assertion passes when the function returns true for at least one command. A *process.Command holds the process's Program, Args, Script for a shell command, Dir, Timeout, IdleTimeout, the Env variables you set, and Input. Its String method returns the command line:

go
processes.AssertRanWhere(func(cmd *process.Command) bool {
	return cmd.String() == "bash import.sh" && cmd.Timeout == 5*time.Minute
})

A command line quotes an argument that contains spaces, as in convert 'my photo.png' thumbnail.png. To check arguments exactly as your code passed them, compare Program and Args:

go
processes.AssertRanWhere(func(cmd *process.Command) bool {
	return cmd.Program == "convert" &&
		slices.Equal(cmd.Args, []string{"my photo.png", "thumbnail.png"})
})

For other checks, Ran() returns every command that ran, in the order they ran.