doxygen fixes
[oweals/gnunet.git] / src / ats / gnunet-service-ats-solver_proportional.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 ats/gnunet-service-ats-solver_proportional.c
23  * @brief ATS proportional solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet-service-ats_addresses.h"
30 #include "gnunet_statistics_service.h"
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__)
33
34 /**
35  *
36  * NOTE: Do not change this documentation. This documentation is based
37  * on gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
38  * use build_txt.sh to generate plaintext output
39  *
40  * ATS addresses : simplistic solver
41  *
42  *    The simplistic solver ("simplistic") distributes the available
43  *    bandwidth fair over all the addresses influenced by the
44  *    preference values. For each available network type an in- and
45  *    outbound quota is configured and the bandwidth available in
46  *    these networks is distributed over the addresses.  The solver
47  *    first assigns every addresses the minimum amount of bandwidth
48  *    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT and then distributes the
49  *    remaining bandwidth available according to the preference
50  *    values. For each peer only a single address gets bandwidth
51  *    assigned and only one address marked as active.  The most
52  *    important functionality for the solver is implemented in: *
53  *    find_address_it is an hashmap iterator returning the prefered
54  *    address for an peer * update_quota_per_network distributes
55  *    available bandwidth for a network over active addresses
56  *
57  *    Changes to addresses automatically have an impact on the the
58  *    bandwidth assigned to other addresses in the same network since
59  *    the solver distributes the remaining bandwidth over the
60  *    addresses in the network.  When changes to the addresses occur,
61  *    the solver first performs the changes, like adding or deleting
62  *    addresses, and then updates bandwidth assignment for the
63  *    affected network. Bandwidth assignment is only recalculated on
64  *    demand when an address is requested by a client for a peer or
65  *    when the addresses available have changed or an address changed
66  *    the network it is located in. When the bandwidth assignment has
67  *    changed the callback is called with the new bandwidth
68  *    assignments. The bandwidth distribution for a network is
69  *    recalculated due to: * address suggestion requests * address
70  *    deletions * address switching networks during address update *
71  *    preference changes
72  *
73  *     3.1 Data structures used
74  *
75  *    For each ATS network (e.g. WAN, LAN, loopback) a struct Network
76  *    is used to specify network related information as total adresses
77  *    and active addresses in this network and the configured in- and
78  *    outbound quota. Each network also contains a list of addresses
79  *    added to the solver located in this network. The simplistic
80  *    solver uses the addresses' solver_information field to store the
81  *    simplistic network it belongs to for each address.
82  *
83  *     3.2 Initializing
84  *
85  *    When the simplistic solver is initialized the solver creates a
86  *    new solver handle and initializes the network structures with
87  *    the quotas passed from addresses and returns the handle solver.
88  *
89  *     3.3 Adding an address
90  *
91  *    When a new address is added to the solver using s_add, a lookup
92  *    for the network for this address is done and the address is
93  *    enqueued in in the linked list of the network.
94  *
95  *     3.4 Updating an address
96  *
97  *    The main purpose of address updates is to update the ATS
98  *    information for addresse selection. Important for the simplistic
99  *    solver is when an address switches network it is located
100  *    in. This is common because addresses added by transport's
101  *    validation mechanism are commonly located in
102  *    GNUNET_ATS_NET_UNSPECIFIED. Addresses in validation are located
103  *    in this network type and only if a connection is successful on
104  *    return of payload data transport switches to the real network
105  *    the address is located in.  When an address changes networks it
106  *    is first of all removed from the old network using the solver
107  *    API function GAS_simplistic_address_delete and the network in
108  *    the address struct is updated. A lookup for the respective new
109  *    simplistic network is done and stored in the addresse's
110  *    solver_information field. Next the address is re-added to the
111  *    solver using the solver API function
112  *    GAS_simplistic_address_add. If the address was marked as in
113  *    active, the solver checks if bandwidth is available in the
114  *    network and if yes sets the address to active and updates the
115  *    bandwidth distribution in this network. If no bandwidth is
116  *    available it sets the bandwidth for this address to 0 and tries
117  *    to suggest an alternative address. If an alternative address was
118  *    found, addresses' callback is called for this address.
119  *
120  *     3.5 Deleting an address
121  *
122  *    When an address is removed from the solver, it removes the
123  *    respective address from the network and if the address was
124  *    marked as active, it updates the bandwidth distribution for this
125  *    network.
126  *
127  *     3.6 Requesting addresses
128  *
129  *    When an address is requested for a peer the solver performs a
130  *    lookup for the peer entry in addresses address hashmap and
131  *    selects the best address.  The selection of the most suitable
132  *    address is done in the find_address_it hashmap iterator
133  *    described in detail in section 3.7. If no address is returned,
134  *    no address can be suggested at the moment. If the address
135  *    returned is marked as active, the solver can return this
136  *    address. If the address is not marked as active, the solver
137  *    checks if another address belongign to this peer is marked as
138  *    active and marks the address as inactive, updates the bandwidth
139  *    for this address to 0, call the bandwidth changed callback for
140  *    this address due to the change and updates quota assignment for
141  *    the addresse's network. the now in-active address is belonging
142  *    to. The solver marks the new address as active and updates the
143  *    bandwidth assignment for this network.
144  *
145  *     3.7 Choosing addresses
146  *
147  *    Choosing the best possible address for suggestion is done by
148  *    iterating over all addresses of a peer stored in addresses'
149  *    hashmap and using the hashmap iterator find_address_it to select
150  *    the best available address.  Several checks are done when an
151  *    address is selected. First if this address is currently blocked
152  *    by addresses from being suggested. An address is blocked for the
153  *    duration of ATS_BLOCKING_DELTA when it is suggested to
154  *    transport. Next it is checked if at least
155  *    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT bytes bandwidth is available
156  *    in the addresse's network, because suggesting an address without
157  *    bandwidth does not make sense. This also ensures that all active
158  *    addresses in this network get at least the minimum amount of
159  *    bandwidth assigned. In the next step the solver ensures that for
160  *    tcp connections inbound connections are prefered over outbound
161  *    connections. In the next stet the solver ensures that
162  *    connections are prefered in the following order: * connections
163  *    are already established and have bandwidth assigned *
164  *    connections with a shorter distance * connectes have a shorter
165  *    latency
166  *
167  *     3.8 Changing preferences
168  *
169  *     3.9 Shutdown
170  *
171  *    During shutdown all network entries and aging processes are
172  *    destroyed and freed.
173  *
174  *
175  * OLD DOCUMENTATION
176  *
177  * This solver assigns in and outbound bandwidth equally for all
178  * addresses in specific network type (WAN, LAN) based on configured
179  * in and outbound quota for this network.
180  *
181  * The solver is notified by addresses about changes to the addresses
182  * and recalculates the bandwith assigned if required. The solver
183  * notifies addresses by calling the GAS_bandwidth_changed_cb
184  * callback.
185  *
186  * - Initialization
187  *
188  *
189  *
190  *
191  * For each peer only a single is selected and marked as "active" in the address
192  * struct.
193  *
194  * E.g.:
195  *
196  * You have the networks WAN and LAN and quotas
197  * WAN_TOTAL_IN, WAN_TOTAL_OUT
198  * LAN_TOTAL_IN, LAN_TOTAL_OUT
199  *
200  * If you have x addresses in the network segment LAN, the quotas are
201  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
202  *
203  * Quotas are automatically recalculated and reported back when addresses are
204  * - requested
205  *
206  */
207
208 #define PREF_AGING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
209 #define PREF_AGING_FACTOR 0.95
210
211 #define DEFAULT_REL_PREFERENCE 1.0
212 #define DEFAULT_ABS_PREFERENCE 0.0
213 #define MIN_UPDATE_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
214
215
216 /**
217  * A handle for the proportional solver
218  */
219 struct GAS_PROPORTIONAL_Handle
220 {
221   /**
222    * Statistics handle
223    */
224
225   struct GNUNET_STATISTICS_Handle *stats;
226
227   /**
228    * Total number of addresses for solver
229    */
230   unsigned int total_addresses;
231
232   /**
233    * Number of active addresses for solver
234    */
235   unsigned int active_addresses;
236
237   /**
238    * Networks array
239    */
240   struct Network *network_entries;
241
242   /**
243    * Number of networks
244    */
245   unsigned int networks;
246
247   /**
248    * Callback
249    */
250   GAS_bandwidth_changed_cb bw_changed;
251
252   /**
253    * Callback cls
254    */
255   void *bw_changed_cls;
256
257   /**
258    * ATS function to get preferences
259    */
260   GAS_get_preferences get_preferences;
261
262   /**
263    * Closure for ATS function to get preferences
264    */
265   void *get_preferences_cls;
266
267   struct GNUNET_CONTAINER_MultiHashMap *prefs;
268
269   struct PreferenceClient *pc_head;
270   struct PreferenceClient *pc_tail;
271 };
272
273
274 /**
275  * Representation of a network
276  */
277 struct Network
278 {
279   /**
280    * ATS network type
281    */
282   unsigned int type;
283
284   /**
285    * Network description
286    */
287   char *desc;
288
289   /**
290    * Total inbound quota
291    *
292    */
293   unsigned long long total_quota_in;
294
295   /**
296    * Total outbound quota
297    *
298    */
299   unsigned long long total_quota_out;
300
301   /**
302    * Number of active addresses for this network
303    */
304   unsigned int active_addresses;
305
306   /**
307    * Number of total addresses for this network
308    */
309   unsigned int total_addresses;
310
311   /**
312    * String for statistics total addresses
313    */
314   char *stat_total;
315
316   /**
317    * String for statistics active addresses
318    */
319   char *stat_active;
320
321   struct AddressWrapper *head;
322   struct AddressWrapper *tail;
323 };
324
325
326 /**
327  * Wrapper for addresses to store them in network's linked list
328  */
329 struct AddressWrapper
330 {
331   /**
332    * Next in DLL
333    */
334   struct AddressWrapper *next;
335
336   /**
337    * Previous in DLL
338    */
339   struct AddressWrapper *prev;
340
341   /**
342    * The address
343    */
344   struct ATS_Address *addr;
345 };
346
347
348
349 /**
350  *  Important solver functions
351  *  ---------------------------
352  */
353
354 /**
355  * Test if bandwidth is available in this network to add an additional address
356  *
357  * @param net the network type to update
358  * @return GNUNET_YES or GNUNET_NO
359  */
360 static int
361 is_bandwidth_available_in_network (struct Network *net)
362 {
363   unsigned int na = net->active_addresses + 1;
364   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
365   if (((net->total_quota_in / na) > min_bw) &&
366       ((net->total_quota_out / na) > min_bw))
367   {
368     LOG (GNUNET_ERROR_TYPE_DEBUG,
369          "Enough bandwidth available for %u active addresses in network `%s'\n",
370          na,
371          net->desc);
372
373     return GNUNET_YES;
374   }
375     LOG (GNUNET_ERROR_TYPE_DEBUG,
376          "Not enough bandwidth available for %u active addresses in network `%s'\n",
377          na,
378          net->desc);
379   return GNUNET_NO;
380 }
381
382
383 /**
384  * Update bandwidth assigned to peers in this network
385  *
386  * @param s the solver handle
387  * @param net the network type to update
388  * @param address_except address excluded from notification, since we suggest
389  * this address
390  */
391 static void
392 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
393                           struct Network *net,
394                           struct ATS_Address *address_except)
395 {
396   unsigned long long remaining_quota_in = 0;
397   unsigned long long quota_out_used = 0;
398
399   unsigned long long remaining_quota_out = 0;
400   unsigned long long quota_in_used = 0;
401   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
402   double peer_prefs;
403   double total_prefs; /* Important: has to be double not float due to precision */
404   double cur_pref; /* Important: has to be double not float due to precision */
405   const double *t = NULL; /* Important: has to be double not float due to precision */
406   int c;
407
408   unsigned long long assigned_quota_in = 0;
409   unsigned long long assigned_quota_out = 0;
410   struct AddressWrapper *cur;
411
412   LOG (GNUNET_ERROR_TYPE_DEBUG,
413               "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
414               net->desc, net->active_addresses, net->total_quota_in, net->total_quota_in);
415
416   if (net->active_addresses == 0)
417     return; /* no addresses to update */
418
419   /* Idea
420    * Assign every peer in network minimum Bandwidth
421    * Distribute bandwidth left according to preference
422    */
423
424   if ((net->active_addresses * min_bw) > net->total_quota_in)
425   {
426     GNUNET_break (0);
427     return;
428   }
429   if ((net->active_addresses * min_bw) > net->total_quota_out)
430   {
431     GNUNET_break (0);
432     return;
433   }
434
435   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
436   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
437   LOG (GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
438               remaining_quota_in, remaining_quota_out);
439   total_prefs = 0.0;
440   for (cur = net->head; NULL != cur; cur = cur->next)
441   {
442       if (GNUNET_YES == cur->addr->active)
443       {
444         GNUNET_assert (NULL != (t = s->get_preferences (s->get_preferences_cls, &cur->addr->peer)));
445
446                                 peer_prefs = 0.0;
447                                 for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
448                                 {
449                                         if (c != GNUNET_ATS_PREFERENCE_END)
450                                         {
451                                                 //fprintf (stderr, "VALUE[%u] %s %.3f \n", c, GNUNET_i2s (&cur->addr->peer), t[c]);
452                                                 peer_prefs += t[c];
453                                         }
454                                 }
455                                 total_prefs += (peer_prefs / (GNUNET_ATS_PreferenceCount -1));
456       }
457   }
458   for (cur = net->head; NULL != cur; cur = cur->next)
459   {
460      if (GNUNET_YES == cur->addr->active)
461      {
462        cur_pref = 0.0;
463        GNUNET_assert (NULL != (t = s->get_preferences (s->get_preferences_cls, &cur->addr->peer)));
464
465                          for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
466                          {
467                                  if (c != GNUNET_ATS_PREFERENCE_END)
468                                          cur_pref += t[c];
469                          }
470                          cur_pref /= 2;
471
472        assigned_quota_in = min_bw + ((cur_pref / total_prefs) * remaining_quota_in);
473        assigned_quota_out = min_bw + ((cur_pref / total_prefs) * remaining_quota_out);
474
475        LOG (GNUNET_ERROR_TYPE_DEBUG,
476                    "New quota for peer `%s' with preference (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
477                    GNUNET_i2s (&cur->addr->peer),
478                    cur_pref, total_prefs,
479                    assigned_quota_in, assigned_quota_out);
480      }
481      else
482      {
483        assigned_quota_in = 0;
484        assigned_quota_out = 0;
485      }
486
487      quota_in_used += assigned_quota_in;
488      quota_out_used += assigned_quota_out;
489      /* Prevent overflow due to rounding errors */
490      if (assigned_quota_in > UINT32_MAX)
491        assigned_quota_in = UINT32_MAX;
492      if (assigned_quota_out > UINT32_MAX)
493        assigned_quota_out = UINT32_MAX;
494
495      /* Compare to current bandwidth assigned */
496      if ((assigned_quota_in != ntohl(cur->addr->assigned_bw_in.value__)) ||
497          (assigned_quota_out != ntohl(cur->addr->assigned_bw_out.value__)))
498      {
499        cur->addr->assigned_bw_in.value__ = htonl (assigned_quota_in);
500        cur->addr->assigned_bw_out.value__ = htonl (assigned_quota_out);
501        /* Notify on change */
502        if ((GNUNET_YES == cur->addr->active) && (cur->addr != address_except))
503          s->bw_changed (s->bw_changed_cls, cur->addr);
504      }
505
506   }
507   LOG (GNUNET_ERROR_TYPE_DEBUG,
508                           "Total bandwidth assigned is (in/out): %llu /%llu\n",
509                           quota_in_used,
510                           quota_out_used);
511   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
512   {
513       LOG (GNUNET_ERROR_TYPE_ERROR,
514                             "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
515                             net->active_addresses,
516                             quota_out_used,
517                             net->total_quota_out);
518   }
519   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
520   {
521       LOG (GNUNET_ERROR_TYPE_ERROR,
522                             "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
523                             net->active_addresses,
524                             quota_in_used,
525                             net->total_quota_in);
526   }
527 }
528
529
530 /**
531  * Extract an ATS performance info from an address
532  *
533  * @param address the address
534  * @param type the type to extract in HBO
535  * @return the value in HBO or GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
536  */
537 static int
538 get_performance_info (struct ATS_Address *address, uint32_t type);
539
540 /**
541  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
542  * If we already have an existing address, we stick to it.
543  * Otherwise, we pick by lowest distance and then by lowest latency.
544  *
545  * @param cls the 'struct ATS_Address**' where we store the result
546  * @param key unused
547  * @param value another 'struct ATS_Address*' to consider using
548  * @return GNUNET_OK (continue to iterate)
549  */
550 static int
551 find_best_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
552 {
553   struct ATS_Address **previous_p = cls;
554   struct ATS_Address *current = (struct ATS_Address *) value;
555   struct ATS_Address *previous = *previous_p;
556   struct GNUNET_TIME_Absolute now;
557   struct Network *net = (struct Network *) current->solver_information;
558   uint32_t p_distance_cur;
559   uint32_t p_distance_prev;
560   uint32_t p_delay_cur;
561   uint32_t p_delay_prev;
562
563   now = GNUNET_TIME_absolute_get();
564
565   if (current->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value)
566   {
567     /* This address is blocked for suggestion */
568     LOG (GNUNET_ERROR_TYPE_DEBUG,
569                 "Address %p blocked for suggestion for %llu ms \n",
570                 current,
571                 GNUNET_TIME_absolute_get_difference(now, current->blocked_until).rel_value);
572     return GNUNET_OK;
573   }
574
575   if (GNUNET_NO == is_bandwidth_available_in_network (net))
576     return GNUNET_OK; /* There's no bandwidth available in this network */
577
578   if (NULL != previous)
579   {
580         GNUNET_assert (NULL != previous->plugin);
581         GNUNET_assert (NULL != current->plugin);
582     if (0 == strcmp (previous->plugin, current->plugin))
583     {
584       if ((0 != previous->addr_len) &&
585           (0 == current->addr_len))
586       {
587         /* saved address was an outbound address, but we have an inbound address */
588         *previous_p = current;
589         return GNUNET_OK;
590       }
591       if (0 == previous->addr_len)
592       {
593         /* saved address was an inbound address, so do not overwrite */
594         return GNUNET_OK;
595       }
596     }
597   }
598
599   if (NULL == previous)
600   {
601     *previous_p = current;
602     return GNUNET_OK;
603   }
604   if ((ntohl (previous->assigned_bw_in.value__) == 0) &&
605       (ntohl (current->assigned_bw_in.value__) > 0))
606   {
607     /* stick to existing connection */
608     *previous_p = current;
609     return GNUNET_OK;
610   }
611
612   p_distance_prev = get_performance_info (previous, GNUNET_ATS_QUALITY_NET_DISTANCE);
613   p_distance_cur = get_performance_info (current, GNUNET_ATS_QUALITY_NET_DISTANCE);
614   if ((p_distance_prev != GNUNET_ATS_VALUE_UNDEFINED) && (p_distance_cur != GNUNET_ATS_VALUE_UNDEFINED) &&
615                 (p_distance_prev > p_distance_cur))
616   {
617     /* user shorter distance */
618     *previous_p = current;
619     return GNUNET_OK;
620   }
621
622   p_delay_prev = get_performance_info (previous, GNUNET_ATS_QUALITY_NET_DELAY);
623   p_delay_cur = get_performance_info (current, GNUNET_ATS_QUALITY_NET_DELAY);
624   if ((p_delay_prev != GNUNET_ATS_VALUE_UNDEFINED) && (p_delay_cur != GNUNET_ATS_VALUE_UNDEFINED) &&
625                 (p_delay_prev > p_delay_cur))
626   {
627     /* user lower latency */
628     *previous_p = current;
629     return GNUNET_OK;
630   }
631
632   /* don't care */
633   return GNUNET_OK;
634 }
635
636 /**
637  *  Helper functions
638  *  ---------------------------
639  */
640
641 /**
642  * Update bandwidth assignment for all networks
643  *
644  * @param s the solver handle
645  */
646 static void
647 distribute_bandwidth_in_all_networks (struct GAS_PROPORTIONAL_Handle *s)
648 {
649         int i;
650         for (i = 0; i < s->networks; i++)
651                 distribute_bandwidth_in_network (s, &s->network_entries[i], NULL);
652
653 }
654
655
656 /**
657  * Lookup network struct by type
658  *
659  * @param s the solver handle
660  * @param type the network type
661  * @return the network struct
662  */
663 static struct Network *
664 get_network (struct GAS_PROPORTIONAL_Handle *s, uint32_t type)
665 {
666   int c;
667   for (c = 0 ; c < s->networks; c++)
668   {
669       if (s->network_entries[c].type == type)
670         return &s->network_entries[c];
671   }
672   return NULL;
673 }
674
675
676 /**
677  * Hashmap Iterator to find current active address for peer
678  *
679  * @param cls last active address
680  * @param key peer's key
681  * @param value address to check
682  * @return GNUNET_NO on double active address else GNUNET_YES
683  */
684 static int
685 get_active_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
686 {
687   struct ATS_Address * dest = (struct ATS_Address *) (*(struct ATS_Address **)cls);
688   struct ATS_Address * aa = (struct ATS_Address *) value;
689
690   if (GNUNET_YES == aa->active)
691   {
692       if (dest != NULL)
693       {
694           /* should never happen */
695           LOG (GNUNET_ERROR_TYPE_ERROR, "Multiple active addresses for peer `%s'\n", GNUNET_i2s (&aa->peer));
696           GNUNET_break (0);
697           return GNUNET_NO;
698       }
699       dest = aa;
700   }
701   return GNUNET_OK;
702 }
703
704
705 /**
706  * Find current active address for peer
707  *
708  * @param solver the solver handle
709  * @param addresses the address set
710  * @param peer the peer
711  * @return active address or NULL
712  */
713 static struct ATS_Address *
714 get_active_address (void *solver,
715                      struct GNUNET_CONTAINER_MultiHashMap * addresses,
716                      const struct GNUNET_PeerIdentity *peer)
717 {
718   struct ATS_Address * dest = NULL;
719
720   GNUNET_CONTAINER_multihashmap_get_multiple(addresses,
721        &peer->hashPubKey,
722        &get_active_address_it, &dest);
723   return dest;
724 }
725
726
727
728 static void
729 addresse_increment (struct GAS_PROPORTIONAL_Handle *s,
730                                 struct Network *net,
731                                 int total,
732                                 int active)
733 {
734   if (GNUNET_YES == total)
735   {
736       s->total_addresses ++;
737       net->total_addresses ++;
738       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
739       GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
740   }
741   if (GNUNET_YES == active)
742   {
743     net->active_addresses ++;
744     s->active_addresses ++;
745     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1, GNUNET_NO);
746     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
747   }
748
749 }
750
751
752 static int
753 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s,
754                     struct Network *net,
755                     int total,
756                     int active)
757 {
758   int res = GNUNET_OK;
759   if (GNUNET_YES == total)
760   {
761     if (s->total_addresses < 1)
762     {
763       GNUNET_break (0);
764       res = GNUNET_SYSERR;
765     }
766     else
767     {
768       s->total_addresses --;
769       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
770     }
771     if (net->total_addresses < 1)
772     {
773       GNUNET_break (0);
774       res = GNUNET_SYSERR;
775     }
776     else
777     {
778       net->total_addresses --;
779       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
780     }
781   }
782
783   if (GNUNET_YES == active)
784   {
785     if (net->active_addresses < 1)
786     {
787       GNUNET_break (0);
788       res = GNUNET_SYSERR;
789     }
790     else
791     {
792       net->active_addresses --;
793       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
794     }
795     if (s->active_addresses < 1)
796     {
797       GNUNET_break (0);
798       res = GNUNET_SYSERR;
799     }
800     else
801     {
802       s->active_addresses --;
803       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
804     }
805   }
806   return res;
807 }
808
809
810 /**
811  * Extract an ATS performance info from an address
812  *
813  * @param address the address
814  * @param type the type to extract in HBO
815  * @return the value in HBO or GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
816  */
817 static int
818 get_performance_info (struct ATS_Address *address, uint32_t type)
819 {
820         int c1;
821         GNUNET_assert (NULL != address);
822
823         if ((NULL == address->atsi) || (0 == address->atsi_count))
824                         return GNUNET_ATS_VALUE_UNDEFINED;
825
826         for (c1 = 0; c1 < address->atsi_count; c1++)
827         {
828                         if (ntohl(address->atsi[c1].type) == type)
829                                 return ntohl(address->atsi[c1].value);
830         }
831         return GNUNET_ATS_VALUE_UNDEFINED;
832 }
833
834
835 /**
836  *  Solver API functions
837  *  ---------------------------
838  */
839
840 /**
841  * Changes the preferences for a peer in the problem
842  *
843  * @param solver the solver handle
844  * @param addresses the address hashmap
845  * @param peer the peer to change the preference for
846  * @param kind the kind to change the preference
847  * @param pref_rel the normalized preference value for this kind over all clients
848  */
849 void
850 GAS_proportional_address_change_preference (void *solver,
851                                                                                         struct GNUNET_CONTAINER_MultiHashMap *addresses,
852                                                                                         const struct GNUNET_PeerIdentity *peer,
853                                                                                         enum GNUNET_ATS_PreferenceKind kind,
854                                                                                         double pref_rel)
855 {
856   struct GAS_PROPORTIONAL_Handle *s = solver;
857   GNUNET_assert (NULL != solver);
858   GNUNET_assert (NULL != peer);
859   distribute_bandwidth_in_all_networks (s);
860 }
861
862 /**
863  * Get the preferred address for a specific peer
864  *
865  * @param solver the solver handle
866  * @param addresses the address hashmap containing all addresses
867  * @param peer the identity of the peer
868  */
869 const struct ATS_Address *
870 GAS_proportional_get_preferred_address (void *solver,
871                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
872                                const struct GNUNET_PeerIdentity *peer)
873 {
874   struct GAS_PROPORTIONAL_Handle *s = solver;
875   struct Network *net_prev;
876   struct Network *net_cur;
877   struct ATS_Address *cur;
878   struct ATS_Address *prev;
879
880   GNUNET_assert (s != NULL);
881   cur = NULL;
882   /* Get address with: stick to current address, lower distance, lower latency */
883   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
884                                               &find_best_address_it, &cur);
885   if (NULL == cur)
886   {
887     LOG (GNUNET_ERROR_TYPE_DEBUG, "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
888     return NULL;
889   }
890
891   LOG (GNUNET_ERROR_TYPE_DEBUG, "Suggesting %s address %p for peer `%s'\n",
892       (GNUNET_NO == cur->active) ? "inactive" : "active",
893       cur, GNUNET_i2s (peer));
894   net_cur = (struct Network *) cur->solver_information;
895   if (GNUNET_YES == cur->active)
896   {
897       /* This address was selected previously, so no need to update quotas */
898       return cur;
899   }
900
901   /* This address was not active, so we have to:
902    *
903    * - mark previous active address as not active
904    * - update quota for previous address network
905    * - update quota for this address network
906    */
907
908   prev = get_active_address (s, addresses, peer);
909   if (NULL != prev)
910   {
911       net_prev = (struct Network *) prev->solver_information;
912       prev->active = GNUNET_NO; /* No active any longer */
913       prev->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
914       prev->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
915       s->bw_changed (s->bw_changed_cls, prev); /* notify about bw change, REQUIRED? */
916       if (GNUNET_SYSERR == addresse_decrement (s, net_prev, GNUNET_NO, GNUNET_YES))
917         GNUNET_break (0);
918       distribute_bandwidth_in_network (s, net_prev, NULL);
919   }
920
921   if (GNUNET_NO == (is_bandwidth_available_in_network (cur->solver_information)))
922   {
923     GNUNET_break (0); /* This should never happen*/
924     return NULL;
925   }
926
927   cur->active = GNUNET_YES;
928   addresse_increment(s, net_cur, GNUNET_NO, GNUNET_YES);
929   distribute_bandwidth_in_network (s, net_cur, cur);
930
931   return cur;
932 }
933
934
935 /**
936  * Stop notifying about address and bandwidth changes for this peer
937  *
938  * @param solver the solver handle
939  * @param addresses address hashmap
940  * @param peer the peer
941  */
942 void
943 GAS_proportional_stop_get_preferred_address (void *solver,
944                                      struct GNUNET_CONTAINER_MultiHashMap *addresses,
945                                      const struct GNUNET_PeerIdentity *peer)
946 {
947         return;
948 }
949
950
951 /**
952  * Remove an address from the solver
953  *
954  * @param solver the solver handle
955  * @param addresses the address hashmap containing all addresses
956  * @param address the address to remove
957  * @param session_only delete only session not whole address
958  */
959 void
960 GAS_proportional_address_delete (void *solver,
961     struct GNUNET_CONTAINER_MultiHashMap * addresses,
962     struct ATS_Address *address, int session_only)
963 {
964   struct GAS_PROPORTIONAL_Handle *s = solver;
965   struct Network *net;
966   struct AddressWrapper *aw;
967
968   /* Remove an adress completely, we have to:
969    * - Remove from specific network
970    * - Decrease number of total addresses
971    * - If active:
972    *   - decrease number of active addreses
973    *   - update quotas
974    */
975
976   net = (struct Network *) address->solver_information;
977
978   if (GNUNET_NO == session_only)
979   {
980     LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
981         (GNUNET_NO == address->active) ? "inactive" : "active",
982         address, GNUNET_i2s (&address->peer),
983         net->desc, net->total_addresses, net->active_addresses);
984
985     /* Remove address */
986     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
987     for (aw = net->head; NULL != aw; aw = aw->next)
988     {
989         if (aw->addr == address)
990           break;
991     }
992     if (NULL == aw )
993     {
994         GNUNET_break (0);
995         return;
996     }
997     GNUNET_CONTAINER_DLL_remove (net->head, net->tail, aw);
998     GNUNET_free (aw);
999   }
1000   else
1001   {
1002       /* Remove session only: remove if active and update */
1003       LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1004           (GNUNET_NO == address->active) ? "inactive" : "active",
1005           address, GNUNET_i2s (&address->peer),
1006           net->desc, net->total_addresses, net->active_addresses);
1007   }
1008
1009   if (GNUNET_YES == address->active)
1010   {
1011       /* Address was active, remove from network and update quotas*/
1012       address->active = GNUNET_NO;
1013       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1014         GNUNET_break (0);
1015       distribute_bandwidth_in_network (s, net, NULL);
1016   }
1017   LOG (GNUNET_ERROR_TYPE_DEBUG, "After deleting address now total %u and active %u addresses in network `%s'\n",
1018       net->total_addresses,
1019       net->active_addresses,
1020       net->desc);
1021
1022 }
1023
1024
1025 /**
1026  * Add a new single address to a network
1027  *
1028  * @param solver the solver Handle
1029  * @param addresses the address hashmap containing all addresses
1030  * @param address the address to add
1031  * @param network network type of this address
1032  */
1033 void
1034 GAS_proportional_address_add (void *solver,
1035                                                         struct GNUNET_CONTAINER_MultiHashMap *addresses,
1036                                                         struct ATS_Address *address,
1037                                                         uint32_t network);
1038
1039 /**
1040  * Updates a single address in the solver and checks previous values
1041  *
1042  * @param solver the solver Handle
1043  * @param addresses the address hashmap containing all addresses
1044  * @param address the update address
1045  * @param session the previous session
1046  * @param in_use the previous address in use state
1047  * @param prev_ats previous ATS information
1048  * @param prev_atsi_count the previous atsi count
1049  */
1050 void
1051 GAS_proportional_address_update (void *solver,
1052                               struct GNUNET_CONTAINER_MultiHashMap *addresses,
1053                               struct ATS_Address *address,
1054                               uint32_t session,
1055                               int in_use,
1056                               const struct GNUNET_ATS_Information *prev_ats,
1057                               uint32_t prev_atsi_count)
1058 {
1059   struct ATS_Address *new;
1060   struct GAS_PROPORTIONAL_Handle *s = (struct GAS_PROPORTIONAL_Handle *) solver;
1061   int i;
1062   uint32_t prev_value;
1063   uint32_t prev_type;
1064   uint32_t addr_net;
1065   int save_active = GNUNET_NO;
1066   struct Network *new_net = NULL;
1067
1068   /* Check updates to performance information */
1069   for (i = 0; i < prev_atsi_count; i++)
1070   {
1071     prev_type = ntohl (prev_ats[i].type);
1072     prev_value = ntohl (prev_ats[i].value);
1073     switch (prev_type)
1074     {
1075     case GNUNET_ATS_UTILIZATION_UP:
1076     case GNUNET_ATS_UTILIZATION_DOWN:
1077     case GNUNET_ATS_QUALITY_NET_DELAY:
1078     case GNUNET_ATS_QUALITY_NET_DISTANCE:
1079     case GNUNET_ATS_COST_WAN:
1080     case GNUNET_ATS_COST_LAN:
1081     case GNUNET_ATS_COST_WLAN:
1082         /* No actions required here*/
1083         break;
1084     case GNUNET_ATS_NETWORK_TYPE:
1085
1086       addr_net = get_performance_info (address, GNUNET_ATS_NETWORK_TYPE);
1087       if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
1088       {
1089         GNUNET_break (0);
1090         addr_net = GNUNET_ATS_NET_UNSPECIFIED;
1091       }
1092       if (addr_net != prev_value)
1093       {
1094         /* Network changed */
1095         LOG (GNUNET_ERROR_TYPE_DEBUG, "Network type changed, moving %s address from `%s' to `%s'\n",
1096             (GNUNET_YES == address->active) ? "active" : "inactive",
1097              GNUNET_ATS_print_network_type(prev_value),
1098              GNUNET_ATS_print_network_type(addr_net));
1099
1100         save_active = address->active;
1101         /* remove from old network */
1102         GAS_proportional_address_delete (solver, addresses, address, GNUNET_NO);
1103
1104         /* set new network type */
1105         new_net = get_network (solver, addr_net);
1106         address->solver_information = new_net;
1107
1108         /* Add to new network and update*/
1109         GAS_proportional_address_add (solver, addresses, address, addr_net);
1110         if (GNUNET_YES == save_active)
1111         {
1112           /* check if bandwidth available in new network */
1113           if (GNUNET_YES == (is_bandwidth_available_in_network (new_net)))
1114           {
1115               /* Suggest updated address */
1116               address->active = GNUNET_YES;
1117               addresse_increment (s, new_net, GNUNET_NO, GNUNET_YES);
1118               distribute_bandwidth_in_network (solver, new_net, NULL);
1119           }
1120           else
1121           {
1122             LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough bandwidth in new network, suggesting alternative address ..\n");
1123
1124             /* Set old address to zero bw */
1125             address->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0);
1126             address->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0);
1127             s->bw_changed  (s->bw_changed_cls, address);
1128
1129             /* Find new address to suggest since no bandwidth in network*/
1130             new = (struct ATS_Address *) GAS_proportional_get_preferred_address (s, addresses, &address->peer);
1131             if (NULL != new)
1132             {
1133                 /* Have an alternative address to suggest */
1134                 s->bw_changed  (s->bw_changed_cls, new);
1135             }
1136
1137           }
1138         }
1139       }
1140
1141       break;
1142     case GNUNET_ATS_ARRAY_TERMINATOR:
1143       break;
1144     default:
1145       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1146                   "Received unsupported ATS type %u\n", prev_type);
1147       GNUNET_break (0);
1148       break;
1149
1150     }
1151
1152   }
1153   if (address->session_id != session)
1154   {
1155       LOG (GNUNET_ERROR_TYPE_DEBUG,
1156                   "Session changed from %u to %u\n", session, address->session_id);
1157   }
1158   if (address->used != in_use)
1159   {
1160       LOG (GNUNET_ERROR_TYPE_DEBUG,
1161                   "Usage changed from %u to %u\n", in_use, address->used);
1162   }
1163
1164 }
1165
1166
1167 /**
1168  * Add a new single address to a network
1169  *
1170  * @param solver the solver Handle
1171  * @param addresses the address hashmap containing all addresses
1172  * @param address the address to add
1173  * @param network network type of this address
1174  */
1175 void
1176 GAS_proportional_address_add (void *solver,
1177                                                         struct GNUNET_CONTAINER_MultiHashMap *addresses,
1178                                                         struct ATS_Address *address,
1179                                                         uint32_t network)
1180 {
1181   struct GAS_PROPORTIONAL_Handle *s = solver;
1182   struct Network *net = NULL;
1183   struct AddressWrapper *aw = NULL;
1184   GNUNET_assert (NULL != s);
1185
1186   net = get_network (s, network);
1187   if (NULL == net)
1188   {
1189     GNUNET_break (0);
1190     return;
1191   }
1192
1193   aw = GNUNET_malloc (sizeof (struct AddressWrapper));
1194   aw->addr = address;
1195   GNUNET_CONTAINER_DLL_insert (net->head, net->tail, aw);
1196   addresse_increment (s, net, GNUNET_YES, GNUNET_NO);
1197   aw->addr->solver_information = net;
1198
1199   LOG (GNUNET_ERROR_TYPE_DEBUG, "After adding address now total %u and active %u addresses in network `%s'\n",
1200       net->total_addresses,
1201       net->active_addresses,
1202       net->desc);
1203 }
1204
1205
1206 /**
1207  * Init the proportional problem solver
1208  *
1209  * Quotas:
1210  * network[i] contains the network type as type GNUNET_ATS_NetworkType[i]
1211  * out_quota[i] contains outbound quota for network type i
1212  * in_quota[i] contains inbound quota for network type i
1213  *
1214  * Example
1215  * network = {GNUNET_ATS_NET_UNSPECIFIED, GNUNET_ATS_NET_LOOPBACK, GNUNET_ATS_NET_LAN, GNUNET_ATS_NET_WAN, GNUNET_ATS_NET_WLAN}
1216  * network[2]   == GNUNET_ATS_NET_LAN
1217  * out_quota[2] == 65353
1218  * in_quota[2]  == 65353
1219  *
1220  * @param cfg configuration handle
1221  * @param stats the GNUNET_STATISTICS handle
1222  * @param network array of GNUNET_ATS_NetworkType with length dest_length
1223  * @param out_quota array of outbound quotas
1224  * @param in_quota array of outbound quota
1225  * @param dest_length array length for quota arrays
1226  * @param bw_changed_cb callback for changed bandwidth amounts
1227  * @param bw_changed_cb_cls cls for callback
1228  * @param get_preference callback to get relative preferences for a peer
1229  * @param get_preference_cls cls for callback to get relative preferences
1230  * @return handle for the solver on success, NULL on fail
1231  */
1232 void *
1233 GAS_proportional_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1234                        const struct GNUNET_STATISTICS_Handle *stats,
1235                        int *network,
1236                        unsigned long long *out_quota,
1237                        unsigned long long *in_quota,
1238                        int dest_length,
1239                        GAS_bandwidth_changed_cb bw_changed_cb,
1240                        void *bw_changed_cb_cls,
1241                        GAS_get_preferences get_preference,
1242                        void *get_preference_cls)
1243 {
1244   int c;
1245   struct GAS_PROPORTIONAL_Handle *s = GNUNET_malloc (sizeof (struct GAS_PROPORTIONAL_Handle));
1246   struct Network * cur;
1247   char * net_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
1248
1249
1250   s->stats = (struct GNUNET_STATISTICS_Handle *) stats;
1251   s->bw_changed = bw_changed_cb;
1252   s->bw_changed_cls = bw_changed_cb_cls;
1253   s->get_preferences = get_preference;
1254   s->get_preferences_cls = get_preference_cls;
1255   s->networks = dest_length;
1256   s->network_entries = GNUNET_malloc (dest_length * sizeof (struct Network));
1257   s->active_addresses = 0;
1258   s->total_addresses = 0;
1259   s->prefs = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1260
1261   for (c = 0; c < dest_length; c++)
1262   {
1263       cur = &s->network_entries[c];
1264       cur->total_addresses = 0;
1265       cur->active_addresses = 0;
1266       cur->type = network[c];
1267       cur->total_quota_in = in_quota[c];
1268       cur->total_quota_out = out_quota[c];
1269       cur->desc = net_str[c];
1270       GNUNET_asprintf (&cur->stat_total, "# ATS addresses %s total", cur->desc);
1271       GNUNET_asprintf (&cur->stat_active, "# ATS active addresses %s total", cur->desc);
1272   }
1273   return s;
1274 }
1275
1276
1277 /**
1278  * Shutdown the proportional problem solver
1279  *
1280  * @param solver the respective handle to shutdown
1281  */
1282 void
1283 GAS_proportional_done (void *solver)
1284 {
1285   struct GAS_PROPORTIONAL_Handle *s = solver;
1286   struct AddressWrapper *cur;
1287   struct AddressWrapper *next;
1288   int c;
1289   GNUNET_assert (s != NULL);
1290
1291   for (c = 0; c < s->networks; c++)
1292   {
1293       if (s->network_entries[c].total_addresses > 0)
1294       {
1295         LOG (GNUNET_ERROR_TYPE_ERROR,
1296                     "Had %u addresses for network `%s' not deleted during shutdown\n",
1297                     s->network_entries[c].total_addresses,
1298                     s->network_entries[c].desc);
1299         GNUNET_break (0);
1300       }
1301
1302       if (s->network_entries[c].active_addresses > 0)
1303       {
1304         LOG (GNUNET_ERROR_TYPE_ERROR,
1305                     "Had %u active addresses for network `%s' not deleted during shutdown\n",
1306                     s->network_entries[c].active_addresses,
1307                     s->network_entries[c].desc);
1308         GNUNET_break (0);
1309       }
1310
1311       next = s->network_entries[c].head;
1312       while (NULL != (cur = next))
1313       {
1314           next = cur->next;
1315           GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head,
1316                                        s->network_entries[c].tail,
1317                                        cur);
1318           GNUNET_free (cur);
1319       }
1320       GNUNET_free (s->network_entries[c].stat_total);
1321       GNUNET_free (s->network_entries[c].stat_active);
1322   }
1323   if (s->total_addresses > 0)
1324   {
1325     LOG (GNUNET_ERROR_TYPE_ERROR,
1326                 "Had %u addresses not deleted during shutdown\n",
1327                 s->total_addresses);
1328     GNUNET_break (0);
1329   }
1330   if (s->active_addresses > 0)
1331   {
1332     LOG (GNUNET_ERROR_TYPE_ERROR,
1333                 "Had %u active addresses not deleted during shutdown\n",
1334                 s->active_addresses);
1335     GNUNET_break (0);
1336   }
1337   GNUNET_free (s->network_entries);
1338   GNUNET_free (s);
1339 }
1340
1341
1342 /* end of gnunet-service-ats-solver_proportional.c */