• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

noironetworks / aci-containers / 10023

06 Nov 2024 10:18AM UTC coverage: 69.589% (+0.04%) from 69.549%
10023

push

travis-pro

jeffinkottaram
debug logs

21 of 24 new or added lines in 1 file covered. (87.5%)

32 existing lines in 2 files now uncovered.

13199 of 18967 relevant lines covered (69.59%)

0.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.48
/pkg/hostagent/pods.go
1
// Copyright 2016 Cisco Systems, Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
// Handlers for pod updates.  Pods map to opflex endpoints
16

17
package hostagent
18

19
import (
20
        "context"
21
        "encoding/json"
22
        "fmt"
23
        "os"
24
        "path/filepath"
25
        "reflect"
26
        jruntime "runtime"
27
        "strings"
28
        "time"
29

30
        "github.com/sirupsen/logrus"
31

32
        aciv1 "github.com/noironetworks/aci-containers/pkg/gbpcrd/apis/acipolicy/v1"
33
        nodepodif "github.com/noironetworks/aci-containers/pkg/nodepodif/apis/acipolicy/v1"
34
        v1 "k8s.io/api/core/v1"
35
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
36
        "k8s.io/apimachinery/pkg/fields"
37
        "k8s.io/apimachinery/pkg/labels"
38
        "k8s.io/apimachinery/pkg/runtime"
39
        "k8s.io/apimachinery/pkg/watch"
40
        "k8s.io/client-go/kubernetes"
41
        "k8s.io/client-go/tools/cache"
42

43
        "k8s.io/kubernetes/pkg/controller"
44

45
        "github.com/google/uuid"
46
        "github.com/noironetworks/aci-containers/pkg/metadata"
47
        cnimeta "github.com/noironetworks/aci-containers/pkg/metadata"
48
        "github.com/noironetworks/aci-containers/pkg/util"
49
        apierrors "k8s.io/apimachinery/pkg/api/errors"
50
)
51

52
const NullMac = "null-mac"
53

54
type epTimeStamps struct {
55
        podCreationNotificationTimestamp   time.Time
56
        podUpdateNotificationsTimestamps   []time.Time
57
        epFileUpdateTimestamps             map[time.Time]string
58
        epFileCreateTimestamp              time.Time
59
        createNotifyToLastEpFileUpdateDiff time.Duration
60
        lastNotifyToLastEpFileUpdateDiff   time.Duration
61
        podCreationToLastEpFileUpdateDiff  time.Duration
62
        podCreationTimestamp               time.Time
63
        podStartTimestamp                  time.Time
64
}
65

66
type opflexEndpoint struct {
67
        Uuid string `json:"uuid"`
68

69
        EgPolicySpace string                 `json:"eg-policy-space,omitempty"`
70
        EndpointGroup string                 `json:"endpoint-group-name,omitempty"`
71
        SecurityGroup []metadata.OpflexGroup `json:"security-group,omitempty"`
72
        QosPolicy     metadata.OpflexGroup   `json:"qos-policy,omitempty"`
73

74
        IpAddress  []string `json:"ip,omitempty"`
75
        MacAddress string   `json:"mac,omitempty"`
76

77
        AccessIface       string `json:"access-interface,omitempty"`
78
        AccessUplinkIface string `json:"access-uplink-interface,omitempty"`
79
        IfaceName         string `json:"interface-name,omitempty"`
80

81
        Attributes        map[string]string `json:"attributes,omitempty"`
82
        SnatUuid          []string          `json:"snat-uuids,omitempty"`
83
        ServiceClusterIps []string          `json:"service-ip,omitempty"`
84
        registered        bool
85
}
86

87
func (agent *HostAgent) getPodIFName(ns, podName string) string {
1✔
88
        return fmt.Sprintf("%s.%s.%s", ns, podName, agent.vtepIP)
1✔
89
}
1✔
90

91
func (agent *HostAgent) EPRegAdd(ep *opflexEndpoint) bool {
1✔
92
        if agent.crdClient == nil {
2✔
93
                ep.registered = true
1✔
94
                return false // crd not used
1✔
95
        }
1✔
96

97
        // force the mask to /32
98
        ipRemEP := strings.Split(ep.IpAddress[0], "/")[0] + "/32"
×
99
        remEP := &aciv1.PodIF{
×
100
                Status: aciv1.PodIFStatus{
×
101
                        PodNS:       ep.Attributes["namespace"],
×
102
                        PodName:     ep.Attributes["vm-name"],
×
103
                        ContainerID: ep.Uuid,
×
104
                        MacAddr:     ep.MacAddress,
×
105
                        IPAddr:      ipRemEP,
×
106
                        EPG:         ep.EndpointGroup,
×
107
                        VTEP:        agent.vtepIP,
×
108
                        IFName:      ep.IfaceName,
×
109
                },
×
110
        }
×
111
        remEP.ObjectMeta.Name = agent.getPodIFName(ep.Attributes["namespace"], ep.Attributes["vm-name"])
×
112

×
113
        podif, err := agent.crdClient.PodIFs("kube-system").Get(context.TODO(), remEP.ObjectMeta.Name, metav1.GetOptions{})
×
114
        if err != nil {
×
115
                // create podif
×
116
                _, err := agent.crdClient.PodIFs("kube-system").Create(context.TODO(), remEP, metav1.CreateOptions{})
×
117
                if err != nil {
×
118
                        logrus.Errorf("Create error %v, podif: %+v", err, remEP)
×
119
                        return true
×
120
                }
×
121
        } else {
×
122
                // update it
×
123
                podif.Status = remEP.Status
×
124
                _, err := agent.crdClient.PodIFs("kube-system").Update(context.TODO(), podif, metav1.UpdateOptions{})
×
125
                if err != nil {
×
126
                        logrus.Errorf("Update error %v, podif: %+v", err, remEP)
×
127
                        return true
×
128
                }
×
129
        }
130
        ep.registered = true
×
131
        opflexEpLogger(agent.log, ep).Info("Updated podif")
×
132
        return false
×
133
}
134

135
func (agent *HostAgent) EPRegDelEP(name string) {
1✔
136
        if agent.crdClient == nil {
2✔
137
                return // crd not used
1✔
138
        }
1✔
139
        err := agent.crdClient.PodIFs("kube-system").Delete(context.TODO(), name, metav1.DeleteOptions{})
×
140
        if err != nil {
×
141
                agent.log.Errorf("Error %v, podif: %s", err, name)
×
142
                return
×
143
        }
×
144
        agent.log.Infof("podif: %s deleted", name)
×
145
}
146

147
func (agent *HostAgent) getNodePodIFName(nodeName string) string {
×
148
        return fmt.Sprintf("%s.%s", nodeName, agent.vtepIP)
×
149
}
×
150

151
func (agent *HostAgent) NodeEPRegAdd(nodePodIfEPs map[string]*opflexEndpoint) bool {
1✔
152
        if agent.nodePodIFClient == nil {
2✔
153
                agent.log.Debug("NodePodIF client or Kube clients are not intialized")
1✔
154
                return false // crd not used
1✔
155
        }
1✔
156

157
        var podifs []nodepodif.PodIF
×
158
        for _, ep := range nodePodIfEPs {
×
159
                ipRemEP := strings.Split(ep.IpAddress[0], "/")[0] + "/32"
×
160
                opflexEpLogger(agent.log, ep).Debug("ipRemEP")
×
161
                var podif nodepodif.PodIF
×
162
                podif.PodNS = ep.Attributes["namespace"]
×
163
                podif.PodName = ep.Attributes["vm-name"]
×
164
                podif.ContainerID = ep.Uuid
×
165
                podif.MacAddr = ep.MacAddress
×
166
                podif.IPAddr = ipRemEP
×
167
                // could change
×
168
                podif.EPG = ep.EndpointGroup
×
169
                podif.VTEP = agent.vtepIP
×
170
                podif.IFName = ep.IfaceName
×
171
                podifs = append(podifs, podif)
×
172
        }
×
173

174
        nodePodif, err := agent.nodePodIFClient.NodePodIFs("kube-system").Get(context.TODO(), agent.getNodePodIFName(agent.config.NodeName), metav1.GetOptions{})
×
175
        if err != nil {
×
176
                // create nodepodif
×
177
                if apierrors.IsNotFound(err) {
×
178
                        remEP := &nodepodif.NodePodIF{
×
179
                                ObjectMeta: metav1.ObjectMeta{
×
180
                                        Name:      agent.getNodePodIFName(agent.config.NodeName),
×
181
                                        Namespace: "kube-system",
×
182
                                },
×
183
                                Spec: nodepodif.NodePodIFSpec{
×
184
                                        PodIFs: podifs,
×
185
                                },
×
186
                        }
×
187

×
188
                        _, err := agent.nodePodIFClient.NodePodIFs("kube-system").Create(context.TODO(), remEP, metav1.CreateOptions{})
×
189
                        agent.log.Debugf("nodepodif: %s created for node", remEP.ObjectMeta.Name)
×
190
                        if err != nil {
×
191
                                logrus.Errorf("Create error %v, nodepodif: %+v", err, remEP)
×
192
                                return true
×
193
                        }
×
194
                }
195
        } else {
×
196
                // update nodepodif
×
197
                if !reflect.DeepEqual(nodePodif.Spec.PodIFs, podifs) {
×
198
                        nodePodif.Spec.PodIFs = podifs
×
199
                        _, err := agent.nodePodIFClient.NodePodIFs("kube-system").Update(context.TODO(), nodePodif, metav1.UpdateOptions{})
×
200
                        if err != nil {
×
201
                                logrus.Errorf("Update error %v, nodepodif: %+v", err, nodePodif)
×
202
                                return true
×
203
                        }
×
204
                }
205
        }
206
        if err == nil {
×
207
                agent.log.Debugf("nodepodif: %s updated for node", nodePodif.ObjectMeta.Name)
×
208
                return true
×
209
        }
×
210
        return false
×
211
}
212

213
func (agent *HostAgent) initPodInformerFromClient(
214
        kubeClient *kubernetes.Clientset) {
×
215
        agent.initPodInformerBase(
×
216
                &cache.ListWatch{
×
217
                        ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
×
218
                                options.FieldSelector =
×
219
                                        fields.Set{"spec.nodeName": agent.config.NodeName}.String()
×
220
                                obj, err := kubeClient.CoreV1().Pods(metav1.NamespaceAll).List(context.TODO(), options)
×
221
                                if err != nil {
×
222
                                        agent.log.Fatal("Failed to list Pods during initialization of PodInformer")
×
223
                                }
×
224
                                return obj, err
×
225
                        },
226
                        WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
×
227
                                options.FieldSelector =
×
228
                                        fields.Set{"spec.nodeName": agent.config.NodeName}.String()
×
229
                                obj, err := kubeClient.CoreV1().Pods(metav1.NamespaceAll).Watch(context.TODO(), options)
×
230
                                if err != nil {
×
231
                                        agent.log.Fatal("Failed to watch Pods during initialization of PodInformer")
×
232
                                }
×
233
                                return obj, err
×
234
                        },
235
                })
236

237
        agent.initControllerInformerBase(
×
238
                &cache.ListWatch{
×
239
                        ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
×
240
                                options.LabelSelector = labels.Set{"name": "aci-containers-controller"}.String()
×
241
                                obj, err := kubeClient.CoreV1().Pods(metav1.NamespaceAll).List(context.TODO(), options)
×
242
                                if err != nil {
×
243
                                        agent.log.Fatal("Failed to list Pods during initialization of ControllerInformer")
×
244
                                }
×
245
                                return obj, err
×
246
                        },
247
                        WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
×
248
                                options.LabelSelector = labels.Set{"name": "aci-containers-controller"}.String()
×
249
                                obj, err := kubeClient.CoreV1().Pods(metav1.NamespaceAll).Watch(context.TODO(), options)
×
250
                                if err != nil {
×
251
                                        agent.log.Fatal("Failed to watch Pods during initialization of ControllerInformer")
×
252
                                }
×
253
                                return obj, err
×
254
                        },
255
                })
256
}
257

258
func (agent *HostAgent) initPodInformerBase(listWatch *cache.ListWatch) {
1✔
259
        agent.podInformer = cache.NewSharedIndexInformer(
1✔
260
                listWatch,
1✔
261
                &v1.Pod{},
1✔
262
                controller.NoResyncPeriodFunc(),
1✔
263
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
1✔
264
        )
1✔
265
        agent.podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
1✔
266
                AddFunc: func(obj interface{}) {
2✔
267
                        fmt.Printf("\nJ: Processing add for pod %v", string(obj.(*v1.Pod).ObjectMeta.UID))
1✔
268
                        agent.initPodCreationNotificationTimestamp(obj.(*v1.Pod))
1✔
269
                        agent.podUpdated(obj)
1✔
270
                },
1✔
271
                UpdateFunc: func(_ interface{}, obj interface{}) {
1✔
272
                        fmt.Printf("\nJ: Processing update for pod %v", string(obj.(*v1.Pod).ObjectMeta.UID))
1✔
273
                        agent.updatePodNotifyTimeStamp(obj.(*v1.Pod))
1✔
274
                        agent.podUpdated(obj)
1✔
275
                },
1✔
276
                DeleteFunc: func(obj interface{}) {
1✔
277
                        fmt.Printf("\nJ: Processing delete for pod %v", string(obj.(*v1.Pod).ObjectMeta.UID))
1✔
278
                        agent.podDeleted(obj)
1✔
279
                },
1✔
280
        })
281
}
282

283
func (agent *HostAgent) initControllerInformerBase(listWatch *cache.ListWatch) {
1✔
284
        agent.controllerInformer = cache.NewSharedIndexInformer(
1✔
285
                listWatch,
1✔
286
                &v1.Pod{},
1✔
287
                controller.NoResyncPeriodFunc(),
1✔
288
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
1✔
289
        )
1✔
290
        agent.controllerInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
1✔
291
                AddFunc: func(obj interface{}) {
2✔
292
                        agent.updateGbpServerInfo(obj.(*v1.Pod))
1✔
293
                },
1✔
294
                UpdateFunc: func(_ interface{}, obj interface{}) {
1✔
295
                        agent.updateGbpServerInfo(obj.(*v1.Pod))
1✔
296
                },
1✔
297
                DeleteFunc: func(obj interface{}) {
1✔
298
                },
1✔
299
        })
300
}
301

302
func getEp(epfile string) (string, error) {
1✔
303
        raw, err := os.ReadFile(epfile)
1✔
304
        if err != nil {
2✔
305
                return "", err
1✔
306
        }
1✔
307
        return string(raw), err
1✔
308
}
309

310
func readEp(epfile string) (*opflexEndpoint, error) {
1✔
311
        epStr, err := getEp(epfile)
1✔
312
        if err != nil {
1✔
313
                return nil, err
×
314
        }
×
315

316
        ep := &opflexEndpoint{}
1✔
317
        err = json.Unmarshal([]byte(epStr), ep)
1✔
318
        return ep, err
1✔
319
}
320

321
func touchFileIfExists(epfile string) (bool, error) {
×
322
        var touch bool
×
323
        _, err := os.Stat(epfile)
×
324
        if err == nil {
×
325
                currentTime := time.Now().Local()
×
326
                er := os.Chtimes(epfile, currentTime, currentTime)
×
327
                if er != nil {
×
328
                        return touch, er
×
329
                }
×
330
                touch = true
×
331
        } else if !os.IsNotExist(err) {
×
332
                return touch, err
×
333
        }
×
334
        return touch, nil
×
335
}
336

337
func writeEp(epfile string, ep *opflexEndpoint) (bool, error) {
1✔
338
        newdata, err := json.MarshalIndent(ep, "", "  ")
1✔
339
        if err != nil {
1✔
340
                return true, err
×
341
        }
×
342
        existingdata, err := os.ReadFile(epfile)
1✔
343
        if err == nil && reflect.DeepEqual(existingdata, newdata) {
2✔
344
                return false, nil
1✔
345
        }
1✔
346
        err = os.WriteFile(epfile, newdata, 0644)
1✔
347
        return true, err
1✔
348
}
349

350
func podLogger(log *logrus.Logger, pod *v1.Pod) *logrus.Entry {
1✔
351
        return log.WithFields(logrus.Fields{
1✔
352
                "namespace": pod.ObjectMeta.Namespace,
1✔
353
                "name":      pod.ObjectMeta.Name,
1✔
354
                "node":      pod.Spec.NodeName,
1✔
355
        })
1✔
356
}
1✔
357

358
func opflexEpLogger(log *logrus.Logger, ep *opflexEndpoint) *logrus.Entry {
1✔
359
        return log.WithFields(logrus.Fields{
1✔
360
                "Uuid":      ep.Uuid,
1✔
361
                "name":      ep.Attributes["vm-name"],
1✔
362
                "namespace": ep.Attributes["namespace"],
1✔
363
        })
1✔
364
}
1✔
365

366
func (agent *HostAgent) FormEPFilePath(uuid string) string {
1✔
367
        return filepath.Join(agent.config.OpFlexEndpointDir, uuid+".ep")
1✔
368
}
1✔
369

370
func (agent *HostAgent) syncOpflexServer() bool {
1✔
371
        grpcAddr := fmt.Sprintf("%s:%d", agent.gbpServerIP, agent.config.GRPCPort)
1✔
372
        srvCfg := &OpflexServerConfig{GRPCAddress: grpcAddr}
1✔
373

1✔
374
        err := os.MkdirAll(filepath.Dir(agent.config.OpFlexServerConfigFile), os.ModeDir|0664)
1✔
375
        if err != nil {
1✔
376
                agent.log.Errorf("Failed to create directory: %s", filepath.Dir(agent.config.OpFlexServerConfigFile))
×
377
        }
×
378

379
        data, _ := json.MarshalIndent(srvCfg, "", "  ")
1✔
380
        err = os.WriteFile(agent.config.OpFlexServerConfigFile, data, 0644)
1✔
381
        if err != nil {
2✔
382
                agent.log.Errorf("Failed to create file: %s", agent.config.OpFlexServerConfigFile)
1✔
383
        } else {
1✔
384
                agent.log.Infof("Updated grpc addr to %s", grpcAddr)
×
385
        }
×
386

387
        return false
1✔
388
}
389

390
func (agent *HostAgent) syncEps() bool {
1✔
391
        if !agent.syncEnabled {
1✔
392
                return false
×
393
        }
×
394

395
        fmt.Printf("\nJ: Syncing Eps")
1✔
396

1✔
397
        agent.log.Debug("Syncing endpoints")
1✔
398
        agent.indexMutex.Lock()
1✔
399
        opflexEps := make(map[string][]*opflexEndpoint)
1✔
400
        for k, v := range agent.opflexEps {
2✔
401
                ep := []*opflexEndpoint{}
1✔
402
                for _, op := range v {
2✔
403
                        val := &opflexEndpoint{}
1✔
404
                        err := util.DeepCopyObj(op, val)
1✔
405
                        if err != nil {
1✔
406
                                continue
×
407
                        }
408
                        ep = append(ep, val)
1✔
409
                }
410
                opflexEps[k] = ep
1✔
411
        }
412
        agent.indexMutex.Unlock()
1✔
413

1✔
414
        files, err := os.ReadDir(agent.config.OpFlexEndpointDir)
1✔
415
        if err != nil {
1✔
416
                agent.log.WithFields(
×
417
                        logrus.Fields{"endpointDir": agent.config.OpFlexEndpointDir},
×
418
                ).Error("Could not read directory ", err)
×
419
                return true
×
420
        }
×
421

422
        needRetry := false
1✔
423
        seen := make(map[string]bool)
1✔
424
        nullMacFile := false
1✔
425
        nullMacCheck := agent.getEpFileName(agent.config.DefaultEg.Name)
1✔
426
        for _, f := range files {
2✔
427
                if !strings.HasSuffix(f.Name(), ".ep") ||
1✔
428
                        strings.Contains(f.Name(), "veth_host_ac") {
2✔
429
                        continue
1✔
430
                }
431

432
                if f.Name() == nullMacCheck {
2✔
433
                        nullMacFile = true
1✔
434
                        continue
1✔
435
                }
436

437
                epfile := filepath.Join(agent.config.OpFlexEndpointDir, f.Name())
1✔
438
                epidstr := f.Name()
1✔
439
                epidstr = epidstr[:len(epidstr)-3]
1✔
440
                epid := strings.Split(epidstr, "_")
1✔
441

1✔
442
                if len(epid) < 3 {
1✔
443
                        agent.log.Warn("Removing invalid endpoint:", f.Name())
×
444
                        os.Remove(epfile)
×
445
                        continue
×
446
                }
447
                poduuid := epid[0]
1✔
448
                contid := epid[1]
1✔
449
                contiface := epid[2]
1✔
450

1✔
451
                logger := agent.log.WithFields(
1✔
452
                        logrus.Fields{
1✔
453
                                "PodUuid":   poduuid,
1✔
454
                                "ContId":    contid,
1✔
455
                                "ContIFace": contiface,
1✔
456
                        },
1✔
457
                )
1✔
458

1✔
459
                existing, ok := opflexEps[poduuid]
1✔
460
                if ok {
2✔
461
                        for _, ep := range existing {
2✔
462
                                if ep.Uuid != epidstr {
2✔
463
                                        continue
1✔
464
                                }
465
                                ep.SnatUuid, err = agent.getSnatUuids(poduuid, epfile)
1✔
466
                                if err != nil {
1✔
467
                                        agent.log.Error("Error while getting snat uuids")
×
468
                                        needRetry = true
×
469
                                        continue
×
470
                                }
471
                                ep.ServiceClusterIps = agent.getServiceIPs(poduuid)
1✔
472

1✔
473
                                existingEp, err := readEp(epfile)
1✔
474
                                if err != nil {
2✔
475
                                        agent.log.Error("Error while reading epfile: ", epidstr)
1✔
476
                                        continue
1✔
477
                                }
478
                                changed_fields := compareOpflexEndpoints(existingEp, ep)
1✔
479
                                if changed_fields != "" {
2✔
480
                                        update_ts := time.Now().UTC()
1✔
481
                                        agent.indexMutex.Lock()
1✔
482
                                        agent.initPodNotifyTimeStamp(poduuid)
1✔
483
                                        agent.podNameToTimeStamps[poduuid].epFileUpdateTimestamps[update_ts] = changed_fields
1✔
484
                                        agent.podNameToTimeStamps[poduuid].createNotifyToLastEpFileUpdateDiff = update_ts.Sub(agent.podNameToTimeStamps[poduuid].podCreationNotificationTimestamp)
1✔
485
                                        agent.podNameToTimeStamps[poduuid].podCreationToLastEpFileUpdateDiff = update_ts.Sub(agent.podNameToTimeStamps[poduuid].podCreationTimestamp)
1✔
486
                                        if len(agent.podNameToTimeStamps[poduuid].podUpdateNotificationsTimestamps) > 0 {
2✔
487
                                                agent.podNameToTimeStamps[poduuid].lastNotifyToLastEpFileUpdateDiff = update_ts.Sub(agent.podNameToTimeStamps[poduuid].podUpdateNotificationsTimestamps[len(agent.podNameToTimeStamps[poduuid].podUpdateNotificationsTimestamps)-1])
1✔
488
                                        } else {
2✔
489
                                                agent.podNameToTimeStamps[poduuid].lastNotifyToLastEpFileUpdateDiff = update_ts.Sub(agent.podNameToTimeStamps[poduuid].podCreationNotificationTimestamp)
1✔
490
                                        }
1✔
491
                                        agent.indexMutex.Unlock()
1✔
492
                                }
493

494
                                agent.epfileMutex.Lock()
1✔
495
                                wrote, err := writeEp(epfile, ep)
1✔
496
                                agent.epfileMutex.Unlock()
1✔
497
                                if err != nil {
1✔
498
                                        opflexEpLogger(agent.log, ep).
×
499
                                                Error("Error writing EP file: ", err)
×
500
                                } else if wrote || !ep.registered {
2✔
501
                                        needRetry = agent.EPRegAdd(ep)
1✔
502
                                }
1✔
503

504
                                if wrote && err == nil {
2✔
505
                                        agent.indexMutex.Lock()
1✔
506
                                        agent.log.Debugf("ep file updated for pod: %s, Timestamps: {podCreatationNoticationTimestamp=%s, "+
1✔
507
                                                "podUpdateNotificationsTimestamps=[%s], epFileUpdateTimestamps=[%s], epFileCreateTimestamp=%s, "+
1✔
508
                                                "createNotifyToLastEpFileUpdateDiff=%s, lastNotifyToLastEpFileUpdateDiff=%s, "+
1✔
509
                                                "podCreationToLastEpFileUpdateDiff=%s, podCreationTimestamp=%s, "+
1✔
510
                                                "podStartTimestamp=%s}", ep.Attributes["vm-name"],
1✔
511
                                                agent.podNameToTimeStamps[poduuid].podCreationNotificationTimestamp.Format("2006-01-02T15:04:05Z"),
1✔
512
                                                formatTimestamps(agent.podNameToTimeStamps[poduuid].podUpdateNotificationsTimestamps),
1✔
513
                                                formatMapTimestamps(agent.podNameToTimeStamps[poduuid].epFileUpdateTimestamps),
1✔
514
                                                agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Format("2006-01-02T15:04:05Z"),
1✔
515
                                                normalizeToMinutes(agent.podNameToTimeStamps[poduuid].createNotifyToLastEpFileUpdateDiff),
1✔
516
                                                normalizeToMinutes(agent.podNameToTimeStamps[poduuid].lastNotifyToLastEpFileUpdateDiff),
1✔
517
                                                normalizeToMinutes(agent.podNameToTimeStamps[poduuid].podCreationToLastEpFileUpdateDiff),
1✔
518
                                                agent.podNameToTimeStamps[poduuid].podCreationTimestamp.Format("2006-01-02T15:04:05Z"),
1✔
519
                                                agent.podNameToTimeStamps[poduuid].podStartTimestamp.Format("2006-01-02T15:04:05Z"))
1✔
520
                                        agent.indexMutex.Unlock()
1✔
521
                                }
1✔
522

523
                                if _, ok := agent.nodePodIfEPs[ep.Uuid]; !ok {
1✔
524
                                        agent.nodePodIfEPs[ep.Uuid] = ep
×
525
                                }
×
526
                                seen[epidstr] = true
1✔
527
                        }
528
                }
529

530
                if !ok || (ok && !seen[epidstr]) {
2✔
531
                        staleEp, err := readEp(epfile)
1✔
532
                        if err == nil {
2✔
533
                                k := agent.getPodIFName(staleEp.Attributes["namespace"], staleEp.Attributes["vm-name"])
1✔
534
                                agent.EPRegDelEP(k)
1✔
535
                                delete(agent.nodePodIfEPs, staleEp.Uuid)
1✔
536
                        }
1✔
537
                        logger.Info("Removing endpoint")
1✔
538
                        fmt.Printf("\nJ: Deleting ep file for %v", poduuid)
1✔
539
                        os.Remove(epfile)
1✔
540
                }
541
        }
542

543
        for _, eps := range opflexEps {
2✔
544
                for _, ep := range eps {
2✔
545
                        if seen[ep.Uuid] {
2✔
546
                                continue
1✔
547
                        }
548
                        epfile := agent.FormEPFilePath(ep.Uuid)
1✔
549
                        poduuid := strings.Split(ep.Uuid, "_")[0]
1✔
550
                        ep.SnatUuid, err = agent.getSnatUuids(poduuid, epfile)
1✔
551
                        if err != nil {
1✔
552
                                agent.log.Error("Error while getting snat uuids")
×
553
                                needRetry = true
×
554
                                continue
×
555
                        }
556
                        ep.ServiceClusterIps = agent.getServiceIPs(poduuid)
1✔
557
                        opflexEpLogger(agent.log, ep).Info("Adding endpoint")
1✔
558
                        agent.indexMutex.Lock()
1✔
559
                        agent.initPodNotifyTimeStamp(poduuid)
1✔
560
                        agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp = time.Now().UTC()
1✔
561
                        agent.podNameToTimeStamps[poduuid].createNotifyToLastEpFileUpdateDiff = agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Sub(agent.podNameToTimeStamps[poduuid].podCreationNotificationTimestamp)
1✔
562
                        agent.podNameToTimeStamps[poduuid].lastNotifyToLastEpFileUpdateDiff = agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Sub(agent.podNameToTimeStamps[poduuid].podCreationNotificationTimestamp)
1✔
563
                        agent.podNameToTimeStamps[poduuid].podCreationToLastEpFileUpdateDiff = agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Sub(agent.podNameToTimeStamps[poduuid].podCreationTimestamp)
1✔
564
                        agent.indexMutex.Unlock()
1✔
565

1✔
566
                        agent.epfileMutex.Lock()
1✔
567
                        _, err = writeEp(epfile, ep)
1✔
568
                        agent.epfileMutex.Unlock()
1✔
569
                        if err != nil {
1✔
570
                                opflexEpLogger(agent.log, ep).
×
571
                                        Error("Error writing EP file: ", err)
×
572
                                needRetry = true
×
573
                        } else {
1✔
574
                                needRetry = agent.EPRegAdd(ep)
1✔
575
                                agent.nodePodIfEPs[ep.Uuid] = ep
1✔
576
                        }
1✔
577
                        agent.indexMutex.Lock()
1✔
578
                        agent.log.Debugf("ep file Created for pod: %s, Timestamps: {podCreatationNoticationTimestamp=%s, "+
1✔
579
                                "podUpdateNotificationsTimestamps=[%s],  epFileUpdateTimestamps=[%s],  epFileCreateTimestamp=%s, "+
1✔
580
                                "createNotifyToLastEpFileUpdateDiff=%s, lastNotifyToLastEpFileUpdateDiff=%s, "+
1✔
581
                                "podCreationToLastEpFileUpdateDiff=%s, podCreationTimestamp=%s, "+
1✔
582
                                "podStartTimestamp=%s}", ep.Attributes["vm-name"],
1✔
583
                                agent.podNameToTimeStamps[poduuid].podCreationNotificationTimestamp.Format("2006-01-02T15:04:05Z"),
1✔
584
                                formatTimestamps(agent.podNameToTimeStamps[poduuid].podUpdateNotificationsTimestamps),
1✔
585
                                formatMapTimestamps(agent.podNameToTimeStamps[poduuid].epFileUpdateTimestamps),
1✔
586
                                agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Format("2006-01-02T15:04:05Z"),
1✔
587
                                normalizeToMinutes(agent.podNameToTimeStamps[poduuid].createNotifyToLastEpFileUpdateDiff),
1✔
588
                                normalizeToMinutes(agent.podNameToTimeStamps[poduuid].lastNotifyToLastEpFileUpdateDiff),
1✔
589
                                normalizeToMinutes(agent.podNameToTimeStamps[poduuid].podCreationToLastEpFileUpdateDiff),
1✔
590
                                agent.podNameToTimeStamps[poduuid].podCreationTimestamp.Format("2006-01-02T15:04:05Z"),
1✔
591
                                agent.podNameToTimeStamps[poduuid].podStartTimestamp.Format("2006-01-02T15:04:05Z"))
1✔
592
                        agent.indexMutex.Unlock()
1✔
593
                }
594
        }
595

596
        if !nullMacFile {
2✔
597
                agent.creatNullMacEp()
1✔
598
        }
1✔
599
        agent.log.Debug("Finished endpoint sync")
1✔
600
        return needRetry
1✔
601
}
602

603
// syncNodePodIfs syncs the NodePodIfs with Eps
604
func (agent *HostAgent) syncNodePodIfs() bool {
1✔
605
        if !agent.syncEnabled || agent.config.ChainedMode {
1✔
606
                return false
×
607
        }
×
608
        agent.log.Debug("Syncing NodePodIfs")
1✔
609
        agent.indexMutex.Lock()
1✔
610
        defer agent.indexMutex.Unlock()
1✔
611
        agent.NodeEPRegAdd(agent.nodePodIfEPs)
1✔
612
        agent.log.Debug("Finished NodePodIfs sync")
1✔
613
        return false
1✔
614
}
615

616
func (agent *HostAgent) getEpFileName(epGroupName string) string {
1✔
617
        temp := strings.Split(epGroupName, "|")
1✔
618
        var EpFileName string
1✔
619
        if len(temp) == 1 {
2✔
620
                EpFileName = epGroupName + "_" + NullMac + ".ep"
1✔
621
        } else {
2✔
622
                EpFileName = temp[1] + "_" + NullMac + ".ep"
1✔
623
        }
1✔
624
        return EpFileName
1✔
625
}
626

627
func (agent *HostAgent) creatNullMacEp() {
1✔
628
        epGroup := agent.config.DefaultEg
1✔
629
        EpFileName := agent.getEpFileName(epGroup.Name)
1✔
630
        EpFilePath := filepath.Join(agent.config.OpFlexEndpointDir, EpFileName)
1✔
631
        ep_file_exists := fileExists(EpFilePath)
1✔
632
        if ep_file_exists {
1✔
633
                return
×
634
        }
×
635
        ep := &opflexEndpoint{
1✔
636
                Uuid:          uuid.New().String(),
1✔
637
                EgPolicySpace: epGroup.PolicySpace,
1✔
638
                EndpointGroup: epGroup.Name,
1✔
639
                MacAddress:    "00:00:00:00:00:00",
1✔
640
        }
1✔
641
        wrote, err := writeEp(EpFilePath, ep)
1✔
642
        if err != nil {
1✔
643
                agent.log.Debug("Unable to write null mac Ep file")
×
644
        } else if wrote {
2✔
645
                agent.log.Debug("Created null mac Ep file")
1✔
646
        }
1✔
647
}
648

649
func podFilter(pod *v1.Pod) bool {
1✔
650
        return !(pod.Spec.HostNetwork)
1✔
651
}
1✔
652

653
func (agent *HostAgent) podUpdated(obj interface{}) {
1✔
654
        agent.log.Infof("Pod updated: namespace=%s name=%s", obj.(*v1.Pod).Namespace, obj.(*v1.Pod).Name)
1✔
655
        agent.indexMutex.Lock()
1✔
656
        defer agent.indexMutex.Unlock()
1✔
657
        agent.depPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
658
        agent.rcPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
659
        if !agent.config.ChainedMode {
2✔
660
                agent.netPolPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
661
                agent.qosPolPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
662
        }
1✔
663
        agent.updatePodStausTimeStamps(obj.(*v1.Pod))
1✔
664
        if !agent.config.ChainedMode {
2✔
665
                agent.handleObjectUpdateForSnat(obj)
1✔
666
        }
1✔
667
        agent.podChangedLocked(obj)
1✔
668
}
669

670
func (agent *HostAgent) initPodNotifyTimeStamp(tsKey string) {
1✔
671
        n := 4
1✔
672
        fmt.Printf("\nJ: Printing the last %d callers in the stack before initPodNotifyTimeStamp:\n", n)
1✔
673
        for i := 1; i <= n; i++ {
2✔
674
                pc, file, line, ok := jruntime.Caller(i)
1✔
675
                if !ok {
1✔
NEW
676
                        break
×
677
                }
678
                fn := jruntime.FuncForPC(pc)
1✔
679
                fmt.Printf("\nJ: Caller %d: Function: %s File: %s Line: %d\n", i, fn.Name(), file, line)
1✔
680
        }
681

682
        if _, exists := agent.podNameToTimeStamps[tsKey]; exists {
2✔
683
                fmt.Printf("\nJ: poduuid %s exists skipping", tsKey)
1✔
684
                return
1✔
685
        }
1✔
686
        fmt.Printf("\nJ: poduuid %s doesn't exist. Initializing", tsKey)
1✔
687
        tsMap := &epTimeStamps{
1✔
688
                podCreationNotificationTimestamp:   time.Time{},
1✔
689
                podUpdateNotificationsTimestamps:   make([]time.Time, 0),
1✔
690
                epFileUpdateTimestamps:             make(map[time.Time]string),
1✔
691
                epFileCreateTimestamp:              time.Time{},
1✔
692
                createNotifyToLastEpFileUpdateDiff: 0,
1✔
693
                lastNotifyToLastEpFileUpdateDiff:   0,
1✔
694
                podCreationToLastEpFileUpdateDiff:  0,
1✔
695
                podCreationTimestamp:               time.Time{},
1✔
696
                podStartTimestamp:                  time.Time{},
1✔
697
        }
1✔
698
        agent.podNameToTimeStamps[tsKey] = tsMap
1✔
699
}
700

701
func (agent *HostAgent) initPodCreationNotificationTimestamp(pod *v1.Pod) {
1✔
702
        tsKey := string(pod.ObjectMeta.UID)
1✔
703
        fmt.Printf("\nJ: initPodCreationNotificationTimestamp for pod: %v", tsKey)
1✔
704
        agent.indexMutex.Lock()
1✔
705
        agent.initPodNotifyTimeStamp(tsKey)
1✔
706
        agent.podNameToTimeStamps[tsKey].podCreationNotificationTimestamp = time.Now().UTC()
1✔
707
        agent.indexMutex.Unlock()
1✔
708
}
1✔
709

710
func (agent *HostAgent) updatePodStausTimeStamps(pod *v1.Pod) {
1✔
711
        tsKey := string(pod.ObjectMeta.UID)
1✔
712
        fmt.Printf("\nJ: updatePodStausTimeStamps for pod: %v", tsKey)
1✔
713
        agent.initPodNotifyTimeStamp(tsKey)
1✔
714
        agent.podNameToTimeStamps[tsKey].podCreationTimestamp = pod.GetCreationTimestamp().UTC()
1✔
715
        if pod.Status.StartTime != nil {
2✔
716
                agent.podNameToTimeStamps[tsKey].podStartTimestamp = pod.Status.StartTime.UTC()
1✔
717
        }
1✔
718
}
719

720
func (agent *HostAgent) updatePodNotifyTimeStamp(pod *v1.Pod) {
1✔
721
        tsKey := string(pod.ObjectMeta.UID)
1✔
722
        defer func() {
2✔
723
                if p := recover(); p != nil {
1✔
NEW
724
                        fmt.Printf("\nJ: panic: %v in updatePodNotifyTimeStamp for poduuid: %v", p, tsKey)
×
NEW
725
                }
×
726
        }()
727
        fmt.Printf("\nJ: updatePodNotifyTimeStamp for pod: %v", tsKey)
1✔
728
        agent.indexMutex.Lock()
1✔
729
        agent.podNameToTimeStamps[tsKey].podUpdateNotificationsTimestamps = append(agent.podNameToTimeStamps[tsKey].podUpdateNotificationsTimestamps, time.Now().UTC())
1✔
730
        agent.indexMutex.Unlock()
1✔
731
}
732

733
func (agent *HostAgent) podChanged(podkey *string) {
1✔
734
        podobj, exists, err := agent.podInformer.GetStore().GetByKey(*podkey)
1✔
735
        if err != nil {
1✔
UNCOV
736
                agent.log.Error("Could not lookup pod: ", err)
×
UNCOV
737
        }
×
738
        if !exists || podobj == nil {
2✔
739
                agent.log.Debug("Object doesn't exist yet ", *podkey)
1✔
740
                return
1✔
741
        }
1✔
742

743
        agent.indexMutex.Lock()
1✔
744
        defer agent.indexMutex.Unlock()
1✔
745
        agent.podChangedLocked(podobj)
1✔
746
}
747

748
// Must have index lock
749
func (agent *HostAgent) podChangedPostLock(podkey *string) {
1✔
750
        podobj, exists, err := agent.podInformer.GetStore().GetByKey(*podkey)
1✔
751
        if err != nil {
1✔
UNCOV
752
                agent.log.Error("Could not lookup pod: ", err)
×
UNCOV
753
        }
×
754
        if !exists || podobj == nil {
2✔
755
                agent.log.Debug("Object doesn't exist yet ", *podkey)
1✔
756
                return
1✔
757
        }
1✔
758

UNCOV
759
        agent.podChangedLocked(podobj)
×
760
}
761

762
func (agent *HostAgent) podChangedLocked(podobj interface{}) {
1✔
763
        pod := podobj.(*v1.Pod)
1✔
764
        logger := podLogger(agent.log, pod)
1✔
765

1✔
766
        if agent.config.ChainedMode {
1✔
UNCOV
767
                return
×
UNCOV
768
        }
×
769
        epMetaKey := fmt.Sprintf("%s/%s", pod.ObjectMeta.Namespace, pod.ObjectMeta.Name)
1✔
770
        epUuid := string(pod.ObjectMeta.UID)
1✔
771

1✔
772
        if !podFilter(pod) {
1✔
UNCOV
773
                agent.epDeleted(&epUuid)
×
UNCOV
774
                return
×
775
        }
×
776
        agent.cniToPodID[epMetaKey] = epUuid
1✔
777
        if pod.Status.PodIP != "" {
2✔
778
                type void struct{}
1✔
779
                var ipexists void
1✔
780
                podIPs := make(map[string]void)
1✔
781
                podIPs[pod.Status.PodIP] = ipexists
1✔
782
                podIPsField := reflect.ValueOf(pod.Status).FieldByName("PodIPs")
1✔
783
                if podIPsField.IsValid() {
2✔
784
                        for _, ip := range pod.Status.PodIPs {
2✔
785
                                podIPs[ip.IP] = ipexists
1✔
786
                        }
1✔
787
                }
788
                for ip := range podIPs {
2✔
789
                        agent.podIpToName[ip] = epMetaKey
1✔
790
                }
1✔
791
        }
792
        agent.podUidToName[epUuid] = epMetaKey
1✔
793
        epGroup, secGroup, qpGroup, _ := agent.assignGroups(pod)
1✔
794
        epAttributes := pod.ObjectMeta.Labels
1✔
795
        if epAttributes == nil {
2✔
796
                epAttributes = make(map[string]string)
1✔
797
        }
1✔
798
        epAttributes["vm-name"] = pod.ObjectMeta.Name
1✔
799
        epAttributes["namespace"] = pod.ObjectMeta.Namespace
1✔
800

1✔
801
        agent.epChanged(&epUuid, &epMetaKey, &epGroup, secGroup, qpGroup, epAttributes, logger)
1✔
802
        var netAttachDef []string
1✔
803
        if pod.ObjectMeta.Annotations[metadata.NetAttDefAnnotation] != "" {
1✔
UNCOV
804
                netAttachDef = strings.Split(pod.ObjectMeta.Annotations[metadata.NetAttDefAnnotation], ",")
×
805
        } else if pod.ObjectMeta.Annotations[metadata.MultusNetAnnotation] != "" {
1✔
806
                netAttachDef = strings.Split(pod.ObjectMeta.Annotations[metadata.MultusNetAnnotation], ",")
×
UNCOV
807
        }
×
808
        if netAttachDef != nil {
1✔
809
                podKey := pod.ObjectMeta.Name + "-" + pod.ObjectMeta.Namespace
×
UNCOV
810
                agent.podToNetAttachDef[podKey] = netAttachDef
×
811
        }
×
812
}
813

814
func (agent *HostAgent) fillEpFields(ep *opflexEndpoint, podkey string) error {
1✔
815
        podobj, exists, err := agent.podInformer.GetStore().GetByKey(podkey)
1✔
816
        if err != nil {
1✔
UNCOV
817
                return err
×
UNCOV
818
        }
×
819
        if !exists {
2✔
820
                return fmt.Errorf("Failed to get pod object of %s ", podkey)
1✔
821
        }
1✔
822
        pod := podobj.(*v1.Pod)
1✔
823
        epAttributes := pod.ObjectMeta.Labels
1✔
824
        if epAttributes == nil {
1✔
UNCOV
825
                epAttributes = make(map[string]string)
×
UNCOV
826
        }
×
827
        epAttributes["vm-name"] = pod.ObjectMeta.Name
1✔
828
        epAttributes["namespace"] = pod.ObjectMeta.Namespace
1✔
829
        epGroup, epSecGroups, epQosPolicy, _ := agent.assignGroups(pod)
1✔
830
        ep.Attributes = make(map[string]string)
1✔
831
        for k, v := range epAttributes {
2✔
832
                ep.Attributes[k] = v
1✔
833
        }
1✔
834
        if epGroup.Tenant != "" {
2✔
835
                ep.EgPolicySpace = epGroup.Tenant
1✔
836
        } else {
1✔
UNCOV
837
                ep.EgPolicySpace = epGroup.PolicySpace
×
UNCOV
838
        }
×
839
        if epGroup.AppProfile != "" {
2✔
840
                ep.EndpointGroup = epGroup.AppProfile + "|" + epGroup.Name
1✔
841
        } else {
1✔
UNCOV
842
                ep.EndpointGroup = epGroup.Name
×
UNCOV
843
        }
×
844
        ep.SecurityGroup = epSecGroups
1✔
845
        ep.QosPolicy = epQosPolicy
1✔
846
        return nil
1✔
847
}
848

849
func (agent *HostAgent) epChanged(epUuid *string, epMetaKey *string, epGroup *metadata.OpflexGroup,
850
        epSecGroups []metadata.OpflexGroup, epQosPolicy metadata.OpflexGroup, epAttributes map[string]string,
851
        logger *logrus.Entry) {
1✔
852
        if logger == nil {
2✔
853
                logger = agent.log.WithFields(logrus.Fields{})
1✔
854
        }
1✔
855
        if agent.config.ChainedMode {
1✔
UNCOV
856
                return
×
UNCOV
857
        }
×
858
        logger.Debug("epChanged...")
1✔
859
        epmetadata, ok := agent.epMetadata[*epMetaKey]
1✔
860
        if !ok {
2✔
861
                logger.Debug("No metadata found for ep: ")
1✔
862
                delete(agent.opflexEps, *epUuid)
1✔
863
                agent.log.Debug("syncEP scheduled")
1✔
864
                agent.scheduleSyncEps()
1✔
865
                return
1✔
866
        }
1✔
867

868
        var neweps []*opflexEndpoint
1✔
869

1✔
870
        for _, epmeta := range epmetadata {
2✔
871
                for _, iface := range epmeta.Ifaces {
2✔
872
                        patchIntName, patchAccessName :=
1✔
873
                                metadata.GetIfaceNames(iface.HostVethName)
1✔
874

1✔
875
                        ips := make([]string, 0)
1✔
876
                        for _, ip := range iface.IPs {
2✔
877
                                if ip.Address.IP == nil {
1✔
UNCOV
878
                                        continue
×
879
                                }
880
                                ips = append(ips, ip.Address.IP.String())
1✔
881
                        }
882

883
                        epidstr := *epUuid + "_" + epmeta.Id.ContId + "_" + iface.HostVethName
1✔
884
                        ep := &opflexEndpoint{
1✔
885
                                Uuid:              epidstr,
1✔
886
                                MacAddress:        iface.Mac,
1✔
887
                                IpAddress:         ips,
1✔
888
                                AccessIface:       iface.HostVethName,
1✔
889
                                AccessUplinkIface: patchAccessName,
1✔
890
                                IfaceName:         patchIntName,
1✔
891
                        }
1✔
892

1✔
893
                        ep.Attributes = make(map[string]string)
1✔
894
                        for k, v := range epAttributes {
2✔
895
                                ep.Attributes[k] = v
1✔
896
                        }
1✔
897

898
                        ep.Attributes["interface-name"] = iface.HostVethName
1✔
899
                        if epGroup.Tenant != "" {
2✔
900
                                ep.EgPolicySpace = epGroup.Tenant
1✔
901
                        } else {
2✔
902
                                ep.EgPolicySpace = epGroup.PolicySpace
1✔
903
                        }
1✔
904
                        if epGroup.AppProfile != "" {
2✔
905
                                ep.EndpointGroup = epGroup.AppProfile + "|" + epGroup.Name
1✔
906
                        } else {
2✔
907
                                ep.EndpointGroup = epGroup.Name
1✔
908
                        }
1✔
909
                        ep.SecurityGroup = epSecGroups
1✔
910
                        ep.QosPolicy = epQosPolicy
1✔
911

1✔
912
                        neweps = append(neweps, ep)
1✔
913
                }
914
        }
915

916
        existing, ok := agent.opflexEps[*epUuid]
1✔
917
        for _, ep := range existing {
2✔
918
                for _, newep := range neweps {
2✔
919
                        if ep.Uuid == newep.Uuid {
2✔
920
                                newep.registered = ep.registered
1✔
921
                        }
1✔
922
                }
923
        }
924

925
        if (ok && !reflect.DeepEqual(existing, neweps)) || !ok {
2✔
926
                logger.WithFields(logrus.Fields{
1✔
927
                        "id": *epMetaKey,
1✔
928
                        "ep": neweps,
1✔
929
                }).Debug("Updated endpoints for pod")
1✔
930
                logger.Infof("EP updated: %+v", neweps[0])
1✔
931
                agent.log.Debug("syncEP scheduled")
1✔
932

1✔
933
                agent.opflexEps[*epUuid] = neweps
1✔
934
                agent.scheduleSyncEps()
1✔
935
        }
1✔
936
}
937

938
func (agent *HostAgent) epDeleted(epUuid *string) {
1✔
939
        if _, ok := agent.opflexEps[*epUuid]; ok {
1✔
UNCOV
940
                delete(agent.opflexEps, *epUuid)
×
UNCOV
941
                agent.log.Debug("syncEP scheduled")
×
942
                agent.scheduleSyncEps()
×
943
        }
×
944
}
945

946
func (agent *HostAgent) podDeleted(obj interface{}) {
1✔
947
        pod, isPod := obj.(*v1.Pod)
1✔
948
        if !isPod {
2✔
949
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
1✔
950
                if !ok {
2✔
951
                        agent.log.Error("Received unexpected object: ", obj)
1✔
952
                        return
1✔
953
                }
1✔
954
                pod, ok = deletedState.Obj.(*v1.Pod)
1✔
955
                if !ok {
2✔
956
                        agent.log.Error("DeletedFinalStateUnknown contained non-Pod object: ", deletedState.Obj)
1✔
957
                        return
1✔
958
                }
1✔
959
        }
960
        agent.log.Infof("Pod deleted: name %s namespace %s", pod.ObjectMeta.Name, pod.ObjectMeta.Namespace)
1✔
961
        podns, podname := pod.ObjectMeta.Namespace, pod.ObjectMeta.Name
1✔
962
        podid := podns + "/" + podname
1✔
963
        mdmap, ok := agent.epMetadata[podid]
1✔
964
        if ok {
2✔
965
                for contid, v := range mdmap {
2✔
966
                        metadata := cnimeta.ContainerMetadata{
1✔
967
                                Id: cnimeta.ContainerId{
1✔
968
                                        ContId:    contid,
1✔
969
                                        Namespace: podns,
1✔
970
                                        Pod:       podname,
1✔
971
                                },
1✔
972
                                Network: cnimeta.ContainerNetworkMetadata{
1✔
973
                                        NetworkName: v.Network.NetworkName,
1✔
974
                                        ChainedMode: agent.config.ChainedMode,
1✔
975
                                },
1✔
976
                        }
1✔
977
                        err := agent.unconfigureContainerIfaces(&metadata)
1✔
978
                        if err != nil {
2✔
979
                                agent.log.Warnf("Could not unconfigure container:%s, %s ", contid, err)
1✔
980
                        }
1✔
981
                }
982
        }
983
        agent.indexMutex.Lock()
1✔
984
        defer agent.indexMutex.Unlock()
1✔
985
        agent.podDeletedLocked(obj)
1✔
986
        agent.depPods.DeletePod(obj.(*v1.Pod))
1✔
987
        agent.rcPods.DeletePod(obj.(*v1.Pod))
1✔
988
        if !agent.config.ChainedMode {
2✔
989
                agent.qosPolPods.DeletePod(obj.(*v1.Pod))
1✔
990
        }
1✔
991
        agent.netPolPods.DeletePod(obj.(*v1.Pod))
1✔
992
        if !agent.config.ChainedMode {
2✔
993
                agent.handleObjectDeleteForSnat(obj)
1✔
994
        }
1✔
995
}
996

997
func (agent *HostAgent) podDeletedLocked(obj interface{}) {
1✔
998
        pod := obj.(*v1.Pod)
1✔
999
        u := string(pod.ObjectMeta.UID)
1✔
1000
        if _, ok := agent.opflexEps[u]; ok {
2✔
1001
                agent.log.Infof("podDeletedLocked: delete %s/%s", pod.ObjectMeta.Namespace, pod.ObjectMeta.Name)
1✔
1002
                delete(agent.opflexEps, u)
1✔
1003
                agent.log.Debug("syncEP scheduled")
1✔
1004
                agent.scheduleSyncEps()
1✔
1005
        }
1✔
1006
        if pod.Status.PodIP != "" {
1✔
UNCOV
1007
                delete(agent.podIpToName, pod.Status.PodIP)
×
UNCOV
1008
        }
×
1009
        delete(agent.podUidToName, u)
1✔
1010
        agent.epDeleted(&u)
1✔
1011
        fmt.Printf("\n J: Deleting %v from podNameToTimeStamps", u)
1✔
1012
        delete(agent.podNameToTimeStamps, u)
1✔
1013
}
1014

1015
func (agent *HostAgent) cniEpDelete(cniKey string) {
1✔
1016
        agent.indexMutex.Lock()
1✔
1017
        defer agent.indexMutex.Unlock()
1✔
1018

1✔
1019
        epUuid, ok := agent.cniToPodID[cniKey]
1✔
1020
        if !ok {
2✔
1021
                agent.log.Warnf("cniEpDelete: PodID not found for %s", cniKey)
1✔
1022
                return
1✔
1023
        }
1✔
1024
        delete(agent.cniToPodID, cniKey)
1✔
1025

1✔
1026
        if _, ok := agent.opflexEps[epUuid]; ok {
2✔
1027
                agent.log.Infof("cniEpDelete: delete %s", cniKey)
1✔
1028
                delete(agent.opflexEps, epUuid)
1✔
1029
                agent.log.Debug("syncEP scheduled")
1✔
1030
                agent.scheduleSyncEps()
1✔
1031
        }
1✔
1032
}
1033

1034
func (agent *HostAgent) updateGbpServerInfo(pod *v1.Pod) {
1✔
1035
        if pod.ObjectMeta.Labels == nil {
2✔
1036
                return
1✔
1037
        }
1✔
1038
        agent.indexMutex.Lock()
1✔
1039
        nameVal := pod.ObjectMeta.Labels["name"]
1✔
1040
        if nameVal == "aci-containers-controller" {
1✔
UNCOV
1041
                if agent.gbpServerIP != pod.Status.PodIP {
×
1042
                        agent.log.Infof("gbpServerIPChanged to %s", pod.Status.PodIP)
×
1043
                        agent.gbpServerIP = pod.Status.PodIP
×
1044
                        agent.scheduleSyncOpflexServer()
×
1045
                }
×
1046
        }
1047
        agent.indexMutex.Unlock()
1✔
1048
}
1049

1050
func formatTimestamps(timestamps []time.Time) string {
1✔
1051
        var formattedTimestamps string
1✔
1052
        for i, timestamp := range timestamps {
2✔
1053
                if i > 0 {
2✔
1054
                        formattedTimestamps += ", "
1✔
1055
                }
1✔
1056
                formattedTimestamps += timestamp.Format("2006-01-02T15:04:05Z")
1✔
1057
        }
1058
        return formattedTimestamps
1✔
1059
}
1060

1061
func formatMapTimestamps(timestamps map[time.Time]string) string {
1✔
1062
        var formattedTimestamps string
1✔
1063
        for key, value := range timestamps {
2✔
1064
                formattedTimestamps += key.Format("2006-01-02T15:04:05Z") + ": " + value + ", "
1✔
1065
        }
1✔
1066

1067
        if len(formattedTimestamps) > 2 {
2✔
1068
                formattedTimestamps = formattedTimestamps[:len(formattedTimestamps)-2]
1✔
1069
        }
1✔
1070
        return formattedTimestamps
1✔
1071
}
1072

1073
func compareOpflexEndpoints(oldEndpoint, newEndpoint *opflexEndpoint) string {
1✔
1074
        var changedFields []string
1✔
1075

1✔
1076
        oldEndpointJSON, _ := json.Marshal(oldEndpoint)
1✔
1077
        newEndpointJSON, _ := json.Marshal(newEndpoint)
1✔
1078

1✔
1079
        var oldMap, newMap map[string]interface{}
1✔
1080
        json.Unmarshal(oldEndpointJSON, &oldMap)
1✔
1081
        json.Unmarshal(newEndpointJSON, &newMap)
1✔
1082

1✔
1083
        for key, oldValue := range oldMap {
2✔
1084
                newValue, exists := newMap[key]
1✔
1085
                if !exists || !reflect.DeepEqual(oldValue, newValue) {
2✔
1086
                        changedFields = append(changedFields, key)
1✔
1087
                }
1✔
1088
        }
1089

1090
        for key := range newMap {
2✔
1091
                if _, exists := oldMap[key]; !exists {
2✔
1092
                        changedFields = append(changedFields, key)
1✔
1093
                }
1✔
1094
        }
1095

1096
        return strings.Join(changedFields, ", ")
1✔
1097
}
1098

1099
func normalizeToMinutes(duration time.Duration) string {
1✔
1100
        return fmt.Sprintf("%.2f min", duration.Minutes())
1✔
1101
}
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc