2 *------------------------------------------------------------------
3 * Copyright (c) 2017 Cisco and/or its affiliates.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *------------------------------------------------------------------
18 #ifndef vapi_hpp_included
19 #define vapi_hpp_included
29 #include <vppinfra/types.h>
30 #include <vapi/vapi.h>
31 #include <vapi/vapi_internal.h>
32 #include <vapi/vapi_dbg.h>
33 #include <vapi/vpe.api.vapi.h>
35 #if VAPI_CPP_DEBUG_LEAKS
36 #include <unordered_set>
49 template <typename Req, typename Resp, typename... Args> class Request;
50 template <typename M> class Msg;
51 template <typename M> void vapi_swap_to_be (M *msg);
52 template <typename M> void vapi_swap_to_host (M *msg);
53 template <typename M, typename... Args>
54 M *vapi_alloc (Connection &con, Args...);
55 template <typename M> vapi_msg_id_t vapi_get_msg_id_t ();
56 template <typename M> class Event_registration;
58 class Unexpected_msg_id_exception : public std::exception
61 virtual const char *what () const throw ()
63 return "unexpected message id";
67 class Msg_not_available_exception : public std::exception
70 virtual const char *what () const throw ()
72 return "message unavailable";
77 /** response not ready yet */
80 /** response to request is ready */
83 /** no response to request (will never come) */
85 } vapi_response_state_e;
88 * Class representing common functionality of a request - response state
94 virtual ~Common_req (){};
96 Connection &get_connection ()
101 vapi_response_state_e get_response_state (void) const
103 return response_state;
108 Common_req (Connection &con)
109 : con (con), context{0}, response_state{RESPONSE_NOT_READY}
113 void set_response_state (vapi_response_state_e state)
115 response_state = state;
118 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
121 void set_context (u32 context)
123 this->context = context;
132 vapi_response_state_e response_state;
134 friend class Connection;
136 template <typename M> friend class Msg;
138 template <typename Req, typename Resp, typename... Args>
139 friend class Request;
141 template <typename Req, typename Resp, typename... Args> friend class Dump;
143 template <typename M> friend class Event_registration;
147 * Class representing a connection to VPP
149 * After creating a Connection object, call connect() to actually connect
150 * to VPP. Use is_msg_available to discover whether a specific message is known
151 * and supported by the VPP connected to.
156 Connection (void) : vapi_ctx{0}, event_count{0}
159 vapi_error_e rv = VAPI_OK;
162 if (VAPI_OK != (rv = vapi_ctx_alloc (&vapi_ctx)))
164 throw std::bad_alloc ();
167 events.reserve (vapi_get_message_count () + 1);
170 Connection (const Connection &) = delete;
174 vapi_ctx_free (vapi_ctx);
175 #if VAPI_CPP_DEBUG_LEAKS
176 for (auto x : shm_data_set)
178 printf ("Leaked shm_data@%p!\n", x);
184 * @brief check if message identified by it's message id is known by the
185 * vpp to which the connection is open
187 bool is_msg_available (vapi_msg_id_t type)
189 return vapi_is_msg_available (vapi_ctx, type);
193 * @brief connect to vpp
195 * @param name application name
196 * @param chroot_prefix shared memory prefix
197 * @param max_queued_request max number of outstanding requests queued
199 * @return VAPI_OK on success, other error code on error
201 vapi_error_e connect (const char *name, const char *chroot_prefix,
202 int max_outstanding_requests, int response_queue_size)
204 return vapi_connect (vapi_ctx, name, chroot_prefix,
205 max_outstanding_requests, response_queue_size,
210 * @brief disconnect from vpp
212 * @return VAPI_OK on success, other error code on error
214 vapi_error_e disconnect ()
216 auto x = requests.size ();
219 VAPI_DBG ("popping request @%p", requests.front ());
220 requests.pop_front ();
223 return vapi_disconnect (vapi_ctx);
227 * @brief get event file descriptor
229 * @note this file descriptor becomes readable when messages (from vpp)
230 * are waiting in queue
232 * @param[out] fd pointer to result variable
234 * @return VAPI_OK on success, other error code on error
236 vapi_error_e get_fd (int *fd)
238 return vapi_get_fd (vapi_ctx, fd);
242 * @brief wait for responses from vpp and assign them to appropriate objects
244 * @param limit stop dispatch after the limit object received it's response
246 * @return VAPI_OK on success, other error code on error
248 vapi_error_e dispatch (const Common_req *limit = nullptr, u32 time = 5)
250 std::lock_guard<std::mutex> lock (dispatch_mutex);
251 vapi_error_e rv = VAPI_OK;
252 bool loop_again = true;
256 size_t shm_data_size;
257 rv = vapi_recv (vapi_ctx, &shm_data, &shm_data_size, SVM_Q_TIMEDWAIT,
263 #if VAPI_CPP_DEBUG_LEAKS
264 on_shm_data_alloc (shm_data);
266 std::lock_guard<std::recursive_mutex> requests_lock (requests_mutex);
267 std::lock_guard<std::recursive_mutex> events_lock (events_mutex);
268 vapi_msg_id_t id = vapi_lookup_vapi_msg_id_t (
269 vapi_ctx, be16toh (*static_cast<u16 *> (shm_data)));
270 bool has_context = vapi_msg_is_with_context (id);
271 bool break_dispatch = false;
272 Common_req *matching_req = nullptr;
275 u32 context = *reinterpret_cast<u32 *> (
276 (static_cast<u8 *> (shm_data) + vapi_get_context_offset (id)));
277 const auto x = requests.front ();
279 if (context == x->context)
281 std::tie (rv, break_dispatch) =
282 x->assign_response (id, shm_data);
286 std::tie (rv, break_dispatch) =
287 x->assign_response (id, nullptr);
291 requests.pop_front ();
298 std::tie (rv, break_dispatch) =
299 events[id]->assign_response (id, shm_data);
300 matching_req = events[id];
307 if ((matching_req && matching_req == limit && break_dispatch) ||
312 loop_again = !requests.empty () || (event_count > 0);
318 * @brief convenience wrapper function
320 vapi_error_e dispatch (const Common_req &limit)
322 return dispatch (&limit);
326 * @brief wait for response to a specific request
328 * @param req request to wait for response for
330 * @return VAPI_OK on success, other error code on error
332 vapi_error_e wait_for_response (const Common_req &req)
334 if (RESPONSE_READY == req.get_response_state ())
338 return dispatch (req);
342 void msg_free (void *shm_data)
344 #if VAPI_CPP_DEBUG_LEAKS
345 on_shm_data_free (shm_data);
347 vapi_msg_free (vapi_ctx, shm_data);
350 template <template <typename XReq, typename XResp, typename... XArgs>
352 typename Req, typename Resp, typename... Args>
353 vapi_error_e send (X<Req, Resp, Args...> *req)
360 req_context_counter.fetch_add (1, std::memory_order_relaxed);
361 req->request.shm_data->header.context = req_context;
362 vapi_swap_to_be<Req> (req->request.shm_data);
363 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
364 vapi_error_e rv = vapi_send (vapi_ctx, req->request.shm_data);
367 VAPI_DBG ("Push %p", req);
368 requests.emplace_back (req);
369 req->set_context (req_context);
370 #if VAPI_CPP_DEBUG_LEAKS
371 on_shm_data_free (req->request.shm_data);
373 req->request.shm_data = nullptr; /* consumed by vapi_send */
377 vapi_swap_to_host<Req> (req->request.shm_data);
382 template <template <typename XReq, typename XResp, typename... XArgs>
384 typename Req, typename Resp, typename... Args>
385 vapi_error_e send_with_control_ping (X<Req, Resp, Args...> *req)
392 req_context_counter.fetch_add (1, std::memory_order_relaxed);
393 req->request.shm_data->header.context = req_context;
394 vapi_swap_to_be<Req> (req->request.shm_data);
395 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
396 vapi_error_e rv = vapi_send_with_control_ping (
397 vapi_ctx, req->request.shm_data, req_context);
400 VAPI_DBG ("Push %p", req);
401 requests.emplace_back (req);
402 req->set_context (req_context);
403 #if VAPI_CPP_DEBUG_LEAKS
404 on_shm_data_free (req->request.shm_data);
406 req->request.shm_data = nullptr; /* consumed by vapi_send */
410 vapi_swap_to_host<Req> (req->request.shm_data);
415 void unregister_request (Common_req *request)
417 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
418 std::remove (requests.begin (), requests.end (), request);
421 template <typename M> void register_event (Event_registration<M> *event)
423 const vapi_msg_id_t id = M::get_msg_id ();
424 std::lock_guard<std::recursive_mutex> lock (events_mutex);
429 template <typename M> void unregister_event (Event_registration<M> *event)
431 const vapi_msg_id_t id = M::get_msg_id ();
432 std::lock_guard<std::recursive_mutex> lock (events_mutex);
433 events[id] = nullptr;
438 std::atomic_ulong req_context_counter;
439 std::mutex dispatch_mutex;
441 std::recursive_mutex requests_mutex;
442 std::recursive_mutex events_mutex;
443 std::deque<Common_req *> requests;
444 std::vector<Common_req *> events;
447 template <typename Req, typename Resp, typename... Args>
448 friend class Request;
450 template <typename Req, typename Resp, typename... Args> friend class Dump;
452 template <typename M> friend class Result_set;
454 template <typename M> friend class Event_registration;
456 template <typename M, typename... Args>
457 friend M *vapi_alloc (Connection &con, Args...);
459 template <typename M> friend class Msg;
461 #if VAPI_CPP_DEBUG_LEAKS
462 void on_shm_data_alloc (void *shm_data)
466 auto pos = shm_data_set.find (shm_data);
467 if (pos == shm_data_set.end ())
469 shm_data_set.insert (shm_data);
473 printf ("Double-add shm_data @%p!\n", shm_data);
478 void on_shm_data_free (void *shm_data)
480 auto pos = shm_data_set.find (shm_data);
481 if (pos == shm_data_set.end ())
483 printf ("Freeing untracked shm_data @%p!\n", shm_data);
487 shm_data_set.erase (pos);
490 std::unordered_set<void *> shm_data_set;
494 template <typename Req, typename Resp, typename... Args> class Request;
496 template <typename Req, typename Resp, typename... Args> class Dump;
498 template <class, class = void> struct vapi_has_payload_trait : std::false_type
502 template <class... T> using vapi_void_t = void;
505 struct vapi_has_payload_trait<T, vapi_void_t<decltype (&T::payload)>>
510 template <typename M> void vapi_msg_set_msg_id (vapi_msg_id_t id)
512 Msg<M>::set_msg_id (id);
516 * Class representing a message stored in shared memory
518 template <typename M> class Msg
521 Msg (const Msg &) = delete;
525 VAPI_DBG ("Destroy Msg<%s>@%p, shm_data@%p",
526 vapi_get_msg_name (get_msg_id ()), this, shm_data);
529 con.get ().msg_free (shm_data);
534 static vapi_msg_id_t get_msg_id ()
536 return *msg_id_holder ();
539 template <typename X = M>
540 typename std::enable_if<vapi_has_payload_trait<X>::value,
541 decltype (X::payload) &>::type
544 return shm_data->payload;
548 Msg (Msg<M> &&msg) : con{msg.con}
550 VAPI_DBG ("Move construct Msg<%s> from msg@%p to msg@%p, shm_data@%p",
551 vapi_get_msg_name (get_msg_id ()), &msg, this, msg.shm_data);
552 shm_data = msg.shm_data;
553 msg.shm_data = nullptr;
556 Msg<M> &operator= (Msg<M> &&msg)
558 VAPI_DBG ("Move assign Msg<%s> from msg@%p to msg@%p, shm_data@%p",
559 vapi_get_msg_name (get_msg_id ()), &msg, this, msg.shm_data);
560 con.get ().msg_free (shm_data);
562 shm_data = msg.shm_data;
563 msg.shm_data = nullptr;
567 struct Msg_allocator : std::allocator<Msg<M>>
569 template <class U, class... Args> void construct (U *p, Args &&... args)
571 ::new ((void *)p) U (std::forward<Args> (args)...);
574 template <class U> struct rebind
576 typedef Msg_allocator other;
580 static void set_msg_id (vapi_msg_id_t id)
582 assert ((INVALID_MSG_ID == *msg_id_holder ()) ||
583 (id == *msg_id_holder ()));
584 *msg_id_holder () = id;
587 static vapi_msg_id_t *msg_id_holder ()
589 static vapi_msg_id_t my_id{INVALID_MSG_ID};
593 Msg (Connection &con, void *shm_data) : con{con}
595 if (!con.is_msg_available (get_msg_id ()))
597 throw Msg_not_available_exception ();
599 this->shm_data = static_cast<shm_data_type *> (shm_data);
600 VAPI_DBG ("New Msg<%s>@%p shm_data@%p", vapi_get_msg_name (get_msg_id ()),
604 void assign_response (vapi_msg_id_t resp_id, void *shm_data)
606 assert (nullptr == this->shm_data);
607 if (resp_id != get_msg_id ())
609 throw Unexpected_msg_id_exception ();
611 this->shm_data = static_cast<M *> (shm_data);
612 vapi_swap_to_host<M> (this->shm_data);
613 VAPI_DBG ("Assign response to Msg<%s>@%p shm_data@%p",
614 vapi_get_msg_name (get_msg_id ()), this, shm_data);
617 std::reference_wrapper<Connection> con;
618 using shm_data_type = M;
619 shm_data_type *shm_data;
621 friend class Connection;
623 template <typename Req, typename Resp, typename... Args>
624 friend class Request;
626 template <typename Req, typename Resp, typename... Args> friend class Dump;
628 template <typename X> friend class Event_registration;
630 template <typename X> friend class Result_set;
632 friend struct Msg_allocator;
634 template <typename X> friend void vapi_msg_set_msg_id (vapi_msg_id_t id);
638 * Class representing a simple request - with a single response message
640 template <typename Req, typename Resp, typename... Args>
641 class Request : public Common_req
644 Request (Connection &con, Args... args,
645 std::function<vapi_error_e (Request<Req, Resp, Args...> &)>
647 : Common_req{con}, callback{callback},
648 request{con, vapi_alloc<Req> (con, args...)}, response{con, nullptr}
652 Request (const Request &) = delete;
656 if (RESPONSE_NOT_READY == get_response_state ())
658 con.unregister_request (this);
662 vapi_error_e execute ()
664 return con.send (this);
667 const Msg<Req> &get_request (void) const
672 const Msg<Resp> &get_response (void)
678 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
681 assert (RESPONSE_NOT_READY == get_response_state ());
682 response.assign_response (id, shm_data);
683 set_response_state (RESPONSE_READY);
684 if (nullptr != callback)
686 return std::make_pair (callback (*this), true);
688 return std::make_pair (VAPI_OK, true);
690 std::function<vapi_error_e (Request<Req, Resp, Args...> &)> callback;
694 friend class Connection;
698 * Class representing iterable set of responses of the same type
700 template <typename M> class Result_set
707 Result_set (const Result_set &) = delete;
709 bool is_complete () const
719 using const_iterator =
720 typename std::vector<Msg<M>,
721 typename Msg<M>::Msg_allocator>::const_iterator;
723 const_iterator begin () const
728 const_iterator end () const
733 void free_response (const_iterator pos)
738 void free_all_responses ()
744 void mark_complete ()
749 void assign_response (vapi_msg_id_t resp_id, void *shm_data)
751 if (resp_id != Msg<M>::get_msg_id ())
754 throw Unexpected_msg_id_exception ();
759 vapi_swap_to_host<M> (static_cast<M *> (shm_data));
760 set.emplace_back (con, shm_data);
761 VAPI_DBG ("Result_set@%p emplace_back shm_data@%p", this, shm_data);
765 Result_set (Connection &con) : con (con), complete{false}
771 std::vector<Msg<M>, typename Msg<M>::Msg_allocator> set;
773 template <typename Req, typename Resp, typename... Args> friend class Dump;
775 template <typename X> friend class Event_registration;
779 * Class representing a dump request - zero or more identical responses to a
780 * single request message
782 template <typename Req, typename Resp, typename... Args>
783 class Dump : public Common_req
786 Dump (Connection &con, Args... args,
787 std::function<vapi_error_e (Dump<Req, Resp, Args...> &)> callback =
789 : Common_req{con}, request{con, vapi_alloc<Req> (con, args...)},
790 result_set{con}, callback{callback}
794 Dump (const Dump &) = delete;
800 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
803 if (id == vapi_msg_id_control_ping_reply)
805 con.msg_free (shm_data);
806 result_set.mark_complete ();
807 set_response_state (RESPONSE_READY);
808 if (nullptr != callback)
810 return std::make_pair (callback (*this), true);
812 return std::make_pair (VAPI_OK, true);
816 result_set.assign_response (id, shm_data);
818 return std::make_pair (VAPI_OK, false);
821 vapi_error_e execute ()
823 return con.send_with_control_ping (this);
826 Msg<Req> &get_request (void)
831 using resp_type = typename Msg<Resp>::shm_data_type;
833 const Result_set<Resp> &get_result_set (void) const
840 Result_set<resp_type> result_set;
841 std::function<vapi_error_e (Dump<Req, Resp, Args...> &)> callback;
843 friend class Connection;
847 * Class representing event registration - incoming events (messages) from
848 * vpp as a result of a subscription (typically a want_* simple request)
850 template <typename M> class Event_registration : public Common_req
855 std::function<vapi_error_e (Event_registration<M> &)> callback = nullptr)
856 : Common_req{con}, result_set{con}, callback{callback}
858 if (!con.is_msg_available (M::get_msg_id ()))
860 throw Msg_not_available_exception ();
862 con.register_event (this);
865 Event_registration (const Event_registration &) = delete;
867 virtual ~Event_registration ()
869 con.unregister_event (this);
872 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
875 result_set.assign_response (id, shm_data);
876 if (nullptr != callback)
878 return std::make_pair (callback (*this), true);
880 return std::make_pair (VAPI_OK, true);
883 using resp_type = typename M::shm_data_type;
885 Result_set<resp_type> &get_result_set (void)
891 Result_set<resp_type> result_set;
892 std::function<vapi_error_e (Event_registration<M> &)> callback;
899 * fd.io coding-style-patch-verification: ON
902 * eval: (c-set-style "gnu")