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 Req, typename Resp, typename StreamMessage,
147 template <typename M> friend class Event_registration;
151 * Class representing a connection to VPP
153 * After creating a Connection object, call connect() to actually connect
154 * to VPP. Use is_msg_available to discover whether a specific message is known
155 * and supported by the VPP connected to.
160 Connection (void) : vapi_ctx{0}, event_count{0}
163 vapi_error_e rv = VAPI_OK;
166 if (VAPI_OK != (rv = vapi_ctx_alloc (&vapi_ctx)))
168 throw std::bad_alloc ();
171 events.reserve (vapi_get_message_count () + 1);
174 Connection (const Connection &) = delete;
178 vapi_ctx_free (vapi_ctx);
179 #if VAPI_CPP_DEBUG_LEAKS
180 for (auto x : shm_data_set)
182 printf ("Leaked shm_data@%p!\n", x);
188 * @brief check if message identified by it's message id is known by the
189 * vpp to which the connection is open
191 bool is_msg_available (vapi_msg_id_t type)
193 return vapi_is_msg_available (vapi_ctx, type);
197 * @brief connect to vpp
199 * @param name application name
200 * @param chroot_prefix shared memory prefix
201 * @param max_queued_request max number of outstanding requests queued
202 * @param handle_keepalives handle memclnt_keepalive automatically
204 * @return VAPI_OK on success, other error code on error
206 vapi_error_e connect (const char *name, const char *chroot_prefix,
207 int max_outstanding_requests, int response_queue_size,
208 bool handle_keepalives = true)
210 return vapi_connect (vapi_ctx, name, chroot_prefix,
211 max_outstanding_requests, response_queue_size,
212 VAPI_MODE_BLOCKING, handle_keepalives);
216 * @brief disconnect from vpp
218 * @return VAPI_OK on success, other error code on error
220 vapi_error_e disconnect ()
222 auto x = requests.size ();
225 VAPI_DBG ("popping request @%p", requests.front ());
226 requests.pop_front ();
229 return vapi_disconnect (vapi_ctx);
233 * @brief get event file descriptor
235 * @note this file descriptor becomes readable when messages (from vpp)
236 * are waiting in queue
238 * @param[out] fd pointer to result variable
240 * @return VAPI_OK on success, other error code on error
242 vapi_error_e get_fd (int *fd)
244 return vapi_get_fd (vapi_ctx, fd);
248 * @brief wait for responses from vpp and assign them to appropriate objects
250 * @param limit stop dispatch after the limit object received it's response
252 * @return VAPI_OK on success, other error code on error
254 vapi_error_e dispatch (const Common_req *limit = nullptr, u32 time = 5)
256 std::lock_guard<std::mutex> lock (dispatch_mutex);
257 vapi_error_e rv = VAPI_OK;
258 bool loop_again = true;
262 size_t shm_data_size;
263 rv = vapi_recv (vapi_ctx, &shm_data, &shm_data_size, SVM_Q_TIMEDWAIT,
269 #if VAPI_CPP_DEBUG_LEAKS
270 on_shm_data_alloc (shm_data);
272 std::lock_guard<std::recursive_mutex> requests_lock (requests_mutex);
273 std::lock_guard<std::recursive_mutex> events_lock (events_mutex);
274 vapi_msg_id_t id = vapi_lookup_vapi_msg_id_t (
275 vapi_ctx, be16toh (*static_cast<u16 *> (shm_data)));
276 bool has_context = vapi_msg_is_with_context (id);
277 bool break_dispatch = false;
278 Common_req *matching_req = nullptr;
281 u32 context = *reinterpret_cast<u32 *> (
282 (static_cast<u8 *> (shm_data) + vapi_get_context_offset (id)));
283 const auto x = requests.front ();
285 if (context == x->context)
287 std::tie (rv, break_dispatch) =
288 x->assign_response (id, shm_data);
292 std::tie (rv, break_dispatch) =
293 x->assign_response (id, nullptr);
297 requests.pop_front ();
304 std::tie (rv, break_dispatch) =
305 events[id]->assign_response (id, shm_data);
306 matching_req = events[id];
313 if ((matching_req && matching_req == limit && break_dispatch) ||
318 loop_again = !requests.empty () || (event_count > 0);
324 * @brief convenience wrapper function
326 vapi_error_e dispatch (const Common_req &limit)
328 return dispatch (&limit);
332 * @brief wait for response to a specific request
334 * @param req request to wait for response for
336 * @return VAPI_OK on success, other error code on error
338 vapi_error_e wait_for_response (const Common_req &req)
340 if (RESPONSE_READY == req.get_response_state ())
344 return dispatch (req);
348 void msg_free (void *shm_data)
350 #if VAPI_CPP_DEBUG_LEAKS
351 on_shm_data_free (shm_data);
353 vapi_msg_free (vapi_ctx, shm_data);
356 template <template <typename XReq, typename XResp, typename... XArgs>
358 typename Req, typename Resp, typename... Args>
359 vapi_error_e send (X<Req, Resp, Args...> *req)
366 req_context_counter.fetch_add (1, std::memory_order_relaxed);
367 req->request.shm_data->header.context = req_context;
368 vapi_swap_to_be<Req> (req->request.shm_data);
369 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
370 vapi_error_e rv = vapi_send (vapi_ctx, req->request.shm_data);
373 VAPI_DBG ("Push %p", req);
374 requests.emplace_back (req);
375 req->set_context (req_context);
376 #if VAPI_CPP_DEBUG_LEAKS
377 on_shm_data_free (req->request.shm_data);
379 req->request.shm_data = nullptr; /* consumed by vapi_send */
383 vapi_swap_to_host<Req> (req->request.shm_data);
388 template <template <typename XReq, typename XResp, typename... XArgs>
390 typename Req, typename Resp, typename... Args>
391 vapi_error_e send_with_control_ping (X<Req, Resp, Args...> *req)
398 req_context_counter.fetch_add (1, std::memory_order_relaxed);
399 req->request.shm_data->header.context = req_context;
400 vapi_swap_to_be<Req> (req->request.shm_data);
401 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
402 vapi_error_e rv = vapi_send_with_control_ping (
403 vapi_ctx, req->request.shm_data, req_context);
406 VAPI_DBG ("Push %p", req);
407 requests.emplace_back (req);
408 req->set_context (req_context);
409 #if VAPI_CPP_DEBUG_LEAKS
410 on_shm_data_free (req->request.shm_data);
412 req->request.shm_data = nullptr; /* consumed by vapi_send */
416 vapi_swap_to_host<Req> (req->request.shm_data);
421 void unregister_request (Common_req *request)
423 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
424 std::remove (requests.begin (), requests.end (), request);
427 template <typename M> void register_event (Event_registration<M> *event)
429 const vapi_msg_id_t id = M::get_msg_id ();
430 std::lock_guard<std::recursive_mutex> lock (events_mutex);
435 template <typename M> void unregister_event (Event_registration<M> *event)
437 const vapi_msg_id_t id = M::get_msg_id ();
438 std::lock_guard<std::recursive_mutex> lock (events_mutex);
439 events[id] = nullptr;
444 std::atomic_ulong req_context_counter;
445 std::mutex dispatch_mutex;
447 std::recursive_mutex requests_mutex;
448 std::recursive_mutex events_mutex;
449 std::deque<Common_req *> requests;
450 std::vector<Common_req *> events;
453 template <typename Req, typename Resp, typename... Args>
454 friend class Request;
456 template <typename Req, typename Resp, typename... Args> friend class Dump;
458 template <typename Req, typename Resp, typename StreamMessage,
462 template <typename M> friend class Result_set;
464 template <typename M> friend class Event_registration;
466 template <typename M, typename... Args>
467 friend M *vapi_alloc (Connection &con, Args...);
469 template <typename M> friend class Msg;
471 #if VAPI_CPP_DEBUG_LEAKS
472 void on_shm_data_alloc (void *shm_data)
476 auto pos = shm_data_set.find (shm_data);
477 if (pos == shm_data_set.end ())
479 shm_data_set.insert (shm_data);
483 printf ("Double-add shm_data @%p!\n", shm_data);
488 void on_shm_data_free (void *shm_data)
490 auto pos = shm_data_set.find (shm_data);
491 if (pos == shm_data_set.end ())
493 printf ("Freeing untracked shm_data @%p!\n", shm_data);
497 shm_data_set.erase (pos);
500 std::unordered_set<void *> shm_data_set;
504 template <typename Req, typename Resp, typename... Args> class Request;
506 template <typename Req, typename Resp, typename... Args> class Dump;
508 template <typename Req, typename Resp, typename StreamMessage,
512 template <class, class = void> struct vapi_has_payload_trait : std::false_type
516 template <class... T> using vapi_void_t = void;
519 struct vapi_has_payload_trait<T, vapi_void_t<decltype (&T::payload)>>
524 template <typename M> void vapi_msg_set_msg_id (vapi_msg_id_t id)
526 Msg<M>::set_msg_id (id);
530 * Class representing a message stored in shared memory
532 template <typename M> class Msg
535 Msg (const Msg &) = delete;
539 VAPI_DBG ("Destroy Msg<%s>@%p, shm_data@%p",
540 vapi_get_msg_name (get_msg_id ()), this, shm_data);
543 con.get ().msg_free (shm_data);
548 static vapi_msg_id_t get_msg_id ()
550 return *msg_id_holder ();
553 template <typename X = M>
554 typename std::enable_if<vapi_has_payload_trait<X>::value,
555 decltype (X::payload) &>::type
558 return shm_data->payload;
562 Msg (Msg<M> &&msg) : con{msg.con}
564 VAPI_DBG ("Move construct Msg<%s> from msg@%p to msg@%p, shm_data@%p",
565 vapi_get_msg_name (get_msg_id ()), &msg, this, msg.shm_data);
566 shm_data = msg.shm_data;
567 msg.shm_data = nullptr;
570 Msg<M> &operator= (Msg<M> &&msg)
572 VAPI_DBG ("Move assign Msg<%s> from msg@%p to msg@%p, shm_data@%p",
573 vapi_get_msg_name (get_msg_id ()), &msg, this, msg.shm_data);
574 con.get ().msg_free (shm_data);
576 shm_data = msg.shm_data;
577 msg.shm_data = nullptr;
581 struct Msg_allocator : std::allocator<Msg<M>>
583 template <class U, class... Args> void construct (U *p, Args &&... args)
585 ::new ((void *)p) U (std::forward<Args> (args)...);
588 template <class U> struct rebind
590 typedef Msg_allocator other;
594 static void set_msg_id (vapi_msg_id_t id)
596 assert ((VAPI_INVALID_MSG_ID == *msg_id_holder ()) ||
597 (id == *msg_id_holder ()));
598 *msg_id_holder () = id;
601 static vapi_msg_id_t *msg_id_holder ()
603 static vapi_msg_id_t my_id{VAPI_INVALID_MSG_ID};
607 Msg (Connection &con, void *shm_data) : con{con}
609 if (!con.is_msg_available (get_msg_id ()))
611 throw Msg_not_available_exception ();
613 this->shm_data = static_cast<shm_data_type *> (shm_data);
614 VAPI_DBG ("New Msg<%s>@%p shm_data@%p", vapi_get_msg_name (get_msg_id ()),
618 void assign_response (vapi_msg_id_t resp_id, void *shm_data)
620 assert (nullptr == this->shm_data);
621 if (resp_id != get_msg_id ())
623 throw Unexpected_msg_id_exception ();
625 this->shm_data = static_cast<M *> (shm_data);
626 vapi_swap_to_host<M> (this->shm_data);
627 VAPI_DBG ("Assign response to Msg<%s>@%p shm_data@%p",
628 vapi_get_msg_name (get_msg_id ()), this, shm_data);
631 std::reference_wrapper<Connection> con;
632 using shm_data_type = M;
633 shm_data_type *shm_data;
635 friend class Connection;
637 template <typename Req, typename Resp, typename... Args>
638 friend class Request;
640 template <typename Req, typename Resp, typename... Args> friend class Dump;
642 template <typename Req, typename Resp, typename StreamMessage,
646 template <typename X> friend class Event_registration;
648 template <typename X> friend class Result_set;
650 friend struct Msg_allocator;
652 template <typename X> friend void vapi_msg_set_msg_id (vapi_msg_id_t id);
656 * Class representing a simple request - with a single response message
658 template <typename Req, typename Resp, typename... Args>
659 class Request : public Common_req
662 Request (Connection &con, Args... args,
663 std::function<vapi_error_e (Request<Req, Resp, Args...> &)>
665 : Common_req{ con }, callback{ std::move (callback) },
666 request{ con, vapi_alloc<Req> (con, args...) }, response{ con,
671 Request (const Request &) = delete;
675 if (RESPONSE_NOT_READY == get_response_state ())
677 con.unregister_request (this);
681 vapi_error_e execute ()
683 return con.send (this);
686 const Msg<Req> &get_request (void) const
691 const Msg<Resp> &get_response (void)
697 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
700 assert (RESPONSE_NOT_READY == get_response_state ());
701 response.assign_response (id, shm_data);
702 set_response_state (RESPONSE_READY);
703 if (nullptr != callback)
705 return std::make_pair (callback (*this), true);
707 return std::make_pair (VAPI_OK, true);
709 std::function<vapi_error_e (Request<Req, Resp, Args...> &)> callback;
713 friend class Connection;
717 * Class representing iterable set of responses of the same type
719 template <typename M> class Result_set
726 Result_set (const Result_set &) = delete;
728 bool is_complete () const
738 using const_iterator =
739 typename std::vector<Msg<M>,
740 typename Msg<M>::Msg_allocator>::const_iterator;
742 const_iterator begin () const
747 const_iterator end () const
752 void free_response (const_iterator pos)
757 void free_all_responses ()
763 void mark_complete ()
768 void assign_response (vapi_msg_id_t resp_id, void *shm_data)
770 if (resp_id != Msg<M>::get_msg_id ())
773 throw Unexpected_msg_id_exception ();
778 vapi_swap_to_host<M> (static_cast<M *> (shm_data));
779 set.emplace_back (con, shm_data);
780 VAPI_DBG ("Result_set@%p emplace_back shm_data@%p", this, shm_data);
784 Result_set (Connection &con) : con (con), complete{false}
790 std::vector<Msg<M>, typename Msg<M>::Msg_allocator> set;
792 template <typename Req, typename Resp, typename StreamMessage,
796 template <typename Req, typename Resp, typename... Args> friend class Dump;
798 template <typename X> friend class Event_registration;
802 * Class representing a RPC request - zero or more identical responses to a
803 * single request message with a response
805 template <typename Req, typename Resp, typename StreamMessage,
807 class Stream : public Common_req
811 Connection &con, Args... args,
812 std::function<vapi_error_e (Stream<Req, Resp, StreamMessage, Args...> &)>
814 : Common_req{ con }, request{ con, vapi_alloc<Req> (con, args...) },
815 response{ con, nullptr }, result_set{ con }, callback{ std::move (cb) }
819 Stream (const Stream &) = delete;
821 virtual ~Stream () {}
823 virtual std::tuple<vapi_error_e, bool>
824 assign_response (vapi_msg_id_t id, void *shm_data)
826 if (id == response.get_msg_id ())
828 response.assign_response (id, shm_data);
829 result_set.mark_complete ();
830 set_response_state (RESPONSE_READY);
831 if (nullptr != callback)
833 return std::make_pair (callback (*this), true);
835 return std::make_pair (VAPI_OK, true);
839 result_set.assign_response (id, shm_data);
841 return std::make_pair (VAPI_OK, false);
847 return con.send (this);
862 using resp_type = typename Msg<StreamMessage>::shm_data_type;
864 const Result_set<StreamMessage> &
865 get_result_set (void) const
873 Result_set<StreamMessage> result_set;
874 std::function<vapi_error_e (Stream<Req, Resp, StreamMessage, Args...> &)>
877 friend class Connection;
878 friend class Result_set<StreamMessage>;
882 * Class representing a dump request - zero or more identical responses to a
883 * single request message
885 template <typename Req, typename Resp, typename... Args>
886 class Dump : public Common_req
889 Dump (Connection &con, Args... args,
890 std::function<vapi_error_e (Dump<Req, Resp, Args...> &)> callback =
892 : Common_req{ con }, request{ con, vapi_alloc<Req> (con, args...) },
893 result_set{ con }, callback{ std::move (callback) }
897 Dump (const Dump &) = delete;
903 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
906 if (id == vapi_msg_id_control_ping_reply)
908 con.msg_free (shm_data);
909 result_set.mark_complete ();
910 set_response_state (RESPONSE_READY);
911 if (nullptr != callback)
913 return std::make_pair (callback (*this), true);
915 return std::make_pair (VAPI_OK, true);
919 result_set.assign_response (id, shm_data);
921 return std::make_pair (VAPI_OK, false);
924 vapi_error_e execute ()
926 return con.send_with_control_ping (this);
929 Msg<Req> &get_request (void)
934 using resp_type = typename Msg<Resp>::shm_data_type;
936 const Result_set<Resp> &get_result_set (void) const
943 Result_set<resp_type> result_set;
944 std::function<vapi_error_e (Dump<Req, Resp, Args...> &)> callback;
946 friend class Connection;
950 * Class representing event registration - incoming events (messages) from
951 * vpp as a result of a subscription (typically a want_* simple request)
953 template <typename M> class Event_registration : public Common_req
958 std::function<vapi_error_e (Event_registration<M> &)> callback = nullptr)
959 : Common_req{ con }, result_set{ con }, callback{ std::move (callback) }
961 if (!con.is_msg_available (M::get_msg_id ()))
963 throw Msg_not_available_exception ();
965 con.register_event (this);
968 Event_registration (const Event_registration &) = delete;
970 virtual ~Event_registration ()
972 con.unregister_event (this);
975 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
978 result_set.assign_response (id, shm_data);
979 if (nullptr != callback)
981 return std::make_pair (callback (*this), true);
983 return std::make_pair (VAPI_OK, true);
986 using resp_type = typename M::shm_data_type;
988 Result_set<resp_type> &get_result_set (void)
994 Result_set<resp_type> result_set;
995 std::function<vapi_error_e (Event_registration<M> &)> callback;
1002 * fd.io coding-style-patch-verification: ON
1005 * eval: (c-set-style "gnu")