Fixup build with golang 1.12
[govpp.git] / adapter / vppapiclient / vppapiclient.go
1 // Copyright (c) 2017 Cisco and/or its affiliates.
2 //
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:
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 // +build !windows,!darwin
16
17 package vppapiclient
18
19 /*
20 #cgo CFLAGS: -DPNG_DEBUG=1
21 #cgo LDFLAGS: -lvppapiclient
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdint.h>
26 #include <arpa/inet.h>
27 #include <vpp-api/client/vppapiclient.h>
28
29 extern void go_msg_callback(uint16_t msg_id, void* data, size_t size);
30
31 typedef struct __attribute__((__packed__)) _req_header {
32     uint16_t msg_id;
33     uint32_t client_index;
34     uint32_t context;
35 } req_header_t;
36
37 typedef struct __attribute__((__packed__)) _reply_header {
38     uint16_t msg_id;
39 } reply_header_t;
40
41 static void
42 govpp_msg_callback(unsigned char *data, int size)
43 {
44     reply_header_t *header = ((reply_header_t *)data);
45     go_msg_callback(ntohs(header->msg_id), data, size);
46 }
47
48 static int
49 govpp_send(uint32_t context, void *data, size_t size)
50 {
51         req_header_t *header = ((req_header_t *)data);
52         header->context = htonl(context);
53     return vac_write(data, size);
54 }
55
56 static int
57 govpp_connect(char *shm)
58 {
59     return vac_connect("govpp", shm, govpp_msg_callback, 32);
60 }
61
62 static int
63 govpp_disconnect()
64 {
65     return vac_disconnect();
66 }
67
68 static uint32_t
69 govpp_get_msg_index(char *name_and_crc)
70 {
71     return vac_get_msg_index(name_and_crc);
72 }
73 */
74 import "C"
75
76 import (
77         "fmt"
78         "os"
79         "path/filepath"
80         "reflect"
81         "unsafe"
82
83         "git.fd.io/govpp.git/adapter"
84         "github.com/fsnotify/fsnotify"
85 )
86
87 const (
88         // shmDir is a directory where shared memory is supposed to be created.
89         shmDir = "/dev/shm/"
90         // vppShmFile is a default name of the file in the shmDir.
91         vppShmFile = "vpe-api"
92 )
93
94 // global VPP binary API client, library vppapiclient only supports
95 // single connection at a time
96 var globalVppClient *vppClient
97
98 // stubVppClient is the default implementation of the VppAPI.
99 type vppClient struct {
100         shmPrefix   string
101         msgCallback adapter.MsgCallback
102 }
103
104 // NewVppClient returns a new VPP binary API client.
105 func NewVppClient(shmPrefix string) adapter.VppAPI {
106         return &vppClient{
107                 shmPrefix: shmPrefix,
108         }
109 }
110
111 // Connect connects the process to VPP.
112 func (a *vppClient) Connect() error {
113         if globalVppClient != nil {
114                 return fmt.Errorf("already connected to binary API, disconnect first")
115         }
116
117         var rc C.int
118         if a.shmPrefix == "" {
119                 rc = C.govpp_connect(nil)
120         } else {
121                 shm := C.CString(a.shmPrefix)
122                 rc = C.govpp_connect(shm)
123         }
124         if rc != 0 {
125                 return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
126         }
127
128         globalVppClient = a
129         return nil
130 }
131
132 // Disconnect disconnects the process from VPP.
133 func (a *vppClient) Disconnect() error {
134         globalVppClient = nil
135
136         rc := C.govpp_disconnect()
137         if rc != 0 {
138                 return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
139         }
140
141         return nil
142 }
143
144 // GetMsgID returns a runtime message ID for the given message name and CRC.
145 func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
146         nameAndCrc := C.CString(msgName + "_" + msgCrc)
147         defer C.free(unsafe.Pointer(nameAndCrc))
148
149         msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
150         if msgID == ^uint16(0) {
151                 // VPP does not know this message
152                 return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
153         }
154
155         return msgID, nil
156 }
157
158 // SendMsg sends a binary-encoded message to VPP.
159 func (a *vppClient) SendMsg(context uint32, data []byte) error {
160         rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
161         if rc != 0 {
162                 return fmt.Errorf("unable to send the message (rc=%v)", rc)
163         }
164         return nil
165 }
166
167 // SetMsgCallback sets a callback function that will be called by the adapter
168 // whenever a message comes from VPP.
169 func (a *vppClient) SetMsgCallback(cb adapter.MsgCallback) {
170         a.msgCallback = cb
171 }
172
173 // WaitReady blocks until shared memory for sending
174 // binary api calls is present on the file system.
175 func (a *vppClient) WaitReady() error {
176         var path string
177
178         // join the path to the shared memory segment
179         if a.shmPrefix == "" {
180                 path = filepath.Join(shmDir, vppShmFile)
181         } else {
182                 path = filepath.Join(shmDir, a.shmPrefix+"-"+vppShmFile)
183         }
184
185         // check if file at the path exists
186         if _, err := os.Stat(path); err == nil {
187                 // file exists, we are ready
188                 return nil
189         } else if !os.IsNotExist(err) {
190                 return err
191         }
192
193         // file does not exist, start watching folder
194         watcher, err := fsnotify.NewWatcher()
195         if err != nil {
196                 return err
197         }
198         defer watcher.Close()
199
200         if err := watcher.Add(shmDir); err != nil {
201                 return err
202         }
203
204         for {
205                 ev := <-watcher.Events
206                 if ev.Name == path {
207                         if (ev.Op & fsnotify.Create) == fsnotify.Create {
208                                 // file was created, we are ready
209                                 break
210                         }
211                 }
212         }
213
214         return nil
215 }
216
217 //export go_msg_callback
218 func go_msg_callback(msgID C.uint16_t, data unsafe.Pointer, size C.size_t) {
219         // convert unsafe.Pointer to byte slice
220         sliceHeader := &reflect.SliceHeader{Data: uintptr(data), Len: int(size), Cap: int(size)}
221         byteSlice := *(*[]byte)(unsafe.Pointer(sliceHeader))
222
223         globalVppClient.msgCallback(uint16(msgID), byteSlice)
224 }