forked from containerd/containerd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
223 lines (205 loc) · 6.2 KB
/
monitor.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
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package monitor
import (
"context"
"fmt"
"time"
"github.com/containerd/containerd"
containers "github.com/containerd/containerd/api/services/containers/v1"
diff "github.com/containerd/containerd/api/services/diff/v1"
images "github.com/containerd/containerd/api/services/images/v1"
namespacesapi "github.com/containerd/containerd/api/services/namespaces/v1"
tasks "github.com/containerd/containerd/api/services/tasks/v1"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/leases"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/plugin"
"github.com/containerd/containerd/runtime/restart"
"github.com/containerd/containerd/services"
"github.com/containerd/containerd/snapshots"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type duration struct {
time.Duration
}
func (d *duration) UnmarshalText(text []byte) error {
var err error
d.Duration, err = time.ParseDuration(string(text))
return err
}
func (d duration) MarshalText() ([]byte, error) {
return []byte(d.Duration.String()), nil
}
// Config for the restart monitor
type Config struct {
// Interval for how long to wait to check for state changes
Interval duration `toml:"interval"`
}
func init() {
plugin.Register(&plugin.Registration{
Type: plugin.InternalPlugin,
Requires: []plugin.Type{
plugin.ServicePlugin,
},
ID: "restart",
Config: &Config{
Interval: duration{
Duration: 10 * time.Second,
},
},
InitFn: func(ic *plugin.InitContext) (interface{}, error) {
opts, err := getServicesOpts(ic)
if err != nil {
return nil, err
}
client, err := containerd.New("", containerd.WithServices(opts...))
if err != nil {
return nil, err
}
m := &monitor{
client: client,
}
go m.run(ic.Config.(*Config).Interval.Duration)
return m, nil
},
})
}
// getServicesOpts get service options from plugin context.
func getServicesOpts(ic *plugin.InitContext) ([]containerd.ServicesOpt, error) {
plugins, err := ic.GetByType(plugin.ServicePlugin)
if err != nil {
return nil, errors.Wrap(err, "failed to get service plugin")
}
opts := []containerd.ServicesOpt{
containerd.WithEventService(ic.Events),
}
for s, fn := range map[string]func(interface{}) containerd.ServicesOpt{
services.ContentService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithContentStore(s.(content.Store))
},
services.ImagesService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithImageService(s.(images.ImagesClient))
},
services.SnapshotsService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithSnapshotters(s.(map[string]snapshots.Snapshotter))
},
services.ContainersService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithContainerService(s.(containers.ContainersClient))
},
services.TasksService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithTaskService(s.(tasks.TasksClient))
},
services.DiffService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithDiffService(s.(diff.DiffClient))
},
services.NamespacesService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithNamespaceService(s.(namespacesapi.NamespacesClient))
},
services.LeasesService: func(s interface{}) containerd.ServicesOpt {
return containerd.WithLeasesService(s.(leases.Manager))
},
} {
p := plugins[s]
if p == nil {
return nil, errors.Errorf("service %q not found", s)
}
i, err := p.Instance()
if err != nil {
return nil, errors.Wrapf(err, "failed to get instance of service %q", s)
}
if i == nil {
return nil, errors.Errorf("instance of service %q not found", s)
}
opts = append(opts, fn(i))
}
return opts, nil
}
type change interface {
apply(context.Context, *containerd.Client) error
}
type monitor struct {
client *containerd.Client
}
func (m *monitor) run(interval time.Duration) {
if interval == 0 {
interval = 10 * time.Second
}
for {
time.Sleep(interval)
if err := m.reconcile(context.Background()); err != nil {
logrus.WithError(err).Error("reconcile")
}
}
}
func (m *monitor) reconcile(ctx context.Context) error {
ns, err := m.client.NamespaceService().List(ctx)
if err != nil {
return err
}
for _, name := range ns {
ctx = namespaces.WithNamespace(ctx, name)
changes, err := m.monitor(ctx)
if err != nil {
logrus.WithError(err).Error("monitor for changes")
continue
}
for _, c := range changes {
if err := c.apply(ctx, m.client); err != nil {
logrus.WithError(err).Error("apply change")
}
}
}
return nil
}
func (m *monitor) monitor(ctx context.Context) ([]change, error) {
containers, err := m.client.Containers(ctx, fmt.Sprintf("labels.%q", restart.StatusLabel))
if err != nil {
return nil, err
}
var changes []change
for _, c := range containers {
labels, err := c.Labels(ctx)
if err != nil {
return nil, err
}
desiredStatus := containerd.ProcessStatus(labels[restart.StatusLabel])
if m.isSameStatus(ctx, desiredStatus, c) {
continue
}
switch desiredStatus {
case containerd.Running:
changes = append(changes, &startChange{
container: c,
logPath: labels[restart.LogPathLabel],
})
case containerd.Stopped:
changes = append(changes, &stopChange{
container: c,
})
}
}
return changes, nil
}
func (m *monitor) isSameStatus(ctx context.Context, desired containerd.ProcessStatus, container containerd.Container) bool {
task, err := container.Task(ctx, nil)
if err != nil {
return desired == containerd.Stopped
}
state, err := task.Status(ctx)
if err != nil {
return desired == containerd.Stopped
}
return desired == state.Status
}