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