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

noironetworks / aci-containers / 8852

21 Mar 2024 03:12PM UTC coverage: 70.881% (-0.4%) from 71.311%
8852

Pull #1287

travis-pro

akhilamohanan
Do VLAN programming upfront for OpenShift on OpenStack

For OpenShift on OpenStack clusters, vnsRsCIfPathAtt is created for each
OpenStack compute hosts along with OpenShift nodes so that VLAN will
already be there when a vm is migrated from one compute host to other.

The change is done to avoid datapath issues after vm migration.
Pull Request #1287: Do VLAN programming upfront for OpenShift on OpenStack

27 of 120 new or added lines in 2 files covered. (22.5%)

175 existing lines in 4 files now uncovered.

10703 of 15100 relevant lines covered (70.88%)

0.8 hits per line

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

73.86
/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
        "strings"
27
        "time"
28

29
        "github.com/sirupsen/logrus"
30

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

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

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

51
const NullMac = "null-mac"
52

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

257
func (agent *HostAgent) initPodInformerBase(listWatch *cache.ListWatch) {
1✔
258
        agent.podInformer = cache.NewSharedIndexInformer(
1✔
259
                listWatch,
1✔
260
                &v1.Pod{},
1✔
261
                controller.NoResyncPeriodFunc(),
1✔
262
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
1✔
263
        )
1✔
264
        agent.podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
1✔
265
                AddFunc: func(obj interface{}) {
2✔
266
                        agent.initPodNotifyTimeStamp(obj.(*v1.Pod))
1✔
267
                        agent.podUpdated(obj)
1✔
268
                },
1✔
269
                UpdateFunc: func(_ interface{}, obj interface{}) {
1✔
270
                        agent.updatePodNotifyTimeStamp(obj.(*v1.Pod))
1✔
271
                        agent.podUpdated(obj)
1✔
272
                },
1✔
273
                DeleteFunc: func(obj interface{}) {
1✔
274
                        agent.podDeleted(obj)
1✔
275
                },
1✔
276
        })
277
}
278

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

298
func getEp(epfile string) (string, error) {
1✔
299
        raw, err := os.ReadFile(epfile)
1✔
300
        if err != nil {
2✔
301
                return "", err
1✔
302
        }
1✔
303
        return string(raw), err
1✔
304
}
305

306
func readEp(epfile string) (*opflexEndpoint, error) {
1✔
307
        epStr, err := getEp(epfile)
1✔
308
        if err != nil {
1✔
UNCOV
309
                return nil, err
×
UNCOV
310
        }
×
311

312
        ep := &opflexEndpoint{}
1✔
313
        err = json.Unmarshal([]byte(epStr), ep)
1✔
314
        return ep, err
1✔
315
}
316

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

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

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

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

362
func (agent *HostAgent) FormEPFilePath(uuid string) string {
1✔
363
        return filepath.Join(agent.config.OpFlexEndpointDir, uuid+".ep")
1✔
364
}
1✔
365

366
func (agent *HostAgent) syncOpflexServer() bool {
1✔
367
        grpcAddr := fmt.Sprintf("%s:%d", agent.gbpServerIP, agent.config.GRPCPort)
1✔
368
        srvCfg := &OpflexServerConfig{GRPCAddress: grpcAddr}
1✔
369

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

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

383
        return false
1✔
384
}
385

386
func (agent *HostAgent) syncEps() bool {
1✔
387
        if !agent.syncEnabled {
1✔
388
                return false
×
389
        }
×
390

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

1✔
408
        files, err := os.ReadDir(agent.config.OpFlexEndpointDir)
1✔
409
        if err != nil {
1✔
410
                agent.log.WithFields(
×
411
                        logrus.Fields{"endpointDir": agent.config.OpFlexEndpointDir},
×
412
                ).Error("Could not read directory ", err)
×
413
                return true
×
414
        }
×
415

416
        needRetry := false
1✔
417
        seen := make(map[string]bool)
1✔
418
        nullMacFile := false
1✔
419
        nullMacCheck := agent.getEpFileName(agent.config.DefaultEg.Name)
1✔
420
        for _, f := range files {
2✔
421
                if !strings.HasSuffix(f.Name(), ".ep") ||
1✔
422
                        strings.Contains(f.Name(), "veth_host_ac") {
2✔
423
                        continue
1✔
424
                }
425

426
                if f.Name() == nullMacCheck {
2✔
427
                        nullMacFile = true
1✔
428
                        continue
1✔
429
                }
430

431
                epfile := filepath.Join(agent.config.OpFlexEndpointDir, f.Name())
1✔
432
                epidstr := f.Name()
1✔
433
                epidstr = epidstr[:len(epidstr)-3]
1✔
434
                epid := strings.Split(epidstr, "_")
1✔
435

1✔
436
                if len(epid) < 3 {
1✔
437
                        agent.log.Warn("Removing invalid endpoint:", f.Name())
×
438
                        os.Remove(epfile)
×
439
                        continue
×
440
                }
441
                poduuid := epid[0]
1✔
442
                contid := epid[1]
1✔
443
                contiface := epid[2]
1✔
444

1✔
445
                logger := agent.log.WithFields(
1✔
446
                        logrus.Fields{
1✔
447
                                "PodUuid":   poduuid,
1✔
448
                                "ContId":    contid,
1✔
449
                                "ContIFace": contiface,
1✔
450
                        },
1✔
451
                )
1✔
452

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

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

487
                                agent.epfileMutex.Lock()
1✔
488
                                wrote, err := writeEp(epfile, ep)
1✔
489
                                agent.epfileMutex.Unlock()
1✔
490
                                if err != nil {
1✔
491
                                        opflexEpLogger(agent.log, ep).
×
492
                                                Error("Error writing EP file: ", err)
×
493
                                } else if wrote || !ep.registered {
2✔
494
                                        needRetry = agent.EPRegAdd(ep)
1✔
495
                                }
1✔
496

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

516
                                if _, ok := agent.nodePodIfEPs[ep.Uuid]; !ok {
1✔
517
                                        agent.nodePodIfEPs[ep.Uuid] = ep
×
518
                                }
×
519
                                seen[epidstr] = true
1✔
520
                        }
521
                }
522

523
                if !ok || (ok && !seen[epidstr]) {
2✔
524
                        staleEp, err := readEp(epfile)
1✔
525
                        if err == nil {
2✔
526
                                k := agent.getPodIFName(staleEp.Attributes["namespace"], staleEp.Attributes["vm-name"])
1✔
527
                                agent.EPRegDelEP(k)
1✔
528
                                delete(agent.nodePodIfEPs, staleEp.Uuid)
1✔
529
                        }
1✔
530
                        logger.Info("Removing endpoint")
1✔
531
                        os.Remove(epfile)
1✔
532
                }
533
        }
534

535
        for _, eps := range opflexEps {
2✔
536
                for _, ep := range eps {
2✔
537
                        if seen[ep.Uuid] {
2✔
538
                                continue
1✔
539
                        }
540
                        epfile := agent.FormEPFilePath(ep.Uuid)
1✔
541
                        poduuid := strings.Split(ep.Uuid, "_")[0]
1✔
542
                        ep.SnatUuid, err = agent.getSnatUuids(poduuid, epfile)
1✔
543
                        if err != nil {
1✔
544
                                agent.log.Error("Error while getting snat uuids")
×
545
                                needRetry = true
×
546
                                continue
×
547
                        }
548
                        ep.ServiceClusterIps = agent.getServiceIPs(poduuid)
1✔
549
                        opflexEpLogger(agent.log, ep).Info("Adding endpoint")
1✔
550
                        agent.indexMutex.Lock()
1✔
551
                        agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp = time.Now().UTC()
1✔
552
                        agent.podNameToTimeStamps[poduuid].createNotifyToLastEpFileUpdateDiff = agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Sub(agent.podNameToTimeStamps[poduuid].podCreatationNoticationTimestamp)
1✔
553
                        agent.podNameToTimeStamps[poduuid].lastNotifyToLastEpFileUpdateDiff = agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Sub(agent.podNameToTimeStamps[poduuid].podCreatationNoticationTimestamp)
1✔
554
                        agent.podNameToTimeStamps[poduuid].podCreationToLastEpFileUpdateDiff = agent.podNameToTimeStamps[poduuid].epFileCreateTimestamp.Sub(agent.podNameToTimeStamps[poduuid].podCreationTimestamp)
1✔
555
                        agent.indexMutex.Unlock()
1✔
556

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

587
        if !nullMacFile {
2✔
588
                agent.creatNullMacEp()
1✔
589
        }
1✔
590
        agent.log.Debug("Finished endpoint sync")
1✔
591
        return needRetry
1✔
592
}
593

594
// syncNodePodIfs syncs the NodePodIfs with Eps
595
func (agent *HostAgent) syncNodePodIfs() bool {
1✔
596
        if !agent.syncEnabled || agent.config.ChainedMode {
1✔
597
                return false
×
598
        }
×
599
        agent.log.Debug("Syncing NodePodIfs")
1✔
600
        agent.indexMutex.Lock()
1✔
601
        defer agent.indexMutex.Unlock()
1✔
602
        agent.NodeEPRegAdd(agent.nodePodIfEPs)
1✔
603
        agent.log.Debug("Finished NodePodIfs sync")
1✔
604
        return false
1✔
605
}
606

607
func (agent *HostAgent) getEpFileName(epGroupName string) string {
1✔
608
        temp := strings.Split(epGroupName, "|")
1✔
609
        var EpFileName string
1✔
610
        if len(temp) == 1 {
2✔
611
                EpFileName = epGroupName + "_" + NullMac + ".ep"
1✔
612
        } else {
2✔
613
                EpFileName = temp[1] + "_" + NullMac + ".ep"
1✔
614
        }
1✔
615
        return EpFileName
1✔
616
}
617

618
func (agent *HostAgent) creatNullMacEp() {
1✔
619
        epGroup := agent.config.DefaultEg
1✔
620
        EpFileName := agent.getEpFileName(epGroup.Name)
1✔
621
        EpFilePath := filepath.Join(agent.config.OpFlexEndpointDir, EpFileName)
1✔
622
        ep_file_exists := fileExists(EpFilePath)
1✔
623
        if ep_file_exists {
1✔
624
                return
×
625
        }
×
626
        ep := &opflexEndpoint{
1✔
627
                Uuid:          uuid.New().String(),
1✔
628
                EgPolicySpace: epGroup.PolicySpace,
1✔
629
                EndpointGroup: epGroup.Name,
1✔
630
                MacAddress:    "00:00:00:00:00:00",
1✔
631
        }
1✔
632
        wrote, err := writeEp(EpFilePath, ep)
1✔
633
        if err != nil {
1✔
UNCOV
634
                agent.log.Debug("Unable to write null mac Ep file")
×
635
        } else if wrote {
2✔
636
                agent.log.Debug("Created null mac Ep file")
1✔
637
        }
1✔
638
}
639

640
func podFilter(pod *v1.Pod) bool {
1✔
641
        return !(pod.Spec.HostNetwork)
1✔
642
}
1✔
643

644
func (agent *HostAgent) podUpdated(obj interface{}) {
1✔
645
        agent.log.Infof("Pod updated: namespace=%s name=%s", obj.(*v1.Pod).Namespace, obj.(*v1.Pod).Name)
1✔
646
        agent.indexMutex.Lock()
1✔
647
        defer agent.indexMutex.Unlock()
1✔
648
        agent.depPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
649
        agent.rcPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
650
        if !agent.config.ChainedMode {
2✔
651
                agent.netPolPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
652
                agent.qosPolPods.UpdatePodNoCallback(obj.(*v1.Pod))
1✔
653
        }
1✔
654
        agent.updatePodStausTimeStamps(obj.(*v1.Pod))
1✔
655
        if !agent.config.ChainedMode {
2✔
656
                agent.handleObjectUpdateForSnat(obj)
1✔
657
        }
1✔
658
        agent.podChangedLocked(obj)
1✔
659
}
660

661
func (agent *HostAgent) initPodNotifyTimeStamp(pod *v1.Pod) {
1✔
662
        tsMap := &epTimeStamps{
1✔
663
                podCreatationNoticationTimestamp:   time.Time{},
1✔
664
                podUpdateNotificationsTimestamps:   make([]time.Time, 0),
1✔
665
                epFileUpdateTimestamps:             make(map[time.Time]string),
1✔
666
                epFileCreateTimestamp:              time.Time{},
1✔
667
                createNotifyToLastEpFileUpdateDiff: 0,
1✔
668
                lastNotifyToLastEpFileUpdateDiff:   0,
1✔
669
                podCreationToLastEpFileUpdateDiff:  0,
1✔
670
                podCreationTimestamp:               time.Time{},
1✔
671
                podStartTimestamp:                  time.Time{},
1✔
672
        }
1✔
673
        tsMap.podCreatationNoticationTimestamp = time.Now().UTC()
1✔
674
        tsKey := string(pod.ObjectMeta.UID)
1✔
675
        agent.indexMutex.Lock()
1✔
676
        agent.podNameToTimeStamps[tsKey] = tsMap
1✔
677
        agent.indexMutex.Unlock()
1✔
678
}
1✔
679

680
func (agent *HostAgent) updatePodStausTimeStamps(pod *v1.Pod) {
1✔
681
        tsKey := string(pod.ObjectMeta.UID)
1✔
682
        agent.podNameToTimeStamps[tsKey].podCreationTimestamp = pod.GetCreationTimestamp().UTC()
1✔
683
        if pod.Status.StartTime != nil {
2✔
684
                agent.podNameToTimeStamps[tsKey].podStartTimestamp = pod.Status.StartTime.UTC()
1✔
685
        }
1✔
686
}
687

688
func (agent *HostAgent) updatePodNotifyTimeStamp(pod *v1.Pod) {
1✔
689
        tsKey := string(pod.ObjectMeta.UID)
1✔
690
        agent.indexMutex.Lock()
1✔
691
        agent.podNameToTimeStamps[tsKey].podUpdateNotificationsTimestamps = append(agent.podNameToTimeStamps[tsKey].podUpdateNotificationsTimestamps, time.Now().UTC())
1✔
692
        agent.indexMutex.Unlock()
1✔
693
}
1✔
694

695
func (agent *HostAgent) podChanged(podkey *string) {
1✔
696
        podobj, exists, err := agent.podInformer.GetStore().GetByKey(*podkey)
1✔
697
        if err != nil {
1✔
698
                agent.log.Error("Could not lookup pod: ", err)
×
699
        }
×
700
        if !exists || podobj == nil {
2✔
701
                agent.log.Debug("Object doesn't exist yet ", *podkey)
1✔
702
                return
1✔
703
        }
1✔
704

705
        agent.indexMutex.Lock()
1✔
706
        defer agent.indexMutex.Unlock()
1✔
707
        agent.podChangedLocked(podobj)
1✔
708
}
709

710
// Must have index lock
711
func (agent *HostAgent) podChangedPostLock(podkey *string) {
1✔
712
        podobj, exists, err := agent.podInformer.GetStore().GetByKey(*podkey)
1✔
713
        if err != nil {
1✔
714
                agent.log.Error("Could not lookup pod: ", err)
×
715
        }
×
716
        if !exists || podobj == nil {
2✔
717
                agent.log.Debug("Object doesn't exist yet ", *podkey)
1✔
718
                return
1✔
719
        }
1✔
720

721
        agent.podChangedLocked(podobj)
×
722
}
723

724
func (agent *HostAgent) podChangedLocked(podobj interface{}) {
1✔
725
        pod := podobj.(*v1.Pod)
1✔
726
        logger := podLogger(agent.log, pod)
1✔
727

1✔
728
        if agent.config.ChainedMode {
1✔
729
                return
×
730
        }
×
731
        epMetaKey := fmt.Sprintf("%s/%s", pod.ObjectMeta.Namespace, pod.ObjectMeta.Name)
1✔
732
        epUuid := string(pod.ObjectMeta.UID)
1✔
733

1✔
734
        if !podFilter(pod) {
1✔
735
                agent.epDeleted(&epUuid)
×
736
                return
×
737
        }
×
738
        agent.cniToPodID[epMetaKey] = epUuid
1✔
739
        if pod.Status.PodIP != "" {
2✔
740
                type void struct{}
1✔
741
                var ipexists void
1✔
742
                podIPs := make(map[string]void)
1✔
743
                podIPs[pod.Status.PodIP] = ipexists
1✔
744
                podIPsField := reflect.ValueOf(pod.Status).FieldByName("PodIPs")
1✔
745
                if podIPsField.IsValid() {
2✔
746
                        for _, ip := range pod.Status.PodIPs {
2✔
747
                                podIPs[ip.IP] = ipexists
1✔
748
                        }
1✔
749
                }
750
                for ip := range podIPs {
2✔
751
                        agent.podIpToName[ip] = epMetaKey
1✔
752
                }
1✔
753
        }
754
        agent.podUidToName[epUuid] = epMetaKey
1✔
755
        epGroup, secGroup, qpGroup, _ := agent.assignGroups(pod)
1✔
756
        epAttributes := pod.ObjectMeta.Labels
1✔
757
        if epAttributes == nil {
2✔
758
                epAttributes = make(map[string]string)
1✔
759
        }
1✔
760
        epAttributes["vm-name"] = pod.ObjectMeta.Name
1✔
761
        epAttributes["namespace"] = pod.ObjectMeta.Namespace
1✔
762

1✔
763
        agent.epChanged(&epUuid, &epMetaKey, &epGroup, secGroup, qpGroup, epAttributes, logger)
1✔
764
        var netAttachDef []string
1✔
765
        if pod.ObjectMeta.Annotations[metadata.NetAttDefAnnotation] != "" {
1✔
766
                netAttachDef = strings.Split(pod.ObjectMeta.Annotations[metadata.NetAttDefAnnotation], ",")
×
767
        } else if pod.ObjectMeta.Annotations[metadata.MultusNetAnnotation] != "" {
1✔
768
                netAttachDef = strings.Split(pod.ObjectMeta.Annotations[metadata.MultusNetAnnotation], ",")
×
769
        }
×
770
        if netAttachDef != nil {
1✔
771
                podKey := pod.ObjectMeta.Name + "-" + pod.ObjectMeta.Namespace
×
772
                agent.podToNetAttachDef[podKey] = netAttachDef
×
773
        }
×
774
}
775

776
func (agent *HostAgent) fillEpFields(ep *opflexEndpoint, podkey string) error {
1✔
777
        podobj, exists, err := agent.podInformer.GetStore().GetByKey(podkey)
1✔
778
        if err != nil {
1✔
779
                return err
×
780
        }
×
781
        if !exists {
2✔
782
                return fmt.Errorf("Failed to get pod object of %s ", podkey)
1✔
783
        }
1✔
784
        pod := podobj.(*v1.Pod)
1✔
785
        epAttributes := pod.ObjectMeta.Labels
1✔
786
        if epAttributes == nil {
1✔
787
                epAttributes = make(map[string]string)
×
788
        }
×
789
        epAttributes["vm-name"] = pod.ObjectMeta.Name
1✔
790
        epAttributes["namespace"] = pod.ObjectMeta.Namespace
1✔
791
        epGroup, epSecGroups, epQosPolicy, _ := agent.assignGroups(pod)
1✔
792
        ep.Attributes = make(map[string]string)
1✔
793
        for k, v := range epAttributes {
2✔
794
                ep.Attributes[k] = v
1✔
795
        }
1✔
796
        if epGroup.Tenant != "" {
2✔
797
                ep.EgPolicySpace = epGroup.Tenant
1✔
798
        } else {
1✔
799
                ep.EgPolicySpace = epGroup.PolicySpace
×
800
        }
×
801
        if epGroup.AppProfile != "" {
2✔
802
                ep.EndpointGroup = epGroup.AppProfile + "|" + epGroup.Name
1✔
803
        } else {
1✔
804
                ep.EndpointGroup = epGroup.Name
×
805
        }
×
806
        ep.SecurityGroup = epSecGroups
1✔
807
        ep.QosPolicy = epQosPolicy
1✔
808
        return nil
1✔
809
}
810

811
func (agent *HostAgent) epChanged(epUuid *string, epMetaKey *string, epGroup *metadata.OpflexGroup,
812
        epSecGroups []metadata.OpflexGroup, epQosPolicy metadata.OpflexGroup, epAttributes map[string]string,
813
        logger *logrus.Entry) {
1✔
814
        if logger == nil {
2✔
815
                logger = agent.log.WithFields(logrus.Fields{})
1✔
816
        }
1✔
817
        if agent.config.ChainedMode {
1✔
818
                return
×
819
        }
×
820
        logger.Debug("epChanged...")
1✔
821
        epmetadata, ok := agent.epMetadata[*epMetaKey]
1✔
822
        if !ok {
2✔
823
                logger.Debug("No metadata found for ep: ")
1✔
824
                delete(agent.opflexEps, *epUuid)
1✔
825
                agent.log.Debug("syncEP scheduled")
1✔
826
                agent.scheduleSyncEps()
1✔
827
                return
1✔
828
        }
1✔
829

830
        var neweps []*opflexEndpoint
1✔
831

1✔
832
        for _, epmeta := range epmetadata {
2✔
833
                for _, iface := range epmeta.Ifaces {
2✔
834
                        patchIntName, patchAccessName :=
1✔
835
                                metadata.GetIfaceNames(iface.HostVethName)
1✔
836

1✔
837
                        ips := make([]string, 0)
1✔
838
                        for _, ip := range iface.IPs {
2✔
839
                                if ip.Address.IP == nil {
1✔
840
                                        continue
×
841
                                }
842
                                ips = append(ips, ip.Address.IP.String())
1✔
843
                        }
844

845
                        epidstr := *epUuid + "_" + epmeta.Id.ContId + "_" + iface.HostVethName
1✔
846
                        ep := &opflexEndpoint{
1✔
847
                                Uuid:              epidstr,
1✔
848
                                MacAddress:        iface.Mac,
1✔
849
                                IpAddress:         ips,
1✔
850
                                AccessIface:       iface.HostVethName,
1✔
851
                                AccessUplinkIface: patchAccessName,
1✔
852
                                IfaceName:         patchIntName,
1✔
853
                        }
1✔
854

1✔
855
                        ep.Attributes = make(map[string]string)
1✔
856
                        for k, v := range epAttributes {
2✔
857
                                ep.Attributes[k] = v
1✔
858
                        }
1✔
859

860
                        ep.Attributes["interface-name"] = iface.HostVethName
1✔
861
                        if epGroup.Tenant != "" {
2✔
862
                                ep.EgPolicySpace = epGroup.Tenant
1✔
863
                        } else {
2✔
864
                                ep.EgPolicySpace = epGroup.PolicySpace
1✔
865
                        }
1✔
866
                        if epGroup.AppProfile != "" {
2✔
867
                                ep.EndpointGroup = epGroup.AppProfile + "|" + epGroup.Name
1✔
868
                        } else {
2✔
869
                                ep.EndpointGroup = epGroup.Name
1✔
870
                        }
1✔
871
                        ep.SecurityGroup = epSecGroups
1✔
872
                        ep.QosPolicy = epQosPolicy
1✔
873

1✔
874
                        neweps = append(neweps, ep)
1✔
875
                }
876
        }
877

878
        existing, ok := agent.opflexEps[*epUuid]
1✔
879
        for _, ep := range existing {
2✔
880
                for _, newep := range neweps {
2✔
881
                        if ep.Uuid == newep.Uuid {
2✔
882
                                newep.registered = ep.registered
1✔
883
                        }
1✔
884
                }
885
        }
886

887
        if (ok && !reflect.DeepEqual(existing, neweps)) || !ok {
2✔
888
                logger.WithFields(logrus.Fields{
1✔
889
                        "id": *epMetaKey,
1✔
890
                        "ep": neweps,
1✔
891
                }).Debug("Updated endpoints for pod")
1✔
892
                logger.Infof("EP updated: %+v", neweps[0])
1✔
893
                agent.log.Debug("syncEP scheduled")
1✔
894

1✔
895
                agent.opflexEps[*epUuid] = neweps
1✔
896
                agent.scheduleSyncEps()
1✔
897
        }
1✔
898
}
899

900
func (agent *HostAgent) epDeleted(epUuid *string) {
1✔
901
        if _, ok := agent.opflexEps[*epUuid]; ok {
1✔
902
                delete(agent.opflexEps, *epUuid)
×
903
                agent.log.Debug("syncEP scheduled")
×
904
                agent.scheduleSyncEps()
×
905
        }
×
906
}
907

908
func (agent *HostAgent) podDeleted(obj interface{}) {
1✔
909
        pod, isPod := obj.(*v1.Pod)
1✔
910
        if !isPod {
2✔
911
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
1✔
912
                if !ok {
2✔
913
                        agent.log.Error("Received unexpected object: ", obj)
1✔
914
                        return
1✔
915
                }
1✔
916
                pod, ok = deletedState.Obj.(*v1.Pod)
1✔
917
                if !ok {
2✔
918
                        agent.log.Error("DeletedFinalStateUnknown contained non-Pod object: ", deletedState.Obj)
1✔
919
                        return
1✔
920
                }
1✔
921
        }
922
        agent.log.Infof("Pod deleted: name %s namespace %s", pod.ObjectMeta.Name, pod.ObjectMeta.Namespace)
1✔
923
        podns, podname := pod.ObjectMeta.Namespace, pod.ObjectMeta.Name
1✔
924
        podid := podns + "/" + podname
1✔
925
        mdmap, ok := agent.epMetadata[podid]
1✔
926
        if ok {
2✔
927
                for contid, v := range mdmap {
2✔
928
                        metadata := cnimeta.ContainerMetadata{
1✔
929
                                Id: cnimeta.ContainerId{
1✔
930
                                        ContId:    contid,
1✔
931
                                        Namespace: podns,
1✔
932
                                        Pod:       podname,
1✔
933
                                },
1✔
934
                                Network: cnimeta.ContainerNetworkMetadata{
1✔
935
                                        NetworkName: v.Network.NetworkName,
1✔
936
                                        ChainedMode: agent.config.ChainedMode,
1✔
937
                                },
1✔
938
                        }
1✔
939
                        err := agent.unconfigureContainerIfaces(&metadata)
1✔
940
                        if err != nil {
2✔
941
                                agent.log.Warnf("Could not unconfigure container:%s, %s ", contid, err)
1✔
942
                        }
1✔
943
                }
944
        }
945
        agent.indexMutex.Lock()
1✔
946
        defer agent.indexMutex.Unlock()
1✔
947
        agent.podDeletedLocked(obj)
1✔
948
        agent.depPods.DeletePod(obj.(*v1.Pod))
1✔
949
        agent.rcPods.DeletePod(obj.(*v1.Pod))
1✔
950
        if !agent.config.ChainedMode {
2✔
951
                agent.qosPolPods.DeletePod(obj.(*v1.Pod))
1✔
952
        }
1✔
953
        agent.netPolPods.DeletePod(obj.(*v1.Pod))
1✔
954
        if !agent.config.ChainedMode {
2✔
955
                agent.handleObjectDeleteForSnat(obj)
1✔
956
        }
1✔
957
}
958

959
func (agent *HostAgent) podDeletedLocked(obj interface{}) {
1✔
960
        pod := obj.(*v1.Pod)
1✔
961
        u := string(pod.ObjectMeta.UID)
1✔
962
        if _, ok := agent.opflexEps[u]; ok {
2✔
963
                agent.log.Infof("podDeletedLocked: delete %s/%s", pod.ObjectMeta.Namespace, pod.ObjectMeta.Name)
1✔
964
                delete(agent.opflexEps, u)
1✔
965
                agent.log.Debug("syncEP scheduled")
1✔
966
                agent.scheduleSyncEps()
1✔
967
        }
1✔
968
        if pod.Status.PodIP != "" {
1✔
969
                delete(agent.podIpToName, pod.Status.PodIP)
×
970
        }
×
971
        delete(agent.podUidToName, u)
1✔
972
        agent.epDeleted(&u)
1✔
973
}
974

975
func (agent *HostAgent) cniEpDelete(cniKey string) {
1✔
976
        agent.indexMutex.Lock()
1✔
977
        defer agent.indexMutex.Unlock()
1✔
978

1✔
979
        epUuid, ok := agent.cniToPodID[cniKey]
1✔
980
        if !ok {
2✔
981
                agent.log.Warnf("cniEpDelete: PodID not found for %s", cniKey)
1✔
982
                return
1✔
983
        }
1✔
984
        delete(agent.cniToPodID, cniKey)
1✔
985

1✔
986
        if _, ok := agent.opflexEps[epUuid]; ok {
2✔
987
                agent.log.Infof("cniEpDelete: delete %s", cniKey)
1✔
988
                delete(agent.opflexEps, epUuid)
1✔
989
                agent.log.Debug("syncEP scheduled")
1✔
990
                agent.scheduleSyncEps()
1✔
991
        }
1✔
992
}
993

994
func (agent *HostAgent) updateGbpServerInfo(pod *v1.Pod) {
1✔
995
        if pod.ObjectMeta.Labels == nil {
2✔
996
                return
1✔
997
        }
1✔
998
        agent.indexMutex.Lock()
1✔
999
        nameVal := pod.ObjectMeta.Labels["name"]
1✔
1000
        if nameVal == "aci-containers-controller" {
1✔
1001
                if agent.gbpServerIP != pod.Status.PodIP {
×
1002
                        agent.log.Infof("gbpServerIPChanged to %s", pod.Status.PodIP)
×
1003
                        agent.gbpServerIP = pod.Status.PodIP
×
1004
                        agent.scheduleSyncOpflexServer()
×
1005
                }
×
1006
        }
1007
        agent.indexMutex.Unlock()
1✔
1008
}
1009

1010
func formatTimestamps(timestamps []time.Time) string {
1✔
1011
        var formattedTimestamps string
1✔
1012
        for i, timestamp := range timestamps {
2✔
1013
                if i > 0 {
2✔
1014
                        formattedTimestamps += ", "
1✔
1015
                }
1✔
1016
                formattedTimestamps += timestamp.Format("2006-01-02T15:04:05Z")
1✔
1017
        }
1018
        return formattedTimestamps
1✔
1019
}
1020

1021
func formatMapTimestamps(timestamps map[time.Time]string) string {
1✔
1022
        var formattedTimestamps string
1✔
1023
        for key, value := range timestamps {
2✔
1024
                formattedTimestamps += key.Format("2006-01-02T15:04:05Z") + ": " + value + ", "
1✔
1025
        }
1✔
1026

1027
        if len(formattedTimestamps) > 2 {
2✔
1028
                formattedTimestamps = formattedTimestamps[:len(formattedTimestamps)-2]
1✔
1029
        }
1✔
1030
        return formattedTimestamps
1✔
1031
}
1032

1033
func compareOpflexEndpoints(oldEndpoint, newEndpoint *opflexEndpoint) string {
1✔
1034
        var changedFields []string
1✔
1035

1✔
1036
        oldEndpointJSON, _ := json.Marshal(oldEndpoint)
1✔
1037
        newEndpointJSON, _ := json.Marshal(newEndpoint)
1✔
1038

1✔
1039
        var oldMap, newMap map[string]interface{}
1✔
1040
        json.Unmarshal(oldEndpointJSON, &oldMap)
1✔
1041
        json.Unmarshal(newEndpointJSON, &newMap)
1✔
1042

1✔
1043
        for key, oldValue := range oldMap {
2✔
1044
                newValue, exists := newMap[key]
1✔
1045
                if !exists || !reflect.DeepEqual(oldValue, newValue) {
2✔
1046
                        changedFields = append(changedFields, key)
1✔
1047
                }
1✔
1048
        }
1049

1050
        for key := range newMap {
2✔
1051
                if _, exists := oldMap[key]; !exists {
2✔
1052
                        changedFields = append(changedFields, key)
1✔
1053
                }
1✔
1054
        }
1055

1056
        return strings.Join(changedFields, ", ")
1✔
1057
}
1058

1059
func normalizeToMinutes(duration time.Duration) string {
1✔
1060
        return fmt.Sprintf("%.2f min", duration.Minutes())
1✔
1061
}
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