Change module name to go.fd.io/govpp
[govpp.git] / adapter / vppapiclient / vppapiclient.go
index 244be43..3ab460d 100644 (file)
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// +build !windows,!darwin
+// +build !windows,!darwin,!novpp
 
 package vppapiclient
 
@@ -29,12 +29,13 @@ import (
        "os"
        "path/filepath"
        "reflect"
+       "sync/atomic"
        "time"
        "unsafe"
 
        "github.com/fsnotify/fsnotify"
 
-       "git.fd.io/govpp.git/adapter"
+       "go.fd.io/govpp/adapter"
 )
 
 var (
@@ -52,7 +53,7 @@ const (
 
 // global VPP binary API client, library vppapiclient only supports
 // single connection at a time
-var globalVppClient *vppClient
+var globalVppClient unsafe.Pointer
 
 // stubVppClient is the default implementation of the VppAPI.
 type vppClient struct {
@@ -76,7 +77,8 @@ func NewVppClientWithInputQueueSize(shmPrefix string, inputQueueSize uint16) ada
 
 // Connect connects the process to VPP.
 func (a *vppClient) Connect() error {
-       if globalVppClient != nil {
+       h := (*vppClient)(atomic.LoadPointer(&globalVppClient))
+       if h != nil {
                return fmt.Errorf("already connected to binary API, disconnect first")
        }
 
@@ -92,19 +94,17 @@ func (a *vppClient) Connect() error {
                return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
        }
 
-       globalVppClient = a
+       atomic.StorePointer(&globalVppClient, unsafe.Pointer(a))
        return nil
 }
 
 // Disconnect disconnects the process from VPP.
 func (a *vppClient) Disconnect() error {
-       globalVppClient = nil
-
+       atomic.StorePointer(&globalVppClient, nil)
        rc := C.govpp_disconnect()
        if rc != 0 {
                return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
        }
-
        return nil
 }
 
@@ -116,7 +116,7 @@ func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
        msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
        if msgID == ^uint16(0) {
                // VPP does not know this message
-               return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
+               return msgID, &adapter.UnknownMsgError{msgName, msgCrc}
        }
 
        return msgID, nil
@@ -187,9 +187,12 @@ func (a *vppClient) WaitReady() error {
 
 //export go_msg_callback
 func go_msg_callback(msgID C.uint16_t, data unsafe.Pointer, size C.size_t) {
+       h := (*vppClient)(atomic.LoadPointer(&globalVppClient))
+       if h == nil {
+               return
+       }
        // convert unsafe.Pointer to byte slice
        sliceHeader := &reflect.SliceHeader{Data: uintptr(data), Len: int(size), Cap: int(size)}
        byteSlice := *(*[]byte)(unsafe.Pointer(sliceHeader))
-
-       globalVppClient.msgCallback(uint16(msgID), byteSlice)
+       h.msgCallback(uint16(msgID), byteSlice)
 }