crosswork

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MPL-2.0 Imports: 23 Imported by: 0

README

Tests

go-crosswork

go-crosswork is a Go client library for Cisco Crosswork Network Controller. It features a simple, extensible API and advanced JSON manipulation.

Getting Started

Installing

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

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

Basic Usage
package main

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

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

    res, _ := client.Get("/crosswork/inventory/v1/nodes/count")
    println(res.Get("number_of_nodes").String())
}

This will print something like:

33
Result manipulation

crosswork.Res uses GJSON to simplify handling JSON results. See the GJSON documentation for more detail.

res, _ := client.Post("/crosswork/inventory/v1/nodes/query", `{"limit":10}`)

for _, node := range res.Get("data").Array() {
    println(node.Get("host_name").String())
}
POST data creation

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

body := crosswork.Body{}.
    Set("data.0.profile", "example").
    Set("data.0.user_pass.0.user_name", "admin").
    Set("data.0.user_pass.0.password", "secret").
    Set("data.0.user_pass.0.type", "ROBOT_USERPASS_SSH")
client.Post("/crosswork/inventory/v1/credentials", body.Str, crosswork.NoLogPayload)

Documentation

See the documentation for more details.

Documentation

Overview

Package crosswork is a Cisco Crosswork Network Controller REST and RESTCONF client library for Go.

Index

Examples

Constants

View Source
const (

	// Job and device states of the Automations API. A job or a device is finished in the first three.
	MopSuccess  = "Success"
	MopFailed   = "Failed"
	MopCanceled = "Canceled"
	MopPending  = "Pending"
	MopRunning  = "Running"
)
View Source
const (
	DefaultMaxRetries         int     = 3
	DefaultBackoffMinDelay    int     = 2
	DefaultBackoffMaxDelay    int     = 60
	DefaultBackoffDelayFactor float64 = 3
	// DefaultDefaultMaxAsyncWaitTime is the default longest wait for an NSO plan, in seconds.
	DefaultDefaultMaxAsyncWaitTime int = 180
	// DefaultPlanPollInterval is the default time between two reads of an NSO plan.
	DefaultPlanPollInterval = time.Second
)

Default retry behaviour.

Variables

View Source
var ErrMopJobWait = errors.New("the job is not finished")

ErrMopJobWait is the error (wrapped) returned by WaitMopJob when the job is still not finished at the timeout.

Functions

func Accept

func Accept(v string) func(req *Req)

Accept sets the Accept header, overriding the default selected from the path.

func AfterWrite

func AfterWrite(fn func(ctx context.Context, res Res) error) func(*Req)

AfterWrite sets a function that Do calls after a successful write (and after the plan wait), still inside the lock of UseMutex or UseMutexKey, so a caller can hold the lock until the work that the write started is finished. The function gets the context of the request and the response of the write. When it fails, Do returns the response of the write together with a *WaitError. It is not called for a GET or for a write that failed.

The function and the requests it makes must not ask for the same key: a lock is not reentrant. Its GETs never take a lock.

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 seconds.

func BackoffMinDelay

func BackoffMinDelay(x int) func(*Client)

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

func ContentType

func ContentType(v string) func(req *Req)

ContentType sets the Content-Type header, overriding the default selected from the path.

func Context

func Context(ctx context.Context) func(req *Req)

Context binds a context to this request, overriding the one set with Client.WithContext.

func DefaultMaxAsyncWaitTime

func DefaultMaxAsyncWaitTime(x int) func(*Client)

DefaultMaxAsyncWaitTime modifies the longest wait for an NSO plan from the default of 180 seconds.

func Insecure

func Insecure(x bool) func(*Client)

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

Example
package main

import (
	"github.com/netascode/go-crosswork"
)

func main() {
	_, _ = crosswork.NewClient("https://1.1.1.1:30603", "user", "pwd", crosswork.Insecure(false))
}

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is an HTTP 409, a RESTCONF `data-exists` error, or a list of per-entry results with a failed entry of 409.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err means the object does not exist: an HTTP 404, a RESTCONF `data-missing` error, an error whose structured Code is a known not-found code, or a list of per-entry results in which every failed entry is a 404. It does not search the message text.

func IsPlanFailed

func IsPlanFailed(err error) bool

IsPlanFailed reports whether err is a PlanError for a plan that failed.

func IsPlanTimeout

func IsPlanTimeout(err error) bool

IsPlanTimeout reports whether err is a PlanError for a plan that did not finish in time.

func IsSessionLimit

func IsSessionLimit(err error) bool

IsSessionLimit reports whether err is the login failure Crosswork returns when the user already has the maximum number of sessions: a 503 from the SSO ticket endpoint ("Per user session limit reached"). The text is not inspected. Release sessions with Logout, or raise NumParallelSessionsPerUser (GET/PUT /crosswork/aaa/v1/sessionconfig).

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is an HTTP 401 or 403.

func JWTService

func JWTService(x string) func(*Client)

JWTService sets the `service` value sent when exchanging the ticket for a JWT.

func MaxAsyncWaitTime

func MaxAsyncWaitTime(seconds int) func(req *Req)

MaxAsyncWaitTime sets the longest time in seconds to wait for the NSO plan of this write. The default is Client.DefaultMaxAsyncWaitTime.

func MaxRetries

func MaxRetries(x int) func(*Client)

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

func NSORetry

func NSORetry(timeoutSeconds int) func(*Client)

NSORetry enables the NSO busy policy for write calls under /crosswork/proxy/nso/. It is off by default.

When NSO rejects a write because another transaction holds the datastore lock, nothing was applied, so the write is safe to retry whatever its method. The policy recognises that from the structured RESTCONF error-tag, `lock-denied` or `in-use`, never from message text. It then waits, polling once a second, until the running datastore has no lock or timeoutSeconds have passed, and retries with the normal backoff, up to MaxRetries times.

func NoLogPayload

func NoLogPayload(req *Req)

NoLogPayload prevents logging of payloads. Used for login and for calls that carry secrets such as credential profiles.

func NoResultCheck

func NoResultCheck(req *Req)

NoResultCheck disables the detection of failures inside HTTP 200 responses for this request.

func NoWait

func NoWait(req *Req)

NoWait makes a write return as soon as NSO accepted it, without waiting for the plan.

func PlanPath

func PlanPath(path string) func(req *Req)

PlanPath sets the full path of the NSO plan of the object this write changes, so the write waits for the plan (see Req.PlanPath and WaitForPlan).

client.Delete(path, crosswork.PlanPath(planPath))

func PlanPollInterval

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

PlanPollInterval modifies the time between two reads of an NSO plan from the default of one second.

func Query

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

Query sets an HTTP query parameter.

client.Get(path, crosswork.Query("content", "config"), crosswork.Query("depth", "1"))

func ReadOnly

func ReadOnly(req *Req)

ReadOnly marks a POST or RPC as a read-only call, so it may be retried after an ambiguous failure.

func RequestTimeout

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

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

func ResultCheck

func ResultCheck(fn func(Res) error) func(*Req)

ResultCheck replaces the built-in detection of failures inside HTTP 200 responses for this request. The function is called with every 2xx response; a non-nil error is returned to the caller.

func RetryNonIdempotent

func RetryNonIdempotent(req *Req)

RetryNonIdempotent allows this request to be retried after an ambiguous failure (connection reset after sending, timeout, 502/503/504) even if it is a write.

func RetryOnErrorCodes

func RetryOnErrorCodes(x []int) func(*Client)

RetryOnErrorCodes adds status codes that are retried, for calls that may be retried after an ambiguous failure (see Req.ReadOnly and Req.RetryNonIdempotent).

func StatusCode

func StatusCode(err error) int

StatusCode returns the HTTP status code of an *APIError, or 0 for any other error.

func Timeout

func Timeout(timeoutSeconds int) func(req *Req)

Timeout sets a custom timeout for this specific request in seconds.

func UseMutex

func UseMutex(req *Req)

UseMutex enables the use of the writing mutex for this request.

func UseMutexKey

func UseMutexKey(key string) func(*Req)

UseMutexKey makes this request take the lock with the given name, a lock that only requests with the same key share, held until Do returns (the response, the plan wait and AfterWrite included). A GET never takes it. The wait for the lock ends with the error of the context when the context of the request is cancelled. Unlike UseMutex it does not take the client's writing mutex as well. Use one key for each group of writes that must not overlap.

func UserAgent

func UserAgent(x string) func(*Client)

UserAgent modifies the HTTP User-Agent string.

func WithToken

func WithToken(jwt string) func(*Client)

WithToken uses a pre-provisioned JWT instead of a username and password. The client never logs in or refreshes; a rejected token is returned as an error.

Example
package main

import (
	"github.com/netascode/go-crosswork"
)

func main() {
	client, _ := crosswork.NewClient("https://1.1.1.1:30603", "", "", crosswork.WithToken("mytoken"))
	_, _ = client.Get("/crosswork/sso/v2/userInfo")
}

Types

type APIError

type APIError struct {
	Method     string
	URL        string
	StatusCode int
	// Message is the human readable message extracted from the body.
	Message string
	// Code is a structured code when the API supplies one: a RESTCONF error-tag, or
	// the [ErrXxx] prefix that some DLM messages carry. It is never derived from prose.
	Code string
	// Body is the raw response body.
	Body string
	// RestconfErrors holds the parsed RESTCONF errors, if any.
	RestconfErrors []RestconfError
	// EntryStatus holds the codes of the failed entries when a 2xx answer is a list of per-entry results
	// (HTTP 207 from the Workflow Manager Solutions services), for example [404, 409]; nil otherwise.
	EntryStatus []int
}

APIError is returned for every failed request: a non-2xx status, or a 2xx response whose body reports a failure (see ResultCheck).

The Error text keeps the `HTTP Request failed: StatusCode N` prefix, so callers that match on it keep working.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) HasRestconfTag

func (e *APIError) HasRestconfTag(tag string) bool

HasRestconfTag reports whether any RESTCONF error carries the given error-tag.

type ApplyMessage

type ApplyMessage struct {
	Template string
	Status   string
	Message  string
}

ApplyMessage is one entry of the message of an Apply Config activity: the template and what NSO said.

func ParseApplyMessages

func ParseApplyMessages(s string) []ApplyMessage

ParseApplyMessages reads the message of an Apply Config activity. On failure it is a JSON string that holds a list of {template, status, message}; any other text is returned as one message without a template.

type Body

type Body struct {
	Str string
}

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

Body{}.Set("name", "ABC").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 string, value interface{}) Body

Set sets a JSON path to a value. Any JSON-encodable value is accepted, so numbers and booleans keep their type.

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("children", Body{}.Set("name", "New").Str).Str

type BodyPager

type BodyPager struct {
	Path string
	// Body is the base request, e.g. a filter; leave it empty for `{}`.
	Body string
	Size int
	// FirstPage is the number of the first page (0 or 1).
	FirstPage int
	// PaginationPath is where the paging object is, in the request and in the response (default "pagination").
	PaginationPath string
	// ItemsPath is where the items are in the response (default "data").
	ItemsPath string
}

BodyPager pages a POST query whose request and response both carry a `pagination` object, the style of the Workflow Manager Solutions services (Golden Configuration, MOP): the request sets `pagination.pageNumber` and `pagination.pageSize`, and the response repeats the object, the Golden Configuration lists with `totalPages` and `last`. The first page is number 0 for Golden Configuration and 1 for the MOP lists, so FirstPage is a field.

func (*BodyPager) Items

func (b *BodyPager) Items(res Res) []Res

Items implements Pager for BodyPager.

func (*BodyPager) Next

func (b *BodyPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for BodyPager.

type Client

type Client struct {
	// HttpClient is the *http.Client used for API requests. Its Transport must stay a
	// *http.Transport: Insecure type-asserts it.
	HttpClient *http.Client
	// Url is the Crosswork base URL, e.g. https://cnc.example.com:30603 (without a trailing slash).
	Url string
	// Maximum number of retries
	MaxRetries int
	// Minimum delay between two retries, in seconds
	BackoffMinDelay int
	// Maximum delay between two retries, in seconds
	BackoffMaxDelay int
	// Backoff delay factor
	BackoffDelayFactor float64
	// UserAgent is the HTTP User-Agent string sent with requests.
	UserAgent string
	// RetryOnErrorCodes lists extra status codes that are retried, for calls that may be retried.
	RetryOnErrorCodes []int
	// NSOLockTimeout enables the NSO busy policy when greater than zero (see NSORetry): the
	// total seconds to wait for the NSO lock to be released. Zero (the default) disables it.
	NSOLockTimeout int
	// DefaultMaxAsyncWaitTime is the longest time in seconds to wait for an NSO plan, when a
	// request does not set MaxAsyncWaitTime. See DefaultMaxAsyncWaitTime.
	DefaultMaxAsyncWaitTime int
	// PlanPollInterval is the time between two reads of an NSO plan while waiting.
	PlanPollInterval time.Duration
	// JWTService is the `service` value sent when exchanging the ticket for a JWT.
	// The default is <Url>/app-dashboard; only the path matters to Crosswork.
	JWTService string
	// contains filtered or unexported fields
}

Client is an HTTP Crosswork client. Always use NewClient to construct it, otherwise requests will panic.

A Client is cheap to copy: all session state (token, ticket, mutexes) sits behind one shared pointer, so copies made with WithContext stay in sync. The request methods have pointer receivers, so assign the result of WithContext to a variable before calling them.

func NewClient

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

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

client, _ := NewClient("https://cnc.example.com:30603", "user", "password", Insecure(false), RequestTimeout(120))

To use a pre-provisioned JWT instead of a username and password, use WithToken. Self-signed certificates are accepted by default; pass Insecure(false) to verify them.

Example
package main

import (
	"github.com/netascode/go-crosswork"
)

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

	res, _ := client.Get("/crosswork/inventory/v1/nodes/count")
	println(res.Get("number_of_nodes").String())
}

func (*Client) Authenticate

func (client *Client) Authenticate() error

Authenticate makes sure a valid token is available: it logs in if there is none, and refreshes the JWT shortly before it expires, first from the cached ticket and, if the ticket was rejected, with a full login.

func (*Client) Backoff

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

Backoff waits following an exponential backoff algorithm and reports whether to retry. It reports false once the maximum number of attempts is reached.

func (*Client) Delete

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

Delete makes a DELETE request and returns a gjson result.

func (*Client) DeleteBody

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

DeleteBody makes a DELETE request with a body and returns a gjson result. Many Crosswork DELETE operations take a request body, e.g. DLM DELETE /crosswork/inventory/v1/credentials and /nodes.

Example
package main

import (
	"github.com/netascode/go-crosswork"
)

func main() {
	client, _ := crosswork.NewClient("https://1.1.1.1:30603", "user", "pwd")
	_, err := client.DeleteBody("/crosswork/inventory/v1/credentials", `{"data":[{"profile":"example"}]}`)
	if crosswork.IsNotFound(err) {
		println("gone")
	}
}

func (*Client) Do

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

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

req := client.NewReq("GET", "/crosswork/inventory/v1/nodes/count", nil)
res, _ := client.Do(req)

On a failed call Res still holds the parsed response body, next to the *APIError.

func (*Client) Get

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

Get makes a GET request and returns a gjson result. The path is the full path, e.g. /crosswork/inventory/v1/nodes/count.

func (*Client) Login

func (client *Client) Login() error

Login authenticates to Crosswork with the username and password and caches the ticket and JWT.

func (*Client) Logout

func (client *Client) Logout() error

Logout ends the Crosswork session that Login or the first call created, by deleting its ticket. Crosswork allows a limited number of sessions per user and counts one per ticket, so a program that logs in more than once (every command run, every test) should call Logout when it is done; an unclosed session counts until it times out.

Logout does nothing, and returns nil, when there is no session, and for a client created with WithToken, because the token is managed by whoever issued it. A ticket that Crosswork no longer knows (404, or a rejected token) counts as already ended. After a successful Logout the next call logs in again.

func (*Client) MopJob

func (client *Client) MopJob(id string, mods ...func(*Req)) (MopJob, error)

MopJob returns the status of a job. Pass NoLogPayload: the answer echoes the job input.

func (*Client) MopJobOutcome

func (client *Client) MopJobOutcome(id string, mods ...func(*Req)) (MopJobOutcome, error)

MopJobOutcome returns the status of a job with the result of every device and, for each device that is not Success, its detail. Call it when the job has finished (see WaitMopJob). Pass NoLogPayload.

func (*Client) MopJobResourceDetail

func (client *Client) MopJobResourceDetail(jobID, resourceID string, mods ...func(*Req)) (MopJobFailure, error)

MopJobResourceDetail returns the messages of one device of a job. The activities carry what NSO said.

func (*Client) MopJobResources

func (client *Client) MopJobResources(id string, mods ...func(*Req)) ([]MopJobResource, error)

MopJobResources returns the result of a job for each device, following the pages.

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) Paginate

func (client *Client) Paginate(p Pager, mods ...func(*Req)) ([]Res, error)

Paginate fetches every page of a list and returns all the items. It stops when the pager says there is no further page, when a page repeats the previous one (a server that ignores the paging parameters would otherwise be read forever), or after maxPages pages. If a page fails it returns the items fetched so far together with the error.

The mods are applied to every page request, e.g. Context or NoLogPayload.

items, err := client.Paginate(crosswork.NewCursorPager("/crosswork/inventory/v1/nodes/query", `{}`, 100))
Example
package main

import (
	"github.com/netascode/go-crosswork"
)

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

	nodes, _ := client.Paginate(crosswork.NewCursorPager("/crosswork/inventory/v1/nodes/query", "", 100))
	println(len(nodes))

	_, _ = client.Paginate(&crosswork.TokenPager{Path: "/crosswork/collection/v1/collectionjob/summary/query", PageSize: 100, ItemsPath: "collection_job_status_list"})
	_, _ = client.Paginate(&crosswork.PageNumberPager{Path: "/crosswork/performance/v1/policies/inventory-devices", PageParam: "page", SizeParam: "pageSize", FirstPage: 1, Size: 100, ItemsPath: "data"})
}

func (*Client) Patch

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

Patch makes a PATCH request and returns a gjson result.

func (*Client) Post

func (client *Client) Post(path, 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.

Example
package main

import (
	"github.com/netascode/go-crosswork"
)

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

	res, _ := client.Post("/crosswork/inventory/v1/nodes/query", `{"limit":10}`)
	for _, node := range res.Get("data").Array() {
		println(node.Get("host_name").String())
	}

	body := crosswork.Body{}.
		Set("data.0.profile", "example").
		Set("data.0.user_pass.0.user_name", "admin").
		Set("data.0.user_pass.0.password", "secret").
		Set("data.0.user_pass.0.type", "ROBOT_USERPASS_SSH")
	client.Post("/crosswork/inventory/v1/credentials", body.Str, crosswork.NoLogPayload)
}

func (*Client) Put

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

Put makes a PUT request and returns a gjson result.

func (*Client) WaitForMopJob

func (client *Client) WaitForMopJob(interval, timeout time.Duration) func(*Req)

WaitForMopJob is a request option for a write that starts a MOP job (the answer carries the id in `key`): after the write, and while the lock of UseMutex or UseMutexKey is held, it polls the job every interval until it has finished or the timeout passes. It is an AfterWrite function, so a failure comes back as a *WaitError next to the response of the write; a job that is still running at the timeout wraps ErrMopJobWait, and an answer without a job id is an error too.

func (*Client) WaitForPlan

func (client *Client) WaitForPlan(planPath string, gone bool, maxSeconds int) error

WaitForPlan reads the NSO plan at planPath (a full path, for example /crosswork/proxy/nso/restconf/data/cisco-sr-te-cfp:sr-te/cisco-sr-te-cfp-sr-odn:odn/odn-template-plan=x) every Client.PlanPollInterval until it is ready, or, with gone set, until it answers 404. A plan that reports a failure ends the wait with a *PlanError, and so does the end of maxSeconds (zero uses Client.DefaultMaxAsyncWaitTime).

A write waits by itself when it carries the PlanPath option; WaitForPlan is for the callers that need to wait later. A plan that does not exist is "gone": for a write that is fine (the object has no plan), so the wait returns nil.

func (*Client) WaitMopJob

func (client *Client) WaitMopJob(ctx context.Context, id string, interval, timeout time.Duration, mods ...func(*Req)) (MopJob, error)

WaitMopJob polls the status of a job every interval until it has finished or the timeout passes. On a timeout it returns the last status with an error that wraps ErrMopJobWait. A job still Pending, Running or Scheduled is not finished. The context cancels the wait. Pass NoLogPayload.

func (Client) WithContext

func (client Client) WithContext(ctx context.Context) Client

WithContext returns a copy of the client bound to ctx. Requests, backoff sleeps and logins made through the copy stop when ctx is cancelled. Session state is shared.

Example
package main

import (
	"context"

	"github.com/netascode/go-crosswork"
)

func main() {
	client, _ := crosswork.NewClient("https://1.1.1.1:30603", "user", "pwd")
	var ctx context.Context = context.Background()

	c := client.WithContext(ctx) // assign first: the methods have pointer receivers
	_, _ = c.Get("/crosswork/inventory/v1/nodes/count")
}

func (*Client) YangPatch

func (client *Client) YangPatch(path, patchID, comment string, edits []YangPatchEdit, mods ...func(*Req)) (Res, error)

YangPatch makes a YANG-PATCH (RFC 8072) request and returns a gjson result. The edits are applied atomically: if one fails, none is applied. It is the way to batch many changes into one call.

client.YangPatch("/crosswork/proxy/nso/restconf/data", "patch-1", "",
    []YangPatchEdit{NewYangPatchEdit("merge", "/tailf-ncs:devices/authgroups/group=g1", Body{}.SetRaw(...))})

The request is sent as application/yang-patch+json and answered as application/yang-data+json. PATCH is not retried after an ambiguous failure unless RetryNonIdempotent is passed.

Example
package main

import (
	"github.com/netascode/go-crosswork"
)

func main() {
	client, _ := crosswork.NewClient("https://1.1.1.1:30603", "user", "pwd", crosswork.NSORetry(120))

	_, _ = client.YangPatch("/crosswork/proxy/nso/restconf/data", "patch-1", "", []crosswork.YangPatchEdit{
		crosswork.NewYangPatchEdit("merge", "/tailf-ncs:devices/authgroups/group=g1",
			crosswork.Body{}.SetRaw("tailf-ncs:group", `[{"name":"g1"}]`)),
		crosswork.NewYangPatchEdit("remove", "/tailf-ncs:devices/authgroups/group=g2", crosswork.Body{}),
	})
}

type CursorPager

type CursorPager struct {
	Path string
	// Body is the base request, e.g. a filter; leave it empty for `{}`.
	Body  string
	Limit int
	// LimitField is the request member for the page size (default "limit").
	LimitField string
	// CursorField is the request member that takes the cursor (default "next_from").
	CursorField string
	// ItemCursor is the member of the last item that becomes the cursor (default "uuid").
	ItemCursor string
	// ItemsPath is where the items are in the response (default "data").
	ItemsPath string
}

CursorPager pages a POST query with a cursor taken from the last item of the previous page. DLM works like this: the request carries `limit` and `next_from`, and the response has no cursor, so the client passes the `uuid` of the last item it received. The response has no `data` member on the last, empty page.

func NewCursorPager

func NewCursorPager(path, body string, limit int) *CursorPager

NewCursorPager returns a CursorPager with the DLM defaults.

func (*CursorPager) Items

func (c *CursorPager) Items(res Res) []Res

Items implements Pager for CursorPager.

func (*CursorPager) Next

func (c *CursorPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for CursorPager.

type FilterDataPager

type FilterDataPager struct {
	Path string
	// Filter is the `filter` member of the request as JSON object text; empty for `{}`.
	Filter string
	// Criteria is the `filterData.Criteria` text; empty for none.
	Criteria string
	// Size is the page size; 200 when zero or negative.
	Size int
	// ItemsPath is where the items are in the response (default "data").
	ItemsPath string
}

FilterDataPager pages a POST query of the inventory service whose request carries `filterData` with `PageSize`, `PageNum` (the first page is 0) and an optional `Criteria`, such as the node query `select uuid from robotnodedata where dg_uuid=<id>` that lists the devices of a data gateway. The last page is short; a page that is exactly full is followed by one more request that answers an empty list.

func (*FilterDataPager) Items

func (f *FilterDataPager) Items(res Res) []Res

Items implements Pager for FilterDataPager.

func (*FilterDataPager) Next

func (f *FilterDataPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for FilterDataPager.

type HeaderPager

type HeaderPager struct {
	Path string
	// Body is the base RPC input.
	Body  string
	Limit int
	// HeaderPath is the path of the collection-header in the request, e.g.
	// "cat-inventory-rpc:input.cat-inventory-rpc:get-all-services-request.collection-header".
	HeaderPath string
	// ItemsPath is the path of the item list in the response, e.g.
	// "cat-inventory-rpc:output.get-all-services-response.collection-data.service-info".
	ItemsPath string
}

HeaderPager pages a RESTCONF RPC whose input has a `collection-header` with `offset` and `limit` (the Active Topology service inventory RPCs). The offset advances by the number of items received.

func (*HeaderPager) Items

func (h *HeaderPager) Items(res Res) []Res

Items implements Pager for HeaderPager.

func (*HeaderPager) Next

func (h *HeaderPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for HeaderPager.

type MopJob

type MopJob struct {
	ID string
	// Name is the job name.
	Name string
	// Status is one of the Mop constants.
	Status string
	// Message is the reason the job gives, for example that every device failed; empty on success.
	Message string
	// Raw is the whole answer. It echoes the job input, variable values included: never log it.
	Raw Res
}

MopJob is the status of a job.

func (MopJob) Finished

func (j MopJob) Finished() bool

Finished reports whether the job has ended (Success, Failed or Canceled).

type MopJobFailure

type MopJobFailure struct {
	Device     string
	DeviceUUID string
	// Result is the device result (Failed, Canceled, Pending or Running).
	Result string
	// Message is the message of the device and Messages the parsed messages of its activities.
	Message  string
	Messages []ApplyMessage
}

MopJobFailure describes a device that did not succeed.

func (MopJobFailure) String

func (f MopJobFailure) String() string

String returns the failure on one line: the device, the result and the messages.

type MopJobOutcome

type MopJobOutcome struct {
	Job       MopJob
	Resources []MopJobResource
	// Failures holds every device that is not Success, with the detail the controller gives.
	Failures []MopJobFailure
}

MopJobOutcome is the status of a job with the result of every device.

func (MopJobOutcome) OK

func (o MopJobOutcome) OK() bool

OK reports whether the job finished and every device succeeded.

type MopJobResource

type MopJobResource struct {
	// ID is the id of the resource, the last segment of its describeURI; it addresses MopJobResourceDetail.
	ID string
	// Name is the name of the device and DeviceUUID its uuid.
	Name       string
	DeviceUUID string
	// Result is one of the Mop constants.
	Result string
	Raw    Res
}

MopJobResource is the result of a job for one device.

func (MopJobResource) Finished

func (r MopJobResource) Finished() bool

Finished reports whether the device has ended (Success, Failed or Canceled).

type OffsetPager

type OffsetPager struct {
	Path        string
	Limit       int
	OffsetParam string // default "offset"
	LimitParam  string // default "limit"
	// ItemsPath is the path of the list in the response, e.g.
	// "cisco-crosswork-segment-routing-policy:sr-policies.policy".
	ItemsPath string
}

OffsetPager pages a GET with `offset` and `limit` query parameters, as the RESTCONF list reads of the topology service do. The offset advances by the number of items received and the last page is short.

func (*OffsetPager) Items

func (o *OffsetPager) Items(res Res) []Res

Items implements Pager for OffsetPager.

func (*OffsetPager) Next

func (o *OffsetPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for OffsetPager.

type PageNumberPager

type PageNumberPager struct {
	Path      string
	PageParam string
	SizeParam string
	// FirstPage is the number of the first page (0 or 1).
	FirstPage int
	Size      int
	// ItemsPath is where the items are in the response ("content" for a Spring page); an empty
	// path means the response is the array.
	ItemsPath string
}

PageNumberPager pages a GET with a page number and a page size, whose parameter names differ by service: page/pageSize (EMF performance), PageNum/PageSize (ZTP config), and so on. For example /performance/v1/policies/inventory-devices: the page number is 1-based and page=0 is a 500. Some lists ignore both parameters, which Paginate copes with by stopping when a page repeats.

func (*PageNumberPager) Items

func (p *PageNumberPager) Items(res Res) []Res

Items implements Pager for PageNumberPager.

func (*PageNumberPager) Next

func (p *PageNumberPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for PageNumberPager.

type PageRequest

type PageRequest struct {
	Method string
	Path   string
	Body   string
	Mods   []func(*Req)
}

PageRequest is the request for one page.

type PageResult

type PageResult struct {
	// Res is the response of the page.
	Res Res
	// Items are the items of this page, as returned by Pager.Items.
	Items []Res
	// Page is the number of the page just fetched, starting at 0.
	Page int
	// Fetched is the number of items fetched so far, including this page.
	Fetched int
}

PageResult is a fetched page.

type Pager

type Pager interface {
	// Next returns the request for the page after prev, or false when there is no further
	// page. prev is nil for the first page.
	Next(prev *PageResult) (PageRequest, bool)
	// Items returns the items of a response.
	Items(res Res) []Res
}

Pager describes how an endpoint is paged.

type PlanError

type PlanError struct {
	// Path is the plan that was read.
	Path string
	// Failed is true when the plan reports a failure; Timeout is true when the wait time passed.
	Failed, Timeout bool
	// Message is the `error-info/message` of the plan, if any.
	Message string
	// Code is the status code of the first failed component, for example TSDN-SR-301.
	Code string
	// Details holds the `status-code-detail` entries.
	Details []PlanStatusDetail
	// State is a one-line summary of the plan at the end of the wait, for example
	// "self: init=not-reached ready=not-reached".
	State string
	// Raw is the body of the last plan read.
	Raw string
}

PlanError is returned when a write was accepted but its NSO plan did not reach the expected state: the plan failed, or it did not get there within the wait time.

A failed plan after a DELETE means the object is already gone from the NSO configuration while its clean-up on the device failed; NSO keeps a zombie that must be recovered (the `tailf-ncs:zombies/service/re-deploy` action) before the same key can be created again.

func (*PlanError) Error

func (e *PlanError) Error() string

Error implements the error interface.

type PlanStatusDetail

type PlanStatusDetail struct {
	Type              string
	Name              string
	Code              string
	Severity          string
	Context           []string
	RecommendedAction string
	ImpactedDevice    string
}

PlanStatusDetail is one entry of the `status-code-detail` list of an NSO plan: what the TSDN function pack reports for a component that failed.

type Req

type Req struct {
	// HttpReq is the *http.Request object.
	HttpReq *http.Request
	// LogPayload indicates whether logging of payloads should be enabled.
	LogPayload bool
	// UseMutex indicates whether to use the client's writing mutex for this request. The mutex is held until Do
	// returns, so it covers the plan wait (PlanPath) and AfterWrite as well as the request itself.
	UseMutex bool
	// MutexKey names a lock of its own for this request (see UseMutexKey). Requests with the same key run one at a
	// time, requests with different keys, and requests with UseMutex, do not wait for each other.
	MutexKey string
	// AfterWrite is called after a successful PUT, POST, PATCH or DELETE, and after the plan wait, while the lock is
	// still held (see AfterWrite). It receives the context of the request and the response of the write.
	AfterWrite func(ctx context.Context, res Res) error
	// ReadOnly marks a POST (or RPC) as a read, so it is retried like a GET.
	ReadOnly bool
	// RetryNonIdempotent allows retries after an ambiguous failure for any method.
	RetryNonIdempotent bool
	// Timeout is a per-request timeout; zero uses the client's timeout (120 seconds for writes
	// under the NSO proxy). It may be longer than the client's timeout.
	Timeout time.Duration
	// MaxAsyncWaitTime is the longest time in seconds to wait for the NSO plan of a write (see
	// PlanPath); zero uses Client.DefaultMaxAsyncWaitTime.
	MaxAsyncWaitTime int
	// NoWait skips the wait for the plan even when PlanPath is set.
	NoWait bool
	// PlanPath is the full path of the NSO plan of the object this write changes. When set, a
	// successful PUT, POST or PATCH waits until the plan is ready and a successful DELETE waits
	// until the plan is gone. NSO does not return a handle on a write, so the caller supplies it.
	PlanPath string
	// contains filtered or unexported fields
}

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

type RestconfError

type RestconfError struct {
	Type    string
	Tag     string
	AppTag  string
	Path    string
	Message string
	Info    string
}

RestconfError is one entry of a RESTCONF `errors` structure (RFC 8040).

type TokenPager

type TokenPager struct {
	Path string
	// Body is the base request; leave it empty for `{}`.
	Body     string
	PageSize int
	// OptionsPath is where the paging options live (default "query_options").
	OptionsPath string
	// ItemsPath is where the items are in the response, e.g. "collection_job_status_list".
	ItemsPath string
}

TokenPager pages a POST query with an opaque page token. The collection service nests the options directly under `query_options` (page_size, page_token); the platform services nest them one level deeper, under `query_options.pagination`. The response carries the token of the next page in the same place, and the last page has no `query_options` (collection) or an empty token. The collection service ends the walk with a REJECTED response, which is accepted as the end of the list; the platform lists end with an empty page that repeats the token.

func (*TokenPager) Items

func (t *TokenPager) Items(res Res) []Res

Items implements Pager for TokenPager.

func (*TokenPager) Next

func (t *TokenPager) Next(prev *PageResult) (PageRequest, bool)

Next implements Pager for TokenPager.

type WaitError

type WaitError struct {
	Err error
}

WaitError is returned by Do when a write was accepted (2xx) but the AfterWrite waiter of the request failed, for example a job that is still running at the timeout. Do returns the response of the write with it, so the caller can read the id that the write returned. It unwraps to the error of the waiter.

func (*WaitError) Error

func (e *WaitError) Error() string

Error implements the error interface.

func (*WaitError) Unwrap

func (e *WaitError) Unwrap() error

Unwrap returns the error of the waiter.

type YangPatchEdit

type YangPatchEdit struct {
	// Operation is one of create, delete, insert, merge, move, replace or remove.
	Operation string
	// Target is the path of the data node, relative to the patch path, e.g. /tailf-ncs:devices/authgroups/group=g1.
	Target string
	// Value is the JSON data of the edit; leave it empty for remove and delete.
	Value Body
}

YangPatchEdit is one edit of a YANG-PATCH (RFC 8072) request.

func NewYangPatchEdit

func NewYangPatchEdit(operation, target string, value Body) YangPatchEdit

NewYangPatchEdit creates a YangPatchEdit for YangPatch.

Jump to

Keyboard shortcuts

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