netconf

package module
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 19 Imported by: 0

README

netconf

CI codecov Go Reference

Go implementation of the NETCONF protocol (RFC 6241).

Features

  • Full NETCONF base operations: get, get-config, edit-config, copy-config, delete-config, lock, unlock, commit, validate, discard-changes, kill-session, close-session
  • Confirmed commit with timeout, persist, and cancel support (RFC 6241 Section 8.4)
  • Event notifications via create-subscription (RFC 5277)
  • Custom RPC dispatch for vendor-specific operations
  • Capability negotiation with automatic NETCONF 1.1 chunked framing upgrade
  • SSH transport (RFC 6242)
  • TLS transport (RFC 7589)

Install

go get github.com/Mrflatt/netconf

Usage

SSH
import (
    "context"

    "github.com/Mrflatt/netconf"
    ncssh "github.com/Mrflatt/netconf/transport/ssh"
    "golang.org/x/crypto/ssh"
)

config := &ssh.ClientConfig{
    User:            "admin",
    Auth:            []ssh.AuthMethod{ssh.Password("admin")},
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}

ctx := context.Background()

tr, err := ncssh.Dial(ctx, "tcp", "router:830", config)
if err != nil {
    // handle error
}

sess, err := netconf.NewSession(ctx, netconf.WithTransport(tr))
if err != nil {
    // handle error
}
defer sess.Close(ctx)

reply, err := sess.GetConfig(ctx, netconf.Running)
if err != nil {
    // handle error
}
fmt.Println(reply)
TLS
import (
    "context"
    "crypto/tls"

    "github.com/Mrflatt/netconf"
    nctls "github.com/Mrflatt/netconf/transport/tls"
)

config := &tls.Config{
    // configure certificates
}

ctx := context.Background()

tr, err := nctls.Dial(ctx, "tcp", "router:6513", config)
if err != nil {
    // handle error
}

sess, err := netconf.NewSession(ctx, netconf.WithTransport(tr))
if err != nil {
    // handle error
}
defer sess.Close(ctx)
Edit config
config := `
<config>
    <interface>
        <name>eth0</name>
        <enabled>true</enabled>
    </interface>
</config>`

err := sess.EditConfig(ctx, netconf.Candidate, config,
    netconf.WithDefaultMergeStrategy(netconf.MergeConfig),
    netconf.WithTestStrategy(netconf.TestThenSet),
)
if err != nil {
    // handle error
}

err = sess.Commit(ctx)
Subtree filtering
filter := `<interfaces/>`
reply, err := sess.GetConfig(ctx, netconf.Running,
    netconf.WithSubtreeFilter(filter),
)
Custom RPC
type GetSchema struct {
    XMLName    xml.Name `xml:"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring get-schema"`
    Identifier string   `xml:"identifier"`
    Format     string   `xml:"format"`
}

reply, err := sess.Dispatch(ctx, &GetSchema{
    Identifier: "ietf-interfaces",
    Format:     "yang",
})

Session options

Option Description
WithTransport Set the transport (required)
WithCapabilities Override default client capabilities
WithNotificationHandler Set handler for async notifications
WithLogger Set a logger
WithErrorSeverity Configure which error severities are returned
WithRPCAttr Add extra XML attributes to outgoing <rpc> elements
WithHelloTimeout Set hello exchange timeout (default 30s)

License

MIT

Documentation

Index

Constants

View Source
const (
	WritableRunningCapability     = "urn:ietf:params:netconf:capability:writable-running:1.0"
	StartupCapability             = "urn:ietf:params:netconf:capability:startup:1.0"
	CandidateCapability           = "urn:ietf:params:netconf:capability:candidate:1.0"
	RollbackOnErrorCapability     = "urn:ietf:params:netconf:capability:rollback-on-error:1.0"
	URLCapability                 = "urn:ietf:params:netconf:capability:url:1.0"
	XPathCapability               = "urn:ietf:params:netconf:capability:xpath:1.0"
	ConfirmedCommitCapability     = "urn:ietf:params:netconf:capability:confirmed-commit:1.1"
	ValidateOldCapability         = "urn:ietf:params:netconf:capability:validate:1.0"
	ValidateCapability            = "urn:ietf:params:netconf:capability:validate:1.1"
	WithDefaultsCapability        = "urn:ietf:params:netconf:capability:with-defaults:1.0"
	NotificationCapability        = "urn:ietf:params:netconf:capability:notification:1.0"
	DynamicNotificationCapability = "urn:ietf:params:netconf:capability:notification:2.0"
	InterleaveCapability          = "urn:ietf:params:netconf:capability:interleave:1.0"
)
View Source
const (
	RunningDatastore   = "running"
	CandidateDatastore = "candidate"
	StartupDatastore   = "startup"
)
View Source
const (
	BaseCapability = "urn:ietf:params:netconf:base"
)

Variables

View Source
var (
	// Running configuration datastore. Required by RFC6241.
	Running = Datastore{Store: "running"}

	// Candidate configuration datastore.  Supported with the
	// `:candidate` capability defined in RFC6241 section 8.3.
	Candidate = Datastore{Store: "candidate"}

	// Startup configuration datastore.  Supported with the
	// `:startup` capability defined in RFC6241 section 8.7.
	Startup = Datastore{Store: "startup"} //
)
View Source
var CiscoNXOSAttrs = []SessionOption{
	WithRPCAttr("xmlns:nxos", "http://www.cisco.com/nxos:1.0"),
	WithRPCAttr("xmlns:if", "http://www.cisco.com/nxos:1.0:if_manager"),
	WithRPCAttr("xmlns:nfcli", "http://www.cisco.com/nxos:1.0:nfcli"),
	WithRPCAttr("xmlns:vlan_mgr_cli", "http://www.cisco.com/nxos:1.0:vlan_mgr_cli"),
}

CiscoNXOSAttrs provides the namespace attributes required by Cisco NX-OS legacy NX-API XML NETCONF stack (port 22, "feature nxapi").

View Source
var DefaultCapabilities = []string{
	BaseCapability + ":1.0",
	BaseCapability + ":1.1",
}

DefaultCapabilities are the capabilities sent by the client during the hello exchange by the server.

View Source
var ErrClosed = errors.New("closed connection")
View Source
var HPComwareAttrs = []SessionOption{
	WithRPCAttr("xmlns:data", "http://www.hp.com/netconf/data:1.0"),
	WithRPCAttr("xmlns:config", "http://www.hp.com/netconf/config:1.0"),
}

HPComwareAttrs provides the namespace attributes used by HP Comware devices.

Functions

func ExpandCapability

func ExpandCapability(s string) string

ExpandCapability will automatically add the standard capability prefix of `urn:ietf:params:netconf:capability` if not already present.

Types

type CancelCommitOption

type CancelCommitOption interface {
	// contains filtered or unexported methods
}

CancelCommitOption is an optional arguments to Session.CancelCommit method.

type CancelCommitRequest

type CancelCommitRequest struct {
	XMLName   xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 cancel-commit"`
	PersistID string   `xml:"persist-id,omitempty"`
}

func NewCancelCommitRequest

func NewCancelCommitRequest(opts ...CancelCommitOption) *CancelCommitRequest

type CloseSessionRequest

type CloseSessionRequest struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 close-session"`
}

type CommitOption

type CommitOption interface {
	// contains filtered or unexported methods
}

CommitOption is an optional arguments to Session.Commit method.

func WithConfigurationRegion

func WithConfigurationRegion(reg string) CommitOption

func WithConfirmed

func WithConfirmed() CommitOption

WithConfirmed will mark the commits as requiring confirmation or will roll back after the default timeout on the device (default should be 600s). The commit can be confirmed with another `<commit>` call without the confirmed option, extended by calling with `Commit` With `WithConfirmed` or `WithConfirmedTimeout` or canceling the commit with a `Session.CancelCommit` call. This requires the device to support the ConfirmedCommitCapability capability.

func WithConfirmedTimeout

func WithConfirmedTimeout(timeout time.Duration) CommitOption

WithConfirmedTimeout is like `WithConfirmed` but using the given timeout duration instead of the device's default.

func WithPersist

func WithPersist(id string) CommitOption

WithPersist allows you to set an identifier to confirm a commit in another sessions. Confirming the commit requires setting the `WithPersistID` in the following `Commit` call matching the id set on the confirmed commit. Will mark the commit as confirmed, if not already set.

type CommitRequest

type CommitRequest struct {
	XMLName        xml.Name     `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 commit"`
	Confirmed      EmptyElement `xml:"confirmed,omitempty"`
	ConfirmTimeout int64        `xml:"confirm-timeout,omitempty"`
	Persist        string       `xml:"persist,omitempty"`
	PersistID      string       `xml:"persist-id,omitempty"`
	Region         string       `xml:"configuration-region,omitempty"`
}

func NewCommitRequest

func NewCommitRequest(opts ...CommitOption) *CommitRequest

type CopyConfigRequest

type CopyConfigRequest struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 copy-config"`
	Target  any      `xml:"target"`
	Source  any      `xml:"source"`
}

type CreateSubscriptionOption

type CreateSubscriptionOption interface {
	// contains filtered or unexported methods
}

CreateSubscriptionOption is an optional arguments to Session.CreateSubscription method.

func WithFilterOption

func WithFilterOption(subtree string) CreateSubscriptionOption

func WithStartTimeOption

func WithStartTimeOption(st time.Time) CreateSubscriptionOption

func WithStopTimeOption

func WithStopTimeOption(et time.Time) CreateSubscriptionOption

func WithStreamOption

func WithStreamOption(s string) CreateSubscriptionOption

type CreateSubscriptionRequest

type CreateSubscriptionRequest struct {
	XMLName   xml.Name `xml:"urn:ietf:params:xml:ns:netconf:notification:1.0 create-subscription"`
	Stream    string   `xml:"stream,omitempty"`
	Filter    Filter   `xml:"filter,omitempty"`
	StartTime string   `xml:"startTime,omitempty"`
	StopTime  string   `xml:"stopTime,omitempty"`
}

type Datastore

type Datastore struct {
	Store  string
	Region string
}

func (Datastore) MarshalXML

func (s Datastore) MarshalXML(e *xml.Encoder, start xml.StartElement) error

func (Datastore) String

func (s Datastore) String() string

type DefaultsMode

type DefaultsMode string
const (
	DefaultsModeTrim           DefaultsMode = "trim"
	DefaultModeReportAll       DefaultsMode = "report-all"
	DefaultModeReportAllTagged DefaultsMode = "report-all-tagged"
	DefaultModeExplicit        DefaultsMode = "explicit"
)

type DeleteConfigRequest

type DeleteConfigRequest struct {
	XMLName xml.Name  `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 delete-config"`
	Target  Datastore `xml:"target"`
}

type DiscardChangesRequest

type DiscardChangesRequest struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 discard-changes"`
}

type EditConfigOption

type EditConfigOption interface {
	// contains filtered or unexported methods
}

EditConfigOption is an optional arguments to Session.EditConfig method.

func WithDefaultMergeStrategy

func WithDefaultMergeStrategy(op MergeStrategy) EditConfigOption

WithDefaultMergeStrategy sets the default config merging strategy for the <edit-config> operation. Only [Merge], [Replace], and [None] are supported (the rest of the strategies are for defining as attributed in individual elements inside the `<config>` subtree).

func WithErrorStrategy

func WithErrorStrategy(opt ErrorStrategy) EditConfigOption

WithErrorStrategy sets the `error-option` in the `<edit-config>` operation. This defines the behavior when errors are encountered applying the supplied config. See ErrorStrategy for the available options.

func WithTestStrategy

func WithTestStrategy(op TestStrategy) EditConfigOption

WithTestStrategy sets the `test-option` in the `<edit-config>` operation. This defines what testing should be done the supplied configuration. See the documentation on TestStrategy for details on each strategy.

type EditConfigRequest

type EditConfigRequest struct {
	XMLName              xml.Name      `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 edit-config"`
	Target               Datastore     `xml:"target"`
	DefaultMergeStrategy MergeStrategy `xml:"default-operation,omitempty"`
	TestStrategy         TestStrategy  `xml:"test-option,omitempty"`
	ErrorStrategy        ErrorStrategy `xml:"error-option,omitempty"`

	Inner any    `xml:",innerxml"`
	URL   string `xml:"url,omitempty"`
}

func NewEditConfigRequest

func NewEditConfigRequest(target Datastore, config any, opts ...EditConfigOption) *EditConfigRequest

type EmptyElement

type EmptyElement bool

func (EmptyElement) MarshalXML

func (e EmptyElement) MarshalXML(enc *xml.Encoder, start xml.StartElement) error

func (*EmptyElement) UnmarshalXML

func (e *EmptyElement) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error

type ErrSeverity

type ErrSeverity string
const (
	SevError   ErrSeverity = "error"
	SevWarning ErrSeverity = "warning"
)

type ErrTag

type ErrTag string
const (
	ErrInUse                 ErrTag = "in-use"
	ErrInvalidValue          ErrTag = "invalid-value"
	ErrTooBig                ErrTag = "too-big"
	ErrMissingAttribute      ErrTag = "missing-attribute"
	ErrBadAttribute          ErrTag = "bad-attribute"
	ErrUnknownAttribute      ErrTag = "unknown-attribute"
	ErrMissingElement        ErrTag = "missing-element"
	ErrBadElement            ErrTag = "bad-element"
	ErrUnknownElement        ErrTag = "unknown-element"
	ErrUnknownNamespace      ErrTag = "unknown-namespace"
	ErrAccessDenied          ErrTag = "access-denied"
	ErrLockDenied            ErrTag = "lock-denied"
	ErrResourceDenied        ErrTag = "resource-denied"
	ErrRollbackFailed        ErrTag = "rollback-failed"
	ErrDataExists            ErrTag = "data-exists"
	ErrDataMissing           ErrTag = "data-missing"
	ErrOperationNotSupported ErrTag = "operation-not-supported"
	ErrOperationFailed       ErrTag = "operation-failed"
	ErrPartialOperation      ErrTag = "partial-operation"
	ErrMalformedMessage      ErrTag = "malformed-message"
)

type ErrType

type ErrType string
const (
	ErrTypeTransport ErrType = "transport"
	ErrTypeRPC       ErrType = "rpc"
	ErrTypeProtocol  ErrType = "protocol"
	ErrTypeApp       ErrType = "app"
)

type ErrorStrategy

type ErrorStrategy string

ErrorStrategy defines the behavior when an error is encountered during a `<edit-config>` operation.

*Note*: in RFC6241 7.2 this is called the `error-option` parameter. Since the `option` term is already overloaded this was changed to `ErrorStrategy` for a cleaner API.

const (
	// StopOnError will about the `<edit-config>` operation on the first error.
	StopOnError ErrorStrategy = "stop-on-error"

	// ContinueOnError will continue to parse the configuration data even if an
	// error is encountered.  Errors are still recorded and reported in the
	// reply.
	ContinueOnError ErrorStrategy = "continue-on-error"

	// RollbackOnError will restore the configuration back to before the
	// `<edit-config>` operation took place.  This requires the device to
	// support the `:rollback-on-error` capability.
	RollbackOnError ErrorStrategy = "rollback-on-error"
)

type Filter

type Filter string

func (Filter) MarshalXML

func (f Filter) MarshalXML(e *xml.Encoder, start xml.StartElement) error

type GetOption

type GetOption interface {
	// contains filtered or unexported methods
}

func WithAttribute

func WithAttribute(key, value string) GetOption

WithAttribute sets `attributes` in the `<get>` operation. For example juniper allows <get [format="(json | set | text | xml)"]> attributes in GetRequest.

func WithDefaultMode

func WithDefaultMode(op DefaultsMode) GetOption

WithDefaultMode sets the `with-defaults` in the `<get>` or `<get-config>` operation. This defines the behavior if default configs should be returned. See DefaultsMode for the available options.

func WithSubtreeFilter

func WithSubtreeFilter(subtree string) GetOption

WithSubtreeFilter sets the subtree `filter` to the `<get>` or `<get-config>` operation.

type GetRequest

type GetRequest struct {
	XMLName      xml.Name
	Attr         []xml.Attr   `xml:",attr,omitempty"`
	Source       *Datastore   `xml:"source,omitempty"`
	Filter       Filter       `xml:"filter,omitempty"`
	WithDefaults DefaultsMode `xml:"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults with-defaults,omitempty"`
}

func NewGetConfigRequest

func NewGetConfigRequest(source Datastore, opts ...GetOption) *GetRequest

func NewGetRequest

func NewGetRequest(opts ...GetOption) *GetRequest

type GetResponse

type GetResponse struct {
	Data []byte `xml:"data"`
}

type Hello

type Hello struct {
	XMLName      xml.Name
	SessionID    uint64   `xml:"session-id,omitempty"`
	Capabilities []string `xml:"capabilities>capability"`
}

type ISession

type ISession interface {
	SessionID() uint64
	ClientCapabilities() []string
	ServerCapabilities() []string
	HasCapability(string) bool
	Logger() Logger
	GetConfig(context.Context, Datastore, ...GetOption) (*RPCReply, error)
	Get(context.Context, ...GetOption) (*RPCReply, error)
	EditConfig(context.Context, Datastore, any, ...EditConfigOption) error
	DiscardChanges(context.Context) error
	CopyConfig(context.Context, any, any) error
	DeleteConfig(context.Context, Datastore) error
	Lock(context.Context, Datastore) error
	Unlock(context.Context, Datastore) error
	KillSession(context.Context, uint64) (*RPCReply, error)
	Close(context.Context) error
	Validate(context.Context, any) error
	Commit(context.Context, ...CommitOption) error
	CancelCommit(context.Context, ...CancelCommitOption) error
	Dispatch(context.Context, any) (*RPCReply, error)
	DispatchWithReply(context.Context, any, any) error
	CreateSubscription(context.Context, ...CreateSubscriptionOption) error
}

ISession is definition of the operations that this netconf client provides.

func NewSession

func NewSession(ctx context.Context, opts ...SessionOption) (ISession, error)

NewSession will create a new Session with the given transport and exchange hello messages. Context is used in handshake together with WithHelloTimeout option. WithTransport SessionOption is required to set the transport for the session.

type KillSessionRequest

type KillSessionRequest struct {
	XMLName   xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 kill-session"`
	SessionID uint64   `xml:"session-id"`
}

type LockRequest

type LockRequest struct {
	XMLName xml.Name
	Target  Datastore `xml:"target"`
}

func NewLockRequest

func NewLockRequest(target Datastore) *LockRequest

func NewUnlockRequest

func NewUnlockRequest(target Datastore) *LockRequest

type Logger

type Logger interface {
	Printf(string, ...any)
	Debugf(string, ...any)
	Infof(string, ...any)
	Warnf(string, ...any)
	Errorf(string, ...any)
}

type MergeStrategy

type MergeStrategy string

MergeStrategy defines the strategies for merging configuration in a `<edit-config> operation`.

*Note*: in RFC6241 7.2 this is called the `operation` attribute and `default-operation` parameter. Since the `operation` term is already overloaded this was changed to `MergeStrategy` for a cleaner API.

const (
	// MergeConfig configuration elements are merged together at the level at
	// which this specified.  Can be used for config elements as well as default
	// defined with [WithDefaultMergeStrategy] option.
	MergeConfig MergeStrategy = "merge"

	// ReplaceConfig defines that the incoming config change should replace the
	// existing config at the level which it is specified.  This can be
	// specified on individual config elements or set as the default strategy set
	// with [WithDefaultMergeStrategy] option.
	ReplaceConfig MergeStrategy = "replace"

	// NoMergeStrategy is only used as a default strategy defined in
	// [WithDefaultMergeStrategy].  Elements must specific one of the other
	// strategies with the `operation` Attribute on elements in the `<config>`
	// subtree.  Elements without the `operation` attribute are ignored.
	NoMergeStrategy MergeStrategy = "none"

	// CreateConfig allows a subtree element to be created only if it doesn't
	// already exist.
	// This strategy is only used as the `operation` attribute of
	// a `<config>` element and cannot be used as the default strategy.
	CreateConfig MergeStrategy = "create"

	// DeleteConfig will completely delete subtree from the config only if it
	// already exists.  This strategy is only used as the `operation` attribute
	// of a `<config>` element and cannot be used as the default strategy.
	DeleteConfig MergeStrategy = "delete"

	// RemoveConfig will remove subtree from the config.  If the subtree doesn't
	// exist in the datastore then it is silently skipped.  This strategy is
	// only used as the `operation` attribute of a `<config>` element and cannot
	// be used as the default strategy.
	RemoveConfig MergeStrategy = "remove"
)

type Notification

type Notification struct {
	XMLName   xml.Name
	EventTime time.Time `xml:"eventTime"`
	// contains filtered or unexported fields
}

func (Notification) Decode

func (r Notification) Decode(v any) error

func (Notification) Raw

func (r Notification) Raw() []byte

func (Notification) String

func (r Notification) String() string

type NotificationHandler

type NotificationHandler func(msg Notification)

NotificationHandler function allows to work with received notifications. A NotificationHandler function can be passed in as an option when calling NewSession method of Session object Typical use of the NotificationHandler function is to retrieve notifications once they are received so that they can be parsed and/or stored somewhere.

type PersistID

type PersistID string

func WithPersistID

func WithPersistID(id string) PersistID

WithPersistID is used to confirm a previous commit set with a given identifier. This allows you to confirm a commit from (potentially) another session.

type RPC

type RPC struct {
	XMLName   xml.Name   `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 rpc"`
	MessageID uint64     `xml:"message-id,attr"`
	Attrs     []xml.Attr `xml:"-"`
	Operation any        `xml:",innerxml"`
}

func (*RPC) MarshalXML

func (msg *RPC) MarshalXML(e *xml.Encoder, _ xml.StartElement) error

type RPCError

type RPCError struct {
	Type     ErrType     `xml:"error-type" json:"error-type"`
	Tag      ErrTag      `xml:"error-tag" json:"error-tag"`
	Severity ErrSeverity `xml:"error-severity" json:"error-severity"`
	AppTag   string      `xml:"error-app-tag,omitempty" json:"error-app-tag,omitempty"`
	Path     string      `xml:"error-path,omitempty" json:"error-path,omitempty"`
	Message  string      `xml:"error-message,omitempty" json:"error-message,omitempty"`
	Info     RawXML      `xml:"error-info,omitempty" json:"error-info,omitempty"`
}

func (RPCError) Error

func (e RPCError) Error() string

type RPCErrors

type RPCErrors []RPCError

func (RPCErrors) Error

func (errs RPCErrors) Error() string

func (RPCErrors) Filter

func (errs RPCErrors) Filter(severity ...ErrSeverity) RPCErrors

func (RPCErrors) Unwrap

func (errs RPCErrors) Unwrap() []error

type RPCReply

type RPCReply struct {
	XMLName   xml.Name
	MessageID uint64    `xml:"message-id,attr"`
	Errors    RPCErrors `xml:"rpc-error,omitempty"`
	// contains filtered or unexported fields
}

func (RPCReply) Decode

func (r RPCReply) Decode(v any) error

func (RPCReply) Err

func (r RPCReply) Err(severity ...ErrSeverity) error

func (RPCReply) Raw

func (r RPCReply) Raw() []byte

func (RPCReply) String

func (r RPCReply) String() string

type RawXML

type RawXML []byte

func (*RawXML) MarshalXML

func (x *RawXML) MarshalXML(e *xml.Encoder, start xml.StartElement) error

func (*RawXML) UnmarshalXML

func (x *RawXML) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents a netconf session to a one given device.

func (*Session) CancelCommit

func (s *Session) CancelCommit(ctx context.Context, opts ...CancelCommitOption) error

CancelCommit issues the `<cancel-commit/>` operation as defined in RFC6241 8.4.4.1.

This requires the device to support the ConfirmedCommitCapability capability

func (*Session) ClientCapabilities

func (s *Session) ClientCapabilities() []string

ClientCapabilities will return the capabilities initialized with the session.

func (*Session) Close

func (s *Session) Close(ctx context.Context) error

Close will gracefully close the sessions first by sending a `close-session` operation to the remote and then closing the underlying transport.

func (*Session) Commit

func (s *Session) Commit(ctx context.Context, opts ...CommitOption) error

Commit will commit a candidate config to the running config as defined in RFC6241 8.3.4.1. This requires the device to support the CandidateCapability capability.

func (*Session) CopyConfig

func (s *Session) CopyConfig(ctx context.Context, source, target any) error

CopyConfig issues the `<copy-config>` operation as defined in RFC6241 7.3 for copying an entire config to/from a source and target datastore.

A `<config>` element defining a full config can be used as the source.

If a device supports the URLCapability capability than a URL object can be used for the source or target datastore.

func (*Session) CreateSubscription

func (s *Session) CreateSubscription(ctx context.Context, opts ...CreateSubscriptionOption) error

CreateSubscription issues the `<create-subscription>` operation as defined in [RFC5277 2.1.1] for initiating an event notification subscription that will send asynchronous event notifications to the initiator.

This requires the device to support the NotificationCapability capability

[RFC5277 2.1.1] https://www.rfc-editor.org/rfc/rfc5277.html#section-2.1.1

func (*Session) DeleteConfig

func (s *Session) DeleteConfig(ctx context.Context, target Datastore) error

DeleteConfig issues the `<delete-config>` operation as defined in RFC6241 7.4 for deleting a configuration datastore.

func (*Session) DiscardChanges

func (s *Session) DiscardChanges(ctx context.Context) error

DiscardChanges issues the `<discard-changes>` operation as defined in RFC6241 8.3.4.2

func (*Session) Dispatch

func (s *Session) Dispatch(ctx context.Context, rpc any) (*RPCReply, error)

Dispatch issues custom `<rpc>` operation and returns RPCReply.

func (*Session) DispatchWithReply

func (s *Session) DispatchWithReply(ctx context.Context, rpc, resp any) error

DispatchWithReply issues custom `<rpc>` operation and decodes the response into a pointer at `resp`.

func (*Session) EditConfig

func (s *Session) EditConfig(ctx context.Context, target Datastore, config any, opts ...EditConfigOption) error

EditConfig issues the `<edit-config>` operation defined in RFC6241 7.2 for updating an existing target config datastore.

func (*Session) Get

func (s *Session) Get(ctx context.Context, opts ...GetOption) (*RPCReply, error)

Get issues the `<get>` operation as defined in [RFC6241 7.7] for retrieving running configuration and device state information.

Only the `subtree` filter type is supported.

[RFC6241 7.7] https://www.rfc-editor.org/rfc/rfc6241.html#section-7.7

func (*Session) GetConfig

func (s *Session) GetConfig(ctx context.Context, source Datastore, opts ...GetOption) (*RPCReply, error)

GetConfig implements the <get-config> rpc operation defined in RFC6241 7.1. `source` is the datastore to query.

func (*Session) HasCapability

func (s *Session) HasCapability(cap string) bool

HasCapability checks if server has a given capability.

func (*Session) KillSession

func (s *Session) KillSession(ctx context.Context, sessionID uint64) (*RPCReply, error)

KillSession issues the `<kill-session>` operation as defined in RFC6241 7.9 for force terminating the NETCONF session.

func (*Session) Lock

func (s *Session) Lock(ctx context.Context, target Datastore) error

Lock issues the `<lock>` operation as defined in RFC6241 7.5 for locking the entire configuration datastore.

func (*Session) Logger

func (s *Session) Logger() Logger

func (*Session) ServerCapabilities

func (s *Session) ServerCapabilities() []string

ServerCapabilities will return the capabilities returned by the server in its hello message.

func (*Session) SessionID

func (s *Session) SessionID() uint64

SessionID returns the current session ID exchanged in the hello messages. Will return 0 if there is no session ID.

func (*Session) Unlock

func (s *Session) Unlock(ctx context.Context, target Datastore) error

Unlock issues the `<unlock>` operation as defined in RFC6241 7.6 for releasing a configuration lock, previously obtained with the Session.Lock operation.

func (*Session) Validate

func (s *Session) Validate(ctx context.Context, source any) error

Validate issues the `<validate>` operation as defined in RFC6241 8.6.4.1 for validating the contents of the specified configuration. This requires the device to support the ValidateCapability capability

type SessionOption

type SessionOption interface {
	// contains filtered or unexported methods
}

func WithCapabilities

func WithCapabilities(capabilities ...string) SessionOption

WithCapabilities sets supported client capabilities for the session.

func WithErrorSeverity

func WithErrorSeverity(severity ...ErrSeverity) SessionOption

WithErrorSeverity sets the severity level for errors returned by the server. Defaults are SevWarning, SevError.

func WithHelloTimeout

func WithHelloTimeout(timeout time.Duration) SessionOption

WithHelloTimeout sets the timeout for hello messages. Default is 30 seconds.

func WithLogger

func WithLogger(logger Logger) SessionOption

WithLogger sets the logger for the session.

func WithNotificationHandler

func WithNotificationHandler(nh NotificationHandler) SessionOption

WithNotificationHandler sets the notification handler for the session.

func WithRPCAttr

func WithRPCAttr(name, value string) SessionOption

WithRPCAttr adds an extra XML attribute to every outgoing <rpc> element. This is typically used to declare vendor-specific namespace prefixes, e.g.:

WithRPCAttr("xmlns:nxos", "http://www.cisco.com/nxos:1.0")

func WithTransport

func WithTransport(transport transport.Transport) SessionOption

WithTransport sets the transport for the session.

type TestStrategy

type TestStrategy string

TestStrategy defines the behavior for testing configuration before applying it in a `<edit-config>` operation.

*Note*: in RFC6241 7.2 this is called the `test-option` parameter. Since the `option` term is already overloaded this was changed to `TestStrategy` for a cleaner API.

const (
	// TestThenSet will validate the configuration and only if is valid then
	// apply the configuration to the datastore.
	TestThenSet TestStrategy = "test-then-set"

	// SetOnly will not do any testing before applying it.
	SetOnly TestStrategy = "set"

	// TestOnly will validate the incoming configuration and return the
	// results without modifying the underlying store.
	TestOnly TestStrategy = "test-only"
)

type URL

type URL string

func (URL) MarshalXML

func (u URL) MarshalXML(e *xml.Encoder, start xml.StartElement) error

type ValidateRequest

type ValidateRequest struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 validate"`
	Source  any      `xml:"source"`
}

Directories

Path Synopsis
ssh
tls

Jump to

Keyboard shortcuts

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