Replace most uses of assert by ovs_assert.
[sliver-openvswitch.git] / lib / table.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "table.h"
20
21 #include "dynamic-string.h"
22 #include "json.h"
23 #include "ovsdb-data.h"
24 #include "ovsdb-error.h"
25 #include "timeval.h"
26 #include "util.h"
27
28 struct column {
29     char *heading;
30 };
31
32 static char *
33 cell_to_text(struct cell *cell, const struct table_style *style)
34 {
35     if (!cell->text) {
36         if (cell->json) {
37             if (style->cell_format == CF_JSON || !cell->type) {
38                 cell->text = json_to_string(cell->json, JSSF_SORT);
39             } else {
40                 struct ovsdb_datum datum;
41                 struct ovsdb_error *error;
42                 struct ds s;
43
44                 error = ovsdb_datum_from_json(&datum, cell->type, cell->json,
45                                               NULL);
46                 if (!error) {
47                     ds_init(&s);
48                     if (style->cell_format == CF_STRING) {
49                         ovsdb_datum_to_string(&datum, cell->type, &s);
50                     } else {
51                         ovsdb_datum_to_bare(&datum, cell->type, &s);
52                     }
53                     ovsdb_datum_destroy(&datum, cell->type);
54                     cell->text = ds_steal_cstr(&s);
55                 } else {
56                     cell->text = json_to_string(cell->json, JSSF_SORT);
57                     ovsdb_error_destroy(error);
58                 }
59             }
60         } else {
61             cell->text = xstrdup("");
62         }
63     }
64
65     return cell->text;
66 }
67
68 static void
69 cell_destroy(struct cell *cell)
70 {
71     free(cell->text);
72     json_destroy(cell->json);
73 }
74
75 /* Initializes 'table' as an empty table.
76  *
77  * The caller should then:
78  *
79  * 1. Call table_add_column() once for each column.
80  * 2. For each row:
81  *    2a. Call table_add_row().
82  *    2b. For each column in the cell, call table_add_cell() and fill in
83  *        the returned cell.
84  * 3. Call table_print() to print the final table.
85  * 4. Free the table with table_destroy().
86  */
87 void
88 table_init(struct table *table)
89 {
90     memset(table, 0, sizeof *table);
91 }
92
93 /* Destroys 'table' and frees all associated storage.  (However, the client
94  * owns the 'type' members pointed to by cells, so these are not destroyed.) */
95 void
96 table_destroy(struct table *table)
97 {
98     if (table) {
99         size_t i;
100
101         for (i = 0; i < table->n_columns; i++) {
102             free(table->columns[i].heading);
103         }
104         free(table->columns);
105
106         for (i = 0; i < table->n_columns * table->n_rows; i++) {
107             cell_destroy(&table->cells[i]);
108         }
109         free(table->cells);
110
111         free(table->caption);
112     }
113 }
114
115 /* Sets 'caption' as the caption for 'table'.
116  *
117  * 'table' takes ownership of 'caption'. */
118 void
119 table_set_caption(struct table *table, char *caption)
120 {
121     free(table->caption);
122     table->caption = caption;
123 }
124
125 /* Turns printing a timestamp along with 'table' on or off, according to
126  * 'timestamp'.  */
127 void
128 table_set_timestamp(struct table *table, bool timestamp)
129 {
130     table->timestamp = timestamp;
131 }
132
133 /* Adds a new column to 'table' just to the right of any existing column, with
134  * 'heading' as a title for the column.  'heading' must be a valid printf()
135  * format specifier.
136  *
137  * Columns must be added before any data is put into 'table'. */
138 void
139 table_add_column(struct table *table, const char *heading, ...)
140 {
141     struct column *column;
142     va_list args;
143
144     ovs_assert(!table->n_rows);
145     if (table->n_columns >= table->allocated_columns) {
146         table->columns = x2nrealloc(table->columns, &table->allocated_columns,
147                                     sizeof *table->columns);
148     }
149     column = &table->columns[table->n_columns++];
150
151     va_start(args, heading);
152     column->heading = xvasprintf(heading, args);
153     va_end(args);
154 }
155
156 static struct cell *
157 table_cell__(const struct table *table, size_t row, size_t column)
158 {
159     return &table->cells[column + row * table->n_columns];
160 }
161
162 /* Adds a new row to 'table'.  The table's columns must already have been added
163  * with table_add_column().
164  *
165  * The row is initially empty; use table_add_cell() to start filling it in. */
166 void
167 table_add_row(struct table *table)
168 {
169     size_t x, y;
170
171     if (table->n_rows >= table->allocated_rows) {
172         table->cells = x2nrealloc(table->cells, &table->allocated_rows,
173                                   table->n_columns * sizeof *table->cells);
174     }
175
176     y = table->n_rows++;
177     table->current_column = 0;
178     for (x = 0; x < table->n_columns; x++) {
179         struct cell *cell = table_cell__(table, y, x);
180         memset(cell, 0, sizeof *cell);
181     }
182 }
183
184 /* Adds a new cell in the current row of 'table', which must have been added
185  * with table_add_row().  Cells are filled in the same order that the columns
186  * were added with table_add_column().
187  *
188  * The caller is responsible for filling in the returned cell, in one of two
189  * fashions:
190  *
191  *   - If the cell should contain an ovsdb_datum, formatted according to the
192  *     table style, then fill in the 'json' member with the JSON representation
193  *     of the datum and 'type' with its type.
194  *
195  *   - If the cell should contain a fixed text string, then the caller should
196  *     assign that string to the 'text' member.  This is undesirable if the
197  *     cell actually contains OVSDB data because 'text' cannot be formatted
198  *     according to the table style; it is always output verbatim.
199  */
200 struct cell *
201 table_add_cell(struct table *table)
202 {
203     size_t x, y;
204
205     ovs_assert(table->n_rows > 0);
206     ovs_assert(table->current_column < table->n_columns);
207
208     x = table->current_column++;
209     y = table->n_rows - 1;
210
211     return table_cell__(table, y, x);
212 }
213
214 static void
215 table_print_table_line__(struct ds *line)
216 {
217     puts(ds_cstr(line));
218     ds_clear(line);
219 }
220
221 static void
222 table_format_timestamp__(char *s, size_t size)
223 {
224     time_t now = time_wall();
225     strftime(s, size, "%Y-%m-%d %H:%M:%S", gmtime(&now));
226 }
227
228 static void
229 table_print_timestamp__(const struct table *table)
230 {
231     if (table->timestamp) {
232         char s[32];
233
234         table_format_timestamp__(s, sizeof s);
235         puts(s);
236     }
237 }
238
239 static void
240 table_print_table__(const struct table *table, const struct table_style *style)
241 {
242     static int n = 0;
243     struct ds line = DS_EMPTY_INITIALIZER;
244     int *widths;
245     size_t x, y;
246
247     if (n++ > 0) {
248         putchar('\n');
249     }
250
251     table_print_timestamp__(table);
252
253     if (table->caption) {
254         puts(table->caption);
255     }
256
257     widths = xmalloc(table->n_columns * sizeof *widths);
258     for (x = 0; x < table->n_columns; x++) {
259         const struct column *column = &table->columns[x];
260
261         widths[x] = strlen(column->heading);
262         for (y = 0; y < table->n_rows; y++) {
263             const char *text = cell_to_text(table_cell__(table, y, x), style);
264             size_t length = strlen(text);
265
266             if (length > widths[x]) {
267                 widths[x] = length;
268             }
269         }
270     }
271
272     if (style->headings) {
273         for (x = 0; x < table->n_columns; x++) {
274             const struct column *column = &table->columns[x];
275             if (x) {
276                 ds_put_char(&line, ' ');
277             }
278             ds_put_format(&line, "%-*s", widths[x], column->heading);
279         }
280         table_print_table_line__(&line);
281
282         for (x = 0; x < table->n_columns; x++) {
283             if (x) {
284                 ds_put_char(&line, ' ');
285             }
286             ds_put_char_multiple(&line, '-', widths[x]);
287         }
288         table_print_table_line__(&line);
289     }
290
291     for (y = 0; y < table->n_rows; y++) {
292         for (x = 0; x < table->n_columns; x++) {
293             const char *text = cell_to_text(table_cell__(table, y, x), style);
294             if (x) {
295                 ds_put_char(&line, ' ');
296             }
297             ds_put_format(&line, "%-*s", widths[x], text);
298         }
299         table_print_table_line__(&line);
300     }
301
302     ds_destroy(&line);
303     free(widths);
304 }
305
306 static void
307 table_print_list__(const struct table *table, const struct table_style *style)
308 {
309     static int n = 0;
310     size_t x, y;
311
312     if (n++ > 0) {
313         putchar('\n');
314     }
315
316     table_print_timestamp__(table);
317
318     if (table->caption) {
319         puts(table->caption);
320     }
321
322     for (y = 0; y < table->n_rows; y++) {
323         if (y > 0) {
324             putchar('\n');
325         }
326         for (x = 0; x < table->n_columns; x++) {
327             const char *text = cell_to_text(table_cell__(table, y, x), style);
328             if (style->headings) {
329                 printf("%-20s: ", table->columns[x].heading);
330             }
331             puts(text);
332         }
333     }
334 }
335
336 static void
337 table_escape_html_text__(const char *s, size_t n)
338 {
339     size_t i;
340
341     for (i = 0; i < n; i++) {
342         char c = s[i];
343
344         switch (c) {
345         case '&':
346             fputs("&amp;", stdout);
347             break;
348         case '<':
349             fputs("&lt;", stdout);
350             break;
351         case '>':
352             fputs("&gt;", stdout);
353             break;
354         case '"':
355             fputs("&quot;", stdout);
356             break;
357         default:
358             putchar(c);
359             break;
360         }
361     }
362 }
363
364 static void
365 table_print_html_cell__(const char *element, const char *content)
366 {
367     const char *p;
368
369     printf("    <%s>", element);
370     for (p = content; *p; ) {
371         struct uuid uuid;
372
373         if (uuid_from_string_prefix(&uuid, p)) {
374             printf("<a href=\"#%.*s\">%.*s</a>", UUID_LEN, p, 8, p);
375             p += UUID_LEN;
376         } else {
377             table_escape_html_text__(p, 1);
378             p++;
379         }
380     }
381     printf("</%s>\n", element);
382 }
383
384 static void
385 table_print_html__(const struct table *table, const struct table_style *style)
386 {
387     size_t x, y;
388
389     table_print_timestamp__(table);
390
391     fputs("<table border=1>\n", stdout);
392
393     if (table->caption) {
394         table_print_html_cell__("caption", table->caption);
395     }
396
397     if (style->headings) {
398         fputs("  <tr>\n", stdout);
399         for (x = 0; x < table->n_columns; x++) {
400             const struct column *column = &table->columns[x];
401             table_print_html_cell__("th", column->heading);
402         }
403         fputs("  </tr>\n", stdout);
404     }
405
406     for (y = 0; y < table->n_rows; y++) {
407         fputs("  <tr>\n", stdout);
408         for (x = 0; x < table->n_columns; x++) {
409             const char *content;
410
411             content = cell_to_text(table_cell__(table, y, x), style);
412             if (!strcmp(table->columns[x].heading, "_uuid")) {
413                 fputs("    <td><a name=\"", stdout);
414                 table_escape_html_text__(content, strlen(content));
415                 fputs("\">", stdout);
416                 table_escape_html_text__(content, 8);
417                 fputs("</a></td>\n", stdout);
418             } else {
419                 table_print_html_cell__("td", content);
420             }
421         }
422         fputs("  </tr>\n", stdout);
423     }
424
425     fputs("</table>\n", stdout);
426 }
427
428 static void
429 table_print_csv_cell__(const char *content)
430 {
431     const char *p;
432
433     if (!strpbrk(content, "\n\",")) {
434         fputs(content, stdout);
435     } else {
436         putchar('"');
437         for (p = content; *p != '\0'; p++) {
438             switch (*p) {
439             case '"':
440                 fputs("\"\"", stdout);
441                 break;
442             default:
443                 putchar(*p);
444                 break;
445             }
446         }
447         putchar('"');
448     }
449 }
450
451 static void
452 table_print_csv__(const struct table *table, const struct table_style *style)
453 {
454     static int n = 0;
455     size_t x, y;
456
457     if (n++ > 0) {
458         putchar('\n');
459     }
460
461     table_print_timestamp__(table);
462
463     if (table->caption) {
464         puts(table->caption);
465     }
466
467     if (style->headings) {
468         for (x = 0; x < table->n_columns; x++) {
469             const struct column *column = &table->columns[x];
470             if (x) {
471                 putchar(',');
472             }
473             table_print_csv_cell__(column->heading);
474         }
475         putchar('\n');
476     }
477
478     for (y = 0; y < table->n_rows; y++) {
479         for (x = 0; x < table->n_columns; x++) {
480             if (x) {
481                 putchar(',');
482             }
483             table_print_csv_cell__(cell_to_text(table_cell__(table, y, x),
484                                                 style));
485         }
486         putchar('\n');
487     }
488 }
489
490 static void
491 table_print_json__(const struct table *table, const struct table_style *style)
492 {
493     struct json *json, *headings, *data;
494     size_t x, y;
495     char *s;
496
497     json = json_object_create();
498     if (table->caption) {
499         json_object_put_string(json, "caption", table->caption);
500     }
501     if (table->timestamp) {
502         char s[32];
503
504         table_format_timestamp__(s, sizeof s);
505         json_object_put_string(json, "time", s);
506     }
507
508     headings = json_array_create_empty();
509     for (x = 0; x < table->n_columns; x++) {
510         const struct column *column = &table->columns[x];
511         json_array_add(headings, json_string_create(column->heading));
512     }
513     json_object_put(json, "headings", headings);
514
515     data = json_array_create_empty();
516     for (y = 0; y < table->n_rows; y++) {
517         struct json *row = json_array_create_empty();
518         for (x = 0; x < table->n_columns; x++) {
519             const struct cell *cell = table_cell__(table, y, x);
520             if (cell->text) {
521                 json_array_add(row, json_string_create(cell->text));
522             } else if (cell->json) {
523                 json_array_add(row, json_clone(cell->json));
524             } else {
525                 json_array_add(row, json_null_create());
526             }
527         }
528         json_array_add(data, row);
529     }
530     json_object_put(json, "data", data);
531
532     s = json_to_string(json, style->json_flags);
533     json_destroy(json);
534     puts(s);
535     free(s);
536 }
537 \f
538 /* Parses 'format' as the argument to a --format command line option, updating
539  * 'style->format'. */
540 void
541 table_parse_format(struct table_style *style, const char *format)
542 {
543     if (!strcmp(format, "table")) {
544         style->format = TF_TABLE;
545     } else if (!strcmp(format, "list")) {
546         style->format = TF_LIST;
547     } else if (!strcmp(format, "html")) {
548         style->format = TF_HTML;
549     } else if (!strcmp(format, "csv")) {
550         style->format = TF_CSV;
551     } else if (!strcmp(format, "json")) {
552         style->format = TF_JSON;
553     } else {
554         ovs_fatal(0, "unknown output format \"%s\"", format);
555     }
556 }
557
558 /* Parses 'format' as the argument to a --data command line option, updating
559  * 'style->cell_format'. */
560 void
561 table_parse_cell_format(struct table_style *style, const char *format)
562 {
563     if (!strcmp(format, "string")) {
564         style->cell_format = CF_STRING;
565     } else if (!strcmp(format, "bare")) {
566         style->cell_format = CF_BARE;
567     } else if (!strcmp(format, "json")) {
568         style->cell_format = CF_JSON;
569     } else {
570         ovs_fatal(0, "unknown data format \"%s\"", format);
571     }
572 }
573
574 /* Outputs 'table' on stdout in the specified 'style'. */
575 void
576 table_print(const struct table *table, const struct table_style *style)
577 {
578     switch (style->format) {
579     case TF_TABLE:
580         table_print_table__(table, style);
581         break;
582
583     case TF_LIST:
584         table_print_list__(table, style);
585         break;
586
587     case TF_HTML:
588         table_print_html__(table, style);
589         break;
590
591     case TF_CSV:
592         table_print_csv__(table, style);
593         break;
594
595     case TF_JSON:
596         table_print_json__(table, style);
597         break;
598     }
599 }