core

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2022 License: Apache-2.0 Imports: 15 Imported by: 62

Documentation

Overview

Package core provides connectivity to VPP via the adapter: sends and receives the messages to/from VPP, marshalls/unmarshalls them and forwards them between the client Go channels and the VPP.

The interface_plugin APIs the core exposes is tied to a connection: Connect provides a connection, that cane be later used to request an API channel via NewAPIChannel / NewAPIChannelBuffered functions:

conn, err := govpp.Connect()
if err != nil {
	// handle error!
}
defer conn.Disconnect()

ch, err := conn.NewAPIChannel()
if err != nil {
	// handle error!
}
defer ch.Close()

Note that one application can open only one connection, that can serve multiple API channels.

The API offers two ways of communication with govpp core: using Go channels, or using convenient function wrappers over the Go channels. The latter should be sufficient for most of the use cases.

The entry point to the API is the Channel structure, that can be obtained from the existing connection using the NewAPIChannel or NewAPIChannelBuffered functions:

conn, err := govpp.Connect()
if err != nil {
	// handle error!
}
defer conn.Disconnect()

ch, err := conn.NewAPIChannel()
if err != nil {
	// handle error!
}
defer ch.Close()

Simple Request-Reply API

The simple version of the API is based on blocking SendRequest / ReceiveReply calls, where a single request message is sent to VPP and a single reply message is filled in when the reply comes from VPP:

req := &acl.ACLPluginGetVersion{}
reply := &acl.ACLPluginGetVersionReply{}

err := ch.SendRequest(req).ReceiveReply(reply)
// process the reply

Note that if the reply message type that comes from VPP does not match with provided one, you'll get an error.

Multipart Reply API

If multiple messages are expected as a reply to a request, SendMultiRequest API must be used:

req := &interfaces.SwInterfaceDump{}
reqCtx := ch.SendMultiRequest(req)

for {
	reply := &interfaces.SwInterfaceDetails{}
	stop, err := reqCtx.ReceiveReply(reply)
	if stop {
		break // break out of the loop
	}
	// process the reply
}

Note that if the last reply has been already consumed, stop boolean return value is set to true. Do not use the message itself if stop is true - it won't be filled with actual data.

Go Channels API

The blocking API introduced above may be not sufficient for some management applications that strongly rely on usage of Go channels. In this case, the API allows to access the underlying Go channels directly, e.g. the following replacement of the SendRequest / ReceiveReply API:

req := &acl.ACLPluginGetVersion{}
// send the request to the request go channel
ch.GetRequestChannel <- &api.VppRequest{Message: req}

// receive a reply from the reply go channel
vppReply := <-ch.GetReplyChannel

// decode the message
reply := &acl.ACLPluginGetVersionReply{}
err := ch.MsgDecoder.DecodeMsg(vppReply.Data, reply)

// process the reply

Notifications API

to subscribe for receiving of the specified notification messages via provided Go channel, use the SubscribeNotification API:

// subscribe for specific notification message
notifChan := make(chan api.Message, 100)
subs, _ := ch.SubscribeNotification(notifChan, interfaces.NewSwInterfaceSetFlags)

// receive one notification
notif := (<-notifChan).(*interfaces.SwInterfaceSetFlags)

ch.UnsubscribeNotification(subs)

Note that the caller is responsible for creating the Go channel with preferred buffer size. If the channel's buffer is full, the notifications will not be delivered into it.

Index

Constants

View Source
const (
	DefaultReconnectInterval    = time.Second / 2 // default interval between reconnect attempts
	DefaultMaxReconnectAttempts = 3               // default maximum number of reconnect attempts
)
View Source
const (
	SystemStatsPrefix               = "/sys/"
	SystemStats_VectorRate          = SystemStatsPrefix + "vector_rate"
	SystemStats_NumWorkerThreads    = SystemStatsPrefix + "num_worker_threads"
	SystemStats_VectorRatePerWorker = SystemStatsPrefix + "vector_rate_per_worker"
	SystemStats_InputRate           = SystemStatsPrefix + "input_rate"
	SystemStats_LastUpdate          = SystemStatsPrefix + "last_update"
	SystemStats_LastStatsClear      = SystemStatsPrefix + "last_stats_clear"
	SystemStats_Heartbeat           = SystemStatsPrefix + "heartbeat"

	NodeStatsPrefix    = "/sys/node/"
	NodeStats_Names    = NodeStatsPrefix + "names"
	NodeStats_Clocks   = NodeStatsPrefix + "clocks"
	NodeStats_Vectors  = NodeStatsPrefix + "vectors"
	NodeStats_Calls    = NodeStatsPrefix + "calls"
	NodeStats_Suspends = NodeStatsPrefix + "suspends"

	BufferStatsPrefix     = "/buffer-pools/"
	BufferStats_Cached    = "cached"
	BufferStats_Used      = "used"
	BufferStats_Available = "available"

	CounterStatsPrefix = "/err/"

	MemoryStatSegPrefix = "/mem/statseg"
	MemoryStatSegment   = "/mem/stat segment"
	MemoryMainHeap      = "/mem/main heap"
	MemoryStats_Total   = "total"
	MemoryStats_Used    = "used"

	InterfaceStatsPrefix         = "/if/"
	InterfaceStats_Names         = InterfaceStatsPrefix + "names"
	InterfaceStats_Drops         = InterfaceStatsPrefix + "drops"
	InterfaceStats_Punt          = InterfaceStatsPrefix + "punt"
	InterfaceStats_IP4           = InterfaceStatsPrefix + "ip4"
	InterfaceStats_IP6           = InterfaceStatsPrefix + "ip6"
	InterfaceStats_RxNoBuf       = InterfaceStatsPrefix + "rx-no-buf"
	InterfaceStats_RxMiss        = InterfaceStatsPrefix + "rx-miss"
	InterfaceStats_RxError       = InterfaceStatsPrefix + "rx-error"
	InterfaceStats_TxError       = InterfaceStatsPrefix + "tx-error"
	InterfaceStats_Mpls          = InterfaceStatsPrefix + "mpls"
	InterfaceStats_Rx            = InterfaceStatsPrefix + "rx"
	InterfaceStats_RxUnicast     = InterfaceStatsPrefix + "rx-unicast"
	InterfaceStats_RxMulticast   = InterfaceStatsPrefix + "rx-multicast"
	InterfaceStats_RxBroadcast   = InterfaceStatsPrefix + "rx-broadcast"
	InterfaceStats_Tx            = InterfaceStatsPrefix + "tx"
	InterfaceStats_TxUnicast     = InterfaceStatsPrefix + "tx-unicast"
	InterfaceStats_TxUnicastMiss = InterfaceStatsPrefix + "tx-unicast-miss"
	InterfaceStats_TxMulticast   = InterfaceStatsPrefix + "tx-multicast"
	InterfaceStats_TxBroadcast   = InterfaceStatsPrefix + "tx-broadcast"

	// TODO: network stats
	NetworkStatsPrefix     = "/net/"
	NetworkStats_RouteTo   = NetworkStatsPrefix + "route/to"
	NetworkStats_RouteVia  = NetworkStatsPrefix + "route/via"
	NetworkStats_MRoute    = NetworkStatsPrefix + "mroute"
	NetworkStats_Adjacency = NetworkStatsPrefix + "adjacency"
	NetworkStats_Punt      = NetworkStatsPrefix + "punt"
)

Variables

View Source
var (
	RequestChanBufSize      = 100 // default size of the request channel buffer
	ReplyChanBufSize        = 100 // default size of the reply channel buffer
	NotificationChanBufSize = 100 // default size of the notification channel buffer
)
View Source
var (
	HealthCheckProbeInterval = time.Second            // default health check probe interval
	HealthCheckReplyTimeout  = time.Millisecond * 250 // timeout for reply to a health check probe
	HealthCheckThreshold     = 2                      // number of failed health checks until the error is reported
	DefaultReplyTimeout      = time.Second            // default timeout for replies from VPP
)
View Source
var (
	ErrNotConnected = errors.New("not connected to VPP, ignoring the request")
	ErrProbeTimeout = errors.New("probe reply not received within timeout period")
)
View Source
var (
	RetryUpdateCount    = 10
	RetryUpdateDelay    = time.Millisecond * 10
	HealthCheckInterval = time.Second // default health check probe interval
)
View Source
var (
	ErrInvalidRequestCtx = errors.New("invalid request context")
)
View Source
var ReplyChannelTimeout = time.Millisecond * 100

Functions

func SetControlPing

func SetControlPing(m api.Message)

SetControlPing sets the control ping message used by core.

func SetControlPingReply

func SetControlPingReply(m api.Message)

SetControlPingReply sets the control ping reply message used by core.

func SetLogLevel

func SetLogLevel(lvl logrus.Level)

SetLogLevel sets global logger level to lvl.

func SetLogger

func SetLogger(l *logrus.Logger)

SetLogger sets global logger to l.

func WithReplySize added in v0.4.0

func WithReplySize(size int) api.StreamOption

func WithReplyTimeout added in v0.4.0

func WithReplyTimeout(timeout time.Duration) api.StreamOption

func WithRequestSize added in v0.4.0

func WithRequestSize(size int) api.StreamOption

Types

type Channel

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

Channel is the main communication interface with govpp core. It contains four Go channels, one for sending the requests to VPP, one for receiving the replies from it and the same set for notifications. The user can access the Go channels via methods provided by Channel interface in this package. Do not use the same channel from multiple goroutines concurrently, otherwise the responses could mix! Use multiple channels instead.

func (*Channel) CheckCompatiblity

func (ch *Channel) CheckCompatiblity(msgs ...api.Message) error

func (*Channel) Close

func (ch *Channel) Close()

func (*Channel) GetID

func (ch *Channel) GetID() uint16

func (*Channel) SendMultiRequest

func (ch *Channel) SendMultiRequest(msg api.Message) api.MultiRequestCtx

func (*Channel) SendRequest

func (ch *Channel) SendRequest(msg api.Message) api.RequestCtx

func (*Channel) SetReplyTimeout

func (ch *Channel) SetReplyTimeout(timeout time.Duration)

func (*Channel) SubscribeNotification

func (ch *Channel) SubscribeNotification(notifChan chan api.Message, event api.Message) (api.SubscriptionCtx, error)

type Connection

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

Connection represents a shared memory connection to VPP via vppAdapter.

func AsyncConnect

func AsyncConnect(binapi adapter.VppAPI, attempts int, interval time.Duration) (*Connection, chan ConnectionEvent, error)

AsyncConnect asynchronously connects to VPP using specified VPP adapter and returns the connection handle and ConnectionState channel. This call does not block until connection is established, it returns immediately. The caller is supposed to watch the returned ConnectionState channel for Connected/Disconnected events. In case of disconnect, the library will asynchronously try to reconnect.

func Connect

func Connect(binapi adapter.VppAPI) (*Connection, error)

Connect connects to VPP API using specified adapter and returns a connection handle. This call blocks until it is either connected, or an error occurs. Only one connection attempt will be performed.

func (*Connection) Disconnect

func (c *Connection) Disconnect()

Disconnect disconnects from VPP API and releases all connection-related resources.

func (*Connection) GetMessageID

func (c *Connection) GetMessageID(msg api.Message) (uint16, error)

GetMessageID returns message identifier of given API message.

func (*Connection) GetMessagePath added in v0.4.0

func (c *Connection) GetMessagePath(msg api.Message) string

GetMessagePath returns path for the given message

func (*Connection) Invoke added in v0.4.0

func (c *Connection) Invoke(ctx context.Context, req api.Message, reply api.Message) error

func (*Connection) LookupByID

func (c *Connection) LookupByID(path string, msgID uint16) (api.Message, error)

LookupByID looks up message name and crc by ID.

func (*Connection) NewAPIChannel

func (c *Connection) NewAPIChannel() (api.Channel, error)

func (*Connection) NewAPIChannelBuffered

func (c *Connection) NewAPIChannelBuffered(reqChanBufSize, replyChanBufSize int) (api.Channel, error)

func (*Connection) NewStream added in v0.4.0

func (c *Connection) NewStream(ctx context.Context, options ...api.StreamOption) (api.Stream, error)

func (*Connection) Trace added in v0.4.0

func (c *Connection) Trace() api.Trace

Trace gives access to the API trace interface

type ConnectionEvent

type ConnectionEvent struct {
	// Timestamp holds the time when the event has been created.
	Timestamp time.Time

	// State holds the new state of the connection at the time when the event has been created.
	State ConnectionState

	// Error holds error if any encountered.
	Error error
}

ConnectionEvent is a notification about change in the VPP connection state.

type ConnectionState

type ConnectionState int

ConnectionState represents the current state of the connection to VPP.

const (
	// Connected represents state in which the connection has been successfully established.
	Connected ConnectionState = iota

	// NotResponding represents a state where the VPP socket accepts messages but replies are received with delay,
	// or not at all. GoVPP treats this state internally the same as disconnected.
	NotResponding

	// Disconnected represents state in which the VPP socket is closed and the connection is considered dropped.
	Disconnected

	// Failed represents state in which the reconnecting failed after exceeding maximum number of attempts.
	Failed
)

func (ConnectionState) String

func (s ConnectionState) String() string

type ControlPing

type ControlPing struct{}

func (*ControlPing) GetCrcString

func (*ControlPing) GetCrcString() string

func (*ControlPing) GetMessageName

func (*ControlPing) GetMessageName() string

func (*ControlPing) GetMessageType

func (*ControlPing) GetMessageType() api.MessageType

type ControlPingReply

type ControlPingReply struct {
	Retval      int32
	ClientIndex uint32
	VpePID      uint32
}

func (*ControlPingReply) GetCrcString

func (*ControlPingReply) GetCrcString() string

func (*ControlPingReply) GetMessageName

func (*ControlPingReply) GetMessageName() string

func (*ControlPingReply) GetMessageType

func (*ControlPingReply) GetMessageType() api.MessageType

type MessageCodec

type MessageCodec interface {
	// EncodeMsg encodes message into binary data.
	EncodeMsg(msg api.Message, msgID uint16) ([]byte, error)
	// DecodeMsg decodes binary-encoded data of a message into provided Message structure.
	DecodeMsg(data []byte, msg api.Message) error
	// DecodeMsgContext decodes context from message data and type.
	DecodeMsgContext(data []byte, msgType api.MessageType) (context uint32, err error)
}

MessageCodec provides functionality for decoding binary data to generated API messages.

type MessageIdentifier

type MessageIdentifier interface {
	// GetMessageID returns message identifier of given API message.
	GetMessageID(msg api.Message) (uint16, error)
	// GetMessagePath returns path for the given message
	GetMessagePath(msg api.Message) string
	// LookupByID looks up message name and crc by ID
	LookupByID(path string, msgID uint16) (api.Message, error)
}

MessageIdentifier provides identification of generated API messages.

type StatsConnection

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

func AsyncConnectStats added in v0.4.0

func AsyncConnectStats(stats adapter.StatsAPI, attempts int, interval time.Duration) (*StatsConnection, chan ConnectionEvent, error)

AsyncConnectStats connects to the VPP stats socket asynchronously and returns the connection handle with state channel. The call is non-blocking and the caller is expected to watch ConnectionEvent values from the channel and wait for connect/disconnect events. Connection loop tries to reconnect the socket in case the session was disconnected.

func ConnectStats

func ConnectStats(stats adapter.StatsAPI) (*StatsConnection, error)

ConnectStats connects to Stats API using specified adapter and returns a connection handle. This call blocks until it is either connected, or an error occurs. Only one connection attempt will be performed.

func (*StatsConnection) Disconnect

func (c *StatsConnection) Disconnect()

Disconnect disconnects from Stats API and releases all connection-related resources.

func (*StatsConnection) GetBufferStats

func (c *StatsConnection) GetBufferStats(bufStats *api.BufferStats) (err error)

GetBufferStats retrieves VPP buffer pools stats.

func (*StatsConnection) GetErrorStats

func (c *StatsConnection) GetErrorStats(errorStats *api.ErrorStats) (err error)

GetErrorStats retrieves VPP error stats.

func (*StatsConnection) GetInterfaceStats

func (c *StatsConnection) GetInterfaceStats(ifaceStats *api.InterfaceStats) (err error)

GetInterfaceStats retrieves VPP per interface stats.

func (*StatsConnection) GetMemoryStats added in v0.4.0

func (c *StatsConnection) GetMemoryStats(memStats *api.MemoryStats) (err error)

func (*StatsConnection) GetNodeStats

func (c *StatsConnection) GetNodeStats(nodeStats *api.NodeStats) (err error)

func (*StatsConnection) GetSystemStats

func (c *StatsConnection) GetSystemStats(sysStats *api.SystemStats) (err error)

GetSystemStats retrieves VPP system stats.

type Stream added in v0.4.0

type Stream struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*Stream) Close added in v0.4.0

func (s *Stream) Close() error

func (*Stream) Context added in v0.4.0

func (s *Stream) Context() context.Context

func (*Stream) RecvMsg added in v0.4.0

func (s *Stream) RecvMsg() (api.Message, error)

func (*Stream) SendMsg added in v0.4.0

func (s *Stream) SendMsg(msg api.Message) error

Jump to

Keyboard shortcuts

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