aci

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 22, 2023 License: MPL-2.0 Imports: 14 Imported by: 1

README

Tests

go-aci

go-aci is a Go client library for Cisco ACI. It is based on Nathan's excellent goaci module and features a simple, extensible API and advanced JSON manipulation.

Getting Started

Installing

To start using go-aci, install Go and go get:

$ go get -u github.com/netascode/go-aci

Basic Usage
package main

import "github.com/netascode/go-aci"

func main() {
    client, _ := aci.NewClient("https://1.1.1.1", "user", "pwd")

    res, _ = client.Get("/api/mo/uni/tn-infra")
    println(res.Get("imdata.0.*.attributes.name"))
}

This will print:

infra
Result manipulation

aci.Result uses GJSON to simplify handling JSON results. See the GJSON documentation for more detail.

res, _ := client.GetClass("fvBD")
res.Get("0.fvBD.attributes.name").Str // name of first BD
res.Get("0.*.attributes.name").Str // name of first BD (if you don't know the class)

for _, bd := range res.Array() {
    println(res.Get("*.attributes|@pretty")) // pretty print BD attributes
}

for _, bd := range res.Get("#.fvBD.attributes").Array() {
    println(res.Get("@pretty")) // pretty print BD attributes
}
Helpers for common patterns
res, _ := client.GetDn("uni/tn-infra")
res, _ := client.GetClass("fvTenant")
Query parameters

Pass the aci.Query object to the Get request to add query paramters:

queryInfra := aci.Query("query-target-filter", `eq(fvTenant.name,"infra")`)
res, _ := client.GetClass("fvTenant", queryInfra)

Pass as many paramters as needed:

res, _ := client.GetClass("isisRoute",
    aci.Query("rsp-subtree-include", "relations"),
    aci.Query("query-target-filter", `eq(isisRoute.pfx,"10.66.0.1/32")`),
)
POST data creation

aci.Body is a wrapper for SJSON. SJSON supports a path syntax simplifying JSON creation.

exampleTenant := aci.Body{}.Set("fvTenant.attributes.name", "aci-example").Str
client.Post("/api/mo/uni/tn-aci-example", exampleTenant)

These can be chained:

tenantA := aci.Body{}.
    Set("fvTenant.attributes.name", "aci-example-a").
    Set("fvTenant.attributes.descr", "Example tenant A")

...or nested:

attrs := aci.Body{}.
    Set("name", "aci-example-b").
    Set("descr", "Example tenant B").
    Str
tenantB := aci.Body{}.SetRaw("fvTenant.attributes", attrs).Str
Token refresh

Token refresh is handled automatically. The client keeps a timer and checks elapsed time on each request, refreshing the token every 8 minutes. This can be handled manually if desired:

res, _ := client.Get("/api/...", aci.NoRefresh)
client.Refresh()

Documentation

See the documentation for more details.

Documentation

Overview

Package aci is a Cisco ACI REST client library for Go.

Index

Constants

View Source
const DefaultBackoffDelayFactor float64 = 3
View Source
const DefaultBackoffMaxDelay int = 60
View Source
const DefaultBackoffMinDelay int = 4
View Source
const DefaultMaxRetries int = 3

Variables

This section is empty.

Functions

func BackoffDelayFactor

func BackoffDelayFactor(x float64) func(*Client)

BackoffDelayFactor modifies the backoff delay factor from the default of 3.

func BackoffMaxDelay

func BackoffMaxDelay(x int) func(*Client)

BackoffMaxDelay modifies the maximum delay between two retries from the default of 60.

func BackoffMinDelay

func BackoffMinDelay(x int) func(*Client)

BackoffMinDelay modifies the minimum delay between two retries from the default of 4.

func Insecure

func Insecure(x bool) func(*Client)

Insecure determines if insecure https connections are allowed. Default value is true.

func Logging

func Logging(x bool) func(*Client)

Logging enables debug logging. Default value is false.

func MaxRetries

func MaxRetries(x int) func(*Client)

MaxRetries modifies the maximum number of retries from the default of 3.

func NoLogPayload

func NoLogPayload(req *Req)

NoLogPayload prevents logging of payloads. Primarily used by the Login and Refresh methods where this could expose secrets.

func NoRefresh

func NoRefresh(req *Req)

NoRefresh prevents token refresh check. Primarily used by the Login and Refresh methods where this would be redundant.

func Query

func Query(k, v string) func(req *Req)

Query sets an HTTP query parameter.

client.GetClass("fvBD", aci.Query("query-target-filter", `eq(fvBD.name,"bd-name")`))

Or set multiple parameters:

 client.GetClass("bgpInst",
	   aci.Query("rsp-subtree-include", "faults"),
	   aci.Query("query-target-filter", `eq(fvBD.name,"bd-name")`))

func RequestTimeout

func RequestTimeout(x time.Duration) func(*Client)

RequestTimeout modifies the HTTP request timeout from the default of 60 seconds.

Types

type Body

type Body struct {
	Str string
}

Body wraps SJSON for building JSON body strings. Usage example:

Body{}.Set("fvTenant.attributes.name", "mytenant").Str

func (Body) Delete

func (body Body) Delete(path string) Body

Delete deletes a JSON path.

func (Body) Res

func (body Body) Res() Res

Res creates a Res object, i.e. a GJSON result object.

func (Body) Set

func (body Body) Set(path, value string) Body

Set sets a JSON path to a value.

func (Body) SetRaw

func (body Body) SetRaw(path, rawValue string) Body

SetRaw sets a JSON path to a raw string value. This is primarily used for building up nested structures, e.g.:

Body{}.SetRaw("fvTenant.attributes", Body{}.Set("name", "mytenant").Str).Str

type Client

type Client struct {
	// HttpClient is the *http.Client used for API requests.
	HttpClient *http.Client
	// Url is the APIC IP or hostname, e.g. https://10.0.0.1:80 (port is optional).
	Url string
	// LastRefresh is the timestamp of the last token refresh interval.
	LastRefresh time.Time
	// Token is the current authentication token.
	Token string
	// Usr is the APIC username.
	Usr string
	// Pwd is the APIC password.
	Pwd string
	// Insecure determines if insecure https connections are allowed.
	Insecure bool
	// Maximum number of retries.
	MaxRetries int
	// Minimum delay between two retries.
	BackoffMinDelay int
	// Maximum delay between two retries.
	BackoffMaxDelay int
	// Backoff delay factor.
	BackoffDelayFactor float64
	// Authentication mutex
	AuthenticationMutex *sync.Mutex
	// Enable debug logging
	Logging bool
}

Client is an HTTP ACI client. Use aci.NewClient to initiate a client. This will ensure proper cookie handling and processing of modifiers.

func NewClient

func NewClient(url, usr, pwd string, mods ...func(*Client)) (Client, error)

NewClient creates a new ACI HTTP client. Pass modifiers in to modify the behavior of the client, e.g.

client, _ := NewClient("https://1.1.1.1", "user", "password", RequestTimeout(120))

func (*Client) Authenticate

func (client *Client) Authenticate() error

Login if no token available or refresh the token if older than 480 seconds.

func (*Client) Backoff

func (client *Client) Backoff(attempts int) bool

Backoff waits following an exponential backoff algorithm

func (*Client) DeleteDn

func (client *Client) DeleteDn(dn string, mods ...func(*Req)) (Res, error)

DeleteDn makes a DELETE request by DN.

func (*Client) Do

func (client *Client) Do(req Req) (Res, error)

Do makes a request. Requests for Do are built ouside of the client, e.g.

req := client.NewReq("GET", "/api/class/fvBD", nil)
res := client.Do(req)

func (*Client) Get

func (client *Client) Get(path string, mods ...func(*Req)) (Res, error)

Get makes a GET request and returns a GJSON result. Results will be the raw data structure as returned by the APIC, wrapped in imdata, e.g.

{
  "imdata": [
    {
      "fvTenant": {
        "attributes": {
          "dn": "uni/tn-mytenant",
          "name": "mytenant",
        }
      }
    }
  ],
  "totalCount": "1"
}

func (*Client) GetClass

func (client *Client) GetClass(class string, mods ...func(*Req)) (Res, error)

GetClass makes a GET request by class and unwraps the results. Result is removed from imdata, but still wrapped in Class.attributes, e.g.

[
  {
    "fvTenant": {
      "attributes": {
        "dn": "uni/tn-mytenant",
        "name": "mytenant",
      }
    }
  }
]

func (*Client) GetDn

func (client *Client) GetDn(dn string, mods ...func(*Req)) (Res, error)

GetDn makes a GET request by DN. Result is removed from imdata and first result is removed from the list, e.g.

{
  "fvTenant": {
    "attributes": {
      "dn": "uni/tn-mytenant",
      "name": "mytenant",
    }
  }
}

func (*Client) Login

func (client *Client) Login() error

Login authenticates to the APIC.

func (Client) NewReq

func (client Client) NewReq(method, uri string, body io.Reader, mods ...func(*Req)) Req

NewReq creates a new Req request for this client.

func (*Client) Post

func (client *Client) Post(dn, data string, mods ...func(*Req)) (Res, error)

Post makes a POST request and returns a GJSON result. Hint: Use the Body struct to easily create POST body data.

func (*Client) Refresh

func (client *Client) Refresh() error

Refresh refreshes the authentication token. Note that this will be handled automatically be default. Refresh will be checked every request and the token will be refreshed after 8 minutes. Pass aci.NoRefresh to prevent automatic refresh handling and handle it directly instead.

type Req

type Req struct {
	// HttpReq is the *http.Request obejct.
	HttpReq *http.Request
	// Refresh indicates whether token refresh should be checked for this request.
	// Pass NoRefresh to disable Refresh check.
	Refresh bool
	// LogPayload indicates whether logging of payloads should be enabled.
	LogPayload bool
}

Req wraps http.Request for API requests.

type Res

type Res = gjson.Result

Res is an API response returned by client requests. This is a GJSON result, which offers advanced and safe parsing capabilities. https://github.com/tidwall/gjson

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL