Fix WaitReady for VPP client adapters
[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         "time"
82         "unsafe"
83
84         "git.fd.io/govpp.git/adapter"
85         "github.com/fsnotify/fsnotify"
86 )
87
88 var (
89         // MaxWaitReady defines maximum duration before waiting for shared memory
90         // segment times out
91         MaxWaitReady = time.Second * 15
92 )
93
94 const (
95         // shmDir is a directory where shared memory is supposed to be created.
96         shmDir = "/dev/shm/"
97         // vppShmFile is a default name of the file in the shmDir.
98         vppShmFile = "vpe-api"
99 )
100
101 // global VPP binary API client, library vppapiclient only supports
102 // single connection at a time
103 var globalVppClient *vppClient
104
105 // stubVppClient is the default implementation of the VppAPI.
106 type vppClient struct {
107         shmPrefix   string
108         msgCallback adapter.MsgCallback
109 }
110
111 // NewVppClient returns a new VPP binary API client.
112 func NewVppClient(shmPrefix string) adapter.VppAPI {
113         return &vppClient{
114                 shmPrefix: shmPrefix,
115         }
116 }
117
118 // Connect connects the process to VPP.
119 func (a *vppClient) Connect() error {
120         if globalVppClient != nil {
121                 return fmt.Errorf("already connected to binary API, disconnect first")
122         }
123
124         var rc C.int
125         if a.shmPrefix == "" {
126                 rc = C.govpp_connect(nil)
127         } else {
128                 shm := C.CString(a.shmPrefix)
129                 rc = C.govpp_connect(shm)
130         }
131         if rc != 0 {
132                 return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
133         }
134
135         globalVppClient = a
136         return nil
137 }
138
139 // Disconnect disconnects the process from VPP.
140 func (a *vppClient) Disconnect() error {
141         globalVppClient = nil
142
143         rc := C.govpp_disconnect()
144         if rc != 0 {
145                 return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
146         }
147
148         return nil
149 }
150
151 // GetMsgID returns a runtime message ID for the given message name and CRC.
152 func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
153         nameAndCrc := C.CString(msgName + "_" + msgCrc)
154         defer C.free(unsafe.Pointer(nameAndCrc))
155
156         msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
157         if msgID == ^uint16(0) {
158                 // VPP does not know this message
159                 return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
160         }
161
162         return msgID, nil
163 }
164
165 // SendMsg sends a binary-encoded message to VPP.
166 func (a *vppClient) SendMsg(context uint32, data []byte) error {
167         rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
168         if rc != 0 {
169                 return fmt.Errorf("unable to send the message (rc=%v)", rc)
170         }
171         return nil
172 }
173
174 // SetMsgCallback sets a callback function that will be called by the adapter
175 // whenever a message comes from VPP.
176 func (a *vppClient) SetMsgCallback(cb adapter.MsgCallback) {
177         a.msgCallback = cb
178 }
179
180 // WaitReady blocks until shared memory for sending
181 // binary api calls is present on the file system.
182 func (a *vppClient) WaitReady() error {
183         // join the path to the shared memory segment
184         var path string
185         if a.shmPrefix == "" {
186                 path = filepath.Join(shmDir, vppShmFile)
187         } else {
188                 path = filepath.Join(shmDir, a.shmPrefix+"-"+vppShmFile)
189         }
190
191         // check if file at the path already exists
192         if _, err := os.Stat(path); err == nil {
193                 // file exists, we are ready
194                 return nil
195         } else if !os.IsNotExist(err) {
196                 return err
197         }
198
199         // file does not exist, start watching folder
200         watcher, err := fsnotify.NewWatcher()
201         if err != nil {
202                 return err
203         }
204         defer watcher.Close()
205
206         // start watching directory
207         if err := watcher.Add(shmDir); err != nil {
208                 return err
209         }
210
211         for {
212                 select {
213                 case <-time.After(MaxWaitReady):
214                         return fmt.Errorf("waiting for shared memory segment timed out (%s)", MaxWaitReady)
215                 case e := <-watcher.Errors:
216                         return e
217                 case ev := <-watcher.Events:
218                         if ev.Name == path {
219                                 if (ev.Op & fsnotify.Create) == fsnotify.Create {
220                                         // file was created, we are ready
221                                         return nil
222                                 }
223                         }
224                 }
225         }
226 }
227
228 //export go_msg_callback
229 func go_msg_callback(msgID C.uint16_t, data unsafe.Pointer, size C.size_t) {
230         // convert unsafe.Pointer to byte slice
231         sliceHeader := &reflect.SliceHeader{Data: uintptr(data), Len: int(size), Cap: int(size)}
232         byteSlice := *(*[]byte)(unsafe.Pointer(sliceHeader))
233
234         globalVppClient.msgCallback(uint16(msgID), byteSlice)
235 }