14815ea36563d86a3c2c637f52670d58c39c27e7
[oweals/gnunet.git] / src / ats / ats_api_performance.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,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  * @file ats/ats_api_performance.c
22  * @brief automatic transport selection and outbound bandwidth determination
23  * @author Christian Grothoff
24  * @author Matthias Wachs
25   */
26 #include "platform.h"
27 #include "gnunet_ats_service.h"
28 #include "ats.h"
29
30
31 /**
32  * Message in linked list we should send to the ATS service.  The
33  * actual binary message follows this struct.
34  */
35 struct PendingMessage
36 {
37
38   /**
39    * Kept in a DLL.
40    */
41   struct PendingMessage *next;
42
43   /**
44    * Kept in a DLL.
45    */
46   struct PendingMessage *prev;
47
48   /**
49    * Size of the message.
50    */
51   size_t size;
52
53   /**
54    * Is this the 'ATS_START' message?
55    */
56   int is_init;
57 };
58
59
60 /**
61  * Linked list of pending reservations.
62  */
63 struct GNUNET_ATS_ReservationContext
64 {
65
66   /**
67    * Kept in a DLL.
68    */
69   struct GNUNET_ATS_ReservationContext *next;
70
71   /**
72    * Kept in a DLL.
73    */
74   struct GNUNET_ATS_ReservationContext *prev;
75
76   /**
77    * Target peer.
78    */
79   struct GNUNET_PeerIdentity peer;
80
81   /**
82    * Desired reservation
83    */
84   int32_t size;
85
86   /**
87    * Function to call on result.
88    */
89   GNUNET_ATS_ReservationCallback rcb;
90
91   /**
92    * Closure for 'rcb'
93    */
94   void *rcb_cls;
95
96   /**
97    * Do we need to undo this reservation if it succeeded?  Set to
98    * GNUNET_YES if a reservation is cancelled.  (at that point, 'info'
99    * is also set to NULL; however, info will ALSO be NULL for the
100    * reservation context that is created to undo the original request,
101    * so 'info' being NULL cannot be used to check if undo is
102    * required).
103    */
104   int undo;
105 };
106
107
108 /**
109  * ATS Handle to obtain and/or modify performance information.
110  */
111 struct GNUNET_ATS_PerformanceHandle
112 {
113
114   /**
115    * Our configuration.
116    */
117   const struct GNUNET_CONFIGURATION_Handle *cfg;
118
119   /**
120    * Callback to invoke on performance changes.
121    */
122   GNUNET_ATS_PeerInformationCallback infocb;
123
124   /**
125    * Closure for 'infocb'.
126    */
127   void *infocb_cls;
128
129   /**
130    * Connection to ATS service.
131    */
132   struct GNUNET_CLIENT_Connection *client;
133
134   /**
135    * Head of list of messages for the ATS service.
136    */
137   struct PendingMessage *pending_head;
138
139   /**
140    * Tail of list of messages for the ATS service
141    */
142   struct PendingMessage *pending_tail;
143
144   /**
145    * Head of linked list of pending reservation requests.
146    */
147   struct GNUNET_ATS_ReservationContext *reservation_head;
148
149   /**
150    * Tail of linked list of pending reservation requests.
151    */
152   struct GNUNET_ATS_ReservationContext *reservation_tail;
153
154   /**
155    * Current request for transmission to ATS.
156    */
157   struct GNUNET_CLIENT_TransmitHandle *th;
158
159   /**
160    * Task to trigger reconnect.
161    */
162   GNUNET_SCHEDULER_TaskIdentifier task;
163
164 };
165
166
167 /**
168  * Re-establish the connection to the ATS service.
169  *
170  * @param ph handle to use to re-connect.
171  */
172 static void
173 reconnect (struct GNUNET_ATS_PerformanceHandle *ph);
174
175
176 /**
177  * Re-establish the connection to the ATS service.
178  *
179  * @param cls handle to use to re-connect.
180  * @param tc scheduler context
181  */
182 static void
183 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
184 {
185   struct GNUNET_ATS_PerformanceHandle *ph = cls;
186
187   ph->task = GNUNET_SCHEDULER_NO_TASK;
188   reconnect (ph);
189 }
190
191
192 /**
193  * Transmit messages from the message queue to the service
194  * (if there are any, and if we are not already trying).
195  *
196  * @param ph handle to use
197  */
198 static void
199 do_transmit (struct GNUNET_ATS_PerformanceHandle *ph);
200
201
202 /**
203  * We can now transmit a message to ATS. Do it.
204  *
205  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
206  * @param size number of bytes we can transmit to ATS
207  * @param buf where to copy the messages
208  * @return number of bytes copied into buf
209  */
210 static size_t
211 transmit_message_to_ats (void *cls, size_t size, void *buf)
212 {
213   struct GNUNET_ATS_PerformanceHandle *ph = cls;
214   struct PendingMessage *p;
215   size_t ret;
216   char *cbuf;
217
218   ph->th = NULL;
219   ret = 0;
220   cbuf = buf;
221   while ((NULL != (p = ph->pending_head)) && (p->size <= size))
222   {
223     memcpy (&cbuf[ret], &p[1], p->size);
224     ret += p->size;
225     size -= p->size;
226     GNUNET_CONTAINER_DLL_remove (ph->pending_head, ph->pending_tail, p);
227     GNUNET_free (p);
228   }
229   do_transmit (ph);
230   return ret;
231 }
232
233
234 /**
235  * Transmit messages from the message queue to the service
236  * (if there are any, and if we are not already trying).
237  *
238  * @param ph handle to use
239  */
240 static void
241 do_transmit (struct GNUNET_ATS_PerformanceHandle *ph)
242 {
243   struct PendingMessage *p;
244
245   if (NULL != ph->th)
246     return;
247   if (NULL == (p = ph->pending_head))
248     return;
249   if (NULL == ph->client)
250     return;                     /* currently reconnecting */
251   ph->th =
252       GNUNET_CLIENT_notify_transmit_ready (ph->client, p->size,
253                                            GNUNET_TIME_UNIT_FOREVER_REL,
254                                            GNUNET_YES, &transmit_message_to_ats,
255                                            ph);
256 }
257
258
259 /**
260  * We received a peer information message.  Validate and process it.
261  *
262  * @param ph our context with the callback
263  * @param msg the message
264  * @return GNUNET_OK if the message was well-formed
265  */
266 static int
267 process_pi_message (struct GNUNET_ATS_PerformanceHandle *ph,
268                     const struct GNUNET_MessageHeader *msg)
269 {
270   const struct PeerInformationMessage *pi;
271   const struct GNUNET_ATS_Information *atsi;
272   const char *plugin_address;
273   const char *plugin_name;
274   struct GNUNET_HELLO_Address address;
275   uint16_t plugin_address_length;
276   uint16_t plugin_name_length;
277   uint32_t ats_count;
278
279   if (ntohs (msg->size) < sizeof (struct PeerInformationMessage))
280   {
281     GNUNET_break (0);
282     return GNUNET_SYSERR;
283   }
284   pi = (const struct PeerInformationMessage *) msg;
285   ats_count = ntohl (pi->ats_count);
286   plugin_address_length = ntohs (pi->address_length);
287   plugin_name_length = ntohs (pi->plugin_name_length);
288   atsi = (const struct GNUNET_ATS_Information *) &pi[1];
289   plugin_address = (const char *) &atsi[ats_count];
290   plugin_name = &plugin_address[plugin_address_length];
291   if ((plugin_address_length + plugin_name_length +
292        ats_count * sizeof (struct GNUNET_ATS_Information) +
293        sizeof (struct PeerInformationMessage) != ntohs (msg->size)) ||
294       (ats_count >
295        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information))
296       || (plugin_name[plugin_name_length - 1] != '\0'))
297   {
298     GNUNET_break (0);
299     return GNUNET_SYSERR;
300   }
301   if (ph->infocb == NULL)
302   {
303     return GNUNET_OK;
304   }
305   address.peer = pi->peer;
306   address.address = plugin_address;
307   address.address_length = plugin_address_length;
308   address.transport_name = plugin_name;
309   ph->infocb (ph->infocb_cls, &address, pi->bandwidth_out, pi->bandwidth_in,
310               atsi, ats_count);
311   return GNUNET_OK;
312 }
313
314
315 /**
316  * We received a reservation result message.  Validate and process it.
317  *
318  * @param ph our context with the callback
319  * @param msg the message
320  * @return GNUNET_OK if the message was well-formed
321  */
322 static int
323 process_rr_message (struct GNUNET_ATS_PerformanceHandle *ph,
324                     const struct GNUNET_MessageHeader *msg)
325 {
326   const struct ReservationResultMessage *rr;
327   struct GNUNET_ATS_ReservationContext *rc;
328   int32_t amount;
329
330   if (ntohs (msg->size) < sizeof (struct ReservationResultMessage))
331   {
332     GNUNET_break (0);
333     return GNUNET_SYSERR;
334   }
335   rr = (const struct ReservationResultMessage *) msg;
336   amount = ntohl (rr->amount);
337   rc = ph->reservation_head;
338   if (0 != memcmp (&rr->peer, &rc->peer, sizeof (struct GNUNET_PeerIdentity)))
339   {
340     GNUNET_break (0);
341     return GNUNET_SYSERR;
342   }
343   GNUNET_CONTAINER_DLL_remove (ph->reservation_head, ph->reservation_tail, rc);
344   if ((amount == 0) || (rc->rcb != NULL))
345   {
346     /* tell client if not cancelled */
347     if (rc->rcb != NULL)
348       rc->rcb (rc->rcb_cls, &rr->peer, amount,
349                GNUNET_TIME_relative_ntoh (rr->res_delay));
350     GNUNET_free (rc);
351     return GNUNET_OK;
352   }
353   /* amount non-zero, but client cancelled, consider undo! */
354   if (GNUNET_YES != rc->undo)
355   {
356     GNUNET_free (rc);
357     return GNUNET_OK;           /* do not try to undo failed undos or negative amounts */
358   }
359   GNUNET_free (rc);
360   (void) GNUNET_ATS_reserve_bandwidth (ph, &rr->peer, -amount, NULL, NULL);
361   return GNUNET_OK;
362 }
363
364
365 /**
366  * Type of a function to call when we receive a message
367  * from the service.
368  *
369  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
370  * @param msg message received, NULL on timeout or fatal error
371  */
372 static void
373 process_ats_message (void *cls, const struct GNUNET_MessageHeader *msg)
374 {
375   struct GNUNET_ATS_PerformanceHandle *ph = cls;
376
377   if (NULL == msg)
378     goto reconnect;
379   switch (ntohs (msg->type))
380   {
381   case GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION:
382     if (GNUNET_OK != process_pi_message (ph, msg))
383       goto reconnect;
384     break;
385   case GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT:
386     if (GNUNET_OK != process_rr_message (ph, msg))
387       goto reconnect;
388     break;
389   default:
390     GNUNET_break (0);
391     goto reconnect;
392   }
393   GNUNET_CLIENT_receive (ph->client, &process_ats_message, ph,
394                          GNUNET_TIME_UNIT_FOREVER_REL);
395   return;
396 reconnect:
397   if (NULL != ph->th)
398   {
399     GNUNET_CLIENT_notify_transmit_ready_cancel (ph->th);
400     ph->th = NULL;
401   }
402   GNUNET_CLIENT_disconnect (ph->client);
403   ph->client = NULL;
404   ph->task =
405       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &reconnect_task,
406                                     ph);
407 }
408
409
410 /**
411  * Re-establish the connection to the ATS service.
412  *
413  * @param ph handle to use to re-connect.
414  */
415 static void
416 reconnect (struct GNUNET_ATS_PerformanceHandle *ph)
417 {
418   struct PendingMessage *p;
419   struct ClientStartMessage *init;
420
421   GNUNET_assert (NULL == ph->client);
422   ph->client = GNUNET_CLIENT_connect ("ats", ph->cfg);
423   GNUNET_assert (NULL != ph->client);
424   GNUNET_CLIENT_receive (ph->client, &process_ats_message, ph,
425                          GNUNET_TIME_UNIT_FOREVER_REL);
426   if ((NULL == (p = ph->pending_head)) || (GNUNET_YES != p->is_init))
427   {
428     p = GNUNET_malloc (sizeof (struct PendingMessage) +
429                        sizeof (struct ClientStartMessage));
430     p->size = sizeof (struct ClientStartMessage);
431     p->is_init = GNUNET_YES;
432     init = (struct ClientStartMessage *) &p[1];
433     init->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_START);
434     init->header.size = htons (sizeof (struct ClientStartMessage));
435     init->start_flag =
436         htonl ((ph->infocb ==
437                 NULL) ? START_FLAG_PERFORMANCE_NO_PIC :
438                START_FLAG_PERFORMANCE_WITH_PIC);
439     GNUNET_CONTAINER_DLL_insert (ph->pending_head, ph->pending_tail, p);
440   }
441   do_transmit (ph);
442 }
443
444
445
446 /**
447  * Get handle to access performance API of the ATS subsystem.
448  *
449  * @param cfg configuration to use
450  * @param infocb function to call on allocation changes, can be NULL
451  * @param infocb_cls closure for infocb
452  * @return ats performance context
453  */
454 struct GNUNET_ATS_PerformanceHandle *
455 GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
456                              GNUNET_ATS_PeerInformationCallback infocb,
457                              void *infocb_cls)
458 {
459   struct GNUNET_ATS_PerformanceHandle *ph;
460
461   ph = GNUNET_malloc (sizeof (struct GNUNET_ATS_PerformanceHandle));
462   ph->cfg = cfg;
463   ph->infocb = infocb;
464   ph->infocb_cls = infocb_cls;
465   reconnect (ph);
466   return ph;
467 }
468
469
470 /**
471  * Client is done using the ATS performance subsystem, release resources.
472  *
473  * @param ph handle
474  */
475 void
476 GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph)
477 {
478   struct PendingMessage *p;
479   struct GNUNET_ATS_ReservationContext *rc;
480
481   while (NULL != (p = ph->pending_head))
482   {
483     GNUNET_CONTAINER_DLL_remove (ph->pending_head, ph->pending_tail, p);
484     GNUNET_free (p);
485   }
486   while (NULL != (rc = ph->reservation_head))
487   {
488     GNUNET_CONTAINER_DLL_remove (ph->reservation_head, ph->reservation_tail,
489                                  rc);
490     GNUNET_break (NULL == rc->rcb);
491     GNUNET_free (rc);
492   }
493   if (GNUNET_SCHEDULER_NO_TASK != ph->task)
494   {
495     GNUNET_SCHEDULER_cancel (ph->task);
496     ph->task = GNUNET_SCHEDULER_NO_TASK;
497   }
498   if (NULL != ph->client)
499   {
500     GNUNET_CLIENT_disconnect (ph->client);
501     ph->client = NULL;
502   }
503   GNUNET_free (ph);
504 }
505
506
507 /**
508  * Reserve inbound bandwidth from the given peer.  ATS will look at
509  * the current amount of traffic we receive from the peer and ensure
510  * that the peer could add 'amount' of data to its stream.
511  *
512  * @param ph performance handle
513  * @param peer identifies the peer
514  * @param amount reserve N bytes for receiving, negative
515  *                amounts can be used to undo a (recent) reservation;
516  * @param rcb function to call with the resulting reservation information
517  * @param rcb_cls closure for info
518  * @return NULL on error
519  * @deprecated will be replaced soon
520  */
521 struct GNUNET_ATS_ReservationContext *
522 GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph,
523                               const struct GNUNET_PeerIdentity *peer,
524                               int32_t amount,
525                               GNUNET_ATS_ReservationCallback rcb, void *rcb_cls)
526 {
527   struct GNUNET_ATS_ReservationContext *rc;
528   struct PendingMessage *p;
529   struct ReservationRequestMessage *m;
530
531   rc = GNUNET_malloc (sizeof (struct GNUNET_ATS_ReservationContext));
532   rc->size = amount;
533   rc->peer = *peer;
534   rc->rcb = rcb;
535   rc->rcb_cls = rcb_cls;
536   if ((rcb != NULL) && (amount > 0))
537     rc->undo = GNUNET_YES;
538   GNUNET_CONTAINER_DLL_insert_tail (ph->reservation_head, ph->reservation_tail,
539                                     rc);
540
541   p = GNUNET_malloc (sizeof (struct PendingMessage) +
542                      sizeof (struct ReservationRequestMessage));
543   p->size = sizeof (struct ReservationRequestMessage);
544   p->is_init = GNUNET_NO;
545   m = (struct ReservationRequestMessage *) &p[1];
546   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST);
547   m->header.size = htons (sizeof (struct ReservationRequestMessage));
548   m->amount = htonl (amount);
549   m->peer = *peer;
550   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
551   do_transmit (ph);
552   return rc;
553 }
554
555
556 /**
557  * Cancel request for reserving bandwidth.
558  *
559  * @param rc context returned by the original GNUNET_ATS_reserve_bandwidth call
560  */
561 void
562 GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc)
563 {
564   rc->rcb = NULL;
565 }
566
567
568 /**
569  * Change preferences for the given peer. Preference changes are forgotten if peers
570  * disconnect.
571  *
572  * @param ph performance handle
573  * @param peer identifies the peer
574  * @param ... 0-terminated specification of the desired changes
575  */
576 void
577 GNUNET_ATS_change_preference (struct GNUNET_ATS_PerformanceHandle *ph,
578                               const struct GNUNET_PeerIdentity *peer, ...)
579 {
580   struct PendingMessage *p;
581   struct ChangePreferenceMessage *m;
582   size_t msize;
583   uint32_t count;
584   struct PreferenceInformation *pi;
585   va_list ap;
586   enum GNUNET_ATS_PreferenceKind kind;
587
588   count = 0;
589   va_start (ap, peer);
590   while (GNUNET_ATS_PREFERENCE_END !=
591          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
592   {
593     switch (kind)
594     {
595     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
596       count++;
597       (void) va_arg (ap, double);
598
599       break;
600     case GNUNET_ATS_PREFERENCE_LATENCY:
601       count++;
602       (void) va_arg (ap, double);
603
604       break;
605     default:
606       GNUNET_assert (0);
607     }
608   }
609   va_end (ap);
610   msize =
611       count * sizeof (struct PreferenceInformation) +
612       sizeof (struct ChangePreferenceMessage);
613   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
614   p->size = msize;
615   p->is_init = GNUNET_NO;
616   m = (struct ChangePreferenceMessage *) &p[1];
617   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE);
618   m->header.size = htons (msize);
619   m->num_preferences = htonl (count);
620   m->peer = *peer;
621   pi = (struct PreferenceInformation *) &m[1];
622   count = 0;
623   va_start (ap, peer);
624   while (GNUNET_ATS_PREFERENCE_END !=
625          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
626   {
627     pi[count].preference_kind = htonl (kind);
628     switch (kind)
629     {
630     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
631       pi[count].preference_value = (float) va_arg (ap, double);
632
633       count++;
634       break;
635     case GNUNET_ATS_PREFERENCE_LATENCY:
636       pi[count].preference_value = (float) va_arg (ap, double);
637
638       count++;
639       break;
640     default:
641       GNUNET_assert (0);
642     }
643   }
644   va_end (ap);
645   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
646   do_transmit (ph);
647 }
648
649 /* end of ats_api_performance.c */