9652721a100557989408e24545001714a0ff6c6e
[oweals/gnunet.git] / src / testbed / gnunet-daemon-latency-logger.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
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 testbed/gnunet-daemon-latency-logger.c
23  * @brief log latency values from neighbour connections into an SQLite database
24  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_ats_service.h"
30 #include <sqlite3.h>
31
32
33 /**
34  * Logging shorthand
35  */
36 #define LOG(type,...)                           \
37   GNUNET_log (type, __VA_ARGS__)
38
39 /**
40  * Debug logging shorthand
41  */
42 #define DEBUG(...)                              \
43   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
44
45 /**
46  * Log an error message at log-level 'level' that indicates
47  * a failure of the command 'cmd' on file 'filename'
48  * with the message given by strerror(errno).
49  */
50 #define LOG_SQLITE(db, msg, level, cmd)                                 \
51   do {                                                                  \
52     GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), \
53                      cmd, __FILE__,__LINE__, sqlite3_errmsg(db));  \
54     if (msg != NULL)                                                    \
55       GNUNET_asprintf(msg, _("`%s' failed at %s:%u with error: %s"), cmd, \
56                       __FILE__, __LINE__, sqlite3_errmsg(db));     \
57   } while(0)
58
59
60 /**
61  * Entry type to be used in the map to store old latency values
62  */
63 struct Entry
64 {
65   /**
66    *  The peer's identity
67    */
68   struct GNUNET_PeerIdentity id;
69
70   /**
71    * The last known value for latency.
72    * FIXME: type!
73    */
74   unsigned int latency;
75
76 };
77
78
79 /**
80  * Handle to the map used to store old latency values for peers
81  */
82 static struct GNUNET_CONTAINER_MultiPeerMap *map;
83
84 /**
85  * The SQLite database handle
86  */
87 static struct sqlite3 *db;
88
89 /**
90  * Handle to the ATS performance subsystem
91  */
92 struct GNUNET_ATS_PerformanceHandle *ats;
93
94 /**
95  * Prepared statement for inserting values into the database table
96  */
97 struct sqlite3_stmt *stmt_insert;
98
99 /**
100  * Shutdown task identifier
101  */
102 struct GNUNET_SCHEDULER_Task * shutdown_task;
103
104
105 /**
106  * @ingroup hashmap
107  * Iterator over hash map entries.
108  *
109  * @param cls closure
110  * @param key current public key
111  * @param value value in the hash map
112  * @return #GNUNET_YES if we should continue to
113  *         iterate,
114  *         #GNUNET_NO if not.
115  */
116 static int
117 free_iterator (void *cls,
118                const struct GNUNET_PeerIdentity *key,
119                void *value)
120 {
121   struct Entry *e = cls;
122
123   GNUNET_assert (GNUNET_YES ==
124                  GNUNET_CONTAINER_multipeermap_remove (map, key, e));
125   GNUNET_free (e);
126   return GNUNET_YES;
127 }
128
129
130 /**
131  * Shutdown
132  *
133  * @param cls NULL
134  * @return
135  */
136 static void
137 do_shutdown (void *cls)
138 {
139   shutdown_task = NULL;
140   GNUNET_ATS_performance_done (ats);
141   ats = NULL;
142   if (NULL != stmt_insert)
143   {
144     sqlite3_finalize (stmt_insert);
145     stmt_insert = NULL;
146   }
147   GNUNET_break (SQLITE_OK == sqlite3_close (db));
148   db = NULL;
149   if (NULL != map)
150   {
151     GNUNET_assert (GNUNET_SYSERR !=
152                    GNUNET_CONTAINER_multipeermap_iterate (map, free_iterator, NULL));
153     GNUNET_CONTAINER_multipeermap_destroy (map);
154     map = NULL;
155   }
156 }
157
158 /**
159  * Signature of a function that is called with QoS information about an address.
160  *
161  * @param cls closure
162  * @param address the address
163  * @param address_active #GNUNET_YES if this address is actively used
164  *        to maintain a connection to a peer;
165  *        #GNUNET_NO if the address is not actively used;
166  *        #GNUNET_SYSERR if this address is no longer available for ATS
167  * @param bandwidth_out assigned outbound bandwidth for the connection
168  * @param bandwidth_in assigned inbound bandwidth for the connection
169  * @param prop performance data for the address (as far as known)
170  */
171 static void
172 addr_info_cb (void *cls,
173               const struct GNUNET_HELLO_Address *address,
174               int address_active,
175               struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
176               struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
177               const struct GNUNET_ATS_Properties *prop)
178 {
179   static const char *query_insert =
180       "INSERT INTO ats_info("
181       " id,"
182       " val,"
183       " timestamp"
184       ") VALUES ("
185       " ?1,"
186       " ?2,"
187       " datetime('now')"
188       ");";
189   struct Entry *entry;
190   int latency; /* FIXME: type!? */
191
192   if (NULL == address)
193   {
194     /* ATS service temporarily disconnected */
195     return;
196   }
197
198   GNUNET_assert (NULL != db);
199   if (GNUNET_YES != address_active)
200     return;
201   latency = (int) prop->delay.rel_value_us;
202   entry = NULL;
203   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (map,
204                                                             &address->peer))
205   {
206     entry = GNUNET_CONTAINER_multipeermap_get (map, &address->peer);
207     GNUNET_assert (NULL != entry);
208     if (latency == entry->latency)
209       return;
210   }
211   if (NULL == stmt_insert)
212   {
213     if (SQLITE_OK != sqlite3_prepare_v2 (db, query_insert, -1, &stmt_insert,
214                                          NULL))
215     {
216       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
217       goto err_shutdown;
218     }
219   }
220   if ( (SQLITE_OK != sqlite3_bind_text (stmt_insert, 1,
221                                         GNUNET_i2s (&address->peer), -1,
222                                         SQLITE_STATIC)) ||
223         (SQLITE_OK != sqlite3_bind_int (stmt_insert, 2, latency)) )
224   {
225      LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_text");
226      goto err_shutdown;
227   }
228   if (SQLITE_DONE != sqlite3_step (stmt_insert))
229   {
230     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_step");
231     goto err_shutdown;
232   }
233   if (SQLITE_OK != sqlite3_reset (stmt_insert))
234   {
235     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_insert");
236     goto err_shutdown;
237   }
238   if (NULL == entry)
239   {
240     entry = GNUNET_new (struct Entry);
241     entry->id = address->peer;
242     GNUNET_CONTAINER_multipeermap_put (map,
243                                        &entry->id, entry,
244                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
245   }
246   entry->latency = latency;
247   return;
248
249  err_shutdown:
250       GNUNET_SCHEDULER_shutdown ();
251 }
252
253
254 /**
255  * Main function that will be run.
256  *
257  * @param cls closure
258  * @param args remaining command-line arguments
259  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
260  * @param c configuration
261  */
262 static void
263 run (void *cls, char *const *args, const char *cfgfile,
264      const struct GNUNET_CONFIGURATION_Handle *c)
265 {
266   const char *query_create =
267       "CREATE TABLE ats_info ("
268       "id TEXT,"
269       "val INTEGER,"
270       "timestamp NUMERIC"
271       ");";
272   char *dbfile;
273
274   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "LATENCY-LOGGER",
275                                                             "DBFILE",
276                                                             &dbfile))
277   {
278     GNUNET_break (0);
279     return;
280   }
281   if (SQLITE_OK != sqlite3_open (dbfile, &db))
282   {
283     if (NULL != db)
284     {
285       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
286       GNUNET_break (SQLITE_OK == sqlite3_close (db));
287     }
288     else
289       LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
290     GNUNET_free (dbfile);
291     return;
292   }
293   if (0 != sqlite3_exec (db, query_create, NULL, NULL, NULL))
294     DEBUG ("SQLite Error: %d.  Perhaps the database `%s' already exits.\n",
295            sqlite3_errcode (db), dbfile);
296   DEBUG ("Opened database %s\n", dbfile);
297   GNUNET_free (dbfile);
298   dbfile = NULL;
299   ats = GNUNET_ATS_performance_init (c, &addr_info_cb, NULL);
300   map = GNUNET_CONTAINER_multipeermap_create (30, GNUNET_YES);
301   shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
302                                                 &do_shutdown, NULL);
303 }
304
305
306 /**
307  * Execution entry point
308  */
309 int
310 main (int argc, char * const *argv)
311 {
312   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
313     GNUNET_GETOPT_OPTION_END
314   };
315   int ret;
316
317   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
318     return 2;
319   ret =
320       (GNUNET_OK ==
321        GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-latency-logger",
322                            _("Daemon to log latency values of connections to neighbours"),
323                            options, &run, NULL)) ? 0 : 1;
324   GNUNET_free ((void*) argv);
325   return ret;
326 }