- fixes
[oweals/gnunet.git] / src / testbed / generate-underlay-topology.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2014 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file testbed/generate-underlay-topology.c
23  * @brief Program to generate a database file containing given underlay topology
24  * @author Sree Harsha Totakura <sreeharsha@totakura.in> 
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_testbed_service.h"
30 #include "testbed_api_topology.h"
31 #include "sqlite3.h"
32
33 #define LOG(type, ...)                          \
34   GNUNET_log (type, __VA_ARGS__)
35
36
37 #define LOG_ERROR(...)                          \
38   LOG (GNUNET_ERROR_TYPE_ERROR, __VA_ARGS__)
39
40 /**
41  * Log an error message at log-level 'level' that indicates
42  * a failure of the command 'cmd' on file 'filename'
43  * with the message given by strerror(errno).
44  */
45 #define LOG_SQLITE(db, msg, level, cmd)                                 \
46   do {                                                                  \
47     GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), \
48                      cmd, __FILE__,__LINE__, sqlite3_errmsg(db));  \
49     if (msg != NULL)                                                    \
50       GNUNET_asprintf(msg, _("`%s' failed at %s:%u with error: %s"), cmd, \
51                       __FILE__, __LINE__, sqlite3_errmsg(db));     \
52   } while(0)
53
54
55 /**
56  * Handle to the sqlite3 database
57  */
58 static struct sqlite3 *db;
59
60 /**
61  * Prepared statement for inserting link values into db
62  */
63 struct sqlite3_stmt *stmt_insert;
64
65 /**
66  * The topology to generate
67  */
68 enum GNUNET_TESTBED_TopologyOption topology;
69
70 /**
71  * The number of peers to include in the topology
72  */
73 static int num_peers;
74
75 /**
76  * program result
77  */
78 static int exit_result;
79
80
81 /**
82  * Functions of this type are called to process underlay link
83  *
84  * @param cls closure
85  * @param A offset of first peer
86  * @param B offset of second peer
87  * @param bandwidth the bandwidth of the link in bytes per second
88  * @param latency the latency of link in milliseconds
89  * @param loss the percentage of messages dropped on the link
90  * @return GNUNET_OK to continue processing; GNUNET_SYSERR to abort
91  */
92 static int
93 link_processor (void *cls,
94                 unsigned int A,
95                 unsigned int B,
96                 unsigned int bandwidth,
97                 unsigned int latency,
98                 unsigned int loss)
99 {
100   if ( (SQLITE_OK != sqlite3_bind_int (stmt_insert, 1, A)) ||
101        (SQLITE_OK != sqlite3_bind_int (stmt_insert, 2, B)) ||
102        (SQLITE_OK != sqlite3_bind_int (stmt_insert, 3, bandwidth)) ||
103        (SQLITE_OK != sqlite3_bind_int (stmt_insert, 4, latency)) ||
104        (SQLITE_OK != sqlite3_bind_int (stmt_insert, 5, loss)) )
105   {
106     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_int");
107     return GNUNET_SYSERR;
108   }
109   if (SQLITE_DONE != sqlite3_step (stmt_insert))
110   {
111     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_step");
112     return GNUNET_SYSERR;
113   }
114   FPRINTF (stdout, "%u -> %u\n", A, B);
115   GNUNET_break (SQLITE_OK == sqlite3_reset (stmt_insert));
116   //GNUNET_break (SQLITE_OK == sqlite3_clear_bindings (stmt_insert));
117   if ( (SQLITE_OK != sqlite3_bind_int (stmt_insert, 1, B)) ||
118        (SQLITE_OK != sqlite3_bind_int (stmt_insert, 2, A)) )
119   {
120     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_int");
121     return GNUNET_SYSERR;
122   }
123   if (SQLITE_DONE != sqlite3_step (stmt_insert))
124   {
125     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_step");
126     return GNUNET_SYSERR;
127   }
128   FPRINTF (stdout, "%u -> %u\n", B, A);
129   GNUNET_break (SQLITE_OK == sqlite3_reset (stmt_insert));
130   return GNUNET_OK;
131 }
132
133
134 /**
135  * Open the database file, creating a new database if not existing and setup the
136  * whitelist table
137  *
138  * @param dbfile the database filename
139  * @return GNUNET_OK upon success; GNUNET_SYSERR upon failure (error message has
140  * to be printed)
141  */
142 static int
143 setup_db (const char *dbfile)
144 {
145   const char *query_create =
146       "CREATE TABLE whitelist ("
147       "id INTEGER,"
148       "oid INTEGER,"
149       "bandwidth INTEGER DEFAULT NULL,"
150       "latency INTEGER DEFAULT NULL,"
151       "loss INTEGER DEFAULT NULL,"
152       " UNIQUE ("
153       "  id,"
154       "  oid"
155       " ) ON CONFLICT IGNORE"
156       ");";
157   const char *query_insert =
158       "INSERT INTO whitelist("
159       " id,"
160       " oid,"
161       " bandwidth,"
162       " latency,"
163       " loss"
164       ") VALUES ("
165       " ?1,"
166       " ?2,"
167       " ?3,"
168       " ?4," 
169       " ?5);";
170   int ret;
171   
172   ret = GNUNET_SYSERR;
173   if (SQLITE_OK != sqlite3_open (dbfile, &db))
174   {
175     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_open");
176     goto err_ret;
177   }
178   if (0 != sqlite3_exec (db, query_create, NULL, NULL, NULL))
179   {
180     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
181     FPRINTF (stderr, "Perhaps the database `%s' already exits.\n", dbfile);
182     goto err_ret;
183   }
184   GNUNET_break (0 == sqlite3_exec (db, "PRAGMA synchronous = 0;", NULL, NULL, NULL));
185   if (SQLITE_OK != sqlite3_prepare_v2 (db, query_insert, -1,
186                                        &stmt_insert, NULL))
187   {
188     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
189     goto err_ret;
190   }
191   ret = GNUNET_OK;
192
193  err_ret:
194   return ret;
195 }
196
197
198 /**
199  * Main run function.
200  *
201  * @param cls NULL
202  * @param args arguments passed to GNUNET_PROGRAM_run
203  * @param cfgfile the path to configuration file
204  * @param cfg the configuration file handle
205  */
206 static void
207 run (void *cls, char *const *args, const char *cfgfile,
208      const struct GNUNET_CONFIGURATION_Handle *config)
209 {
210   const char *dbfile;
211   const char *topology_string;
212   unsigned int arg_uint1;
213   unsigned int arg_uint2;
214   const char *arg_str1;
215   const char *value;
216   unsigned int argc;
217
218   argc = 0;
219   if (NULL == args)
220   {
221     LOG_ERROR (_("Need atleast 2 arguments\n"));
222     return;
223   }
224   if (NULL == (dbfile = args[argc++]))
225   {
226     LOG_ERROR (_("Database filename missing\n"));
227     return;
228   }
229   if (GNUNET_OK != setup_db (dbfile))
230     return;
231   if (NULL == (topology_string = args[argc++]))
232   {
233     LOG_ERROR (_("Topology string missing\n"));
234     return;
235   }
236   if (GNUNET_YES != GNUNET_TESTBED_topology_get_ (&topology, topology_string))
237   {
238     LOG_ERROR (_("Invalid topology: %s\n"), topology_string);
239     return;
240   }
241   /* parse for first TOPOOPT.  This can either be arg_uint1 or arg_str1 */
242   switch (topology)
243   {
244   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
245   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
246   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
247   case GNUNET_TESTBED_TOPOLOGY_SCALE_FREE:
248     if (NULL == (value = args[argc++]))
249     {
250       LOG_ERROR (_("An argument is missing for given topology `%s'\n"),
251                  topology_string);
252       return;
253     }
254     if (-1 == SSCANF (value, "%u", &arg_uint1))
255     {
256       LOG_ERROR (_("Invalid argument `%s' given as topology argument\n"),
257                  value);
258       return;
259     }
260     break;
261   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
262     if (NULL == (arg_str1 = args[argc++]))
263     {
264       LOG_ERROR (_("Filename argument missing for topology `%s'\n"),
265                  topology_string);
266       return;
267     }
268     break;
269   default:
270     break;
271   }
272   /* parse for second TOPOOPT.  Only required for SCALE_FREE topology */
273   switch (topology)
274   {
275   case GNUNET_TESTBED_TOPOLOGY_SCALE_FREE:
276     if (NULL == (value = args[argc++]))
277     {
278       LOG_ERROR (_("Second argument for topology `%s' is missing\n"),
279                  topology_string);
280       return;
281     }
282     if (-1 == SSCANF (value, "%u", &arg_uint2))
283     {
284       LOG_ERROR (_("Invalid argument `%s'; expecting unsigned int\n"), value);
285       return;
286     }
287     break;
288   default:
289     break;
290   }
291   /* contruct topologies */
292   switch (topology)
293   {
294   case GNUNET_TESTBED_TOPOLOGY_LINE:
295   case GNUNET_TESTBED_TOPOLOGY_RING:
296   case GNUNET_TESTBED_TOPOLOGY_CLIQUE:
297   case GNUNET_TESTBED_TOPOLOGY_2D_TORUS:
298     GNUNET_TESTBED_underlay_construct_ (num_peers, link_processor, NULL,
299                                         topology);
300     break;
301   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
302   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
303   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
304     GNUNET_TESTBED_underlay_construct_ (num_peers, link_processor, NULL,
305                                         topology,
306                                         arg_uint1);
307     break;
308   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
309     GNUNET_TESTBED_underlay_construct_ (num_peers, link_processor, NULL,
310                                         topology,
311                                         arg_str1);
312     break;
313   case GNUNET_TESTBED_TOPOLOGY_SCALE_FREE:
314     GNUNET_TESTBED_underlay_construct_ (num_peers, link_processor, NULL,
315                                         topology,
316                                         arg_uint1,
317                                         arg_uint2);
318     break;
319   default:
320     GNUNET_assert (0);
321   }
322 }
323
324
325 /**
326  * Main
327  */
328 int
329 main (int argc, char *const argv[])
330 {
331   struct GNUNET_GETOPT_CommandLineOption option[] = {
332     {'p', "num-peers", "COUNT",
333      gettext_noop ("create COUNT number of peers"),
334      GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_peers},
335     GNUNET_GETOPT_OPTION_END
336   };
337   int ret;
338   
339   exit_result = GNUNET_SYSERR;
340   ret =
341       GNUNET_PROGRAM_run (argc, argv, "gnunet-underlay-topology",
342                           _("Generates SQLite3 database representing a given underlay topology.\n"
343                             "Usage: gnunet-underlay-topology [OPTIONS] db-filename TOPO [TOPOOPTS]\n"
344                             "The following options are available for TOPO followed by TOPOOPTS if applicable:\n"
345                             "\t LINE\n"
346                             "\t RING\n"
347                             "\t RANDOM <num_rnd_links>\n"
348                             "\t SMALL_WORLD <num_rnd_links>\n"
349                             "\t SMALL_WORLD_RING <num_rnd_links>\n"
350                             "\t CLIQUE\n"
351                             "\t 2D_TORUS\n"
352                             "\t SCALE_FREE <cap> <m>\n"
353                             "\t FROM_FILE <filename>\n"
354                             "TOPOOPTS:\n"
355                             "\t num_rnd_links: The number of random links\n"
356                             "\t cap: the maximum number of links a node can have\n"
357                             "\t m: the number of links a node should have while joining the network\n"
358                             "\t filename: the path of the file which contains topology information\n"
359                             "NOTE: the format of the above file is descibed here: https://www.gnunet.org/content/topology-file-format\n"),
360                           option, &run, NULL);
361   if (NULL != stmt_insert)
362     sqlite3_finalize (stmt_insert);
363   if (NULL != db)
364     sqlite3_close (db);
365   if ((GNUNET_OK != ret) || (GNUNET_OK != exit_result))
366     return 1;
367   return 0;
368 }