Xvine: fixes
[oweals/gnunet.git] / src / dht / gnunet_dht_profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 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 dht/gnunet_dht_profiler.c
23  * @brief Profiler for GNUnet DHT
24  * @author Sree Harsha Totakura <sreeharsha@totakura.in>
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_testbed_service.h"
30 #include "gnunet_dht_service.h"
31
32 #define INFO(...)                                       \
33   GNUNET_log (GNUNET_ERROR_TYPE_INFO, __VA_ARGS__)
34
35 #define DEBUG(...)                                           \
36   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
37
38 /**
39  * Number of peers which should perform a PUT out of 100 peers
40  */
41 #define PUT_PROBABILITY 50
42
43 /**
44  * Configuration
45  */
46 static struct GNUNET_CONFIGURATION_Handle *cfg;
47
48 /**
49  * Name of the file with the hosts to run the test over
50  */
51 static char *hosts_file;
52
53 /**
54  * Context for a peer which actively does DHT PUT/GET
55  */
56 struct ActiveContext;
57
58 /**
59  * Context to hold data of peer
60  */
61 struct Context
62 {
63
64   /**
65    * The testbed peer this context belongs to
66    */
67   struct GNUNET_TESTBED_Peer *peer;
68
69   /**
70    * Testbed operation acting on this peer
71    */
72   struct GNUNET_TESTBED_Operation *op;
73
74   /**
75    * Active context; NULL if this peer is not an active peer
76    */
77   struct ActiveContext *ac;
78 };
79
80
81 /**
82  * Context for a peer which actively does DHT PUT/GET
83  */
84 struct ActiveContext
85 {
86   /**
87    * The linked peer context
88    */
89   struct Context *ctx;
90
91   /**
92    * Handler to the DHT service
93    */
94   struct GNUNET_DHT_Handle *dht;
95
96   /**
97    * The data used for do a PUT.  Will be NULL if a PUT hasn't been performed yet
98    */
99   void *put_data;
100
101   /**
102    * The active context used for our DHT GET
103    */
104   struct ActiveContext *get_ac;
105
106   /**
107    * The put handle
108    */
109   struct GNUNET_DHT_PutHandle *dht_put;
110
111   /**
112    * The get handle
113    */
114   struct GNUNET_DHT_GetHandle *dht_get;
115
116   /**
117    * The hash of the @e put_data
118    */
119   struct GNUNET_HashCode hash;
120
121   /**
122    * Delay task
123    */
124   GNUNET_SCHEDULER_TaskIdentifier delay_task;
125
126   /**
127    * The size of the @e put_data
128    */
129   uint16_t put_data_size;
130
131   /**
132    * The number of peers currently doing GET on our data
133    */
134   uint16_t nrefs;
135 };
136
137
138 /**
139  * An array of contexts.  The size of this array should be equal to @a num_peers
140  */
141 static struct Context *a_ctx;
142
143 /**
144  * Array of active peers
145  */
146 static struct ActiveContext *a_ac;
147
148 /**
149  * The delay between starting to do PUTS and GETS
150  */
151 static struct GNUNET_TIME_Relative delay;
152
153 /**
154  * The timeout for GET and PUT
155  */
156 static struct GNUNET_TIME_Relative timeout;
157
158 /**
159  * Number of peers
160  */
161 static unsigned int num_peers;
162
163 /**
164  * Number of active peers
165  */
166 static unsigned int n_active;
167
168 /**
169  * Number of DHT service connections we currently have
170  */
171 static unsigned int n_dht;
172
173 /**
174  * Number of DHT PUTs made
175  */
176 static unsigned int n_puts;
177
178 /**
179  * Number of DHT PUTs succeeded
180  */
181 static unsigned int n_puts_ok;
182
183 /**
184  * Number of DHT PUTs failed
185  */
186 static unsigned int n_puts_fail;
187
188 /**
189  * Number of DHT GETs made
190  */
191 static unsigned int n_gets;
192
193 /**
194  * Number of DHT GETs succeeded
195  */
196 static unsigned int n_gets_ok;
197
198 /**
199  * Number of DHT GETs succeeded
200  */
201 static unsigned int n_gets_fail;
202
203
204 /**
205  * Shutdown task.  Cleanup all resources and operations.
206  *
207  * @param cls NULL
208  * @param tc scheduler task context
209  */
210 static void
211 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
212 {
213   struct ActiveContext *ac;
214   unsigned int cnt;
215
216   if (NULL != a_ctx)
217   {
218     for (cnt=0; cnt < num_peers; cnt++)
219     {
220       if (NULL != a_ctx[cnt].op)
221         GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
222
223       /* Cleanup active context if this peer is an active peer */
224       ac = a_ctx[cnt].ac;
225       if (NULL == ac)
226         continue;
227       if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
228         GNUNET_SCHEDULER_cancel (ac->delay_task);
229       if (NULL != ac->put_data)
230         GNUNET_free (ac->put_data);
231       if (NULL != ac->dht_put)
232         GNUNET_DHT_put_cancel (ac->dht_put);
233       if (NULL != ac->dht_get)
234         GNUNET_DHT_get_stop (ac->dht_get);
235     }
236     GNUNET_free (a_ctx);
237     a_ctx = NULL;
238   }
239   GNUNET_free_non_null (a_ac);
240 }
241
242
243 static void
244 summarize ()
245 {
246   INFO ("# PUTS made: %u\n", n_puts);
247   INFO ("# PUTS succeeded: %u\n", n_puts_ok);
248   INFO ("# PUTS failed: %u\n", n_puts_fail);
249   INFO ("# GETS made: %u\n", n_gets);
250   INFO ("# GETS succeeded: %u\n", n_gets_ok);
251   INFO ("# GETS failed: %u\n", n_gets_fail);
252   GNUNET_SCHEDULER_shutdown ();
253 }
254
255
256 /**
257  * Task to cancel DHT GET.
258  *
259  * @param cls NULL
260  * @param tc scheduler task context
261  */
262 static void
263 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
264 {
265   struct ActiveContext *ac = cls;
266
267   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
268   GNUNET_assert (NULL != ac->dht_get);
269   GNUNET_DHT_get_stop (ac->dht_get);
270   ac->dht_get = NULL;
271   n_gets_fail++;
272
273   /* If profiling is complete, summarize */
274   if (n_gets == n_gets_fail + n_gets_ok)
275     summarize ();
276 }
277
278
279 /**
280  * Iterator called on each result obtained for a DHT
281  * operation that expects a reply
282  *
283  * @param cls closure
284  * @param exp when will this value expire
285  * @param key key of the result
286  * @param get_path peers on reply path (or NULL if not recorded)
287  *                 [0] = datastore's first neighbor, [length - 1] = local peer
288  * @param get_path_length number of entries in @a get_path
289  * @param put_path peers on the PUT path (or NULL if not recorded)
290  *                 [0] = origin, [length - 1] = datastore
291  * @param put_path_length number of entries in @a put_path
292  * @param type type of the result
293  * @param size number of bytes in @a data
294  * @param data pointer to the result data
295  */
296 static void
297 get_iter (void *cls,
298           struct GNUNET_TIME_Absolute exp,
299           const struct GNUNET_HashCode *key,
300           const struct GNUNET_PeerIdentity *get_path,
301           unsigned int get_path_length,
302           const struct GNUNET_PeerIdentity *put_path,
303           unsigned int put_path_length,
304           enum GNUNET_BLOCK_Type type,
305           size_t size, const void *data)
306 {
307   struct ActiveContext *ac = cls;
308   struct ActiveContext *get_ac = ac->get_ac;
309
310   /* Check the keys of put and get match or not. */
311   if (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)))
312   {
313     if (get_ac->put_data_size != size)
314     {
315       DEBUG ("Found a GET with incorrect data length (this may happen, but very unlikely)\n");
316       return;
317     }
318     if (0 != memcmp (data, get_ac->put_data, size))
319     {
320       DEBUG ("Found a GET with incorrect data (this may happen, but very unlikely)\n");
321       return;
322     }
323   }
324   
325   /* we found the data we are looking for */
326   DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
327   n_gets_ok++;
328   get_ac->nrefs--;
329   GNUNET_DHT_get_stop (ac->dht_get);
330   ac->dht_get = NULL;
331   GNUNET_SCHEDULER_cancel (ac->delay_task);
332   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
333
334   /* Summarize if profiling is complete */
335   if (n_gets == n_gets_fail + n_gets_ok)
336     summarize ();
337 }
338
339
340 /**
341  * Task to do DHT GETs
342  *
343  * @param cls the active context
344  * @param tc the scheduler task context
345  */
346 static void
347 delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
348 {
349   struct ActiveContext *ac = cls;
350   struct ActiveContext *get_ac;
351   unsigned int r;
352
353   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
354   get_ac = NULL;
355   while (1)
356   {
357     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, n_active);
358     get_ac = &a_ac[r];
359     if (NULL != get_ac->put_data)
360       break;
361   }
362   get_ac->nrefs++;
363   ac->get_ac = get_ac;
364   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
365                                       GNUNET_BLOCK_TYPE_TEST,
366                                       &ac->hash,
367                                       1, /* replication level */
368                                       GNUNET_DHT_RO_NONE,
369                                       NULL, 0, /* extended query and size */
370                                       get_iter, ac); /* GET iterator and closure
371                                                         */
372   n_gets++;
373
374   /* schedule the timeout task for GET */
375   ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, &cancel_get, ac);
376 }
377
378
379 /**
380  * Queue up a delayed task for doing DHT GET
381  *
382  * @param cls the active context
383  * @param success #GNUNET_OK if the PUT was transmitted,
384  *                #GNUNET_NO on timeout,
385  *                #GNUNET_SYSERR on disconnect from service
386  *                after the PUT message was transmitted
387  *                (so we don't know if it was received or not)
388  */
389 static void
390 put_cont (void *cls, int success)
391 {
392   struct ActiveContext *ac = cls;
393
394   ac->dht_put = NULL;
395   if (success)
396     n_puts_ok++;
397   else
398     n_puts_fail++;
399   ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_get, ac);
400 }
401
402
403 /**
404  * Task to do DHT PUTS
405  *
406  * @param cls the active context
407  * @param tc the scheduler task context
408  */
409 static void
410 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
411 {
412   struct ActiveContext *ac = cls;
413
414   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
415   /* Generate and DHT PUT some random data */
416   ac->put_data_size = 16;       /* minimum */
417   ac->put_data_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
418                                                  (63*1024));
419   ac->put_data = GNUNET_malloc (ac->put_data_size);
420   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
421                               ac->put_data, ac->put_data_size);
422   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
423   DEBUG ("Doing a DHT PUT with data of size %u\n", ac->put_data_size);
424   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
425                                 1,            /* replication level */
426                                 GNUNET_DHT_RO_NONE,
427                                 GNUNET_BLOCK_TYPE_TEST,
428                                 ac->put_data_size,
429                                 ac->put_data,
430                                 GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */
431                                 timeout,                      /* PUT timeout */
432                                 put_cont, ac);                /* continuation and its closure */
433   n_puts++;
434 }
435
436
437 /**
438  * Connection to DHT has been established.  Call the delay task.
439  *
440  * @param cls the active context
441  * @param op the operation that has been finished
442  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
443  * @param emsg error message in case the operation has failed; will be NULL if
444  *          operation has executed successfully.
445  */
446 static void
447 dht_connected (void *cls,
448                struct GNUNET_TESTBED_Operation *op,
449                void *ca_result,
450                const char *emsg)
451 {
452   struct ActiveContext *ac = cls;
453   struct Context *ctx = ac->ctx;
454
455   GNUNET_assert (NULL != ctx);
456   GNUNET_assert (NULL != ctx->op);
457   GNUNET_assert (ctx->op == op);
458   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
459   if (NULL != emsg)
460   {
461     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
462     GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */
463     ctx->op = NULL;
464     return;
465   }
466   ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_put, ac);
467 }
468
469
470 /**
471  * Connect to DHT service and return the DHT client handler
472  *
473  * @param cls the active context
474  * @param cfg configuration of the peer to connect to; will be available until
475  *          GNUNET_TESTBED_operation_done() is called on the operation returned
476  *          from GNUNET_TESTBED_service_connect()
477  * @return service handle to return in 'op_result', NULL on error
478  */
479 static void *
480 dht_connect (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
481 {
482   n_dht++;
483   return GNUNET_DHT_connect (cfg, 10);
484 }
485
486
487 /**
488  * Adapter function called to destroy a connection to
489  * a service.
490  *
491  * @param cls the active context
492  * @param op_result service handle returned from the connect adapter
493  */
494 static void
495 dht_disconnect (void *cls, void *op_result)
496 {
497   struct ActiveContext *ac = cls;
498
499   GNUNET_assert (NULL != ac->dht);
500   GNUNET_assert (ac->dht == op_result);
501   GNUNET_DHT_disconnect (ac->dht);
502   n_dht--;
503   if (0 == n_dht)
504     GNUNET_SCHEDULER_shutdown ();
505 }
506
507
508 /**
509  * Callback called when DHT service on the peer is started
510  *
511  * @param cls the context
512  * @param op the operation that has been finished
513  * @param emsg error message in case the operation has failed; will be NULL if
514  *          operation has executed successfully.
515  */
516 static void
517 service_started (void *cls,
518                  struct GNUNET_TESTBED_Operation *op,
519                  const char *emsg)
520 {
521   struct Context *ctx = cls;
522
523   GNUNET_assert (NULL != ctx);
524   GNUNET_assert (NULL != ctx->op);
525   GNUNET_TESTBED_operation_done (ctx->op);
526   ctx->op = NULL;
527   if (NULL == ctx->ac)
528     return;
529   /* FIXME: connect to the DHT service and wait before starting a PUT */
530   ctx->op = GNUNET_TESTBED_service_connect (ctx, ctx->peer,
531                                             "dht",
532                                             &dht_connected, ctx->ac,
533                                             &dht_connect,
534                                             &dht_disconnect,
535                                             ctx->ac);
536 }
537
538
539 /**
540  * Signature of a main function for a testcase.
541  *
542  * @param cls closure
543  * @param h the run handle
544  * @param num_peers number of peers in 'peers'
545  * @param peers handle to peers run in the testbed
546  * @param links_succeeded the number of overlay link connection attempts that
547  *          succeeded
548  * @param links_failed the number of overlay link
549  */
550 static void
551 test_run (void *cls,
552           struct GNUNET_TESTBED_RunHandle *h,
553           unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers,
554           unsigned int links_succeeded,
555           unsigned int links_failed)
556 {
557   unsigned int cnt;
558   unsigned int ac_cnt;
559     
560   if (NULL == peers)
561   {
562     /* exit */
563     GNUNET_assert (0);
564   }
565   INFO ("%u peers started\n", num_peers);
566   a_ctx = GNUNET_malloc (sizeof (struct Context) * num_peers);
567
568   /* select the peers which actively participate in profiling */
569   n_active = num_peers * PUT_PROBABILITY / 100;
570   if (0 == n_active)
571   {
572     GNUNET_SCHEDULER_shutdown ();
573     GNUNET_free (a_ctx);
574     return;
575   }
576   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
577   ac_cnt = 0;
578   for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
579   {
580     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
581         PUT_PROBABILITY)
582       continue;
583     a_ctx[cnt].ac = &a_ac[ac_cnt];
584     a_ac[ac_cnt].ctx = &a_ctx[cnt];
585     ac_cnt++;
586   }
587   n_active = ac_cnt;
588   a_ac = GNUNET_realloc (a_ac, n_active * sizeof (struct ActiveContext));
589   INFO ("Active peers: %u\n", n_active);
590
591   /* start DHT service on all peers */
592   for (cnt = 0; cnt < num_peers; cnt++)
593   {
594     a_ctx[cnt].peer = peers[cnt];
595     a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt],
596                                                         peers[cnt],
597                                                         "dht",
598                                                         &service_started,
599                                                         &a_ctx[cnt],
600                                                         1);
601   }
602 }
603
604
605 /**
606  * Main function that will be run by the scheduler.
607  *
608  * @param cls closure
609  * @param args remaining command-line arguments
610  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
611  * @param config configuration
612  */
613 static void
614 run (void *cls, char *const *args, const char *cfgfile,
615      const struct GNUNET_CONFIGURATION_Handle *config)
616 {
617   uint64_t event_mask;
618
619   if (0 == num_peers)
620   {
621     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Exiting as the number of peers is %u\n"),
622                 num_peers);
623     return;
624   }
625   cfg = GNUNET_CONFIGURATION_dup (config);
626   event_mask = 0;
627   GNUNET_TESTBED_run (hosts_file, cfg, num_peers, event_mask, NULL,
628                       NULL, &test_run, NULL);
629   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
630                                 NULL);
631 }
632
633
634 /**
635  * Main function.
636  *
637  * @return 0 on success
638  */
639 int
640 main (int argc, char *const *argv)
641 {
642   int rc;
643
644   static struct GNUNET_GETOPT_CommandLineOption options[] = {
645     {'n', "peers", "COUNT",
646      gettext_noop ("number of peers to start"),
647      1, &GNUNET_GETOPT_set_uint, &num_peers},
648     {'H', "hosts", "FILENAME",
649      gettext_noop ("name of the file with the login information for the testbed"),
650      1, &GNUNET_GETOPT_set_string, &hosts_file},
651     {'d', "delay", "DELAY",
652      gettext_noop ("delay for starting DHT PUT and GET"),
653      1, &GNUNET_GETOPT_set_relative_time, &delay},
654     {'t', "timeout", "TIMEOUT",
655      gettext_noop ("timeout for DHT PUT and GET requests"),
656      1, &GNUNET_GETOPT_set_relative_time, &timeout},
657     GNUNET_GETOPT_OPTION_END
658   };
659
660   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
661     return 2;
662   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3); /* default delay */
663   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3); /* default timeout */
664   rc = 0;
665   if (GNUNET_OK !=
666       GNUNET_PROGRAM_run (argc, argv, "dht-profiler",
667                           gettext_noop
668                           ("Measure quality and performance of the DHT service."),
669                           options, &run, NULL))
670     rc = 1;
671   return rc;
672 }