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

noironetworks / aci-containers / 9205

20 Jun 2024 09:34PM UTC coverage: 69.485% (-0.02%) from 69.509%
9205

push

travis-pro

tomflynn
Stop pinning libs to specific version unnecessarily

Remove pinning of no longer used libs

Signed-off-by: Tom Flynn <tom.flynn@gmail.com>

11857 of 17064 relevant lines covered (69.49%)

0.79 hits per line

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

69.93
/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) (*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
                subscriptions: subIndex{
1✔
233
                        subs: make(map[string]*subscription),
1✔
234
                        ids:  make(map[string]string),
1✔
235
                },
1✔
236
                desiredState:       make(map[string]ApicSlice),
1✔
237
                desiredStateDn:     make(map[string]ApicObject),
1✔
238
                keyHashes:          make(map[string]string),
1✔
239
                containerDns:       make(map[string]bool),
1✔
240
                cachedState:        make(map[string]ApicSlice),
1✔
241
                cacheDnSubIds:      make(map[string]map[string]bool),
1✔
242
                pendingSubDnUpdate: make(map[string]pendingChange),
1✔
243
                CachedSubnetDns:    make(map[string]string),
1✔
244
        }
1✔
245
        return conn, nil
1✔
246
}
247

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

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

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

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

1✔
298
                                        conn.pendingSubDnUpdate[dn] = pendingChange{
1✔
299
                                                kind:    pendingKind,
1✔
300
                                                subIds:  subIds,
1✔
301
                                                isDirty: false,
1✔
302
                                        }
1✔
303
                                        if key == "opflexODev" && conn.odevQueue != nil {
2✔
304
                                                conn.log.Debug("Adding dn to odevQueue: ", dn)
1✔
305
                                                conn.odevQueue.Add(dn)
1✔
306
                                        } else if isPriorityObject(dn) {
2✔
307
                                                conn.log.Debug("Adding dn to priorityQueue: ", dn)
×
308
                                                conn.priorityQueue.Add(dn)
×
309
                                        } else if conn.deltaQueue != nil {
2✔
310
                                                conn.deltaQueue.Add(dn)
1✔
311
                                        }
1✔
312
                                        conn.indexMutex.Unlock()
1✔
313
                                }
314
                        }
315
                }
316
        }
317
}
318

319
func (conn *ApicConnection) restart() {
1✔
320
        conn.indexMutex.Lock()
1✔
321
        if conn.restartCh != nil {
2✔
322
                conn.log.Debug("Restarting connection")
1✔
323
                close(conn.restartCh)
1✔
324
                conn.restartCh = nil
1✔
325
        }
1✔
326
        conn.indexMutex.Unlock()
1✔
327
}
328

329
func (conn *ApicConnection) handleQueuedDn(dn string) bool {
1✔
330
        var respClasses []string
1✔
331
        var updateHandlers []ApicObjectHandler
1✔
332
        var deleteHandlers []ApicDnHandler
1✔
333
        var rootDn string
1✔
334

1✔
335
        handleId := func(id string) {
2✔
336
                conn.indexMutex.Lock()
1✔
337
                if value, ok := conn.subscriptions.ids[id]; ok {
2✔
338
                        if sub, ok := conn.subscriptions.subs[value]; ok {
2✔
339
                                if subComp, ok := sub.childSubs[id]; ok {
1✔
340
                                        respClasses =
×
341
                                                append(respClasses, subComp.respClasses...)
×
342
                                } else {
1✔
343
                                        respClasses =
1✔
344
                                                append(respClasses, sub.respClasses...)
1✔
345
                                }
1✔
346
                                if sub.updateHook != nil {
2✔
347
                                        updateHandlers = append(updateHandlers, sub.updateHook)
1✔
348
                                }
1✔
349
                                if sub.deleteHook != nil {
2✔
350
                                        deleteHandlers = append(deleteHandlers, sub.deleteHook)
1✔
351
                                }
1✔
352

353
                                if sub.kind == apicSubTree {
1✔
354
                                        rootDn = getRootDn(dn, value)
×
355
                                }
×
356
                        }
357
                } else {
×
358
                        conn.log.Warning("Unexpected subscription: ", id)
×
359
                }
×
360
                conn.indexMutex.Unlock()
1✔
361
        }
362

363
        var requeue bool
1✔
364
        conn.indexMutex.Lock()
1✔
365
        pending, hasPendingChange := conn.pendingSubDnUpdate[dn]
1✔
366
        conn.pendingSubDnUpdate[dn] = pendingChange{isDirty: true}
1✔
367
        obj, hasDesiredState := conn.desiredStateDn[dn]
1✔
368
        conn.indexMutex.Unlock()
1✔
369

1✔
370
        if hasPendingChange {
2✔
371
                for _, id := range pending.subIds {
2✔
372
                        handleId(id)
1✔
373
                }
1✔
374
        }
375

376
        if rootDn == "" {
2✔
377
                rootDn = dn
1✔
378
        }
1✔
379

380
        if hasDesiredState {
2✔
381
                if hasPendingChange {
2✔
382
                        if pending.kind == pendingChangeDelete {
2✔
383
                                conn.logger.WithFields(logrus.Fields{"mod": "APICAPI", "DN": dn}).
1✔
384
                                        Warning("Restoring unexpectedly deleted" +
1✔
385
                                                " ACI object")
1✔
386
                                requeue = conn.postDn(dn, obj)
1✔
387
                        } else {
2✔
388
                                conn.log.Debug("getSubtreeDn for:", rootDn)
1✔
389
                                conn.getSubtreeDn(rootDn, respClasses, updateHandlers)
1✔
390
                        }
1✔
391
                } else {
1✔
392
                        requeue = conn.postDn(dn, obj)
1✔
393
                }
1✔
394
        } else {
1✔
395
                if hasPendingChange {
2✔
396
                        if pending.kind == pendingChangeDelete {
2✔
397
                                for _, handler := range deleteHandlers {
2✔
398
                                        handler(dn)
1✔
399
                                }
1✔
400
                        }
401

402
                        if (pending.kind != pendingChangeDelete) || (dn != rootDn) {
2✔
403
                                conn.log.Debug("getSubtreeDn for:", rootDn)
1✔
404
                                conn.getSubtreeDn(rootDn, respClasses, updateHandlers)
1✔
405
                        }
1✔
406
                } else {
1✔
407
                        requeue = conn.Delete(dn)
1✔
408
                }
1✔
409
        }
410

411
        return requeue
1✔
412
}
413

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

445
type fullSync struct{}
446

447
func (conn *ApicConnection) runConn(stopCh <-chan struct{}) {
1✔
448
        done := make(chan struct{})
1✔
449
        restart := make(chan struct{})
1✔
450
        queueStop := make(chan struct{})
1✔
451
        odevQueueStop := make(chan struct{})
1✔
452
        priorityQueueStop := make(chan struct{})
1✔
453
        syncHook := make(chan fullSync, 1)
1✔
454
        conn.restartCh = restart
1✔
455

1✔
456
        go func() {
2✔
457
                defer conn.connection.Close()
1✔
458
                defer close(done)
1✔
459

1✔
460
                for {
2✔
461
                        var apicresp ApicResponse
1✔
462
                        err := conn.connection.ReadJSON(&apicresp)
1✔
463
                        var closeErr *websocket.CloseError
1✔
464
                        if errors.As(err, &closeErr) {
1✔
465
                                conn.log.Info("Websocket connection closed: ", closeErr.Code)
×
466
                                conn.restart()
×
467
                                break
×
468
                        } else if err != nil {
2✔
469
                                conn.log.Error("Could not read web socket message:", err)
1✔
470
                                conn.restart()
1✔
471
                                break
1✔
472
                        } else {
1✔
473
                                conn.handleSocketUpdate(&apicresp)
1✔
474
                        }
1✔
475
                }
476
        }()
477

478
        conn.indexMutex.Lock()
1✔
479
        oldState := conn.cacheDnSubIds
1✔
480
        conn.cachedState = make(map[string]ApicSlice)
1✔
481
        conn.cacheDnSubIds = make(map[string]map[string]bool)
1✔
482
        conn.deltaQueue = workqueue.NewNamedRateLimitingQueue(
1✔
483
                workqueue.NewMaxOfRateLimiter(
1✔
484
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
485
                                10*time.Second),
1✔
486
                        &workqueue.BucketRateLimiter{
1✔
487
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
488
                        },
1✔
489
                ),
1✔
490
                "delta")
1✔
491
        go conn.processQueue(conn.deltaQueue, queueStop, "delta")
1✔
492
        conn.odevQueue = workqueue.NewNamedRateLimitingQueue(
1✔
493
                workqueue.NewMaxOfRateLimiter(
1✔
494
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
495
                                10*time.Second),
1✔
496
                        &workqueue.BucketRateLimiter{
1✔
497
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
498
                        },
1✔
499
                ),
1✔
500
                "odev")
1✔
501
        go conn.processQueue(conn.odevQueue, odevQueueStop, "odev")
1✔
502
        conn.priorityQueue = workqueue.NewNamedRateLimitingQueue(
1✔
503
                workqueue.NewMaxOfRateLimiter(
1✔
504
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
505
                                10*time.Second),
1✔
506
                        &workqueue.BucketRateLimiter{
1✔
507
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
508
                        },
1✔
509
                ),
1✔
510
                "priority")
1✔
511
        go conn.processQueue(conn.priorityQueue, priorityQueueStop, "priority")
1✔
512
        conn.indexMutex.Unlock()
1✔
513

1✔
514
        refreshInterval := conn.RefreshInterval
1✔
515
        if refreshInterval == 0 {
1✔
516
                refreshInterval = defaultConnectionRefresh
×
517
        }
×
518
        // Adjust refreshTickerInterval.
519
        // To refresh the subscriptions early than actual refresh timeout value
520
        refreshTickerInterval := refreshInterval - conn.RefreshTickerAdjust
1✔
521
        refreshTicker := time.NewTicker(refreshTickerInterval)
1✔
522
        defer refreshTicker.Stop()
1✔
523

1✔
524
        var hasErr bool
1✔
525
        for value, subscription := range conn.subscriptions.subs {
2✔
526
                if !(conn.subscribe(value, subscription)) {
1✔
527
                        hasErr = true
×
528
                        conn.restart()
×
529
                        break
×
530
                }
531
        }
532
        if !hasErr {
2✔
533
                conn.checkDeletes(oldState)
1✔
534
                go func() {
2✔
535
                        if conn.FullSyncHook != nil {
1✔
536
                                conn.FullSyncHook()
×
537
                        }
×
538
                        syncHook <- fullSync{}
1✔
539
                }()
540
        }
541

542
        // Get APIC version if connection restarts
543
        if conn.version == "" && conn.checkVersion {
1✔
544
                go func() {
×
545
                        version, err := conn.GetVersion()
×
546
                        if err != nil {
×
547
                                conn.log.Error("Error while getting APIC version: ", err, " Restarting connection...")
×
548
                                conn.restart()
×
549
                        } else {
×
550
                                conn.log.Debug("Cached version:", conn.CachedVersion, " New version:", version)
×
551
                                if ApicVersion != version {
×
552
                                        ApicVersion = version
×
553
                                        if ApicVersion >= "6.0(4c)" {
×
554
                                                metadata["fvBD"].attributes["serviceBdRoutingDisable"] = "no"
×
555
                                        } else {
×
556
                                                delete(metadata["fvBD"].attributes, "serviceBdRoutingDisable")
×
557
                                        }
×
558
                                        conn.VersionUpdateHook()
×
559
                                }
560
                                conn.CachedVersion = version
×
561
                        }
562
                }()
563
        }
564

565
        closeConn := func(stop bool) {
2✔
566
                close(queueStop)
1✔
567
                close(odevQueueStop)
1✔
568

1✔
569
                conn.indexMutex.Lock()
1✔
570
                conn.deltaQueue = nil
1✔
571
                conn.odevQueue = nil
1✔
572
                conn.priorityQueue = nil
1✔
573
                conn.stopped = stop
1✔
574
                conn.syncEnabled = false
1✔
575
                conn.subscriptions.ids = make(map[string]string)
1✔
576
                conn.version = ""
1✔
577
                conn.indexMutex.Unlock()
1✔
578

1✔
579
                conn.log.Debug("Shutting down web socket")
1✔
580
                err := conn.connection.WriteMessage(websocket.CloseMessage,
1✔
581
                        websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
1✔
582
                if err != nil {
1✔
583
                        conn.log.Error("Error while closing socket: ", err)
×
584
                } else {
1✔
585
                        select {
1✔
586
                        case <-done:
1✔
587
                        case <-time.After(time.Second):
×
588
                        }
589
                }
590
                conn.connection.Close()
1✔
591
        }
592

593
loop:
1✔
594
        for {
2✔
595
                select {
1✔
596
                case <-syncHook:
1✔
597
                        conn.fullSync()
1✔
598
                case <-refreshTicker.C:
1✔
599
                        conn.refresh()
1✔
600
                case <-restart:
1✔
601
                        closeConn(false)
1✔
602
                        break loop
1✔
603
                case <-stopCh:
1✔
604
                        closeConn(true)
1✔
605
                        break loop
1✔
606
                }
607
        }
608

609
        conn.log.Debug("Exiting websocket handler")
1✔
610
}
611

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

1✔
617
        if len(conn.Apic) == 0 {
1✔
618
                return "", errors.New("No APIC configuration")
×
619
        }
×
620

621
        conn.checkVersion = true // enable version check on websocket reconnect
1✔
622
        // To Handle unit-tests
1✔
623
        if strings.Contains(conn.Apic[conn.ApicIndex], "127.0.0.1") {
2✔
624
                conn.version = "4.2(4i)"
1✔
625
                conn.SnatPbrFltrChain = true
1✔
626
                conn.log.Debug("Returning APIC version 4.2(4i) for test server")
1✔
627
                return conn.version, nil
1✔
628
        }
1✔
629

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

×
633
        retries := 0
×
634
        for conn.version == "" {
×
635
                if retries <= conn.ReconnectRetryLimit {
×
636
                        // Wait before Retry.
×
637
                        time.Sleep(conn.ReconnectInterval)
×
638
                        retries++
×
639
                } else {
×
640
                        return "", fmt.Errorf("Failed to get APIC version after %d retries", retries)
×
641
                }
×
642

643
                token, err := conn.login()
×
644
                if err != nil {
×
645
                        conn.log.Error("Failed to log into APIC: ", err)
×
646
                        continue
×
647
                }
648
                conn.token = token
×
649

×
650
                req, err := http.NewRequest("GET", url, http.NoBody)
×
651
                if err != nil {
×
652
                        conn.log.Error("Could not create request:", err)
×
653
                        continue
×
654
                }
655
                conn.sign(req, uri, nil)
×
656
                resp, err := conn.client.Do(req)
×
657
                if err != nil {
×
658
                        conn.log.Error("Could not get response for ", versionMo, ": ", err)
×
659
                        continue
×
660
                }
661
                defer complete(resp)
×
662
                if resp.StatusCode < 200 || resp.StatusCode >= 300 {
×
663
                        conn.logErrorResp("Could not get response for "+versionMo, resp)
×
664
                        conn.log.Debug("Request:", req)
×
665
                        continue
×
666
                }
667

668
                var apicresp ApicResponse
×
669
                err = json.NewDecoder(resp.Body).Decode(&apicresp)
×
670
                if err != nil {
×
671
                        conn.log.Error("Could not parse APIC response: ", err)
×
672
                        continue
×
673
                }
674
                for _, obj := range apicresp.Imdata {
×
675
                        vresp := obj["firmwareCtrlrRunning"]
×
676
                        version, ok := vresp.Attributes["version"]
×
677
                        if !ok {
×
678
                                conn.log.Debug("No version attribute in the response??!")
×
679
                                conn.logger.WithFields(logrus.Fields{
×
680
                                        "mod":                            "APICAPI",
×
681
                                        "firmwareCtrlrRunning":           vresp,
×
682
                                        "firmwareCtrlRunning Attributes": vresp.Attributes,
×
683
                                }).Debug("Response:")
×
684
                        } else {
×
685
                                switch version := version.(type) {
×
686
                                default:
×
687
                                case string:
×
688
                                        version_split := strings.Split(version, "(")
×
689
                                        version_number, err := strconv.ParseFloat(version_split[0], 64)
×
690
                                        conn.log.Info("Actual APIC version:", version, " Stripped out version:", version_number)
×
691
                                        if err == nil {
×
692
                                                conn.version = version //return the actual version
×
693
                                        }
×
694
                                }
695
                        }
696
                }
697
        }
698
        return conn.version, nil
×
699
}
700

701
func (conn *ApicConnection) Run(stopCh <-chan struct{}) {
1✔
702
        if len(conn.Apic) == 0 {
1✔
703
                conn.log.Warning("APIC connection not configured")
×
704
                return
×
705
        }
×
706

707
        if conn.version >= "6.0(4c)" {
1✔
708
                metadata["fvBD"].attributes["serviceBdRoutingDisable"] = "no"
×
709
        }
×
710

711
        for !conn.stopped {
2✔
712
                func() {
2✔
713
                        defer func() {
2✔
714
                                conn.ApicIndex = (conn.ApicIndex + 1) % len(conn.Apic)
1✔
715
                                time.Sleep(conn.ReconnectInterval)
1✔
716
                        }()
1✔
717

718
                        conn.logger.WithFields(logrus.Fields{
1✔
719
                                "mod":  "APICAPI",
1✔
720
                                "host": conn.Apic[conn.ApicIndex],
1✔
721
                        }).Info("Connecting to APIC")
1✔
722

1✔
723
                        for dn := range conn.subscriptions.subs {
2✔
724
                                conn.subscriptions.subs[dn].childSubs = make(map[string]subComponent)
1✔
725
                        }
1✔
726
                        conn.subscriptions.ids = make(map[string]string)
1✔
727

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

1✔
735
                        uri := fmt.Sprintf("/socket%s", token)
1✔
736
                        url := fmt.Sprintf("wss://%s%s",
1✔
737
                                conn.Apic[conn.ApicIndex], uri)
1✔
738
                        header := make(http.Header)
1✔
739
                        if conn.signer != nil {
2✔
740
                                sig, err := conn.signer.sign("GET", uri, nil)
1✔
741
                                if err != nil {
1✔
742
                                        conn.log.Error("Failed to sign request: ", err)
×
743
                                        return
×
744
                                }
×
745
                                header.Set("Cookie", conn.apicSigCookie(sig, token))
1✔
746
                        }
747

748
                        conn.connection, _, err = conn.dialer.Dial(url, header)
1✔
749
                        if err != nil {
1✔
750
                                conn.log.Error("Failed to open APIC websocket: ", err)
×
751
                                return
×
752
                        }
×
753
                        conn.log.Info("Websocket connected!")
1✔
754
                        conn.runConn(stopCh)
1✔
755
                }()
756
        }
757
}
758

759
func (conn *ApicConnection) refresh() {
1✔
760
        if conn.signer == nil {
2✔
761
                url := fmt.Sprintf("https://%s/api/aaaRefresh.json",
1✔
762
                        conn.Apic[conn.ApicIndex])
1✔
763
                req, err := http.NewRequest("GET", url, http.NoBody)
1✔
764
                if err != nil {
1✔
765
                        conn.log.Error("Could not create request: ", err)
×
766
                        return
×
767
                }
×
768
                resp, err := conn.client.Do(req)
1✔
769
                if err != nil {
2✔
770
                        conn.log.Error("Failed to refresh APIC session: ", err)
1✔
771
                        conn.restart()
1✔
772
                        return
1✔
773
                }
1✔
774
                if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
775
                        conn.logErrorResp("Error while refreshing login", resp)
1✔
776
                        complete(resp)
1✔
777
                        conn.restart()
1✔
778
                        return
1✔
779
                }
1✔
780
                complete(resp)
1✔
781
                conn.log.Debugf("Refresh: url %v", url)
1✔
782
        }
783

784
        for _, sub := range conn.subscriptions.subs {
2✔
785
                refreshId := func(id string) {
2✔
786
                        uri := fmt.Sprintf("/api/subscriptionRefresh.json?id=%s", id)
1✔
787
                        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
788
                        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
789
                        if err != nil {
1✔
790
                                conn.log.Error("Could not create request: ", err)
×
791
                                return
×
792
                        }
×
793
                        conn.sign(req, uri, nil)
1✔
794
                        resp, err := conn.client.Do(req)
1✔
795
                        if err != nil {
1✔
796
                                conn.log.Error("Failed to refresh APIC subscription: ", err)
×
797
                                conn.restart()
×
798
                                return
×
799
                        }
×
800
                        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
801
                                conn.logErrorResp("Error while refreshing subscription", resp)
1✔
802
                                complete(resp)
1✔
803
                                conn.restart()
1✔
804
                                return
1✔
805
                        }
1✔
806
                        complete(resp)
1✔
807
                        conn.log.Debugf("Refresh sub: url %v", url)
1✔
808
                        time.Sleep(conn.SubscriptionDelay)
1✔
809
                }
810
                if len(sub.childSubs) > 0 {
1✔
811
                        for id := range sub.childSubs {
×
812
                                refreshId(id)
×
813
                        }
×
814
                } else {
1✔
815
                        refreshId(sub.id)
1✔
816
                }
1✔
817
        }
818
}
819

820
func (conn *ApicConnection) logErrorResp(message string, resp *http.Response) {
1✔
821
        var apicresp ApicResponse
1✔
822
        err := json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
823
        if err != nil {
1✔
824
                conn.log.Error("Could not parse APIC error response: ", err)
×
825
        } else {
1✔
826
                code := 0
1✔
827
                text := ""
1✔
828
                for _, o := range apicresp.Imdata {
2✔
829
                        if ob, ok := o["error"]; ok {
2✔
830
                                if ob.Attributes != nil {
2✔
831
                                        if t, isStr := ob.Attributes["text"].(string); isStr {
2✔
832
                                                text = t
1✔
833
                                        }
1✔
834
                                        if c, isInt := ob.Attributes["code"].(int); isInt {
1✔
835
                                                code = c
×
836
                                        }
×
837
                                }
838
                        }
839
                }
840
                conn.logger.WithFields(logrus.Fields{
1✔
841
                        "mod":    "APICAPI",
1✔
842
                        "text":   text,
1✔
843
                        "code":   code,
1✔
844
                        "url":    resp.Request.URL,
1✔
845
                        "status": resp.StatusCode,
1✔
846
                }).Error(message)
1✔
847
        }
848
}
849

850
// To make sure cluster's POD/NodeBDs and L3OUT are all mapped
851
// to same and correct VRF.
852
func (conn *ApicConnection) ValidateAciVrfAssociation(acivrfdn string, expectedVrfRelations []string) error {
×
853
        var aciVrfBdL3OuttDns []string
×
854
        args := []string{
×
855
                "query-target=subtree",
×
856
                "target-subtree-class=fvRtCtx,fvRtEctx",
×
857
        }
×
858

×
859
        uri := fmt.Sprintf("/api/mo/%s.json?%s", acivrfdn, strings.Join(args, "&"))
×
860
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
861
        req, err := http.NewRequest("GET", url, http.NoBody)
×
862
        if err != nil {
×
863
                conn.log.Error("Could not create request: ", err)
×
864
                return err
×
865
        }
×
866
        conn.sign(req, uri, nil)
×
867
        resp, err := conn.client.Do(req)
×
868
        if err != nil {
×
869
                conn.log.Error("Could not get subtree for ", acivrfdn, ": ", err)
×
870
                return err
×
871
        }
×
872
        defer complete(resp)
×
873
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
×
874
                conn.logErrorResp("Could not get subtree for "+acivrfdn, resp)
×
875
                return err
×
876
        }
×
877

878
        var apicresp ApicResponse
×
879
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
×
880
        if err != nil {
×
881
                conn.log.Error("Could not parse APIC response: ", err)
×
882
                return err
×
883
        }
×
884

885
        for _, obj := range apicresp.Imdata {
×
886
                for _, body := range obj {
×
887
                        tDn, ok := body.Attributes["tDn"].(string)
×
888
                        if !ok {
×
889
                                continue
×
890
                        }
891
                        aciVrfBdL3OuttDns = append(aciVrfBdL3OuttDns, tDn)
×
892
                }
893
        }
894
        sort.Strings(aciVrfBdL3OuttDns)
×
895
        conn.log.Debug("aciVrfBdL3OuttDns:", aciVrfBdL3OuttDns)
×
896
        for _, expectedDn := range expectedVrfRelations {
×
897
                i := sort.SearchStrings(aciVrfBdL3OuttDns, expectedDn)
×
898
                if !(i < len(aciVrfBdL3OuttDns) && aciVrfBdL3OuttDns[i] == expectedDn) {
×
899
                        conn.log.Debug("Missing (or) Incorrect Vrf association: ", expectedDn)
×
900
                        return errors.New("Incorrect Pod/NodeBD/L3OUT VRF association")
×
901
                }
×
902
        }
903
        return nil
×
904
}
905

906
func (conn *ApicConnection) getSubtreeDn(dn string, respClasses []string,
907
        updateHandlers []ApicObjectHandler) {
1✔
908
        args := []string{
1✔
909
                "rsp-subtree=full",
1✔
910
        }
1✔
911

1✔
912
        if len(respClasses) > 0 {
2✔
913
                args = append(args, "rsp-subtree-class="+strings.Join(respClasses, ","))
1✔
914
        }
1✔
915
        // properly encoding the URI query parameters breaks APIC
916
        uri := fmt.Sprintf("/api/mo/%s.json?%s", dn, strings.Join(args, "&"))
1✔
917
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
918
        conn.log.Debugf("URL: %v", url)
1✔
919
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
920
        if err != nil {
1✔
921
                conn.log.Error("Could not create request: ", err)
×
922
                return
×
923
        }
×
924
        conn.sign(req, uri, nil)
1✔
925
        resp, err := conn.client.Do(req)
1✔
926
        if err != nil {
1✔
927
                conn.log.Error("Could not get subtree for ", dn, ": ", err)
×
928
                conn.restart()
×
929
                return
×
930
        }
×
931
        defer complete(resp)
1✔
932
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
933
                conn.logErrorResp("Could not get subtree for "+dn, resp)
×
934
                conn.restart()
×
935
                return
×
936
        }
×
937

938
        var apicresp ApicResponse
1✔
939
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
940
        if err != nil {
1✔
941
                conn.log.Error("Could not parse APIC response: ", err)
×
942
                return
×
943
        }
×
944
        if len(apicresp.Imdata) == 0 {
1✔
945
                conn.log.Debugf("No subtree found for dn %s", dn)
×
946
        }
×
947

948
        for _, obj := range apicresp.Imdata {
2✔
949
                conn.logger.WithFields(logrus.Fields{
1✔
950
                        "mod": "APICAPI",
1✔
951
                        "dn":  obj.GetDn(),
1✔
952
                        "obj": obj,
1✔
953
                }).Debug("Object updated on APIC")
1✔
954
                var count int
1✔
955
                prepareApicCache("", obj, &count)
1✔
956

1✔
957
                handled := false
1✔
958
                for _, handler := range updateHandlers {
1✔
959
                        if handler(obj) {
×
960
                                handled = true
×
961
                                break
×
962
                        }
963
                }
964
                if handled {
1✔
965
                        continue
×
966
                }
967
                conn.reconcileApicObject(obj)
1✔
968
        }
969
}
970

971
func (conn *ApicConnection) queuePriorityDn(dn string) {
×
972
        conn.indexMutex.Lock()
×
973
        if conn.priorityQueue != nil {
×
974
                conn.priorityQueue.Add(dn)
×
975
        }
×
976
        conn.indexMutex.Unlock()
×
977
}
978

979
func (conn *ApicConnection) queueDn(dn string) {
1✔
980
        conn.indexMutex.Lock()
1✔
981
        if conn.deltaQueue != nil {
2✔
982
                conn.deltaQueue.Add(dn)
1✔
983
        }
1✔
984
        conn.indexMutex.Unlock()
1✔
985
}
986

987
func (conn *ApicConnection) ForceRelogin() {
×
988
        conn.token = ""
×
989
}
×
990

991
func (conn *ApicConnection) PostDnInline(dn string, obj ApicObject) error {
×
992
        conn.logger.WithFields(logrus.Fields{
×
993
                "mod": "APICAPI",
×
994
                "dn":  dn,
×
995
                "obj": obj,
×
996
        }).Debug("Posting Dn Inline")
×
997
        if conn.token == "" {
×
998
                token, err := conn.login()
×
999
                if err != nil {
×
1000
                        conn.log.Errorf("Login: %v", err)
×
1001
                        return err
×
1002
                }
×
1003
                conn.token = token
×
1004
        }
1005
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
×
1006
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
1007
        raw, err := json.Marshal(obj)
×
1008
        if err != nil {
×
1009
                conn.log.Error("Could not serialize object for dn ", dn, ": ", err)
×
1010
                return err
×
1011
        }
×
1012
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
×
1013
        if err != nil {
×
1014
                conn.log.Error("Could not create request: ", err)
×
1015
                return err
×
1016
        }
×
1017
        conn.sign(req, uri, raw)
×
1018
        req.Header.Set("Content-Type", "application/json")
×
1019
        conn.log.Infof("Post: %+v", req)
×
1020
        resp, err := conn.client.Do(req)
×
1021
        if err != nil {
×
1022
                conn.log.Error("Could not update dn ", dn, ": ", err)
×
1023
                return err
×
1024
        }
×
1025

1026
        complete(resp)
×
1027
        if resp.StatusCode != http.StatusOK {
×
1028
                return fmt.Errorf("Status: %v", resp.StatusCode)
×
1029
        }
×
1030
        return nil
×
1031
}
1032

1033
func (conn *ApicConnection) DeleteDnInline(dn string) error {
1✔
1034
        conn.logger.WithFields(logrus.Fields{
1✔
1035
                "mod": "APICAPI",
1✔
1036
                "dn":  dn,
1✔
1037
        }).Debug("Deleting Dn Inline")
1✔
1038
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1039
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1040
        req, err := http.NewRequest("DELETE", url, http.NoBody)
1✔
1041
        if err != nil {
1✔
1042
                conn.log.Error("Could not create delete request: ", err)
×
1043
                return err
×
1044
        }
×
1045
        conn.sign(req, uri, nil)
1✔
1046
        resp, err := conn.client.Do(req)
1✔
1047
        if err != nil {
2✔
1048
                conn.log.Error("Could not delete dn ", dn, ": ", err)
1✔
1049
                return err
1✔
1050
        }
1✔
1051
        defer complete(resp)
×
1052
        return nil
×
1053
}
1054

1055
func (conn *ApicConnection) postDn(dn string, obj ApicObject) bool {
1✔
1056
        conn.logger.WithFields(logrus.Fields{
1✔
1057
                "mod": "APICAPI",
1✔
1058
                "dn":  dn,
1✔
1059
                "obj": obj,
1✔
1060
        }).Debug("Posting Dn")
1✔
1061

1✔
1062
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1063
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1064
        raw, err := json.Marshal(obj)
1✔
1065
        if err != nil {
1✔
1066
                conn.log.Error("Could not serialize object for dn ", dn, ": ", err)
×
1067
        }
×
1068
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
1✔
1069
        if err != nil {
1✔
1070
                conn.log.Error("Could not create request: ", err)
×
1071
                conn.restart()
×
1072
                return false
×
1073
        }
×
1074
        conn.sign(req, uri, raw)
1✔
1075
        req.Header.Set("Content-Type", "application/json")
1✔
1076
        resp, err := conn.client.Do(req)
1✔
1077
        if err != nil {
1✔
1078
                conn.log.Error("Could not update dn ", dn, ": ", err)
×
1079
                conn.restart()
×
1080
                return false
×
1081
        }
×
1082
        defer complete(resp)
1✔
1083
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1084
                conn.logErrorResp("Could not update dn "+dn, resp)
×
1085
                if resp.StatusCode == 400 {
×
1086
                        return true
×
1087
                }
×
1088
                conn.restart()
×
1089
        }
1090
        return false
1✔
1091
}
1092

1093
func (conn *ApicConnection) Delete(dn string) bool {
1✔
1094
        if dn == "" {
1✔
1095
                conn.log.Debug("Skip delete for empty Dn: ")
×
1096
                return false
×
1097
        }
×
1098
        dnSlice := strings.Split(dn, "/")
1✔
1099
        identifier := dnSlice[len(dnSlice)-1]
1✔
1100
        iSlice := strings.SplitN(identifier, "-", 2)
1✔
1101
        if len(iSlice) == 2 {
2✔
1102
                if iSlice[0] == "ip" {
1✔
1103
                        addr := strings.Trim(iSlice[1], "[]")
×
1104
                        obj := NewDeleteHostprotRemoteIp(addr)
×
1105
                        conn.log.Debug("Posting delete of dn ", dn)
×
1106
                        return conn.postDn(dn, obj)
×
1107
                }
×
1108
        }
1109
        return conn.DeleteDn(dn)
1✔
1110
}
1111

1112
func (conn *ApicConnection) DeleteDn(dn string) bool {
1✔
1113
        if dn == "" {
1✔
1114
                conn.log.Debug("Skip delete for empty Dn: ")
×
1115
                return false
×
1116
        }
×
1117
        conn.logger.WithFields(logrus.Fields{
1✔
1118
                "mod": "APICAPI",
1✔
1119
                "dn":  dn,
1✔
1120
        }).Debug("Deleting Dn")
1✔
1121
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1122
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1123
        req, err := http.NewRequest("DELETE", url, http.NoBody)
1✔
1124
        if err != nil {
1✔
1125
                conn.log.Error("Could not create delete request: ", err)
×
1126
                conn.restart()
×
1127
                return false
×
1128
        }
×
1129
        conn.sign(req, uri, nil)
1✔
1130
        resp, err := conn.client.Do(req)
1✔
1131
        if err != nil {
1✔
1132
                conn.log.Error("Could not delete dn ", dn, ": ", err)
×
1133
                conn.restart()
×
1134
                return false
×
1135
        }
×
1136
        defer complete(resp)
1✔
1137
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1138
                conn.logErrorResp("Could not delete dn "+dn, resp)
×
1139
                conn.restart()
×
1140
        }
×
1141
        return false
1✔
1142
}
1143

1144
func doComputeRespClasses(targetClasses []string,
1145
        visited map[string]bool) {
1✔
1146
        for _, class := range targetClasses {
2✔
1147
                if visited[class] {
1✔
1148
                        continue
×
1149
                }
1150
                visited[class] = true
1✔
1151
                if md, ok := metadata[class]; ok {
2✔
1152
                        doComputeRespClasses(md.children, visited)
1✔
1153
                }
1✔
1154
        }
1155
}
1156

1157
func computeRespClasses(targetClasses []string) []string {
1✔
1158
        visited := make(map[string]bool)
1✔
1159
        doComputeRespClasses(targetClasses, visited)
1✔
1160

1✔
1161
        // Don't include targetclasses in rsp-subtree
1✔
1162
        // because they are implicitly included
1✔
1163
        for i := range targetClasses {
2✔
1164
                delete(visited, targetClasses[i])
1✔
1165
        }
1✔
1166

1167
        var respClasses []string
1✔
1168
        for class := range visited {
2✔
1169
                respClasses = append(respClasses, class)
1✔
1170
        }
1✔
1171
        respClasses = append(respClasses, "tagAnnotation")
1✔
1172
        return respClasses
1✔
1173
}
1174

1175
// AddSubscriptionTree subscribe at a subtree level. class specifies
1176
// the root. Changes will cause entire subtree of the rootdn to be fetched
1177
func (conn *ApicConnection) AddSubscriptionTree(class string,
1178
        targetClasses []string, targetFilter string) {
1✔
1179
        if _, ok := classDepth[class]; !ok {
1✔
1180
                errStr := fmt.Sprintf("classDepth not for class %s", class)
×
1181
                panic(errStr)
×
1182
        }
1183

1184
        conn.indexMutex.Lock()
1✔
1185
        conn.subscriptions.subs[class] = &subscription{
1✔
1186
                kind:          apicSubTree,
1✔
1187
                childSubs:     make(map[string]subComponent),
1✔
1188
                targetClasses: targetClasses,
1✔
1189
                targetFilter:  targetFilter,
1✔
1190
        }
1✔
1191
        conn.indexMutex.Unlock()
1✔
1192
}
1193

1194
func (conn *ApicConnection) AddSubscriptionClass(class string,
1195
        targetClasses []string, targetFilter string) {
1✔
1196
        conn.indexMutex.Lock()
1✔
1197
        conn.subscriptions.subs[class] = &subscription{
1✔
1198
                kind:          apicSubClass,
1✔
1199
                childSubs:     make(map[string]subComponent),
1✔
1200
                targetClasses: targetClasses,
1✔
1201
                respClasses:   computeRespClasses(targetClasses),
1✔
1202
                targetFilter:  targetFilter,
1✔
1203
        }
1✔
1204
        conn.indexMutex.Unlock()
1✔
1205
}
1✔
1206

1207
func (conn *ApicConnection) AddSubscriptionDn(dn string,
1208
        targetClasses []string) {
1✔
1209
        conn.logger.WithFields(logrus.Fields{
1✔
1210
                "mod": "APICAPI",
1✔
1211
                "dn":  dn,
1✔
1212
        }).Debug("Adding Subscription for Dn")
1✔
1213

1✔
1214
        conn.indexMutex.Lock()
1✔
1215
        conn.subscriptions.subs[dn] = &subscription{
1✔
1216
                kind:          apicSubDn,
1✔
1217
                childSubs:     make(map[string]subComponent),
1✔
1218
                targetClasses: targetClasses,
1✔
1219
                respClasses:   computeRespClasses(targetClasses),
1✔
1220
        }
1✔
1221
        conn.indexMutex.Unlock()
1✔
1222
}
1✔
1223

1224
func (conn *ApicConnection) SetSubscriptionHooks(value string,
1225
        updateHook ApicObjectHandler, deleteHook ApicDnHandler) {
1✔
1226
        conn.indexMutex.Lock()
1✔
1227
        if s, ok := conn.subscriptions.subs[value]; ok {
2✔
1228
                s.updateHook = updateHook
1✔
1229
                s.deleteHook = deleteHook
1✔
1230
        }
1✔
1231
        conn.indexMutex.Unlock()
1✔
1232
}
1233

1234
func (conn *ApicConnection) GetApicResponse(uri string) (ApicResponse, error) {
1✔
1235
        conn.log.Debug("apicIndex: ", conn.Apic[conn.ApicIndex], " uri: ", uri)
1✔
1236
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1237
        var apicresp ApicResponse
1✔
1238
        conn.log.Debug("Apic Get url: ", url)
1✔
1239
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1240
        if err != nil {
1✔
1241
                conn.log.Error("Could not create request: ", err)
×
1242
                return apicresp, err
×
1243
        }
×
1244
        conn.sign(req, uri, nil)
1✔
1245
        resp, err := conn.client.Do(req)
1✔
1246
        if err != nil {
1✔
1247
                conn.log.Error("Could not get response for ", url, ": ", err)
×
1248
                return apicresp, err
×
1249
        }
×
1250
        defer complete(resp)
1✔
1251
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1252
                conn.logErrorResp("Could not get subtree for "+url, resp)
×
1253
                return apicresp, err
×
1254
        }
×
1255
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
1256
        if err != nil {
1✔
1257
                conn.log.Error("Could not parse APIC response: ", err)
×
1258
                return apicresp, err
×
1259
        }
×
1260
        return apicresp, nil
1✔
1261
}
1262

1263
func (conn *ApicConnection) doSubscribe(args []string,
1264
        kind, value, refresh_interval string, apicresp *ApicResponse) bool {
1✔
1265
        // properly encoding the URI query parameters breaks APIC
1✔
1266
        uri := fmt.Sprintf("/api/%s/%s.json?subscription=yes&%s%s",
1✔
1267
                kind, value, refresh_interval, strings.Join(args, "&"))
1✔
1268
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1269
        conn.log.Info("APIC connection URL: ", url)
1✔
1270

1✔
1271
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1272
        if err != nil {
1✔
1273
                conn.log.Error("Could not create request: ", err)
×
1274
                return false
×
1275
        }
×
1276
        conn.sign(req, uri, nil)
1✔
1277
        resp, err := conn.client.Do(req)
1✔
1278
        if err != nil {
1✔
1279
                conn.log.Error("Failed to subscribe to ", value, ": ", err)
×
1280
                return false
×
1281
        }
×
1282
        defer complete(resp)
1✔
1283
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1284
                conn.logErrorResp("Could not subscribe to "+value, resp)
×
1285
                return false
×
1286
        }
×
1287

1288
        err = json.NewDecoder(resp.Body).Decode(apicresp)
1✔
1289
        if err != nil {
1✔
1290
                conn.log.Error("Could not decode APIC response", err)
×
1291
                return false
×
1292
        }
×
1293
        time.Sleep(conn.SubscriptionDelay)
1✔
1294
        return true
1✔
1295
}
1296

1297
func (conn *ApicConnection) subscribe(value string, sub *subscription) bool {
1✔
1298
        baseArgs := []string{
1✔
1299
                "query-target=subtree",
1✔
1300
                "rsp-subtree=full",
1✔
1301
                "target-subtree-class=" + strings.Join(sub.targetClasses, ","),
1✔
1302
        }
1✔
1303

1✔
1304
        const defaultArgs = 1
1✔
1305
        var argCount = defaultArgs
1✔
1306
        var combinableSubClasses, separableSubClasses []string
1✔
1307
        var splitTargetClasses [][]string
1✔
1308
        var splitRespClasses [][]string
1✔
1309
        var argSet [][]string
1✔
1310
        argSet = make([][]string, defaultArgs)
1✔
1311
        argSet[defaultArgs-1] = make([]string, len(baseArgs))
1✔
1312
        copy(argSet[defaultArgs-1], baseArgs)
1✔
1313
        if sub.respClasses != nil {
2✔
1314
                separateClasses := func(classes []string, combClasses, sepClasses *[]string) {
2✔
1315
                        for i := range classes {
2✔
1316
                                if classMeta, ok := metadata[classes[i]]; ok {
2✔
1317
                                        if classes[i] == "tagAnnotation" {
2✔
1318
                                                continue
1✔
1319
                                        }
1320
                                        if classMeta.hints != nil && classMeta.hints["cardinality"] == "high" {
2✔
1321
                                                *sepClasses = append(*sepClasses, classes[i])
1✔
1322
                                                continue
1✔
1323
                                        }
1324
                                        *combClasses = append(*combClasses, classes[i])
1✔
1325
                                }
1326
                        }
1327
                }
1328
                separateClasses(sub.respClasses, &combinableSubClasses, &separableSubClasses)
1✔
1329

1✔
1330
                // In case there are high cardinality children, we register for all the classes individually.
1✔
1331
                // The concept of target-subtree and rsp-subtree class cannot be used because of the tagAnnotation object
1✔
1332
                // vmmInjectedLabel is added for every object, so getting it separately will not be scalable
1✔
1333
                if len(separableSubClasses) > 0 {
2✔
1334
                        separateClasses(sub.targetClasses, &combinableSubClasses, &separableSubClasses)
1✔
1335
                        separableSubClasses = append(separableSubClasses, combinableSubClasses...)
1✔
1336
                        baseArgs = []string{
1✔
1337
                                "query-target=subtree",
1✔
1338
                                "rsp-subtree=children",
1✔
1339
                        }
1✔
1340
                        subscribingClasses := make(map[string]bool)
1✔
1341
                        argSet = make([][]string, len(separableSubClasses))
1✔
1342
                        splitTargetClasses = make([][]string, len(separableSubClasses))
1✔
1343
                        splitRespClasses = make([][]string, len(separableSubClasses))
1✔
1344

1✔
1345
                        argCount = 0
1✔
1346
                        for i := range separableSubClasses {
2✔
1347
                                // Eliminate duplicates
1✔
1348
                                if _, ok := subscribingClasses[separableSubClasses[i]]; ok {
1✔
1349
                                        continue
×
1350
                                }
1351
                                subscribingClasses[separableSubClasses[i]] = true
1✔
1352
                                argSet[argCount] = make([]string, len(baseArgs))
1✔
1353
                                copy(argSet[argCount], baseArgs)
1✔
1354
                                argSet[argCount] = append(argSet[argCount], "target-subtree-class="+separableSubClasses[i], "rsp-subtree-class=tagAnnotation")
1✔
1355
                                splitTargetClasses[argCount] = append(splitTargetClasses[argCount], separableSubClasses[i])
1✔
1356
                                splitRespClasses[argCount] = computeRespClasses([]string{separableSubClasses[i]})
1✔
1357
                                argCount++
1✔
1358
                        }
1359
                } else {
1✔
1360
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], "rsp-subtree-class="+strings.Join(combinableSubClasses, ",")+",tagAnnotation")
1✔
1361
                }
1✔
1362
        }
1363
        if sub.targetFilter != "" {
2✔
1364
                targetFilterArgs := "query-target-filter=" + sub.targetFilter
1✔
1365
                if len(separableSubClasses) == 0 {
2✔
1366
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], targetFilterArgs)
1✔
1367
                } else {
1✔
1368
                        for i := 0; i < argCount; i++ {
×
1369
                                argSet[i] = append(argSet[i], targetFilterArgs)
×
1370
                        }
×
1371
                }
1372
        }
1373

1374
        kind := "mo"
1✔
1375
        if sub.kind == apicSubClass || sub.kind == apicSubTree {
2✔
1376
                kind = "class"
1✔
1377
        }
1✔
1378

1379
        refresh_interval := ""
1✔
1380
        if conn.RefreshInterval != 0 {
2✔
1381
                refresh_interval = fmt.Sprintf("refresh-timeout=%v&",
1✔
1382
                        conn.RefreshInterval.Seconds())
1✔
1383
        }
1✔
1384
        for i := 0; i < argCount; i++ {
2✔
1385
                var apicresp ApicResponse
1✔
1386
                if !conn.doSubscribe(argSet[i], kind, value, refresh_interval, &apicresp) {
1✔
1387
                        return false
×
1388
                }
×
1389
                subId, ok := apicresp.SubscriptionId.(string)
1✔
1390
                if !ok {
1✔
1391
                        conn.log.Error("Subscription ID is not a string")
×
1392
                        return false
×
1393
                }
×
1394

1395
                conn.logger.WithFields(logrus.Fields{
1✔
1396
                        "mod":   "APICAPI",
1✔
1397
                        "value": value,
1✔
1398
                        "kind":  kind,
1✔
1399
                        "id":    subId,
1✔
1400
                        "args":  argSet[i],
1✔
1401
                }).Debug("Subscribed")
1✔
1402

1✔
1403
                conn.indexMutex.Lock()
1✔
1404
                if argCount > defaultArgs {
2✔
1405
                        sub.childSubs[subId] = subComponent{
1✔
1406
                                targetClasses: splitTargetClasses[i],
1✔
1407
                                respClasses:   splitRespClasses[i],
1✔
1408
                        }
1✔
1409
                } else {
2✔
1410
                        conn.subscriptions.subs[value].id = subId
1✔
1411
                }
1✔
1412
                conn.subscriptions.ids[subId] = value
1✔
1413
                conn.indexMutex.Unlock()
1✔
1414
                var respObjCount int
1✔
1415
                for _, obj := range apicresp.Imdata {
2✔
1416
                        dn := obj.GetDn()
1✔
1417
                        if dn == "" {
1✔
1418
                                continue
×
1419
                        }
1420
                        conn.indexMutex.Lock()
1✔
1421
                        subIds, found := conn.cacheDnSubIds[dn]
1✔
1422
                        if !found {
2✔
1423
                                subIds = make(map[string]bool)
1✔
1424
                                conn.cacheDnSubIds[dn] = subIds
1✔
1425
                        }
1✔
1426
                        subIds[subId] = true
1✔
1427
                        conn.indexMutex.Unlock()
1✔
1428

1✔
1429
                        if sub.updateHook != nil && sub.updateHook(obj) {
2✔
1430
                                continue
1✔
1431
                        }
1432

1433
                        tag := obj.GetTag()
1✔
1434
                        if !conn.isSyncTag(tag) {
1✔
1435
                                continue
×
1436
                        }
1437

1438
                        conn.logger.WithFields(logrus.Fields{
1✔
1439
                                "mod": "APICAPI",
1✔
1440
                                "dn":  dn,
1✔
1441
                                "tag": tag,
1✔
1442
                                "obj": obj,
1✔
1443
                        }).Debug("Caching")
1✔
1444
                        var count int
1✔
1445
                        prepareApicCache("", obj, &count)
1✔
1446
                        respObjCount += count
1✔
1447
                        conn.indexMutex.Lock()
1✔
1448
                        conn.cachedState[tag] = append(conn.cachedState[tag], obj)
1✔
1449
                        conn.indexMutex.Unlock()
1✔
1450
                }
1451
                if respObjCount >= ApicSubscriptionResponseMoMaxCount/10 {
1✔
1452
                        conn.logger.WithFields(logrus.Fields{
×
1453
                                "args":       argSet[i],
×
1454
                                "moCount":    respObjCount,
×
1455
                                "maxAllowed": ApicSubscriptionResponseMoMaxCount,
×
1456
                        }).Warning("Subscription response is significantly large. Each new object will add 2 Mos atleast and twice the number of labels on the object")
×
1457
                } else {
1✔
1458
                        conn.logger.WithFields(logrus.Fields{
1✔
1459
                                "moCount": respObjCount,
1✔
1460
                        }).Debug("ResponseObjCount")
1✔
1461
                }
1✔
1462
        }
1463

1464
        return true
1✔
1465
}
1466

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

1469
func (conn *ApicConnection) isSyncTag(tag string) bool {
1✔
1470
        return tagRegexp.MatchString(tag) &&
1✔
1471
                strings.HasPrefix(tag, conn.prefix+"-")
1✔
1472
}
1✔
1473

1474
func getRootDn(dn, rootClass string) string {
1✔
1475
        depth := classDepth[rootClass]
1✔
1476
        parts := strings.Split(dn, "/")
1✔
1477
        parts = parts[:depth]
1✔
1478
        return strings.Join(parts, "/")
1✔
1479
}
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