-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.go
More file actions
237 lines (200 loc) · 5.67 KB
/
monitor.go
File metadata and controls
237 lines (200 loc) · 5.67 KB
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
package vm
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/threefoldtech/zosbase/pkg/gridtypes"
"github.com/threefoldtech/zosbase/pkg/rotate"
"github.com/threefoldtech/zosbase/pkg/stubs"
)
const (
failuresBeforeDestroy = 4
monitorEvery = 10 * time.Second
logrotateEvery = 10 * time.Minute
cleanupEvery = 10 * time.Minute
)
var (
// if the failures marker is set to permanent it means
// the monitoring will not try to restart this machine
// when it detects that it is down.
permanent = struct{}{}
rotator = rotate.NewRotator(
rotate.MaxSize(8*rotate.Megabytes),
rotate.TailSize(4*rotate.Megabytes),
)
)
func (m *Module) logrotate(ctx context.Context) error {
log.Debug().Msg("running log rotations for vms")
running, err := FindAll()
if err != nil {
return err
}
names := make([]string, 0, len(running))
for name := range running {
names = append(names, name)
}
return rotator.RotateAll(filepath.Join(m.root, logsDir), names...)
}
// Monitor start vms monitoring
func (m *Module) Monitor(ctx context.Context) {
go func() {
monTicker := time.NewTicker(monitorEvery)
defer monTicker.Stop()
logTicker := time.NewTicker(logrotateEvery)
defer logTicker.Stop()
cleanupTicker := time.NewTicker(cleanupEvery)
defer cleanupTicker.Stop()
for {
select {
case <-monTicker.C:
if err := m.monitor(ctx); err != nil {
log.Error().Err(err).Msg("failed to run monitoring")
}
case <-logTicker.C:
if err := m.logrotate(ctx); err != nil {
log.Error().Err(err).Msg("failed to run log rotation")
}
case <-cleanupTicker.C:
if err := m.cleanupCidata(); err != nil {
log.Error().Err(err).Msg("failed to run cleanup")
}
case <-ctx.Done():
return
}
}
}()
}
func (m *Module) monitor(ctx context.Context) error {
// this lock works with Run call to avoid
// monitoring trying to restart a machine that is not running yet.
m.lock.Lock()
defer m.lock.Unlock()
// list all machines available under `{root}/firecracker`
items, err := os.ReadDir(m.cfg)
if os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
running, err := FindAll()
if err != nil {
return err
}
for _, item := range items {
if item.IsDir() {
continue
}
id := item.Name()
if err := m.monitorID(ctx, running, id); err != nil {
log.Err(err).Str("id", id).Msg("failed to monitor machine")
}
// remove vm from running vms
delete(running, id)
}
// now we have running vms that shouldn't be running
// because they have no config.
for id, ps := range running {
log.Info().Str("id", id).Msg("machine is running but not configured")
_ = syscall.Kill(ps.Pid, syscall.SIGKILL)
}
return nil
}
func (m *Module) cleanupCidata() error {
m.lock.Lock()
defer m.lock.Unlock()
log.Debug().Msg("running cleanup for vms cidata")
running, err := FindAll()
if err != nil {
return err
}
dir := filepath.Join(m.root, cloudInitDir)
files, err := os.ReadDir(dir)
if os.IsNotExist(err) {
return nil
} else if err != nil {
return fmt.Errorf("failed to list directory '%s' files: %w", dir, err)
}
for _, file := range files {
name := file.Name()
if _, ok := running[name]; !ok {
_ = os.Remove(filepath.Join(dir, name))
continue
}
}
return nil
}
func (m *Module) monitorID(ctx context.Context, running map[string]Process, id string) error {
stub := stubs.NewProvisionStub(m.client)
log := log.With().Str("id", id).Logger()
// skip healthcheck vms
if strings.HasPrefix(id, "healthcheck-vm") {
return nil
}
if ps, ok := running[id]; ok {
state, exists, err := stub.GetWorkloadStatus(ctx, id)
if err != nil {
return errors.Wrapf(err, "failed to get workload status for vm:%s ", id)
}
if !exists || state.IsAny(gridtypes.StateDeleted, gridtypes.StateError) {
log.Debug().Str("name", id).Msg("deleting running vm with no active workload")
m.removeConfig(id)
_ = syscall.Kill(ps.Pid, syscall.SIGKILL)
}
return nil
}
// otherwise machine is not running. we need to check if we need to restart
// it
marker, ok := m.failures.Get(id)
if !ok {
// no previous value. so this is the first failure
m.failures.Set(id, int(0), cache.DefaultExpiration)
}
if marker == permanent {
// if the marker is permanent. it means that this vm
// is being deleted or not monitored. we don't need to take any more action here
// (don't try to restart or delete)
m.removeConfig(id)
return nil
}
count, err := m.failures.IncrementInt(id, 1)
if err != nil {
// this should never happen because we make sure value
// is set
return errors.Wrap(err, "failed to check number of failure for the vm")
}
var reason error
if count < failuresBeforeDestroy {
vm, err := MachineFromFile(m.configPath(id))
if err != nil {
return err
}
if vm.NoKeepAlive {
// if the permanent marker was not set, and we reach here it's possible that
// the vmd was restarted, hence the in-memory copy of this flag was gone. Hence
// we need to set it correctly, and just return
m.failures.Set(id, permanent, cache.NoExpiration)
return nil
}
log.Debug().Str("name", id).Msg("trying to restart the vm")
if _, err = vm.Run(ctx, m.socketPath(id), m.logsPath(id)); err != nil {
reason = m.withLogs(m.logsPath(id), err)
}
} else {
reason = fmt.Errorf("deleting vm due to so many crashes")
}
if reason != nil {
log.Debug().Err(reason).Msg("deleting vm due to restart error")
m.removeConfig(id)
if err := stub.DecommissionCached(ctx, id, reason.Error()); err != nil {
return errors.Wrapf(err, "failed to decommission reservation '%s'", id)
}
}
return nil
}