06f1a9169cdf8658829112206f63b4276003b64a
[vpp.git] / src / vpp / app / vpp_prometheus_export.c
1 /*
2  *------------------------------------------------------------------
3  * vpp_get_stats.c
4  *
5  * Copyright (c) 2018 Cisco and/or its affiliates.
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at:
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *------------------------------------------------------------------
18  */
19
20 #include <arpa/inet.h>
21 #include <sys/epoll.h>
22 #include <stdbool.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <netdb.h>
30 #include <sys/socket.h>
31 #include <vpp-api/client/stat_client.h>
32 #include <vlib/vlib.h>
33 #include <ctype.h>
34
35 /* https://github.com/prometheus/prometheus/wiki/Default-port-allocations */
36 #define SERVER_PORT 9482
37
38 static char *
39 prom_string (char *s)
40 {
41   char *p = s;
42   while (*p)
43     {
44       if (!isalnum (*p))
45         *p = '_';
46       p++;
47     }
48   return s;
49 }
50
51 static void
52 dump_metrics (FILE * stream, u8 ** patterns)
53 {
54   stat_segment_data_t *res;
55   int i, j, k;
56   static u32 *stats = 0;
57
58 retry:
59   res = stat_segment_dump (stats);
60   if (res == 0)
61     {                           /* Memory layout has changed */
62       if (stats)
63         vec_free (stats);
64       stats = stat_segment_ls (patterns);
65       goto retry;
66     }
67
68   for (i = 0; i < vec_len (res); i++)
69     {
70       switch (res[i].type)
71         {
72         case STAT_DIR_TYPE_COUNTER_VECTOR_SIMPLE:
73           fformat (stream, "# TYPE %s counter\n", prom_string (res[i].name));
74           for (k = 0; k < vec_len (res[i].simple_counter_vec); k++)
75             for (j = 0; j < vec_len (res[i].simple_counter_vec[k]); j++)
76               fformat (stream, "%s{thread=\"%d\",interface=\"%d\"} %lld\n",
77                        prom_string (res[i].name), k, j,
78                        res[i].simple_counter_vec[k][j]);
79           break;
80
81         case STAT_DIR_TYPE_COUNTER_VECTOR_COMBINED:
82           fformat (stream, "# TYPE %s_packets counter\n",
83                    prom_string (res[i].name));
84           fformat (stream, "# TYPE %s_bytes counter\n",
85                    prom_string (res[i].name));
86           for (k = 0; k < vec_len (res[i].simple_counter_vec); k++)
87             for (j = 0; j < vec_len (res[i].combined_counter_vec[k]); j++)
88               {
89                 fformat (stream,
90                          "%s_packets{thread=\"%d\",interface=\"%d\"} %lld\n",
91                          prom_string (res[i].name), k, j,
92                          res[i].combined_counter_vec[k][j].packets);
93                 fformat (stream,
94                          "%s_bytes{thread=\"%d\",interface=\"%d\"} %lld\n",
95                          prom_string (res[i].name), k, j,
96                          res[i].combined_counter_vec[k][j].bytes);
97               }
98           break;
99         case STAT_DIR_TYPE_ERROR_INDEX:
100           for (j = 0; j < vec_len (res[i].error_vector); j++)
101             {
102               fformat (stream, "# TYPE %s counter\n",
103                        prom_string (res[i].name));
104               fformat (stream, "%s{thread=\"%d\"} %lld\n",
105                        prom_string (res[i].name), j, res[i].error_vector[j]);
106             }
107           break;
108
109         case STAT_DIR_TYPE_SCALAR_INDEX:
110           fformat (stream, "# TYPE %s counter\n", prom_string (res[i].name));
111           fformat (stream, "%s %.2f\n", prom_string (res[i].name),
112                    res[i].scalar_value);
113           break;
114
115         default:
116           fformat (stderr, "Unknown value %d\n", res[i].type);
117           ;
118         }
119     }
120   stat_segment_data_free (res);
121
122 }
123
124
125 #define ROOTPAGE  "<html><head><title>Metrics exporter</title></head><body><ul><li><a href=\"/metrics\">metrics</a></li></ul></body></html>"
126 #define NOT_FOUND_ERROR "<html><head><title>Document not found</title></head><body><h1>404 - Document not found</h1></body></html>"
127
128 static void
129 http_handler (FILE * stream, u8 ** patterns)
130 {
131   char status[80] = { 0 };
132   if (fgets (status, sizeof (status) - 1, stream) == 0)
133     {
134       fprintf (stderr, "fgets error: %s %s\n", status, strerror (errno));
135       return;
136     }
137   char *saveptr;
138   char *method = strtok_r (status, " \t\r\n", &saveptr);
139   if (method == 0 || strncmp (method, "GET", 4) != 0)
140     {
141       fputs ("HTTP/1.0 405 Method Not Allowed\r\n", stream);
142       return;
143     }
144   char *request_uri = strtok_r (NULL, " \t", &saveptr);
145   char *protocol = strtok_r (NULL, " \t\r\n", &saveptr);
146   if (protocol == 0 || strncmp (protocol, "HTTP/1.", 7) != 0)
147     {
148       fputs ("HTTP/1.0 400 Bad Request\r\n", stream);
149       return;
150     }
151   /* Read the other headers */
152   for (;;)
153     {
154       char header[1024];
155       if (fgets (header, sizeof (header) - 1, stream) == 0)
156         {
157           fprintf (stderr, "fgets error: %s\n", strerror (errno));
158           return;
159         }
160       if (header[0] == '\n' || header[1] == '\n')
161         {
162           break;
163         }
164     }
165   if (strcmp (request_uri, "/") == 0)
166     {
167       fprintf (stream, "HTTP/1.0 200 OK\r\nContent-Length: %lu\r\n\r\n",
168                (unsigned long) strlen (ROOTPAGE));
169       fputs (ROOTPAGE, stream);
170       return;
171     }
172   if (strcmp (request_uri, "/metrics") != 0)
173     {
174       fprintf (stream,
175                "HTTP/1.0 404 Not Found\r\nContent-Length: %lu\r\n\r\n",
176                (unsigned long) strlen (NOT_FOUND_ERROR));
177       fputs (NOT_FOUND_ERROR, stream);
178       return;
179     }
180   fputs ("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n", stream);
181   dump_metrics (stream, patterns);
182 }
183
184 static int
185 start_listen (u16 port)
186 {
187   struct sockaddr_in6 serveraddr;
188   int addrlen = sizeof (serveraddr);
189   int enable = 1;
190
191   int listenfd = socket (AF_INET6, SOCK_STREAM, 0);
192   if (listenfd == -1)
193     {
194       perror ("Failed opening socket");
195       return -1;
196     }
197
198   int rv =
199     setsockopt (listenfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof (int));
200   if (rv < 0)
201     {
202       perror ("Failed setsockopt");
203       close (listenfd);
204       return -1;
205     }
206
207   clib_memset (&serveraddr, 0, sizeof (serveraddr));
208   serveraddr.sin6_family = AF_INET6;
209   serveraddr.sin6_port = htons (port);
210   serveraddr.sin6_addr = in6addr_any;
211
212   if (bind (listenfd, (struct sockaddr *) &serveraddr, addrlen) < 0)
213     {
214       fprintf (stderr, "bind() error %s\n", strerror (errno));
215       close (listenfd);
216       return -1;
217     }
218   if (listen (listenfd, 1000000) != 0)
219     {
220       fprintf (stderr, "listen() error for %s\n", strerror (errno));
221       close (listenfd);
222       return -1;
223     }
224   return listenfd;
225 }
226
227 /* Socket epoll, linux-specific */
228 union my_sockaddr
229 {
230   struct sockaddr_storage storage;
231   struct sockaddr addr;
232   struct sockaddr_in sin_addr;
233   struct sockaddr_in6 sin6_addr;
234 };
235
236
237
238 int
239 main (int argc, char **argv)
240 {
241   unformat_input_t _argv, *a = &_argv;
242   u8 *stat_segment_name, *pattern = 0, **patterns = 0;
243   int rv;
244
245   /* Allocating 32MB heap */
246   clib_mem_init (0, 32 << 20);
247
248   unformat_init_command_line (a, argv);
249
250   stat_segment_name = (u8 *) STAT_SEGMENT_SOCKET_FILE;
251
252   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
253     {
254       if (unformat (a, "socket-name %s", &stat_segment_name))
255         ;
256       else if (unformat (a, "%s", &pattern))
257         {
258           vec_add1 (patterns, pattern);
259         }
260       else
261         {
262           fformat (stderr,
263                    "%s: usage [socket-name <name>] <patterns> ...\n",
264                    argv[0]);
265           exit (1);
266         }
267     }
268
269   if (vec_len (patterns) == 0)
270     {
271       fformat (stderr,
272                "%s: usage [socket-name <name>] <patterns> ...\n", argv[0]);
273       exit (1);
274     }
275
276   rv = stat_segment_connect ((char *) stat_segment_name);
277   if (rv)
278     {
279       fformat (stderr, "Couldn't connect to vpp, does %s exist?\n",
280                stat_segment_name);
281       exit (1);
282     }
283
284   int fd = start_listen (SERVER_PORT);
285   if (fd < 0)
286     {
287       exit (1);
288     }
289   for (;;)
290     {
291       int conn_sock = accept (fd, NULL, NULL);
292       if (conn_sock < 0)
293         {
294           fprintf (stderr, "Accept failed: %s", strerror (errno));
295           continue;
296         }
297       else
298         {
299           struct sockaddr_in6 clientaddr = { 0 };
300           char address[INET6_ADDRSTRLEN];
301           socklen_t addrlen;
302           getpeername (conn_sock, (struct sockaddr *) &clientaddr, &addrlen);
303           if (inet_ntop
304               (AF_INET6, &clientaddr.sin6_addr, address, sizeof (address)))
305             {
306               fprintf (stderr, "Client address is [%s]:%d\n", address,
307                        ntohs (clientaddr.sin6_port));
308             }
309         }
310
311       FILE *stream = fdopen (conn_sock, "r+");
312       if (stream == NULL)
313         {
314           fprintf (stderr, "fdopen error: %s\n", strerror (errno));
315           close (conn_sock);
316           continue;
317         }
318       /* Single reader at the moment */
319       http_handler (stream, patterns);
320       fclose (stream);
321     }
322
323   stat_segment_disconnect ();
324   close (fd);
325
326   exit (0);
327 }
328
329 /*
330  * fd.io coding-style-patch-verification: ON
331  *
332  * Local Variables:
333  * eval: (c-set-style "gnu")
334  * End:
335  */