goeapi

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2022 License: BSD-3-Clause Imports: 17 Imported by: 69

README

Arista Go eAPI Library Build Status codecov.io GoDoc

Table of Contents
  1. Overview
  2. Installation
  3. Upgrading
  4. Getting Started
  5. Building Local Documentation
  6. Testing
  7. Contributing
  8. License

Overview

The Go Client for eAPI provides a native Go implementation for programming Arista EOS network devices using Golang. The Go client provides the ability to build native applications in Go that can communicate with EOS remotely over a HTTP/S transport (off-box). It uses a standard INI-style configuration file to specifiy one or more connection profiles.

The goeapi implemenation also provides an API layer for building native Go objects that allow for configuration and state extraction of EOS nodes. The API layer provides a consistent implementation for working with EOS configuration resources. The implementation of the API layer is highly extensible and can be used as a foundation for building custom data models.

The libray is freely provided to the open source community for building robust applications using Arista EOS eAPI. Support is provided as best effort through Github iusses.

Requirements

  • Arista EOS v4.12 or later
  • Arista eAPI enabled for either http or https
  • Go 1.5+

Installation

First, it is assumed you have and are working in a standard Go workspace, as described in http://golang.org/doc/code.html, with proper GOPATH set. Go 1.5+ is what's recommended for using goeapi. To download and install goeapi:

$ go get github.com/aristanetworks/goeapi

After setting up Go and installing goeapi, any required build tools can be installed by bootstrapping your environment via:

$ make bootstrap

Upgrading

$ go get -u github.com/aristanetworks/goeapi

Getting Started

The following steps need to be followed to assure successful configuration of goeapi.

  1. EOS Command API must be enabled

    To enable EOS Command API from configuration mode, configure proper protocol under management api, and then verify:

        Switch# configure terminal
        Switch(config)# management api http-commands
        Switch(config-mgmt-api-http-cmds)# protocol ?
          http         Configure HTTP server options
          https        Configure HTTPS server options
          unix-socket  Configure Unix Domain Socket
        Switch(config-mgmt-api-http-cmds)# protocol http
        Switch(config-mgmt-api-http-cmds)# end
    
        Switch# show management api http-commands
        Enabled:            Yes
        HTTPS server:       running, set to use port 443
        HTTP server:        running, set to use port 80
        Local HTTP server:  shutdown, no authentication, set to use port 8080
        Unix Socket server: shutdown, no authentication
        ...
    

2. Create configuration file with proper node properties. (*See eapi.conf file examples below*)

    **Note:** The default search path for the conf file is ``~/.eapi.conf``
    followed by ``/mnt/flash/eapi.conf``.   This can be overridden by setting
    ``EAPI_CONF=<path file conf file>`` in your environment.

## Example eapi.conf File
Below is an example of an eAPI conf file.  The conf file can contain more than
one node.  Each node section must be prefaced by **connection:\<name\>** where
\<name\> is the name of the connection.

The following configuration options are available for defining node entries:

* **host** - The IP address or FQDN of the remote device.  If the host parameter is omitted then the connection name is used
* **username** - The eAPI username to use for authentication (only required for http or https connections)
* **password** - The eAPI password to use for authentication (only required for http or https connections)
* **enablepwd** - The enable mode password if required by the destination node
* **transport** - Configures the type of transport connection to use.  The default value is _https_.  Valid values are:
  * http
  * https
  * socket
* **port** - Configures the port to use for the eAPI connection. (Currently Not Implemented)

_Note:_ See the EOS User Manual found at arista.com for more details on configuring eAPI values.

# Using Goeapi
Once goeapi has been installed and your .eapi.config file is setup correctly, you are now ready to try it out. Here is a working example of .eapi.config file and go program:

```sh
$ cat ~/.eapi.config
[connection:arista1]
host=arista1
username=admin
password=root
enablepwd=passwd
transport=https
$ cat example1.go
package main

import (
        "fmt"

        "github.com/aristanetworks/goeapi"
        "github.com/aristanetworks/goeapi/module"
)

func main() {
        // connect to our device
        node, err := goeapi.ConnectTo("Arista1")
        if err != nil {
                panic(err)
        }
        // get the running config and print it
        conf := node.RunningConfig()
        fmt.Printf("Running Config:\n%s\n", conf)

        // get api system module
        sys := module.System(node)
        // change the host name to "Ladie"
        if ok := sys.SetHostname("Ladie"); !ok {
                fmt.Printf("SetHostname Failed\n")
        }
        // get system info
        sysInfo := sys.Get()
        fmt.Printf("\nSysinfo: %#v\n", sysInfo.HostName())
}

goeapi provides a way for users to directly couple a command with a predefined response. The underlying api will issue the command and the response stored in the defined type. For example, lets say the configured vlan ports are needed for some form of processing. If we know the JSON response for the command composed like the following: (from Arista Command API Explorer):

 {
    "jsonrpc": "2.0",
    "result": [
       {
          "sourceDetail": "",
          "vlans": {
             "2": {
                "status": "active",
                "name": "VLAN0002",
                "interfaces": {
                   "Port-Channel10": {
                      "privatePromoted": false
                   },
                   "Ethernet2": {
                      "privatePromoted": false
                   },
                   "Ethernet1": {
                      "privatePromoted": false
                   },
                   "Port-Channel5": {
                      "privatePromoted": false
                   }
                },
                "dynamic": false
             },
          }
       }
    ],
    "id": "CapiExplorer-123"
 }

We can then build our Go structures based on the response format and couple our show command with the type:

type MyShowVlan struct {
        SourceDetail string          `json:"sourceDetail"`
        Vlans        map[string]Vlan `json:"vlans"`
}

type Vlan struct {
        Status     string               `json:"status"`
        Name       string               `json:"name"`
        Interfaces map[string]Interface `json:"interfaces"`
        Dynamic    bool                 `json:"dynamic"`
}

type Interface struct {
        Annotation      string `json:"annotation"`
        PrivatePromoted bool   `json:"privatePromoted"`
}

func (s *MyShowVlan) GetCmd() string {
        return "show vlan configured-ports"
}

Since the command show vlan configured-ports is coupled with the response structure, the underlying api knows to issue the command and the response needs to be filled in. The resulting code looks like:

package main

import (
        "fmt"

        "github.com/aristanetworks/goeapi"
)

type MyShowVlan struct {
        SourceDetail string          `json:"sourceDetail"`
        Vlans        map[string]Vlan `json:"vlans"`
}

type Vlan struct {
        Status     string               `json:"status"`
        Name       string               `json:"name"`
        Interfaces map[string]Interface `json:"interfaces"`
        Dynamic    bool                 `json:"dynamic"`
}

type Interface struct {
        Annotation      string `json:"annotation"`
        PrivatePromoted bool   `json:"privatePromoted"`
}

func (s *MyShowVlan) GetCmd() string {
        return "show vlan configured-ports"
}

func main() {
        node, err := goeapi.ConnectTo("dut")
        if err != nil {
                panic(err)
        }

        sv := &MyShowVlan{}

        handle, _ := node.GetHandle("json")
        handle.AddCommand(sv)
        if err := handle.Call(); err != nil {
                panic(err)
        }

        for k, v := range sv.Vlans {
                fmt.Printf("Vlan:%s\n", k)
                fmt.Printf("  Name  : %s\n", v.Name)
                fmt.Printf("  Status: %s\n", v.Status)
        }
}

Also, if several commands/responses have been defined, goeapi supports command stacking to batch issue all at once:

    ...
	handle, _ := node.GetHandle("json")
	handle.AddCommand(showVersion)
	handle.AddCommand(showVlan)
	handle.AddCommand(showHostname)
	handle.AddCommand(showIp)
	if err := handle.Call(); err != nil {
		panic(err)
	}
	fmt.Printf("Version           : %s\n", showVersion.Version)
	fnt.Printf("Hostname          : %s\n", showHostname.Hostname)
    ...

There are several go example's using goeapi (as well as example .eapi.config file) provided in the examples directory.

Building Local Documentation

Documentation can be generated locally in plain text via:

$ godoc github.com/aristanetworks/goeapi

Or you can run the local godoc server and view the html version of the documentation by pointing your browser at http://localhost:6060

$ make doc
    or
$ godoc -http=:6060 -index

Testing

The goeapi library provides various tests. To run System specific tests, you will need to update the dut.conf file (found in testutils/fixtures) to include the device level specifics for your setup. The switch used for testing should have at least interfaces Ethernet1-7.

  • For running System tests, issue the following from the root of the goeapi directory:
$ make systest
    or
$ go test ./... -run SystemTest$
  • Similarly, Unit tests can be run via:
$ make unittest
    or
$ go test ./... -run UnitTest$

Verbose mode can be specified as a flag to provide additional information:

$ make GOTEST_FLAGS=-v test

Note: Test cases for XXX.go files live in respective XXX_test.go files and have the following function signature:

  • Unit Tests: TestXXX_UnitTest(t *testing.T){...
  • System Tests: TestXXX_SystemTest(t *testing.T){...

Any tests written must conform to this standard.

Contributing

Contributing pull requests are gladly welcomed for this repository. Please note that all contributions that modify the library behavior require corresponding test cases otherwise the pull request will be rejected.

License

Copyright (c) 2015-2016, Arista Networks Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of Arista Networks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Documentation

Overview

Package goeapi allows for creating connections to EOS eAPI enabled nodes using the Connect or ConnectTo function. Both functions will return an instance of a Node object that can be used to send and receive eAPI commands.

Index

Constants

View Source
const (
	RunningConfig = "running-config"
	StartupConfig = "startup-config"
)
View Source
const DefaultHTTPLocalPort = 8080

DefaultHTTPLocalPort uses 8080

View Source
const DefaultHTTPPort = 80

DefaultHTTPPort uses 80

View Source
const DefaultHTTPSPath = "/command-api"

DefaultHTTPSPath command path

View Source
const DefaultHTTPSPort = 443

DefaultHTTPSPort default port used by https

View Source
const UseDefaultPortNum = -1

UseDefaultPortNum recommends the underlying api to use default value for Port Number.

Variables

This section is empty.

Functions

func AddCommand

func AddCommand(handle *EapiReqHandle, v EapiCommand) error

AddCommand adds a pre-defined EapiCommand type to the command block list for this EapiReqHandle.

func AddCommandStr

func AddCommandStr(handle *EapiReqHandle, command string, v EapiCommand) error

AddCommandStr adds a command string with specified EapiCommand type to the command block list for this EapiReqHandle.

func Close

func Close(handle *EapiReqHandle) error

Close closes the relationship between the EapiReqHandle supplied and a Node. Any queued commands are deleted. User is responsible for proper handling of the handle after the close.

func ConfigFor

func ConfigFor(name string) ini.Section

ConfigFor function to get settings for named config

This function will return the settings for a specific connection as specified by name. Its a convenience function that calls get_connection on the global config instance

Args:

name (string): The name of the connection to return.  The connection
            name is specified as the string right of the : in the INI file

Returns:

An ini.Section object of key/value pairs that represent the
nodes configuration settings from the config instance

func Connections

func Connections() []string

Connections returns all of the loaded connections names as a list

func LoadConfig

func LoadConfig(filename string)

LoadConfig function method that loads a conf file

This function will load the file specified by filename into the config instance. Its a convenience function that calls load on the config instance

Args:

filename (string): The full path to the filename to load

Types

type EapiCommand

type EapiCommand interface {
	GetCmd() string
}

EapiCommand interface is implemented by any pre-defined response structure associated with a command issue toward a node.

type EapiConfig

type EapiConfig struct {
	ini.File
	// contains filtered or unexported fields
}

EapiConfig provides the instance for managing of eapi.conf file. We embed ini.File here to use properties of the ini.File type.

func NewEapiConfig

func NewEapiConfig() *EapiConfig

NewEapiConfig creates a new EapiConfig instance and initiates the autoload.

func NewEapiConfigFile

func NewEapiConfigFile(filename string) *EapiConfig

NewEapiConfigFile creates a new EapiConfig instance with the provided file name. After setting the filename, the method initiates the autoload for the config file.

Args:

filename (string): filename/path of the eapi.conf file.

func (*EapiConfig) AddConnection

func (e *EapiConfig) AddConnection(name string) ini.Section

AddConnection adds a connection to the configuration

This method will add a connection to the configuration. The connection added is only available for the lifetime of the object and is not persisted.

Note:

If a call is made to load() or reload(), any connections added
with this method must be re-added to the config instance

Args:

name (string): The name of the connection to add to the config.  The
            name provided will automatically be prepended with the string
            connection:

Returns:

bool: True if successful

func (*EapiConfig) AutoLoad

func (e *EapiConfig) AutoLoad()

AutoLoad loads the eapi.conf file

This method will use the module variable CONFIG_SEARCH_PATH to attempt to locate a valid eapi.conf file if a filename is not already configured. This method will load the first eapi.conf file it finds and then return.

The CONFIG_SEARCH_PATH can be overridden using an environment variable by setting EAPI_CONF.

func (*EapiConfig) Connections

func (e *EapiConfig) Connections() []string

Connections returns all of the loaded connections names as a list

func (*EapiConfig) GetConnection

func (e *EapiConfig) GetConnection(name string) ini.Section

GetConnection returns the properties for a connection name

This method will return the settings for the configuration specified by name. Note that the name argument should only be the name.

For instance, give the following eapi.conf file

.. code-block:: ini

[connection:veos01]
transport: http

Args:

name (string): The name of the connection to return

Returns:

ini.Section object of key/value pairs that represent
the node configuration.  If the name provided in the argument
is not found, then nil is returned.

func (*EapiConfig) Load

func (e *EapiConfig) Load(filename string) bool

Load loads the file specified by filename

This method works in conjunction with the autoload method to load the file specified by filename.

Args:

filename (string): The full path to the file to be loaded

Returns:

bool: True if successful

func (*EapiConfig) Read

func (e *EapiConfig) Read(filename string) error

Read reads the file specified by filename

This method will load the eapi.conf file specified by filename into the instance object. It will also add the default connection localhost if it was not defined in the eapi.conf file Args:

filename (string): The full path to the file to load

func (*EapiConfig) Reload

func (e *EapiConfig) Reload() bool

Reload reloades the configuration

This method will reload the configuration instance using the last known filename. Note this method will initially clear the configuration and reload all entries.

Returns:

bool: True if successful

type EapiConnection

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

EapiConnection represents the base object for implementing an EapiConnection type. This clase should not be instantiated directly

func (*EapiConnection) Authentication

func (conn *EapiConnection) Authentication(username string, passwd string)

Authentication Configures the user authentication for eAPI. This method configures the username and password combination to use for authenticating to eAPI.

Args:

username (string): The username to use to authenticate the eAPI
                    connection with
password (string): The password in clear text to use to authenticate
                    the eAPI connection with

func (*EapiConnection) ClearError

func (conn *EapiConnection) ClearError()

ClearError clears any error for Connection

func (*EapiConnection) Error

func (conn *EapiConnection) Error() error

Error returns the current error for Connection

func (*EapiConnection) Execute

func (conn *EapiConnection) Execute(commands []interface{},
	encoding string) (*JSONRPCResponse, error)

Execute the list of commands on the destination node. In the case of EapiConnection, this serves as a base model and is not fully implemented.

Args:

commands ([]interface): list of commands to execute on remote node
encoding (string): The encoding to send along with the request
                    message to the destination node.  Valid values include
                    'json' or 'text'.  This argument will influence the
                    response encoding

Returns:

pointer to JSONRPCResponse or error on failure

func (*EapiConnection) SetDisableKeepAlive added in v0.6.0

func (conn *EapiConnection) SetDisableKeepAlive(disableKeepAlive bool)

SetDisableKeepAlive sets disablekeepalive value for Connection

func (*EapiConnection) SetError

func (conn *EapiConnection) SetError(e error)

SetError sets error for Connection

func (*EapiConnection) SetTimeout added in v0.2.0

func (conn *EapiConnection) SetTimeout(timeOut uint32)

SetTimeout sets timeout value for Connection

type EapiConnectionEntity

type EapiConnectionEntity interface {
	Execute(commands []interface{}, encoding string) (*JSONRPCResponse, error)
	SetTimeout(to uint32)
	SetDisableKeepAlive(disableKeepAlive bool)
	Error() error
}

EapiConnectionEntity is an interface representing the ability to execute a single json transaction, obtaining the Response for a given Request.

func Connection added in v0.3.0

func Connection(transport string, host string, username string, passwd string,
	port int) (EapiConnectionEntity, error)

Connection creates a connection using the supplied settings

This function will create a connection to an Arista EOS node using the arguments. All arguments are optional with default values.

Args:

transport (string): Specifies the type of connection transport to use.
                 Valid values for the connection are socket, http_local,
                 http, and https.  https is the default.
host (string): The IP addres or DNS host name of the connection device.
            The default value is 'localhost'
username (string): The username to pass to the device to authenticate
                the eAPI connection.   The default value is 'admin'
password (string): The password to pass to the device to authenticate
                the eAPI connection.  The default value is ''
port (int): The TCP port of the endpoint for the eAPI connection.  If
            this keyword is not specified, the default value is
            automatically determined by the transport type.
            (http=80, https=443)

Returns:

An instance of EapiConnectionEntity object for the specified transport.

func NewHTTPEapiConnection

func NewHTTPEapiConnection(transport string, host string, username string,
	password string, port int) EapiConnectionEntity

NewHTTPEapiConnection initializes a HttpEapiConnection.

Args:

transport (string): The transport to use to create the instance.
host (string): The IP addres or DNS host name of the connection device.
username(string): The username to pass to the device to authenticate
                  the eAPI connection.
password(string): The password to pass to the device to authenticate
                  the eAPI connection. The default value is ''
port(int): The TCP port of the endpoint for the eAPI connection.

Returns:

Newly created HTTPEapiConnection

func NewHTTPLocalEapiConnection

func NewHTTPLocalEapiConnection(transport string, host string, username string,
	password string, port int) EapiConnectionEntity

NewHTTPLocalEapiConnection initializes a HTTPLocalEapiConnection.

Args:

transport (string): The transport to use to create the instance.
host (string): The IP addres or DNS host name of the connection device.
username(string): The username to pass to the device to authenticate
                  the eAPI connection.
password(string): The password to pass to the device to authenticate
                  the eAPI connection. The default value is ''
port(int): The TCP port of the endpoint for the eAPI connection.

Returns:

Newly created SocketEapiConnection

func NewHTTPSEapiConnection

func NewHTTPSEapiConnection(transport string, host string, username string,
	password string, port int) EapiConnectionEntity

NewHTTPSEapiConnection initializes an HttpsEapiConnection.

Args:

transport (string): The transport to use to create the instance.
host (string): The IP addres or DNS host name of the connection device.
username(string): The username to pass to the device to authenticate
                  the eAPI connection.
password(string): The password to pass to the device to authenticate
                  the eAPI connection. The default value is ''
port(int): The TCP port of the endpoint for the eAPI connection.

Returns:

Newly created HTTPSEapiConnection

func NewSocketEapiConnection

func NewSocketEapiConnection(transport string, host string, username string,
	password string, port int) EapiConnectionEntity

NewSocketEapiConnection initializes a SocketEapiConnection.

Args:

transport (string): The transport to use to create the instance.
host (string): The IP addres or DNS host name of the connection device.
username(string): The username to pass to the device to authenticate
                  the eAPI connection.
password(string): The password to pass to the device to authenticate
                  the eAPI connection. The default value is ''
port(int): The TCP port of the endpoint for the eAPI connection.

Returns:

Newly created SocketEapiConnection

type EapiReqHandle

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

EapiReqHandle ...

func GetHandle

func GetHandle(n *Node, encoding string) (*EapiReqHandle, error)

GetHandle returns the EapiReqHandle for the connection.

Args:

n (*Node): Node for which we are aquiring an EapiReqHandle
encoding (string): Encoding to be used

Returns:

Pointer to an EapiReqHandle or error on failure

func (*EapiReqHandle) AddCommand

func (handle *EapiReqHandle) AddCommand(v EapiCommand) error

AddCommand adds a pre-defined EapiCommand type to the command block list for this EapiReqHandle.

func (*EapiReqHandle) AddCommandStr

func (handle *EapiReqHandle) AddCommandStr(command string, v EapiCommand) error

AddCommandStr adds a command string with specified EapiCommand type to the command block list for this EapiReqHandle.

func (*EapiReqHandle) Call

func (handle *EapiReqHandle) Call() error

Call executes the commands previously added to the command block using AddCommand().

Responses from issued commands are stored in the EapiCommand associated with that commands response.

Returns:

error if handle is invalid, or problem encountered during sending or
receiveing.

func (*EapiReqHandle) Close

func (handle *EapiReqHandle) Close() error

Close closes the relationship between this EapiReqHandle and a Node. Any queued commands are deleted. User is responsible for proper handling of the handle after the close.

func (*EapiReqHandle) Enable

func (handle *EapiReqHandle) Enable(v EapiCommand) error

Enable takes an EapiCommand type to issue toward the Node. Decoded results are stored in the EapiCommand. Returns:

error on failure

type HTTPEapiConnection

type HTTPEapiConnection struct {
	EapiConnection
}

HTTPEapiConnection is an EapiConnection suited for HTTP connection

func (*HTTPEapiConnection) Execute

func (conn *HTTPEapiConnection) Execute(commands []interface{},
	encoding string) (*JSONRPCResponse, error)

Execute the list of commands on the destination node

This method takes a list of commands and sends them to the destination node, returning the results. It is assumed that the list of commands (type []interface{}) has been properly built and enable mode passwd is set if needed. On success, a reference to JSONRPCResponse is returned...otherwise err is set.

Args:

commands ([]interface): list of commands to execute on remote node
encoding (string): The encoding to send along with the request
                    message to the destination node.  Valid values include
                    'json' or 'text'.  This argument will influence the
                    response encoding

Returns:

pointer to JSONRPCResponse or error on failure

type HTTPLocalEapiConnection

type HTTPLocalEapiConnection struct {
	EapiConnection
}

HTTPLocalEapiConnection is an EapiConnection suited for local HTTP connection

func (*HTTPLocalEapiConnection) Execute

func (conn *HTTPLocalEapiConnection) Execute(commands []interface{},
	encoding string) (*JSONRPCResponse, error)

Execute the list of commands

This method takes a list of commands and sends them to the destination node, returning the results. It is assumed that the list of commands (type []interface{}) has been properly built and enable mode passwd is set if needed. On success, a reference to JSONRPCResponse is returned...otherwise err is set.

Args:

commands ([]interface): list of commands to execute on remote node
encoding (string): The encoding to send along with the request
                    message to the destination node.  Valid values include
                    'json' or 'text'.  This argument will influence the
                    response encoding

Returns:

pointer to JSONRPCResponse or error on failure

type HTTPSEapiConnection

type HTTPSEapiConnection struct {
	EapiConnection
	// contains filtered or unexported fields
}

HTTPSEapiConnection is an EapiConnection suited for HTTP connection

func (*HTTPSEapiConnection) Execute

func (conn *HTTPSEapiConnection) Execute(commands []interface{},
	encoding string) (*JSONRPCResponse, error)

Execute the list of commands on the destination node

This method takes a list of commands and sends them to the destination node, returning the results. It is assumed that the list of commands (type []interface{}) has been properly built and enable mode passwd is set if needed. On success, a reference to JSONRPCResponse is returned...otherwise err is set.

Args:

commands ([]interface): list of commands to execute on remote node
encoding (string): The encoding to send along with the request
                    message to the destination node.  Valid values include
                    'json' or 'text'.  This argument will influence the
                    response encoding

Returns:

pointer to JSONRPCResponse or error on failure

type JSONRPCResponse

type JSONRPCResponse struct {
	Jsonrpc string                   `json:"jsonrpc"`
	Result  []map[string]interface{} `json:"result"`
	ID      string                   `json:"id"`
	Error   *RespError               `json:"error"`
}

JSONRPCResponse ...

type Node

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

A Node represents a single device for sending and receiving eAPI messages

Node provides an instance for communicating with Arista EOS devices. The Node object provides easy to use methods for sending both enable and config commands to the device using a specific transport. This object forms the base for communicating with devices.

func Connect

func Connect(transport string, host string, username string, passwd string,
	port int) (*Node, error)

Connect establishes a connection (using the supplied settings) and creates a Node instance.

This function will create a connection to an Arista EOS node using the arguments. All arguments are optional with default values.

Args:

transport (string): Specifies the type of connection transport to use.
                 Valid values for the connection are socket, http_local,
                 http, and https.  https is the default.
host (string): The IP addres or DNS host name of the connection device.
            The default value is 'localhost'
username (string): The username to pass to the device to authenticate
                the eAPI connection.   The default value is 'admin'
password (string): The password to pass to the device to authenticate
                the eAPI connection.  The default value is ''
port (int): The TCP port of the endpoint for the eAPI connection.  If
            this keyword is not specified, the default value is
            automatically determined by the transport type.
            (http=80, https=443)

Returns:

An instance of Node object for the specified transport.

func ConnectTo

func ConnectTo(name string) (*Node, error)

ConnectTo Creates a Node instance based on an entry from the config

This function will retrieve the settings for the specified connection from the config and return a Node instance. The configuration must be loaded prior to calling this function.

Args:

name (string): The name of the connection to load from the config.  The
            name argument should be the connection name (everything
            right of the colon from the INI file)

Returns:

This function will return an instance of Node with the settings
from the config instance.

func (*Node) Config

func (n *Node) Config(commands ...string) bool

Config the node with the specified commands

This method is used to send configuration commands to the node. It will takes a list of strings and prepend the necessary commands to put the session into config mode.

func (*Node) ConfigWithErr added in v0.4.0

func (n *Node) ConfigWithErr(commands ...string) error

ConfigWithErr the node with the specified commands

This method is used to send configuration commands to the node. It will takes a list of strings and prepend the necessary commands to put the session into config mode. Returns error if issues arise.

func (*Node) Enable

func (n *Node) Enable(commands []string) ([]map[string]string, error)

Enable issues an array of commands to the node in enable mode

This method will send the commands to the node and evaluate the results. (TODO) If a command fails due to an encoding error, then the command set will be re-issued individual with text encoding.

Args:

commands (string array): The list of commands to send to the node

Returns:

An array of map'd interfaces that includes the response for each
command along with the encoding. Error is returned on failure.

func (*Node) EnableAuthentication

func (n *Node) EnableAuthentication(passwd string)

EnableAuthentication configures the enable mode authentication password present in passwd

Args:

passwd (string): The password string in clear text used to
                 authenticate to exec mode

func (*Node) GetConfig

func (n *Node) GetConfig(config, params, encoding string) (map[string]interface{}, error)

GetConfig retrieves the config from the node.

The config to retrieve can be specified as either the startup-config or the running-config. An error is returned on invalid parameter or if the underlying transmit failed.

Args:

config (string): Specifies to return either the nodes startup-config
              or running-config.  The default value is the running-config
params (string): A string of keywords to append to the command for
              retrieving the config.
encoding (string): Encoding to be used

Returns:

Will return the config requested or error if failure

func (*Node) GetConnection

func (n *Node) GetConnection() EapiConnectionEntity

GetConnection returns the EapiConnectionEntity associtated with this Node.

Returns:

EapiConnectionEntity

func (*Node) GetHandle

func (n *Node) GetHandle(encoding string) (*EapiReqHandle, error)

GetHandle returns the EapiReqHandle for the connection.

Args:

encoding (string): Encoding to be used

Returns:

Pointer to an EapiReqHandle or error on failure

func (*Node) GetSection

func (n *Node) GetSection(regex string, config string) (string, error)

GetSection retrieves the config section from the Node

Args:

regex (string):
config (string):

Returns:

String value of the config section requested.
Error returned on failure.

func (*Node) Refresh

func (n *Node) Refresh()

Refresh refreshes the config properties.

This method will refresh the runningConfig and startupConfig properites. Since the properties are lazily loaded, this method will clear the current internal instance variables. On the next call the instance variables will be repopulated with the current config

func (*Node) RunCommands added in v0.5.0

func (n *Node) RunCommands(commands []string,
	encoding string) (*JSONRPCResponse, error)

RunCommands sends the commands over the transport to the device

This method sends the commands to the device using the nodes transport. This is a lower layer function that shouldn't normally need to be used, prefering instead to use config() or enable().

Args:

commands (array): The ordered list of commands to send to the
                 device using the transport
encoding (string): The encoding method to use for the request and
                excpected response. ('json' or 'text')

Returns:

This method will return the raw response from the connection
which is a JSONRPCResponse object or error on failure.

func (*Node) RunningConfig

func (n *Node) RunningConfig() string

RunningConfig returns the running configuration for the Arista EOS device. A copy is cached locally if one does not already exist.

Returns:

String format of the running config

func (*Node) SetAutoRefresh

func (n *Node) SetAutoRefresh(val bool)

SetAutoRefresh sets the current nodes auto refresh attribute to either true or false.

Args:

val (bool): If True, the running-config and startup-config are
            refreshed on config events.  If False, then the config
            properties must be manually refreshed.

func (*Node) SetConnection

func (n *Node) SetConnection(c EapiConnectionEntity)

SetConnection sets the EapiConnectionEntity associtated with this Node.

func (*Node) StartupConfig

func (n *Node) StartupConfig() string

StartupConfig returns the startup configuration for the Arista EOS device. A copy is cached locally if one does not already exist.

Returns:

String format of the startup config

func (*Node) Version added in v1.0.0

func (n *Node) Version() string

Version returns the EOS version for this node

type Parameters

type Parameters struct {
	Version int           `json:"version"`
	Cmds    []interface{} `json:"cmds"`
	Format  string        `json:"format"`
}

Parameters ...

type RawJSONRPCResponse

type RawJSONRPCResponse struct {
	Jsonrpc string                 `json:"jsonrpc"`
	Result  []json.RawMessage      `json:"result"`
	Error   map[string]interface{} `json:"error"`
	ID      string                 `json:"id"`
}

RawJSONRPCResponse ...

type Request

type Request struct {
	Jsonrpc string     `json:"jsonrpc"`
	Method  string     `json:"method"`
	Params  Parameters `json:"params"`
	ID      string     `json:"id"`
}

Request ...

type RespError

type RespError struct {
	Code    int
	Message string
	Data    interface{}
}

RespError message format breakout

type SocketEapiConnection

type SocketEapiConnection struct {
	EapiConnection
}

SocketEapiConnection represents the EapiConnection for handling Socket level transactions

func (*SocketEapiConnection) Execute

func (conn *SocketEapiConnection) Execute(commands []interface{},
	encoding string) (*JSONRPCResponse, error)

Execute the list of commands on the destination node

This method takes a list of commands and sends them to the destination node, returning the results. It is assumed that the list of commands (type []interface{}) has been properly built and enable mode passwd is set if needed. On success, a reference to JSONRPCResponse is returned...otherwise err is set.

Args:

commands ([]interface): list of commands to execute on remote node
encoding (string): The encoding to send along with the request
                    message to the destination node.  Valid values include
                    'json' or 'text'.  This argument will influence the
                    response encoding

Returns:

pointer to JSONRPCResponse or error on failure

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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