docs: better docs, mv doxygen to sphinx
[vpp.git] / docs / usecases / webapp.rst
1 Web applications with VPP
2 =========================
3
4 Vpp includes a versatile http/https “static” server plugin. We quote the
5 word static in the previous sentence because the server is easily
6 extended. This note describes how to build a Hugo site which includes
7 both monitoring and control functions.
8
9 Let’s assume that we have a vpp data-plane plugin which needs a
10 monitoring and control web application. Here’s how to build one.
11
12 Step 1: Add URL handlers
13 ------------------------
14
15 Individual URL handlers are pretty straightforward. You can return just
16 about anything you like, but as we work through the example you’ll see
17 why returning data in .json format tends to work out pretty well.
18
19 ::
20
21        static int
22        handle_get_status (http_builtin_method_type_t reqtype,
23                         u8 * request, http_session_t * hs)
24        {
25          my_main_t *mm = &my_main;
26          u8 *s = 0;
27
28          /* Construct a .json reply */
29          s = format (s, "{\"status\": {");
30          s = format (s, "   \"thing1\": \"%s\",", mm->thing1_value_string);
31          s = format (s, "   \"thing2\": \"%s\",", mm->thing2_value_string);
32          /* ... etc ... */
33          s = format (s, "   \"lastthing\": \"%s\"", mm->last_value_string);
34          s = format (s, "}}");
35
36          /* And tell the static server plugin how to send the results */
37          hs->data = s;
38          hs->data_offset = 0;
39          hs->cache_pool_index = ~0;
40          hs->free_data = 1; /* free s when done with it, in the framework */
41          return 0;
42        }
43
44 Words to the Wise: Chrome has a very nice set of debugging tools. Select
45 “More Tools -> Developer Tools”. Right-hand sidebar appears with html
46 source code, a javascript debugger, network results including .json
47 objects, and so on.
48
49 Note: .json object format is **intolerant** of both missing and extra
50 commas, missing and extra curly-braces. It’s easy to waste a
51 considerable amount of time debugging .json bugs.
52
53 Step 2: Register URL handlers with the server
54 ---------------------------------------------
55
56 Call http_static_server_register_builtin_handler() as shown. It’s likely
57 but not guaranteed that the static server plugin will be available.
58
59 ::
60
61        int
62        plugin_url_init (vlib_main_t * vm)
63        {
64          void (*fp) (void *, char *, int);
65
66          /* Look up the builtin URL registration handler */
67          fp = vlib_get_plugin_symbol ("http_static_plugin.so",
68                           "http_static_server_register_builtin_handler");
69
70          if (fp == 0)
71            {
72              clib_warning ("http_static_plugin.so not loaded...");
73              return -1;
74            }
75
76          (*fp) (handle_get_status, "status.json", HTTP_BUILTIN_METHOD_GET);
77          (*fp) (handle_get_run, "run.json", HTTP_BUILTIN_METHOD_GET);
78          (*fp) (handle_get_reset, "reset.json", HTTP_BUILTIN_METHOD_GET);
79          (*fp) (handle_get_stop, "stop.json", HTTP_BUILTIN_METHOD_GET);
80          return 0;
81          }
82
83 Make sure to start the http static server **before** calling
84 plugin_url_init(…), or the registrations will disappear.
85
86 Step 3: Install Hugo, pick a theme, and create a site
87 -----------------------------------------------------
88
89 Please refer to the Hugo documentation.
90
91 See `the Hugo Quick Start
92 Page <https://gohugo.io/getting-started/quick-start>`__. Prebuilt binary
93 artifacts for many different environments are available on `the Hugo
94 release page <https://github.com/gohugoio/hugo/releases>`__.
95
96 To pick a theme, visit `the Hugo Theme
97 site <https://themes.gohugo.io>`__. Decide what you need your site to
98 look like. Stay away from complex themes unless you’re prepared to spend
99 considerable time tweaking and tuning.
100
101 The “Introduction” theme is a good choice for a simple site, YMMV.
102
103 Step 4: Create a “rawhtml” shortcode
104 ------------------------------------
105
106 Once you’ve initialized your new site, create the directory
107 /layouts/shortcodes. Create the file “rawhtml.html” in that directory,
108 with the following contents:
109
110 ::
111
112        <!-- raw html -->
113        {{.Inner}}
114
115 This is a key trick which allows a static Hugo site to include
116 javascript code.
117
118 Step 5: create Hugo content which interacts with vpp
119 ----------------------------------------------------
120
121 Now it’s time to do some web front-end coding in javascript. Of course,
122 you can create static text, images, etc. as described in the Hugo
123 documentation. Nothing changes in that respect.
124
125 To include dynamically-generated data in your Hugo pages, splat down
126 some
127
128 .. raw:: html
129
130    <div>
131
132 HTML tags, and define a few buttons:
133
134 ::
135
136        {{< rawhtml >}}
137        <div id="Thing1"></div>
138        <div id="Thing2"></div>
139        <div id="Lastthing"></div>
140        <input type="button" value="Run" onclick="runButtonClick()">
141        <input type="button" value="Reset" onclick="resetButtonClick()">
142        <input type="button" value="Stop" onclick="stopButtonClick()">
143        <div id="Message"></div>
144        {{< /rawhtml >}}
145
146 Time for some javascript code to interact with vpp:
147
148 ::
149
150    {{< rawhtml >}}
151    <script>
152    async function getStatusJson() {
153        pump_url = location.href + "status.json";
154        const json = await fetch(pump_url, {
155            method: 'GET',
156            mode: 'no-cors',
157            cache: 'no-cache',
158            headers: {
159                'Content-Type': 'application/json',
160            },
161        })
162        .then((response) => response.json())
163        .catch(function(error) {
164            console.log(error);
165        });
166
167        return json.status;
168    };
169
170    async function sendButton(which) {
171        my_url = location.href + which + ".json";
172        const json = await fetch(my_url, {
173            method: 'GET',
174            mode: 'no-cors',
175            cache: 'no-cache',
176            headers: {
177                'Content-Type': 'application/json',
178            },
179        })
180        .then((response) => response.json())
181        .catch(function(error) {
182            console.log(error);
183        });
184        return json.message;
185    };
186
187    async function getStatus() {
188          const status = await getStatusJson();
189
190          document.getElementById("Thing1").innerHTML = status.thing1;
191          document.getElementById("Thing2").innerHTML = status.thing2;
192          document.getElementById("Lastthing").innerHTML = status.lastthing;
193    };
194
195    async function runButtonClick() {
196          const json = await sendButton("run");
197          document.getElementById("Message").innerHTML = json.Message;
198    }
199
200    async function resetButtonClick() {
201          const json = await sendButton("reset");
202          document.getElementById("Message").innerHTML = json.Message;
203    }
204    async function stopButtonClick() {
205          const json = await sendButton("stop");
206          document.getElementById("Message").innerHTML = json.Message;
207    }
208
209    getStatus();
210
211    </script>
212    {{< /rawhtml >}}
213
214 At this level, javascript coding is pretty simple. Unless you know
215 exactly what you’re doing, please follow the async function / await
216 pattern shown above.
217
218 Step 6: compile the website
219 ---------------------------
220
221 At the top of the website workspace, simply type “hugo”. The compiled
222 website lands in the “public” subdirectory.
223
224 You can use the Hugo static server - with suitable stub javascript code
225 - to see what your site will eventually look like. To start the hugo
226 static server, type “hugo server”. Browse to “http://localhost:1313”.
227
228 Step 7: configure vpp
229 ---------------------
230
231 In terms of command-line args: you may wish to use poll-sleep-usec 100
232 to keep the load average low. Totally appropriate if vpp won’t be
233 processing a lot of packets or handling high-rate http/https traffic.
234
235 ::
236
237       unix {
238         ...
239         poll-sleep-usec 100
240         startup-config ... see below ...
241         ...
242        }
243
244 If you wish to provide an https site, configure tls. The simplest tls
245 configuration uses a built-in test certificate - which will annoy Chrome
246 / Firefox - but it’s sufficient for testing:
247
248 ::
249
250        tls {
251            use-test-cert-in-ca
252        }
253
254 vpp startup configuration
255 ~~~~~~~~~~~~~~~~~~~~~~~~~
256
257 Enable the vpp static server by way of the startup config mentioned
258 above:
259
260 ::
261
262        http static server www-root /myhugosite/public uri tcp://0.0.0.0/2345 cache-size 5m fifo-size 8192
263
264 The www-root must be specified, and must correctly name the compiled
265 hugo site root. If your Hugo site is located at /myhugosite, specify
266 “www-root /myhugosite/public” in the “http static server” stanza. The
267 uri shown above binds to TCP port 2345.
268
269 If you’re using https, use a uri like “tls://0.0.0.0/443” instead of the
270 uri shown above.
271
272 You may want to add a Linux host interface to view the full-up site
273 locally:
274
275 ::
276
277        create tap host-if-name lstack host-ip4-addr 192.168.10.2/24
278        set int ip address tap0 192.168.10.1/24
279        set int state tap0 up