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