-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathshared_container_data.go
More file actions
268 lines (246 loc) · 9.35 KB
/
shared_container_data.go
File metadata and controls
268 lines (246 loc) · 9.35 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
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
package objectcache
import (
"fmt"
"iter"
"strings"
"time"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/utils-k8s-go/wlid"
"github.com/google/go-containerregistry/pkg/name"
"github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/instanceidhandler"
helpersv1 "github.com/kubescape/k8s-interface/instanceidhandler/v1/helpers"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/node-agent/pkg/utils"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation"
)
// UserDefinedNetworkMetadataKey is the pod label that references a
// user-provided NetworkNeighborhood resource by name (analogous to
// helpersv1.UserDefinedProfileMetadataKey for ApplicationProfiles).
const UserDefinedNetworkMetadataKey = "kubescape.io/user-defined-network"
type ContainerType int
const (
// ContainerType represents the type of container in a pod
Unknown = iota
Container
InitContainer
EphemeralContainer
)
type WatchedContainerStatus string
const (
// WatchedContainerStatus represents the status of a watched container
WatchedContainerStatusInitializing WatchedContainerStatus = helpersv1.Initializing
WatchedContainerStatusReady WatchedContainerStatus = helpersv1.Learning
WatchedContainerStatusCompleted WatchedContainerStatus = helpersv1.Completed
WatchedContainerStatusFailed WatchedContainerStatus = helpersv1.Failed
WatchedContainerStatusMissingRuntime WatchedContainerStatus = helpersv1.MissingRuntime
WatchedContainerStatusTooLarge WatchedContainerStatus = helpersv1.TooLarge
)
type WatchedContainerCompletionStatus string
const (
// WatchedContainerCompletionStatus represents the completion status of a watched container
WatchedContainerCompletionStatusPartial WatchedContainerCompletionStatus = helpersv1.Partial
WatchedContainerCompletionStatusFull WatchedContainerCompletionStatus = helpersv1.Full
)
func (c ContainerType) String() string {
return [...]string{"unknown", "containers", "initContainers", "ephemeralContainers"}[c]
}
type WatchedContainerData struct {
InstanceID instanceidhandler.IInstanceID
UpdateDataTicker *time.Ticker
SyncChannel chan error
AckChan chan struct{}
ParentResourceVersion string
ContainerID string
PodName string
Namespace string
ImageTag string
ImageID string
Wlid string
WorkloadUID string // UID of the top-level workload (from WLID)
ContainerType ContainerType
ContainerIndex int
ContainerInfos map[ContainerType][]ContainerInfo
NsMntId uint64
InitialDelayExpired bool
status WatchedContainerStatus
completionStatus WatchedContainerCompletionStatus
ParentWorkloadSelector *metav1.LabelSelector
SeccompProfilePath *string
PreRunningContainer bool
SeriesID string
PreviousReportTimestamp time.Time
CurrentReportTimestamp time.Time
UserDefinedProfile string
UserDefinedNetwork string
}
type ContainerInfo struct {
Name string
ImageTag string
ImageID string
}
func GetLabels(cloudMetadata *armotypes.CloudMetadata, watchedContainer *WatchedContainerData, stripContainer bool) map[string]string {
labels := watchedContainer.InstanceID.GetLabels()
for i := range labels {
if labels[i] == "" {
delete(labels, i)
} else if stripContainer && i == helpersv1.ContainerNameMetadataKey {
delete(labels, i)
} else {
switch i {
case helpersv1.KindMetadataKey:
labels[i] = wlid.GetKindFromWlid(watchedContainer.Wlid)
case helpersv1.NameMetadataKey:
labels[i] = wlid.GetNameFromWlid(watchedContainer.Wlid)
}
errs := validation.IsValidLabelValue(labels[i])
if len(errs) != 0 {
logger.L().Debug("GetLabels - label is not valid", helpers.String("label", labels[i]))
for j := range errs {
logger.L().Debug("GetLabels - label err description", helpers.String("Err: ", errs[j]))
}
delete(labels, i)
}
}
}
if watchedContainer.ParentResourceVersion != "" {
labels[helpersv1.ResourceVersionMetadataKey] = watchedContainer.ParentResourceVersion
}
if cloudMetadata != nil {
labels[helpersv1.HostTypeMetadataKey] = string(cloudMetadata.HostType)
if machineID := cloudMetadata.MachineID; machineID != "" {
labels[helpersv1.HostIDMetadataKey] = machineID
}
if clusterName := cloudMetadata.ClusterName; clusterName != "" {
labels[helpersv1.ClusterMetadataKey] = clusterName
}
if accountID := cloudMetadata.AccountID; accountID != "" {
labels[helpersv1.AWSAccountIDMetadataKey] = accountID
}
if region := cloudMetadata.Region; region != "" {
labels[helpersv1.RegionMetadataKey] = region
}
}
return labels
}
func (watchedContainer *WatchedContainerData) GetStatus() WatchedContainerStatus {
return watchedContainer.status
}
func (watchedContainer *WatchedContainerData) GetCompletionStatus() WatchedContainerCompletionStatus {
return watchedContainer.completionStatus
}
func (watchedContainer *WatchedContainerData) SetStatus(newStatus WatchedContainerStatus) {
if newStatus != watchedContainer.status {
watchedContainer.status = newStatus
}
}
func (watchedContainer *WatchedContainerData) SetCompletionStatus(newStatus WatchedContainerCompletionStatus) {
if newStatus != watchedContainer.completionStatus {
watchedContainer.completionStatus = newStatus
}
}
func (watchedContainer *WatchedContainerData) SetContainerInfo(wl workloadinterface.IWorkload, containerName string) error {
labels := wl.GetPodLabels()
// check for user defined profile
if userDefinedProfile, ok := labels[helpersv1.UserDefinedProfileMetadataKey]; ok {
if userDefinedProfile != "" {
logger.L().Info("container has a user defined profile",
helpers.String("profile", userDefinedProfile),
helpers.String("container", containerName),
helpers.String("workload", wl.GetName()))
watchedContainer.UserDefinedProfile = userDefinedProfile
}
}
// check for user defined network neighborhood
if userDefinedNetwork, ok := labels[UserDefinedNetworkMetadataKey]; ok {
if userDefinedNetwork != "" {
logger.L().Info("container has a user defined network neighborhood",
helpers.String("network", userDefinedNetwork),
helpers.String("container", containerName),
helpers.String("workload", wl.GetName()))
watchedContainer.UserDefinedNetwork = userDefinedNetwork
}
}
podSpec, err := wl.GetPodSpec()
if err != nil {
return fmt.Errorf("failed to get pod spec: %w", err)
}
podStatus, err := wl.GetPodStatus()
if err != nil {
return fmt.Errorf("failed to get pod status: %w", err)
}
// check pod level seccomp profile (might be overridden at container level)
if podSpec.SecurityContext != nil && podSpec.SecurityContext.SeccompProfile != nil {
watchedContainer.SeccompProfilePath = podSpec.SecurityContext.SeccompProfile.LocalhostProfile
}
// fill container infos
if watchedContainer.ContainerInfos == nil {
watchedContainer.ContainerInfos = make(map[ContainerType][]ContainerInfo)
}
checkContainers := func(containers iter.Seq2[int, v1.Container], containerStatuses []v1.ContainerStatus, containerType ContainerType) error {
statusesMap := utils.MapContainerStatuses(containerStatuses)
var containersInfo []ContainerInfo
for i, c := range containers {
normalizedImageName := normalizeImageName(c.Image)
containersInfo = append(containersInfo, ContainerInfo{
Name: c.Name,
ImageTag: normalizedImageName,
ImageID: statusesMap[c.Name].ImageID,
})
if c.Name == containerName {
watchedContainer.ContainerIndex = i
watchedContainer.ContainerType = containerType
if c.SecurityContext != nil && c.SecurityContext.SeccompProfile != nil {
watchedContainer.SeccompProfilePath = c.SecurityContext.SeccompProfile.LocalhostProfile
}
watchedContainer.ImageTag = normalizedImageName
watchedContainer.ImageID = statusesMap[c.Name].ImageID
}
}
watchedContainer.ContainerInfos[containerType] = containersInfo
return nil
}
// containers
if err := checkContainers(containersIterator(podSpec.Containers), podStatus.ContainerStatuses, Container); err != nil {
return err
}
// initContainers
if err := checkContainers(containersIterator(podSpec.InitContainers), podStatus.InitContainerStatuses, InitContainer); err != nil {
return err
}
// ephemeralContainers
if err := checkContainers(ephemeralContainersIterator(podSpec.EphemeralContainers), podStatus.EphemeralContainerStatuses, EphemeralContainer); err != nil {
return err
}
return nil
}
func containersIterator(c []v1.Container) iter.Seq2[int, v1.Container] {
return func(yield func(int, v1.Container) bool) {
for i := 0; i < len(c); i++ {
if !yield(i, c[i]) {
return
}
}
}
}
func ephemeralContainersIterator(c []v1.EphemeralContainer) iter.Seq2[int, v1.Container] {
return func(yield func(int, v1.Container) bool) {
for i := 0; i < len(c); i++ {
if !yield(i, v1.Container(c[i].EphemeralContainerCommon)) {
return
}
}
}
}
func normalizeImageName(image string) string {
ref, err := name.ParseReference(image)
if err != nil {
logger.L().Debug("failed to parse image reference", helpers.Error(err), helpers.String("image", image))
return image
}
// docker.io is parsed as index.docker.io
return strings.Replace(ref.Name(), "index.docker.io", "docker.io", 1)
}