summaryrefslogtreecommitdiff
path: root/internal/cli/stop/command.go
blob: 8b4b589f5432ed05247919d1384bc18dc639b2f0 (plain)
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
package stop

import (
	"log"
	"os"
	"strconv"
	"syscall"

	"github.com/roadrunner-server/errors"
	"github.com/spf13/cobra"
)

const (
	// sync with root.go
	pidFileName string = ".pid"
)

// NewCommand creates `serve` command.
func NewCommand(silent *bool) *cobra.Command {
	return &cobra.Command{
		Use:   "stop",
		Short: "Stop RoadRunner server",
		RunE: func(*cobra.Command, []string) error {
			const op = errors.Op("rr_stop")

			data, err := os.ReadFile(pidFileName)
			if err != nil {
				return errors.Errorf("%v, to create a .pid file, you must run RR with the following options: './rr serve -p'", err)
			}

			pid, err := strconv.Atoi(string(data))
			if err != nil {
				return errors.E(op, err)
			}

			process, err := os.FindProcess(pid)
			if err != nil {
				return errors.E(op, err)
			}

			if !*silent {
				log.Printf("stopping process with PID: %d", pid)
			}

			err = process.Signal(syscall.SIGTERM)
			if err != nil {
				return errors.E(op, err)
			}

			return nil
		},
	}
}