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.
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/codec"
34 DefaultReconnectInterval = time.Second / 2 // default interval between reconnect attempts
35 DefaultMaxReconnectAttempts = 3 // default maximum number of reconnect attempts
39 RequestChanBufSize = 100 // default size of the request channel buffer
40 ReplyChanBufSize = 100 // default size of the reply channel buffer
41 NotificationChanBufSize = 100 // default size of the notification channel buffer
45 HealthCheckProbeInterval = time.Second // default health check probe interval
46 HealthCheckReplyTimeout = time.Millisecond * 250 // timeout for reply to a health check probe
47 HealthCheckThreshold = 2 // number of failed health checks until the error is reported
48 DefaultReplyTimeout = time.Second // default timeout for replies from VPP
51 // ConnectionState represents the current state of the connection to VPP.
52 type ConnectionState int
55 // Connected represents state in which the connection has been successfully established.
56 Connected ConnectionState = iota
58 // NotResponding represents a state where the VPP socket accepts messages but replies are received with delay,
59 // or not at all. GoVPP treats this state internally the same as disconnected.
62 // Disconnected represents state in which the VPP socket is closed and the connection is considered dropped.
65 // Failed represents state in which the reconnecting failed after exceeding maximum number of attempts.
69 func (s ConnectionState) String() string {
74 return "NotResponding"
80 return fmt.Sprintf("UnknownState(%d)", s)
84 // ConnectionEvent is a notification about change in the VPP connection state.
85 type ConnectionEvent struct {
86 // Timestamp holds the time when the event has been created.
89 // State holds the new state of the connection at the time when the event has been created.
92 // Error holds error if any encountered.
96 // Connection represents a shared memory connection to VPP via vppAdapter.
97 type Connection struct {
98 vppClient adapter.VppAPI // VPP binary API client
100 maxAttempts int // interval for reconnect attempts
101 recInterval time.Duration // maximum number of reconnect attempts
103 vppConnected uint32 // non-zero if the adapter is connected to VPP
105 connChan chan ConnectionEvent // connection status events are sent to this channel
106 healthCheckDone chan struct{} // used to terminate health check loop
108 codec MessageCodec // message codec
109 msgIDs map[string]uint16 // map of message IDs indexed by message name + CRC
110 msgMapByPath map[string]map[uint16]api.Message // map of messages indexed by message ID which are indexed by path
112 channelsLock sync.RWMutex // lock for the channels map and the channel ID
113 nextChannelID uint16 // next potential channel ID (the real limit is 2^15)
114 channels map[uint16]*Channel // map of all API channels indexed by the channel ID
116 subscriptionsLock sync.RWMutex // lock for the subscriptions map
117 subscriptions map[uint16][]*subscriptionCtx // map od all notification subscriptions indexed by message ID
119 pingReqID uint16 // ID if the ControlPing message
120 pingReplyID uint16 // ID of the ControlPingReply message
122 lastReplyLock sync.Mutex // lock for the last reply
123 lastReply time.Time // time of the last received reply from VPP
125 msgControlPing api.Message
126 msgControlPingReply api.Message
128 apiTrace *trace // API tracer (disabled by default)
131 func newConnection(binapi adapter.VppAPI, attempts int, interval time.Duration) *Connection {
133 attempts = DefaultMaxReconnectAttempts
136 interval = DefaultReconnectInterval
141 maxAttempts: attempts,
142 recInterval: interval,
143 connChan: make(chan ConnectionEvent, NotificationChanBufSize),
144 healthCheckDone: make(chan struct{}),
145 codec: codec.DefaultCodec,
146 msgIDs: make(map[string]uint16),
147 msgMapByPath: make(map[string]map[uint16]api.Message),
148 channels: make(map[uint16]*Channel),
149 subscriptions: make(map[uint16][]*subscriptionCtx),
150 msgControlPing: msgControlPing,
151 msgControlPingReply: msgControlPingReply,
153 list: make([]*api.Record, 0),
157 binapi.SetMsgCallback(c.msgCallback)
161 // Connect connects to VPP API using specified adapter and returns a connection handle.
162 // This call blocks until it is either connected, or an error occurs.
163 // Only one connection attempt will be performed.
164 func Connect(binapi adapter.VppAPI) (*Connection, error) {
165 // create new connection handle
166 c := newConnection(binapi, DefaultMaxReconnectAttempts, DefaultReconnectInterval)
168 // blocking attempt to connect to VPP
169 if err := c.connectVPP(); err != nil {
176 // AsyncConnect asynchronously connects to VPP using specified VPP adapter and returns the connection handle
177 // and ConnectionState channel. This call does not block until connection is established, it
178 // returns immediately. The caller is supposed to watch the returned ConnectionState channel for
179 // Connected/Disconnected events. In case of disconnect, the library will asynchronously try to reconnect.
180 func AsyncConnect(binapi adapter.VppAPI, attempts int, interval time.Duration) (*Connection, chan ConnectionEvent, error) {
181 // create new connection handle
182 c := newConnection(binapi, attempts, interval)
184 // asynchronously attempt to connect to VPP
187 return c, c.connChan, nil
190 // connectVPP performs blocking attempt to connect to VPP.
191 func (c *Connection) connectVPP() error {
192 log.Debug("Connecting to VPP..")
195 if err := c.vppClient.Connect(); err != nil {
198 log.Debugf("Connected to VPP")
200 if err := c.retrieveMessageIDs(); err != nil {
201 if err := c.vppClient.Disconnect(); err != nil {
202 log.Debugf("disconnecting vpp client failed: %v", err)
204 return fmt.Errorf("VPP is incompatible: %v", err)
207 // store connected state
208 atomic.StoreUint32(&c.vppConnected, 1)
213 // Disconnect disconnects from VPP API and releases all connection-related resources.
214 func (c *Connection) Disconnect() {
218 if c.vppClient != nil {
223 // disconnectVPP disconnects from VPP in case it is connected.
224 func (c *Connection) disconnectVPP() {
225 if atomic.CompareAndSwapUint32(&c.vppConnected, 1, 0) {
226 close(c.healthCheckDone)
227 log.Debug("Disconnecting from VPP..")
229 if err := c.vppClient.Disconnect(); err != nil {
230 log.Debugf("Disconnect from VPP failed: %v", err)
232 log.Debug("Disconnected from VPP")
236 func (c *Connection) NewAPIChannel() (api.Channel, error) {
237 return c.newAPIChannel(RequestChanBufSize, ReplyChanBufSize)
240 func (c *Connection) NewAPIChannelBuffered(reqChanBufSize, replyChanBufSize int) (api.Channel, error) {
241 return c.newAPIChannel(reqChanBufSize, replyChanBufSize)
244 // NewAPIChannelBuffered returns a new API channel for communication with VPP via govpp core.
245 // It allows to specify custom buffer sizes for the request and reply Go channels.
246 func (c *Connection) newAPIChannel(reqChanBufSize, replyChanBufSize int) (*Channel, error) {
248 return nil, errors.New("nil connection passed in")
251 channel, err := c.newChannel(reqChanBufSize, replyChanBufSize)
256 // start watching on the request channel
257 go c.watchRequests(channel)
262 // releaseAPIChannel releases API channel that needs to be closed.
263 func (c *Connection) releaseAPIChannel(ch *Channel) {
264 log.WithFields(logger.Fields{
266 }).Debug("API channel released")
268 // delete the channel from channels map
269 c.channelsLock.Lock()
270 delete(c.channels, ch.id)
271 c.channelsLock.Unlock()
274 // connectLoop attempts to connect to VPP until it succeeds.
275 // Then it continues with healthCheckLoop.
276 func (c *Connection) connectLoop() {
277 var reconnectAttempts int
279 // loop until connected
281 if err := c.vppClient.WaitReady(); err != nil {
282 log.Debugf("wait ready failed: %v", err)
284 if err := c.connectVPP(); err == nil {
285 // signal connected event
286 c.sendConnEvent(ConnectionEvent{Timestamp: time.Now(), State: Connected})
288 } else if reconnectAttempts < c.maxAttempts {
290 log.Warnf("connecting failed (attempt %d/%d): %v", reconnectAttempts, c.maxAttempts, err)
291 time.Sleep(c.recInterval)
293 c.sendConnEvent(ConnectionEvent{Timestamp: time.Now(), State: Failed, Error: err})
298 // we are now connected, continue with health check loop
302 // healthCheckLoop checks whether connection to VPP is alive. In case of disconnect,
303 // it continues with connectLoop and tries to reconnect.
304 func (c *Connection) healthCheckLoop() {
305 // create a separate API channel for health check probes
306 ch, err := c.newAPIChannel(1, 1)
308 log.Error("Failed to create health check API channel, health check will be disabled:", err)
314 sinceLastReply time.Duration
318 // send health check probes until an error or timeout occurs
319 probeInterval := time.NewTicker(HealthCheckProbeInterval)
320 defer probeInterval.Stop()
325 case <-c.healthCheckDone:
326 // Terminate the health check loop on connection disconnect
327 log.Debug("Disconnected on request, exiting health check loop.")
329 case <-probeInterval.C:
330 // try draining probe replies from previous request before sending next one
333 log.Debug("drained old probe reply from reply channel")
337 // send the control ping request
338 ch.reqChan <- &vppRequest{msg: c.msgControlPing}
341 // expect response within timeout period
343 case vppReply := <-ch.replyChan:
346 case <-time.After(HealthCheckReplyTimeout):
347 err = ErrProbeTimeout
349 // check if time since last reply from any other
350 // channel is less than health check reply timeout
351 c.lastReplyLock.Lock()
352 sinceLastReply = time.Since(c.lastReply)
353 c.lastReplyLock.Unlock()
355 if sinceLastReply < HealthCheckReplyTimeout {
356 log.Warnf("VPP health check probe timing out, but some request on other channel was received %v ago, continue waiting!", sinceLastReply)
363 if err == ErrProbeTimeout {
365 log.Warnf("VPP health check probe timed out after %v (%d. timeout)", HealthCheckReplyTimeout, failedChecks)
366 if failedChecks > HealthCheckThreshold {
367 // in case of exceeded failed check threshold, assume VPP unresponsive
368 log.Errorf("VPP does not responding, the health check exceeded threshold for timeouts (>%d)", HealthCheckThreshold)
369 c.sendConnEvent(ConnectionEvent{Timestamp: time.Now(), State: NotResponding})
372 } else if err != nil {
373 // in case of error, assume VPP disconnected
374 log.Errorf("VPP health check probe failed: %v", err)
375 c.sendConnEvent(ConnectionEvent{Timestamp: time.Now(), State: Disconnected, Error: err})
377 } else if failedChecks > 0 {
378 // in case of success after failed checks, clear failed check counter
380 log.Infof("VPP health check probe OK")
388 // we are now disconnected, start connect loop
392 func getMsgNameWithCrc(x api.Message) string {
393 return getMsgID(x.GetMessageName(), x.GetCrcString())
396 func getMsgID(name, crc string) string {
397 return name + "_" + crc
400 func getMsgFactory(msg api.Message) func() api.Message {
401 return func() api.Message {
402 return reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
406 // GetMessageID returns message identifier of given API message.
407 func (c *Connection) GetMessageID(msg api.Message) (uint16, error) {
409 return 0, errors.New("nil connection passed in")
411 pkgPath := c.GetMessagePath(msg)
412 msgID, err := c.vppClient.GetMsgID(msg.GetMessageName(), msg.GetCrcString())
416 if pathMsgs, pathOk := c.msgMapByPath[pkgPath]; !pathOk {
417 c.msgMapByPath[pkgPath] = make(map[uint16]api.Message)
418 c.msgMapByPath[pkgPath][msgID] = msg
419 } else if _, msgOk := pathMsgs[msgID]; !msgOk {
420 c.msgMapByPath[pkgPath][msgID] = msg
422 if _, ok := c.msgIDs[getMsgNameWithCrc(msg)]; ok {
425 c.msgIDs[getMsgNameWithCrc(msg)] = msgID
429 // LookupByID looks up message name and crc by ID.
430 func (c *Connection) LookupByID(path string, msgID uint16) (api.Message, error) {
432 return nil, errors.New("nil connection passed in")
434 if msg, ok := c.msgMapByPath[path][msgID]; ok {
437 return nil, fmt.Errorf("unknown message ID %d for path '%s'", msgID, path)
440 // GetMessagePath returns path for the given message
441 func (c *Connection) GetMessagePath(msg api.Message) string {
442 return path.Dir(reflect.TypeOf(msg).Elem().PkgPath())
445 // retrieveMessageIDs retrieves IDs for all registered messages and stores them in map
446 func (c *Connection) retrieveMessageIDs() (err error) {
449 msgsByPath := api.GetRegisteredMessages()
452 for pkgPath, msgs := range msgsByPath {
453 for _, msg := range msgs {
454 msgID, err := c.GetMessageID(msg)
457 log.Debugf("retrieving message ID for %s.%s failed: %v",
458 pkgPath, msg.GetMessageName(), err)
464 if c.pingReqID == 0 && msg.GetMessageName() == c.msgControlPing.GetMessageName() {
466 c.msgControlPing = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
467 } else if c.pingReplyID == 0 && msg.GetMessageName() == c.msgControlPingReply.GetMessageName() {
468 c.pingReplyID = msgID
469 c.msgControlPingReply = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
473 log.Debugf("message %q (%s) has ID: %d", msg.GetMessageName(), getMsgNameWithCrc(msg), msgID)
476 log.WithField("took", time.Since(t)).
477 Debugf("retrieved IDs for %d messages (registered %d) from path %s", n, len(msgs), pkgPath)
483 func (c *Connection) sendConnEvent(event ConnectionEvent) {
485 case c.connChan <- event:
487 log.Warn("Connection state channel is full, discarding value.")
491 // Trace gives access to the API trace interface
492 func (c *Connection) Trace() api.Trace {
496 // trace records api message
497 func (c *Connection) trace(msg api.Message, chId uint16, t time.Time, isReceived bool) {
498 if atomic.LoadInt32(&c.apiTrace.isEnabled) == 0 {
501 entry := &api.Record{
504 IsReceived: isReceived,
507 c.apiTrace.mux.Lock()
508 c.apiTrace.list = append(c.apiTrace.list, entry)
509 c.apiTrace.mux.Unlock()