1 // Copyright (c) 2017 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 //go:generate binapi-generator --input-dir=bin_api --output-dir=bin_api
26 logger "github.com/sirupsen/logrus"
28 "git.fd.io/govpp.git/adapter"
29 "git.fd.io/govpp.git/api"
30 "git.fd.io/govpp.git/core/bin_api/vpe"
34 requestChannelBufSize = 100 // default size of the request channel buffers
35 replyChannelBufSize = 100 // default size of the reply channel buffers
36 notificationChannelBufSize = 100 // default size of the notification channel buffers
40 healthCheckProbeInterval = time.Second * 1 // default health check probe interval
41 healthCheckReplyTimeout = time.Millisecond * 100 // timeout for reply to a health check probe
42 healthCheckThreshold = 1 // number of failed healthProbe until the error is reported
45 // ConnectionState holds the current state of the connection to VPP.
46 type ConnectionState int
49 // Connected connection state means that the connection to VPP has been successfully established.
50 Connected ConnectionState = iota
52 // Disconnected connection state means that the connection to VPP has been lost.
56 // ConnectionEvent is a notification about change in the VPP connection state.
57 type ConnectionEvent struct {
58 // Timestamp holds the time when the event has been generated.
61 // State holds the new state of the connection to VPP at the time when the event has been generated.
65 // Connection represents a shared memory connection to VPP via vppAdapter.
66 type Connection struct {
67 vpp adapter.VppAdapter // VPP adapter
68 connected uint32 // non-zero if the adapter is connected to VPP
69 codec *MsgCodec // message codec
71 msgIDs map[string]uint16 // map of message IDs indexed by message name + CRC
72 msgIDsLock sync.RWMutex // lock for the message IDs map
74 channels map[uint32]*api.Channel // map of all API channels indexed by the channel ID
75 channelsLock sync.RWMutex // lock for the channels map
77 notifSubscriptions map[uint16][]*api.NotifSubscription // map od all notification subscriptions indexed by message ID
78 notifSubscriptionsLock sync.RWMutex // lock for the subscriptions map
80 maxChannelID uint32 // maximum used client ID
81 pingReqID uint16 // ID if the ControlPing message
82 pingReplyID uint16 // ID of the ControlPingReply message
85 // channelMetadata contains core-local metadata of an API channel.
86 type channelMetadata struct {
87 id uint32 // channel ID
88 multipart uint32 // 1 if multipart request is being processed, 0 otherwise
92 log *logger.Logger // global logger
93 conn *Connection // global handle to the Connection (used in the message receive callback)
94 connLock sync.RWMutex // lock for the global connection
97 // init initializes global logger, which logs debug level messages to stdout.
101 log.Level = logger.DebugLevel
104 // SetLogger sets global logger to provided one.
105 func SetLogger(l *logger.Logger) {
109 // SetHealthCheckProbeInterval sets health check probe interval.
110 // Beware: Function is not thread-safe. It is recommended to setup this parameter
111 // before connecting to vpp.
112 func SetHealthCheckProbeInterval(interval time.Duration) {
113 healthCheckProbeInterval = interval
116 // SetHealthCheckReplyTimeout sets timeout for reply to a health check probe.
117 // If reply arrives after the timeout, check is considered as failed.
118 // Beware: Function is not thread-safe. It is recommended to setup this parameter
119 // before connecting to vpp.
120 func SetHealthCheckReplyTimeout(timeout time.Duration) {
121 healthCheckReplyTimeout = timeout
124 // SetHealthCheckThreshold sets the number of failed healthProbe checks until the error is reported.
125 // Beware: Function is not thread-safe. It is recommended to setup this parameter
126 // before connecting to vpp.
127 func SetHealthCheckThreshold(threshold int) {
128 healthCheckThreshold = threshold
131 // Connect connects to VPP using specified VPP adapter and returns the connection handle.
132 // This call blocks until VPP is connected, or an error occurs. Only one connection attempt will be performed.
133 func Connect(vppAdapter adapter.VppAdapter) (*Connection, error) {
134 // create new connection handle
135 c, err := newConnection(vppAdapter)
140 // blocking attempt to connect to VPP
149 // AsyncConnect asynchronously connects to VPP using specified VPP adapter and returns the connection handle
150 // and ConnectionState channel. This call does not block until connection is established, it
151 // returns immediately. The caller is supposed to watch the returned ConnectionState channel for
152 // Connected/Disconnected events. In case of disconnect, the library will asynchronously try to reconnect.
153 func AsyncConnect(vppAdapter adapter.VppAdapter) (*Connection, chan ConnectionEvent, error) {
154 // create new connection handle
155 c, err := newConnection(vppAdapter)
160 // asynchronously attempt to connect to VPP
161 connChan := make(chan ConnectionEvent, notificationChannelBufSize)
162 go c.connectLoop(connChan)
164 return conn, connChan, nil
167 // Disconnect disconnects from VPP and releases all connection-related resources.
168 func (c *Connection) Disconnect() {
173 defer connLock.Unlock()
175 if c != nil && c.vpp != nil {
181 // newConnection returns new connection handle.
182 func newConnection(vppAdapter adapter.VppAdapter) (*Connection, error) {
184 defer connLock.Unlock()
187 return nil, errors.New("only one connection per process is supported")
193 channels: make(map[uint32]*api.Channel),
194 msgIDs: make(map[string]uint16),
195 notifSubscriptions: make(map[uint16][]*api.NotifSubscription),
198 conn.vpp.SetMsgCallback(msgCallback)
202 // connectVPP performs one blocking attempt to connect to VPP.
203 func (c *Connection) connectVPP() error {
204 log.Debug("Connecting to VPP...")
207 err := c.vpp.Connect()
213 // store connected state
214 atomic.StoreUint32(&c.connected, 1)
216 // store control ping IDs
217 c.pingReqID, _ = c.GetMessageID(&vpe.ControlPing{})
218 c.pingReplyID, _ = c.GetMessageID(&vpe.ControlPingReply{})
220 log.Info("Connected to VPP.")
224 // disconnectVPP disconnects from VPP in case it is connected.
225 func (c *Connection) disconnectVPP() {
226 if atomic.CompareAndSwapUint32(&c.connected, 1, 0) {
231 // connectLoop attempts to connect to VPP until it succeeds.
232 // Then it continues with healthCheckLoop.
233 func (c *Connection) connectLoop(connChan chan ConnectionEvent) {
234 // loop until connected
237 if err := c.connectVPP(); err == nil {
238 // signal connected event
239 connChan <- ConnectionEvent{Timestamp: time.Now(), State: Connected}
244 // we are now connected, continue with health check loop
245 c.healthCheckLoop(connChan)
248 // healthCheckLoop checks whether connection to VPP is alive. In case of disconnect,
249 // it continues with connectLoop and tries to reconnect.
250 func (c *Connection) healthCheckLoop(connChan chan ConnectionEvent) {
251 // create a separate API channel for health check probes
252 ch, err := conn.NewAPIChannel()
254 log.Error("Error by creating health check API channel, health check will be disabled:", err)
259 // send health check probes until an error occurs
261 // wait for healthCheckProbeInterval
262 <-time.After(healthCheckProbeInterval)
264 if atomic.LoadUint32(&c.connected) == 0 {
265 // Disconnect has been called in the meantime, return the healthcheck - reconnect loop
266 log.Debug("Disconnected on request, exiting health check loop.")
270 // send the control ping
271 ch.ReqChan <- &api.VppRequest{Message: &vpe.ControlPing{}}
273 // expect response within timeout period
275 case vppReply := <-ch.ReplyChan:
277 case <-time.After(healthCheckReplyTimeout):
278 err = errors.New("probe reply not received within the timeout period")
287 if failedChecks >= healthCheckThreshold {
288 // in case of error, break & disconnect
289 log.Errorf("VPP health check failed: %v", err)
290 // signal disconnected event via channel
291 connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected}
300 // we are now disconnected, start connect loop
301 c.connectLoop(connChan)
304 // NewAPIChannel returns a new API channel for communication with VPP via govpp core.
305 // It uses default buffer sizes for the request and reply Go channels.
306 func (c *Connection) NewAPIChannel() (*api.Channel, error) {
308 return nil, errors.New("nil connection passed in")
310 return c.NewAPIChannelBuffered(requestChannelBufSize, replyChannelBufSize)
313 // NewAPIChannelBuffered returns a new API channel for communication with VPP via govpp core.
314 // It allows to specify custom buffer sizes for the request and reply Go channels.
315 func (c *Connection) NewAPIChannelBuffered(reqChanBufSize, replyChanBufSize int) (*api.Channel, error) {
317 return nil, errors.New("nil connection passed in")
319 chID := atomic.AddUint32(&c.maxChannelID, 1)
320 chMeta := &channelMetadata{id: chID}
322 ch := api.NewChannelInternal(chMeta)
323 ch.MsgDecoder = c.codec
326 // create the communication channels
327 ch.ReqChan = make(chan *api.VppRequest, reqChanBufSize)
328 ch.ReplyChan = make(chan *api.VppReply, replyChanBufSize)
329 ch.NotifSubsChan = make(chan *api.NotifSubscribeRequest, reqChanBufSize)
330 ch.NotifSubsReplyChan = make(chan error, replyChanBufSize)
332 // store API channel within the client
333 c.channelsLock.Lock()
334 c.channels[chID] = ch
335 c.channelsLock.Unlock()
337 // start watching on the request channel
338 go c.watchRequests(ch, chMeta)
343 // releaseAPIChannel releases API channel that needs to be closed.
344 func (c *Connection) releaseAPIChannel(ch *api.Channel, chMeta *channelMetadata) {
345 log.WithFields(logger.Fields{
346 "context": chMeta.id,
347 }).Debug("API channel closed.")
349 // delete the channel from channels map
350 c.channelsLock.Lock()
351 delete(c.channels, chMeta.id)
352 c.channelsLock.Unlock()