-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
241 lines (196 loc) · 6.16 KB
/
client.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
package containers
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/castai/kvisor/pkg/cgroup"
"github.com/castai/kvisor/pkg/logging"
"github.com/castai/kvisor/pkg/metrics"
containerdContainers "github.com/containerd/containerd/containers"
"github.com/samber/lo"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
ErrContainerNotFound = errors.New("container not found")
)
type ContainerCreatedListener func(c *Container)
type ContainerDeletedListener func(c *Container)
type Container struct {
ID string
Name string
CgroupID uint64
PodNamespace string
PodUID string
PodName string
Cgroup *cgroup.Cgroup
PIDs []uint32
Err error
}
// Client is generic container client.
type Client struct {
log *logging.Logger
containerClient *containerClient
cgroupClient *cgroup.Client
containersByCgroup map[uint64]*Container
mu sync.RWMutex
containerCreatedListeners []ContainerCreatedListener
containerDeletedListeners []ContainerDeletedListener
listenerMu sync.RWMutex
}
func NewClient(log *logging.Logger, cgroupClient *cgroup.Client, containerdSock string) (*Client, error) {
contClient, err := newContainerClient(containerdSock)
if err != nil {
return nil, err
}
return &Client{
log: log.WithField("component", "cgroups"),
containerClient: contClient,
cgroupClient: cgroupClient,
containersByCgroup: map[uint64]*Container{},
}, nil
}
func (c *Client) ListContainers() []*Container {
c.mu.RLock()
defer c.mu.RUnlock()
return lo.Filter(lo.Values(c.containersByCgroup), func(item *Container, index int) bool {
return item.Err == nil && item.Cgroup != nil
})
}
func (c *Client) addContainerByCgroupID(ctx context.Context, cgroupID cgroup.ID) (cont *Container, rerrr error) {
defer func() {
if rerrr != nil {
// TODO: This is quick fix to prevent constant search for invalid containers.
// Check for some better error handling. For example container client network error could occur.
cont = &Container{
Err: rerrr,
}
c.mu.Lock()
c.containersByCgroup[cgroupID] = cont
c.mu.Unlock()
}
}()
cg, err := c.cgroupClient.GetCgroupForID(cgroupID)
// The found cgroup is not a container.
if err != nil || cg.ContainerID == "" {
return nil, ErrContainerNotFound
}
container, err := c.containerClient.client.ContainerService().Get(ctx, cg.ContainerID)
if err != nil {
return nil, err
}
return c.addContainerWithCgroup(container, cg)
}
func (c *Client) addContainerWithCgroup(container containerdContainers.Container, cg *cgroup.Cgroup) (cont *Container, rerrr error) {
podNamespace := container.Labels["io.kubernetes.pod.namespace"]
containerName := container.Labels["io.kubernetes.container.name"]
podName := container.Labels["io.kubernetes.pod.name"]
podID := container.Labels["io.kubernetes.pod.uid"]
// Only containerd is supported right now.
// TODO: We also allow docker here, but support only docker shim. If container type docker we assume that it's still uses containerd.
if cg.ContainerRuntime != cgroup.ContainerdRuntime && cg.ContainerRuntime != cgroup.DockerRuntime {
return nil, ErrContainerNotFound
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
pids, err := c.containerClient.getContainerPids(ctx, cg.ContainerID)
if err != nil {
if st, ok := status.FromError(err); ok && st.Code() == codes.NotFound {
return nil, ErrContainerNotFound
}
return nil, fmt.Errorf("get container pids: %w", err)
}
cont = &Container{
ID: cg.ContainerID,
Name: containerName,
CgroupID: cg.Id,
PodNamespace: podNamespace,
PodUID: podID,
PodName: podName,
Cgroup: cg,
PIDs: pids,
}
c.mu.Lock()
c.containersByCgroup[cg.Id] = cont
c.mu.Unlock()
c.log.Debugf("added container, id=%s pod=%s name=%s", container.ID, podName, containerName)
go c.fireContainerCreatedListeners(cont)
return cont, nil
}
func (c *Client) GetContainerForCgroup(ctx context.Context, cgroup uint64) (*Container, error) {
container, found, err := c.LookupContainerForCgroupInCache(cgroup)
if err != nil {
return nil, err
}
if !found {
metrics.AgentLoadContainerByCgroup.Inc()
return c.addContainerByCgroupID(ctx, cgroup)
}
return container, nil
}
func (c *Client) LookupContainerForCgroupInCache(cgroup uint64) (*Container, bool, error) {
c.mu.RLock()
container, found := c.containersByCgroup[cgroup]
c.mu.RUnlock()
if !found {
return nil, false, nil
}
if container.Err != nil {
return nil, true, container.Err
}
return container, true, nil
}
func (c *Client) CleanupCgroup(cgroup cgroup.ID) {
c.mu.Lock()
container := c.containersByCgroup[cgroup]
delete(c.containersByCgroup, cgroup)
c.mu.Unlock()
if container != nil {
c.fireContainerDeletedListeners(container)
}
}
func (c *Client) GetCgroupsInNamespace(namespace string) []uint64 {
c.mu.RLock()
defer c.mu.RUnlock()
var result []uint64
for cgroup, container := range c.containersByCgroup {
if container.PodNamespace == namespace {
result = append(result, cgroup)
}
}
return result
}
func (c *Client) RegisterContainerCreatedListener(l ContainerCreatedListener) {
c.listenerMu.Lock()
defer c.listenerMu.Unlock()
c.containerCreatedListeners = append(c.containerCreatedListeners, l)
}
func (c *Client) RegisterContainerDeletedListener(l ContainerDeletedListener) {
c.listenerMu.Lock()
defer c.listenerMu.Unlock()
c.containerDeletedListeners = append(c.containerDeletedListeners, l)
}
func (c *Client) fireContainerCreatedListeners(container *Container) {
c.listenerMu.RLock()
listeners := c.containerCreatedListeners
c.listenerMu.RUnlock()
for _, l := range listeners {
l(container)
}
}
func (c *Client) fireContainerDeletedListeners(container *Container) {
c.listenerMu.RLock()
listeners := c.containerDeletedListeners
c.listenerMu.RUnlock()
for _, l := range listeners {
l(container)
}
}
func (c *Client) GetCgroupCpuStats(cont *Container) (*cgroup.CPUStat, error) {
return cont.Cgroup.CpuStat()
}
func (c *Client) GetCgroupMemoryStats(cont *Container) (*cgroup.MemoryStat, error) {
return cont.Cgroup.MemoryStat()
}