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