adapt to new MYSQL API
[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 (select_stmt_handle, 1,
365                                                     rbind, &return_ok, NULL,
366                                                     MYSQL_TYPE_BLOB, key,
367                                                     sizeof (struct
368                                                             GNUNET_HashCode),
369                                                     &k_length,
370                                                     MYSQL_TYPE_STRING,
371                                                     edges[i].label,
372                                                     strlen (edges[i].label),
373                                                     &e_length, -1);
374
375     if (GNUNET_SYSERR == result)
376     {
377       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
378                   "Error executing prepared mysql select statement\n");
379       GNUNET_SCHEDULER_add_now (&do_abort, NULL);
380       return;
381     }
382
383     if (-1 != total && total > 0)
384     {
385       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Total: %llu (%s, %s)\n", total,
386                   GNUNET_h2s (key), edges[i].label);
387     }
388
389     result =
390         GNUNET_MYSQL_statement_run_prepared (stmt_handle, NULL,
391                                              MYSQL_TYPE_BLOB, key,
392                                              sizeof (struct GNUNET_HashCode),
393                                              &k_length, MYSQL_TYPE_STRING,
394                                              edges[i].label,
395                                              strlen (edges[i].label), &e_length,
396                                              MYSQL_TYPE_BLOB,
397                                              &edges[i].destination,
398                                              sizeof (struct GNUNET_HashCode),
399                                              &d_length, MYSQL_TYPE_LONG,
400                                              &accepting, GNUNET_YES, -1);
401
402     if (0 == result)
403     {
404       char *key_str = GNUNET_strdup (GNUNET_h2s (key));
405       char *to_key_str = GNUNET_strdup (GNUNET_h2s (&edges[i].destination));
406
407       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Merged (%s, %s, %s, %i)\n", key_str,
408                   edges[i].label, to_key_str, accepting);
409       GNUNET_free (key_str);
410       GNUNET_free (to_key_str);
411       num_merged_transitions++;
412     }
413     else if (-1 != total)
414     {
415       num_merged_states++;
416     }
417
418     if (GNUNET_SYSERR == result || (1 != result && 0 != result))
419     {
420       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
421                   "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n",
422                   result);
423       GNUNET_SCHEDULER_add_now (&do_abort, NULL);
424     }
425   }
426
427   if (0 == num_edges)
428   {
429     k_length = sizeof (struct GNUNET_HashCode);
430     e_length = 0;
431     d_length = 0;
432
433     result =
434         GNUNET_MYSQL_statement_run_prepared (stmt_handle, NULL,
435                                              MYSQL_TYPE_BLOB, key,
436                                              sizeof (struct GNUNET_HashCode),
437                                              &k_length, MYSQL_TYPE_STRING, NULL,
438                                              0, &e_length, MYSQL_TYPE_BLOB,
439                                              NULL, 0, &d_length,
440                                              MYSQL_TYPE_LONG, &accepting,
441                                              GNUNET_YES, -1);
442
443     if (1 != result && 0 != result)
444     {
445       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
446                   "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n",
447                   result);
448       GNUNET_SCHEDULER_add_now (&do_abort, NULL);
449     }
450   }
451 }
452
453
454 /**
455  * Announce a regex by creating the DFA and iterating over each state, inserting
456  * each state into a MySQL database.
457  *
458  * @param regex regular expression.
459  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure.
460  */
461 static int
462 announce_regex (const char *regex)
463 {
464   struct REGEX_INTERNAL_Automaton *dfa;
465
466   dfa =
467       REGEX_INTERNAL_construct_dfa (regex,
468                                     strlen (regex),
469                                     max_path_compression);
470
471   if (NULL == dfa)
472   {
473     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
474                 "Failed to create DFA for regex %s\n",
475                 regex);
476     GNUNET_SCHEDULER_add_now (&do_abort, NULL);
477     return GNUNET_SYSERR;
478   }
479   REGEX_INTERNAL_iterate_all_edges (dfa,
480                                     &regex_iterator, NULL);
481   REGEX_INTERNAL_automaton_destroy (dfa);
482
483   return GNUNET_OK;
484 }
485
486
487 /**
488  * Function called with a filename.
489  *
490  * @param cls closure
491  * @param filename complete filename (absolute path)
492  * @return #GNUNET_OK to continue to iterate,
493  *  #GNUNET_SYSERR to abort iteration with error!
494  */
495 static int
496 policy_filename_cb (void *cls, const char *filename)
497 {
498   char *regex;
499   char *data;
500   char *buf;
501   uint64_t filesize;
502   unsigned int offset;
503
504   GNUNET_assert (NULL != filename);
505
506   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
507               "Announcing regexes from file %s\n",
508               filename);
509
510   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
511   {
512     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
513                 "Could not find policy file %s\n",
514                 filename);
515     return GNUNET_OK;
516   }
517   if (GNUNET_OK !=
518       GNUNET_DISK_file_size (filename, &filesize,
519                              GNUNET_YES, GNUNET_YES))
520     filesize = 0;
521   if (0 == filesize)
522   {
523     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n",
524                 filename);
525     return GNUNET_OK;
526   }
527   data = GNUNET_malloc (filesize);
528   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
529   {
530     GNUNET_free (data);
531     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
532                 "Could not read policy file %s.\n",
533                 filename);
534     return GNUNET_OK;
535   }
536
537   update_meter (meter);
538
539   buf = data;
540   offset = 0;
541   regex = NULL;
542   while (offset < (filesize - 1))
543   {
544     offset++;
545     if (((data[offset] == '\n')) && (buf != &data[offset]))
546     {
547       data[offset] = '|';
548       num_policies++;
549       buf = &data[offset + 1];
550     }
551     else if ((data[offset] == '\n') || (data[offset] == '\0'))
552       buf = &data[offset + 1];
553   }
554   data[offset] = '\0';
555   GNUNET_asprintf (&regex, "%s(%s)", regex_prefix, data);
556   GNUNET_assert (NULL != regex);
557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
558               "Announcing regex: %s\n", regex);
559
560   if (GNUNET_OK != announce_regex (regex))
561   {
562     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
563                 "Could not announce regex %s\n",
564                 regex);
565   }
566   GNUNET_free (regex);
567   GNUNET_free (data);
568   return GNUNET_OK;
569 }
570
571
572 /**
573  * Iterate over files contained in policy_dir.
574  *
575  * @param cls NULL
576  */
577 static void
578 do_directory_scan (void *cls)
579 {
580   struct GNUNET_TIME_Absolute start_time;
581   struct GNUNET_TIME_Relative duration;
582   char *stmt;
583
584   /* Create an MySQL prepared statement for the inserts */
585   scan_task = NULL;
586   GNUNET_asprintf (&stmt, INSERT_EDGE_STMT, table_name);
587   stmt_handle = GNUNET_MYSQL_statement_prepare (mysql_ctx, stmt);
588   GNUNET_free (stmt);
589
590   GNUNET_asprintf (&stmt, SELECT_KEY_STMT, table_name);
591   select_stmt_handle = GNUNET_MYSQL_statement_prepare (mysql_ctx, stmt);
592   GNUNET_free (stmt);
593
594   GNUNET_assert (NULL != stmt_handle);
595
596   meter = create_meter (num_policy_files,
597                         "Announcing policy files\n",
598                         GNUNET_YES);
599   start_time = GNUNET_TIME_absolute_get ();
600   GNUNET_DISK_directory_scan (policy_dir,
601                               &policy_filename_cb,
602                               stmt_handle);
603   duration = GNUNET_TIME_absolute_get_duration (start_time);
604   reset_meter (meter);
605   free_meter (meter);
606   meter = NULL;
607
608   printf ("Announced %u files containing %u policies in %s\n"
609           "Duplicate transitions: %llu\nMerged states: %llu\n",
610           num_policy_files,
611           num_policies,
612           GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_NO),
613           num_merged_transitions,
614           num_merged_states);
615   result = GNUNET_OK;
616   GNUNET_SCHEDULER_shutdown ();
617 }
618
619
620 /**
621  * Main function that will be run by the scheduler.
622  *
623  * @param cls closure
624  * @param args remaining command-line arguments
625  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
626  * @param config configuration
627  */
628 static void
629 run (void *cls,
630      char *const *args,
631      const char *cfgfile,
632      const struct GNUNET_CONFIGURATION_Handle *config)
633 {
634   if (NULL == args[0])
635   {
636     fprintf (stderr,
637              _("No policy directory specified on command line. Exiting.\n"));
638     result = GNUNET_SYSERR;
639     return;
640   }
641   if (GNUNET_YES !=
642       GNUNET_DISK_directory_test (args[0], GNUNET_YES))
643   {
644     fprintf (stderr,
645              _("Specified policies directory does not exist. Exiting.\n"));
646     result = GNUNET_SYSERR;
647     return;
648   }
649   policy_dir = args[0];
650
651   num_policy_files = GNUNET_DISK_directory_scan (policy_dir,
652                                                  NULL, NULL);
653   meter = NULL;
654
655   if (NULL == table_name)
656   {
657     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
658                 "No table name specified, using default \"NFA\".\n");
659     table_name = "NFA";
660   }
661
662   mysql_ctx = GNUNET_MYSQL_context_create (config, "regex-mysql");
663   if (NULL == mysql_ctx)
664   {
665     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
666                 "Failed to create mysql context\n");
667     result = GNUNET_SYSERR;
668     return;
669   }
670
671   if (GNUNET_OK !=
672       GNUNET_CONFIGURATION_get_value_string (config,
673                                              "regex-mysql",
674                                              "REGEX_PREFIX",
675                                              &regex_prefix))
676   {
677     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
678                                "regex-mysql",
679                                "REGEX_PREFIX");
680     result = GNUNET_SYSERR;
681     return;
682   }
683
684   result = GNUNET_OK;
685   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
686                                  NULL);
687   scan_task = GNUNET_SCHEDULER_add_now (&do_directory_scan, NULL);
688 }
689
690
691 /**
692  * Main function.
693  *
694  * @param argc argument count
695  * @param argv argument values
696  * @return 0 on success
697  */
698 int
699 main (int argc, char *const *argv)
700 {
701   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
702     {'t', "table", "TABLENAME",
703      gettext_noop ("name of the table to write DFAs"),
704      1, &GNUNET_GETOPT_set_string, &table_name},
705     {'p', "max-path-compression", "MAX_PATH_COMPRESSION",
706      gettext_noop ("maximum path compression length"),
707      1, &GNUNET_GETOPT_set_uint, &max_path_compression},
708     GNUNET_GETOPT_OPTION_END
709   };
710   int ret;
711
712   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
713     return 2;
714
715   result = GNUNET_SYSERR;
716   ret =
717       GNUNET_PROGRAM_run (argc, argv,
718                           "gnunet-regex-simulationprofiler [OPTIONS] policy-dir",
719                           _("Profiler for regex library"), options, &run, NULL);
720   if (GNUNET_OK != ret)
721     return ret;
722   if (GNUNET_OK != result)
723     return 1;
724   return 0;
725 }