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

noironetworks / aci-containers / 9934

24 Sep 2024 08:46AM UTC coverage: 69.502% (-0.1%) from 69.632%
9934

push

travis-pro

web-flow
Merge pull request #1403 from noironetworks/annotation-error-fix

Reduce the frequency of error logs

0 of 30 new or added lines in 1 file covered. (0.0%)

15 existing lines in 4 files now uncovered.

13129 of 18890 relevant lines covered (69.5%)

0.79 hits per line

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

66.06
/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) UnsubscribeImmediateDnLocked(dn string,
448
        targetClasses []string) {
×
449
        // Post local delete, subscription will not be refreshed
×
450
        // after refresh time-out
×
451
        delete(conn.subscriptions.subs, dn)
×
452
}
×
453

454
func (conn *ApicConnection) AddImmediateSubscriptionDnLocked(dn string,
455
        targetClasses []string, updateHook ApicObjectHandler, deleteHook ApicDnHandler) bool {
×
456
        conn.logger.WithFields(logrus.Fields{
×
457
                "mod": "APICAPI",
×
458
                "dn":  dn,
×
459
        }).Debug("Adding Subscription for Dn")
×
460

×
461
        conn.subscriptions.subs[dn] = &subscription{
×
462
                kind:          apicSubDn,
×
463
                childSubs:     make(map[string]subComponent),
×
464
                targetClasses: targetClasses,
×
465
                respClasses:   computeRespClasses(targetClasses),
×
466
        }
×
467
        if updateHook != nil {
×
468
                conn.subscriptions.subs[dn].updateHook = updateHook
×
469
        }
×
470
        if deleteHook != nil {
×
471
                conn.subscriptions.subs[dn].deleteHook = deleteHook
×
472
        }
×
473
        return conn.subscribe(dn, conn.subscriptions.subs[dn], true)
×
474
}
475

476
func (conn *ApicConnection) runConn(stopCh <-chan struct{}) {
1✔
477
        done := make(chan struct{})
1✔
478
        restart := make(chan struct{})
1✔
479
        queueStop := make(chan struct{})
1✔
480
        odevQueueStop := make(chan struct{})
1✔
481
        priorityQueueStop := make(chan struct{})
1✔
482
        syncHook := make(chan fullSync, 1)
1✔
483
        conn.restartCh = restart
1✔
484

1✔
485
        go func() {
2✔
486
                defer conn.connection.Close()
1✔
487
                defer close(done)
1✔
488

1✔
489
                for {
2✔
490
                        var apicresp ApicResponse
1✔
491
                        err := conn.connection.ReadJSON(&apicresp)
1✔
492
                        var closeErr *websocket.CloseError
1✔
493
                        if errors.As(err, &closeErr) {
1✔
494
                                conn.log.Info("Websocket connection closed: ", closeErr.Code)
×
495
                                conn.restart()
×
496
                                break
×
497
                        } else if err != nil {
2✔
498
                                conn.log.Error("Could not read web socket message:", err)
1✔
499
                                conn.restart()
1✔
500
                                break
1✔
501
                        } else {
1✔
502
                                conn.handleSocketUpdate(&apicresp)
1✔
503
                        }
1✔
504
                }
505
        }()
506

507
        conn.indexMutex.Lock()
1✔
508
        oldState := conn.cacheDnSubIds
1✔
509
        conn.cachedState = make(map[string]ApicSlice)
1✔
510
        conn.cacheDnSubIds = make(map[string]map[string]bool)
1✔
511
        conn.deltaQueue = workqueue.NewNamedRateLimitingQueue(
1✔
512
                workqueue.NewMaxOfRateLimiter(
1✔
513
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
514
                                10*time.Second),
1✔
515
                        &workqueue.BucketRateLimiter{
1✔
516
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
517
                        },
1✔
518
                ),
1✔
519
                "delta")
1✔
520
        go conn.processQueue(conn.deltaQueue, queueStop, "delta")
1✔
521
        conn.odevQueue = workqueue.NewNamedRateLimitingQueue(
1✔
522
                workqueue.NewMaxOfRateLimiter(
1✔
523
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
524
                                10*time.Second),
1✔
525
                        &workqueue.BucketRateLimiter{
1✔
526
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
527
                        },
1✔
528
                ),
1✔
529
                "odev")
1✔
530
        go conn.processQueue(conn.odevQueue, odevQueueStop, "odev")
1✔
531
        conn.priorityQueue = workqueue.NewNamedRateLimitingQueue(
1✔
532
                workqueue.NewMaxOfRateLimiter(
1✔
533
                        workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond,
1✔
534
                                10*time.Second),
1✔
535
                        &workqueue.BucketRateLimiter{
1✔
536
                                Limiter: rate.NewLimiter(rate.Limit(10), int(100)),
1✔
537
                        },
1✔
538
                ),
1✔
539
                "priority")
1✔
540
        go conn.processQueue(conn.priorityQueue, priorityQueueStop, "priority")
1✔
541
        conn.indexMutex.Unlock()
1✔
542

1✔
543
        refreshInterval := conn.RefreshInterval
1✔
544
        if refreshInterval == 0 {
1✔
545
                refreshInterval = defaultConnectionRefresh
×
546
        }
×
547
        // Adjust refreshTickerInterval.
548
        // To refresh the subscriptions early than actual refresh timeout value
549
        refreshTickerInterval := refreshInterval - conn.RefreshTickerAdjust
1✔
550
        refreshTicker := time.NewTicker(refreshTickerInterval)
1✔
551
        defer refreshTicker.Stop()
1✔
552

1✔
553
        var hasErr bool
1✔
554
        for value, subscription := range conn.subscriptions.subs {
2✔
555
                if !(conn.subscribe(value, subscription, false)) {
1✔
556
                        hasErr = true
×
557
                        conn.restart()
×
558
                        break
×
559
                }
560
        }
561
        if !hasErr {
2✔
562
                conn.checkDeletes(oldState)
1✔
563
                go func() {
2✔
564
                        if conn.FullSyncHook != nil {
1✔
565
                                conn.FullSyncHook()
×
566
                        }
×
567
                        syncHook <- fullSync{}
1✔
568
                }()
569
        }
570

571
        // Get APIC version if connection restarts
572
        if conn.version == "" && conn.checkVersion {
1✔
573
                go func() {
×
574
                        version, err := conn.GetVersion()
×
575
                        if err != nil {
×
576
                                conn.log.Error("Error while getting APIC version: ", err, " Restarting connection...")
×
577
                                conn.restart()
×
578
                        } else {
×
579
                                conn.log.Debug("Cached version:", conn.CachedVersion, " New version:", version)
×
580
                                if ApicVersion != version {
×
581
                                        ApicVersion = version
×
582
                                        if ApicVersion >= "6.0(4c)" {
×
583
                                                metadata["fvBD"].attributes["serviceBdRoutingDisable"] = "no"
×
584
                                        } else {
×
585
                                                delete(metadata["fvBD"].attributes, "serviceBdRoutingDisable")
×
586
                                        }
×
587
                                        conn.VersionUpdateHook()
×
588
                                }
589
                                conn.CachedVersion = version
×
590
                        }
591
                }()
592
        }
593

594
        closeConn := func(stop bool) {
2✔
595
                close(queueStop)
1✔
596
                close(odevQueueStop)
1✔
597

1✔
598
                conn.indexMutex.Lock()
1✔
599
                conn.deltaQueue = nil
1✔
600
                conn.odevQueue = nil
1✔
601
                conn.priorityQueue = nil
1✔
602
                conn.stopped = stop
1✔
603
                conn.syncEnabled = false
1✔
604
                conn.subscriptions.ids = make(map[string]string)
1✔
605
                conn.version = ""
1✔
606
                conn.indexMutex.Unlock()
1✔
607

1✔
608
                conn.log.Debug("Shutting down web socket")
1✔
609
                err := conn.connection.WriteMessage(websocket.CloseMessage,
1✔
610
                        websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
1✔
611
                if err != nil {
1✔
612
                        conn.log.Error("Error while closing socket: ", err)
×
613
                } else {
1✔
614
                        select {
1✔
615
                        case <-done:
1✔
616
                        case <-time.After(time.Second):
×
617
                        }
618
                }
619
                conn.connection.Close()
1✔
620
        }
621

622
loop:
1✔
623
        for {
2✔
624
                select {
1✔
625
                case <-syncHook:
1✔
626
                        conn.fullSync()
1✔
627
                case <-refreshTicker.C:
1✔
628
                        conn.refresh()
1✔
629
                case <-restart:
1✔
630
                        closeConn(false)
1✔
631
                        break loop
1✔
632
                case <-stopCh:
1✔
633
                        closeConn(true)
1✔
634
                        break loop
1✔
635
                }
636
        }
637

638
        conn.log.Debug("Exiting websocket handler")
1✔
639
}
640

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

1✔
646
        if len(conn.Apic) == 0 {
1✔
647
                return "", errors.New("No APIC configuration")
×
648
        }
×
649

650
        conn.checkVersion = true // enable version check on websocket reconnect
1✔
651
        // To Handle unit-tests
1✔
652
        if strings.Contains(conn.Apic[conn.ApicIndex], "127.0.0.1") {
2✔
653
                conn.version = "4.2(4i)"
1✔
654
                conn.SnatPbrFltrChain = true
1✔
655
                conn.log.Debug("Returning APIC version 4.2(4i) for test server")
1✔
656
                return conn.version, nil
1✔
657
        }
1✔
658

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

×
662
        retries := 0
×
663
        for conn.version == "" {
×
664
                if retries <= conn.ReconnectRetryLimit {
×
665
                        // Wait before Retry.
×
666
                        time.Sleep(conn.ReconnectInterval)
×
667
                        retries++
×
668
                } else {
×
669
                        return "", fmt.Errorf("Failed to get APIC version after %d retries", retries)
×
670
                }
×
671

672
                token, err := conn.login()
×
673
                if err != nil {
×
674
                        conn.log.Error("Failed to log into APIC: ", err)
×
675
                        continue
×
676
                }
677
                conn.token = token
×
678

×
679
                req, err := http.NewRequest("GET", url, http.NoBody)
×
680
                if err != nil {
×
681
                        conn.log.Error("Could not create request:", err)
×
682
                        continue
×
683
                }
684
                conn.sign(req, uri, nil)
×
685
                resp, err := conn.client.Do(req)
×
686
                if err != nil {
×
687
                        conn.log.Error("Could not get response for ", versionMo, ": ", err)
×
688
                        continue
×
689
                }
690
                defer complete(resp)
×
691
                if resp.StatusCode < 200 || resp.StatusCode >= 300 {
×
692
                        conn.logErrorResp("Could not get response for "+versionMo, resp)
×
693
                        conn.log.Debug("Request:", req)
×
694
                        continue
×
695
                }
696

697
                var apicresp ApicResponse
×
698
                err = json.NewDecoder(resp.Body).Decode(&apicresp)
×
699
                if err != nil {
×
700
                        conn.log.Error("Could not parse APIC response: ", err)
×
701
                        continue
×
702
                }
703
                for _, obj := range apicresp.Imdata {
×
704
                        vresp := obj["firmwareCtrlrRunning"]
×
705
                        version, ok := vresp.Attributes["version"]
×
706
                        if !ok {
×
707
                                conn.log.Debug("No version attribute in the response??!")
×
708
                                conn.logger.WithFields(logrus.Fields{
×
709
                                        "mod":                            "APICAPI",
×
710
                                        "firmwareCtrlrRunning":           vresp,
×
711
                                        "firmwareCtrlRunning Attributes": vresp.Attributes,
×
712
                                }).Debug("Response:")
×
713
                        } else {
×
714
                                switch version := version.(type) {
×
715
                                default:
×
716
                                case string:
×
717
                                        version_split := strings.Split(version, "(")
×
718
                                        version_number, err := strconv.ParseFloat(version_split[0], 64)
×
719
                                        conn.log.Info("Actual APIC version:", version, " Stripped out version:", version_number)
×
720
                                        if err == nil {
×
721
                                                conn.version = version //return the actual version
×
722
                                        }
×
723
                                }
724
                        }
725
                }
726
        }
727
        return conn.version, nil
×
728
}
729

730
func (conn *ApicConnection) Run(stopCh <-chan struct{}) {
1✔
731
        if len(conn.Apic) == 0 {
1✔
732
                conn.log.Warning("APIC connection not configured")
×
733
                return
×
734
        }
×
735

736
        if conn.version >= "6.0(4c)" {
1✔
737
                metadata["fvBD"].attributes["serviceBdRoutingDisable"] = "no"
×
738
        }
×
739

740
        for !conn.stopped {
2✔
741
                func() {
2✔
742
                        defer func() {
2✔
743
                                conn.ApicIndex = (conn.ApicIndex + 1) % len(conn.Apic)
1✔
744
                                time.Sleep(conn.ReconnectInterval)
1✔
745
                        }()
1✔
746

747
                        conn.logger.WithFields(logrus.Fields{
1✔
748
                                "mod":  "APICAPI",
1✔
749
                                "host": conn.Apic[conn.ApicIndex],
1✔
750
                        }).Info("Connecting to APIC")
1✔
751

1✔
752
                        for dn := range conn.subscriptions.subs {
2✔
753
                                conn.subscriptions.subs[dn].childSubs = make(map[string]subComponent)
1✔
754
                        }
1✔
755
                        conn.subscriptions.ids = make(map[string]string)
1✔
756

1✔
757
                        token, err := conn.login()
1✔
758
                        if err != nil {
2✔
759
                                conn.log.Error("Failed to log into APIC: ", err)
1✔
760
                                return
1✔
761
                        }
1✔
762
                        conn.token = token
1✔
763

1✔
764
                        uri := fmt.Sprintf("/socket%s", token)
1✔
765
                        url := fmt.Sprintf("wss://%s%s",
1✔
766
                                conn.Apic[conn.ApicIndex], uri)
1✔
767
                        header := make(http.Header)
1✔
768
                        if conn.signer != nil {
2✔
769
                                sig, err := conn.signer.sign("GET", uri, nil)
1✔
770
                                if err != nil {
1✔
771
                                        conn.log.Error("Failed to sign request: ", err)
×
772
                                        return
×
773
                                }
×
774
                                header.Set("Cookie", conn.apicSigCookie(sig, token))
1✔
775
                        }
776

777
                        conn.connection, _, err = conn.dialer.Dial(url, header)
1✔
778
                        if err != nil {
1✔
779
                                conn.log.Error("Failed to open APIC websocket: ", err)
×
780
                                return
×
781
                        }
×
782
                        conn.log.Info("Websocket connected!")
1✔
783
                        conn.runConn(stopCh)
1✔
784
                }()
785
        }
786
}
787

788
func (conn *ApicConnection) refresh() {
1✔
789
        if conn.signer == nil {
2✔
790
                url := fmt.Sprintf("https://%s/api/aaaRefresh.json",
1✔
791
                        conn.Apic[conn.ApicIndex])
1✔
792
                req, err := http.NewRequest("GET", url, http.NoBody)
1✔
793
                if err != nil {
1✔
794
                        conn.log.Error("Could not create request: ", err)
×
795
                        return
×
796
                }
×
797
                resp, err := conn.client.Do(req)
1✔
798
                if err != nil {
1✔
799
                        conn.log.Error("Failed to refresh APIC session: ", err)
×
800
                        conn.restart()
×
801
                        return
×
802
                }
×
803
                if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
804
                        conn.logErrorResp("Error while refreshing login", resp)
1✔
805
                        complete(resp)
1✔
806
                        conn.restart()
1✔
807
                        return
1✔
808
                }
1✔
809
                complete(resp)
1✔
810
                conn.log.Debugf("Refresh: url %v", url)
1✔
811
        }
812

813
        for _, sub := range conn.subscriptions.subs {
2✔
814
                refreshId := func(id string) {
2✔
815
                        uri := fmt.Sprintf("/api/subscriptionRefresh.json?id=%s", id)
1✔
816
                        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
817
                        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
818
                        if err != nil {
1✔
819
                                conn.log.Error("Could not create request: ", err)
×
820
                                return
×
821
                        }
×
822
                        conn.sign(req, uri, nil)
1✔
823
                        resp, err := conn.client.Do(req)
1✔
824
                        if err != nil {
1✔
825
                                conn.log.Error("Failed to refresh APIC subscription: ", err)
×
826
                                conn.restart()
×
827
                                return
×
828
                        }
×
829
                        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
2✔
830
                                conn.logErrorResp("Error while refreshing subscription", resp)
1✔
831
                                complete(resp)
1✔
832
                                conn.restart()
1✔
833
                                return
1✔
834
                        }
1✔
UNCOV
835
                        complete(resp)
×
UNCOV
836
                        conn.log.Debugf("Refresh sub: url %v", url)
×
UNCOV
837
                        time.Sleep(conn.SubscriptionDelay)
×
838
                }
839
                if len(sub.childSubs) > 0 {
1✔
840
                        for id := range sub.childSubs {
×
841
                                refreshId(id)
×
842
                        }
×
843
                } else {
1✔
844
                        refreshId(sub.id)
1✔
845
                }
1✔
846
        }
847
}
848

849
func (conn *ApicConnection) logErrorResp(message string, resp *http.Response) {
1✔
850
        var apicresp ApicResponse
1✔
851
        err := json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
852
        if err != nil {
1✔
853
                conn.log.Error("Could not parse APIC error response: ", err)
×
854
        } else {
1✔
855
                code := 0
1✔
856
                text := ""
1✔
857
                for _, o := range apicresp.Imdata {
2✔
858
                        if ob, ok := o["error"]; ok {
2✔
859
                                if ob.Attributes != nil {
2✔
860
                                        if t, isStr := ob.Attributes["text"].(string); isStr {
2✔
861
                                                text = t
1✔
862
                                        }
1✔
863
                                        if c, isInt := ob.Attributes["code"].(int); isInt {
1✔
864
                                                code = c
×
865
                                        }
×
866
                                }
867
                        }
868
                }
869
                conn.logger.WithFields(logrus.Fields{
1✔
870
                        "mod":    "APICAPI",
1✔
871
                        "text":   text,
1✔
872
                        "code":   code,
1✔
873
                        "url":    resp.Request.URL,
1✔
874
                        "status": resp.StatusCode,
1✔
875
                }).Error(message)
1✔
876
        }
877
}
878

879
// To make sure cluster's POD/NodeBDs and L3OUT are all mapped
880
// to same and correct VRF.
881
func (conn *ApicConnection) ValidateAciVrfAssociation(acivrfdn string, expectedVrfRelations []string) error {
×
882
        var aciVrfBdL3OuttDns []string
×
883
        args := []string{
×
884
                "query-target=subtree",
×
885
                "target-subtree-class=fvRtCtx,fvRtEctx",
×
886
        }
×
887

×
888
        uri := fmt.Sprintf("/api/mo/%s.json?%s", acivrfdn, strings.Join(args, "&"))
×
889
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
890
        req, err := http.NewRequest("GET", url, http.NoBody)
×
891
        if err != nil {
×
892
                conn.log.Error("Could not create request: ", err)
×
893
                return err
×
894
        }
×
895
        conn.sign(req, uri, nil)
×
896
        resp, err := conn.client.Do(req)
×
897
        if err != nil {
×
898
                conn.log.Error("Could not get subtree for ", acivrfdn, ": ", err)
×
899
                return err
×
900
        }
×
901
        defer complete(resp)
×
902
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
×
903
                conn.logErrorResp("Could not get subtree for "+acivrfdn, resp)
×
904
                return err
×
905
        }
×
906

907
        var apicresp ApicResponse
×
908
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
×
909
        if err != nil {
×
910
                conn.log.Error("Could not parse APIC response: ", err)
×
911
                return err
×
912
        }
×
913

914
        for _, obj := range apicresp.Imdata {
×
915
                for _, body := range obj {
×
916
                        tDn, ok := body.Attributes["tDn"].(string)
×
917
                        if !ok {
×
918
                                continue
×
919
                        }
920
                        aciVrfBdL3OuttDns = append(aciVrfBdL3OuttDns, tDn)
×
921
                }
922
        }
923
        sort.Strings(aciVrfBdL3OuttDns)
×
924
        conn.log.Debug("aciVrfBdL3OuttDns:", aciVrfBdL3OuttDns)
×
925
        for _, expectedDn := range expectedVrfRelations {
×
926
                i := sort.SearchStrings(aciVrfBdL3OuttDns, expectedDn)
×
927
                if !(i < len(aciVrfBdL3OuttDns) && aciVrfBdL3OuttDns[i] == expectedDn) {
×
928
                        conn.log.Debug("Missing (or) Incorrect Vrf association: ", expectedDn)
×
929
                        return errors.New("Incorrect Pod/NodeBD/L3OUT VRF association")
×
930
                }
×
931
        }
932
        return nil
×
933
}
934

935
func (conn *ApicConnection) getSubtreeDn(dn string, respClasses []string,
936
        updateHandlers []ApicObjectHandler) {
1✔
937
        args := []string{
1✔
938
                "rsp-subtree=full",
1✔
939
        }
1✔
940

1✔
941
        if len(respClasses) > 0 {
2✔
942
                args = append(args, "rsp-subtree-class="+strings.Join(respClasses, ","))
1✔
943
        }
1✔
944
        // properly encoding the URI query parameters breaks APIC
945
        uri := fmt.Sprintf("/api/mo/%s.json?%s", dn, strings.Join(args, "&"))
1✔
946
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
947
        conn.log.Debugf("URL: %v", url)
1✔
948
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
949
        if err != nil {
1✔
950
                conn.log.Error("Could not create request: ", err)
×
951
                return
×
952
        }
×
953
        conn.sign(req, uri, nil)
1✔
954
        resp, err := conn.client.Do(req)
1✔
955
        if err != nil {
1✔
956
                conn.log.Error("Could not get subtree for ", dn, ": ", err)
×
957
                conn.restart()
×
958
                return
×
959
        }
×
960
        defer complete(resp)
1✔
961
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
962
                conn.logErrorResp("Could not get subtree for "+dn, resp)
×
963
                conn.restart()
×
964
                return
×
965
        }
×
966

967
        var apicresp ApicResponse
1✔
968
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
969
        if err != nil {
1✔
970
                conn.log.Error("Could not parse APIC response: ", err)
×
971
                return
×
972
        }
×
973
        if len(apicresp.Imdata) == 0 {
1✔
974
                conn.log.Debugf("No subtree found for dn %s", dn)
×
975
        }
×
976

977
        for _, obj := range apicresp.Imdata {
2✔
978
                conn.logger.WithFields(logrus.Fields{
1✔
979
                        "mod": "APICAPI",
1✔
980
                        "dn":  obj.GetDn(),
1✔
981
                        "obj": obj,
1✔
982
                }).Debug("Object updated on APIC")
1✔
983
                var count int
1✔
984
                prepareApicCache("", obj, &count)
1✔
985

1✔
986
                handled := false
1✔
987
                for _, handler := range updateHandlers {
1✔
988
                        if handler(obj) {
×
989
                                handled = true
×
990
                                break
×
991
                        }
992
                }
993
                if handled {
1✔
994
                        continue
×
995
                }
996
                conn.reconcileApicObject(obj)
1✔
997
        }
998
}
999

1000
func (conn *ApicConnection) queuePriorityDn(dn string) {
×
1001
        conn.indexMutex.Lock()
×
1002
        if conn.priorityQueue != nil {
×
1003
                conn.priorityQueue.Add(dn)
×
1004
        }
×
1005
        conn.indexMutex.Unlock()
×
1006
}
1007

1008
func (conn *ApicConnection) queueDn(dn string) {
1✔
1009
        conn.indexMutex.Lock()
1✔
1010
        if conn.deltaQueue != nil {
2✔
1011
                conn.deltaQueue.Add(dn)
1✔
1012
        }
1✔
1013
        conn.indexMutex.Unlock()
1✔
1014
}
1015

1016
func (conn *ApicConnection) ForceRelogin() {
×
1017
        conn.token = ""
×
1018
}
×
1019

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

1055
        complete(resp)
×
1056
        if resp.StatusCode != http.StatusOK {
×
1057
                return fmt.Errorf("Status: %v", resp.StatusCode)
×
1058
        }
×
1059
        return nil
×
1060
}
1061

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

1084
func (conn *ApicConnection) postDn(dn string, obj ApicObject) bool {
1✔
1085
        conn.logger.WithFields(logrus.Fields{
1✔
1086
                "mod": "APICAPI",
1✔
1087
                "dn":  dn,
1✔
1088
                "obj": obj,
1✔
1089
        }).Debug("Posting Dn")
1✔
1090

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

1122
func (conn *ApicConnection) Delete(dn string) bool {
1✔
1123
        if dn == "" {
1✔
1124
                conn.log.Debug("Skip delete for empty Dn: ")
×
1125
                return false
×
1126
        }
×
1127
        dnSlice := strings.Split(dn, "/")
1✔
1128
        identifier := dnSlice[len(dnSlice)-1]
1✔
1129
        iSlice := strings.SplitN(identifier, "-", 2)
1✔
1130
        if len(iSlice) == 2 {
2✔
1131
                if iSlice[0] == "ip" {
1✔
1132
                        addr := strings.Trim(iSlice[1], "[]")
×
1133
                        obj := NewDeleteHostprotRemoteIp(addr)
×
1134
                        conn.log.Debug("Posting delete of dn ", dn)
×
1135
                        return conn.postDn(dn, obj)
×
1136
                } else if iSlice[0] == "odev" {
1✔
1137
                        conn.log.Debug("Skipping delete of opflexODev : ", dn)
×
1138
                        return false
×
1139
                }
×
1140
        }
1141
        return conn.DeleteDn(dn)
1✔
1142
}
1143

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

1176
func doComputeRespClasses(targetClasses []string,
1177
        visited map[string]bool) {
1✔
1178
        for _, class := range targetClasses {
2✔
1179
                if visited[class] {
1✔
1180
                        continue
×
1181
                }
1182
                visited[class] = true
1✔
1183
                if md, ok := metadata[class]; ok {
2✔
1184
                        doComputeRespClasses(md.children, visited)
1✔
1185
                }
1✔
1186
        }
1187
}
1188

1189
func computeRespClasses(targetClasses []string) []string {
1✔
1190
        visited := make(map[string]bool)
1✔
1191
        doComputeRespClasses(targetClasses, visited)
1✔
1192

1✔
1193
        // Don't include targetclasses in rsp-subtree
1✔
1194
        // because they are implicitly included
1✔
1195
        for i := range targetClasses {
2✔
1196
                delete(visited, targetClasses[i])
1✔
1197
        }
1✔
1198

1199
        var respClasses []string
1✔
1200
        for class := range visited {
2✔
1201
                respClasses = append(respClasses, class)
1✔
1202
        }
1✔
1203
        respClasses = append(respClasses, "tagAnnotation")
1✔
1204
        return respClasses
1✔
1205
}
1206

1207
// AddSubscriptionTree subscribe at a subtree level. class specifies
1208
// the root. Changes will cause entire subtree of the rootdn to be fetched
1209
func (conn *ApicConnection) AddSubscriptionTree(class string,
1210
        targetClasses []string, targetFilter string) {
1✔
1211
        if _, ok := classDepth[class]; !ok {
1✔
1212
                errStr := fmt.Sprintf("classDepth not for class %s", class)
×
1213
                panic(errStr)
×
1214
        }
1215

1216
        conn.indexMutex.Lock()
1✔
1217
        conn.subscriptions.subs[class] = &subscription{
1✔
1218
                kind:          apicSubTree,
1✔
1219
                childSubs:     make(map[string]subComponent),
1✔
1220
                targetClasses: targetClasses,
1✔
1221
                targetFilter:  targetFilter,
1✔
1222
        }
1✔
1223
        conn.indexMutex.Unlock()
1✔
1224
}
1225

1226
func (conn *ApicConnection) AddSubscriptionClass(class string,
1227
        targetClasses []string, targetFilter string) {
1✔
1228
        conn.indexMutex.Lock()
1✔
1229
        conn.subscriptions.subs[class] = &subscription{
1✔
1230
                kind:          apicSubClass,
1✔
1231
                childSubs:     make(map[string]subComponent),
1✔
1232
                targetClasses: targetClasses,
1✔
1233
                respClasses:   computeRespClasses(targetClasses),
1✔
1234
                targetFilter:  targetFilter,
1✔
1235
        }
1✔
1236
        conn.indexMutex.Unlock()
1✔
1237
}
1✔
1238

1239
func (conn *ApicConnection) AddSubscriptionDn(dn string,
1240
        targetClasses []string) {
1✔
1241
        conn.logger.WithFields(logrus.Fields{
1✔
1242
                "mod": "APICAPI",
1✔
1243
                "dn":  dn,
1✔
1244
        }).Debug("Adding Subscription for Dn")
1✔
1245

1✔
1246
        conn.indexMutex.Lock()
1✔
1247
        conn.subscriptions.subs[dn] = &subscription{
1✔
1248
                kind:          apicSubDn,
1✔
1249
                childSubs:     make(map[string]subComponent),
1✔
1250
                targetClasses: targetClasses,
1✔
1251
                respClasses:   computeRespClasses(targetClasses),
1✔
1252
        }
1✔
1253
        conn.indexMutex.Unlock()
1✔
1254
}
1✔
1255

1256
func (conn *ApicConnection) SetSubscriptionHooks(value string,
1257
        updateHook ApicObjectHandler, deleteHook ApicDnHandler) {
1✔
1258
        conn.indexMutex.Lock()
1✔
1259
        if s, ok := conn.subscriptions.subs[value]; ok {
2✔
1260
                s.updateHook = updateHook
1✔
1261
                s.deleteHook = deleteHook
1✔
1262
        }
1✔
1263
        conn.indexMutex.Unlock()
1✔
1264
}
1265

1266
func (conn *ApicConnection) GetApicResponse(uri string) (ApicResponse, error) {
1✔
1267
        conn.log.Debug("apicIndex: ", conn.Apic[conn.ApicIndex], " uri: ", uri)
1✔
1268
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1269
        var apicresp ApicResponse
1✔
1270
        conn.log.Debug("Apic Get url: ", url)
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 apicresp, err
×
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("Could not get response for ", url, ": ", err)
×
1280
                return apicresp, err
×
1281
        }
×
1282
        defer complete(resp)
1✔
1283
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1284
                conn.logErrorResp("Could not get subtree for "+url, resp)
×
1285
                return apicresp, err
×
1286
        }
×
1287
        err = json.NewDecoder(resp.Body).Decode(&apicresp)
1✔
1288
        if err != nil {
1✔
1289
                conn.log.Error("Could not parse APIC response: ", err)
×
1290
                return apicresp, err
×
1291
        }
×
1292
        return apicresp, nil
1✔
1293
}
1294

1295
func (conn *ApicConnection) doSubscribe(args []string,
1296
        kind, value, refresh_interval string, apicresp *ApicResponse) bool {
1✔
1297
        // properly encoding the URI query parameters breaks APIC
1✔
1298
        uri := fmt.Sprintf("/api/%s/%s.json?subscription=yes&%s%s",
1✔
1299
                kind, value, refresh_interval, strings.Join(args, "&"))
1✔
1300
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
1✔
1301
        conn.log.Info("APIC connection URL: ", url)
1✔
1302

1✔
1303
        req, err := http.NewRequest("GET", url, http.NoBody)
1✔
1304
        if err != nil {
1✔
1305
                conn.log.Error("Could not create request: ", err)
×
1306
                return false
×
1307
        }
×
1308
        conn.sign(req, uri, nil)
1✔
1309
        resp, err := conn.client.Do(req)
1✔
1310
        if err != nil {
1✔
1311
                conn.log.Error("Failed to subscribe to ", value, ": ", err)
×
1312
                return false
×
1313
        }
×
1314
        defer complete(resp)
1✔
1315
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
1✔
1316
                conn.logErrorResp("Could not subscribe to "+value, resp)
×
1317
                return false
×
1318
        }
×
1319

1320
        err = json.NewDecoder(resp.Body).Decode(apicresp)
1✔
1321
        if err != nil {
1✔
1322
                conn.log.Error("Could not decode APIC response", err)
×
1323
                return false
×
1324
        }
×
1325
        time.Sleep(conn.SubscriptionDelay)
1✔
1326
        return true
1✔
1327
}
1328

1329
func (conn *ApicConnection) subscribe(value string, sub *subscription, lockHeld bool) bool {
1✔
1330
        baseArgs := []string{
1✔
1331
                "query-target=subtree",
1✔
1332
                "rsp-subtree=full",
1✔
1333
                "target-subtree-class=" + strings.Join(sub.targetClasses, ","),
1✔
1334
        }
1✔
1335

1✔
1336
        const defaultArgs = 1
1✔
1337
        var argCount = defaultArgs
1✔
1338
        var combinableSubClasses, separableSubClasses []string
1✔
1339
        var splitTargetClasses [][]string
1✔
1340
        var splitRespClasses [][]string
1✔
1341
        var argSet [][]string
1✔
1342
        argSet = make([][]string, defaultArgs)
1✔
1343
        argSet[defaultArgs-1] = make([]string, len(baseArgs))
1✔
1344
        copy(argSet[defaultArgs-1], baseArgs)
1✔
1345
        if sub.respClasses != nil {
2✔
1346
                separateClasses := func(classes []string, combClasses, sepClasses *[]string) {
2✔
1347
                        for i := range classes {
2✔
1348
                                if classMeta, ok := metadata[classes[i]]; ok {
2✔
1349
                                        if classes[i] == "tagAnnotation" {
2✔
1350
                                                continue
1✔
1351
                                        }
1352
                                        if classMeta.hints != nil && classMeta.hints["cardinality"] == "high" {
2✔
1353
                                                *sepClasses = append(*sepClasses, classes[i])
1✔
1354
                                                continue
1✔
1355
                                        }
1356
                                        *combClasses = append(*combClasses, classes[i])
1✔
1357
                                }
1358
                        }
1359
                }
1360
                separateClasses(sub.respClasses, &combinableSubClasses, &separableSubClasses)
1✔
1361

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

1✔
1377
                        argCount = 0
1✔
1378
                        for i := range separableSubClasses {
2✔
1379
                                // Eliminate duplicates
1✔
1380
                                if _, ok := subscribingClasses[separableSubClasses[i]]; ok {
1✔
1381
                                        continue
×
1382
                                }
1383
                                subscribingClasses[separableSubClasses[i]] = true
1✔
1384
                                argSet[argCount] = make([]string, len(baseArgs))
1✔
1385
                                copy(argSet[argCount], baseArgs)
1✔
1386
                                argSet[argCount] = append(argSet[argCount], "target-subtree-class="+separableSubClasses[i], "rsp-subtree-class=tagAnnotation")
1✔
1387
                                splitTargetClasses[argCount] = append(splitTargetClasses[argCount], separableSubClasses[i])
1✔
1388
                                splitRespClasses[argCount] = computeRespClasses([]string{separableSubClasses[i]})
1✔
1389
                                argCount++
1✔
1390
                        }
1391
                } else {
1✔
1392
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], "rsp-subtree-class="+strings.Join(combinableSubClasses, ",")+",tagAnnotation")
1✔
1393
                }
1✔
1394
        }
1395
        if sub.targetFilter != "" {
2✔
1396
                targetFilterArgs := "query-target-filter=" + sub.targetFilter
1✔
1397
                if len(separableSubClasses) == 0 {
2✔
1398
                        argSet[defaultArgs-1] = append(argSet[defaultArgs-1], targetFilterArgs)
1✔
1399
                } else {
1✔
1400
                        for i := 0; i < argCount; i++ {
×
1401
                                argSet[i] = append(argSet[i], targetFilterArgs)
×
1402
                        }
×
1403
                }
1404
        }
1405

1406
        kind := "mo"
1✔
1407
        if sub.kind == apicSubClass || sub.kind == apicSubTree {
2✔
1408
                kind = "class"
1✔
1409
        }
1✔
1410

1411
        refresh_interval := ""
1✔
1412
        if conn.RefreshInterval != 0 {
2✔
1413
                refresh_interval = fmt.Sprintf("refresh-timeout=%v&",
1✔
1414
                        conn.RefreshInterval.Seconds())
1✔
1415
        }
1✔
1416
        for i := 0; i < argCount; i++ {
2✔
1417
                var apicresp ApicResponse
1✔
1418
                if !conn.doSubscribe(argSet[i], kind, value, refresh_interval, &apicresp) {
1✔
1419
                        return false
×
1420
                }
×
1421
                subId, ok := apicresp.SubscriptionId.(string)
1✔
1422
                if !ok {
1✔
1423
                        conn.log.Error("Subscription ID is not a string")
×
1424
                        return false
×
1425
                }
×
1426

1427
                conn.logger.WithFields(logrus.Fields{
1✔
1428
                        "mod":   "APICAPI",
1✔
1429
                        "value": value,
1✔
1430
                        "kind":  kind,
1✔
1431
                        "id":    subId,
1✔
1432
                        "args":  argSet[i],
1✔
1433
                }).Debug("Subscribed")
1✔
1434
                if !lockHeld {
2✔
1435
                        conn.indexMutex.Lock()
1✔
1436
                }
1✔
1437
                if argCount > defaultArgs {
2✔
1438
                        sub.childSubs[subId] = subComponent{
1✔
1439
                                targetClasses: splitTargetClasses[i],
1✔
1440
                                respClasses:   splitRespClasses[i],
1✔
1441
                        }
1✔
1442
                } else {
2✔
1443
                        conn.subscriptions.subs[value].id = subId
1✔
1444
                }
1✔
1445
                conn.subscriptions.ids[subId] = value
1✔
1446
                if !lockHeld {
2✔
1447
                        conn.indexMutex.Unlock()
1✔
1448
                }
1✔
1449
                var respObjCount int
1✔
1450
                for _, obj := range apicresp.Imdata {
2✔
1451
                        dn := obj.GetDn()
1✔
1452
                        if dn == "" {
1✔
1453
                                continue
×
1454
                        }
1455
                        conn.indexMutex.Lock()
1✔
1456
                        subIds, found := conn.cacheDnSubIds[dn]
1✔
1457
                        if !found {
2✔
1458
                                subIds = make(map[string]bool)
1✔
1459
                                conn.cacheDnSubIds[dn] = subIds
1✔
1460
                        }
1✔
1461
                        subIds[subId] = true
1✔
1462
                        conn.indexMutex.Unlock()
1✔
1463

1✔
1464
                        if sub.updateHook != nil && sub.updateHook(obj) {
2✔
1465
                                continue
1✔
1466
                        }
1467

1468
                        tag := obj.GetTag()
1✔
1469
                        if !conn.isSyncTag(tag) {
1✔
1470
                                continue
×
1471
                        }
1472

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

1499
        return true
1✔
1500
}
1501

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

1504
func (conn *ApicConnection) isSyncTag(tag string) bool {
1✔
1505
        return tagRegexp.MatchString(tag) &&
1✔
1506
                strings.HasPrefix(tag, conn.prefix+"-")
1✔
1507
}
1✔
1508

1509
func getRootDn(dn, rootClass string) string {
1✔
1510
        depth := classDepth[rootClass]
1✔
1511
        parts := strings.Split(dn, "/")
1✔
1512
        parts = parts[:depth]
1✔
1513
        return strings.Join(parts, "/")
1✔
1514
}
1✔
1515

1516
func (conn *ApicConnection) PostApicObjects(uri string, payload ApicSlice) error {
×
1517
        conn.log.Debug("apicIndex: ", conn.Apic[conn.ApicIndex], " uri: ", uri)
×
1518
        url := fmt.Sprintf("https://%s%s", conn.Apic[conn.ApicIndex], uri)
×
1519
        conn.log.Debug("Apic POST url: ", url)
×
1520

×
1521
        if conn.token == "" {
×
1522
                token, err := conn.login()
×
1523
                if err != nil {
×
1524
                        conn.log.Errorf("Login: %v", err)
×
1525
                        return err
×
1526
                }
×
1527
                conn.token = token
×
1528
        }
1529

1530
        raw, err := json.Marshal(payload)
×
1531
        if err != nil {
×
1532
                conn.log.Error("Could not serialize object: ", err)
×
1533
                return err
×
1534
        }
×
1535

1536
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(raw))
×
1537
        if err != nil {
×
1538
                conn.log.Error("Could not create request: ", err)
×
1539
                return err
×
1540
        }
×
1541

1542
        conn.sign(req, uri, raw)
×
1543
        req.Header.Set("Content-Type", "application/json")
×
1544
        conn.log.Infof("Post: %+v", req)
×
1545
        resp, err := conn.client.Do(req)
×
1546
        if err != nil {
×
1547
                conn.log.Error("Could not update  ", url, ": ", err)
×
1548
                return err
×
1549
        }
×
1550

1551
        complete(resp)
×
1552

×
1553
        if resp.StatusCode != http.StatusOK {
×
1554
                return fmt.Errorf("Status: %v", resp.StatusCode)
×
1555
        }
×
1556

1557
        return nil
×
1558
}
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