rps: keep track of valid peers in peermap
[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     }
331
332     GNUNET_array_grow (sampler->sampler_elements,
333                        sampler->sampler_size,
334                        new_size);
335     LOG (GNUNET_ERROR_TYPE_DEBUG,
336          "sampler->sampler_elements now points to %p\n",
337          sampler->sampler_elements);
338
339   }
340   else if (old_size < new_size)
341   { /* Growing */
342     LOG (GNUNET_ERROR_TYPE_DEBUG,
343          "Growing sampler %d -> %d\n",
344          old_size,
345          new_size);
346
347     to_file (sampler->file_name,
348          "Growing sampler %d -> %d",
349          old_size,
350          new_size);
351
352     GNUNET_array_grow (sampler->sampler_elements,
353         sampler->sampler_size,
354         new_size);
355
356     for (i = old_size ; i < new_size ; i++)
357     { /* Add new sampler elements */
358       sampler->sampler_elements[i] = RPS_sampler_elem_create ();
359
360       to_file (sampler->file_name,
361                "+%" PRIu32 ": %s",
362                i,
363                sampler->sampler_elements[i]->file_name);
364     }
365   }
366   else
367   {
368     LOG (GNUNET_ERROR_TYPE_DEBUG, "Size remains the same -- nothing to do\n");
369     return;
370   }
371
372   GNUNET_assert (sampler->sampler_size == new_size);
373 }
374
375
376 /**
377  * Grow or shrink the size of the sampler.
378  *
379  * @param sampler the sampler to resize.
380  * @param new_size the new size of the sampler
381  */
382 void
383 RPS_sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
384 {
385   GNUNET_assert (0 < new_size);
386   sampler_resize (sampler, new_size);
387 }
388
389
390 /**
391  * Empty the sampler.
392  *
393  * @param sampler the sampler to empty.
394  * @param new_size the new size of the sampler
395  */
396 static void
397 sampler_empty (struct RPS_Sampler *sampler)
398 {
399   sampler_resize (sampler, 0);
400 }
401
402
403 /**
404  * Initialise a tuple of sampler elements.
405  *
406  * @param init_size the size the sampler is initialised with
407  * @param max_round_interval maximum time a round takes
408  * @return a handle to a sampler that consists of sampler elements.
409  */
410 struct RPS_Sampler *
411 RPS_sampler_init (size_t init_size,
412                   struct GNUNET_TIME_Relative max_round_interval)
413 {
414   struct RPS_Sampler *sampler;
415
416   /* Initialise context around extended sampler */
417   min_size = 10; // TODO make input to _samplers_init()
418   max_size = 1000; // TODO make input to _samplers_init()
419
420   sampler = GNUNET_new (struct RPS_Sampler);
421
422   #ifdef TO_FILE
423   sampler->file_name = create_file ("sampler-");
424
425   LOG (GNUNET_ERROR_TYPE_DEBUG,
426        "Initialised sampler %s\n",
427        sampler->file_name);
428   #endif /* TO_FILE */
429
430   sampler->max_round_interval = max_round_interval;
431   sampler->get_peers = sampler_get_rand_peer;
432   //sampler->sampler_elements = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
433   //GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, min_size);
434   RPS_sampler_resize (sampler, init_size);
435
436   client_get_index = 0;
437
438   //GNUNET_assert (init_size == sampler->sampler_size);
439   return sampler;
440 }
441
442 /**
443  * Initialise a modified tuple of sampler elements.
444  *
445  * @param init_size the size the sampler is initialised with
446  * @param max_round_interval maximum time a round takes
447  * @return a handle to a sampler that consists of sampler elements.
448  */
449 struct RPS_Sampler *
450 RPS_sampler_mod_init (size_t init_size,
451                       struct GNUNET_TIME_Relative max_round_interval)
452 {
453   struct RPS_Sampler *sampler;
454
455   sampler = RPS_sampler_init (init_size, max_round_interval);
456   sampler->get_peers = sampler_mod_get_rand_peer;
457
458   LOG (GNUNET_ERROR_TYPE_DEBUG,
459        "Initialised modified sampler %s\n",
460        sampler->file_name);
461   to_file (sampler->file_name,
462            "This is a modified sampler");
463
464   return sampler;
465 }
466
467
468 /**
469  * A fuction to update every sampler in the given list
470  *
471  * @param sampler the sampler to update.
472  * @param id the PeerID that is put in the sampler
473  */
474   void
475 RPS_sampler_update (struct RPS_Sampler *sampler,
476                     const struct GNUNET_PeerIdentity *id)
477 {
478   uint32_t i;
479
480   to_file (sampler->file_name,
481            "Got %s",
482            GNUNET_i2s_full (id));
483
484   for (i = 0 ; i < sampler->sampler_size ; i++)
485   {
486     RPS_sampler_elem_next (sampler->sampler_elements[i],
487                            id);
488   }
489
490 }
491
492
493 /**
494  * Reinitialise all previously initialised sampler elements with the given value.
495  *
496  * Used to get rid of a PeerID.
497  *
498  * @param sampler the sampler to reinitialise a sampler element in.
499  * @param id the id of the sampler elements to update.
500  */
501   void
502 RPS_sampler_reinitialise_by_value (struct RPS_Sampler *sampler,
503                                    const struct GNUNET_PeerIdentity *id)
504 {
505   uint32_t i;
506   struct RPS_SamplerElement *trash_entry;
507
508   for ( i = 0 ; i < sampler->sampler_size ; i++ )
509   {
510     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity(id, &(sampler->sampler_elements[i]->peer_id)) )
511     {
512       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reinitialising sampler\n");
513       trash_entry = GNUNET_new (struct RPS_SamplerElement);
514       *trash_entry = *(sampler->sampler_elements[i]);
515       to_file (trash_entry->file_name,
516                "--- non-active");
517       RPS_sampler_elem_reinit (sampler->sampler_elements[i]);
518     }
519   }
520 }
521
522
523 /**
524  * Get one random peer out of the sampled peers.
525  *
526  * We might want to reinitialise this sampler after giving the
527  * corrsponding peer to the client.
528  * Only used internally
529  */
530 static void
531 sampler_get_rand_peer (void *cls)
532 {
533   struct GetPeerCls *gpc = cls;
534   uint32_t r_index;
535   struct RPS_Sampler *sampler;
536
537   gpc->get_peer_task = NULL;
538   sampler = gpc->req_handle->sampler;
539
540   /**;
541    * Choose the r_index of the peer we want to return
542    * at random from the interval of the gossip list
543    */
544   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
545       sampler->sampler_size);
546
547   if (EMPTY == sampler->sampler_elements[r_index]->is_empty)
548   {
549     //LOG (GNUNET_ERROR_TYPE_DEBUG,
550     //     "Not returning randomly selected, empty PeerID. - Rescheduling.\n");
551
552     /* FIXME no active wait - get notified, when new id arrives?
553      * Might also be a freshly emptied one. Others might still contain ids.
554      * Counter?
555      */
556     gpc->get_peer_task =
557       GNUNET_SCHEDULER_add_delayed (
558           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1),
559           &sampler_get_rand_peer,
560           cls);
561     return;
562   }
563
564   GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
565                                gpc->req_handle->gpc_tail,
566                                gpc);
567   *gpc->id = sampler->sampler_elements[r_index]->peer_id;
568   gpc->cont (gpc->cont_cls, gpc->id);
569
570   GNUNET_free (gpc);
571 }
572
573
574 /**
575  * Get one random peer out of the sampled peers.
576  *
577  * We might want to reinitialise this sampler after giving the
578  * corrsponding peer to the client.
579  */
580 static void
581 sampler_mod_get_rand_peer (void *cls)
582 {
583   struct GetPeerCls *gpc = cls;
584   struct RPS_SamplerElement *s_elem;
585   struct GNUNET_TIME_Relative last_request_diff;
586   struct RPS_Sampler *sampler;
587
588   gpc->get_peer_task = NULL;
589   sampler = gpc->req_handle->sampler;
590
591   LOG (GNUNET_ERROR_TYPE_DEBUG, "Single peer was requested\n");
592
593   /* Cycle the #client_get_index one step further */
594   client_get_index = (client_get_index + 1) % sampler->sampler_size;
595
596   s_elem = sampler->sampler_elements[client_get_index];
597   *gpc->id = s_elem->peer_id;
598   GNUNET_assert (NULL != s_elem);
599
600   if (EMPTY == s_elem->is_empty)
601   {
602     LOG (GNUNET_ERROR_TYPE_DEBUG,
603          "Sampler_mod element empty, rescheduling.\n");
604     GNUNET_assert (NULL == gpc->get_peer_task);
605     gpc->get_peer_task =
606       GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
607                                     &sampler_mod_get_rand_peer,
608                                     cls);
609     return;
610   }
611
612   /* Check whether we may use this sampler to give it back to the client */
613   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != s_elem->last_client_request.abs_value_us)
614   {
615     last_request_diff =
616       GNUNET_TIME_absolute_get_difference (s_elem->last_client_request,
617                                            GNUNET_TIME_absolute_get ());
618     /* We're not going to give it back now if it was
619      * already requested by a client this round */
620     if (last_request_diff.rel_value_us < sampler->max_round_interval.rel_value_us)
621     {
622       LOG (GNUNET_ERROR_TYPE_DEBUG,
623           "Last client request on this sampler was less than max round interval ago -- scheduling for later\n");
624       ///* How many time remains untile the next round has started? */
625       //inv_last_request_diff =
626       //  GNUNET_TIME_absolute_get_difference (last_request_diff,
627       //                                       sampler->max_round_interval);
628       // add a little delay
629       /* Schedule it one round later */
630       GNUNET_assert (NULL == gpc->get_peer_task);
631       gpc->get_peer_task =
632         GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
633                                       &sampler_mod_get_rand_peer,
634                                       cls);
635       return;
636     }
637     // TODO add other reasons to wait here
638   }
639
640   s_elem->last_client_request = GNUNET_TIME_absolute_get ();
641
642   GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
643                                gpc->req_handle->gpc_tail,
644                                gpc);
645   gpc->cont (gpc->cont_cls, gpc->id);
646   GNUNET_free (gpc);
647 }
648
649
650 /**
651  * Get n random peers out of the sampled peers.
652  *
653  * We might want to reinitialise this sampler after giving the
654  * corrsponding peer to the client.
655  * Random with or without consumption?
656  *
657  * @param sampler the sampler to get peers from.
658  * @param cb callback that will be called once the ids are ready.
659  * @param cls closure given to @a cb
660  * @param for_client #GNUNET_YES if result is used for client,
661  *                   #GNUNET_NO if used internally
662  * @param num_peers the number of peers requested
663  */
664 struct RPS_SamplerRequestHandle *
665 RPS_sampler_get_n_rand_peers (struct RPS_Sampler *sampler,
666                               RPS_sampler_n_rand_peers_ready_cb cb,
667                               void *cls, uint32_t num_peers)
668 {
669   GNUNET_assert (0 != sampler->sampler_size);
670   if (0 == num_peers)
671     return NULL;
672
673   // TODO check if we have too much (distinct) sampled peers
674   uint32_t i;
675   struct RPS_SamplerRequestHandle *req_handle;
676   struct GetPeerCls *gpc;
677
678   req_handle = GNUNET_new (struct RPS_SamplerRequestHandle);
679   req_handle->num_peers = num_peers;
680   req_handle->cur_num_peers = 0;
681   req_handle->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
682   req_handle->sampler = sampler;
683   req_handle->callback = cb;
684   req_handle->cls = cls;
685   GNUNET_CONTAINER_DLL_insert (sampler->req_handle_head,
686                                sampler->req_handle_tail,
687                                req_handle);
688
689   LOG (GNUNET_ERROR_TYPE_DEBUG,
690       "Scheduling requests for %" PRIu32 " peers\n", num_peers);
691
692   for (i = 0 ; i < num_peers ; i++)
693   {
694     gpc = GNUNET_new (struct GetPeerCls);
695     gpc->req_handle = req_handle;
696     gpc->cont = check_n_peers_ready;
697     gpc->cont_cls = req_handle;
698     gpc->id = &req_handle->ids[i];
699
700     GNUNET_CONTAINER_DLL_insert (req_handle->gpc_head,
701                                  req_handle->gpc_tail,
702                                  gpc);
703     // maybe add a little delay
704     gpc->get_peer_task = GNUNET_SCHEDULER_add_now (sampler->get_peers,
705                                                    gpc);
706   }
707   return req_handle;
708 }
709
710 /**
711  * Cancle a request issued through #RPS_sampler_n_rand_peers_ready_cb.
712  *
713  * @param req_handle the handle to the request
714  */
715 void
716 RPS_sampler_request_cancel (struct RPS_SamplerRequestHandle *req_handle)
717 {
718   struct GetPeerCls *i;
719
720   while (NULL != (i = req_handle->gpc_head) )
721   {
722     GNUNET_CONTAINER_DLL_remove (req_handle->gpc_head,
723                                  req_handle->gpc_tail,
724                                  i);
725     if (NULL != i->get_peer_task)
726       GNUNET_SCHEDULER_cancel (i->get_peer_task);
727     GNUNET_free (i);
728   }
729   GNUNET_CONTAINER_DLL_remove (req_handle->sampler->req_handle_head,
730                                req_handle->sampler->req_handle_tail,
731                                req_handle);
732   GNUNET_free (req_handle);
733 }
734
735
736 /**
737  * Counts how many Samplers currently hold a given PeerID.
738  *
739  * @param sampler the sampler to count ids in.
740  * @param id the PeerID to count.
741  *
742  * @return the number of occurrences of id.
743  */
744   uint32_t
745 RPS_sampler_count_id (struct RPS_Sampler *sampler,
746                       const struct GNUNET_PeerIdentity *id)
747 {
748   uint32_t count;
749   uint32_t i;
750
751   count = 0;
752   for ( i = 0 ; i < sampler->sampler_size ; i++ )
753   {
754     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&sampler->sampler_elements[i]->peer_id, id)
755         && EMPTY != sampler->sampler_elements[i]->is_empty)
756       count++;
757   }
758   return count;
759 }
760
761
762 /**
763  * Cleans the sampler.
764  */
765   void
766 RPS_sampler_destroy (struct RPS_Sampler *sampler)
767 {
768   if (NULL != sampler->req_handle_head)
769   {
770     LOG (GNUNET_ERROR_TYPE_WARNING,
771         "There are still pending requests. Going to remove them.\n");
772     while (NULL != sampler->req_handle_head)
773       RPS_sampler_request_cancel (sampler->req_handle_head);
774   }
775   sampler_empty (sampler);
776   GNUNET_free (sampler);
777 }
778
779 /* end of gnunet-service-rps.c */