-cleaning up bandwidth allocation routine
[oweals/gnunet.git] / src / ats / plugin_ats_proportional.c
1 /*
2  This file is part of GNUnet.
3  Copyright (C) 2011-2015 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/plugin_ats_proportional.c
23  * @brief ATS proportional solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_ats_plugin.h"
30 #include "gnunet_ats_service.h"
31 #include "gnunet-service-ats_addresses.h"
32
33 #define PROP_STABILITY_FACTOR 1.25
34
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__)
37
38
39 /**
40  *
41  * NOTE: Do not change this documentation. This documentation is based
42  * on gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
43  * use build_txt.sh to generate plaintext output
44  *
45  * ATS addresses : proportional solver
46  *
47  *    The proportional solver ("proportional") distributes the available
48  *    bandwidth fair over all the addresses influenced by the
49  *    preference values. For each available network type an in- and
50  *    outbound quota is configured and the bandwidth available in
51  *    these networks is distributed over the addresses.  The solver
52  *    first assigns every addresses the minimum amount of bandwidth
53  *    #GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT and then distributes the
54  *    remaining bandwidth available according to the preference
55  *    values. For each peer only a single address gets bandwidth
56  *    assigned and only one address marked as active.  The most
57  *    important functionality for the solver is implemented in: *
58  *    find_address_it is an hashmap iterator returning the prefered
59  *    address for an peer * update_quota_per_network distributes
60  *    available bandwidth for a network over active addresses
61  *
62  *    Changes to addresses automatically have an impact on the the
63  *    bandwidth assigned to other addresses in the same network since
64  *    the solver distributes the remaining bandwidth over the
65  *    addresses in the network.  When changes to the addresses occur,
66  *    the solver first performs the changes, like adding or deleting
67  *    addresses, and then updates bandwidth assignment for the
68  *    affected network. Bandwidth assignment is only recalculated on
69  *    demand when an address is requested by a client for a peer or
70  *    when the addresses available have changed or an address changed
71  *    the network it is located in. When the bandwidth assignment has
72  *    changed the callback is called with the new bandwidth
73  *    assignments. The bandwidth distribution for a network is
74  *    recalculated due to: * address suggestion requests * address
75  *    deletions * address switching networks during address update *
76  *    preference changes
77  *
78  *     3.1 Data structures used
79  *
80  *    For each ATS network (e.g. WAN, LAN, loopback) a struct Network
81  *    is used to specify network related information as total adresses
82  *    and active addresses in this network and the configured in- and
83  *    outbound quota. Each network also contains a list of addresses
84  *    added to the solver located in this network. The proportional
85  *    solver uses the addresses' solver_information field to store the
86  *    proportional network it belongs to for each address.
87  *
88  *     3.2 Initializing
89  *
90  *    When the proportional solver is initialized the solver creates a
91  *    new solver handle and initializes the network structures with
92  *    the quotas passed from addresses and returns the handle solver.
93  *
94  *     3.3 Adding an address
95  *
96  *    When a new address is added to the solver using s_add, a lookup
97  *    for the network for this address is done and the address is
98  *    enqueued in in the linked list of the network.
99  *
100  *     3.4 Updating an address
101  *
102  *    The main purpose of address updates is to update the ATS
103  *    information for addresse selection. Important for the proportional
104  *    solver is when an address switches network it is located
105  *    in. This is common because addresses added by transport's
106  *    validation mechanism are commonly located in
107  *    #GNUNET_ATS_NET_UNSPECIFIED. Addresses in validation are located
108  *    in this network type and only if a connection is successful on
109  *    return of payload data transport switches to the real network
110  *    the address is located in.  When an address changes networks it
111  *    is first of all removed from the old network using the solver
112  *    API function #GAS_proportional_address_delete() and the network in
113  *    the address struct is updated. A lookup for the respective new
114  *    proportional network is done and stored in the addresse's
115  *    solver_information field. Next the address is re-added to the
116  *    solver using the solver API function
117  *    #GAS_proportional_address_add(). If the address was marked as in
118  *    active, the solver checks if bandwidth is available in the
119  *    network and if yes sets the address to active and updates the
120  *    bandwidth distribution in this network. If no bandwidth is
121  *    available it sets the bandwidth for this address to 0 and tries
122  *    to suggest an alternative address. If an alternative address was
123  *    found, addresses' callback is called for this address.
124  *
125  *     3.5 Deleting an address
126  *
127  *    When an address is removed from the solver, it removes the
128  *    respective address from the network and if the address was
129  *    marked as active, it updates the bandwidth distribution for this
130  *    network.
131  *
132  *     3.6 Requesting addresses
133  *
134  *    When an address is requested for a peer the solver performs a
135  *    lookup for the peer entry in addresses address hashmap and
136  *    selects the best address.  The selection of the most suitable
137  *    address is done in the find_address_it hashmap iterator
138  *    described in detail in section 3.7. If no address is returned,
139  *    no address can be suggested at the moment. If the address
140  *    returned is marked as active, the solver can return this
141  *    address. If the address is not marked as active, the solver
142  *    checks if another address belongign to this peer is marked as
143  *    active and marks the address as inactive, updates the bandwidth
144  *    for this address to 0, call the bandwidth changed callback for
145  *    this address due to the change and updates quota assignment for
146  *    the addresse's network. the now in-active address is belonging
147  *    to. The solver marks the new address as active and updates the
148  *    bandwidth assignment for this network.
149  *
150  *     3.7 Choosing addresses
151  *
152  *    Choosing the best possible address for suggestion is done by
153  *    iterating over all addresses of a peer stored in addresses'
154  *    hashmap and using the hashmap iterator find_address_it to select
155  *    the best available address.  Several checks are done when an
156  *    address is selected. First if this address is currently blocked
157  *    by addresses from being suggested. An address is blocked for the
158  *    duration of #ATS_BLOCKING_DELTA when it is suggested to
159  *    transport. Next it is checked if at least
160  *    #GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT bytes bandwidth is available
161  *    in the addresse's network, because suggesting an address without
162  *    bandwidth does not make sense. This also ensures that all active
163  *    addresses in this network get at least the minimum amount of
164  *    bandwidth assigned. In the next step the solver ensures that for
165  *    tcp connections inbound connections are prefered over outbound
166  *    connections. In the next stet the solver ensures that
167  *    connections are prefered in the following order: * connections
168  *    are already established and have bandwidth assigned *
169  *    connections with a shorter distance * connectes have a shorter
170  *    latency
171  *
172  *     3.8 Changing preferences
173  *
174  *     3.9 Shutdown
175  *
176  *    During shutdown all network entries and aging processes are
177  *    destroyed and freed.
178  *
179  *
180  * OLD DOCUMENTATION
181  *
182  * This solver assigns in and outbound bandwidth equally for all
183  * addresses in specific network type (WAN, LAN) based on configured
184  * in and outbound quota for this network.
185  *
186  * The solver is notified by addresses about changes to the addresses
187  * and recalculates the bandwith assigned if required. The solver
188  * notifies addresses by calling the GAS_bandwidth_changed_cb
189  * callback.
190  *
191  * - Initialization
192  *
193  *
194  *
195  *
196  * For each peer only a single is selected and marked as "active" in the address
197  * struct.
198  *
199  * E.g.:
200  *
201  * You have the networks WAN and LAN and quotas
202  * WAN_TOTAL_IN, WAN_TOTAL_OUT
203  * LAN_TOTAL_IN, LAN_TOTAL_OUT
204  *
205  * If you have x addresses in the network segment LAN, the quotas are
206  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
207  *
208  * Quotas are automatically recalculated and reported back when addresses are
209  * - requested
210  *
211  */
212
213 /**
214  * Default value to assume for the proportionality factor,
215  * if none is given in the configuration.
216  */
217 #define PROPORTIONALITY_FACTOR 2.0
218
219
220 /**
221  * Address information stored for the proportional solver in the
222  * `solver_information` member of `struct GNUNET_ATS_Address`.
223  *
224  * They are also stored in the respective `struct Network`'s linked
225  * list.
226  */
227 struct AddressWrapper
228 {
229   /**
230    * Next in DLL
231    */
232   struct AddressWrapper *next;
233
234   /**
235    * Previous in DLL
236    */
237   struct AddressWrapper *prev;
238
239   /**
240    * The address
241    */
242   struct ATS_Address *addr;
243
244     /**
245    * Network scope this address is in
246    */
247   struct Network *network;
248
249   /**
250    * Inbound quota
251    */
252   uint32_t calculated_quota_in;
253
254   /**
255    * Outbound quota
256    */
257   uint32_t calculated_quota_out;
258
259   /**
260    * When was this address activated
261    */
262   struct GNUNET_TIME_Absolute activated;
263
264 };
265
266
267 /**
268  * Representation of a network
269  */
270 struct Network
271 {
272   /**
273    * Network description
274    */
275   const char *desc;
276
277   /**
278    * String for statistics total addresses
279    */
280   char *stat_total;
281
282   /**
283    * String for statistics active addresses
284    */
285   char *stat_active;
286
287   /**
288    * Linked list of addresses in this network: head
289    */
290   struct AddressWrapper *head;
291
292   /**
293    * Linked list of addresses in this network: tail
294    */
295   struct AddressWrapper *tail;
296
297   /**
298    * Total inbound quota
299    */
300   unsigned long long total_quota_in;
301
302   /**
303    * Total outbound quota
304    */
305   unsigned long long total_quota_out;
306
307   /**
308    * ATS network type
309    */
310   enum GNUNET_ATS_Network_Type type;
311
312   /**
313    * Number of active addresses for this network
314    */
315   unsigned int active_addresses;
316
317   /**
318    * Number of total addresses for this network
319    */
320   unsigned int total_addresses;
321
322 };
323
324
325 /**
326  * A handle for the proportional solver
327  */
328 struct GAS_PROPORTIONAL_Handle
329 {
330
331   /**
332    * Our execution environment.
333    */
334   struct GNUNET_ATS_PluginEnvironment *env;
335
336   /**
337    * Networks array
338    */
339   struct Network *network_entries;
340
341   /**
342    * Proportionality factor
343    */
344   double prop_factor;
345
346   /**
347    * Stability factor
348    */
349   double stability_factor;
350
351   /**
352    * Bulk lock counter. If zero, we are not locked.
353    */
354   unsigned int bulk_lock;
355
356   /**
357    * Number of changes made while solver was locked.  We really only
358    * use 0/non-zero to check on unlock if we have to run the update.
359    */
360   unsigned int bulk_requests;
361
362   /**
363    * Number of active addresses for solver
364    */
365   unsigned int active_addresses;
366
367   /**
368    * Number of networks in @a network_entries
369    */
370   unsigned int network_count;
371 };
372
373
374 /**
375  * Test if bandwidth is available in this network to add an additional address.
376  *
377  * @param net the network type to check
378  * @param extra for how many extra addresses do we check?
379  * @return #GNUNET_YES or #GNUNET_NO
380  */
381 static int
382 is_bandwidth_available_in_network (struct Network *net,
383                                    int extra)
384 {
385   unsigned int na;
386   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
387
388   GNUNET_assert (net->active_addresses + extra >= 0);
389   na = net->active_addresses + extra;
390   if (0 == na)
391     return GNUNET_YES;
392   if ( ((net->total_quota_in / na) > min_bw) &&
393        ((net->total_quota_out / na) > min_bw) )
394     return GNUNET_YES;
395   return GNUNET_NO;
396 }
397
398
399 /**
400  * Test if all peers in this network require connectivity at level at
401  * least @a con.
402  *
403  * @param s the solver handle
404  * @param net the network type to check
405  * @param con connection return value threshold to check
406  * @return #GNUNET_YES or #GNUNET_NO
407  */
408 static int
409 all_require_connectivity (struct GAS_PROPORTIONAL_Handle *s,
410                           struct Network *net,
411                           unsigned int con)
412 {
413   struct AddressWrapper *aw;
414
415   for (aw = net->head; NULL != aw; aw = aw->next)
416     if (con >
417         s->env->get_connectivity (s->env->cls,
418                                   &aw->addr->peer))
419       return GNUNET_NO;
420   return GNUNET_YES;
421 }
422
423
424 /**
425  * Update bandwidth assigned to peers in this network.  The basic idea
426  * is to assign every peer in the network the minimum bandwidth, and
427  * then distribute the remaining bandwidth proportional to application
428  * preferences.
429  *
430  * @param s the solver handle
431  * @param net the network type to update
432  */
433 static void
434 distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
435                       struct Network *net)
436 {
437   const uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
438   struct AddressWrapper *aw;
439   unsigned long long remaining_quota_in;
440   unsigned long long quota_out_used;
441   unsigned long long remaining_quota_out;
442   unsigned long long quota_in_used;
443   unsigned int count_addresses;
444   double sum_relative_peer_prefences;
445   double peer_weight;
446   double total_weight;
447   const double *peer_relative_prefs;
448
449   LOG (GNUNET_ERROR_TYPE_INFO,
450        "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
451        net->desc,
452        net->active_addresses,
453        net->total_quota_in,
454        net->total_quota_in);
455
456   if (0 == net->active_addresses)
457     return; /* no addresses to update */
458
459   /* sanity checks */
460   if ((net->active_addresses * min_bw) > net->total_quota_in)
461   {
462     GNUNET_break(0);
463     return;
464   }
465   if ((net->active_addresses * min_bw) > net->total_quota_out)
466   {
467     GNUNET_break(0);
468     return;
469   }
470
471   /* Calculate sum of relative preference for active addresses in this
472      network */
473   sum_relative_peer_prefences = 0.0;
474   count_addresses = 0;
475   for (aw = net->head; NULL != aw; aw = aw->next)
476   {
477     if (GNUNET_YES != aw->addr->active)
478       continue;
479     peer_relative_prefs = s->env->get_preferences (s->env->cls,
480                                                    &aw->addr->peer);
481     sum_relative_peer_prefences += peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
482     count_addresses++;
483   }
484   if (count_addresses != net->active_addresses)
485   {
486     GNUNET_break (0);
487     LOG (GNUNET_ERROR_TYPE_WARNING,
488          "%s: Counted %u active addresses, expected %u active addresses\n",
489          net->desc,
490          count_addresses,
491          net->active_addresses);
492     /* try to fix... */
493     net->active_addresses = count_addresses;
494   }
495   LOG (GNUNET_ERROR_TYPE_INFO,
496        "Total relative preference %.3f for %u addresses in network %s\n",
497        sum_relative_peer_prefences,
498        net->active_addresses,
499        net->desc);
500
501   /* check how much we have to distribute */
502   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
503   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
504   LOG (GNUNET_ERROR_TYPE_DEBUG,
505        "Proportionally distributable bandwidth (in/out): %llu/%llu\n",
506        remaining_quota_in,
507        remaining_quota_out);
508
509   /* distribute remaining quota; we do not do it exactly proportional,
510      but balance "even" distribution ("net->active_addresses") with
511      the preference sum using the "prop_factor". */
512   total_weight = net->active_addresses +
513     s->prop_factor * sum_relative_peer_prefences;
514   quota_out_used = 0;
515   quota_in_used = 0;
516   for (aw = net->head; NULL != aw; aw = aw->next)
517   {
518     if (GNUNET_YES != aw->addr->active)
519     {
520       /* set to 0, just to be sure */
521       aw->calculated_quota_in = 0;
522       aw->calculated_quota_out = 0;
523       continue;
524     }
525     peer_relative_prefs = s->env->get_preferences (s->env->cls,
526                                                    &aw->addr->peer);
527     peer_weight = 1.0
528       + s->prop_factor * peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
529
530     aw->calculated_quota_in = min_bw
531       + (peer_weight / total_weight) * remaining_quota_in;
532     aw->calculated_quota_out = min_bw
533       + (peer_weight / total_weight) * remaining_quota_out;
534
535     LOG (GNUNET_ERROR_TYPE_INFO,
536          "New quotas for peer `%s' with weight (cur/total) %.3f/%.3f (in/out) are: %u/%u\n",
537          GNUNET_i2s (&aw->addr->peer),
538          peer_weight,
539          total_weight,
540          (unsigned int) aw->calculated_quota_in,
541          (unsigned int) aw->calculated_quota_out);
542     quota_in_used += aw->calculated_quota_in;
543     quota_out_used += aw->calculated_quota_out;
544   }
545   LOG (GNUNET_ERROR_TYPE_DEBUG,
546        "Total bandwidth assigned is (in/out): %llu /%llu\n",
547        quota_in_used,
548        quota_out_used);
549   /* +1 due to possible rounding errors */
550   GNUNET_break (quota_out_used <= net->total_quota_out + 1);
551   GNUNET_break (quota_in_used <= net->total_quota_in + 1);
552 }
553
554
555 /**
556  * Notify ATS service of bandwidth changes to addresses.
557  *
558  * @param s solver handle
559  * @param net the network to propagate changes in
560  */
561 static void
562 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
563                      struct Network *net)
564 {
565   struct AddressWrapper *cur;
566
567   for (cur = net->head; NULL != cur; cur = cur->next)
568   {
569     if ( (cur->addr->assigned_bw_in == cur->calculated_quota_in) &&
570          (cur->addr->assigned_bw_out == cur->calculated_quota_out) )
571       continue;
572     cur->addr->assigned_bw_in = cur->calculated_quota_in;
573     cur->addr->assigned_bw_out = cur->calculated_quota_out;
574     if (GNUNET_YES == cur->addr->active)
575       s->env->bandwidth_changed_cb (s->env->cls,
576                                     cur->addr);
577   }
578 }
579
580
581 /**
582  * Distribute bandwidth.  The addresses have already been selected,
583  * this is merely distributed the bandwidth among the addresses.
584  *
585  * @param s the solver handle
586  * @param n the network, can be NULL for all networks
587  */
588 static void
589 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
590                                  struct Network *n)
591 {
592   unsigned int i;
593
594   if (GNUNET_YES == s->bulk_lock)
595   {
596     s->bulk_requests++;
597     return;
598   }
599   if (NULL != n)
600   {
601     LOG (GNUNET_ERROR_TYPE_DEBUG,
602         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
603          GNUNET_ATS_print_network_type(n->type),
604          n->active_addresses,
605          n->total_addresses);
606     s->env->info_cb (s->env->cls,
607                      GAS_OP_SOLVE_START,
608                      GAS_STAT_SUCCESS,
609                      GAS_INFO_PROP_SINGLE);
610     distribute_bandwidth(s,
611                          n);
612     s->env->info_cb (s->env->cls,
613                      GAS_OP_SOLVE_STOP,
614                      GAS_STAT_SUCCESS,
615                      GAS_INFO_PROP_SINGLE);
616     s->env->info_cb (s->env->cls,
617                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
618                      GAS_STAT_SUCCESS,
619                      GAS_INFO_PROP_SINGLE);
620     propagate_bandwidth (s,
621                          n);
622
623     s->env->info_cb (s->env->cls,
624                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
625                      GAS_STAT_SUCCESS,
626                      GAS_INFO_PROP_SINGLE);
627   }
628   else
629   {
630     s->env->info_cb (s->env->cls,
631                      GAS_OP_SOLVE_START,
632                      GAS_STAT_SUCCESS,
633                      GAS_INFO_PROP_ALL);
634     for (i = 0; i < s->network_count; i++)
635       distribute_bandwidth (s,
636                             &s->network_entries[i]);
637     s->env->info_cb (s->env->cls,
638                      GAS_OP_SOLVE_STOP,
639                      GAS_STAT_SUCCESS,
640                      GAS_INFO_PROP_ALL);
641     s->env->info_cb (s->env->cls,
642                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
643                      GAS_STAT_SUCCESS,
644                      GAS_INFO_PROP_ALL);
645     for (i = 0; i < s->network_count; i++)
646       propagate_bandwidth (s,
647                            &s->network_entries[i]);
648     s->env->info_cb (s->env->cls,
649                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
650                      GAS_STAT_SUCCESS,
651                      GAS_INFO_PROP_ALL);
652   }
653 }
654
655
656 /**
657  * Context for finding the best address* Linked list of addresses in this network: head
658  */
659 struct FindBestAddressCtx
660 {
661   /**
662    * The solver handle
663    */
664   struct GAS_PROPORTIONAL_Handle *s;
665
666   /**
667    * The currently best address
668    */
669   struct ATS_Address *best;
670 };
671
672
673 /**
674  * Find index of a ATS property type in the quality properties array.
675  *
676  * @param type ATS property type
677  * @return index in the quality array, #GNUNET_SYSERR if the type
678  *         was not a quality property
679  */
680 static int
681 find_quality_property_index (enum GNUNET_ATS_Property type)
682 {
683   enum GNUNET_ATS_Property existing_types[] = GNUNET_ATS_QualityProperties;
684   unsigned int c;
685
686   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
687     if (existing_types[c] == type)
688       return c;
689   GNUNET_break (0);
690   return GNUNET_SYSERR;
691 }
692
693
694 /**
695  * Find a "good" address to use for a peer by iterating over the
696  * addresses for this peer.  If we already have an existing address,
697  * we stick to it.  Otherwise, we pick by lowest distance and then by
698  * lowest latency.
699  *
700  * @param cls the `struct FindBestAddressCtx *' where we store the result
701  * @param key the peer we are trying to find the best address for
702  * @param value another `struct ATS_Address*` to consider using
703  * @return #GNUNET_OK (continue to iterate)
704  */
705 static int
706 find_best_address_it (void *cls,
707                       const struct GNUNET_PeerIdentity *key,
708                       void *value)
709 {
710   struct FindBestAddressCtx *ctx = cls;
711   struct ATS_Address *current = value;
712   struct AddressWrapper *asi = current->solver_information;
713   struct GNUNET_TIME_Relative active_time;
714   double best_delay;
715   double best_distance;
716   double cur_delay;
717   double cur_distance;
718   int index;
719   unsigned int con;
720   int bw_available;
721   int need;
722
723   /* we need +1 slot if 'current' is not yet active */
724   need = (GNUNET_YES == current->active) ? 0 : 1;
725   /* we save -1 slot if 'best' is active and belongs
726      to the same network (as we would replace it) */
727   if ( (NULL != ctx->best) &&
728        (GNUNET_YES == ctx->best->active) &&
729        (((struct AddressWrapper *) ctx->best->solver_information)->network ==
730         asi->network) )
731     need--;
732   /* we can gain -1 slot if this peers connectivity
733      requirement is higher than that of another peer
734      in that network scope */
735   con = ctx->s->env->get_connectivity (ctx->s->env->cls,
736                                        key);
737   if (GNUNET_YES !=
738       all_require_connectivity (ctx->s,
739                                 asi->network,
740                                 con))
741     need--;
742   /* test if minimum bandwidth for 'current' would be available */
743   bw_available
744     = is_bandwidth_available_in_network (asi->network,
745                                          need);
746   if (! bw_available)
747   {
748     /* Bandwidth for this address is unavailable, so we cannot use
749        it. */
750     return GNUNET_OK;
751   }
752   if (GNUNET_YES == current->active)
753   {
754     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
755     if (active_time.rel_value_us <=
756         ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) * ctx->s->stability_factor)
757     {
758       /* Keep active address for stability reasons */
759       ctx->best = current;
760       return GNUNET_NO;
761     }
762   }
763   if (NULL == ctx->best)
764   {
765     /* We so far have nothing else, so go with it! */
766     ctx->best = current;
767     return GNUNET_OK;
768   }
769
770   /* Now compare ATS information */
771   index = find_quality_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
772   cur_distance = current->atsin[index].norm;
773   best_distance = ctx->best->atsin[index].norm;
774   index = find_quality_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
775   cur_delay = current->atsin[index].norm;
776   best_delay = ctx->best->atsin[index].norm;
777
778   /* user shorter distance */
779   if (cur_distance < best_distance)
780   {
781     if (GNUNET_NO == ctx->best->active)
782     {
783       /* Activity doesn't influence the equation, use current */
784       ctx->best = current;
785     }
786     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
787     {
788       /* Distance change is significant, switch active address! */
789       ctx->best = current;
790     }
791   }
792
793   /* User connection with less delay */
794   if (cur_delay < best_delay)
795   {
796     if (GNUNET_NO == ctx->best->active)
797     {
798       /* Activity doesn't influence the equation, use current */
799       ctx->best = current;
800     }
801     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
802     {
803       /* Latency change is significant, switch active address! */
804       ctx->best = current;
805     }
806   }
807   return GNUNET_OK;
808 }
809
810
811 /**
812  * Find the currently best address for a peer from the set of
813  * addresses available or return NULL of no address is available.
814  *
815  * @param s the proportional handle
816  * @param addresses the address hashmap
817  * @param id the peer id
818  * @return the address or NULL
819  */
820 struct ATS_Address *
821 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
822                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
823                   const struct GNUNET_PeerIdentity *id)
824 {
825   struct FindBestAddressCtx fba_ctx;
826
827   fba_ctx.best = NULL;
828   fba_ctx.s = s;
829   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
830                                               id,
831                                               &find_best_address_it,
832                                               &fba_ctx);
833   return fba_ctx.best;
834 }
835
836
837 /**
838  * Decrease number of active addresses in network.
839  *
840  * @param s the solver handle
841  * @param net the network type
842  */
843 static void
844 address_decrement_active (struct GAS_PROPORTIONAL_Handle *s,
845                           struct Network *net)
846 {
847   GNUNET_assert (net->active_addresses > 0);
848   net->active_addresses--;
849   GNUNET_STATISTICS_update (s->env->stats,
850                             net->stat_active,
851                             -1,
852                             GNUNET_NO);
853   GNUNET_assert (s->active_addresses > 0);
854   s->active_addresses--;
855   GNUNET_STATISTICS_update (s->env->stats,
856                             "# ATS addresses total",
857                             -1,
858                             GNUNET_NO);
859 }
860
861
862 /**
863  * Address map iterator to find current active address for peer.
864  * Asserts that only one address is active per peer.
865  *
866  * @param cls last active address
867  * @param key peer's key
868  * @param value address to check
869  * @return #GNUNET_NO on double active address else #GNUNET_YES;
870  */
871 static int
872 get_active_address_it (void *cls,
873                        const struct GNUNET_PeerIdentity *key,
874                        void *value)
875 {
876   struct ATS_Address **dest = cls;
877   struct ATS_Address *aa = value;
878
879   if (GNUNET_YES != aa->active)
880     return GNUNET_OK;
881   GNUNET_assert (NULL == (*dest));
882   (*dest) = aa;
883   return GNUNET_OK;
884 }
885
886
887 /**
888  * Find current active address for peer
889  *
890  * @param s the solver handle
891  * @param peer the peer
892  * @return active address or NULL
893  */
894 static struct ATS_Address *
895 get_active_address (struct GAS_PROPORTIONAL_Handle *s,
896                     const struct GNUNET_PeerIdentity *peer)
897 {
898   struct ATS_Address *dest;
899
900   dest = NULL;
901   GNUNET_CONTAINER_multipeermap_get_multiple (s->env->addresses,
902                                               peer,
903                                               &get_active_address_it,
904                                               &dest);
905   return dest;
906 }
907
908
909 /**
910  * Update active address for a peer.  Check if active address exists
911  * and what the best address is, if addresses are different switch.
912  * Then reallocate bandwidth within the affected network scopes.
913  *
914  * @param s solver handle
915  * @param current_address the address currently active for the peer,
916  *        NULL for none
917  * @param peer the peer to check
918  */
919 static void
920 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
921                        struct ATS_Address *current_address,
922                        const struct GNUNET_PeerIdentity *peer)
923 {
924   struct ATS_Address *best_address;
925   struct AddressWrapper *asi_cur;
926   struct AddressWrapper *asi_best;
927   struct AddressWrapper *aw;
928   struct AddressWrapper *aw_min;
929   unsigned int a_con;
930   unsigned int con_min;
931
932   best_address = get_best_address (s,
933                                    s->env->addresses,
934                                    peer);
935   if (NULL != best_address)
936     asi_best = best_address->solver_information;
937   else
938     asi_best = NULL;
939   if (current_address == best_address)
940     return; /* no changes */
941   if (NULL != current_address)
942   {
943     /* We switch to a new address (or to none);
944        mark old address as inactive. */
945     asi_cur = current_address->solver_information;
946     GNUNET_assert (GNUNET_YES == current_address->active);
947     LOG (GNUNET_ERROR_TYPE_INFO,
948          "Disabling previous active address for peer `%s'\n",
949          GNUNET_i2s (peer));
950     asi_cur->activated = GNUNET_TIME_UNIT_ZERO_ABS;
951     current_address->active = GNUNET_NO;
952     current_address->assigned_bw_in = 0;
953     current_address->assigned_bw_out = 0;
954     address_decrement_active (s,
955                               asi_cur->network);
956     if ( (NULL == best_address) ||
957          (asi_best->network != asi_cur->network) )
958       distribute_bandwidth_in_network (s,
959                                        asi_cur->network);
960     if (NULL == best_address)
961     {
962       /* We previously had an active address, but now we cannot
963        * suggest one.  Therefore we have to disconnect the peer.
964        * The above call to "distribute_bandwidth_in_network()
965        * does not see 'current_address' so we need to trigger
966        * the update here. */
967       LOG (GNUNET_ERROR_TYPE_DEBUG,
968            "Disconnecting peer `%s'.\n",
969            GNUNET_i2s (peer));
970       s->env->bandwidth_changed_cb (s->env->cls,
971                                     current_address);
972       return;
973     }
974   }
975   if (NULL == best_address)
976   {
977     /* We do not have a new address, so we are done. */
978     LOG (GNUNET_ERROR_TYPE_DEBUG,
979          "Cannot suggest address for peer `%s'\n",
980          GNUNET_i2s (peer));
981     return;
982   }
983   /* We do have a new address, activate it */
984   LOG (GNUNET_ERROR_TYPE_DEBUG,
985        "Suggesting new address %p for peer `%s'\n",
986        best_address,
987        GNUNET_i2s (peer));
988   /* Mark address as active */
989   best_address->active = GNUNET_YES;
990   asi_best->activated = GNUNET_TIME_absolute_get ();
991   asi_best->network->active_addresses++;
992   s->active_addresses++;
993   GNUNET_STATISTICS_update (s->env->stats,
994                             "# ATS active addresses total",
995                             1,
996                             GNUNET_NO);
997   GNUNET_STATISTICS_update (s->env->stats,
998                             asi_best->network->stat_active,
999                             1,
1000                             GNUNET_NO);
1001   LOG (GNUNET_ERROR_TYPE_INFO,
1002        "Address %p for peer `%s' is now active\n",
1003        best_address,
1004        GNUNET_i2s (peer));
1005
1006
1007   if (GNUNET_NO ==
1008       is_bandwidth_available_in_network (asi_best->network,
1009                                          0))
1010   {
1011     /* we went over the maximum number of addresses for
1012        this scope; remove the address with the smallest
1013        connectivity requirement */
1014     con_min = UINT32_MAX;
1015     aw_min = NULL;
1016     for (aw = asi_best->network->head; NULL != aw; aw = aw->next)
1017     {
1018       if (con_min >
1019           (a_con = s->env->get_connectivity (s->env->cls,
1020                                              &aw->addr->peer)))
1021       {
1022         aw_min = aw;
1023         con_min = a_con;
1024         if (0 == con_min)
1025           break;
1026       }
1027     }
1028     update_active_address (s,
1029                            aw_min->addr,
1030                            &aw->addr->peer);
1031   }
1032   distribute_bandwidth_in_network (s,
1033                                    asi_best->network);
1034 }
1035
1036
1037 /**
1038  * The preferences for a peer in the problem changed.
1039  *
1040  * @param solver the solver handle
1041  * @param peer the peer to change the preference for
1042  * @param kind the kind to change the preference
1043  * @param pref_rel the normalized preference value for this kind over all clients
1044  */
1045 static void
1046 GAS_proportional_change_preference (void *solver,
1047                                     const struct GNUNET_PeerIdentity *peer,
1048                                     enum GNUNET_ATS_PreferenceKind kind,
1049                                     double pref_rel)
1050 {
1051   struct GAS_PROPORTIONAL_Handle *s = solver;
1052
1053   distribute_bandwidth_in_network (s,
1054                                    NULL);
1055 }
1056
1057
1058 /**
1059  * Get application feedback for a peer
1060  *
1061  * @param solver the solver handle
1062  * @param application the application
1063  * @param peer the peer to change the preference for
1064  * @param scope the time interval for this feedback: [now - scope .. now]
1065  * @param kind the kind to change the preference
1066  * @param score the score
1067  */
1068 static void
1069 GAS_proportional_feedback (void *solver,
1070                            struct GNUNET_SERVER_Client *application,
1071                            const struct GNUNET_PeerIdentity *peer,
1072                            const struct GNUNET_TIME_Relative scope,
1073                            enum GNUNET_ATS_PreferenceKind kind,
1074                            double score)
1075 {
1076   /* Proportional does not care about feedback */
1077 }
1078
1079
1080 /**
1081  * Get the preferred address for a specific peer
1082  *
1083  * @param solver the solver handle
1084  * @param peer the identity of the peer
1085  */
1086 static void
1087 GAS_proportional_start_get_address (void *solver,
1088                                     const struct GNUNET_PeerIdentity *peer)
1089 {
1090   struct GAS_PROPORTIONAL_Handle *s = solver;
1091
1092   update_active_address (s,
1093                          get_active_address (s,
1094                                              peer),
1095                          peer);
1096 }
1097
1098
1099 /**
1100  * Stop notifying about address and bandwidth changes for this peer
1101  *
1102  * @param solver the solver handle
1103  * @param peer the peer
1104  */
1105 static void
1106 GAS_proportional_stop_get_address (void *solver,
1107                                    const struct GNUNET_PeerIdentity *peer)
1108 {
1109   struct GAS_PROPORTIONAL_Handle *s = solver;
1110   struct ATS_Address *cur;
1111   struct AddressWrapper *asi;
1112
1113   cur = get_active_address (s,
1114                             peer);
1115   if (NULL == cur)
1116     return;
1117   asi = cur->solver_information;
1118   distribute_bandwidth_in_network (s,
1119                                    asi->network);
1120 }
1121
1122
1123 /**
1124  * Start a bulk operation
1125  *
1126  * @param solver the solver
1127  */
1128 static void
1129 GAS_proportional_bulk_start (void *solver)
1130 {
1131   struct GAS_PROPORTIONAL_Handle *s = solver;
1132
1133   LOG (GNUNET_ERROR_TYPE_DEBUG,
1134        "Locking solver for bulk operation ...\n");
1135   GNUNET_assert (NULL != solver);
1136   s->bulk_lock++;
1137 }
1138
1139
1140 /**
1141  * Bulk operation done.
1142  *
1143  * @param solver our `struct GAS_PROPORTIONAL_Handle *`
1144  */
1145 static void
1146 GAS_proportional_bulk_stop (void *solver)
1147 {
1148   struct GAS_PROPORTIONAL_Handle *s = solver;
1149
1150   LOG (GNUNET_ERROR_TYPE_DEBUG,
1151        "Unlocking solver from bulk operation ...\n");
1152   if (s->bulk_lock < 1)
1153   {
1154     GNUNET_break(0);
1155     return;
1156   }
1157   s->bulk_lock--;
1158   if ( (0 == s->bulk_lock) &&
1159        (0 < s->bulk_requests) )
1160   {
1161     LOG (GNUNET_ERROR_TYPE_INFO,
1162          "No lock pending, recalculating\n");
1163     distribute_bandwidth_in_network (s,
1164                                      NULL);
1165     s->bulk_requests = 0;
1166   }
1167 }
1168
1169
1170 /**
1171  * Transport properties for this address have changed
1172  *
1173  * @param solver solver handle
1174  * @param address the address
1175  * @param type the ATSI type in HBO
1176  * @param abs_value the absolute value of the property
1177  * @param rel_value the normalized value
1178  */
1179 static void
1180 GAS_proportional_address_property_changed (void *solver,
1181                                            struct ATS_Address *address,
1182                                            enum GNUNET_ATS_Property type,
1183                                            uint32_t abs_value,
1184                                            double rel_value)
1185 {
1186   struct GAS_PROPORTIONAL_Handle *s = solver;
1187   struct AddressWrapper *asi = address->solver_information;
1188
1189   distribute_bandwidth_in_network (s,
1190                                    asi->network);
1191 }
1192
1193
1194 /**
1195  * Add a new single address to a network
1196  *
1197  * @param solver the solver Handle
1198  * @param address the address to add
1199  * @param network network type of this address
1200  */
1201 static void
1202 GAS_proportional_address_add (void *solver,
1203                               struct ATS_Address *address,
1204                               enum GNUNET_ATS_Network_Type network)
1205 {
1206   struct GAS_PROPORTIONAL_Handle *s = solver;
1207   struct Network *net;
1208   struct AddressWrapper *aw;
1209
1210   GNUNET_assert (network < s->env->network_count);
1211   net = &s->network_entries[network];
1212   net->total_addresses++;
1213
1214   aw = GNUNET_new (struct AddressWrapper);
1215   aw->addr = address;
1216   aw->network = net;
1217   address->solver_information = aw;
1218   GNUNET_CONTAINER_DLL_insert (net->head,
1219                                net->tail,
1220                                aw);
1221   GNUNET_STATISTICS_update (s->env->stats,
1222                             "# ATS addresses total",
1223                             1,
1224                             GNUNET_NO);
1225   GNUNET_STATISTICS_update (s->env->stats,
1226                             net->stat_total,
1227                             1,
1228                             GNUNET_NO);
1229   if (0 !=
1230       s->env->get_connectivity (s->env->cls,
1231                                 &address->peer))
1232   {
1233     /* This peer is requested, find best address */
1234     update_active_address (s,
1235                            get_active_address (s,
1236                                                &address->peer),
1237                            &address->peer);
1238   }
1239   LOG (GNUNET_ERROR_TYPE_INFO,
1240        "Added new address for `%s', now total %u and active %u addresses in network `%s'\n",
1241        GNUNET_i2s (&address->peer),
1242        net->total_addresses,
1243        net->active_addresses,
1244        net->desc);
1245 }
1246
1247
1248 /**
1249  * Remove an address from the solver. To do so, we:
1250  * - Removed it from specific network
1251  * - Decrease the number of total addresses
1252  * - If active:
1253  *   - decrease number of active addreses
1254  *   - update quotas
1255  *
1256  * @param solver the solver handle
1257  * @param address the address to remove
1258  */
1259 static void
1260 GAS_proportional_address_delete (void *solver,
1261                                  struct ATS_Address *address)
1262 {
1263   struct GAS_PROPORTIONAL_Handle *s = solver;
1264   struct AddressWrapper *aw = address->solver_information;
1265   struct Network *net = aw->network;
1266
1267   LOG (GNUNET_ERROR_TYPE_DEBUG,
1268        "Deleting %s address for peer `%s' from network `%s' (total: %u/active: %u)\n",
1269        (GNUNET_NO == address->active) ? "inactive" : "active",
1270        GNUNET_i2s (&address->peer),
1271        net->desc,
1272        net->total_addresses,
1273        net->active_addresses);
1274
1275   GNUNET_CONTAINER_DLL_remove (net->head,
1276                                net->tail,
1277                                aw);
1278   GNUNET_assert (net->total_addresses > 0);
1279   net->total_addresses--;
1280   GNUNET_STATISTICS_update (s->env->stats,
1281                             net->stat_total,
1282                             -1,
1283                             GNUNET_NO);
1284   if (GNUNET_YES == address->active)
1285   {
1286     /* Address was active, remove from network and update quotas */
1287     update_active_address (s,
1288                            address,
1289                            &address->peer);
1290     distribute_bandwidth_in_network (s, net);
1291   }
1292   GNUNET_free (aw);
1293   address->solver_information = NULL;
1294   LOG (GNUNET_ERROR_TYPE_DEBUG,
1295        "After deleting address now total %u and active %u addresses in network `%s'\n",
1296        net->total_addresses,
1297        net->active_addresses,
1298        net->desc);
1299 }
1300
1301
1302 /**
1303  * Function invoked when the plugin is loaded.
1304  *
1305  * @param[in,out] cls the `struct GNUNET_ATS_PluginEnvironment *` to use;
1306  *            modified to return the API functions (ugh).
1307  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1308  */
1309 void *
1310 libgnunet_plugin_ats_proportional_init (void *cls)
1311 {
1312   static struct GNUNET_ATS_SolverFunctions sf;
1313   struct GNUNET_ATS_PluginEnvironment *env = cls;
1314   struct GAS_PROPORTIONAL_Handle *s;
1315   struct Network * cur;
1316   float f_tmp;
1317   unsigned int c;
1318
1319   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1320   s->env = env;
1321   sf.cls = s;
1322   sf.s_add = &GAS_proportional_address_add;
1323   sf.s_address_update_property = &GAS_proportional_address_property_changed;
1324   sf.s_get = &GAS_proportional_start_get_address;
1325   sf.s_get_stop = &GAS_proportional_stop_get_address;
1326   sf.s_pref = &GAS_proportional_change_preference;
1327   sf.s_feedback = &GAS_proportional_feedback;
1328   sf.s_del = &GAS_proportional_address_delete;
1329   sf.s_bulk_start = &GAS_proportional_bulk_start;
1330   sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1331   s->stability_factor = PROP_STABILITY_FACTOR;
1332   if (GNUNET_SYSERR !=
1333       GNUNET_CONFIGURATION_get_value_float (env->cfg,
1334                                             "ats",
1335                                             "PROP_STABILITY_FACTOR",
1336                                             &f_tmp))
1337   {
1338     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1339     {
1340       LOG (GNUNET_ERROR_TYPE_ERROR,
1341            _("Invalid %s configuration %f \n"),
1342            "PROP_STABILITY_FACTOR",
1343            f_tmp);
1344     }
1345     else
1346     {
1347       s->stability_factor = f_tmp;
1348       LOG (GNUNET_ERROR_TYPE_INFO,
1349            "Using %s of %.3f\n",
1350            "PROP_STABILITY_FACTOR",
1351            f_tmp);
1352     }
1353   }
1354   s->prop_factor = PROPORTIONALITY_FACTOR;
1355   if (GNUNET_SYSERR !=
1356       GNUNET_CONFIGURATION_get_value_float (env->cfg,
1357                                             "ats",
1358                                             "PROP_PROPORTIONALITY_FACTOR",
1359                                             &f_tmp))
1360   {
1361     if (f_tmp < 1.0)
1362     {
1363       LOG (GNUNET_ERROR_TYPE_ERROR,
1364            _("Invalid %s configuration %f\n"),
1365            "PROP_PROPORTIONALITY_FACTOR",
1366            f_tmp);
1367     }
1368     else
1369     {
1370       s->prop_factor = f_tmp;
1371       LOG (GNUNET_ERROR_TYPE_INFO,
1372            "Using %s of %.3f\n",
1373            "PROP_PROPORTIONALITY_FACTOR",
1374            f_tmp);
1375     }
1376   }
1377
1378   s->network_entries = GNUNET_malloc (env->network_count *
1379                                       sizeof (struct Network));
1380   for (c = 0; c < env->network_count; c++)
1381   {
1382     cur = &s->network_entries[c];
1383     cur->type = c;
1384     cur->total_quota_in = env->in_quota[c];
1385     cur->total_quota_out = env->out_quota[c];
1386     cur->desc = GNUNET_ATS_print_network_type (c);
1387     GNUNET_asprintf (&cur->stat_total,
1388                      "# ATS addresses %s total",
1389                      cur->desc);
1390     GNUNET_asprintf (&cur->stat_active,
1391                      "# ATS active addresses %s total",
1392                      cur->desc);
1393     LOG (GNUNET_ERROR_TYPE_INFO,
1394          "Added network %u `%s' (%llu/%llu)\n",
1395          c,
1396          cur->desc,
1397          cur->total_quota_in,
1398          cur->total_quota_out);
1399   }
1400   return &sf;
1401 }
1402
1403
1404 /**
1405  * Function used to unload the plugin.
1406  *
1407  * @param cls return value from #libgnunet_plugin_ats_proportional_init()
1408  */
1409 void *
1410 libgnunet_plugin_ats_proportional_done (void *cls)
1411 {
1412   struct GNUNET_ATS_SolverFunctions *sf = cls;
1413   struct GAS_PROPORTIONAL_Handle *s = sf->cls;
1414   struct AddressWrapper *cur;
1415   struct AddressWrapper *next;
1416   unsigned int c;
1417
1418   for (c = 0; c < s->network_count; c++)
1419   {
1420     GNUNET_break (0 == s->network_entries[c].total_addresses);
1421     GNUNET_break (0 == s->network_entries[c].active_addresses);
1422     next = s->network_entries[c].head;
1423     while (NULL != (cur = next))
1424     {
1425       next = cur->next;
1426       GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head,
1427                                    s->network_entries[c].tail,
1428                                    cur);
1429       GNUNET_free_non_null (cur->addr->solver_information);
1430       GNUNET_free(cur);
1431     }
1432     GNUNET_free (s->network_entries[c].stat_total);
1433     GNUNET_free (s->network_entries[c].stat_active);
1434   }
1435   GNUNET_break (0 == s->active_addresses);
1436   GNUNET_free (s->network_entries);
1437   GNUNET_free (s);
1438   return NULL;
1439 }
1440
1441
1442 /* end of plugin_ats_proportional.c */