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

noironetworks / aci-containers / 10441

28 Feb 2025 04:14AM UTC coverage: 69.039% (-0.08%) from 69.123%
10441

push

travis-pro

web-flow
Merge pull request #1492 from noironetworks/delete-stale-snatlocalinfo

Delete stale snatlocalinfo CRs

16 of 62 new or added lines in 2 files covered. (25.81%)

4 existing lines in 1 file now uncovered.

13279 of 19234 relevant lines covered (69.04%)

0.79 hits per line

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

65.81
/pkg/apicapi/apicapi.go
1
// Copyright 2017 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
// Interface for connecting to APIC REST API using websockets
16
package apicapi
17

18
import (
19
        "bytes"
20
        "crypto/tls"
21
        "crypto/x509"
22
        "encoding/json"
23
        "errors"
24
        "fmt"
25
        "io"
26
        "net/http"
27
        "net/http/cookiejar"
28
        "regexp"
29
        "sort"
30
        "strconv"
31
        "strings"
32
        "time"
33

34
        "k8s.io/apimachinery/pkg/util/wait"
35
        "k8s.io/client-go/util/workqueue"
36

37
        "github.com/gorilla/websocket"
38
        "github.com/sirupsen/logrus"
39
        "golang.org/x/time/rate"
40
)
41

42
// defaultConnectionRefresh is used as connection refresh interval if
43
// RefreshInterval is set to 0
44
const defaultConnectionRefresh = 30 * time.Second
45

46
// ApicVersion - This global variable to be used when dealing with version-
47
// dependencies during APIC interaction. It gets filled with actual version
48
// as part of runConn()
49
var (
50
        ApicVersion = "3.1"
51
)
52

53
func complete(resp *http.Response) {
1✔
54
        if resp.StatusCode != http.StatusOK {
2✔
55
                rBody, err := io.ReadAll(resp.Body)
1✔
56
                if err != nil {
1✔
57
                        logrus.Errorf("ReadAll :%v", err)
×
58
                } else {
1✔
59
                        logrus.Infof("Resp: %s", rBody)
1✔
60
                }
1✔
61
        }
62
        resp.Body.Close()
1✔
63
}
64

65
// Yes, this is really stupid, but this is really how this works
66
func (conn *ApicConnection) sign(req *http.Request, uri string, body []byte) {
1✔
67
        if conn.signer == nil {
2✔
68
                return
1✔
69
        }
1✔
70

71
        sig, err := conn.signer.sign(req.Method, uri, body)
1✔
72
        if err != nil {
1✔
73
                conn.log.Error("Failed to sign request: ", err)
×
74
                return
×
75
        }
×
76

77
        req.Header.Set("Cookie", conn.apicSigCookie(sig, conn.token))
1✔
78
}
79

80
func (conn *ApicConnection) apicSigCookie(sig, token string) string {
1✔
81
        tokc := ""
1✔
82
        if token != "" {
2✔
83
                tokc = "; APIC-WebSocket-Session=" + token
1✔
84
        }
1✔
85
        return fmt.Sprintf("APIC-Request-Signature=%s; "+
1✔
86
                "APIC-Certificate-Algorithm=v1.0; "+
1✔
87
                "APIC-Certificate-DN=uni/userext/user-%s/usercert-%s.crt; "+
1✔
88
                "APIC-Certificate-Fingerprint=fingerprint%s",
1✔
89
                sig, conn.user, conn.user, tokc)
1✔
90
}
91

92
func (conn *ApicConnection) login() (string, error) {
1✔
93
        var path string
1✔
94
        var method string
1✔
95

1✔
96
        if conn.signer == nil {
2✔
97
                path = "aaaLogin"
1✔
98
                method = "POST"
1✔
99
        } else {
2✔
100
                path = "webtokenSession"
1✔
101
                method = "GET"
1✔
102
        }
1✔
103
        uri := fmt.Sprintf("/api/%s.json", path)
1✔
104
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
105

1✔
106
        var reqBody io.Reader
1✔
107
        var raw []byte
1✔
108
        var err error
1✔
109
        if conn.signer == nil {
2✔
110
                login := &ApicObject{
1✔
111
                        "aaaUser": &ApicObjectBody{
1✔
112
                                Attributes: map[string]interface{}{
1✔
113
                                        "name": conn.user,
1✔
114
                                        "pwd":  conn.password,
1✔
115
                                },
1✔
116
                        },
1✔
117
                }
1✔
118
                raw, err = json.Marshal(login)
1✔
119
                if err != nil {
1✔
120
                        return "", err
×
121
                }
×
122
                reqBody = bytes.NewBuffer(raw)
1✔
123
        }
124
        req, err := http.NewRequest(method, url, reqBody)
1✔
125
        if err != nil {
1✔
126
                return "", err
×
127
        }
×
128
        conn.log.Infof("Req: %+v", req)
1✔
129
        conn.sign(req, uri, raw)
1✔
130
        req.Header.Set("Content-Type", "application/json")
1✔
131
        resp, err := conn.client.Do(req)
1✔
132
        if err != nil {
1✔
133
                return "", err
×
134
        }
×
135
        defer complete(resp)
1✔
136

1✔
137
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
138
                conn.logErrorResp("Error while logging into APIC", resp)
1✔
139
                return "", errors.New("Server returned error status")
1✔
140
        }
1✔
141

142
        var apicresp ApicResponse
1✔
143
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
144
        if err != nil {
1✔
145
                return "", err
×
146
        }
×
147

148
        for _, obj := range apicresp.Imdata {
2✔
149
                lresp, ok := obj["aaaLogin"]
1✔
150
                if !ok {
2✔
151
                        lresp, ok = obj["webtokenSession"]
1✔
152
                        if !ok {
1✔
153
                                continue
×
154
                        }
155
                }
156

157
                token, ok := lresp.Attributes["token"]
1✔
158
                if !ok {
1✔
159
                        return "", errors.New("Token not found in login response")
×
160
                }
×
161
                stoken, isStr := token.(string)
1✔
162
                if !isStr {
1✔
163
                        return "", errors.New("Token is not a string")
×
164
                }
×
165
                return stoken, nil
1✔
166
        }
167
        return "", errors.New("Login response not found")
×
168
}
169

170
func configureTls(cert []byte) (*tls.Config, error) {
1✔
171
        if cert == nil {
1✔
172
                return &tls.Config{InsecureSkipVerify: true}, nil
×
173
        }
×
174
        pool := x509.NewCertPool()
1✔
175
        if !pool.AppendCertsFromPEM(cert) {
1✔
176
                return nil, errors.New("Could not load CA certificates")
×
177
        }
×
178
        return &tls.Config{RootCAs: pool}, nil
1✔
179
}
180

181
func New(log *logrus.Logger, apic []string, user string,
182
        password string, privKey []byte, cert []byte,
183
        prefix string, refresh int, refreshTickerAdjust int,
184
        subscriptionDelay int, vrfTenant string, lldpIfHldr func(dn, lldpIf string) bool) (*ApicConnection, error) {
1✔
185
        tls, err := configureTls(cert)
1✔
186
        if err != nil {
1✔
187
                return nil, err
×
188
        }
×
189

190
        var signer *signer
1✔
191
        if privKey != nil {
2✔
192
                signer, err = newSigner(privKey)
1✔
193
                if err != nil {
1✔
194
                        return nil, err
×
195
                }
×
196
        }
197

198
        dialer := &websocket.Dialer{
1✔
199
                TLSClientConfig: tls,
1✔
200
        }
1✔
201
        tr := &http.Transport{
1✔
202
                Proxy:           http.ProxyFromEnvironment,
1✔
203
                TLSClientConfig: dialer.TLSClientConfig,
1✔
204
        }
1✔
205
        jar, err := cookiejar.New(nil)
1✔
206
        if err != nil {
1✔
207
                return nil, err
×
208
        }
×
209
        client := &http.Client{
1✔
210
                Transport: tr,
1✔
211
                Jar:       jar,
1✔
212
                Timeout:   5 * time.Minute,
1✔
213
        }
1✔
214

1✔
215
        conn := &ApicConnection{
1✔
216
                ReconnectInterval:   time.Duration(5) * time.Second,
1✔
217
                ReconnectRetryLimit: 5,
1✔
218
                RefreshInterval:     time.Duration(refresh) * time.Second,
1✔
219
                RefreshTickerAdjust: time.Duration(refreshTickerAdjust) * time.Second,
1✔
220
                SubscriptionDelay:   time.Duration(subscriptionDelay) * time.Millisecond,
1✔
221
                SyncDone:            false,
1✔
222
                signer:              signer,
1✔
223
                dialer:              dialer,
1✔
224
                logger:              log,
1✔
225
                log:                 log.WithField("mod", "APICAPI"),
1✔
226
                Apic:                apic,
1✔
227
                user:                user,
1✔
228
                password:            password,
1✔
229
                prefix:              prefix,
1✔
230
                client:              client,
1✔
231
                vrfTenant:           vrfTenant,
1✔
232
                lldpIfHldr:          lldpIfHldr,
1✔
233
                subscriptions: subIndex{
1✔
234
                        subs: make(map[string]*subscription),
1✔
235
                        ids:  make(map[string]string),
1✔
236
                },
1✔
237
                desiredState:       make(map[string]ApicSlice),
1✔
238
                desiredStateDn:     make(map[string]ApicObject),
1✔
239
                keyHashes:          make(map[string]string),
1✔
240
                containerDns:       make(map[string]bool),
1✔
241
                cachedState:        make(map[string]ApicSlice),
1✔
242
                cacheDnSubIds:      make(map[string]map[string]bool),
1✔
243
                pendingSubDnUpdate: make(map[string]pendingChange),
1✔
244
                CachedSubnetDns:    make(map[string]string),
1✔
245
                cachedLLDPIfs:      make(map[string]string),
1✔
246
        }
1✔
247
        return conn, nil
1✔
248
}
249

250
func (conn *ApicConnection) handleSocketUpdate(apicresp *ApicResponse) {
1✔
251
        var subIds []string
1✔
252
        switch ids := apicresp.SubscriptionId.(type) {
1✔
253
        case string:
×
254
                subIds = append(subIds, ids)
×
255
        case []interface{}:
1✔
256
                for _, id := range ids {
2✔
257
                        subIds = append(subIds, id.(string))
1✔
258
                }
1✔
259
        }
260

261
        nameAttrClass := map[string]bool{"vnsLDevVip": true, "vnsAbsGraph": true, "vzFilter": true, "vzBrCP": true, "l3extInstP": true, "vnsSvcRedirectPol": true, "vnsRedirectHealthGroup": true, "fvIPSLAMonitoringPol": true}
1✔
262

1✔
263
        for _, obj := range apicresp.Imdata {
2✔
264
                for key, body := range obj {
2✔
265
                        if dn, ok := body.Attributes["dn"].(string); ok {
2✔
266
                                if status, isStr := body.Attributes["status"].(string); isStr {
2✔
267
                                        dnSlice := strings.Split(dn, "/")
1✔
268
                                        if len(dnSlice) > 1 && strings.Contains(dnSlice[1], conn.vrfTenant) {
2✔
269
                                                var attr string
1✔
270
                                                if nameAttrClass[key] {
1✔
271
                                                        _, ok := body.Attributes["name"]
×
272
                                                        if ok {
×
273
                                                                attr = body.Attributes["name"].(string)
×
274
                                                        }
×
275
                                                } else if key == "tagAnnotation" {
1✔
276
                                                        _, ok := body.Attributes["value"]
×
277
                                                        if ok {
×
278
                                                                attr = body.Attributes["value"].(string)
×
279
                                                        }
×
280
                                                }
281
                                                if attr != "" && !strings.Contains(attr, conn.prefix) {
1✔
282
                                                        conn.log.Debug("Skipping websocket notification for :", dn)
×
283
                                                        continue
×
284
                                                }
285
                                        }
286
                                        var pendingKind int
1✔
287
                                        if status == "deleted" {
2✔
288
                                                pendingKind = pendingChangeDelete
1✔
289
                                        } else {
2✔
290
                                                pendingKind = pendingChangeUpdate
1✔
291
                                        }
1✔
292
                                        conn.indexMutex.Lock()
1✔
293

1✔
294
                                        conn.logger.WithFields(logrus.Fields{
1✔
295
                                                "mod": "APICAPI",
1✔
296
                                                "dn":  obj.GetDn(),
1✔
297
                                                "obj": obj,
1✔
298
                                        }).Debug("Processing websocket notification for:")
1✔
299

1✔
300
                                        conn.pendingSubDnUpdate[dn] = pendingChange{
1✔
301
                                                kind:    pendingKind,
1✔
302
                                                subIds:  subIds,
1✔
303
                                                isDirty: false,
1✔
304
                                        }
1✔
305
                                        if key == "opflexODev" && conn.odevQueue != nil {
2✔
306
                                                conn.log.Debug("Adding dn to odevQueue: ", dn)
1✔
307
                                                conn.odevQueue.Add(dn)
1✔
308
                                        } else if isPriorityObject(dn) {
2✔
309
                                                conn.log.Debug("Adding dn to priorityQueue: ", dn)
×
310
                                                conn.priorityQueue.Add(dn)
×
311
                                        } else if isLLDPIfObject(dn) && conn.lldpIfQueue != nil {
1✔
312
                                                if lldpIf, ok := body.Attributes["portDesc"].(string); ok {
×
313
                                                        conn.cachedLLDPIfs[dn] = lldpIf
×
314
                                                }
×
315
                                                conn.log.Debug("Adding dn to lldpIfQueue: ", dn)
×
316
                                                conn.lldpIfQueue.Add(dn)
×
317
                                        } else if conn.deltaQueue != nil {
2✔
318
                                                conn.deltaQueue.Add(dn)
1✔
319
                                        }
1✔
320
                                        conn.indexMutex.Unlock()
1✔
321
                                }
322
                        }
323
                }
324
        }
325
}
326

327
func (conn *ApicConnection) restart() {
1✔
328
        conn.indexMutex.Lock()
1✔
329
        if conn.restartCh != nil {
2✔
330
                conn.log.Debug("Restarting connection")
1✔
331
                close(conn.restartCh)
1✔
332
                conn.restartCh = nil
1✔
333
        }
1✔
334
        conn.indexMutex.Unlock()
1✔
335
}
336

337
func (conn *ApicConnection) handleQueuedDn(dn string) bool {
1✔
338
        var respClasses []string
1✔
339
        var updateHandlers []ApicObjectHandler
1✔
340
        var deleteHandlers []ApicDnHandler
1✔
341
        var rootDn string
1✔
342

1✔
343
        handleId := func(id string) {
2✔
344
                conn.indexMutex.Lock()
1✔
345
                if value, ok := conn.subscriptions.ids[id]; ok {
2✔
346
                        if sub, ok := conn.subscriptions.subs[value]; ok {
2✔
347
                                if subComp, ok := sub.childSubs[id]; ok {
1✔
348
                                        respClasses =
×
349
                                                append(respClasses, subComp.respClasses...)
×
350
                                } else {
1✔
351
                                        respClasses =
1✔
352
                                                append(respClasses, sub.respClasses...)
1✔
353
                                }
1✔
354
                                if sub.updateHook != nil {
2✔
355
                                        updateHandlers = append(updateHandlers, sub.updateHook)
1✔
356
                                }
1✔
357
                                if sub.deleteHook != nil {
2✔
358
                                        deleteHandlers = append(deleteHandlers, sub.deleteHook)
1✔
359
                                }
1✔
360

361
                                if sub.kind == apicSubTree {
1✔
362
                                        rootDn = getRootDn(dn, value)
×
363
                                }
×
364
                        }
365
                } else {
×
366
                        conn.log.Warning("Unexpected subscription: ", id)
×
367
                }
×
368
                conn.indexMutex.Unlock()
1✔
369
        }
370

371
        var requeue bool
1✔
372
        conn.indexMutex.Lock()
1✔
373
        pending, hasPendingChange := conn.pendingSubDnUpdate[dn]
1✔
374
        conn.pendingSubDnUpdate[dn] = pendingChange{isDirty: true}
1✔
375
        obj, hasDesiredState := conn.desiredStateDn[dn]
1✔
376
        conn.indexMutex.Unlock()
1✔
377

1✔
378
        if hasPendingChange {
2✔
379
                for _, id := range pending.subIds {
2✔
380
                        handleId(id)
1✔
381
                }
1✔
382
        }
383

384
        if rootDn == "" {
2✔
385
                rootDn = dn
1✔
386
        }
1✔
387

388
        if hasDesiredState {
2✔
389
                if hasPendingChange {
2✔
390
                        if pending.kind == pendingChangeDelete {
2✔
391
                                conn.logger.WithFields(logrus.Fields{"mod": "APICAPI", "DN": dn}).
1✔
392
                                        Warning("Restoring unexpectedly deleted" +
1✔
393
                                                " ACI object")
1✔
394
                                requeue = conn.postDn(dn, obj)
1✔
395
                        } else {
2✔
396
                                conn.log.Debug("getSubtreeDn for:", rootDn)
1✔
397
                                conn.getSubtreeDn(rootDn, respClasses, updateHandlers)
1✔
398
                        }
1✔
399
                } else {
1✔
400
                        requeue = conn.postDn(dn, obj)
1✔
401
                }
1✔
402
        } else {
1✔
403
                if hasPendingChange {
2✔
404
                        if pending.kind == pendingChangeDelete {
2✔
405
                                for _, handler := range deleteHandlers {
2✔
406
                                        handler(dn)
1✔
407
                                }
1✔
408
                        }
409

410
                        if (pending.kind != pendingChangeDelete) || (dn != rootDn) {
2✔
411
                                conn.log.Debug("getSubtreeDn for:", rootDn)
1✔
412
                                conn.getSubtreeDn(rootDn, respClasses, updateHandlers)
1✔
413
                        }
1✔
414
                } else {
1✔
415
                        requeue = conn.Delete(dn)
1✔
416
                }
1✔
417
        }
418

419
        return requeue
1✔
420
}
421

422
func (conn *ApicConnection) processQueue(queue workqueue.RateLimitingInterface,
423
        queueStop <-chan struct{}, name string) {
1✔
424
        go wait.Until(func() {
2✔
425
                conn.log.Debug("Running processQueue for queue ", name)
1✔
426
                for {
2✔
427
                        dn, quit := queue.Get()
1✔
428
                        if quit {
2✔
429
                                break
1✔
430
                        }
431
                        conn.log.Debug("Processing queue for:", dn)
1✔
432
                        var requeue bool
1✔
433
                        if dn, ok := dn.(string); ok {
2✔
434
                                requeue = conn.handleQueuedDn(dn)
1✔
435
                        }
1✔
436
                        if requeue {
1✔
437
                                queue.AddRateLimited(dn)
×
438
                        } else {
1✔
439
                                conn.indexMutex.Lock()
1✔
440
                                if conn.pendingSubDnUpdate[dn.(string)].isDirty {
2✔
441
                                        delete(conn.pendingSubDnUpdate, dn.(string))
1✔
442
                                }
1✔
443
                                conn.indexMutex.Unlock()
1✔
444
                                queue.Forget(dn)
1✔
445
                        }
446
                        queue.Done(dn)
1✔
447
                }
448
        }, time.Second, queueStop)
449
        <-queueStop
1✔
450
        queue.ShutDown()
1✔
451
}
452

453
func (conn *ApicConnection) processLLDPIfQueue(queue workqueue.RateLimitingInterface,
454
        handler func(dn, lldpIf string) bool, stopCh <-chan struct{}) {
1✔
455
        go wait.Until(func() {
2✔
456
                for {
2✔
457
                        key, quit := queue.Get()
1✔
458
                        if quit {
2✔
459
                                break
1✔
460
                        }
461
                        var requeue bool
×
462
                        switch key := key.(type) {
×
463
                        case chan struct{}:
×
464
                                close(key)
×
465
                        case string:
×
466
                                if handler != nil {
×
467
                                        if lldpIf, ok := conn.cachedLLDPIfs[key]; ok {
×
468
                                                requeue = handler(key, lldpIf)
×
469
                                        }
×
470
                                }
471
                        }
472
                        if requeue {
×
473
                                queue.AddRateLimited(key)
×
474
                        } else {
×
475
                                queue.Forget(key)
×
476
                        }
×
477
                        queue.Done(key)
×
478

479
                }
480
        }, time.Second, stopCh)
481
        <-stopCh
1✔
482
        queue.ShutDown()
1✔
483
}
484

485
type fullSync struct{}
486

487
func (conn *ApicConnection) UnsubscribeImmediateDnLocked(dn string,
488
        targetClasses []string) {
×
489
        // Post local delete, subscription will not be refreshed
×
490
        // after refresh time-out
×
491
        delete(conn.subscriptions.subs, dn)
×
492
}
×
493

494
func (conn *ApicConnection) AddImmediateSubscriptionDnLocked(dn string,
495
        targetClasses []string, updateHook ApicObjectHandler, deleteHook ApicDnHandler) bool {
×
496
        conn.logger.WithFields(logrus.Fields{
×
497
                "mod": "APICAPI",
×
498
                "dn":  dn,
×
499
        }).Debug("Adding Subscription for Dn")
×
500

×
501
        conn.subscriptions.subs[dn] = &subscription{
×
502
                kind:          apicSubDn,
×
503
                childSubs:     make(map[string]subComponent),
×
504
                targetClasses: targetClasses,
×
505
                respClasses:   computeRespClasses(targetClasses),
×
506
        }
×
507
        if updateHook != nil {
×
508
                conn.subscriptions.subs[dn].updateHook = updateHook
×
509
        }
×
510
        if deleteHook != nil {
×
511
                conn.subscriptions.subs[dn].deleteHook = deleteHook
×
512
        }
×
513
        if conn.connection != nil {
×
514
                return conn.subscribe(dn, conn.subscriptions.subs[dn], true)
×
515
        } else {
×
516
                return false
×
517
        }
×
518
}
519

520
func (conn *ApicConnection) runConn(stopCh <-chan struct{}) {
1✔
521
        done := make(chan struct{})
1✔
522
        restart := make(chan struct{})
1✔
523
        queueStop := make(chan struct{})
1✔
524
        odevQueueStop := make(chan struct{})
1✔
525
        priorityQueueStop := make(chan struct{})
1✔
526
        syncHook := make(chan fullSync, 1)
1✔
527
        conn.restartCh = restart
1✔
528

1✔
529
        go func() {
2✔
530
                defer conn.connection.Close()
1✔
531
                defer close(done)
1✔
532

1✔
533
                for {
2✔
534
                        var apicresp ApicResponse
1✔
535
                        err := conn.connection.ReadJSON(&apicresp)
1✔
536
                        var closeErr *websocket.CloseError
1✔
537
                        if errors.As(err, &closeErr) {
1✔
538
                                conn.log.Info("Websocket connection closed: ", closeErr.Code)
×
539
                                conn.restart()
×
540
                                break
×
541
                        } else if err != nil {
2✔
542
                                conn.log.Error("Could not read web socket message:", err)
1✔
543
                                conn.restart()
1✔
544
                                break
1✔
545
                        } else {
1✔
546
                                conn.handleSocketUpdate(&apicresp)
1✔
547
                        }
1✔
548
                }
549
        }()
550

551
        conn.indexMutex.Lock()
1✔
552
        oldState := conn.cacheDnSubIds
1✔
553
        conn.cachedState = make(map[string]ApicSlice)
1✔
554
        conn.cacheDnSubIds = make(map[string]map[string]bool)
1✔
555
        conn.deltaQueue = workqueue.NewNamedRateLimitingQueue(
1✔
556
                workqueue.NewMaxOfRateLimiter(
1✔
557
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
558
                                10*time.Second),
1✔
559
                        &workqueue.BucketRateLimiter{
1✔
560
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
561
                        },
1✔
562
                ),
1✔
563
                "delta")
1✔
564
        go conn.processQueue(conn.deltaQueue, queueStop, "delta")
1✔
565
        conn.odevQueue = workqueue.NewNamedRateLimitingQueue(
1✔
566
                workqueue.NewMaxOfRateLimiter(
1✔
567
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
568
                                10*time.Second),
1✔
569
                        &workqueue.BucketRateLimiter{
1✔
570
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
571
                        },
1✔
572
                ),
1✔
573
                "odev")
1✔
574
        go conn.processQueue(conn.odevQueue, odevQueueStop, "odev")
1✔
575
        conn.priorityQueue = workqueue.NewNamedRateLimitingQueue(
1✔
576
                workqueue.NewMaxOfRateLimiter(
1✔
577
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
578
                                10*time.Second),
1✔
579
                        &workqueue.BucketRateLimiter{
1✔
580
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
581
                        },
1✔
582
                ),
1✔
583
                "priority")
1✔
584
        go conn.processQueue(conn.priorityQueue, priorityQueueStop, "priority")
1✔
585
        conn.lldpIfQueue = workqueue.NewNamedRateLimitingQueue(
1✔
586
                workqueue.NewMaxOfRateLimiter(
1✔
587
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
588
                                10*time.Second),
1✔
589
                        &workqueue.BucketRateLimiter{
1✔
590
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
591
                        },
1✔
592
                ),
1✔
593
                "lldpIf")
1✔
594
        go conn.processLLDPIfQueue(conn.lldpIfQueue,
1✔
595
                conn.lldpIfHldr, stopCh)
1✔
596
        conn.indexMutex.Unlock()
1✔
597

1✔
598
        refreshInterval := conn.RefreshInterval
1✔
599
        if refreshInterval == 0 {
1✔
600
                refreshInterval = defaultConnectionRefresh
×
601
        }
×
602
        // Adjust refreshTickerInterval.
603
        // To refresh the subscriptions early than actual refresh timeout value
604
        refreshTickerInterval := refreshInterval - conn.RefreshTickerAdjust
1✔
605
        refreshTicker := time.NewTicker(refreshTickerInterval)
1✔
606
        defer refreshTicker.Stop()
1✔
607

1✔
608
        var hasErr bool
1✔
609
        for value, subscription := range conn.subscriptions.subs {
2✔
610
                if !(conn.subscribe(value, subscription, false)) {
1✔
611
                        hasErr = true
×
612
                        conn.restart()
×
613
                        break
×
614
                }
615
        }
616
        if !hasErr {
2✔
617
                conn.checkDeletes(oldState)
1✔
618
                go func() {
2✔
619
                        if conn.FullSyncHook != nil {
1✔
620
                                conn.FullSyncHook()
×
621
                        }
×
622
                        syncHook <- fullSync{}
1✔
623
                }()
624
        }
625

626
        // Get APIC version if connection restarts
627
        if conn.version == "" && conn.checkVersion {
1✔
628
                go func() {
×
629
                        version, err := conn.GetVersion()
×
630
                        if err != nil {
×
631
                                conn.log.Error("Error while getting APIC version: ", err, " Restarting connection...")
×
632
                                conn.restart()
×
633
                        } else {
×
634
                                conn.log.Debug("Cached version:", conn.CachedVersion, " New version:", version)
×
635
                                if ApicVersion != version {
×
636
                                        ApicVersion = version
×
637
                                        if ApicVersion >= "6.0(4c)" {
×
638
                                                metadata["fvBD"].attributes["serviceBdRoutingDisable"] = "no"
×
639
                                        } else {
×
640
                                                delete(metadata["fvBD"].attributes, "serviceBdRoutingDisable")
×
641
                                        }
×
642
                                        conn.VersionUpdateHook()
×
643
                                }
644
                                conn.CachedVersion = version
×
645
                        }
646
                }()
647
        }
648

649
        closeConn := func(stop bool) {
2✔
650
                close(queueStop)
1✔
651
                close(odevQueueStop)
1✔
652

1✔
653
                conn.indexMutex.Lock()
1✔
654
                conn.deltaQueue = nil
1✔
655
                conn.odevQueue = nil
1✔
656
                conn.priorityQueue = nil
1✔
657
                conn.lldpIfQueue = nil
1✔
658
                conn.stopped = stop
1✔
659
                conn.syncEnabled = false
1✔
660
                conn.subscriptions.ids = make(map[string]string)
1✔
661
                conn.version = ""
1✔
662
                conn.indexMutex.Unlock()
1✔
663

1✔
664
                conn.log.Debug("Shutting down web socket")
1✔
665
                err := conn.connection.WriteMessage(websocket.CloseMessage,
1✔
666
                        websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
1✔
667
                if err != nil {
1✔
668
                        conn.log.Error("Error while closing socket: ", err)
×
669
                } else {
1✔
670
                        select {
1✔
671
                        case <-done:
1✔
672
                        case <-time.After(time.Second):
×
673
                        }
674
                }
675
                conn.connection.Close()
1✔
676
        }
677

678
loop:
1✔
679
        for {
2✔
680
                select {
1✔
681
                case <-syncHook:
1✔
682
                        conn.fullSync()
1✔
683
                case <-refreshTicker.C:
1✔
684
                        conn.refresh()
1✔
685
                case <-restart:
1✔
686
                        closeConn(false)
1✔
687
                        break loop
1✔
688
                case <-stopCh:
1✔
689
                        closeConn(true)
1✔
690
                        break loop
1✔
691
                }
692
        }
693

694
        conn.log.Debug("Exiting websocket handler")
1✔
695
}
696

697
// This function should only to be called before we make the first connection to APIC.
698
// Use the cached Apic version when determining the version elsewhere. This can lead to inconsistent tokens.
699
func (conn *ApicConnection) GetVersion() (string, error) {
1✔
700
        versionMo := "firmwareCtrlrRunning"
1✔
701

1✔
702
        if len(conn.Apic) == 0 {
1✔
703
                return "", errors.New("No APIC configuration")
×
704
        }
×
705

706
        conn.checkVersion = true // enable version check on websocket reconnect
1✔
707
        // To Handle unit-tests
1✔
708
        if strings.Contains(conn.Apic[conn.ApicIndex], "127.0.0.1") {
2✔
709
                conn.version = "4.2(4i)"
1✔
710
                conn.SnatPbrFltrChain = true
1✔
711
                conn.log.Debug("Returning APIC version 4.2(4i) for test server")
1✔
712
                return conn.version, nil
1✔
713
        }
1✔
714

715
        uri := fmt.Sprintf("/api/node/class/%s.json?&", versionMo)
×
716
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
717

×
718
        retries := 0
×
719
        for conn.version == "" {
×
720
                if retries <= conn.ReconnectRetryLimit {
×
721
                        // Wait before Retry.
×
722
                        time.Sleep(conn.ReconnectInterval)
×
723
                        retries++
×
724
                } else {
×
725
                        return "", fmt.Errorf("Failed to get APIC version after %d retries", retries)
×
726
                }
×
727

728
                token, err := conn.login()
×
729
                if err != nil {
×
730
                        conn.log.Error("Failed to log into APIC: ", err)
×
731
                        continue
×
732
                }
733
                conn.token = token
×
734

×
735
                req, err := http.NewRequest("GET", url, http.NoBody)
×
736
                if err != nil {
×
737
                        conn.log.Error("Could not create request:", err)
×
738
                        continue
×
739
                }
740
                conn.sign(req, uri, nil)
×
741
                resp, err := conn.client.Do(req)
×
742
                if err != nil {
×
743
                        conn.log.Error("Could not get response for ", versionMo, ": ", err)
×
744
                        continue
×
745
                }
746
                defer complete(resp)
×
747
                if resp.StatusCode < 200 || resp.StatusCode >= 300 {
×
748
                        conn.logErrorResp("Could not get response for "+versionMo, resp)
×
749
                        conn.log.Debug("Request:", req)
×
750
                        continue
×
751
                }
752

753
                var apicresp ApicResponse
×
754
                err = json.NewDecoder(resp.Body).Decode(&apicresp)
×
755
                if err != nil {
×
756
                        conn.log.Error("Could not parse APIC response: ", err)
×
757
                        continue
×
758
                }
759
                for _, obj := range apicresp.Imdata {
×
760
                        vresp := obj["firmwareCtrlrRunning"]
×
761
                        version, ok := vresp.Attributes["version"]
×
762
                        if !ok {
×
763
                                conn.log.Debug("No version attribute in the response??!")
×
764
                                conn.logger.WithFields(logrus.Fields{
×
765
                                        "mod":                            "APICAPI",
×
766
                                        "firmwareCtrlrRunning":           vresp,
×
767
                                        "firmwareCtrlRunning Attributes": vresp.Attributes,
×
768
                                }).Debug("Response:")
×
769
                        } else {
×
770
                                switch version := version.(type) {
×
771
                                default:
×
772
                                case string:
×
773
                                        version_split := strings.Split(version, "(")
×
774
                                        version_number, err := strconv.ParseFloat(version_split[0], 64)
×
775
                                        conn.log.Info("Actual APIC version:", version, " Stripped out version:", version_number)
×
776
                                        if err == nil {
×
777
                                                conn.version = version //return the actual version
×
778
                                        }
×
779
                                }
780
                        }
781
                }
782
        }
783
        return conn.version, nil
×
784
}
785

786
func (conn *ApicConnection) Run(stopCh <-chan struct{}) {
1✔
787
        if len(conn.Apic) == 0 {
1✔
788
                conn.log.Warning("APIC connection not configured")
×
789
                return
×
790
        }
×
791

792
        if conn.version >= "6.0(4c)" {
1✔
793
                metadata["fvBD"].attributes["serviceBdRoutingDisable"] = "no"
×
794
        }
×
795

796
        for !conn.stopped {
2✔
797
                func() {
2✔
798
                        defer func() {
2✔
799
                                conn.ApicIndex = (conn.ApicIndex + 1) % len(conn.Apic)
1✔
800
                                time.Sleep(conn.ReconnectInterval)
1✔
801
                        }()
1✔
802

803
                        conn.logger.WithFields(logrus.Fields{
1✔
804
                                "mod":  "APICAPI",
1✔
805
                                "host": conn.Apic[conn.ApicIndex],
1✔
806
                        }).Info("Connecting to APIC")
1✔
807

1✔
808
                        for dn := range conn.subscriptions.subs {
2✔
809
                                conn.subscriptions.subs[dn].childSubs = make(map[string]subComponent)
1✔
810
                        }
1✔
811
                        conn.subscriptions.ids = make(map[string]string)
1✔
812

1✔
813
                        token, err := conn.login()
1✔
814
                        if err != nil {
2✔
815
                                conn.log.Error("Failed to log into APIC: ", err)
1✔
816
                                return
1✔
817
                        }
1✔
818
                        conn.token = token
1✔
819

1✔
820
                        uri := fmt.Sprintf("/socket%s", token)
1✔
821
                        url := fmt.Sprintf("wss://%s%s",
1✔
822
                                conn.Apic[conn.ApicIndex], uri)
1✔
823
                        header := make(http.Header)
1✔
824
                        if conn.signer != nil {
2✔
825
                                sig, err := conn.signer.sign("GET", uri, nil)
1✔
826
                                if err != nil {
1✔
827
                                        conn.log.Error("Failed to sign request: ", err)
×
828
                                        return
×
829
                                }
×
830
                                header.Set("Cookie", conn.apicSigCookie(sig, token))
1✔
831
                        }
832

833
                        conn.connection, _, err = conn.dialer.Dial(url, header)
1✔
834
                        if err != nil {
1✔
835
                                conn.log.Error("Failed to open APIC websocket: ", err)
×
836
                                return
×
837
                        }
×
838
                        conn.log.Info("Websocket connected!")
1✔
839
                        conn.runConn(stopCh)
1✔
840
                }()
841
        }
842
}
843

844
func (conn *ApicConnection) refresh() {
1✔
845
        if conn.signer == nil {
2✔
846
                url := fmt.Sprintf("https://%s/api/aaaRefresh.json",
1✔
847
                        conn.Apic[conn.ApicIndex])
1✔
848
                req, err := http.NewRequest("GET", url, http.NoBody)
1✔
849
                if err != nil {
1✔
850
                        conn.log.Error("Could not create request: ", err)
×
851
                        return
×
852
                }
×
853
                resp, err := conn.client.Do(req)
1✔
854
                if err != nil {
1✔
UNCOV
855
                        conn.log.Error("Failed to refresh APIC session: ", err)
×
UNCOV
856
                        conn.restart()
×
UNCOV
857
                        return
×
UNCOV
858
                }
×
859
                if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
860
                        conn.logErrorResp("Error while refreshing login", resp)
1✔
861
                        complete(resp)
1✔
862
                        conn.restart()
1✔
863
                        return
1✔
864
                }
1✔
865
                complete(resp)
1✔
866
                conn.log.Debugf("Refresh: url %v", url)
1✔
867
        }
868

869
        for _, sub := range conn.subscriptions.subs {
2✔
870
                refreshId := func(id string) {
2✔
871
                        uri := fmt.Sprintf("/api/subscriptionRefresh.json?id=%s", id)
1✔
872
                        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
873
                        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
874
                        if err != nil {
1✔
875
                                conn.log.Error("Could not create request: ", err)
×
876
                                return
×
877
                        }
×
878
                        conn.sign(req, uri, nil)
1✔
879
                        resp, err := conn.client.Do(req)
1✔
880
                        if err != nil {
1✔
881
                                conn.log.Error("Failed to refresh APIC subscription: ", err)
×
882
                                conn.restart()
×
883
                                return
×
884
                        }
×
885
                        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
886
                                conn.logErrorResp("Error while refreshing subscription", resp)
1✔
887
                                complete(resp)
1✔
888
                                conn.restart()
1✔
889
                                return
1✔
890
                        }
1✔
891
                        complete(resp)
1✔
892
                        conn.log.Debugf("Refresh sub: url %v", url)
1✔
893
                        time.Sleep(conn.SubscriptionDelay)
1✔
894
                }
895
                if len(sub.childSubs) > 0 {
1✔
896
                        for id := range sub.childSubs {
×
897
                                refreshId(id)
×
898
                        }
×
899
                } else {
1✔
900
                        refreshId(sub.id)
1✔
901
                }
1✔
902
        }
903
}
904

905
func (conn *ApicConnection) logErrorResp(message string, resp *http.Response) {
1✔
906
        var apicresp ApicResponse
1✔
907
        err := json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
908
        if err != nil {
1✔
909
                conn.log.Error("Could not parse APIC error response: ", err)
×
910
        } else {
1✔
911
                code := 0
1✔
912
                text := ""
1✔
913
                for _, o := range apicresp.Imdata {
2✔
914
                        if ob, ok := o["error"]; ok {
2✔
915
                                if ob.Attributes != nil {
2✔
916
                                        if t, isStr := ob.Attributes["text"].(string); isStr {
2✔
917
                                                text = t
1✔
918
                                        }
1✔
919
                                        if c, isInt := ob.Attributes["code"].(int); isInt {
1✔
920
                                                code = c
×
921
                                        }
×
922
                                }
923
                        }
924
                }
925
                conn.logger.WithFields(logrus.Fields{
1✔
926
                        "mod":    "APICAPI",
1✔
927
                        "text":   text,
1✔
928
                        "code":   code,
1✔
929
                        "url":    resp.Request.URL,
1✔
930
                        "status": resp.StatusCode,
1✔
931
                }).Error(message)
1✔
932
        }
933
}
934

935
// To make sure cluster's POD/NodeBDs and L3OUT are all mapped
936
// to same and correct VRF.
937
func (conn *ApicConnection) ValidateAciVrfAssociation(acivrfdn string, expectedVrfRelations []string) error {
×
938
        var aciVrfBdL3OuttDns []string
×
939
        args := []string{
×
940
                "query-target=subtree",
×
941
                "target-subtree-class=fvRtCtx,fvRtEctx",
×
942
        }
×
943

×
944
        uri := fmt.Sprintf("/api/mo/%s.json?%s", acivrfdn, strings.Join(args, "&"))
×
945
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
946
        req, err := http.NewRequest("GET", url, http.NoBody)
×
947
        if err != nil {
×
948
                conn.log.Error("Could not create request: ", err)
×
949
                return err
×
950
        }
×
951
        conn.sign(req, uri, nil)
×
952
        resp, err := conn.client.Do(req)
×
953
        if err != nil {
×
954
                conn.log.Error("Could not get subtree for ", acivrfdn, ": ", err)
×
955
                return err
×
956
        }
×
957
        defer complete(resp)
×
958
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
×
959
                conn.logErrorResp("Could not get subtree for "+acivrfdn, resp)
×
960
                return err
×
961
        }
×
962

963
        var apicresp ApicResponse
×
964
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
×
965
        if err != nil {
×
966
                conn.log.Error("Could not parse APIC response: ", err)
×
967
                return err
×
968
        }
×
969

970
        for _, obj := range apicresp.Imdata {
×
971
                for _, body := range obj {
×
972
                        tDn, ok := body.Attributes["tDn"].(string)
×
973
                        if !ok {
×
974
                                continue
×
975
                        }
976
                        aciVrfBdL3OuttDns = append(aciVrfBdL3OuttDns, tDn)
×
977
                }
978
        }
979
        sort.Strings(aciVrfBdL3OuttDns)
×
980
        conn.log.Debug("aciVrfBdL3OuttDns:", aciVrfBdL3OuttDns)
×
981
        for _, expectedDn := range expectedVrfRelations {
×
982
                i := sort.SearchStrings(aciVrfBdL3OuttDns, expectedDn)
×
983
                if !(i < len(aciVrfBdL3OuttDns) && aciVrfBdL3OuttDns[i] == expectedDn) {
×
984
                        conn.log.Debug("Missing (or) Incorrect Vrf association: ", expectedDn)
×
985
                        return errors.New("Incorrect Pod/NodeBD/L3OUT VRF association")
×
986
                }
×
987
        }
988
        return nil
×
989
}
990

991
func (conn *ApicConnection) getSubtreeDn(dn string, respClasses []string,
992
        updateHandlers []ApicObjectHandler) {
1✔
993
        args := []string{
1✔
994
                "rsp-subtree=full",
1✔
995
        }
1✔
996

1✔
997
        if len(respClasses) > 0 {
2✔
998
                args = append(args, "rsp-subtree-class="+strings.Join(respClasses, ","))
1✔
999
        }
1✔
1000
        // properly encoding the URI query parameters breaks APIC
1001
        uri := fmt.Sprintf("/api/mo/%s.json?%s", dn, strings.Join(args, "&"))
1✔
1002
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1003
        conn.log.Debugf("URL: %v", url)
1✔
1004
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1005
        if err != nil {
1✔
1006
                conn.log.Error("Could not create request: ", err)
×
1007
                return
×
1008
        }
×
1009
        conn.sign(req, uri, nil)
1✔
1010
        resp, err := conn.client.Do(req)
1✔
1011
        if err != nil {
1✔
1012
                conn.log.Error("Could not get subtree for ", dn, ": ", err)
×
1013
                conn.restart()
×
1014
                return
×
1015
        }
×
1016
        defer complete(resp)
1✔
1017
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1018
                conn.logErrorResp("Could not get subtree for "+dn, resp)
×
1019
                conn.restart()
×
1020
                return
×
1021
        }
×
1022

1023
        var apicresp ApicResponse
1✔
1024
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
1025
        if err != nil {
1✔
1026
                conn.log.Error("Could not parse APIC response: ", err)
×
1027
                return
×
1028
        }
×
1029
        if len(apicresp.Imdata) == 0 {
1✔
1030
                conn.log.Debugf("No subtree found for dn %s", dn)
×
1031
        }
×
1032

1033
        for _, obj := range apicresp.Imdata {
2✔
1034
                conn.logger.WithFields(logrus.Fields{
1✔
1035
                        "mod": "APICAPI",
1✔
1036
                        "dn":  obj.GetDn(),
1✔
1037
                        "obj": obj,
1✔
1038
                }).Debug("Object updated on APIC")
1✔
1039
                var count int
1✔
1040
                prepareApicCache("", obj, &count)
1✔
1041

1✔
1042
                handled := false
1✔
1043
                for _, handler := range updateHandlers {
1✔
1044
                        if handler(obj) {
×
1045
                                handled = true
×
1046
                                break
×
1047
                        }
1048
                }
1049
                if handled {
1✔
1050
                        continue
×
1051
                }
1052
                conn.reconcileApicObject(obj)
1✔
1053
        }
1054
}
1055

1056
func (conn *ApicConnection) queuePriorityDn(dn string) {
×
1057
        conn.indexMutex.Lock()
×
1058
        if conn.priorityQueue != nil {
×
1059
                conn.priorityQueue.Add(dn)
×
1060
        }
×
1061
        conn.indexMutex.Unlock()
×
1062
}
1063

1064
func (conn *ApicConnection) queueDn(dn string) {
1✔
1065
        conn.indexMutex.Lock()
1✔
1066
        if conn.deltaQueue != nil {
2✔
1067
                conn.deltaQueue.Add(dn)
1✔
1068
        }
1✔
1069
        conn.indexMutex.Unlock()
1✔
1070
}
1071

1072
func (conn *ApicConnection) ForceRelogin() {
×
1073
        conn.token = ""
×
1074
}
×
1075

1076
func (conn *ApicConnection) PostDnInline(dn string, obj ApicObject) error {
×
1077
        conn.logger.WithFields(logrus.Fields{
×
1078
                "mod": "APICAPI",
×
1079
                "dn":  dn,
×
1080
                "obj": obj,
×
1081
        }).Debug("Posting Dn Inline")
×
1082
        if conn.token == "" {
×
1083
                token, err := conn.login()
×
1084
                if err != nil {
×
1085
                        conn.log.Errorf("Login: %v", err)
×
1086
                        return err
×
1087
                }
×
1088
                conn.token = token
×
1089
        }
1090
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
×
1091
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
1092
        raw, err := json.Marshal(obj)
×
1093
        if err != nil {
×
1094
                conn.log.Error("Could not serialize object for dn ", dn, ": ", err)
×
1095
                return err
×
1096
        }
×
1097
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
×
1098
        if err != nil {
×
1099
                conn.log.Error("Could not create request: ", err)
×
1100
                return err
×
1101
        }
×
1102
        conn.sign(req, uri, raw)
×
1103
        req.Header.Set("Content-Type", "application/json")
×
1104
        conn.log.Infof("Post: %+v", req)
×
1105
        resp, err := conn.client.Do(req)
×
1106
        if err != nil {
×
1107
                conn.log.Error("Could not update dn ", dn, ": ", err)
×
1108
                return err
×
1109
        }
×
1110

1111
        complete(resp)
×
1112
        if resp.StatusCode != http.StatusOK {
×
1113
                return fmt.Errorf("Status: %v", resp.StatusCode)
×
1114
        }
×
1115
        return nil
×
1116
}
1117

1118
func (conn *ApicConnection) DeleteDnInline(dn string) error {
1✔
1119
        conn.logger.WithFields(logrus.Fields{
1✔
1120
                "mod": "APICAPI",
1✔
1121
                "dn":  dn,
1✔
1122
        }).Debug("Deleting Dn Inline")
1✔
1123
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1124
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1125
        req, err := http.NewRequest("DELETE", url, http.NoBody)
1✔
1126
        if err != nil {
1✔
1127
                conn.log.Error("Could not create delete request: ", err)
×
1128
                return err
×
1129
        }
×
1130
        conn.sign(req, uri, nil)
1✔
1131
        resp, err := conn.client.Do(req)
1✔
1132
        if err != nil {
2✔
1133
                conn.log.Error("Could not delete dn ", dn, ": ", err)
1✔
1134
                return err
1✔
1135
        }
1✔
1136
        defer complete(resp)
×
1137
        return nil
×
1138
}
1139

1140
func (conn *ApicConnection) postDn(dn string, obj ApicObject) bool {
1✔
1141
        conn.logger.WithFields(logrus.Fields{
1✔
1142
                "mod": "APICAPI",
1✔
1143
                "dn":  dn,
1✔
1144
                "obj": obj,
1✔
1145
        }).Debug("Posting Dn")
1✔
1146

1✔
1147
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1148
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1149
        raw, err := json.Marshal(obj)
1✔
1150
        if err != nil {
1✔
1151
                conn.log.Error("Could not serialize object for dn ", dn, ": ", err)
×
1152
        }
×
1153
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
1✔
1154
        if err != nil {
1✔
1155
                conn.log.Error("Could not create request: ", err)
×
1156
                conn.restart()
×
1157
                return false
×
1158
        }
×
1159
        conn.sign(req, uri, raw)
1✔
1160
        req.Header.Set("Content-Type", "application/json")
1✔
1161
        resp, err := conn.client.Do(req)
1✔
1162
        if err != nil {
1✔
1163
                conn.log.Error("Could not update dn ", dn, ": ", err)
×
1164
                conn.restart()
×
1165
                return false
×
1166
        }
×
1167
        defer complete(resp)
1✔
1168
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1169
                conn.logErrorResp("Could not update dn "+dn, resp)
×
1170
                if resp.StatusCode == 400 {
×
1171
                        return true
×
1172
                }
×
1173
                conn.restart()
×
1174
        }
1175
        return false
1✔
1176
}
1177

1178
func (conn *ApicConnection) Delete(dn string) bool {
1✔
1179
        if dn == "" {
1✔
1180
                conn.log.Debug("Skip delete for empty Dn: ")
×
1181
                return false
×
1182
        }
×
1183
        dnSlice := strings.Split(dn, "/")
1✔
1184
        identifier := dnSlice[len(dnSlice)-1]
1✔
1185
        iSlice := strings.SplitN(identifier, "-", 2)
1✔
1186
        if len(iSlice) == 2 {
2✔
1187
                if iSlice[0] == "ip" {
1✔
1188
                        addr := strings.Trim(iSlice[1], "[]")
×
1189
                        obj := NewDeleteHostprotRemoteIp(addr)
×
1190
                        conn.log.Debug("Posting delete of dn ", dn)
×
1191
                        return conn.postDn(dn, obj)
×
1192
                } else if iSlice[0] == "odev" {
1✔
1193
                        conn.log.Debug("Skipping delete of opflexODev : ", dn)
×
1194
                        return false
×
1195
                }
×
1196
        }
1197
        return conn.DeleteDn(dn)
1✔
1198
}
1199

1200
func (conn *ApicConnection) DeleteDn(dn string) bool {
1✔
1201
        if dn == "" {
1✔
1202
                conn.log.Debug("Skip delete for empty Dn: ")
×
1203
                return false
×
1204
        }
×
1205
        conn.logger.WithFields(logrus.Fields{
1✔
1206
                "mod": "APICAPI",
1✔
1207
                "dn":  dn,
1✔
1208
        }).Debug("Deleting Dn")
1✔
1209
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1210
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1211
        req, err := http.NewRequest("DELETE", url, http.NoBody)
1✔
1212
        if err != nil {
1✔
1213
                conn.log.Error("Could not create delete request: ", err)
×
1214
                conn.restart()
×
1215
                return false
×
1216
        }
×
1217
        conn.sign(req, uri, nil)
1✔
1218
        resp, err := conn.client.Do(req)
1✔
1219
        if err != nil {
1✔
1220
                conn.log.Error("Could not delete dn ", dn, ": ", err)
×
1221
                conn.restart()
×
1222
                return false
×
1223
        }
×
1224
        defer complete(resp)
1✔
1225
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1226
                conn.logErrorResp("Could not delete dn "+dn, resp)
×
1227
                conn.restart()
×
1228
        }
×
1229
        return false
1✔
1230
}
1231

1232
func doComputeRespClasses(targetClasses []string,
1233
        visited map[string]bool) {
1✔
1234
        for _, class := range targetClasses {
2✔
1235
                if visited[class] {
1✔
1236
                        continue
×
1237
                }
1238
                visited[class] = true
1✔
1239
                if md, ok := metadata[class]; ok {
2✔
1240
                        doComputeRespClasses(md.children, visited)
1✔
1241
                }
1✔
1242
        }
1243
}
1244

1245
func computeRespClasses(targetClasses []string) []string {
1✔
1246
        visited := make(map[string]bool)
1✔
1247
        doComputeRespClasses(targetClasses, visited)
1✔
1248

1✔
1249
        var respClasses []string
1✔
1250
        for class := range visited {
2✔
1251
                respClasses = append(respClasses, class)
1✔
1252
        }
1✔
1253
        respClasses = append(respClasses, "tagAnnotation")
1✔
1254
        return respClasses
1✔
1255
}
1256

1257
// AddSubscriptionTree subscribe at a subtree level. class specifies
1258
// the root. Changes will cause entire subtree of the rootdn to be fetched
1259
func (conn *ApicConnection) AddSubscriptionTree(class string,
1260
        targetClasses []string, targetFilter string) {
1✔
1261
        if _, ok := classDepth[class]; !ok {
1✔
1262
                errStr := fmt.Sprintf("classDepth not for class %s", class)
×
1263
                panic(errStr)
×
1264
        }
1265

1266
        conn.indexMutex.Lock()
1✔
1267
        conn.subscriptions.subs[class] = &subscription{
1✔
1268
                kind:          apicSubTree,
1✔
1269
                childSubs:     make(map[string]subComponent),
1✔
1270
                targetClasses: targetClasses,
1✔
1271
                targetFilter:  targetFilter,
1✔
1272
        }
1✔
1273
        conn.indexMutex.Unlock()
1✔
1274
}
1275

1276
func (conn *ApicConnection) AddSubscriptionClass(class string,
1277
        targetClasses []string, targetFilter string) {
1✔
1278
        conn.indexMutex.Lock()
1✔
1279
        conn.subscriptions.subs[class] = &subscription{
1✔
1280
                kind:          apicSubClass,
1✔
1281
                childSubs:     make(map[string]subComponent),
1✔
1282
                targetClasses: targetClasses,
1✔
1283
                respClasses:   computeRespClasses(targetClasses),
1✔
1284
                targetFilter:  targetFilter,
1✔
1285
        }
1✔
1286
        conn.indexMutex.Unlock()
1✔
1287
}
1✔
1288

1289
func (conn *ApicConnection) AddSubscriptionDn(dn string,
1290
        targetClasses []string) {
1✔
1291
        conn.logger.WithFields(logrus.Fields{
1✔
1292
                "mod": "APICAPI",
1✔
1293
                "dn":  dn,
1✔
1294
        }).Debug("Adding Subscription for Dn")
1✔
1295

1✔
1296
        conn.indexMutex.Lock()
1✔
1297
        conn.subscriptions.subs[dn] = &subscription{
1✔
1298
                kind:          apicSubDn,
1✔
1299
                childSubs:     make(map[string]subComponent),
1✔
1300
                targetClasses: targetClasses,
1✔
1301
                respClasses:   computeRespClasses(targetClasses),
1✔
1302
        }
1✔
1303
        conn.indexMutex.Unlock()
1✔
1304
}
1✔
1305

1306
func (conn *ApicConnection) SetSubscriptionHooks(value string,
1307
        updateHook ApicObjectHandler, deleteHook ApicDnHandler) {
1✔
1308
        conn.indexMutex.Lock()
1✔
1309
        if s, ok := conn.subscriptions.subs[value]; ok {
2✔
1310
                s.updateHook = updateHook
1✔
1311
                s.deleteHook = deleteHook
1✔
1312
        }
1✔
1313
        conn.indexMutex.Unlock()
1✔
1314
}
1315

1316
func (conn *ApicConnection) GetApicResponse(uri string) (ApicResponse, error) {
1✔
1317
        conn.log.Debug("apicIndex: ", conn.Apic[conn.ApicIndex], " uri: ", uri)
1✔
1318
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1319
        var apicresp ApicResponse
1✔
1320
        conn.log.Debug("Apic Get url: ", url)
1✔
1321
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1322
        if err != nil {
1✔
1323
                conn.log.Error("Could not create request: ", err)
×
1324
                return apicresp, err
×
1325
        }
×
1326
        conn.sign(req, uri, nil)
1✔
1327
        resp, err := conn.client.Do(req)
1✔
1328
        if err != nil {
1✔
1329
                conn.log.Error("Could not get response for ", url, ": ", err)
×
1330
                return apicresp, err
×
1331
        }
×
1332
        defer complete(resp)
1✔
1333
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1334
                conn.logErrorResp("Could not get subtree for "+url, resp)
×
1335
                return apicresp, err
×
1336
        }
×
1337
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
1338
        if err != nil {
1✔
1339
                conn.log.Error("Could not parse APIC response: ", err)
×
1340
                return apicresp, err
×
1341
        }
×
1342
        return apicresp, nil
1✔
1343
}
1344

1345
func (conn *ApicConnection) doSubscribe(args []string,
1346
        kind, value, refresh_interval string, apicresp *ApicResponse) bool {
1✔
1347
        // properly encoding the URI query parameters breaks APIC
1✔
1348
        uri := fmt.Sprintf("/api/%s/%s.json?subscription=yes&%s%s",
1✔
1349
                kind, value, refresh_interval, strings.Join(args, "&"))
1✔
1350
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1351
        conn.log.Info("APIC connection URL: ", url)
1✔
1352

1✔
1353
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1354
        if err != nil {
1✔
1355
                conn.log.Error("Could not create request: ", err)
×
1356
                return false
×
1357
        }
×
1358
        conn.sign(req, uri, nil)
1✔
1359
        resp, err := conn.client.Do(req)
1✔
1360
        if err != nil {
1✔
1361
                conn.log.Error("Failed to subscribe to ", value, ": ", err)
×
1362
                return false
×
1363
        }
×
1364
        defer complete(resp)
1✔
1365
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1366
                conn.logErrorResp("Could not subscribe to "+value, resp)
×
1367
                return false
×
1368
        }
×
1369

1370
        err = json.NewDecoder(resp.Body).Decode(apicresp)
1✔
1371
        if err != nil {
1✔
1372
                conn.log.Error("Could not decode APIC response", err)
×
1373
                return false
×
1374
        }
×
1375
        time.Sleep(conn.SubscriptionDelay)
1✔
1376
        return true
1✔
1377
}
1378

1379
func (conn *ApicConnection) subscribe(value string, sub *subscription, lockHeld bool) bool {
1✔
1380
        baseArgs := []string{
1✔
1381
                "query-target=subtree",
1✔
1382
                "rsp-subtree=full",
1✔
1383
                "target-subtree-class=" + strings.Join(sub.targetClasses, ","),
1✔
1384
        }
1✔
1385

1✔
1386
        const defaultArgs = 1
1✔
1387
        var argCount = defaultArgs
1✔
1388
        var combinableSubClasses, separableSubClasses []string
1✔
1389
        var splitTargetClasses [][]string
1✔
1390
        var splitRespClasses [][]string
1✔
1391
        var argSet [][]string
1✔
1392
        argSet = make([][]string, defaultArgs)
1✔
1393
        argSet[defaultArgs-1] = make([]string, len(baseArgs))
1✔
1394
        copy(argSet[defaultArgs-1], baseArgs)
1✔
1395
        if sub.respClasses != nil {
2✔
1396
                separateClasses := func(classes []string, combClasses, sepClasses *[]string) {
2✔
1397
                        for i := range classes {
2✔
1398
                                if classMeta, ok := metadata[classes[i]]; ok {
2✔
1399
                                        if classes[i] == "tagAnnotation" {
2✔
1400
                                                continue
1✔
1401
                                        }
1402
                                        if classMeta.hints != nil && classMeta.hints["cardinality"] == "high" {
2✔
1403
                                                *sepClasses = append(*sepClasses, classes[i])
1✔
1404
                                                continue
1✔
1405
                                        }
1406
                                        *combClasses = append(*combClasses, classes[i])
1✔
1407
                                }
1408
                        }
1409
                }
1410
                separateClasses(sub.respClasses, &combinableSubClasses, &separableSubClasses)
1✔
1411

1✔
1412
                // In case there are high cardinality children, we register for all the classes individually.
1✔
1413
                // The concept of target-subtree and rsp-subtree class cannot be used because of the tagAnnotation object
1✔
1414
                // vmmInjectedLabel is added for every object, so getting it separately will not be scalable
1✔
1415
                if len(separableSubClasses) > 0 {
2✔
1416
                        separateClasses(sub.targetClasses, &combinableSubClasses, &separableSubClasses)
1✔
1417
                        separableSubClasses = append(separableSubClasses, combinableSubClasses...)
1✔
1418
                        baseArgs = []string{
1✔
1419
                                "query-target=subtree",
1✔
1420
                                "rsp-subtree=children",
1✔
1421
                        }
1✔
1422
                        subscribingClasses := make(map[string]bool)
1✔
1423
                        argSet = make([][]string, len(separableSubClasses))
1✔
1424
                        splitTargetClasses = make([][]string, len(separableSubClasses))
1✔
1425
                        splitRespClasses = make([][]string, len(separableSubClasses))
1✔
1426

1✔
1427
                        argCount = 0
1✔
1428
                        for i := range separableSubClasses {
2✔
1429
                                // Eliminate duplicates
1✔
1430
                                if _, ok := subscribingClasses[separableSubClasses[i]]; ok {
2✔
1431
                                        continue
1✔
1432
                                }
1433
                                subscribingClasses[separableSubClasses[i]] = true
1✔
1434
                                argSet[argCount] = make([]string, len(baseArgs))
1✔
1435
                                copy(argSet[argCount], baseArgs)
1✔
1436
                                argSet[argCount] = append(argSet[argCount], "target-subtree-class="+separableSubClasses[i], "rsp-subtree-class=tagAnnotation")
1✔
1437
                                splitTargetClasses[argCount] = append(splitTargetClasses[argCount], separableSubClasses[i])
1✔
1438
                                splitRespClasses[argCount] = computeRespClasses([]string{separableSubClasses[i]})
1✔
1439
                                argCount++
1✔
1440
                        }
1441
                } else {
1✔
1442
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], "rsp-subtree-class="+strings.Join(combinableSubClasses, ",")+",tagAnnotation")
1✔
1443
                }
1✔
1444
        }
1445
        if sub.targetFilter != "" {
2✔
1446
                targetFilterArgs := "query-target-filter=" + sub.targetFilter
1✔
1447
                if len(separableSubClasses) == 0 {
2✔
1448
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], targetFilterArgs)
1✔
1449
                } else {
1✔
1450
                        for i := 0; i < argCount; i++ {
×
1451
                                argSet[i] = append(argSet[i], targetFilterArgs)
×
1452
                        }
×
1453
                }
1454
        }
1455

1456
        kind := "mo"
1✔
1457
        if sub.kind == apicSubClass || sub.kind == apicSubTree {
2✔
1458
                kind = "class"
1✔
1459
        }
1✔
1460

1461
        refresh_interval := ""
1✔
1462
        if conn.RefreshInterval != 0 {
2✔
1463
                refresh_interval = fmt.Sprintf("refresh-timeout=%v&",
1✔
1464
                        conn.RefreshInterval.Seconds())
1✔
1465
        }
1✔
1466
        for i := 0; i < argCount; i++ {
2✔
1467
                var apicresp ApicResponse
1✔
1468
                if !conn.doSubscribe(argSet[i], kind, value, refresh_interval, &apicresp) {
1✔
1469
                        return false
×
1470
                }
×
1471
                subId, ok := apicresp.SubscriptionId.(string)
1✔
1472
                if !ok {
1✔
1473
                        conn.log.Error("Subscription ID is not a string")
×
1474
                        return false
×
1475
                }
×
1476

1477
                conn.logger.WithFields(logrus.Fields{
1✔
1478
                        "mod":   "APICAPI",
1✔
1479
                        "value": value,
1✔
1480
                        "kind":  kind,
1✔
1481
                        "id":    subId,
1✔
1482
                        "args":  argSet[i],
1✔
1483
                }).Debug("Subscribed")
1✔
1484
                if !lockHeld {
2✔
1485
                        conn.indexMutex.Lock()
1✔
1486
                }
1✔
1487
                if argCount > defaultArgs {
2✔
1488
                        sub.childSubs[subId] = subComponent{
1✔
1489
                                targetClasses: splitTargetClasses[i],
1✔
1490
                                respClasses:   splitRespClasses[i],
1✔
1491
                        }
1✔
1492
                } else {
2✔
1493
                        conn.subscriptions.subs[value].id = subId
1✔
1494
                }
1✔
1495
                conn.subscriptions.ids[subId] = value
1✔
1496
                if !lockHeld {
2✔
1497
                        conn.indexMutex.Unlock()
1✔
1498
                }
1✔
1499
                var respObjCount int
1✔
1500
                for _, obj := range apicresp.Imdata {
2✔
1501
                        dn := obj.GetDn()
1✔
1502
                        if dn == "" {
1✔
1503
                                continue
×
1504
                        }
1505
                        if !lockHeld {
2✔
1506
                                conn.indexMutex.Lock()
1✔
1507
                        }
1✔
1508
                        subIds, found := conn.cacheDnSubIds[dn]
1✔
1509
                        if !found {
2✔
1510
                                subIds = make(map[string]bool)
1✔
1511
                                conn.cacheDnSubIds[dn] = subIds
1✔
1512
                        }
1✔
1513
                        subIds[subId] = true
1✔
1514
                        if !lockHeld {
2✔
1515
                                conn.indexMutex.Unlock()
1✔
1516
                        }
1✔
1517
                        if sub.updateHook != nil && sub.updateHook(obj) {
2✔
1518
                                continue
1✔
1519
                        }
1520

1521
                        tag := obj.GetTag()
1✔
1522
                        if !conn.isSyncTag(tag) {
1✔
1523
                                continue
×
1524
                        }
1525

1526
                        conn.logger.WithFields(logrus.Fields{
1✔
1527
                                "mod": "APICAPI",
1✔
1528
                                "dn":  dn,
1✔
1529
                                "tag": tag,
1✔
1530
                                "obj": obj,
1✔
1531
                        }).Debug("Caching")
1✔
1532
                        var count int
1✔
1533
                        prepareApicCache("", obj, &count)
1✔
1534
                        respObjCount += count
1✔
1535
                        if !lockHeld {
2✔
1536
                                conn.indexMutex.Lock()
1✔
1537
                        }
1✔
1538
                        conn.cachedState[tag] = append(conn.cachedState[tag], obj)
1✔
1539
                        if !lockHeld {
2✔
1540
                                conn.indexMutex.Unlock()
1✔
1541
                        }
1✔
1542
                }
1543
                if respObjCount >= ApicSubscriptionResponseMoMaxCount/10 {
1✔
1544
                        conn.logger.WithFields(logrus.Fields{
×
1545
                                "args":       argSet[i],
×
1546
                                "moCount":    respObjCount,
×
1547
                                "maxAllowed": ApicSubscriptionResponseMoMaxCount,
×
1548
                        }).Warning("Subscription response is significantly large. Each new object will add 2 Mos atleast and twice the number of labels on the object")
×
1549
                } else {
1✔
1550
                        conn.logger.WithFields(logrus.Fields{
1✔
1551
                                "moCount": respObjCount,
1✔
1552
                        }).Debug("ResponseObjCount")
1✔
1553
                }
1✔
1554
        }
1555

1556
        return true
1✔
1557
}
1558

1559
var tagRegexp = regexp.MustCompile(`[a-zA-Z0-9_]{1,31}-[a-f0-9]{32}`)
1560

1561
func (conn *ApicConnection) isSyncTag(tag string) bool {
1✔
1562
        return tagRegexp.MatchString(tag) &&
1✔
1563
                strings.HasPrefix(tag, conn.prefix+"-")
1✔
1564
}
1✔
1565

1566
func getRootDn(dn, rootClass string) string {
1✔
1567
        depth := classDepth[rootClass]
1✔
1568
        parts := strings.Split(dn, "/")
1✔
1569
        parts = parts[:depth]
1✔
1570
        return strings.Join(parts, "/")
1✔
1571
}
1✔
1572

1573
func (conn *ApicConnection) PostApicObjects(uri string, payload ApicSlice) error {
×
1574
        conn.log.Debug("apicIndex: ", conn.Apic[conn.ApicIndex], " uri: ", uri)
×
1575
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
1576
        conn.log.Debug("Apic POST url: ", url)
×
1577

×
1578
        if conn.token == "" {
×
1579
                token, err := conn.login()
×
1580
                if err != nil {
×
1581
                        conn.log.Errorf("Login: %v", err)
×
1582
                        return err
×
1583
                }
×
1584
                conn.token = token
×
1585
        }
1586

1587
        raw, err := json.Marshal(payload)
×
1588
        if err != nil {
×
1589
                conn.log.Error("Could not serialize object: ", err)
×
1590
                return err
×
1591
        }
×
1592

1593
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
×
1594
        if err != nil {
×
1595
                conn.log.Error("Could not create request: ", err)
×
1596
                return err
×
1597
        }
×
1598

1599
        conn.sign(req, uri, raw)
×
1600
        req.Header.Set("Content-Type", "application/json")
×
1601
        conn.log.Infof("Post: %+v", req)
×
1602
        resp, err := conn.client.Do(req)
×
1603
        if err != nil {
×
1604
                conn.log.Error("Could not update  ", url, ": ", err)
×
1605
                return err
×
1606
        }
×
1607

1608
        complete(resp)
×
1609

×
1610
        if resp.StatusCode != http.StatusOK {
×
1611
                return fmt.Errorf("Status: %v", resp.StatusCode)
×
1612
        }
×
1613

1614
        return nil
×
1615
}
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

© 2026 Coveralls, Inc