-
Notifications
You must be signed in to change notification settings - Fork 115
/
monit_job_supervisor.go
382 lines (316 loc) · 10 KB
/
monit_job_supervisor.go
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
package jobsupervisor
import (
"fmt"
"path"
"strings"
"time"
"github.com/pivotal-golang/clock"
"github.com/pivotal/go-smtpd/smtpd"
boshalert "github.com/cloudfoundry/bosh-agent/agent/alert"
boshmonit "github.com/cloudfoundry/bosh-agent/jobsupervisor/monit"
boshdir "github.com/cloudfoundry/bosh-agent/settings/directories"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
const monitJobSupervisorLogTag = "monitJobSupervisor"
type monitJobSupervisor struct {
fs boshsys.FileSystem
runner boshsys.CmdRunner
client boshmonit.Client
logger boshlog.Logger
dirProvider boshdir.Provider
jobFailuresServerPort int
reloadOptions MonitReloadOptions
timeService clock.Clock
}
type MonitReloadOptions struct {
// Number of times `monit reload` will be executed
MaxTries int
// Number of times monit incarnation will be checked
// for difference after executing `monit reload`
MaxCheckTries int
// Length of time between checking for incarnation difference
DelayBetweenCheckTries time.Duration
}
func NewMonitJobSupervisor(
fs boshsys.FileSystem,
runner boshsys.CmdRunner,
client boshmonit.Client,
logger boshlog.Logger,
dirProvider boshdir.Provider,
jobFailuresServerPort int,
reloadOptions MonitReloadOptions,
timeService clock.Clock,
) JobSupervisor {
return &monitJobSupervisor{
fs: fs,
runner: runner,
client: client,
logger: logger,
dirProvider: dirProvider,
jobFailuresServerPort: jobFailuresServerPort,
reloadOptions: reloadOptions,
timeService: timeService,
}
}
func (m monitJobSupervisor) Reload() error {
var currentIncarnation int
oldIncarnation, err := m.getIncarnation()
if err != nil {
return bosherr.WrapError(err, "Getting monit incarnation")
}
// Monit process could be started in the same second as `monit reload` runs
// so it's ideal for MaxCheckTries * DelayBetweenCheckTries to be greater than 1 sec
// because monit incarnation id is just a timestamp with 1 sec resolution.
for reloadI := 0; reloadI < m.reloadOptions.MaxTries; reloadI++ {
// Exit code or output cannot be trusted
_, _, _, err := m.runner.RunCommand("monit", "reload")
if err != nil {
m.logger.Error(monitJobSupervisorLogTag, "Failed to reload monit %s", err.Error())
}
for checkI := 0; checkI < m.reloadOptions.MaxCheckTries; checkI++ {
currentIncarnation, err = m.getIncarnation()
if err != nil {
return bosherr.WrapError(err, "Getting monit incarnation")
}
// Incarnation id can decrease or increase because
// monit uses time(...) and system time can be changed
if oldIncarnation != currentIncarnation {
return nil
}
m.logger.Debug(
monitJobSupervisorLogTag,
"Waiting for monit to reload: before=%d after=%d",
oldIncarnation, currentIncarnation,
)
time.Sleep(m.reloadOptions.DelayBetweenCheckTries)
}
}
return bosherr.Errorf(
"Failed to reload monit: before=%d after=%d",
oldIncarnation, currentIncarnation,
)
}
func (m monitJobSupervisor) Start() error {
services, err := m.client.ServicesInGroup("vcap")
if err != nil {
return bosherr.WrapError(err, "Getting vcap services")
}
for _, service := range services {
m.logger.Debug(monitJobSupervisorLogTag, "Starting service %s", service)
err = m.client.StartService(service)
if err != nil {
return bosherr.WrapErrorf(err, "Starting service %s", service)
}
}
err = m.fs.RemoveAll(m.stoppedFilePath())
if err != nil {
return bosherr.WrapError(err, "Removing stopped File")
}
return nil
}
func (m monitJobSupervisor) Stop() error {
services, err := m.client.ServicesInGroup("vcap")
if err != nil {
return bosherr.WrapError(err, "Getting vcap services")
}
for _, service := range services {
m.logger.Debug(monitJobSupervisorLogTag, "Stopping service %s", service)
err = m.client.StopService(service)
if err != nil {
return bosherr.WrapErrorf(err, "Stopping service %s", service)
}
}
err = m.fs.WriteFileString(m.stoppedFilePath(), "")
if err != nil {
return bosherr.WrapError(err, "Creating stopped File")
}
return nil
}
func (m monitJobSupervisor) StopAndWait() error {
timer := m.timeService.NewTimer(5 * time.Minute)
for {
services, err := m.checkServices()
if err != nil {
return err
}
pendingServices := m.filterServices(services, func(service boshmonit.Service) bool {
return service.Pending
})
if len(pendingServices) == 0 {
break
}
select {
case <-timer.C():
return bosherr.Errorf("Timed out waiting for services '%s' to no longer be pending after 5 minutes", strings.Join(pendingServices, ", "))
default:
}
m.timeService.Sleep(500 * time.Millisecond)
}
_, _, _, err := m.runner.RunCommand("monit", "stop", "-g", "vcap")
if err != nil {
stdout, stderr, _, summaryError := m.runner.RunCommand("monit", "summary")
if summaryError != nil {
m.logger.Error(monitJobSupervisorLogTag, "Failed to stop jobs: %s. Also failed to get monit summary: %s", err.Error(), summaryError.Error())
} else {
m.logger.Error(monitJobSupervisorLogTag, "Failed to stop jobs: %s. Current monit summary:\nstdout:\n%sstderr:\n%s", err.Error(), stdout, stderr)
}
return bosherr.WrapErrorf(err, "Stop all services")
}
err = m.fs.WriteFileString(m.stoppedFilePath(), "")
if err != nil {
return bosherr.WrapError(err, "Creating stopped File")
}
m.logger.Debug(monitJobSupervisorLogTag, "Waiting for services to stop")
for {
services, err := m.checkServices()
if err != nil {
return err
}
erroredServices := m.filterServices(services, func(service boshmonit.Service) bool {
return service.Errored
})
servicesToStop := m.filterServices(services, func(service boshmonit.Service) bool {
return service.Monitored || service.Pending
})
if len(erroredServices) > 0 {
return bosherr.Errorf("Stopping services '%v' errored", erroredServices)
}
if len(servicesToStop) == 0 {
m.logger.Debug(monitJobSupervisorLogTag, "Successfully stopped all services")
return nil
}
select {
case <-timer.C():
return bosherr.Errorf("Timed out waiting for services '%s' to stop after 5 minutes", strings.Join(servicesToStop, ", "))
default:
}
m.logger.Debug(monitJobSupervisorLogTag, "Waiting for '%v' to stop", servicesToStop)
m.timeService.Sleep(500 * time.Millisecond)
}
}
func (m monitJobSupervisor) Unmonitor() error {
services, err := m.client.ServicesInGroup("vcap")
if err != nil {
return bosherr.WrapError(err, "Getting vcap services")
}
for _, service := range services {
m.logger.Debug(monitJobSupervisorLogTag, "Unmonitoring service %s", service)
err := m.client.UnmonitorService(service)
if err != nil {
return bosherr.WrapErrorf(err, "Unmonitoring service %s", service)
}
}
return nil
}
func (m monitJobSupervisor) Status() (status string) {
status = "running"
m.logger.Debug(monitJobSupervisorLogTag, "Getting monit status")
monitStatus, err := m.client.Status()
if err != nil {
status = "unknown"
return
}
if m.fs.FileExists(m.stoppedFilePath()) {
status = "stopped"
} else {
services := monitStatus.ServicesInGroup("vcap")
for _, service := range services {
if service.Status == "starting" {
return "starting"
}
if !service.Monitored || service.Status != "running" {
status = "failing"
}
}
}
return
}
func (m monitJobSupervisor) Processes() (processes []Process, err error) {
processes = []Process{}
monitStatus, err := m.client.Status()
if err != nil {
return processes, bosherr.WrapError(err, "Getting service status")
}
for _, service := range monitStatus.ServicesInGroup("vcap") {
process := Process{
Name: service.Name,
State: service.Status,
Uptime: UptimeVitals{
Secs: service.Uptime,
},
Memory: MemoryVitals{
Kb: service.MemoryKilobytesTotal,
Percent: service.MemoryPercentTotal,
},
CPU: CPUVitals{
Total: service.CPUPercentTotal,
},
}
processes = append(processes, process)
}
return
}
func (m monitJobSupervisor) getIncarnation() (int, error) {
monitStatus, err := m.client.Status()
if err != nil {
return -1, err
}
return monitStatus.GetIncarnation()
}
func (m monitJobSupervisor) AddJob(jobName string, jobIndex int, configPath string) error {
targetFilename := fmt.Sprintf("%04d_%s.monitrc", jobIndex, jobName)
targetConfigPath := path.Join(m.dirProvider.MonitJobsDir(), targetFilename)
configContent, err := m.fs.ReadFile(configPath)
if err != nil {
return bosherr.WrapError(err, "Reading job config from file")
}
err = m.fs.WriteFile(targetConfigPath, configContent)
if err != nil {
return bosherr.WrapError(err, "Writing to job config file")
}
return nil
}
func (m monitJobSupervisor) RemoveAllJobs() error {
return m.fs.RemoveAll(m.dirProvider.MonitJobsDir())
}
func (m monitJobSupervisor) MonitorJobFailures(handler JobFailureHandler) (err error) {
alertHandler := func(smtpd.Connection, smtpd.MailAddress) (env smtpd.Envelope, err error) {
env = &alertEnvelope{
new(smtpd.BasicEnvelope),
handler,
new(boshalert.MonitAlert),
}
return
}
serv := &smtpd.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", m.jobFailuresServerPort),
OnNewMail: alertHandler,
}
err = serv.ListenAndServe()
if err != nil {
err = bosherr.WrapError(err, "Listen for SMTP")
}
return
}
func (m monitJobSupervisor) stoppedFilePath() string {
return path.Join(m.dirProvider.MonitDir(), "stopped")
}
func (m monitJobSupervisor) filterServices(services []boshmonit.Service, fn func(boshmonit.Service) bool) []string {
matchingServices := []string{}
for _, service := range services {
if fn(service) {
matchingServices = append(matchingServices, service.Name)
}
}
return matchingServices
}
func (m monitJobSupervisor) checkServices() ([]boshmonit.Service, error) {
monitStatus, err := m.client.Status()
if err != nil {
return nil, bosherr.WrapErrorf(err, "Getting monit status")
}
services := monitStatus.ServicesInGroup("vcap")
return services, nil
}