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