Refactor GoVPP
[govpp.git] / adapter / vppapiclient / vppapiclient_adapter.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 is the default VPP adapter being used for the connection with VPP via shared memory.
18 // It is based on the communication with the vppapiclient VPP library written in C via CGO.
19 package vppapiclient
20
21 /*
22 #cgo CFLAGS: -DPNG_DEBUG=1
23 #cgo LDFLAGS: -lvppapiclient
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <stdint.h>
28 #include <arpa/inet.h>
29 #include <vpp-api/client/vppapiclient.h>
30
31 extern void go_msg_callback(uint16_t msg_id, uint32_t context, void* data, size_t size);
32
33 typedef struct __attribute__((__packed__)) _req_header {
34     uint16_t msg_id;
35     uint32_t client_index;
36     uint32_t context;
37 } req_header_t;
38
39 typedef struct __attribute__((__packed__)) _reply_header {
40     uint16_t msg_id;
41     uint32_t context; // currently not all reply messages contain context field
42 } reply_header_t;
43
44 static void
45 govpp_msg_callback (unsigned char *data, int size)
46 {
47     reply_header_t *header = ((reply_header_t *)data);
48     go_msg_callback(ntohs(header->msg_id), ntohl(header->context), data, size);
49 }
50
51 static int
52 govpp_send(uint32_t context, void *data, size_t size)
53 {
54         req_header_t *header = ((req_header_t *)data);
55         header->context = htonl(context);
56     return vac_write(data, size);
57 }
58
59 static int
60 govpp_connect (char *shm)
61 {
62     return vac_connect("govpp", shm, govpp_msg_callback, 32);
63 }
64
65 static int
66 govvp_disconnect()
67 {
68     return vac_disconnect();
69 }
70
71 static uint32_t
72 govpp_get_msg_index(char *name_and_crc)
73 {
74     return vac_get_msg_index(name_and_crc);
75 }
76 */
77 import "C"
78
79 import (
80         "fmt"
81         "os"
82         "path/filepath"
83         "reflect"
84         "unsafe"
85
86         "git.fd.io/govpp.git/adapter"
87         "github.com/fsnotify/fsnotify"
88 )
89
90 const (
91         // watchedFolder is a folder where vpp's shared memory is supposed to be created.
92         // File system events are monitored in this folder.
93         watchedFolder = "/dev/shm/"
94         // watchedFile is a default name of the file in the watchedFolder. Once the file is present,
95         // the vpp is ready to accept a new connection.
96         watchedFile = "vpe-api"
97 )
98
99 // vppAPIClientAdapter is the opaque context of the adapter.
100 type vppAPIClientAdapter struct {
101         shmPrefix string
102         callback  adapter.MsgCallback
103 }
104
105 var vppClient *vppAPIClientAdapter // global vpp API client adapter context
106
107 // NewVppAdapter returns a new vpp API client adapter.
108 func NewVppAdapter(shmPrefix string) adapter.VppAdapter {
109         return &vppAPIClientAdapter{
110                 shmPrefix: shmPrefix,
111         }
112 }
113
114 // Connect connects the process to VPP.
115 func (a *vppAPIClientAdapter) Connect() error {
116         vppClient = a
117         var rc _Ctype_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("unable to connect to VPP (error=%d)", rc)
126         }
127         return nil
128 }
129
130 // Disconnect disconnects the process from VPP.
131 func (a *vppAPIClientAdapter) Disconnect() {
132         C.govvp_disconnect()
133 }
134
135 // GetMsgID returns a runtime message ID for the given message name and CRC.
136 func (a *vppAPIClientAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
137         nameAndCrc := C.CString(msgName + "_" + msgCrc)
138         defer C.free(unsafe.Pointer(nameAndCrc))
139
140         msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
141         if msgID == ^uint16(0) {
142                 // VPP does not know this message
143                 return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
144         }
145
146         return msgID, nil
147 }
148
149 // SendMsg sends a binary-encoded message to VPP.
150 func (a *vppAPIClientAdapter) SendMsg(context uint32, data []byte) error {
151         rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
152         if rc != 0 {
153                 return fmt.Errorf("unable to send the message (error=%d)", rc)
154         }
155         return nil
156 }
157
158 // SetMsgCallback sets a callback function that will be called by the adapter whenever a message comes from VPP.
159 func (a *vppAPIClientAdapter) SetMsgCallback(cb adapter.MsgCallback) {
160         a.callback = cb
161 }
162
163 // WaitReady blocks until shared memory for sending
164 // binary api calls is present on the file system.
165 func (a *vppAPIClientAdapter) WaitReady() error {
166         // Path to the shared memory segment
167         var path string
168         if a.shmPrefix == "" {
169                 path = filepath.Join(watchedFolder, watchedFile)
170         } else {
171                 path = filepath.Join(watchedFolder, a.shmPrefix+"-"+watchedFile)
172         }
173
174         // Watch folder if file does not exist yet
175         if !fileExists(path) {
176                 watcher, err := fsnotify.NewWatcher()
177                 if err != nil {
178                         return err
179                 }
180                 defer watcher.Close()
181
182                 if err := watcher.Add(watchedFolder); err != nil {
183                         return err
184                 }
185
186                 for {
187                         ev := <-watcher.Events
188                         if ev.Name == path && (ev.Op&fsnotify.Create) == fsnotify.Create {
189                                 break
190                         }
191                 }
192         }
193
194         return nil
195 }
196
197 func fileExists(name string) bool {
198         if _, err := os.Stat(name); err != nil {
199                 if os.IsNotExist(err) {
200                         return false
201                 }
202         }
203         return true
204 }
205
206 //export go_msg_callback
207 func go_msg_callback(msgID C.uint16_t, context C.uint32_t, data unsafe.Pointer, size C.size_t) {
208         // convert unsafe.Pointer to byte slice
209         slice := &reflect.SliceHeader{Data: uintptr(data), Len: int(size), Cap: int(size)}
210         byteArr := *(*[]byte)(unsafe.Pointer(slice))
211
212         vppClient.callback(uint16(msgID), uint32(context), byteArr)
213 }