restconf

package module
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2023 License: MPL-2.0 Imports: 18 Imported by: 0

README

Tests

go-restconf

go-restconf is a Go client library for RESTCONF devices. 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-restconf, install Go and go get:

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

Basic Usage
package main

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

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

    res, _ := client.GetData("Cisco-IOS-XE-native:native")
    println(res.Res.Get("Cisco-IOS-XE-native:native.hostname").String())
}

This will print for example:

ROUTER-1
Result manipulation

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

res, _ := client.GetData("Cisco-IOS-XE-native:native/interface/GigabitEthernet")
println(res.Res.Get("Cisco-IOS-XE-native:GigabitEthernet.0.name").String()) // name of first interface

for _, int := range res.Res.Get("Cisco-IOS-XE-native:GigabitEthernet").Array() {
    println(int.Get("@pretty").Raw) // pretty print interface attributes
}
Helpers for common patterns
res, _ := client.GetData("Cisco-IOS-XE-native:native/hostname")
res, _ := client.DeleteData("Cisco-IOS-XE-native:native/banner/login/banner")
Query parameters

Pass the restconf.Query object to the Get request to add query parameters:

queryConfig := restconf.Query("content", "config")
res, _ := client.GetData("Cisco-IOS-XE-native:native", queryConfig)

Pass as many parameters as needed:

res, _ := client.GetData("Cisco-IOS-XE-native:native",
    restconf.Query("content", "config"),
    restconf.Query("depth", "1"),
)
POST data creation

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

exampleUser := restconf.Body{}.Set("Cisco-IOS-XE-native:username.name", "test-user").Str
client.PostData("Cisco-IOS-XE-native:native", exampleUser)

These can be chained:

user1 := restconf.Body{}.
    Set("Cisco-IOS-XE-native:username.name", "test-user").
    Set("Cisco-IOS-XE-native:username.description", "My Test User")

...or nested:

attrs := restconf.Body{}.
    Set("name", "test-user").
    Set("description", "My Test User").
    Str
user1 := restconf.Body{}.SetRaw("Cisco-IOS-XE-native:username", attrs).Str

Documentation

See the documentation for more details.

Documentation

Overview

Package restconf is a RESTCONF (RFC 8040) client library for Go.

Index

Constants

View Source
const (
	DefaultMaxRetries         int     = 10
	DefaultBackoffMinDelay    int     = 1
	DefaultBackoffMaxDelay    int     = 60
	DefaultBackoffDelayFactor float64 = 1.2
	RestconfDataEndpoint      string  = "/data"
)

Variables

View Source
var TransientErrors = [...]TransientError{

	{
		StatusCode:   400,
		ErrorTag:     "invalid-value",
		ErrorMessage: "inconsistent value: Device refused one or more commands",
	},
	{
		ErrorTag: "lock-denied",
	},
	{
		ErrorTag: "in-use",
	},
	{
		StatusCode: 500,
	},
	{
		StatusCode: 501,
	},
	{
		StatusCode: 502,
	},
	{
		StatusCode: 503,
	},
	{
		StatusCode: 504,
	},
}

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 MaxRetries

func MaxRetries(x int) func(*Client)

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

func Query

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

Query sets an HTTP query parameter.

client.GetData("Cisco-IOS-XE-native:native", restconf.Query("content", "config"))

Or set multiple parameters:

client.GetData("Cisco-IOS-XE-native:native",
  restconf.Query("content", "config"),
  restconf.Query("depth", "1"))

func RequestTimeout

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

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

func SkipDiscovery added in v0.1.8

func SkipDiscovery(restconfEndpoint string, yangPatchCapability bool) func(*Client)

SkipDiscovery provides the otherwise dynamically discovered capabilities

Types

type Body

type Body struct {
	Str string
}

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

Body{}.Set(Cisco-IOS-XE-native:native.hostname", "ROUTER-1").Str

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.

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("Cisco-IOS-XE-native:native", Body{}.Set("hostname", "ROUTER-1").Str).Str

type CapabilitiesModel added in v0.1.4

type CapabilitiesModel struct {
	Capability []string `json:"capability"`
}

type CapabilitiesRootModel added in v0.1.4

type CapabilitiesRootModel struct {
	Capabilities CapabilitiesModel `json:"ietf-restconf-monitoring:capabilities"`
}

type Client

type Client struct {
	// HttpClient is the *http.Client used for API requests.
	HttpClient *http.Client

	// Url is the device url.
	Url string
	// Usr is the device username.
	Usr string
	// Pwd is the device 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
	// True if discovery (RESTCONF API endpoint and capabilities) is complete
	DiscoveryComplete bool
	// Discovered RESTCONF API endpoint
	RestconfEndpoint string
	// RESTCONF capabilities
	Capabilities []string
	// RESTCONF YANG-Patch capability
	YangPatchCapability bool
	// contains filtered or unexported fields
}

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

func NewClient

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

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

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

func (*Client) Backoff

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

Backoff waits following an exponential backoff algorithm

func (*Client) DeleteData

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

DeleteData makes a DELETE request and returns a GJSON result.

func (*Client) Discovery added in v0.1.4

func (client *Client) Discovery(mods ...func(*Req)) error

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", "Cisco-IOS-XE-native:native/hostname", nil)
res, _ := client.Do(req)

func (*Client) GetData

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

GetData makes a GET request and returns a GJSON result.

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

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

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

func (*Client) PostData

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

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

func (*Client) PutData

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

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

func (*Client) YangPatchData added in v0.1.4

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

YangPatchData makes a YANG-PATCH (RFC 8072) request and returns a GJSON result.

type ErrorModel added in v0.1.4

type ErrorModel struct {
	ErrorType    string `json:"error-type"`
	ErrorTag     string `json:"error-tag"`
	ErrorAppTag  string `json:"error-app-tag,omitempty"`
	ErrorPath    string `json:"error-path,omitempty"`
	ErrorMessage string `json:"error-message,omitempty"`
	ErrorInfo    string `json:"error-info,omitempty"`
}

type ErrorsModel added in v0.1.4

type ErrorsModel struct {
	Error []ErrorModel `json:"error"`
}

type ErrorsRootModel added in v0.1.4

type ErrorsRootModel struct {
	Errors ErrorsModel `json:"errors"`
}

type ErrorsRootNamespaceModel added in v0.1.7

type ErrorsRootNamespaceModel struct {
	Errors ErrorsModel `json:"ietf-restconf:errors"`
}

type Req

type Req struct {
	// HttpReq is the *http.Request object.
	HttpReq *http.Request
}

Req wraps http.Request for API requests.

type Res

type Res struct {
	Res gjson.Result
	// HTTP response status code
	StatusCode      int
	Errors          ErrorsModel
	YangPatchStatus YangPatchStatusModel
}

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

type TransientError added in v0.1.2

type TransientError struct {
	StatusCode   int
	ErrorType    string
	ErrorTag     string
	ErrorAppTag  string
	ErrorPath    string
	ErrorMessage string
	ErrorInfo    string
}

type YangPatchEdit added in v0.1.4

type YangPatchEdit struct {
	Operation string
	Target    string
	Value     Body
}

func NewYangPatchEdit added in v0.1.4

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

Create new YangPathEdit for YangPatchData()

type YangPatchEditModel added in v0.1.4

type YangPatchEditModel struct {
	EditId    string          `json:"edit-id"`
	Operation string          `json:"operation"`
	Target    string          `json:"target"`
	Point     string          `json:"point,omitempty"`
	Where     string          `json:"where,omitempty"`
	Value     json.RawMessage `json:"value,omitempty"`
}

type YangPatchModel added in v0.1.4

type YangPatchModel struct {
	PatchId string               `json:"patch-id"`
	Comment string               `json:"comment,omitempty"`
	Edit    []YangPatchEditModel `json:"edit"`
}

type YangPatchRootModel added in v0.1.4

type YangPatchRootModel struct {
	YangPatch YangPatchModel `json:"ietf-yang-patch:yang-patch"`
}

type YangPatchStatusEditStatusEditModel added in v0.1.4

type YangPatchStatusEditStatusEditModel struct {
	EditId string      `json:"edit-id"`
	Ok     bool        `json:"ok"`
	Errors ErrorsModel `json:"errors"`
}

type YangPatchStatusEditStatusModel added in v0.1.4

type YangPatchStatusEditStatusModel struct {
	Edit []YangPatchStatusEditStatusEditModel `json:"edit"`
}

type YangPatchStatusGlobalStatusModel added in v0.1.4

type YangPatchStatusGlobalStatusModel struct {
	Ok     bool        `json:"ok"`
	Errors ErrorsModel `json:"errors"`
}

type YangPatchStatusModel added in v0.1.4

type YangPatchStatusModel struct {
	PatchId      string                           `json:"patch-id"`
	GlobalStatus YangPatchStatusGlobalStatusModel `json:"global-status,omitempty"`
	EditStatus   YangPatchStatusEditStatusModel   `json:"edit-status,omitempty"`
	Errors       ErrorsModel                      `json:"errors,omitempty"`
}

type YangPatchStatusRootModel added in v0.1.4

type YangPatchStatusRootModel struct {
	YangPatchStatus YangPatchStatusModel `json:"ietf-yang-patch:yang-patch-status"`
}

Jump to

Keyboard shortcuts

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