uncrustify as demanded.
[oweals/gnunet.git] / src / regex / gnunet-regex-simulation-profiler.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011, 2012 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19  */
20
21
22 /**
23  * @file regex/gnunet-regex-simulation-profiler.c
24  * @brief Regex profiler that dumps all DFAs into a database instead of
25  *        using the DHT (with cadet).
26  * @author Maximilian Szengel
27  * @author Christophe Genevey
28  *
29  */
30
31 #include "platform.h"
32 #include "gnunet_util_lib.h"
33 #include "regex_internal_lib.h"
34 #include "gnunet_mysql_lib.h"
35 #include "gnunet_my_lib.h"
36 #include <mysql/mysql.h>
37
38 /**
39  * MySQL statement to insert an edge.
40  */
41 #define INSERT_EDGE_STMT "INSERT IGNORE INTO `%s` " \
42   "(`key`, `label`, `to_key`, `accepting`) " \
43   "VALUES (?, ?, ?, ?);"
44
45 /**
46  * MySQL statement to select a key count.
47  */
48 #define SELECT_KEY_STMT "SELECT COUNT(*) FROM `%s` " \
49   "WHERE `key` = ? AND `label` = ?;"
50
51 /**
52  * Simple struct to keep track of progress, and print a
53  * nice little percentage meter for long running tasks.
54  */
55 struct ProgressMeter {
56   /**
57    * Total number of elements.
58    */
59   unsigned int total;
60
61   /**
62    * Intervall for printing percentage.
63    */
64   unsigned int modnum;
65
66   /**
67    * Number of dots to print.
68    */
69   unsigned int dotnum;
70
71   /**
72    * Completed number.
73    */
74   unsigned int completed;
75
76   /**
77    * Should the meter be printed?
78    */
79   int print;
80
81   /**
82    * String to print on startup.
83    */
84   char *startup_string;
85 };
86
87
88 /**
89  * Handle for the progress meter
90  */
91 static struct ProgressMeter *meter;
92
93 /**
94  * Scan task identifier;
95  */
96 static struct GNUNET_SCHEDULER_Task *scan_task;
97
98 /**
99  * Global testing status.
100  */
101 static int result;
102
103 /**
104  * MySQL context.
105  */
106 static struct GNUNET_MYSQL_Context *mysql_ctx;
107
108 /**
109  * MySQL prepared statement handle.
110  */
111 static struct GNUNET_MYSQL_StatementHandle *stmt_handle;
112
113 /**
114  * MySQL prepared statement handle for `key` select.
115  */
116 static struct GNUNET_MYSQL_StatementHandle *select_stmt_handle;
117
118 /**
119  * MySQL table name.
120  */
121 static char *table_name;
122
123 /**
124  * Policy dir containing files that contain policies.
125  */
126 static char *policy_dir;
127
128 /**
129  * Number of policy files.
130  */
131 static unsigned int num_policy_files;
132
133 /**
134  * Number of policies.
135  */
136 static unsigned int num_policies;
137
138 /**
139  * Maximal path compression length.
140  */
141 static unsigned int max_path_compression;
142
143 /**
144  * Number of merged transitions.
145  */
146 static unsigned long long num_merged_transitions;
147
148 /**
149  * Number of merged states from different policies.
150  */
151 static unsigned long long num_merged_states;
152
153 /**
154  * Prefix to add before every regex we're announcing.
155  */
156 static char *regex_prefix;
157
158
159 /**
160  * Create a meter to keep track of the progress of some task.
161  *
162  * @param total the total number of items to complete
163  * @param start_string a string to prefix the meter with (if printing)
164  * @param print GNUNET_YES to print the meter, GNUNET_NO to count
165  *              internally only
166  *
167  * @return the progress meter
168  */
169 static struct ProgressMeter *
170 create_meter(unsigned int total, char *start_string, int print)
171 {
172   struct ProgressMeter *ret;
173
174   ret = GNUNET_new(struct ProgressMeter);
175   ret->print = print;
176   ret->total = total;
177   ret->modnum = total / 4;
178   if (ret->modnum == 0)         /* Divide by zero check */
179     ret->modnum = 1;
180   ret->dotnum = (total / 50) + 1;
181   if (start_string != NULL)
182     ret->startup_string = GNUNET_strdup(start_string);
183   else
184     ret->startup_string = GNUNET_strdup("");
185
186   return ret;
187 }
188
189
190 /**
191  * Update progress meter (increment by one).
192  *
193  * @param meter the meter to update and print info for
194  *
195  * @return GNUNET_YES if called the total requested,
196  *         GNUNET_NO if more items expected
197  */
198 static int
199 update_meter(struct ProgressMeter *meter)
200 {
201   if (meter->print == GNUNET_YES)
202     {
203       if (meter->completed % meter->modnum == 0)
204         {
205           if (meter->completed == 0)
206             {
207               fprintf(stdout, "%sProgress: [0%%", meter->startup_string);
208             }
209           else
210             fprintf(stdout, "%d%%",
211                     (int)(((float)meter->completed / meter->total) * 100));
212         }
213       else if (meter->completed % meter->dotnum == 0)
214         fprintf(stdout, "%s", ".");
215
216       if (meter->completed + 1 == meter->total)
217         fprintf(stdout, "%d%%]\n", 100);
218       fflush(stdout);
219     }
220   meter->completed++;
221
222   if (meter->completed == meter->total)
223     return GNUNET_YES;
224   if (meter->completed > meter->total)
225     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Progress meter overflow!!\n");
226   return GNUNET_NO;
227 }
228
229
230 /**
231  * Reset progress meter.
232  *
233  * @param meter the meter to reset
234  *
235  * @return #GNUNET_YES if meter reset,
236  *         #GNUNET_SYSERR on error
237  */
238 static int
239 reset_meter(struct ProgressMeter *meter)
240 {
241   if (meter == NULL)
242     return GNUNET_SYSERR;
243
244   meter->completed = 0;
245   return GNUNET_YES;
246 }
247
248
249 /**
250  * Release resources for meter
251  *
252  * @param meter the meter to free
253  */
254 static void
255 free_meter(struct ProgressMeter *meter)
256 {
257   GNUNET_free_non_null(meter->startup_string);
258   GNUNET_free(meter);
259 }
260
261
262 /**
263  * Shutdown task.
264  *
265  * @param cls NULL
266  */
267 static void
268 do_shutdown(void *cls)
269 {
270   if (NULL != mysql_ctx)
271     {
272       GNUNET_MYSQL_context_destroy(mysql_ctx);
273       mysql_ctx = NULL;
274     }
275   if (NULL != meter)
276     {
277       free_meter(meter);
278       meter = NULL;
279     }
280 }
281
282
283 /**
284  * Abort task to run on test timed out.
285  *
286  * FIXME: this doesn't actually work, it used to cancel
287  * the already running 'scan_task', but now that should
288  * always be NULL and do nothing. We instead need to set
289  * a global variable and abort scan_task internally, not
290  * via scheduler.
291  *
292  * @param cls NULL
293  */
294 static void
295 do_abort(void *cls)
296 {
297   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Aborting\n");
298   if (NULL != scan_task)
299     {
300       GNUNET_SCHEDULER_cancel(scan_task);
301       scan_task = NULL;
302     }
303   result = GNUNET_SYSERR;
304   GNUNET_SCHEDULER_shutdown();
305 }
306
307 /**
308  * Iterator over all states that inserts each state into the MySQL db.
309  *
310  * @param cls closure.
311  * @param key hash for current state.
312  * @param proof proof for current state.
313  * @param accepting #GNUNET_YES if this is an accepting state, #GNUNET_NO if not.
314  * @param num_edges number of edges leaving current state.
315  * @param edges edges leaving current state.
316  */
317 static void
318 regex_iterator(void *cls,
319                const struct GNUNET_HashCode *key,
320                const char *proof,
321                int accepting,
322                unsigned int num_edges,
323                const struct REGEX_BLOCK_Edge *edges)
324 {
325   unsigned int i;
326   int result;
327
328   uint32_t iaccepting = (uint32_t)accepting;
329   uint64_t total;
330
331   GNUNET_assert(NULL != mysql_ctx);
332
333   for (i = 0; i < num_edges; i++)
334     {
335       struct GNUNET_MY_QueryParam params_select[] = {
336         GNUNET_MY_query_param_auto_from_type(key),
337         GNUNET_MY_query_param_string(edges[i].label),
338         GNUNET_MY_query_param_end
339       };
340
341       struct GNUNET_MY_ResultSpec results_select[] = {
342         GNUNET_MY_result_spec_uint64(&total),
343         GNUNET_MY_result_spec_end
344       };
345
346       result =
347         GNUNET_MY_exec_prepared(mysql_ctx,
348                                 select_stmt_handle,
349                                 params_select);
350
351       if (GNUNET_SYSERR == result)
352         {
353           GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
354                      "Error executing prepared mysql select statement\n");
355           GNUNET_SCHEDULER_add_now(&do_abort, NULL);
356           return;
357         }
358
359       result =
360         GNUNET_MY_extract_result(select_stmt_handle,
361                                  results_select);
362
363       if (GNUNET_SYSERR == result)
364         {
365           GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
366                      "Error extracting result mysql select statement\n");
367           GNUNET_SCHEDULER_add_now(&do_abort, NULL);
368           return;
369         }
370
371       if (-1 != total && total > 0)
372         {
373           GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Total: %llu (%s, %s)\n",
374                      (unsigned long long)total,
375                      GNUNET_h2s(key), edges[i].label);
376         }
377
378       struct GNUNET_MY_QueryParam params_stmt[] = {
379         GNUNET_MY_query_param_auto_from_type(&key),
380         GNUNET_MY_query_param_string(edges[i].label),
381         GNUNET_MY_query_param_auto_from_type(&edges[i].destination),
382         GNUNET_MY_query_param_uint32(&iaccepting),
383         GNUNET_MY_query_param_end
384       };
385
386       result =
387         GNUNET_MY_exec_prepared(mysql_ctx,
388                                 stmt_handle,
389                                 params_stmt);
390
391       if (0 == result)
392         {
393           char *key_str = GNUNET_strdup(GNUNET_h2s(key));
394           char *to_key_str = GNUNET_strdup(GNUNET_h2s(&edges[i].destination));
395
396           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Merged (%s, %s, %s, %i)\n",
397                      key_str,
398                      edges[i].label,
399                      to_key_str,
400                      accepting);
401
402           GNUNET_free(key_str);
403           GNUNET_free(to_key_str);
404           num_merged_transitions++;
405         }
406       else if (-1 != total)
407         {
408           num_merged_states++;
409         }
410
411       if (GNUNET_SYSERR == result || (1 != result && 0 != result))
412         {
413           GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
414                      "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n",
415                      result);
416           GNUNET_SCHEDULER_add_now(&do_abort, NULL);
417         }
418     }
419
420   if (0 == num_edges)
421     {
422       struct GNUNET_MY_QueryParam params_stmt[] = {
423         GNUNET_MY_query_param_auto_from_type(key),
424         GNUNET_MY_query_param_string(""),
425         GNUNET_MY_query_param_fixed_size(NULL, 0),
426         GNUNET_MY_query_param_uint32(&iaccepting),
427         GNUNET_MY_query_param_end
428       };
429
430       result =
431         GNUNET_MY_exec_prepared(mysql_ctx,
432                                 stmt_handle,
433                                 params_stmt);
434
435       if (1 != result && 0 != result)
436         {
437           GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
438                      "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n",
439                      result);
440           GNUNET_SCHEDULER_add_now(&do_abort, NULL);
441         }
442     }
443 }
444
445
446 /**
447  * Announce a regex by creating the DFA and iterating over each state, inserting
448  * each state into a MySQL database.
449  *
450  * @param regex regular expression.
451  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure.
452  */
453 static int
454 announce_regex(const char *regex)
455 {
456   struct REGEX_INTERNAL_Automaton *dfa;
457
458   dfa =
459     REGEX_INTERNAL_construct_dfa(regex,
460                                  strlen(regex),
461                                  max_path_compression);
462
463   if (NULL == dfa)
464     {
465       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
466                  "Failed to create DFA for regex %s\n",
467                  regex);
468       GNUNET_SCHEDULER_add_now(&do_abort, NULL);
469       return GNUNET_SYSERR;
470     }
471   REGEX_INTERNAL_iterate_all_edges(dfa,
472                                    &regex_iterator, NULL);
473   REGEX_INTERNAL_automaton_destroy(dfa);
474
475   return GNUNET_OK;
476 }
477
478
479 /**
480  * Function called with a filename.
481  *
482  * @param cls closure
483  * @param filename complete filename (absolute path)
484  * @return #GNUNET_OK to continue to iterate,
485  *  #GNUNET_SYSERR to abort iteration with error!
486  */
487 static int
488 policy_filename_cb(void *cls, const char *filename)
489 {
490   char *regex;
491   char *data;
492   char *buf;
493   uint64_t filesize;
494   unsigned int offset;
495
496   GNUNET_assert(NULL != filename);
497
498   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
499              "Announcing regexes from file %s\n",
500              filename);
501
502   if (GNUNET_YES != GNUNET_DISK_file_test(filename))
503     {
504       GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
505                  "Could not find policy file %s\n",
506                  filename);
507       return GNUNET_OK;
508     }
509   if (GNUNET_OK !=
510       GNUNET_DISK_file_size(filename, &filesize,
511                             GNUNET_YES, GNUNET_YES))
512     filesize = 0;
513   if (0 == filesize)
514     {
515       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n",
516                  filename);
517       return GNUNET_OK;
518     }
519   data = GNUNET_malloc(filesize);
520   if (filesize != GNUNET_DISK_fn_read(filename, data, filesize))
521     {
522       GNUNET_free(data);
523       GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
524                  "Could not read policy file %s.\n",
525                  filename);
526       return GNUNET_OK;
527     }
528
529   update_meter(meter);
530
531   buf = data;
532   offset = 0;
533   regex = NULL;
534   while (offset < (filesize - 1))
535     {
536       offset++;
537       if (((data[offset] == '\n')) && (buf != &data[offset]))
538         {
539           data[offset] = '|';
540           num_policies++;
541           buf = &data[offset + 1];
542         }
543       else if ((data[offset] == '\n') || (data[offset] == '\0'))
544         buf = &data[offset + 1];
545     }
546   data[offset] = '\0';
547   GNUNET_asprintf(&regex, "%s(%s)", regex_prefix, data);
548   GNUNET_assert(NULL != regex);
549   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
550              "Announcing regex: %s\n", regex);
551
552   if (GNUNET_OK != announce_regex(regex))
553     {
554       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
555                  "Could not announce regex %s\n",
556                  regex);
557     }
558   GNUNET_free(regex);
559   GNUNET_free(data);
560   return GNUNET_OK;
561 }
562
563
564 /**
565  * Iterate over files contained in policy_dir.
566  *
567  * @param cls NULL
568  */
569 static void
570 do_directory_scan(void *cls)
571 {
572   struct GNUNET_TIME_Absolute start_time;
573   struct GNUNET_TIME_Relative duration;
574   char *stmt;
575
576   /* Create an MySQL prepared statement for the inserts */
577   scan_task = NULL;
578   GNUNET_asprintf(&stmt, INSERT_EDGE_STMT, table_name);
579   stmt_handle = GNUNET_MYSQL_statement_prepare(mysql_ctx, stmt);
580   GNUNET_free(stmt);
581
582   GNUNET_asprintf(&stmt, SELECT_KEY_STMT, table_name);
583   select_stmt_handle = GNUNET_MYSQL_statement_prepare(mysql_ctx, stmt);
584   GNUNET_free(stmt);
585
586   GNUNET_assert(NULL != stmt_handle);
587
588   meter = create_meter(num_policy_files,
589                        "Announcing policy files\n",
590                        GNUNET_YES);
591   start_time = GNUNET_TIME_absolute_get();
592   GNUNET_DISK_directory_scan(policy_dir,
593                              &policy_filename_cb,
594                              stmt_handle);
595   duration = GNUNET_TIME_absolute_get_duration(start_time);
596   reset_meter(meter);
597   free_meter(meter);
598   meter = NULL;
599
600   printf("Announced %u files containing %u policies in %s\n"
601          "Duplicate transitions: %llu\nMerged states: %llu\n",
602          num_policy_files,
603          num_policies,
604          GNUNET_STRINGS_relative_time_to_string(duration, GNUNET_NO),
605          num_merged_transitions,
606          num_merged_states);
607   result = GNUNET_OK;
608   GNUNET_SCHEDULER_shutdown();
609 }
610
611
612 /**
613  * Main function that will be run by the scheduler.
614  *
615  * @param cls closure
616  * @param args remaining command-line arguments
617  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
618  * @param config configuration
619  */
620 static void
621 run(void *cls,
622     char *const *args,
623     const char *cfgfile,
624     const struct GNUNET_CONFIGURATION_Handle *config)
625 {
626   if (NULL == args[0])
627     {
628       fprintf(stderr,
629               _("No policy directory specified on command line. Exiting.\n"));
630       result = GNUNET_SYSERR;
631       return;
632     }
633   if (GNUNET_YES !=
634       GNUNET_DISK_directory_test(args[0], GNUNET_YES))
635     {
636       fprintf(stderr,
637               _("Specified policies directory does not exist. Exiting.\n"));
638       result = GNUNET_SYSERR;
639       return;
640     }
641   policy_dir = args[0];
642
643   num_policy_files = GNUNET_DISK_directory_scan(policy_dir,
644                                                 NULL, NULL);
645   meter = NULL;
646
647   if (NULL == table_name)
648     {
649       GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
650                  "No table name specified, using default \"NFA\".\n");
651       table_name = "NFA";
652     }
653
654   mysql_ctx = GNUNET_MYSQL_context_create(config, "regex-mysql");
655   if (NULL == mysql_ctx)
656     {
657       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
658                  "Failed to create mysql context\n");
659       result = GNUNET_SYSERR;
660       return;
661     }
662
663   if (GNUNET_OK !=
664       GNUNET_CONFIGURATION_get_value_string(config,
665                                             "regex-mysql",
666                                             "REGEX_PREFIX",
667                                             &regex_prefix))
668     {
669       GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
670                                 "regex-mysql",
671                                 "REGEX_PREFIX");
672       result = GNUNET_SYSERR;
673       return;
674     }
675
676   result = GNUNET_OK;
677   GNUNET_SCHEDULER_add_shutdown(&do_shutdown,
678                                 NULL);
679   scan_task = GNUNET_SCHEDULER_add_now(&do_directory_scan, NULL);
680 }
681
682
683 /**
684  * Main function.
685  *
686  * @param argc argument count
687  * @param argv argument values
688  * @return 0 on success
689  */
690 int
691 main(int argc, char *const *argv)
692 {
693   struct GNUNET_GETOPT_CommandLineOption options[] = {
694     GNUNET_GETOPT_option_string('t',
695                                 "table",
696                                 "TABLENAME",
697                                 gettext_noop("name of the table to write DFAs"),
698                                 &table_name),
699
700     GNUNET_GETOPT_option_uint('p',
701                               "max-path-compression",
702                               "MAX_PATH_COMPRESSION",
703                               gettext_noop("maximum path compression length"),
704                               &max_path_compression),
705
706     GNUNET_GETOPT_OPTION_END
707   };
708   int ret;
709
710   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
711     return 2;
712
713   result = GNUNET_SYSERR;
714   ret =
715     GNUNET_PROGRAM_run(argc, argv,
716                        "gnunet-regex-simulationprofiler [OPTIONS] policy-dir",
717                        _("Profiler for regex library"), options, &run, NULL);
718   if (GNUNET_OK != ret)
719     return ret;
720   if (GNUNET_OK != result)
721     return 1;
722   return 0;
723 }