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