vnet: export header files to build the plugins
[vpp.git] / src / plugins / unittest / api_test.c
1 /* SPDX-License-Identifier: Apache-2.0
2  * Copyright(c) 2022 Cisco Systems, Inc.
3  */
4
5 #include <vnet/vnet.h>
6 #include <vnet/plugin/plugin.h>
7
8 #include <vlibapi/api.h>
9 #include <vlibmemory/api.h>
10 #include <vpp/app/version.h>
11 #include <stdbool.h>
12 #include <vapi/vapi.h>
13
14 #include <vapi/memclnt.api.vapi.h>
15 #include <vapi/vlib.api.vapi.h>
16 #include <vapi/vpe.api.vapi.h>
17
18 /*
19  * Example of how to call the VPP binary API from an internal API client.
20  * Using the VAPI C language binding.
21  */
22
23 DEFINE_VAPI_MSG_IDS_VPE_API_JSON;
24
25 /*
26  * Connect an VPP binary API client to VPP API
27  */
28 static vapi_ctx_t
29 connect_to_vpp (void)
30 {
31   vapi_ctx_t ctx;
32   if (vapi_ctx_alloc (&ctx) != VAPI_OK)
33     {
34       clib_warning ("ctx_alloc failed");
35       return 0;
36     }
37   if (vapi_connect_from_vpp (ctx, "apifromplugin", 64, 32, VAPI_MODE_BLOCKING,
38                              true) != VAPI_OK)
39     {
40       clib_warning ("vapi_connect failed");
41       vapi_ctx_free (ctx);
42       return 0;
43     }
44   return ctx;
45 }
46
47 /*
48  * Gets called when the show_version_reply message is received
49  */
50 vapi_error_e
51 show_version_cb (vapi_ctx_t ctx, void *caller_ctx, vapi_error_e rv,
52                  bool is_last, vapi_payload_show_version_reply *p)
53 {
54   if (rv != VAPI_OK)
55     clib_warning ("Return value: %d", rv);
56   fformat (
57     stdout,
58     "show_version_reply: program: `%s', version: `%s', build directory: "
59     "`%s', build date: `%s'\n",
60     p->program, p->version, p->build_directory, p->build_date);
61   return VAPI_OK;
62 }
63
64 static void *
65 api_show_version_blocking_fn (void *args)
66 {
67   vapi_ctx_t ctx;
68
69   if ((ctx = connect_to_vpp ()) == 0)
70     return clib_error_return (0, "API connection failed");
71
72   int called;
73   vapi_msg_show_version *sv = vapi_alloc_show_version (ctx);
74   vapi_error_e vapi_rv = vapi_show_version (ctx, sv, show_version_cb, &called);
75   if (vapi_rv != VAPI_OK)
76     clib_warning ("call failed");
77
78   vapi_disconnect_from_vpp (ctx);
79   vapi_ctx_free (ctx);
80
81   return 0;
82 }
83
84 static clib_error_t *
85 test_api_test_command_fn (vlib_main_t *vm, unformat_input_t *input,
86                           vlib_cli_command_t *cmd)
87 {
88   /* Run call in a pthread */
89   pthread_t thread;
90   int rv = pthread_create (&thread, NULL, api_show_version_blocking_fn, 0);
91   if (rv)
92     {
93       return clib_error_return (0, "API call failed");
94     }
95   return 0;
96 }
97
98 VLIB_CLI_COMMAND (test_api_command, static) = {
99   .path = "test api internal",
100   .short_help = "test internal api client",
101   .function = test_api_test_command_fn,
102 };