vapi: support api clients within vpp process
[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       return 0;
42     }
43   return ctx;
44 }
45
46 /*
47  * Gets called when the show_version_reply message is received
48  */
49 vapi_error_e
50 show_version_cb (vapi_ctx_t ctx, void *caller_ctx, vapi_error_e rv,
51                  bool is_last, vapi_payload_show_version_reply *p)
52 {
53   if (rv != VAPI_OK)
54     clib_warning ("Return value: %d", rv);
55   fformat (
56     stdout,
57     "show_version_reply: program: `%s', version: `%s', build directory: "
58     "`%s', build date: `%s'\n",
59     p->program, p->version, p->build_directory, p->build_date);
60   return VAPI_OK;
61 }
62
63 static void *
64 api_show_version_blocking_fn (void *args)
65 {
66   vapi_ctx_t ctx;
67
68   if ((ctx = connect_to_vpp ()) == 0)
69     return clib_error_return (0, "API connection failed");
70
71   int called;
72   vapi_msg_show_version *sv = vapi_alloc_show_version (ctx);
73   vapi_error_e vapi_rv = vapi_show_version (ctx, sv, show_version_cb, &called);
74   if (vapi_rv != VAPI_OK)
75     clib_warning ("call failed");
76
77   vapi_disconnect_from_vpp (ctx);
78   vapi_ctx_free (ctx);
79
80   return 0;
81 }
82
83 static clib_error_t *
84 test_api_test_command_fn (vlib_main_t *vm, unformat_input_t *input,
85                           vlib_cli_command_t *cmd)
86 {
87   /* Run call in a pthread */
88   pthread_t thread;
89   int rv = pthread_create (&thread, NULL, api_show_version_blocking_fn, 0);
90   if (rv)
91     {
92       return clib_error_return (0, "API call failed");
93     }
94   return 0;
95 }
96
97 VLIB_CLI_COMMAND (test_api_command, static) = {
98   .path = "test api internal",
99   .short_help = "test internal api client",
100   .function = test_api_test_command_fn,
101 };