b52e04712cb1df02ed3eec547252514898cb6eb1
[oweals/gnunet.git] / src / fs / gnunet-service-fs_pe.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs_pe.c
23  * @brief API to manage query plan
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-fs.h"
28 #include "gnunet-service-fs_cp.h"
29 #include "gnunet-service-fs_pe.h"
30 #include "gnunet-service-fs_pr.h"
31
32
33 /**
34  * Information we keep per request per peer.  This is a doubly-linked
35  * list (with head and tail in the 'struct GSF_PendingRequestData')
36  * with one entry in each heap of each 'struct PeerPlan'.  Each
37  * entry tracks information relevant for this request and this peer.
38  */
39 struct GSF_RequestPlan
40 {
41
42   /**
43    * This is a doubly-linked list.
44    */
45   struct GSF_RequestPlan *next;
46
47   /**
48    * This is a doubly-linked list.
49    */
50   struct GSF_RequestPlan *prev;
51
52   /**
53    * Heap node associated with this request and this peer.
54    */
55   struct GNUNET_CONTAINER_HeapNode *hn;
56
57   /**
58    * Associated pending request.
59    */
60   struct GSF_PendingRequest *pr;
61
62   /**
63    * Earliest time we'd be happy to (re)transmit this request.
64    */
65   struct GNUNET_TIME_Absolute earliest_transmission;
66
67   /**
68    * When was the last time we transmitted this request to this peer? 0 for never.
69    */
70   struct GNUNET_TIME_Absolute last_transmission;
71
72   /**
73    * Current priority for this request for this target.
74    */
75   uint64_t priority;
76
77   /**
78    * How often did we transmit this request to this peer?
79    */
80   unsigned int transmission_counter;
81
82 };
83
84
85 /**
86  * Transmission plan for a peer.
87  */
88 struct PeerPlan
89 {
90   /**
91    * Heap with pending queries (struct GSF_RequestPlan), higher weights mean higher priority.
92    */
93   struct GNUNET_CONTAINER_Heap *priority_heap;
94
95   /**
96    * Heap with pending queries (struct GSF_RequestPlan), by transmission time, lowest first.
97    */
98   struct GNUNET_CONTAINER_Heap *delay_heap;
99
100   /**
101    * Current transmission request handle.
102    */
103   struct GSF_PeerTransmitHandle *pth;
104
105   /**
106    * Peer for which this is the plan.
107    */
108   struct GSF_ConnectedPeer *cp;
109
110   /**
111    * Current task for executing the plan.
112    */
113   GNUNET_SCHEDULER_TaskIdentifier task;
114 };
115
116
117 /**
118  * Hash map from peer identities to PeerPlans.
119  */
120 static struct GNUNET_CONTAINER_MultiHashMap *plans;
121
122 /**
123  * Sum of all transmission counters (equals total delay for all plan entries).
124  */
125 static unsigned long long total_delay;
126
127 /**
128  * Number of plan entries.
129  */
130 static unsigned long long plan_count;
131
132
133 /**
134  * Figure out when and how to transmit to the given peer.
135  *
136  * @param cls the 'struct GSF_ConnectedPeer' for transmission
137  * @param tc scheduler context
138  */
139 static void
140 schedule_peer_transmission (void *cls,
141                             const struct GNUNET_SCHEDULER_TaskContext *tc);
142
143
144 /**
145  * Insert the given request plan into the heap with the appropriate weight.
146  *
147  * @param pp associated peer's plan
148  * @param rp request to plan
149  */
150 static void
151 plan (struct PeerPlan *pp,
152       struct GSF_RequestPlan *rp)
153 {
154   struct GSF_PendingRequestData *prd;
155   struct GNUNET_TIME_Relative delay;
156
157   GNUNET_STATISTICS_set (GSF_stats,
158                          gettext_noop ("# average retransmission delay (ms)"),
159                          total_delay * 1000LL / plan_count,
160                          GNUNET_NO);
161   prd = GSF_pending_request_get_data_ (rp->pr);
162   // FIXME: calculate 'rp->priority'!  
163   if (rp->transmission_counter < 32)
164     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
165                                            1LL << rp->transmission_counter);
166   else
167     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
168                                            UINT_MAX);
169   rp->earliest_transmission 
170     = GNUNET_TIME_relative_to_absolute (delay);
171 #if DEBUG_FS
172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
173               "Earliest (re)transmission for `%s' in %us\n",
174               GNUNET_h2s (&prd->query),
175               rp->transmission_counter);
176 #endif 
177
178   GNUNET_assert (rp->hn == NULL);
179   if (GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission).rel_value == 0)
180     rp->hn = GNUNET_CONTAINER_heap_insert (pp->priority_heap,
181                                            rp,
182                                            rp->priority);
183   else
184     rp->hn = GNUNET_CONTAINER_heap_insert (pp->delay_heap,
185                                            rp,
186                                            rp->earliest_transmission.abs_value);
187   if (GNUNET_SCHEDULER_NO_TASK != pp->task)
188     GNUNET_SCHEDULER_cancel (pp->task);
189   pp->task = GNUNET_SCHEDULER_add_now (&schedule_peer_transmission, pp);
190 }
191
192
193 /**
194  * Function called to get a message for transmission.
195  *
196  * @param cls closure
197  * @param buf_size number of bytes available in buf
198  * @param buf where to copy the message, NULL on error (peer disconnect)
199  * @return number of bytes copied to 'buf', can be 0 (without indicating an error)
200  */
201 static size_t 
202 transmit_message_callback (void *cls,
203                            size_t buf_size,
204                            void *buf)
205 {
206   struct PeerPlan *pp = cls;
207   struct GSF_RequestPlan *rp;
208   size_t msize;
209
210   pp->pth = NULL;
211   if (NULL == buf)
212     {
213       /* failed, try again... */
214       pp->task = GNUNET_SCHEDULER_add_now (&schedule_peer_transmission, pp);
215       return 0;
216     }
217   rp = GNUNET_CONTAINER_heap_peek (pp->priority_heap);
218   if (NULL == rp)
219     {
220       pp->task = GNUNET_SCHEDULER_add_now (&schedule_peer_transmission, pp);
221       return 0;
222     }
223   msize = GSF_pending_request_get_message_ (rp->pr, buf_size, buf);
224   if (msize > buf_size)
225     {
226       /* buffer to small (message changed), try again */
227       pp->task = GNUNET_SCHEDULER_add_now (&schedule_peer_transmission, pp);
228       return 0;
229     }
230   /* remove from root, add again elsewhere... */
231   GNUNET_assert (rp == GNUNET_CONTAINER_heap_remove_root (pp->priority_heap));
232   rp->hn = NULL;
233   rp->last_transmission = GNUNET_TIME_absolute_get ();
234   rp->transmission_counter++;
235   total_delay++;
236 #if DEBUG_FS
237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
238               "Executing plan %p executed %u times, planning retransmission\n",
239               rp,
240               rp->transmission_counter);
241 #endif    
242   plan (pp, rp);
243   GNUNET_STATISTICS_update (GSF_stats,
244                             gettext_noop ("# queries messages sent to other peers"),
245                             1,
246                             GNUNET_NO);
247   return msize;
248 }
249
250
251 /**
252  * Figure out when and how to transmit to the given peer.
253  *
254  * @param cls the 'struct PeerPlan'
255  * @param tc scheduler context
256  */
257 static void
258 schedule_peer_transmission (void *cls,
259                             const struct GNUNET_SCHEDULER_TaskContext *tc)
260 {
261   struct PeerPlan *pp = cls;
262   struct GSF_RequestPlan *rp;
263   size_t msize;
264
265   pp->task = GNUNET_SCHEDULER_NO_TASK;
266   if (pp->pth != NULL)
267     {
268       GSF_peer_transmit_cancel_ (pp->pth);
269       pp->pth = NULL;
270     }
271   /* move ready requests to priority queue */
272   while ( (NULL != (rp = GNUNET_CONTAINER_heap_peek (pp->delay_heap))) &&
273           (GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission).rel_value == 0) )
274     {
275       GNUNET_assert (rp == GNUNET_CONTAINER_heap_remove_root (pp->delay_heap));
276       rp->hn = GNUNET_CONTAINER_heap_insert (pp->priority_heap,
277                                              rp, 
278                                              rp->priority);                                     
279     }   
280   if (0 == GNUNET_CONTAINER_heap_get_size (pp->priority_heap))
281     {
282       /* priority heap (still) empty, check for delay... */
283       rp = GNUNET_CONTAINER_heap_peek (pp->delay_heap);
284       if (NULL == rp)
285         {
286 #if DEBUG_FS
287           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
288                       "No active requests for plan %p.\n",
289                       pp);
290 #endif
291           return; /* both queues empty */
292         }
293 #if DEBUG_FS
294       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
295                   "Sleeping for %llu ms before retrying requests on plan %p.\n",
296                   (unsigned long long) GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission).rel_value,
297                   pp);
298 #endif
299       pp->task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission),
300                                                &schedule_peer_transmission,
301                                                pp);
302       return;
303     }
304   /* process from priority heap */
305   rp = GNUNET_CONTAINER_heap_peek (pp->priority_heap);
306 #if DEBUG_FS > 1
307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
308               "Executing query plan %p\n",
309               rp);
310 #endif    
311   GNUNET_assert (NULL != rp);
312   msize = GSF_pending_request_get_message_ (rp->pr, 0, NULL);
313   pp->pth = GSF_peer_transmit_ (pp->cp,
314                                 GNUNET_YES,
315                                 rp->priority,
316                                 GNUNET_TIME_UNIT_FOREVER_REL,
317                                 msize,
318                                 &transmit_message_callback,
319                                 pp);
320   GNUNET_assert (NULL != pp->pth);
321 }
322
323
324 /**
325  * Create a new query plan entry.
326  *
327  * @param cp peer with the entry
328  * @param pr request with the entry
329  */
330 void
331 GSF_plan_add_ (struct GSF_ConnectedPeer *cp,
332                struct GSF_PendingRequest *pr)
333 {
334   struct GNUNET_PeerIdentity id;
335   struct PeerPlan *pp;
336   struct GSF_PendingRequestData *prd;
337   struct GSF_RequestPlan *rp;
338
339   GNUNET_assert (NULL != cp);
340   GSF_connected_peer_get_identity_ (cp, &id);
341   pp = GNUNET_CONTAINER_multihashmap_get (plans,
342                                           &id.hashPubKey);
343   if (NULL == pp)
344     {
345       pp = GNUNET_malloc (sizeof (struct PeerPlan));
346       pp->priority_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX);
347       pp->delay_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
348       pp->cp = cp;
349       GNUNET_CONTAINER_multihashmap_put (plans,
350                                          &id.hashPubKey,
351                                          pp,
352                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
353     }
354   prd = GSF_pending_request_get_data_ (pr);
355   plan_count++;
356   GNUNET_STATISTICS_update (GSF_stats,
357                             gettext_noop ("# query plan entries"),
358                             1,
359                             GNUNET_NO);
360   rp = GNUNET_malloc (sizeof (struct GSF_RequestPlan));
361 #if DEBUG_FS
362   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
363               "Planning transmission of query `%s' to peer `%s' (%p)\n",
364               GNUNET_h2s (&prd->query),
365               GNUNET_i2s (&id), 
366               rp);
367 #endif    
368   rp->pr = pr;
369   GNUNET_CONTAINER_DLL_insert (prd->rp_head,
370                                prd->rp_tail,
371                                rp);
372   plan (pp, rp);
373 }
374
375
376 /**
377  * Notify the plan about a peer being no longer available;
378  * destroy all entries associated with this peer.
379  *
380  * @param cp connected peer 
381  */
382 void
383 GSF_plan_notify_peer_disconnect_ (const struct GSF_ConnectedPeer *cp)
384 {
385   struct GNUNET_PeerIdentity id;
386   struct PeerPlan *pp;
387   struct GSF_RequestPlan *rp;
388   struct GSF_PendingRequestData *prd;
389
390   GSF_connected_peer_get_identity_ (cp, &id);
391   pp = GNUNET_CONTAINER_multihashmap_get (plans,
392                                           &id.hashPubKey);
393   if (NULL == pp)
394     return; /* nothing was ever planned for this peer */
395   GNUNET_assert (GNUNET_YES ==
396                  GNUNET_CONTAINER_multihashmap_remove (plans,
397                                                        &id.hashPubKey,
398                                                        pp));
399   if (NULL != pp->pth)
400     GSF_peer_transmit_cancel_ (pp->pth);
401   if (GNUNET_SCHEDULER_NO_TASK != pp->task)
402     {
403       GNUNET_SCHEDULER_cancel (pp->task);
404       pp->task = GNUNET_SCHEDULER_NO_TASK;
405     }
406   while (NULL != (rp = GNUNET_CONTAINER_heap_remove_root (pp->priority_heap)))
407     {
408       prd = GSF_pending_request_get_data_ (rp->pr);
409       GNUNET_CONTAINER_DLL_remove (prd->rp_head,
410                                    prd->rp_tail,
411                                    rp);
412       plan_count--;
413       GNUNET_free (rp);
414     }
415   GNUNET_CONTAINER_heap_destroy (pp->priority_heap);
416   while (NULL != (rp = GNUNET_CONTAINER_heap_remove_root (pp->delay_heap)))
417     {
418       prd = GSF_pending_request_get_data_ (rp->pr);
419       GNUNET_CONTAINER_DLL_remove (prd->rp_head,
420                                    prd->rp_tail,
421                                    rp);
422       plan_count--;
423       GNUNET_free (rp);
424     }
425   GNUNET_STATISTICS_set (GSF_stats,
426                          gettext_noop ("# query plan entries"),
427                          plan_count,
428                          GNUNET_NO);
429
430   GNUNET_CONTAINER_heap_destroy (pp->delay_heap);
431   GNUNET_free (pp);
432 }
433
434
435 /**
436  * Notify the plan about a request being done; destroy all entries
437  * associated with this request.
438  *
439  * @param pr request that is done
440  */
441 void
442 GSF_plan_notify_request_done_ (struct GSF_PendingRequest *pr)
443 {
444   struct GSF_RequestPlan *rp;
445   struct GSF_PendingRequestData *prd;
446
447   prd = GSF_pending_request_get_data_ (pr);
448   while (NULL != (rp = prd->rp_head))
449     {
450       GNUNET_CONTAINER_heap_remove_node (rp->hn);
451       GNUNET_CONTAINER_DLL_remove (prd->rp_head,
452                                    prd->rp_tail,
453                                    rp);
454       plan_count--;
455       GNUNET_free (rp);
456     }
457   GNUNET_STATISTICS_set (GSF_stats,
458                          gettext_noop ("# query plan entries"),
459                          plan_count,
460                          GNUNET_NO);  
461 }
462
463
464 /**
465  * Initialize plan subsystem.
466  */
467 void
468 GSF_plan_init ()
469 {
470   plans = GNUNET_CONTAINER_multihashmap_create (256);
471 }
472
473
474 /**
475  * Shutdown plan subsystem.
476  */
477 void
478 GSF_plan_done ()
479 {
480   GNUNET_assert (0 == 
481                  GNUNET_CONTAINER_multihashmap_size (plans));
482   GNUNET_CONTAINER_multihashmap_destroy (plans);
483 }
484
485
486
487 /* end of gnunet-service-fs_pe.h */