Merge remote-tracking branch 'origin/master' into identity_abe
[oweals/gnunet.git] / src / rps / gnunet-service-rps_sampler.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps_sampler.c
23  * @brief sampler implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "rps.h"
29
30 #include "gnunet-service-rps_sampler.h"
31 #include "gnunet-service-rps_sampler_elem.h"
32
33 #include <math.h>
34 #include <inttypes.h>
35
36 #include "rps-test_util.h"
37
38 #define LOG(kind, ...) GNUNET_log_from(kind,"rps-sampler",__VA_ARGS__)
39
40
41 // multiple 'clients'?
42
43 // TODO check for overflows
44
45 // TODO align message structs
46
47 // hist_size_init, hist_size_max
48
49 /***********************************************************************
50  * WARNING: This section needs to be reviewed regarding the use of
51  * functions providing (pseudo)randomness!
52 ***********************************************************************/
53
54 // TODO care about invalid input of the caller (size 0 or less...)
55
56 /**
57  * Callback that is called from _get_rand_peer() when the PeerID is ready.
58  *
59  * @param cls the closure given alongside this function.
60  * @param id the PeerID that was returned
61  */
62 typedef void
63 (*RPS_sampler_rand_peer_ready_cont) (void *cls,
64                                      const struct GNUNET_PeerIdentity *id);
65
66
67 /**
68  * Closure for #sampler_mod_get_rand_peer() and #sampler_get_rand_peer
69  */
70 struct GetPeerCls
71 {
72   /**
73    * DLL
74    */
75   struct GetPeerCls *next;
76   struct GetPeerCls *prev;
77
78   /**
79    * The #RPS_SamplerRequestHandle this single request belongs to.
80    */
81   struct RPS_SamplerRequestHandle *req_handle;
82
83   /**
84    * The task for this function.
85    */
86   struct GNUNET_SCHEDULER_Task *get_peer_task;
87
88   /**
89    * The callback
90    */
91   RPS_sampler_rand_peer_ready_cont cont;
92
93   /**
94    * The closure to the callback @e cont
95    */
96   void *cont_cls;
97
98   /**
99    * The address of the id to be stored at
100    */
101   struct GNUNET_PeerIdentity *id;
102 };
103
104
105 /**
106  * Type of function used to differentiate between modified and not modified
107  * Sampler.
108  */
109 typedef void
110 (*RPS_get_peers_type) (void *cls);
111
112 /**
113  * Get one random peer out of the sampled peers.
114  *
115  * We might want to reinitialise this sampler after giving the
116  * corrsponding peer to the client.
117  * Only used internally
118  */
119 static void
120 sampler_get_rand_peer (void *cls);
121
122
123 /**
124  * Get one random peer out of the sampled peers.
125  *
126  * We might want to reinitialise this sampler after giving the
127  * corrsponding peer to the client.
128  */
129 static void
130 sampler_mod_get_rand_peer (void *cls);
131
132
133 /**
134  * Sampler with its own array of SamplerElements
135  */
136 struct RPS_Sampler
137 {
138   /**
139    * Number of sampler elements we hold.
140    */
141   unsigned int sampler_size;
142   //size_t size;
143
144   /**
145    * All sampler elements in one array.
146    */
147   struct RPS_SamplerElement **sampler_elements;
148
149   /**
150    * Maximum time a round takes
151    *
152    * Used in the context of RPS
153    */
154   struct GNUNET_TIME_Relative max_round_interval;
155
156   /**
157    * Stores the function to return peers. Which one it is depends on whether
158    * the Sampler is the modified one or not.
159    */
160   RPS_get_peers_type get_peers;
161
162   /**
163    * Head and tail for the DLL to store the #RPS_SamplerRequestHandle
164    */
165   struct RPS_SamplerRequestHandle *req_handle_head;
166   struct RPS_SamplerRequestHandle *req_handle_tail;
167
168   #ifdef TO_FILE
169   /**
170    * File name to log to
171    */
172   char *file_name;
173   #endif /* TO_FILE */
174 };
175
176 /**
177  * Closure to _get_n_rand_peers_ready_cb()
178  */
179 struct RPS_SamplerRequestHandle
180 {
181   /**
182    * DLL
183    */
184   struct RPS_SamplerRequestHandle *next;
185   struct RPS_SamplerRequestHandle *prev;
186
187   /**
188    * Number of peers we are waiting for.
189    */
190   uint32_t num_peers;
191
192   /**
193    * Number of peers we currently have.
194    */
195   uint32_t cur_num_peers;
196
197   /**
198    * Pointer to the array holding the ids.
199    */
200   struct GNUNET_PeerIdentity *ids;
201
202   /**
203    * Head and tail for the DLL to store the tasks for single requests
204    */
205   struct GetPeerCls *gpc_head;
206   struct GetPeerCls *gpc_tail;
207
208   /**
209    * Sampler.
210    */
211   struct RPS_Sampler *sampler;
212
213   /**
214    * Callback to be called when all ids are available.
215    */
216   RPS_sampler_n_rand_peers_ready_cb callback;
217
218   /**
219    * Closure given to the callback
220    */
221   void *cls;
222 };
223
224 ///**
225 // * Global sampler variable.
226 // */
227 //struct RPS_Sampler *sampler;
228
229
230 /**
231  * The minimal size for the extended sampler elements.
232  */
233 static size_t min_size;
234
235 /**
236  * The maximal size the extended sampler elements should grow to.
237  */
238 static size_t max_size;
239
240 /**
241  * The size the extended sampler elements currently have.
242  */
243 //static size_t extra_size;
244
245 /**
246  * Inedex to the sampler element that is the next to be returned
247  */
248 static uint32_t client_get_index;
249
250
251 /**
252  * Callback to _get_rand_peer() used by _get_n_rand_peers().
253  *
254  * Checks whether all n peers are available. If they are,
255  * give those back.
256  */
257 static void
258 check_n_peers_ready (void *cls,
259     const struct GNUNET_PeerIdentity *id)
260 {
261   struct RPS_SamplerRequestHandle *req_handle = cls;
262
263   req_handle->cur_num_peers++;
264   LOG (GNUNET_ERROR_TYPE_DEBUG,
265       "Got %" PRIX32 ". of %" PRIX32 " peers\n",
266       req_handle->cur_num_peers, req_handle->num_peers);
267
268   if (req_handle->num_peers == req_handle->cur_num_peers)
269   { /* All peers are ready -- return those to the client */
270     GNUNET_assert (NULL != req_handle->callback);
271
272     LOG (GNUNET_ERROR_TYPE_DEBUG,
273         "returning %" PRIX32 " peers to the client\n",
274         req_handle->num_peers);
275     req_handle->callback (req_handle->cls, req_handle->ids, req_handle->num_peers);
276
277     RPS_sampler_request_cancel (req_handle);
278   }
279 }
280
281
282 /**
283  * Get the size of the sampler.
284  *
285  * @param sampler the sampler to return the size of.
286  * @return the size of the sampler
287  */
288 unsigned int
289 RPS_sampler_get_size (struct RPS_Sampler *sampler)
290 {
291   return sampler->sampler_size;
292 }
293
294
295 /**
296  * Grow or shrink the size of the sampler.
297  *
298  * @param sampler the sampler to resize.
299  * @param new_size the new size of the sampler
300  */
301 static void
302 sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
303 {
304   unsigned int old_size;
305   uint32_t i;
306
307   // TODO check min and max size
308
309   old_size = sampler->sampler_size;
310
311   if (old_size > new_size)
312   { /* Shrinking */
313
314     LOG (GNUNET_ERROR_TYPE_DEBUG,
315          "Shrinking sampler %d -> %d\n",
316          old_size,
317          new_size);
318
319     to_file (sampler->file_name,
320          "Shrinking sampler %d -> %d",
321          old_size,
322          new_size);
323
324     for (i = new_size ; i < old_size ; i++)
325     {
326       to_file (sampler->file_name,
327                "-%" PRIu32 ": %s",
328                i,
329                sampler->sampler_elements[i]->file_name);
330       RPS_sampler_elem_destroy (sampler->sampler_elements[i]);
331     }
332
333     GNUNET_array_grow (sampler->sampler_elements,
334                        sampler->sampler_size,
335                        new_size);
336     LOG (GNUNET_ERROR_TYPE_DEBUG,
337          "sampler->sampler_elements now points to %p\n",
338          sampler->sampler_elements);
339
340   }
341   else if (old_size < new_size)
342   { /* Growing */
343     LOG (GNUNET_ERROR_TYPE_DEBUG,
344          "Growing sampler %d -> %d\n",
345          old_size,
346          new_size);
347
348     to_file (sampler->file_name,
349          "Growing sampler %d -> %d",
350          old_size,
351          new_size);
352
353     GNUNET_array_grow (sampler->sampler_elements,
354         sampler->sampler_size,
355         new_size);
356
357     for (i = old_size ; i < new_size ; i++)
358     { /* Add new sampler elements */
359       sampler->sampler_elements[i] = RPS_sampler_elem_create ();
360
361       to_file (sampler->file_name,
362                "+%" PRIu32 ": %s",
363                i,
364                sampler->sampler_elements[i]->file_name);
365     }
366   }
367   else
368   {
369     LOG (GNUNET_ERROR_TYPE_DEBUG, "Size remains the same -- nothing to do\n");
370     return;
371   }
372
373   GNUNET_assert (sampler->sampler_size == new_size);
374 }
375
376
377 /**
378  * Grow or shrink the size of the sampler.
379  *
380  * @param sampler the sampler to resize.
381  * @param new_size the new size of the sampler
382  */
383 void
384 RPS_sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
385 {
386   GNUNET_assert (0 < new_size);
387   sampler_resize (sampler, new_size);
388 }
389
390
391 /**
392  * Empty the sampler.
393  *
394  * @param sampler the sampler to empty.
395  * @param new_size the new size of the sampler
396  */
397 static void
398 sampler_empty (struct RPS_Sampler *sampler)
399 {
400   sampler_resize (sampler, 0);
401 }
402
403
404 /**
405  * Initialise a tuple of sampler elements.
406  *
407  * @param init_size the size the sampler is initialised with
408  * @param max_round_interval maximum time a round takes
409  * @return a handle to a sampler that consists of sampler elements.
410  */
411 struct RPS_Sampler *
412 RPS_sampler_init (size_t init_size,
413                   struct GNUNET_TIME_Relative max_round_interval)
414 {
415   struct RPS_Sampler *sampler;
416
417   /* Initialise context around extended sampler */
418   min_size = 10; // TODO make input to _samplers_init()
419   max_size = 1000; // TODO make input to _samplers_init()
420
421   sampler = GNUNET_new (struct RPS_Sampler);
422
423   #ifdef TO_FILE
424   sampler->file_name = create_file ("sampler-");
425
426   LOG (GNUNET_ERROR_TYPE_DEBUG,
427        "Initialised sampler %s\n",
428        sampler->file_name);
429   #endif /* TO_FILE */
430
431   sampler->max_round_interval = max_round_interval;
432   sampler->get_peers = sampler_get_rand_peer;
433   //sampler->sampler_elements = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
434   //GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, min_size);
435   RPS_sampler_resize (sampler, init_size);
436
437   client_get_index = 0;
438
439   //GNUNET_assert (init_size == sampler->sampler_size);
440   return sampler;
441 }
442
443 /**
444  * Initialise a modified tuple of sampler elements.
445  *
446  * @param init_size the size the sampler is initialised with
447  * @param max_round_interval maximum time a round takes
448  * @return a handle to a sampler that consists of sampler elements.
449  */
450 struct RPS_Sampler *
451 RPS_sampler_mod_init (size_t init_size,
452                       struct GNUNET_TIME_Relative max_round_interval)
453 {
454   struct RPS_Sampler *sampler;
455
456   sampler = RPS_sampler_init (init_size, max_round_interval);
457   sampler->get_peers = sampler_mod_get_rand_peer;
458
459   LOG (GNUNET_ERROR_TYPE_DEBUG,
460        "Initialised modified sampler %s\n",
461        sampler->file_name);
462   to_file (sampler->file_name,
463            "This is a modified sampler");
464
465   return sampler;
466 }
467
468
469 /**
470  * A fuction to update every sampler in the given list
471  *
472  * @param sampler the sampler to update.
473  * @param id the PeerID that is put in the sampler
474  */
475   void
476 RPS_sampler_update (struct RPS_Sampler *sampler,
477                     const struct GNUNET_PeerIdentity *id)
478 {
479   uint32_t i;
480
481   to_file (sampler->file_name,
482            "Got %s",
483            GNUNET_i2s_full (id));
484
485   for (i = 0 ; i < sampler->sampler_size ; i++)
486   {
487     RPS_sampler_elem_next (sampler->sampler_elements[i],
488                            id);
489   }
490
491 }
492
493
494 /**
495  * Reinitialise all previously initialised sampler elements with the given value.
496  *
497  * Used to get rid of a PeerID.
498  *
499  * @param sampler the sampler to reinitialise a sampler element in.
500  * @param id the id of the sampler elements to update.
501  */
502   void
503 RPS_sampler_reinitialise_by_value (struct RPS_Sampler *sampler,
504                                    const struct GNUNET_PeerIdentity *id)
505 {
506   uint32_t i;
507
508   for (i = 0; i < sampler->sampler_size; i++)
509   {
510     if (0 == GNUNET_CRYPTO_cmp_peer_identity(id,
511           &(sampler->sampler_elements[i]->peer_id)) )
512     {
513       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reinitialising sampler\n");
514       to_file (sampler->sampler_elements[i]->file_name,
515                "--- non-active");
516       RPS_sampler_elem_reinit (sampler->sampler_elements[i]);
517     }
518   }
519 }
520
521
522 /**
523  * Get one random peer out of the sampled peers.
524  *
525  * We might want to reinitialise this sampler after giving the
526  * corrsponding peer to the client.
527  * Only used internally
528  */
529 static void
530 sampler_get_rand_peer (void *cls)
531 {
532   struct GetPeerCls *gpc = cls;
533   uint32_t r_index;
534   struct RPS_Sampler *sampler;
535
536   gpc->get_peer_task = NULL;
537   sampler = gpc->req_handle->sampler;
538
539   /**;
540    * Choose the r_index of the peer we want to return
541    * at random from the interval of the gossip list
542    */
543   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
544       sampler->sampler_size);
545
546   if (EMPTY == sampler->sampler_elements[r_index]->is_empty)
547   {
548     //LOG (GNUNET_ERROR_TYPE_DEBUG,
549     //     "Not returning randomly selected, empty PeerID. - Rescheduling.\n");
550
551     /* FIXME no active wait - get notified, when new id arrives?
552      * Might also be a freshly emptied one. Others might still contain ids.
553      * Counter?
554      */
555     gpc->get_peer_task =
556       GNUNET_SCHEDULER_add_delayed (
557           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1),
558           &sampler_get_rand_peer,
559           cls);
560     return;
561   }
562
563   GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
564                                gpc->req_handle->gpc_tail,
565                                gpc);
566   *gpc->id = sampler->sampler_elements[r_index]->peer_id;
567   gpc->cont (gpc->cont_cls, gpc->id);
568
569   GNUNET_free (gpc);
570 }
571
572
573 /**
574  * Get one random peer out of the sampled peers.
575  *
576  * We might want to reinitialise this sampler after giving the
577  * corrsponding peer to the client.
578  */
579 static void
580 sampler_mod_get_rand_peer (void *cls)
581 {
582   struct GetPeerCls *gpc = cls;
583   struct RPS_SamplerElement *s_elem;
584   struct GNUNET_TIME_Relative last_request_diff;
585   struct RPS_Sampler *sampler;
586
587   gpc->get_peer_task = NULL;
588   sampler = gpc->req_handle->sampler;
589
590   LOG (GNUNET_ERROR_TYPE_DEBUG, "Single peer was requested\n");
591
592   /* Cycle the #client_get_index one step further */
593   client_get_index = (client_get_index + 1) % sampler->sampler_size;
594
595   s_elem = sampler->sampler_elements[client_get_index];
596   *gpc->id = s_elem->peer_id;
597   GNUNET_assert (NULL != s_elem);
598
599   if (EMPTY == s_elem->is_empty)
600   {
601     LOG (GNUNET_ERROR_TYPE_DEBUG,
602          "Sampler_mod element empty, rescheduling.\n");
603     GNUNET_assert (NULL == gpc->get_peer_task);
604     gpc->get_peer_task =
605       GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
606                                     &sampler_mod_get_rand_peer,
607                                     cls);
608     return;
609   }
610
611   /* Check whether we may use this sampler to give it back to the client */
612   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != s_elem->last_client_request.abs_value_us)
613   {
614     last_request_diff =
615       GNUNET_TIME_absolute_get_difference (s_elem->last_client_request,
616                                            GNUNET_TIME_absolute_get ());
617     /* We're not going to give it back now if it was
618      * already requested by a client this round */
619     if (last_request_diff.rel_value_us < sampler->max_round_interval.rel_value_us)
620     {
621       LOG (GNUNET_ERROR_TYPE_DEBUG,
622           "Last client request on this sampler was less than max round interval ago -- scheduling for later\n");
623       ///* How many time remains untile the next round has started? */
624       //inv_last_request_diff =
625       //  GNUNET_TIME_absolute_get_difference (last_request_diff,
626       //                                       sampler->max_round_interval);
627       // add a little delay
628       /* Schedule it one round later */
629       GNUNET_assert (NULL == gpc->get_peer_task);
630       gpc->get_peer_task =
631         GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
632                                       &sampler_mod_get_rand_peer,
633                                       cls);
634       return;
635     }
636     // TODO add other reasons to wait here
637   }
638
639   s_elem->last_client_request = GNUNET_TIME_absolute_get ();
640
641   GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
642                                gpc->req_handle->gpc_tail,
643                                gpc);
644   gpc->cont (gpc->cont_cls, gpc->id);
645   GNUNET_free (gpc);
646 }
647
648
649 /**
650  * Get n random peers out of the sampled peers.
651  *
652  * We might want to reinitialise this sampler after giving the
653  * corrsponding peer to the client.
654  * Random with or without consumption?
655  *
656  * @param sampler the sampler to get peers from.
657  * @param cb callback that will be called once the ids are ready.
658  * @param cls closure given to @a cb
659  * @param for_client #GNUNET_YES if result is used for client,
660  *                   #GNUNET_NO if used internally
661  * @param num_peers the number of peers requested
662  */
663 struct RPS_SamplerRequestHandle *
664 RPS_sampler_get_n_rand_peers (struct RPS_Sampler *sampler,
665                               RPS_sampler_n_rand_peers_ready_cb cb,
666                               void *cls, uint32_t num_peers)
667 {
668   GNUNET_assert (0 != sampler->sampler_size);
669   if (0 == num_peers)
670     return NULL;
671
672   // TODO check if we have too much (distinct) sampled peers
673   uint32_t i;
674   struct RPS_SamplerRequestHandle *req_handle;
675   struct GetPeerCls *gpc;
676
677   req_handle = GNUNET_new (struct RPS_SamplerRequestHandle);
678   req_handle->num_peers = num_peers;
679   req_handle->cur_num_peers = 0;
680   req_handle->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
681   req_handle->sampler = sampler;
682   req_handle->callback = cb;
683   req_handle->cls = cls;
684   GNUNET_CONTAINER_DLL_insert (sampler->req_handle_head,
685                                sampler->req_handle_tail,
686                                req_handle);
687
688   LOG (GNUNET_ERROR_TYPE_DEBUG,
689       "Scheduling requests for %" PRIu32 " peers\n", num_peers);
690
691   for (i = 0 ; i < num_peers ; i++)
692   {
693     gpc = GNUNET_new (struct GetPeerCls);
694     gpc->req_handle = req_handle;
695     gpc->cont = check_n_peers_ready;
696     gpc->cont_cls = req_handle;
697     gpc->id = &req_handle->ids[i];
698
699     GNUNET_CONTAINER_DLL_insert (req_handle->gpc_head,
700                                  req_handle->gpc_tail,
701                                  gpc);
702     // maybe add a little delay
703     gpc->get_peer_task = GNUNET_SCHEDULER_add_now (sampler->get_peers,
704                                                    gpc);
705   }
706   return req_handle;
707 }
708
709 /**
710  * Cancle a request issued through #RPS_sampler_n_rand_peers_ready_cb.
711  *
712  * @param req_handle the handle to the request
713  */
714 void
715 RPS_sampler_request_cancel (struct RPS_SamplerRequestHandle *req_handle)
716 {
717   struct GetPeerCls *i;
718
719   while (NULL != (i = req_handle->gpc_head) )
720   {
721     GNUNET_CONTAINER_DLL_remove (req_handle->gpc_head,
722                                  req_handle->gpc_tail,
723                                  i);
724     if (NULL != i->get_peer_task)
725     {
726       GNUNET_SCHEDULER_cancel (i->get_peer_task);
727     }
728     GNUNET_free (i);
729   }
730   GNUNET_CONTAINER_DLL_remove (req_handle->sampler->req_handle_head,
731                                req_handle->sampler->req_handle_tail,
732                                req_handle);
733   GNUNET_free (req_handle);
734 }
735
736
737 /**
738  * Counts how many Samplers currently hold a given PeerID.
739  *
740  * @param sampler the sampler to count ids in.
741  * @param id the PeerID to count.
742  *
743  * @return the number of occurrences of id.
744  */
745   uint32_t
746 RPS_sampler_count_id (struct RPS_Sampler *sampler,
747                       const struct GNUNET_PeerIdentity *id)
748 {
749   uint32_t count;
750   uint32_t i;
751
752   count = 0;
753   for ( i = 0 ; i < sampler->sampler_size ; i++ )
754   {
755     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&sampler->sampler_elements[i]->peer_id, id)
756         && EMPTY != sampler->sampler_elements[i]->is_empty)
757       count++;
758   }
759   return count;
760 }
761
762
763 /**
764  * Cleans the sampler.
765  */
766   void
767 RPS_sampler_destroy (struct RPS_Sampler *sampler)
768 {
769   if (NULL != sampler->req_handle_head)
770   {
771     LOG (GNUNET_ERROR_TYPE_WARNING,
772         "There are still pending requests. Going to remove them.\n");
773     while (NULL != sampler->req_handle_head)
774     {
775       RPS_sampler_request_cancel (sampler->req_handle_head);
776     }
777   }
778   sampler_empty (sampler);
779   GNUNET_free (sampler);
780 }
781
782 /* end of gnunet-service-rps.c */