notify performance monitors about destroyed addresses (for #3406)
[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 #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 ats performance data for the address (as far as known)
170  * @param ats_count number of performance records in 'ats'
171  */
172 static void
173 addr_info_cb (void *cls,
174               const struct GNUNET_HELLO_Address *address,
175               int address_active,
176               struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
177               struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
178               const struct GNUNET_ATS_Information *ats,
179               uint32_t ats_count)
180 {
181   static const char *query_insert =
182       "INSERT INTO ats_info("
183       " id,"
184       " val,"
185       " timestamp"
186       ") VALUES ("
187       " ?1,"
188       " ?2,"
189       " datetime('now')"
190       ");";
191   struct Entry *entry;
192   int latency;
193   unsigned int cnt;
194
195   if (NULL == address)
196   {
197     /* ATS service temporarily disconnected */
198     return;
199   }
200
201   GNUNET_assert (NULL != db);
202   if (GNUNET_YES != address_active)
203     return;
204   for (cnt = 0; cnt < ats_count; cnt++)
205   {
206     if (GNUNET_ATS_QUALITY_NET_DELAY == ntohl (ats[cnt].type))
207       goto insert;
208   }
209   return;
210
211  insert:
212   latency = (int) ntohl (ats[cnt].value);
213   entry = NULL;
214   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (map,
215                                                             &address->peer))
216   {
217     entry = GNUNET_CONTAINER_multipeermap_get (map, &address->peer);
218     GNUNET_assert (NULL != entry);
219     if (latency == entry->latency)
220       return;
221   }
222   if (NULL == stmt_insert)
223   {
224     if (SQLITE_OK != sqlite3_prepare_v2 (db, query_insert, -1, &stmt_insert,
225                                          NULL))
226     {
227       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_prepare_v2");
228       goto err_shutdown;
229     }
230   }
231   if ( (SQLITE_OK != sqlite3_bind_text (stmt_insert, 1,
232                                         GNUNET_i2s (&address->peer), -1,
233                                         SQLITE_STATIC)) ||
234         (SQLITE_OK != sqlite3_bind_int (stmt_insert, 2, latency)) )
235   {
236      LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_bind_text");
237      goto err_shutdown;
238   }
239   if (SQLITE_DONE != sqlite3_step (stmt_insert))
240   {
241     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_step");
242     goto err_shutdown;
243   }
244   if (SQLITE_OK != sqlite3_reset (stmt_insert))
245   {
246     LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_insert");
247     goto err_shutdown;
248   }
249   if (NULL == entry)
250   {
251     entry = GNUNET_new (struct Entry);
252     entry->id = address->peer;
253     GNUNET_CONTAINER_multipeermap_put (map,
254                                        &entry->id, entry,
255                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
256   }
257   entry->latency = latency;
258   return;
259
260  err_shutdown:
261       GNUNET_SCHEDULER_shutdown ();
262 }
263
264
265 /**
266  * Main function that will be run.
267  *
268  * @param cls closure
269  * @param args remaining command-line arguments
270  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
271  * @param c configuration
272  */
273 static void
274 run (void *cls, char *const *args, const char *cfgfile,
275      const struct GNUNET_CONFIGURATION_Handle *c)
276 {
277   const char *query_create =
278       "CREATE TABLE ats_info ("
279       "id TEXT,"
280       "val INTEGER,"
281       "timestamp NUMERIC"
282       ");";
283   char *dbfile;
284
285   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (c, "LATENCY-LOGGER",
286                                                             "DBFILE",
287                                                             &dbfile))
288   {
289     GNUNET_break (0);
290     return;
291   }
292   if (SQLITE_OK != sqlite3_open (dbfile, &db))
293   {
294     if (NULL != db)
295     {
296       LOG_SQLITE (db, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_open_v2");
297       sqlite3_close (db);
298     }
299     else
300       LOG (GNUNET_ERROR_TYPE_ERROR, "Cannot open sqlite file %s\n", dbfile);
301     GNUNET_free (dbfile);
302     return;
303   }
304   if (0 != sqlite3_exec (db, query_create, NULL, NULL, NULL))
305     DEBUG ("SQLite Error: %d.  Perhaps the database `%s' already exits.\n",
306            sqlite3_errcode (db), dbfile);
307   DEBUG ("Opened database %s\n", dbfile);
308   GNUNET_free (dbfile);
309   dbfile = NULL;
310   ats = GNUNET_ATS_performance_init (c, &addr_info_cb, NULL);
311   map = GNUNET_CONTAINER_multipeermap_create (30, GNUNET_YES);
312   shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
313                                                 &do_shutdown, NULL);
314 }
315
316
317 /**
318  * Execution entry point
319  */
320 int
321 main (int argc, char * const *argv)
322 {
323   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
324     GNUNET_GETOPT_OPTION_END
325   };
326   int ret;
327
328   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
329     return 2;
330   ret =
331       (GNUNET_OK ==
332        GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-latency-logger",
333                            _("Daemon to log latency values of connections to neighbours"),
334                            options, &run, NULL)) ? 0 : 1;
335   GNUNET_free ((void*) argv);
336   return ret;
337 }