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