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