Welcome to mirror list, hosted at ThFree Co, Russian Federation.

supervisor.go « supervisor « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 72a0bd19ae5aee0a75d77b757013c58379559e49 (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
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
package supervisor

import (
	"fmt"
	"io"
	"os/exec"
	"sync"
	"time"

	"github.com/kelseyhightower/envconfig"
	"github.com/prometheus/client_golang/prometheus"
	log "github.com/sirupsen/logrus"
)

// Config holds configuration for the circuit breaker of the respawn loop.
type Config struct {
	// GITALY_SUPERVISOR_CRASH_THRESHOLD
	CrashThreshold int `split_words:"true" default:"5"`
	// GITALY_SUPERVISOR_CRASH_WAIT_TIME
	CrashWaitTime time.Duration `split_words:"true" default:"1m"`
	// GITALY_SUPERVISOR_CRASH_RESET_TIME
	CrashResetTime time.Duration `split_words:"true" default:"1m"`
}

var (
	startCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "gitaly_supervisor_starts_total",
			Help: "Number of starts of supervised processes.",
		},
		[]string{"name"},
	)

	config Config
)

func init() {
	envconfig.MustProcess("gitaly_supervisor", &config)
	prometheus.MustRegister(startCounter)
}

// Process represents a running process.
type Process struct {
	Name string

	memoryThreshold int
	events          chan<- Event
	healthCheck     func() error

	// Information to start the process
	env  []string
	args []string
	dir  string

	// Shutdown
	shutdown chan struct{}
	done     chan struct{}
	stopOnce sync.Once
}

// New creates a new proces instance.
func New(name string, env []string, args []string, dir string, memoryThreshold int, events chan<- Event, healthCheck func() error) (*Process, error) {
	if len(args) < 1 {
		return nil, fmt.Errorf("need at least one argument")
	}

	p := &Process{
		Name:            name,
		memoryThreshold: memoryThreshold,
		events:          events,
		healthCheck:     healthCheck,
		env:             env,
		args:            args,
		dir:             dir,
		shutdown:        make(chan struct{}),
		done:            make(chan struct{}),
	}

	go watch(p)
	return p, nil
}

func (p *Process) start(logger *log.Entry) (*exec.Cmd, error) {
	startCounter.WithLabelValues(p.Name).Inc()

	cmd := exec.Command(p.args[0], p.args[1:]...)
	cmd.Env = p.env
	cmd.Dir = p.dir
	cmd.Stdout = logger.WriterLevel(log.InfoLevel)
	cmd.Stderr = logger.WriterLevel(log.InfoLevel)
	return cmd, cmd.Start()
}

func (p *Process) notifyUp(pid int) {
	select {
	case p.events <- Event{Type: Up, Pid: pid}:
	case <-time.After(1 * time.Second):
		// Timeout
	}
}

func watch(p *Process) {
	// Count crashes to prevent a tight respawn loop. This is a 'circuit breaker'.
	crashes := 0

	logger := log.WithField("supervisor.args", p.args).WithField("supervisor.name", p.Name)

	// Use a buffered channel because we don't want to block the respawn loop
	// on the monitor goroutine.
	monitorChan := make(chan monitorProcess, config.CrashThreshold)
	monitorDone := make(chan struct{})
	go monitorRss(monitorChan, monitorDone, p.events, p.Name, p.memoryThreshold)

	healthShutdown := make(chan struct{})
	if p.healthCheck != nil {
		go monitorHealth(p.healthCheck, p.events, p.Name, healthShutdown)
	}

spawnLoop:
	for {
		if crashes >= config.CrashThreshold {
			logger.Warn("opening circuit breaker")
			select {
			case <-p.shutdown:
				break spawnLoop
			case <-time.After(config.CrashWaitTime):
				logger.Warn("closing circuit breaker")
				crashes = 0
			}
		}

		select {
		case <-p.shutdown:
			break spawnLoop
		default:
		}

		cmd, err := p.start(logger)
		if err != nil {
			crashes++
			logger.WithError(err).Error("start failed")
			continue
		}
		pid := cmd.Process.Pid
		go p.notifyUp(pid)
		logger.WithField("supervisor.pid", pid).Warn("spawned")

		waitCh := make(chan struct{})
		go func(cmd *exec.Cmd, waitCh chan struct{}) {
			err := cmd.Wait()
			close(waitCh)

			cmd.Stdout.(io.WriteCloser).Close()
			cmd.Stderr.(io.WriteCloser).Close()
			logger.WithError(err).Warn("exited")
		}(cmd, waitCh)

		monitorChan <- monitorProcess{pid: pid, wait: waitCh}

	waitLoop:
		for {
			select {
			case <-time.After(1 * time.Minute):
				// We repeat this idempotent notification because its delivery is not
				// guaranteed.
				go p.notifyUp(pid)
			case <-time.After(config.CrashResetTime):
				crashes = 0
			case <-waitCh:
				crashes++
				break waitLoop
			case <-p.shutdown:
				if cmd.Process != nil {
					cmd.Process.Kill()
				}
				<-waitCh
				break spawnLoop
			}
		}
	}

	close(healthShutdown)
	close(monitorChan)
	<-monitorDone
	close(p.done)
}

// Stop terminates the process.
func (p *Process) Stop() {
	if p == nil {
		return
	}

	p.stopOnce.Do(func() {
		close(p.shutdown)
	})

	select {
	case <-p.done:
	case <-time.After(1 * time.Second):
		// Don't wait for shutdown forever
	}
}