plugin datastore mysql
[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       GNUNET_free (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   struct RPS_SamplerElement *trash_entry;
508
509   for ( i = 0 ; i < sampler->sampler_size ; i++ )
510   {
511     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity(id, &(sampler->sampler_elements[i]->peer_id)) )
512     {
513       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reinitialising sampler\n");
514       trash_entry = GNUNET_new (struct RPS_SamplerElement);
515       *trash_entry = *(sampler->sampler_elements[i]);
516       to_file (trash_entry->file_name,
517                "--- non-active");
518       RPS_sampler_elem_reinit (sampler->sampler_elements[i]);
519     }
520   }
521 }
522
523
524 /**
525  * Get one random peer out of the sampled peers.
526  *
527  * We might want to reinitialise this sampler after giving the
528  * corrsponding peer to the client.
529  * Only used internally
530  */
531 static void
532 sampler_get_rand_peer (void *cls)
533 {
534   struct GetPeerCls *gpc = cls;
535   uint32_t r_index;
536   struct RPS_Sampler *sampler;
537
538   gpc->get_peer_task = NULL;
539   sampler = gpc->req_handle->sampler;
540
541   /**;
542    * Choose the r_index of the peer we want to return
543    * at random from the interval of the gossip list
544    */
545   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
546       sampler->sampler_size);
547
548   if (EMPTY == sampler->sampler_elements[r_index]->is_empty)
549   {
550     //LOG (GNUNET_ERROR_TYPE_DEBUG,
551     //     "Not returning randomly selected, empty PeerID. - Rescheduling.\n");
552
553     /* FIXME no active wait - get notified, when new id arrives?
554      * Might also be a freshly emptied one. Others might still contain ids.
555      * Counter?
556      */
557     gpc->get_peer_task =
558       GNUNET_SCHEDULER_add_delayed (
559           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1),
560           &sampler_get_rand_peer,
561           cls);
562     return;
563   }
564
565   GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
566                                gpc->req_handle->gpc_tail,
567                                gpc);
568   *gpc->id = sampler->sampler_elements[r_index]->peer_id;
569   gpc->cont (gpc->cont_cls, gpc->id);
570
571   GNUNET_free (gpc);
572 }
573
574
575 /**
576  * Get one random peer out of the sampled peers.
577  *
578  * We might want to reinitialise this sampler after giving the
579  * corrsponding peer to the client.
580  */
581 static void
582 sampler_mod_get_rand_peer (void *cls)
583 {
584   struct GetPeerCls *gpc = cls;
585   struct RPS_SamplerElement *s_elem;
586   struct GNUNET_TIME_Relative last_request_diff;
587   struct RPS_Sampler *sampler;
588
589   gpc->get_peer_task = NULL;
590   sampler = gpc->req_handle->sampler;
591
592   LOG (GNUNET_ERROR_TYPE_DEBUG, "Single peer was requested\n");
593
594   /* Cycle the #client_get_index one step further */
595   client_get_index = (client_get_index + 1) % sampler->sampler_size;
596
597   s_elem = sampler->sampler_elements[client_get_index];
598   *gpc->id = s_elem->peer_id;
599   GNUNET_assert (NULL != s_elem);
600
601   if (EMPTY == s_elem->is_empty)
602   {
603     LOG (GNUNET_ERROR_TYPE_DEBUG,
604          "Sampler_mod element empty, rescheduling.\n");
605     GNUNET_assert (NULL == gpc->get_peer_task);
606     gpc->get_peer_task =
607       GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
608                                     &sampler_mod_get_rand_peer,
609                                     cls);
610     return;
611   }
612
613   /* Check whether we may use this sampler to give it back to the client */
614   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != s_elem->last_client_request.abs_value_us)
615   {
616     last_request_diff =
617       GNUNET_TIME_absolute_get_difference (s_elem->last_client_request,
618                                            GNUNET_TIME_absolute_get ());
619     /* We're not going to give it back now if it was
620      * already requested by a client this round */
621     if (last_request_diff.rel_value_us < sampler->max_round_interval.rel_value_us)
622     {
623       LOG (GNUNET_ERROR_TYPE_DEBUG,
624           "Last client request on this sampler was less than max round interval ago -- scheduling for later\n");
625       ///* How many time remains untile the next round has started? */
626       //inv_last_request_diff =
627       //  GNUNET_TIME_absolute_get_difference (last_request_diff,
628       //                                       sampler->max_round_interval);
629       // add a little delay
630       /* Schedule it one round later */
631       GNUNET_assert (NULL == gpc->get_peer_task);
632       gpc->get_peer_task =
633         GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
634                                       &sampler_mod_get_rand_peer,
635                                       cls);
636       return;
637     }
638     // TODO add other reasons to wait here
639   }
640
641   s_elem->last_client_request = GNUNET_TIME_absolute_get ();
642
643   GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
644                                gpc->req_handle->gpc_tail,
645                                gpc);
646   gpc->cont (gpc->cont_cls, gpc->id);
647   GNUNET_free (gpc);
648 }
649
650
651 /**
652  * Get n random peers out of the sampled peers.
653  *
654  * We might want to reinitialise this sampler after giving the
655  * corrsponding peer to the client.
656  * Random with or without consumption?
657  *
658  * @param sampler the sampler to get peers from.
659  * @param cb callback that will be called once the ids are ready.
660  * @param cls closure given to @a cb
661  * @param for_client #GNUNET_YES if result is used for client,
662  *                   #GNUNET_NO if used internally
663  * @param num_peers the number of peers requested
664  */
665 struct RPS_SamplerRequestHandle *
666 RPS_sampler_get_n_rand_peers (struct RPS_Sampler *sampler,
667                               RPS_sampler_n_rand_peers_ready_cb cb,
668                               void *cls, uint32_t num_peers)
669 {
670   GNUNET_assert (0 != sampler->sampler_size);
671   if (0 == num_peers)
672     return NULL;
673
674   // TODO check if we have too much (distinct) sampled peers
675   uint32_t i;
676   struct RPS_SamplerRequestHandle *req_handle;
677   struct GetPeerCls *gpc;
678
679   req_handle = GNUNET_new (struct RPS_SamplerRequestHandle);
680   req_handle->num_peers = num_peers;
681   req_handle->cur_num_peers = 0;
682   req_handle->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
683   req_handle->sampler = sampler;
684   req_handle->callback = cb;
685   req_handle->cls = cls;
686   GNUNET_CONTAINER_DLL_insert (sampler->req_handle_head,
687                                sampler->req_handle_tail,
688                                req_handle);
689
690   LOG (GNUNET_ERROR_TYPE_DEBUG,
691       "Scheduling requests for %" PRIu32 " peers\n", num_peers);
692
693   for (i = 0 ; i < num_peers ; i++)
694   {
695     gpc = GNUNET_new (struct GetPeerCls);
696     gpc->req_handle = req_handle;
697     gpc->cont = check_n_peers_ready;
698     gpc->cont_cls = req_handle;
699     gpc->id = &req_handle->ids[i];
700
701     GNUNET_CONTAINER_DLL_insert (req_handle->gpc_head,
702                                  req_handle->gpc_tail,
703                                  gpc);
704     // maybe add a little delay
705     gpc->get_peer_task = GNUNET_SCHEDULER_add_now (sampler->get_peers,
706                                                    gpc);
707   }
708   return req_handle;
709 }
710
711 /**
712  * Cancle a request issued through #RPS_sampler_n_rand_peers_ready_cb.
713  *
714  * @param req_handle the handle to the request
715  */
716 void
717 RPS_sampler_request_cancel (struct RPS_SamplerRequestHandle *req_handle)
718 {
719   struct GetPeerCls *i;
720
721   while (NULL != (i = req_handle->gpc_head) )
722   {
723     GNUNET_CONTAINER_DLL_remove (req_handle->gpc_head,
724                                  req_handle->gpc_tail,
725                                  i);
726     if (NULL != i->get_peer_task)
727       GNUNET_SCHEDULER_cancel (i->get_peer_task);
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       RPS_sampler_request_cancel (sampler->req_handle_head);
775   }
776   sampler_empty (sampler);
777   GNUNET_free (sampler);
778 }
779
780 /* end of gnunet-service-rps.c */