-indentation
[oweals/gnunet.git] / src / testbed / gnunet-daemon-latency-logger.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/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    */
73   unsigned int latency;
74   
75 };
76
77
78 /**
79  * Handle to the map used to store old latency values for peers
80  */
81 static struct GNUNET_CONTAINER_MultiPeerMap *map;
82
83 /**
84  * The SQLite database handle
85  */
86 static struct sqlite3 *db;
87
88 /**
89  * Handle to the ATS performance subsystem
90  */
91 struct GNUNET_ATS_PerformanceHandle *ats;
92
93 /**
94  * Prepared statement for inserting values into the database table
95  */
96 struct sqlite3_stmt *stmt_insert;
97
98 /**
99  * Shutdown task identifier
100  */
101 GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
102
103
104 /**
105  * @ingroup hashmap
106  * Iterator over hash map entries.
107  *
108  * @param cls closure
109  * @param key current public key
110  * @param value value in the hash map
111  * @return #GNUNET_YES if we should continue to
112  *         iterate,
113  *         #GNUNET_NO if not.
114  */
115 static int
116 free_iterator (void *cls,
117                const struct GNUNET_PeerIdentity *key,
118                void *value)
119 {
120   struct Entry *e = cls;
121
122   GNUNET_assert (GNUNET_YES == 
123                  GNUNET_CONTAINER_multipeermap_remove (map, key, e));
124   GNUNET_free (e);
125   return GNUNET_YES;
126 }
127
128
129 /**
130  * Shutdown
131  *
132  * @param cls NULL
133  * @param tc task context from scheduler
134  * @return 
135  */
136 static void
137 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
138 {
139   shutdown_task = GNUNET_SCHEDULER_NO_TASK;
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 is this address actively used to maintain a connection
164  *                              to a peer
165  * @param bandwidth_out assigned outbound bandwidth for the connection
166  * @param bandwidth_in assigned inbound bandwidth for the connection
167  * @param ats performance data for the address (as far as known)
168  * @param ats_count number of performance records in 'ats'
169  */
170 static void
171 addr_info_cb (void *cls,
172               const struct GNUNET_HELLO_Address *address,
173               int address_active,
174               struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
175               struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
176               const struct GNUNET_ATS_Information *ats,
177               uint32_t ats_count)
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;
191   unsigned int cnt;
192
193   if (NULL == address)
194   {
195     /* ATS service temporarily disconnected */
196     return;
197   }
198
199   GNUNET_assert (NULL != db);
200   if (GNUNET_NO == address_active)
201     return;
202   for (cnt = 0; cnt < ats_count; cnt++)
203   {
204     if (GNUNET_ATS_QUALITY_NET_DELAY == ntohl (ats[cnt].type))
205       goto insert;
206   }
207   return;
208
209  insert:
210   latency = (int) ntohl (ats[cnt].value);
211   entry = NULL;
212   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (map,
213                                                             &address->peer))
214   {
215     entry = GNUNET_CONTAINER_multipeermap_get (map, &address->peer);
216     GNUNET_assert (NULL != entry);
217     if (latency == entry->latency)
218       return;
219   }
220   if (NULL == stmt_insert)
221   {
222     if (SQLITE_OK != sqlite3_prepare_v2 (db, query_insert, -1, &stmt_insert,
223                                          NULL))
224     {
225       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
226       goto err_shutdown;
227     }
228   }
229   if ( (SQLITE_OK != sqlite3_bind_text (stmt_insert, 1,
230                                         GNUNET_i2s (&address->peer), -1,
231                                         SQLITE_STATIC)) ||
232         (SQLITE_OK != sqlite3_bind_int (stmt_insert, 2, latency)) )
233   {
234      LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_text");
235      goto err_shutdown;
236   }
237   if (SQLITE_DONE != sqlite3_step (stmt_insert))
238   {
239     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_step");
240     goto err_shutdown;
241   }
242   if (SQLITE_OK != sqlite3_reset (stmt_insert))
243   {
244     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_insert");
245     goto err_shutdown;
246   }
247   if (NULL == entry)
248   {
249     entry = GNUNET_new (struct Entry);
250     entry->id = address->peer;
251     GNUNET_CONTAINER_multipeermap_put (map, 
252                                        &entry->id, entry,
253                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
254   }
255   entry->latency = latency;
256   return;
257   
258  err_shutdown:
259       GNUNET_SCHEDULER_shutdown ();
260 }
261
262
263 /**
264  * Main function that will be run.
265  *
266  * @param cls closure
267  * @param args remaining command-line arguments
268  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
269  * @param c configuration
270  */
271 static void
272 run (void *cls, char *const *args, const char *cfgfile,
273      const struct GNUNET_CONFIGURATION_Handle *c)
274 {
275   const char *query_create = 
276       "CREATE TABLE ats_info ("
277       "id TEXT,"
278       "val INTEGER,"
279       "timestamp NUMERIC"
280       ");";
281   char *dbfile;
282
283   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "LATENCY-LOGGER",
284                                                             "DBFILE",
285                                                             &dbfile))
286   {
287     GNUNET_break (0);
288     return;
289   }
290   if (SQLITE_OK != sqlite3_open (dbfile, &db))
291   {
292     if (NULL != db)
293     {
294       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
295       sqlite3_close (db);
296     }
297     else
298       LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
299     GNUNET_free (dbfile);
300     return;
301   }
302   if (0 != sqlite3_exec (db, query_create, NULL, NULL, NULL))
303     DEBUG ("SQLite Error: %d.  Perhaps the database `%s' already exits.\n",
304            sqlite3_errcode (db), dbfile);
305   DEBUG ("Opened database %s\n", dbfile);
306   GNUNET_free (dbfile);  
307   dbfile = NULL;
308   ats = GNUNET_ATS_performance_init (c, addr_info_cb, NULL);
309   map = GNUNET_CONTAINER_multipeermap_create (30, GNUNET_YES);
310   shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
311                                                 &do_shutdown, NULL);
312 }
313
314
315 /**
316  * Execution entry point
317  */
318 int
319 main (int argc, char * const *argv)
320 {
321   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
322     GNUNET_GETOPT_OPTION_END
323   };
324   int ret;
325
326   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
327     return 2;
328   ret =
329       (GNUNET_OK ==
330        GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-latency-logger",
331                            _("Daemon to log latency values of connections to neighbours"),
332                            options, &run, NULL)) ? 0 : 1;
333   GNUNET_free ((void*) argv);
334   return ret;
335 }