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