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