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