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

noironetworks / aci-containers / 9264

05 Jul 2024 09:00AM UTC coverage: 71.577% (-0.04%) from 71.615%
9264

push

travis-pro

akhilamohanan
Set unkMacUcastAct of service BD as proxy

Sets unkMacUcastAct of service BD as proxy instaed of flood

1 of 1 new or added line in 1 file covered. (100.0%)

10 existing lines in 3 files now uncovered.

11214 of 15667 relevant lines covered (71.58%)

0.81 hits per line

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

67.68
/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 {
1✔
310
                                                if conn.deltaQueue != nil {
2✔
311
                                                        conn.deltaQueue.Add(dn)
1✔
312
                                                }
1✔
313
                                        }
314
                                        conn.indexMutex.Unlock()
1✔
315
                                }
316
                        }
317
                }
318
        }
319
}
320

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

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

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

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

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

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

378
        if rootDn == "" {
2✔
379
                rootDn = dn
1✔
380
        }
1✔
381

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

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

413
        return requeue
1✔
414
}
415

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

447
type fullSync struct{}
448

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

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

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

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

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

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

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

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

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

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

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

611
        conn.log.Debug("Exiting websocket handler")
1✔
612
}
613

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1030
func (conn *ApicConnection) PostDnInline(dn string, obj ApicObject) error {
×
1031
        conn.logger.WithFields(logrus.Fields{
×
1032
                "mod": "APICAPI",
×
1033
                "dn":  dn,
×
1034
                "obj": obj,
×
1035
        }).Debug("Posting Dn Inline")
×
1036
        if conn.token == "" {
×
1037
                token, err := conn.login()
×
1038
                if err != nil {
×
1039
                        conn.log.Errorf("Login: %v", err)
×
1040
                        return err
×
1041
                }
×
1042
                conn.token = token
×
1043
        }
1044
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
×
1045
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
1046
        raw, err := json.Marshal(obj)
×
1047
        if err != nil {
×
1048
                conn.log.Error("Could not serialize object for dn ", dn, ": ", err)
×
1049
                return err
×
1050
        }
×
1051
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
×
1052
        if err != nil {
×
1053
                conn.log.Error("Could not create request: ", err)
×
1054
                return err
×
1055
        }
×
1056
        conn.sign(req, uri, raw)
×
1057
        req.Header.Set("Content-Type", "application/json")
×
1058
        conn.log.Infof("Post: %+v", req)
×
1059
        resp, err := conn.client.Do(req)
×
1060
        if err != nil {
×
1061
                conn.log.Error("Could not update dn ", dn, ": ", err)
×
1062
                return err
×
1063
        }
×
1064

1065
        complete(resp)
×
1066
        if resp.StatusCode != http.StatusOK {
×
1067
                return fmt.Errorf("Status: %v", resp.StatusCode)
×
1068
        }
×
1069
        return nil
×
1070
}
1071

1072
func (conn *ApicConnection) DeleteDnInline(dn string) error {
1✔
1073
        conn.logger.WithFields(logrus.Fields{
1✔
1074
                "mod": "APICAPI",
1✔
1075
                "dn":  dn,
1✔
1076
        }).Debug("Deleting Dn Inline")
1✔
1077
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1078
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1079
        req, err := http.NewRequest("DELETE", url, http.NoBody)
1✔
1080
        if err != nil {
1✔
1081
                conn.log.Error("Could not create delete request: ", err)
×
1082
                return err
×
1083
        }
×
1084
        conn.sign(req, uri, nil)
1✔
1085
        resp, err := conn.client.Do(req)
1✔
1086
        if err != nil {
2✔
1087
                conn.log.Error("Could not delete dn ", dn, ": ", err)
1✔
1088
                return err
1✔
1089
        }
1✔
1090
        defer complete(resp)
×
1091
        return nil
×
1092
}
1093

1094
func (conn *ApicConnection) postDn(dn string, obj ApicObject) bool {
1✔
1095
        conn.logger.WithFields(logrus.Fields{
1✔
1096
                "mod": "APICAPI",
1✔
1097
                "dn":  dn,
1✔
1098
                "obj": obj,
1✔
1099
        }).Debug("Posting Dn")
1✔
1100

1✔
1101
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1102
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1103
        raw, err := json.Marshal(obj)
1✔
1104
        if err != nil {
1✔
1105
                conn.log.Error("Could not serialize object for dn ", dn, ": ", err)
×
1106
        }
×
1107
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
1✔
1108
        if err != nil {
1✔
1109
                conn.log.Error("Could not create request: ", err)
×
1110
                conn.restart()
×
1111
                return false
×
1112
        }
×
1113
        conn.sign(req, uri, raw)
1✔
1114
        req.Header.Set("Content-Type", "application/json")
1✔
1115
        resp, err := conn.client.Do(req)
1✔
1116
        if err != nil {
1✔
1117
                conn.log.Error("Could not update dn ", dn, ": ", err)
×
1118
                conn.restart()
×
1119
                return false
×
1120
        }
×
1121
        defer complete(resp)
1✔
1122
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1123
                conn.logErrorResp("Could not update dn "+dn, resp)
×
1124
                if resp.StatusCode == 400 {
×
1125
                        return true
×
1126
                }
×
1127
                conn.restart()
×
1128
        }
1129
        return false
1✔
1130
}
1131

1132
func (conn *ApicConnection) Delete(dn string) bool {
1✔
1133
        if dn == "" {
1✔
1134
                conn.log.Debug("Skip delete for empty Dn: ")
×
1135
                return false
×
1136
        }
×
1137
        dnSlice := strings.Split(dn, "/")
1✔
1138
        identifier := dnSlice[len(dnSlice)-1]
1✔
1139
        iSlice := strings.SplitN(identifier, "-", 2)
1✔
1140
        if len(iSlice) == 2 {
2✔
1141
                if iSlice[0] == "ip" {
1✔
1142
                        addr := strings.Trim(iSlice[1], "[]")
×
1143
                        obj := NewDeleteHostprotRemoteIp(addr)
×
1144
                        conn.log.Debug("Posting delete of dn ", dn)
×
1145
                        return conn.postDn(dn, obj)
×
1146
                } else if iSlice[0] == "odev" {
1✔
1147
                        conn.log.Debug("Skipping delete of opflexODev : ", dn)
×
1148
                        return false
×
1149
                }
×
1150
        }
1151
        return conn.DeleteDn(dn)
1✔
1152
}
1153

1154
func (conn *ApicConnection) DeleteDn(dn string) bool {
1✔
1155
        if dn == "" {
1✔
1156
                conn.log.Debug("Skip delete for empty Dn: ")
×
1157
                return false
×
1158
        }
×
1159
        conn.logger.WithFields(logrus.Fields{
1✔
1160
                "mod": "APICAPI",
1✔
1161
                "dn":  dn,
1✔
1162
        }).Debug("Deleting Dn")
1✔
1163
        uri := fmt.Sprintf("/api/mo/%s.json", dn)
1✔
1164
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1165
        req, err := http.NewRequest("DELETE", url, http.NoBody)
1✔
1166
        if err != nil {
1✔
1167
                conn.log.Error("Could not create delete request: ", err)
×
1168
                conn.restart()
×
1169
                return false
×
1170
        }
×
1171
        conn.sign(req, uri, nil)
1✔
1172
        resp, err := conn.client.Do(req)
1✔
1173
        if err != nil {
1✔
1174
                conn.log.Error("Could not delete dn ", dn, ": ", err)
×
1175
                conn.restart()
×
1176
                return false
×
1177
        }
×
1178
        defer complete(resp)
1✔
1179
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1180
                conn.logErrorResp("Could not delete dn "+dn, resp)
×
1181
                conn.restart()
×
1182
        }
×
1183
        return false
1✔
1184
}
1185

1186
func doComputeRespClasses(targetClasses []string,
1187
        visited map[string]bool) {
1✔
1188
        for _, class := range targetClasses {
2✔
1189
                if visited[class] {
1✔
1190
                        continue
×
1191
                }
1192
                visited[class] = true
1✔
1193
                if md, ok := metadata[class]; ok {
2✔
1194
                        doComputeRespClasses(md.children, visited)
1✔
1195
                }
1✔
1196
        }
1197
}
1198

1199
func computeRespClasses(targetClasses []string) []string {
1✔
1200
        visited := make(map[string]bool)
1✔
1201
        doComputeRespClasses(targetClasses, visited)
1✔
1202

1✔
1203
        // Don't include targetclasses in rsp-subtree
1✔
1204
        // because they are implicitly included
1✔
1205
        for i := range targetClasses {
2✔
1206
                delete(visited, targetClasses[i])
1✔
1207
        }
1✔
1208

1209
        var respClasses []string
1✔
1210
        for class := range visited {
2✔
1211
                respClasses = append(respClasses, class)
1✔
1212
        }
1✔
1213
        respClasses = append(respClasses, "tagAnnotation")
1✔
1214
        return respClasses
1✔
1215
}
1216

1217
// AddSubscriptionTree subscribe at a subtree level. class specifies
1218
// the root. Changes will cause entire subtree of the rootdn to be fetched
1219
func (conn *ApicConnection) AddSubscriptionTree(class string,
1220
        targetClasses []string, targetFilter string) {
1✔
1221
        if _, ok := classDepth[class]; !ok {
1✔
1222
                errStr := fmt.Sprintf("classDepth not for class %s", class)
×
1223
                panic(errStr)
×
1224
        }
1225

1226
        conn.indexMutex.Lock()
1✔
1227
        conn.subscriptions.subs[class] = &subscription{
1✔
1228
                kind:          apicSubTree,
1✔
1229
                childSubs:     make(map[string]subComponent),
1✔
1230
                targetClasses: targetClasses,
1✔
1231
                targetFilter:  targetFilter,
1✔
1232
        }
1✔
1233
        conn.indexMutex.Unlock()
1✔
1234
}
1235

1236
func (conn *ApicConnection) AddSubscriptionClass(class string,
1237
        targetClasses []string, targetFilter string) {
1✔
1238
        conn.indexMutex.Lock()
1✔
1239
        conn.subscriptions.subs[class] = &subscription{
1✔
1240
                kind:          apicSubClass,
1✔
1241
                childSubs:     make(map[string]subComponent),
1✔
1242
                targetClasses: targetClasses,
1✔
1243
                respClasses:   computeRespClasses(targetClasses),
1✔
1244
                targetFilter:  targetFilter,
1✔
1245
        }
1✔
1246
        conn.indexMutex.Unlock()
1✔
1247
}
1✔
1248

1249
func (conn *ApicConnection) AddSubscriptionDn(dn string,
1250
        targetClasses []string) {
1✔
1251
        conn.logger.WithFields(logrus.Fields{
1✔
1252
                "mod": "APICAPI",
1✔
1253
                "dn":  dn,
1✔
1254
        }).Debug("Adding Subscription for Dn")
1✔
1255

1✔
1256
        conn.indexMutex.Lock()
1✔
1257
        conn.subscriptions.subs[dn] = &subscription{
1✔
1258
                kind:          apicSubDn,
1✔
1259
                childSubs:     make(map[string]subComponent),
1✔
1260
                targetClasses: targetClasses,
1✔
1261
                respClasses:   computeRespClasses(targetClasses),
1✔
1262
        }
1✔
1263
        conn.indexMutex.Unlock()
1✔
1264
}
1✔
1265

1266
func (conn *ApicConnection) SetSubscriptionHooks(value string,
1267
        updateHook ApicObjectHandler, deleteHook ApicDnHandler) {
1✔
1268
        conn.indexMutex.Lock()
1✔
1269
        if s, ok := conn.subscriptions.subs[value]; ok {
2✔
1270
                s.updateHook = updateHook
1✔
1271
                s.deleteHook = deleteHook
1✔
1272
        }
1✔
1273
        conn.indexMutex.Unlock()
1✔
1274
}
1275

1276
func (conn *ApicConnection) GetApicResponse(uri string) (ApicResponse, error) {
1✔
1277
        conn.log.Debug("apicIndex: ", conn.Apic[conn.ApicIndex], " uri: ", uri)
1✔
1278
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1279
        var apicresp ApicResponse
1✔
1280
        conn.log.Debug("Apic Get url: ", url)
1✔
1281
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1282
        if err != nil {
1✔
1283
                conn.log.Error("Could not create request: ", err)
×
1284
                return apicresp, err
×
1285
        }
×
1286
        conn.sign(req, uri, nil)
1✔
1287
        resp, err := conn.client.Do(req)
1✔
1288
        if err != nil {
1✔
1289
                conn.log.Error("Could not get response for ", url, ": ", err)
×
1290
                return apicresp, err
×
1291
        }
×
1292
        defer complete(resp)
1✔
1293
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1294
                conn.logErrorResp("Could not get subtree for "+url, resp)
×
1295
                return apicresp, err
×
1296
        }
×
1297
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
1298
        if err != nil {
1✔
1299
                conn.log.Error("Could not parse APIC response: ", err)
×
1300
                return apicresp, err
×
1301
        }
×
1302
        return apicresp, nil
1✔
1303
}
1304

1305
func (conn *ApicConnection) doSubscribe(args []string,
1306
        kind, value, refresh_interval string, apicresp *ApicResponse) bool {
1✔
1307
        // properly encoding the URI query parameters breaks APIC
1✔
1308
        uri := fmt.Sprintf("/api/%s/%s.json?subscription=yes&%s%s",
1✔
1309
                kind, value, refresh_interval, strings.Join(args, "&"))
1✔
1310
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1311
        conn.log.Info("APIC connection URL: ", url)
1✔
1312

1✔
1313
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1314
        if err != nil {
1✔
1315
                conn.log.Error("Could not create request: ", err)
×
1316
                return false
×
1317
        }
×
1318
        conn.sign(req, uri, nil)
1✔
1319
        resp, err := conn.client.Do(req)
1✔
1320
        if err != nil {
1✔
1321
                conn.log.Error("Failed to subscribe to ", value, ": ", err)
×
1322
                return false
×
1323
        }
×
1324
        defer complete(resp)
1✔
1325
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1326
                conn.logErrorResp("Could not subscribe to "+value, resp)
×
1327
                return false
×
1328
        }
×
1329

1330
        err = json.NewDecoder(resp.Body).Decode(apicresp)
1✔
1331
        if err != nil {
1✔
1332
                conn.log.Error("Could not decode APIC response", err)
×
1333
                return false
×
1334
        }
×
1335
        time.Sleep(conn.SubscriptionDelay)
1✔
1336
        return true
1✔
1337
}
1338

1339
func (conn *ApicConnection) subscribe(value string, sub *subscription) bool {
1✔
1340
        baseArgs := []string{
1✔
1341
                "query-target=subtree",
1✔
1342
                "rsp-subtree=full",
1✔
1343
                "target-subtree-class=" + strings.Join(sub.targetClasses, ","),
1✔
1344
        }
1✔
1345

1✔
1346
        const defaultArgs = 1
1✔
1347
        var argCount = defaultArgs
1✔
1348
        var combinableSubClasses, separableSubClasses []string
1✔
1349
        var splitTargetClasses [][]string
1✔
1350
        var splitRespClasses [][]string
1✔
1351
        var argSet [][]string
1✔
1352
        argSet = make([][]string, defaultArgs)
1✔
1353
        argSet[defaultArgs-1] = make([]string, len(baseArgs))
1✔
1354
        copy(argSet[defaultArgs-1], baseArgs)
1✔
1355
        if sub.respClasses != nil {
2✔
1356
                separateClasses := func(classes []string, combClasses, sepClasses *[]string) {
2✔
1357
                        for i := range classes {
2✔
1358
                                if classMeta, ok := metadata[classes[i]]; ok {
2✔
1359
                                        if classes[i] == "tagAnnotation" {
2✔
1360
                                                continue
1✔
1361
                                        }
1362
                                        if classMeta.hints != nil && classMeta.hints["cardinality"] == "high" {
2✔
1363
                                                *sepClasses = append(*sepClasses, classes[i])
1✔
1364
                                                continue
1✔
1365
                                        }
1366
                                        *combClasses = append(*combClasses, classes[i])
1✔
1367
                                }
1368
                        }
1369
                }
1370
                separateClasses(sub.respClasses, &combinableSubClasses, &separableSubClasses)
1✔
1371

1✔
1372
                // In case there are high cardinality children, we register for all the classes individually.
1✔
1373
                // The concept of target-subtree and rsp-subtree class cannot be used because of the tagAnnotation object
1✔
1374
                // vmmInjectedLabel is added for every object, so getting it separately will not be scalable
1✔
1375
                if len(separableSubClasses) > 0 {
2✔
1376
                        separateClasses(sub.targetClasses, &combinableSubClasses, &separableSubClasses)
1✔
1377
                        separableSubClasses = append(separableSubClasses, combinableSubClasses...)
1✔
1378
                        baseArgs = []string{
1✔
1379
                                "query-target=subtree",
1✔
1380
                                "rsp-subtree=children",
1✔
1381
                        }
1✔
1382
                        subscribingClasses := make(map[string]bool)
1✔
1383
                        argSet = make([][]string, len(separableSubClasses))
1✔
1384
                        splitTargetClasses = make([][]string, len(separableSubClasses))
1✔
1385
                        splitRespClasses = make([][]string, len(separableSubClasses))
1✔
1386

1✔
1387
                        argCount = 0
1✔
1388
                        for i := range separableSubClasses {
2✔
1389
                                // Eliminate duplicates
1✔
1390
                                if _, ok := subscribingClasses[separableSubClasses[i]]; ok {
1✔
1391
                                        continue
×
1392
                                }
1393
                                subscribingClasses[separableSubClasses[i]] = true
1✔
1394
                                argSet[argCount] = make([]string, len(baseArgs))
1✔
1395
                                copy(argSet[argCount], baseArgs)
1✔
1396
                                argSet[argCount] = append(argSet[argCount], "target-subtree-class="+separableSubClasses[i], "rsp-subtree-class=tagAnnotation")
1✔
1397
                                splitTargetClasses[argCount] = append(splitTargetClasses[argCount], separableSubClasses[i])
1✔
1398
                                splitRespClasses[argCount] = computeRespClasses([]string{separableSubClasses[i]})
1✔
1399
                                argCount++
1✔
1400
                        }
1401
                } else {
1✔
1402
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], "rsp-subtree-class="+strings.Join(combinableSubClasses, ",")+",tagAnnotation")
1✔
1403
                }
1✔
1404
        }
1405
        if sub.targetFilter != "" {
2✔
1406
                targetFilterArgs := "query-target-filter=" + sub.targetFilter
1✔
1407
                if len(separableSubClasses) == 0 {
2✔
1408
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], targetFilterArgs)
1✔
1409
                } else {
1✔
1410
                        for i := 0; i < argCount; i++ {
×
1411
                                argSet[i] = append(argSet[i], targetFilterArgs)
×
1412
                        }
×
1413
                }
1414
        }
1415

1416
        kind := "mo"
1✔
1417
        if sub.kind == apicSubClass || sub.kind == apicSubTree {
2✔
1418
                kind = "class"
1✔
1419
        }
1✔
1420

1421
        refresh_interval := ""
1✔
1422
        if conn.RefreshInterval != 0 {
2✔
1423
                refresh_interval = fmt.Sprintf("refresh-timeout=%v&",
1✔
1424
                        conn.RefreshInterval.Seconds())
1✔
1425
        }
1✔
1426
        for i := 0; i < argCount; i++ {
2✔
1427
                var apicresp ApicResponse
1✔
1428
                if !conn.doSubscribe(argSet[i], kind, value, refresh_interval, &apicresp) {
1✔
1429
                        return false
×
1430
                }
×
1431
                subId, ok := apicresp.SubscriptionId.(string)
1✔
1432
                if !ok {
1✔
1433
                        conn.log.Error("Subscription ID is not a string")
×
1434
                        return false
×
1435
                }
×
1436

1437
                conn.logger.WithFields(logrus.Fields{
1✔
1438
                        "mod":   "APICAPI",
1✔
1439
                        "value": value,
1✔
1440
                        "kind":  kind,
1✔
1441
                        "id":    subId,
1✔
1442
                        "args":  argSet[i],
1✔
1443
                }).Debug("Subscribed")
1✔
1444

1✔
1445
                conn.indexMutex.Lock()
1✔
1446
                if argCount > defaultArgs {
2✔
1447
                        sub.childSubs[subId] = subComponent{
1✔
1448
                                targetClasses: splitTargetClasses[i],
1✔
1449
                                respClasses:   splitRespClasses[i],
1✔
1450
                        }
1✔
1451
                } else {
2✔
1452
                        conn.subscriptions.subs[value].id = subId
1✔
1453
                }
1✔
1454
                conn.subscriptions.ids[subId] = value
1✔
1455
                conn.indexMutex.Unlock()
1✔
1456
                var respObjCount int
1✔
1457
                for _, obj := range apicresp.Imdata {
2✔
1458
                        dn := obj.GetDn()
1✔
1459
                        if dn == "" {
1✔
1460
                                continue
×
1461
                        }
1462
                        conn.indexMutex.Lock()
1✔
1463
                        subIds, found := conn.cacheDnSubIds[dn]
1✔
1464
                        if !found {
2✔
1465
                                subIds = make(map[string]bool)
1✔
1466
                                conn.cacheDnSubIds[dn] = subIds
1✔
1467
                        }
1✔
1468
                        subIds[subId] = true
1✔
1469
                        conn.indexMutex.Unlock()
1✔
1470

1✔
1471
                        if sub.updateHook != nil && sub.updateHook(obj) {
2✔
1472
                                continue
1✔
1473
                        }
1474

1475
                        tag := obj.GetTag()
1✔
1476
                        if !conn.isSyncTag(tag) {
1✔
1477
                                continue
×
1478
                        }
1479

1480
                        conn.logger.WithFields(logrus.Fields{
1✔
1481
                                "mod": "APICAPI",
1✔
1482
                                "dn":  dn,
1✔
1483
                                "tag": tag,
1✔
1484
                                "obj": obj,
1✔
1485
                        }).Debug("Caching")
1✔
1486
                        var count int
1✔
1487
                        prepareApicCache("", obj, &count)
1✔
1488
                        respObjCount += count
1✔
1489
                        conn.indexMutex.Lock()
1✔
1490
                        conn.cachedState[tag] = append(conn.cachedState[tag], obj)
1✔
1491
                        conn.indexMutex.Unlock()
1✔
1492
                }
1493
                if respObjCount >= ApicSubscriptionResponseMoMaxCount/10 {
1✔
1494
                        conn.logger.WithFields(logrus.Fields{
×
1495
                                "args":       argSet[i],
×
1496
                                "moCount":    respObjCount,
×
1497
                                "maxAllowed": ApicSubscriptionResponseMoMaxCount,
×
1498
                        }).Warning("Subscription response is significantly large. Each new object will add 2 Mos atleast and twice the number of labels on the object")
×
1499
                } else {
1✔
1500
                        conn.logger.WithFields(logrus.Fields{
1✔
1501
                                "moCount": respObjCount,
1✔
1502
                        }).Debug("ResponseObjCount")
1✔
1503
                }
1✔
1504
        }
1505

1506
        return true
1✔
1507
}
1508

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

1511
func (conn *ApicConnection) isSyncTag(tag string) bool {
1✔
1512
        return tagRegexp.MatchString(tag) &&
1✔
1513
                strings.HasPrefix(tag, conn.prefix+"-")
1✔
1514
}
1✔
1515

1516
func getRootDn(dn, rootClass string) string {
1✔
1517
        depth := classDepth[rootClass]
1✔
1518
        parts := strings.Split(dn, "/")
1✔
1519
        parts = parts[:depth]
1✔
1520
        return strings.Join(parts, "/")
1✔
1521
}
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