/
container.go
307 lines (256 loc) · 8.09 KB
/
container.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
package v1
import (
"context"
"database/sql"
"errors"
"github.com/go-co-op/gocron"
"github.com/icinga/icinga-kubernetes/pkg/com"
"github.com/icinga/icinga-kubernetes/pkg/database"
"github.com/icinga/icinga-kubernetes/pkg/types"
"golang.org/x/sync/errgroup"
"io"
kcorev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
"sync"
"time"
)
var (
scheduler = gocron.NewScheduler(time.UTC)
containerLogs = make(map[string]ContainerLog)
containerLogsMu sync.Mutex
deletedPodIds = make(map[string]bool)
)
const (
MaxConcurrentJobs int = 60
ScheduleInterval = 5 * time.Minute
)
type ContainerMeta struct {
Id types.Binary `db:"id"`
PodId types.Binary `db:"pod_id"`
}
type Container struct {
ContainerMeta
Name string
Image string
CpuLimits int64
CpuRequests int64
MemoryLimits int64
MemoryRequests int64
State sql.NullString
StateDetails string
Ready types.Bool
Started types.Bool
RestartCount int32
Devices []ContainerDevice `db:"-"`
Mounts []ContainerMount `db:"-"`
}
func (c *Container) Relations() []database.Relation {
fk := database.WithForeignKey("container_id")
return []database.Relation{
database.HasMany(c.Devices, fk),
database.HasMany(c.Mounts, fk),
// Allow to automatically remove the logs when a container is deleted. Otherwise, we will have some dangling
// container logs in the database if the logs aren't deleted before removing the container, since any error
// can interrupt the deletion process of the logs when using the `on success` mechanism.
database.HasOne(ContainerLog{}, fk),
}
}
type ContainerDevice struct {
ContainerId types.Binary
PodId types.Binary
Name string
Path string
}
type ContainerMount struct {
ContainerId types.Binary
PodId types.Binary
VolumeName string
Path string
SubPath sql.NullString
ReadOnly types.Bool
}
type ContainerLogMeta struct {
Logs string `db:"logs"`
LastUpdate types.UnixMilli `db:"last_update"`
}
type ContainerLog struct {
PodId types.Binary `db:"pod_id"`
ContainerId types.Binary `db:"container_id"`
ContainerLogMeta
Namespace string `db:"-"`
PodName string `db:"-"`
ContainerName string `db:"-"`
}
// Upsert implements the database.Upserter interface.
func (cl *ContainerLog) Upsert() interface{} {
return cl.ContainerLogMeta
}
// syncContainerLogs fetches the logs from the kubernetes API for the given container and syncs to the database.
func (cl *ContainerLog) syncContainerLogs(ctx context.Context, clientset *kubernetes.Clientset, db *database.Database) error {
logOptions := &kcorev1.PodLogOptions{Container: cl.ContainerName}
if !cl.LastUpdate.Time().IsZero() {
sinceSeconds := int64(time.Since(cl.LastUpdate.Time()).Seconds())
logOptions.SinceSeconds = &sinceSeconds
}
req := clientset.CoreV1().Pods(cl.Namespace).GetLogs(cl.PodName, logOptions)
body, err := req.Stream(ctx)
if err != nil {
return err
}
defer func() { _ = body.Close() }()
logs, err := io.ReadAll(body)
if err != nil || len(logs) == 0 {
return err
}
cl.LastUpdate = types.UnixMilli(time.Now())
cl.Logs += string(logs)
entities := make(chan interface{}, 1)
entities <- cl
close(entities)
return db.UpsertStreamed(ctx, entities)
}
// SyncContainers consumes from the `upsertPods` and `deletePods` chans concurrently and schedules a job for
// each of the containers (drawn from `upsertPods`) that periodically syncs the container logs with the database.
// When pods are deleted, their IDs are streamed through the `deletePods` chan, and this fetches all the container
// IDs matching the respective pod ID from the database and initiates a container deletion stream that cleans up all
// container-related resources.
func SyncContainers(ctx context.Context, db *database.Database, g *errgroup.Group, upsertPods <-chan interface{}, deletePods <-chan interface{}) {
// Fetch all container logs from the database
err := make(chan error, 1)
err <- warmup(ctx, db)
close(err)
com.ErrgroupReceive(g, err)
// Use buffered channel here not to block the goroutines, as they can stream container ids
// from multiple pods concurrently.
containerIds := make(chan interface{}, db.Options.MaxPlaceholdersPerStatement)
g.Go(func() error {
defer runtime.HandleCrash()
return db.DeleteStreamed(ctx, &Container{}, containerIds, database.WithCascading())
})
g.Go(func() error {
defer runtime.HandleCrash()
defer close(containerIds)
scheduler.SetMaxConcurrentJobs(MaxConcurrentJobs, gocron.WaitMode)
scheduler.TagsUnique()
scheduler.StartAsync()
defer scheduler.Stop()
query := db.BuildSelectStmt(&Container{}, ContainerMeta{}) + ` WHERE pod_id=:pod_id`
for {
select {
case <-ctx.Done():
return ctx.Err()
case podId, ok := <-deletePods:
if !ok {
return nil
}
meta := &ContainerMeta{PodId: podId.([]byte)}
if _, ok := deletedPodIds[meta.PodId.String()]; ok {
// Due to the recursive relation resolution in the `DB#DeleteStreamed()` method, we may get the
// same pod ID multiple times since they all share the same `on success` handler.
break
}
deletedPodIds[meta.PodId.String()] = true
entities, errs := db.YieldAll(ctx, func() (interface{}, error) {
return &Container{}, nil
}, query, meta)
com.ErrgroupReceive(g, errs)
g.Go(func() error {
defer runtime.HandleCrash()
for {
select {
case <-ctx.Done():
return ctx.Err()
case e, ok := <-entities:
if !ok {
return nil
}
container := e.(*Container)
select {
case containerIds <- container.Id:
case <-ctx.Done():
return ctx.Err()
}
err := scheduler.RemoveByTag(container.Id.String())
if err != nil && !errors.Is(err, gocron.ErrJobNotFoundWithTag) {
return err
}
containerLogsMu.Lock()
delete(containerLogs, container.Id.String())
containerLogsMu.Unlock()
}
}
})
case e, ok := <-upsertPods:
if !ok {
return nil
}
pod := e.(*Pod)
delete(deletedPodIds, pod.Id.String())
for _, container := range pod.Containers {
_, err := scheduler.FindJobsByTag(container.Id.String())
if err != nil && !errors.Is(err, gocron.ErrJobNotFoundWithTag) {
return err
}
if container.Started.Bool && err != nil {
containerLog := &ContainerLog{
ContainerId: container.Id,
PodId: container.PodId,
ContainerName: container.Name,
Namespace: pod.Namespace,
PodName: pod.Name,
}
containerLogsMu.Lock()
if cl, ok := containerLogs[container.Id.String()]; ok {
containerLog.Logs = cl.Logs
}
containerLogsMu.Unlock()
scheduler.Every(ScheduleInterval.String()).Tag(container.Id.String())
_, err = scheduler.Do(containerLog.syncContainerLogs, ctx, pod.factory.clientset, db)
if err != nil {
return err
}
} else if err == nil {
err := scheduler.RemoveByTag(container.Id.String())
if err != nil {
return err
}
containerLogsMu.Lock()
delete(containerLogs, container.Id.String())
containerLogsMu.Unlock()
}
}
}
}
})
}
// warmup fetches all container logs from the database and caches them in the containerlogs variable.
func warmup(ctx context.Context, db *database.Database) error {
g, ctx := errgroup.WithContext(ctx)
entities, errs := db.YieldAll(ctx, func() (interface{}, error) {
return &ContainerLog{}, nil
}, db.BuildSelectStmt(ContainerLog{}, ContainerLog{}))
com.ErrgroupReceive(g, errs)
g.Go(func() error {
defer runtime.HandleCrash()
containerLogsMu.Lock()
defer containerLogsMu.Unlock()
for {
select {
case <-ctx.Done():
return ctx.Err()
case e, ok := <-entities:
if !ok {
return nil
}
containerLog := e.(*ContainerLog)
containerLogs[containerLog.ContainerId.String()] = *containerLog
}
}
})
return g.Wait()
}
// Assert that the Container type satisfies the interface compliance.
var (
_ database.HasRelations = (*Container)(nil)
)