adapt gnunet-regex-simulation-profiler to libgnunetmy
[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
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      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      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file regex/gnunet-regex-simulation-profiler.c
23  * @brief Regex profiler that dumps all DFAs into a database instead of
24  *        using the DHT (with cadet).
25  * @author Maximilian Szengel
26  * @author Christophe Genevey
27  *
28  */
29
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "regex_internal_lib.h"
33 #include "gnunet_mysql_lib.h"
34 #include "gnunet_my_lib.h"
35 #include <mysql/mysql.h>
36
37 /**
38  * MySQL statement to insert an edge.
39  */
40 #define INSERT_EDGE_STMT "INSERT IGNORE INTO `%s` "\
41                          "(`key`, `label`, `to_key`, `accepting`) "\
42                          "VALUES (?, ?, ?, ?);"
43
44 /**
45  * MySQL statement to select a key count.
46  */
47 #define SELECT_KEY_STMT "SELECT COUNT(*) FROM `%s` "\
48                         "WHERE `key` = ? AND `label` = ?;"
49
50 /**
51  * Simple struct to keep track of progress, and print a
52  * nice little percentage meter for long running tasks.
53  */
54 struct ProgressMeter
55 {
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_fixed_size(edges[i].label, strlen (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", total,
374                   GNUNET_h2s (key), edges[i].label);
375     }
376
377     struct GNUNET_MY_QueryParam params_stmt[] = {
378       GNUNET_MY_query_param_auto_from_type (&key),
379       GNUNET_MY_query_param_fixed_size (edges[i].label, strlen (edges[i].label)),
380       GNUNET_MY_query_param_auto_from_type (&edges[i].destination),
381       GNUNET_MY_query_param_uint32 (&iaccepting),
382       GNUNET_MY_query_param_end
383     };
384
385     result = 
386       GNUNET_MY_exec_prepared (mysql_ctx,
387                               stmt_handle,
388                               params_stmt);
389
390     if (0 == result)
391     {
392       char *key_str = GNUNET_strdup (GNUNET_h2s (key));
393       char *to_key_str = GNUNET_strdup (GNUNET_h2s (&edges[i].destination));
394
395       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Merged (%s, %s, %s, %i)\n", key_str,
396                   edges[i].label, to_key_str, accepting);
397       GNUNET_free (key_str);
398       GNUNET_free (to_key_str);
399       num_merged_transitions++;
400     }
401     else if (-1 != total)
402     {
403       num_merged_states++;
404     }
405
406     if (GNUNET_SYSERR == result || (1 != result && 0 != result))
407     {
408       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
409                   "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n",
410                   result);
411       GNUNET_SCHEDULER_add_now (&do_abort, NULL);
412     }
413   }
414
415   if (0 == num_edges)
416   {
417     struct GNUNET_MY_QueryParam params_stmt[] = {
418       GNUNET_MY_query_param_auto_from_type (key),
419       GNUNET_MY_query_param_fixed_size (NULL, 0),
420       GNUNET_MY_query_param_auto_from_type (NULL),
421       GNUNET_MY_query_param_uint32 (&iaccepting),
422       GNUNET_MY_query_param_end
423     };
424
425     result = 
426       GNUNET_MY_exec_prepared(mysql_ctx,
427                               stmt_handle,
428                               params_stmt);
429
430     if (1 != result && 0 != result)
431     {
432       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
433                   "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n",
434                   result);
435       GNUNET_SCHEDULER_add_now (&do_abort, NULL);
436     }
437   }
438 }
439
440
441 /**
442  * Announce a regex by creating the DFA and iterating over each state, inserting
443  * each state into a MySQL database.
444  *
445  * @param regex regular expression.
446  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure.
447  */
448 static int
449 announce_regex (const char *regex)
450 {
451   struct REGEX_INTERNAL_Automaton *dfa;
452
453   dfa =
454       REGEX_INTERNAL_construct_dfa (regex,
455                                     strlen (regex),
456                                     max_path_compression);
457
458   if (NULL == dfa)
459   {
460     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
461                 "Failed to create DFA for regex %s\n",
462                 regex);
463     GNUNET_SCHEDULER_add_now (&do_abort, NULL);
464     return GNUNET_SYSERR;
465   }
466   REGEX_INTERNAL_iterate_all_edges (dfa,
467                                     &regex_iterator, NULL);
468   REGEX_INTERNAL_automaton_destroy (dfa);
469
470   return GNUNET_OK;
471 }
472
473
474 /**
475  * Function called with a filename.
476  *
477  * @param cls closure
478  * @param filename complete filename (absolute path)
479  * @return #GNUNET_OK to continue to iterate,
480  *  #GNUNET_SYSERR to abort iteration with error!
481  */
482 static int
483 policy_filename_cb (void *cls, const char *filename)
484 {
485   char *regex;
486   char *data;
487   char *buf;
488   uint64_t filesize;
489   unsigned int offset;
490
491   GNUNET_assert (NULL != filename);
492
493   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
494               "Announcing regexes from file %s\n",
495               filename);
496
497   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
498   {
499     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
500                 "Could not find policy file %s\n",
501                 filename);
502     return GNUNET_OK;
503   }
504   if (GNUNET_OK !=
505       GNUNET_DISK_file_size (filename, &filesize,
506                              GNUNET_YES, GNUNET_YES))
507     filesize = 0;
508   if (0 == filesize)
509   {
510     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n",
511                 filename);
512     return GNUNET_OK;
513   }
514   data = GNUNET_malloc (filesize);
515   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
516   {
517     GNUNET_free (data);
518     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
519                 "Could not read policy file %s.\n",
520                 filename);
521     return GNUNET_OK;
522   }
523
524   update_meter (meter);
525
526   buf = data;
527   offset = 0;
528   regex = NULL;
529   while (offset < (filesize - 1))
530   {
531     offset++;
532     if (((data[offset] == '\n')) && (buf != &data[offset]))
533     {
534       data[offset] = '|';
535       num_policies++;
536       buf = &data[offset + 1];
537     }
538     else if ((data[offset] == '\n') || (data[offset] == '\0'))
539       buf = &data[offset + 1];
540   }
541   data[offset] = '\0';
542   GNUNET_asprintf (&regex, "%s(%s)", regex_prefix, data);
543   GNUNET_assert (NULL != regex);
544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
545               "Announcing regex: %s\n", regex);
546
547   if (GNUNET_OK != announce_regex (regex))
548   {
549     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
550                 "Could not announce regex %s\n",
551                 regex);
552   }
553   GNUNET_free (regex);
554   GNUNET_free (data);
555   return GNUNET_OK;
556 }
557
558
559 /**
560  * Iterate over files contained in policy_dir.
561  *
562  * @param cls NULL
563  */
564 static void
565 do_directory_scan (void *cls)
566 {
567   struct GNUNET_TIME_Absolute start_time;
568   struct GNUNET_TIME_Relative duration;
569   char *stmt;
570
571   /* Create an MySQL prepared statement for the inserts */
572   scan_task = NULL;
573   GNUNET_asprintf (&stmt, INSERT_EDGE_STMT, table_name);
574   stmt_handle = GNUNET_MYSQL_statement_prepare (mysql_ctx, stmt);
575   GNUNET_free (stmt);
576
577   GNUNET_asprintf (&stmt, SELECT_KEY_STMT, table_name);
578   select_stmt_handle = GNUNET_MYSQL_statement_prepare (mysql_ctx, stmt);
579   GNUNET_free (stmt);
580
581   GNUNET_assert (NULL != stmt_handle);
582
583   meter = create_meter (num_policy_files,
584                         "Announcing policy files\n",
585                         GNUNET_YES);
586   start_time = GNUNET_TIME_absolute_get ();
587   GNUNET_DISK_directory_scan (policy_dir,
588                               &policy_filename_cb,
589                               stmt_handle);
590   duration = GNUNET_TIME_absolute_get_duration (start_time);
591   reset_meter (meter);
592   free_meter (meter);
593   meter = NULL;
594
595   printf ("Announced %u files containing %u policies in %s\n"
596           "Duplicate transitions: %llu\nMerged states: %llu\n",
597           num_policy_files,
598           num_policies,
599           GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_NO),
600           num_merged_transitions,
601           num_merged_states);
602   result = GNUNET_OK;
603   GNUNET_SCHEDULER_shutdown ();
604 }
605
606
607 /**
608  * Main function that will be run by the scheduler.
609  *
610  * @param cls closure
611  * @param args remaining command-line arguments
612  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
613  * @param config configuration
614  */
615 static void
616 run (void *cls,
617      char *const *args,
618      const char *cfgfile,
619      const struct GNUNET_CONFIGURATION_Handle *config)
620 {
621   if (NULL == args[0])
622   {
623     fprintf (stderr,
624              _("No policy directory specified on command line. Exiting.\n"));
625     result = GNUNET_SYSERR;
626     return;
627   }
628   if (GNUNET_YES !=
629       GNUNET_DISK_directory_test (args[0], GNUNET_YES))
630   {
631     fprintf (stderr,
632              _("Specified policies directory does not exist. Exiting.\n"));
633     result = GNUNET_SYSERR;
634     return;
635   }
636   policy_dir = args[0];
637
638   num_policy_files = GNUNET_DISK_directory_scan (policy_dir,
639                                                  NULL, NULL);
640   meter = NULL;
641
642   if (NULL == table_name)
643   {
644     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
645                 "No table name specified, using default \"NFA\".\n");
646     table_name = "NFA";
647   }
648
649   mysql_ctx = GNUNET_MYSQL_context_create (config, "regex-mysql");
650   if (NULL == mysql_ctx)
651   {
652     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
653                 "Failed to create mysql context\n");
654     result = GNUNET_SYSERR;
655     return;
656   }
657
658   if (GNUNET_OK !=
659       GNUNET_CONFIGURATION_get_value_string (config,
660                                              "regex-mysql",
661                                              "REGEX_PREFIX",
662                                              &regex_prefix))
663   {
664     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
665                                "regex-mysql",
666                                "REGEX_PREFIX");
667     result = GNUNET_SYSERR;
668     return;
669   }
670
671   result = GNUNET_OK;
672   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
673                                  NULL);
674   scan_task = GNUNET_SCHEDULER_add_now (&do_directory_scan, NULL);
675 }
676
677
678 /**
679  * Main function.
680  *
681  * @param argc argument count
682  * @param argv argument values
683  * @return 0 on success
684  */
685 int
686 main (int argc, char *const *argv)
687 {
688   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
689     {'t', "table", "TABLENAME",
690      gettext_noop ("name of the table to write DFAs"),
691      1, &GNUNET_GETOPT_set_string, &table_name},
692     {'p', "max-path-compression", "MAX_PATH_COMPRESSION",
693      gettext_noop ("maximum path compression length"),
694      1, &GNUNET_GETOPT_set_uint, &max_path_compression},
695     GNUNET_GETOPT_OPTION_END
696   };
697   int ret;
698
699   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
700     return 2;
701
702   result = GNUNET_SYSERR;
703   ret =
704       GNUNET_PROGRAM_run (argc, argv,
705                           "gnunet-regex-simulationprofiler [OPTIONS] policy-dir",
706                           _("Profiler for regex library"), options, &run, NULL);
707   if (GNUNET_OK != ret)
708     return ret;
709   if (GNUNET_OK != result)
710     return 1;
711   return 0;
712 }