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
198 * @param handle_keepalives handle memclnt_keepalive automatically
200 * @return VAPI_OK on success, other error code on error
202 vapi_error_e connect (const char *name, const char *chroot_prefix,
203 int max_outstanding_requests, int response_queue_size,
204 bool handle_keepalives = true)
206 return vapi_connect (vapi_ctx, name, chroot_prefix,
207 max_outstanding_requests, response_queue_size,
208 VAPI_MODE_BLOCKING, handle_keepalives);
212 * @brief disconnect from vpp
214 * @return VAPI_OK on success, other error code on error
216 vapi_error_e disconnect ()
218 auto x = requests.size ();
221 VAPI_DBG ("popping request @%p", requests.front ());
222 requests.pop_front ();
225 return vapi_disconnect (vapi_ctx);
229 * @brief get event file descriptor
231 * @note this file descriptor becomes readable when messages (from vpp)
232 * are waiting in queue
234 * @param[out] fd pointer to result variable
236 * @return VAPI_OK on success, other error code on error
238 vapi_error_e get_fd (int *fd)
240 return vapi_get_fd (vapi_ctx, fd);
244 * @brief wait for responses from vpp and assign them to appropriate objects
246 * @param limit stop dispatch after the limit object received it's response
248 * @return VAPI_OK on success, other error code on error
250 vapi_error_e dispatch (const Common_req *limit = nullptr, u32 time = 5)
252 std::lock_guard<std::mutex> lock (dispatch_mutex);
253 vapi_error_e rv = VAPI_OK;
254 bool loop_again = true;
258 size_t shm_data_size;
259 rv = vapi_recv (vapi_ctx, &shm_data, &shm_data_size, SVM_Q_TIMEDWAIT,
265 #if VAPI_CPP_DEBUG_LEAKS
266 on_shm_data_alloc (shm_data);
268 std::lock_guard<std::recursive_mutex> requests_lock (requests_mutex);
269 std::lock_guard<std::recursive_mutex> events_lock (events_mutex);
270 vapi_msg_id_t id = vapi_lookup_vapi_msg_id_t (
271 vapi_ctx, be16toh (*static_cast<u16 *> (shm_data)));
272 bool has_context = vapi_msg_is_with_context (id);
273 bool break_dispatch = false;
274 Common_req *matching_req = nullptr;
277 u32 context = *reinterpret_cast<u32 *> (
278 (static_cast<u8 *> (shm_data) + vapi_get_context_offset (id)));
279 const auto x = requests.front ();
281 if (context == x->context)
283 std::tie (rv, break_dispatch) =
284 x->assign_response (id, shm_data);
288 std::tie (rv, break_dispatch) =
289 x->assign_response (id, nullptr);
293 requests.pop_front ();
300 std::tie (rv, break_dispatch) =
301 events[id]->assign_response (id, shm_data);
302 matching_req = events[id];
309 if ((matching_req && matching_req == limit && break_dispatch) ||
314 loop_again = !requests.empty () || (event_count > 0);
320 * @brief convenience wrapper function
322 vapi_error_e dispatch (const Common_req &limit)
324 return dispatch (&limit);
328 * @brief wait for response to a specific request
330 * @param req request to wait for response for
332 * @return VAPI_OK on success, other error code on error
334 vapi_error_e wait_for_response (const Common_req &req)
336 if (RESPONSE_READY == req.get_response_state ())
340 return dispatch (req);
344 void msg_free (void *shm_data)
346 #if VAPI_CPP_DEBUG_LEAKS
347 on_shm_data_free (shm_data);
349 vapi_msg_free (vapi_ctx, shm_data);
352 template <template <typename XReq, typename XResp, typename... XArgs>
354 typename Req, typename Resp, typename... Args>
355 vapi_error_e send (X<Req, Resp, Args...> *req)
362 req_context_counter.fetch_add (1, std::memory_order_relaxed);
363 req->request.shm_data->header.context = req_context;
364 vapi_swap_to_be<Req> (req->request.shm_data);
365 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
366 vapi_error_e rv = vapi_send (vapi_ctx, req->request.shm_data);
369 VAPI_DBG ("Push %p", req);
370 requests.emplace_back (req);
371 req->set_context (req_context);
372 #if VAPI_CPP_DEBUG_LEAKS
373 on_shm_data_free (req->request.shm_data);
375 req->request.shm_data = nullptr; /* consumed by vapi_send */
379 vapi_swap_to_host<Req> (req->request.shm_data);
384 template <template <typename XReq, typename XResp, typename... XArgs>
386 typename Req, typename Resp, typename... Args>
387 vapi_error_e send_with_control_ping (X<Req, Resp, Args...> *req)
394 req_context_counter.fetch_add (1, std::memory_order_relaxed);
395 req->request.shm_data->header.context = req_context;
396 vapi_swap_to_be<Req> (req->request.shm_data);
397 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
398 vapi_error_e rv = vapi_send_with_control_ping (
399 vapi_ctx, req->request.shm_data, req_context);
402 VAPI_DBG ("Push %p", req);
403 requests.emplace_back (req);
404 req->set_context (req_context);
405 #if VAPI_CPP_DEBUG_LEAKS
406 on_shm_data_free (req->request.shm_data);
408 req->request.shm_data = nullptr; /* consumed by vapi_send */
412 vapi_swap_to_host<Req> (req->request.shm_data);
417 void unregister_request (Common_req *request)
419 std::lock_guard<std::recursive_mutex> lock (requests_mutex);
420 std::remove (requests.begin (), requests.end (), request);
423 template <typename M> void register_event (Event_registration<M> *event)
425 const vapi_msg_id_t id = M::get_msg_id ();
426 std::lock_guard<std::recursive_mutex> lock (events_mutex);
431 template <typename M> void unregister_event (Event_registration<M> *event)
433 const vapi_msg_id_t id = M::get_msg_id ();
434 std::lock_guard<std::recursive_mutex> lock (events_mutex);
435 events[id] = nullptr;
440 std::atomic_ulong req_context_counter;
441 std::mutex dispatch_mutex;
443 std::recursive_mutex requests_mutex;
444 std::recursive_mutex events_mutex;
445 std::deque<Common_req *> requests;
446 std::vector<Common_req *> events;
449 template <typename Req, typename Resp, typename... Args>
450 friend class Request;
452 template <typename Req, typename Resp, typename... Args> friend class Dump;
454 template <typename M> friend class Result_set;
456 template <typename M> friend class Event_registration;
458 template <typename M, typename... Args>
459 friend M *vapi_alloc (Connection &con, Args...);
461 template <typename M> friend class Msg;
463 #if VAPI_CPP_DEBUG_LEAKS
464 void on_shm_data_alloc (void *shm_data)
468 auto pos = shm_data_set.find (shm_data);
469 if (pos == shm_data_set.end ())
471 shm_data_set.insert (shm_data);
475 printf ("Double-add shm_data @%p!\n", shm_data);
480 void on_shm_data_free (void *shm_data)
482 auto pos = shm_data_set.find (shm_data);
483 if (pos == shm_data_set.end ())
485 printf ("Freeing untracked shm_data @%p!\n", shm_data);
489 shm_data_set.erase (pos);
492 std::unordered_set<void *> shm_data_set;
496 template <typename Req, typename Resp, typename... Args> class Request;
498 template <typename Req, typename Resp, typename... Args> class Dump;
500 template <class, class = void> struct vapi_has_payload_trait : std::false_type
504 template <class... T> using vapi_void_t = void;
507 struct vapi_has_payload_trait<T, vapi_void_t<decltype (&T::payload)>>
512 template <typename M> void vapi_msg_set_msg_id (vapi_msg_id_t id)
514 Msg<M>::set_msg_id (id);
518 * Class representing a message stored in shared memory
520 template <typename M> class Msg
523 Msg (const Msg &) = delete;
527 VAPI_DBG ("Destroy Msg<%s>@%p, shm_data@%p",
528 vapi_get_msg_name (get_msg_id ()), this, shm_data);
531 con.get ().msg_free (shm_data);
536 static vapi_msg_id_t get_msg_id ()
538 return *msg_id_holder ();
541 template <typename X = M>
542 typename std::enable_if<vapi_has_payload_trait<X>::value,
543 decltype (X::payload) &>::type
546 return shm_data->payload;
550 Msg (Msg<M> &&msg) : con{msg.con}
552 VAPI_DBG ("Move construct Msg<%s> from msg@%p to msg@%p, shm_data@%p",
553 vapi_get_msg_name (get_msg_id ()), &msg, this, msg.shm_data);
554 shm_data = msg.shm_data;
555 msg.shm_data = nullptr;
558 Msg<M> &operator= (Msg<M> &&msg)
560 VAPI_DBG ("Move assign Msg<%s> from msg@%p to msg@%p, shm_data@%p",
561 vapi_get_msg_name (get_msg_id ()), &msg, this, msg.shm_data);
562 con.get ().msg_free (shm_data);
564 shm_data = msg.shm_data;
565 msg.shm_data = nullptr;
569 struct Msg_allocator : std::allocator<Msg<M>>
571 template <class U, class... Args> void construct (U *p, Args &&... args)
573 ::new ((void *)p) U (std::forward<Args> (args)...);
576 template <class U> struct rebind
578 typedef Msg_allocator other;
582 static void set_msg_id (vapi_msg_id_t id)
584 assert ((VAPI_INVALID_MSG_ID == *msg_id_holder ()) ||
585 (id == *msg_id_holder ()));
586 *msg_id_holder () = id;
589 static vapi_msg_id_t *msg_id_holder ()
591 static vapi_msg_id_t my_id{VAPI_INVALID_MSG_ID};
595 Msg (Connection &con, void *shm_data) : con{con}
597 if (!con.is_msg_available (get_msg_id ()))
599 throw Msg_not_available_exception ();
601 this->shm_data = static_cast<shm_data_type *> (shm_data);
602 VAPI_DBG ("New Msg<%s>@%p shm_data@%p", vapi_get_msg_name (get_msg_id ()),
606 void assign_response (vapi_msg_id_t resp_id, void *shm_data)
608 assert (nullptr == this->shm_data);
609 if (resp_id != get_msg_id ())
611 throw Unexpected_msg_id_exception ();
613 this->shm_data = static_cast<M *> (shm_data);
614 vapi_swap_to_host<M> (this->shm_data);
615 VAPI_DBG ("Assign response to Msg<%s>@%p shm_data@%p",
616 vapi_get_msg_name (get_msg_id ()), this, shm_data);
619 std::reference_wrapper<Connection> con;
620 using shm_data_type = M;
621 shm_data_type *shm_data;
623 friend class Connection;
625 template <typename Req, typename Resp, typename... Args>
626 friend class Request;
628 template <typename Req, typename Resp, typename... Args> friend class Dump;
630 template <typename X> friend class Event_registration;
632 template <typename X> friend class Result_set;
634 friend struct Msg_allocator;
636 template <typename X> friend void vapi_msg_set_msg_id (vapi_msg_id_t id);
640 * Class representing a simple request - with a single response message
642 template <typename Req, typename Resp, typename... Args>
643 class Request : public Common_req
646 Request (Connection &con, Args... args,
647 std::function<vapi_error_e (Request<Req, Resp, Args...> &)>
649 : Common_req{con}, callback{callback},
650 request{con, vapi_alloc<Req> (con, args...)}, response{con, nullptr}
654 Request (const Request &) = delete;
658 if (RESPONSE_NOT_READY == get_response_state ())
660 con.unregister_request (this);
664 vapi_error_e execute ()
666 return con.send (this);
669 const Msg<Req> &get_request (void) const
674 const Msg<Resp> &get_response (void)
680 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
683 assert (RESPONSE_NOT_READY == get_response_state ());
684 response.assign_response (id, shm_data);
685 set_response_state (RESPONSE_READY);
686 if (nullptr != callback)
688 return std::make_pair (callback (*this), true);
690 return std::make_pair (VAPI_OK, true);
692 std::function<vapi_error_e (Request<Req, Resp, Args...> &)> callback;
696 friend class Connection;
700 * Class representing iterable set of responses of the same type
702 template <typename M> class Result_set
709 Result_set (const Result_set &) = delete;
711 bool is_complete () const
721 using const_iterator =
722 typename std::vector<Msg<M>,
723 typename Msg<M>::Msg_allocator>::const_iterator;
725 const_iterator begin () const
730 const_iterator end () const
735 void free_response (const_iterator pos)
740 void free_all_responses ()
746 void mark_complete ()
751 void assign_response (vapi_msg_id_t resp_id, void *shm_data)
753 if (resp_id != Msg<M>::get_msg_id ())
756 throw Unexpected_msg_id_exception ();
761 vapi_swap_to_host<M> (static_cast<M *> (shm_data));
762 set.emplace_back (con, shm_data);
763 VAPI_DBG ("Result_set@%p emplace_back shm_data@%p", this, shm_data);
767 Result_set (Connection &con) : con (con), complete{false}
773 std::vector<Msg<M>, typename Msg<M>::Msg_allocator> set;
775 template <typename Req, typename Resp, typename... Args> friend class Dump;
777 template <typename X> friend class Event_registration;
781 * Class representing a dump request - zero or more identical responses to a
782 * single request message
784 template <typename Req, typename Resp, typename... Args>
785 class Dump : public Common_req
788 Dump (Connection &con, Args... args,
789 std::function<vapi_error_e (Dump<Req, Resp, Args...> &)> callback =
791 : Common_req{con}, request{con, vapi_alloc<Req> (con, args...)},
792 result_set{con}, callback{callback}
796 Dump (const Dump &) = delete;
802 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
805 if (id == vapi_msg_id_control_ping_reply)
807 con.msg_free (shm_data);
808 result_set.mark_complete ();
809 set_response_state (RESPONSE_READY);
810 if (nullptr != callback)
812 return std::make_pair (callback (*this), true);
814 return std::make_pair (VAPI_OK, true);
818 result_set.assign_response (id, shm_data);
820 return std::make_pair (VAPI_OK, false);
823 vapi_error_e execute ()
825 return con.send_with_control_ping (this);
828 Msg<Req> &get_request (void)
833 using resp_type = typename Msg<Resp>::shm_data_type;
835 const Result_set<Resp> &get_result_set (void) const
842 Result_set<resp_type> result_set;
843 std::function<vapi_error_e (Dump<Req, Resp, Args...> &)> callback;
845 friend class Connection;
849 * Class representing event registration - incoming events (messages) from
850 * vpp as a result of a subscription (typically a want_* simple request)
852 template <typename M> class Event_registration : public Common_req
857 std::function<vapi_error_e (Event_registration<M> &)> callback = nullptr)
858 : Common_req{con}, result_set{con}, callback{callback}
860 if (!con.is_msg_available (M::get_msg_id ()))
862 throw Msg_not_available_exception ();
864 con.register_event (this);
867 Event_registration (const Event_registration &) = delete;
869 virtual ~Event_registration ()
871 con.unregister_event (this);
874 virtual std::tuple<vapi_error_e, bool> assign_response (vapi_msg_id_t id,
877 result_set.assign_response (id, shm_data);
878 if (nullptr != callback)
880 return std::make_pair (callback (*this), true);
882 return std::make_pair (VAPI_OK, true);
885 using resp_type = typename M::shm_data_type;
887 Result_set<resp_type> &get_result_set (void)
893 Result_set<resp_type> result_set;
894 std::function<vapi_error_e (Event_registration<M> &)> callback;
901 * fd.io coding-style-patch-verification: ON
904 * eval: (c-set-style "gnu")