fix #4545: create directory for log file if it does not exist
[oweals/gnunet.git] / src / util / bandwidth.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2010, 2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/bandwidth.c
23  * @brief functions related to bandwidth (unit)
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "util-bandwidth", __VA_ARGS__)
31
32 /**
33  * Create a new bandwidth value.
34  *
35  * @param bytes_per_second value to create
36  * @return the new bandwidth value
37  */
38 struct GNUNET_BANDWIDTH_Value32NBO
39 GNUNET_BANDWIDTH_value_init (uint32_t bytes_per_second)
40 {
41   struct GNUNET_BANDWIDTH_Value32NBO ret;
42
43   LOG (GNUNET_ERROR_TYPE_DEBUG,
44        "Initializing bandwidth of %u Bps\n",
45        (unsigned int) bytes_per_second);
46   ret.value__ = htonl (bytes_per_second);
47   return ret;
48 }
49
50
51 /**
52  * Compute the MIN of two bandwidth values.
53  *
54  * @param b1 first value
55  * @param b2 second value
56  * @return the min of b1 and b2
57  */
58 struct GNUNET_BANDWIDTH_Value32NBO
59 GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1,
60                             struct GNUNET_BANDWIDTH_Value32NBO b2)
61 {
62   return
63       GNUNET_BANDWIDTH_value_init (GNUNET_MIN
64                                    (ntohl (b1.value__),
65                                     ntohl (b2.value__)));
66 }
67
68
69 /**
70  * Compute the MAX of two bandwidth values.
71  *
72  * @param b1 first value
73  * @param b2 second value
74  * @return the min of b1 and b2
75  */
76 struct GNUNET_BANDWIDTH_Value32NBO
77 GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1,
78                             struct GNUNET_BANDWIDTH_Value32NBO b2)
79 {
80   return
81       GNUNET_BANDWIDTH_value_init (GNUNET_MAX
82                                    (ntohl (b1.value__),
83                                     ntohl (b2.value__)));
84 }
85
86
87 /**
88  * At the given bandwidth, calculate how much traffic will be
89  * available until the given deadline.
90  *
91  * @param bps bandwidth
92  * @param deadline when is the deadline
93  * @return number of bytes available at bps until deadline
94  */
95 uint64_t
96 GNUNET_BANDWIDTH_value_get_available_until (struct GNUNET_BANDWIDTH_Value32NBO bps,
97                                             struct GNUNET_TIME_Relative deadline)
98 {
99   uint64_t b;
100
101   b = ntohl (bps.value__);
102   LOG (GNUNET_ERROR_TYPE_DEBUG,
103        "Bandwidth has %llu bytes available until deadline in %s\n",
104        (unsigned long long) ((b * deadline.rel_value_us + 500000LL) / 1000000LL),
105        GNUNET_STRINGS_relative_time_to_string (deadline, GNUNET_YES));
106   return (b * deadline.rel_value_us + 500000LL) / 1000000LL;
107 }
108
109
110 /**
111  * At the given bandwidth, calculate how long it would take for
112  * @a size bytes to be transmitted.
113  *
114  * @param bps bandwidth
115  * @param size number of bytes we want to have available
116  * @return how long it would take
117  */
118 struct GNUNET_TIME_Relative
119 GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps,
120                                       uint64_t size)
121 {
122   uint64_t b;
123   struct GNUNET_TIME_Relative ret;
124
125   b = ntohl (bps.value__);
126   if (0 == b)
127   {
128     LOG (GNUNET_ERROR_TYPE_DEBUG,
129          "Bandwidth suggests delay of infinity (zero bandwidth)\n");
130     return GNUNET_TIME_UNIT_FOREVER_REL;
131   }
132   ret.rel_value_us = size * 1000LL * 1000LL / b;
133   LOG (GNUNET_ERROR_TYPE_DEBUG,
134        "Bandwidth suggests delay of %s for %llu bytes of traffic\n",
135        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES),
136        (unsigned long long) size);
137   return ret;
138 }
139
140
141 /**
142  * Task run whenever we hit the bandwidth limit for a tracker.
143  *
144  * @param cls the `struct GNUNET_BANDWIDTH_Tracker`
145  */
146 static void
147 excess_trigger (void *cls)
148 {
149   struct GNUNET_BANDWIDTH_Tracker *av = cls;
150
151   av->excess_task = NULL;
152   if (NULL != av->excess_cb)
153     av->excess_cb (av->excess_cb_cls);
154 }
155
156
157 /**
158  * Recalculate when we might need to call the excess callback.
159  */
160 static void
161 update_excess (struct GNUNET_BANDWIDTH_Tracker *av)
162 {
163   struct GNUNET_TIME_Relative delay;
164   struct GNUNET_TIME_Absolute now;
165   uint64_t delta_time;
166   uint64_t delta_avail;
167   int64_t left_bytes;
168   uint64_t max_carry;
169   int64_t current_consumption;
170
171   if (NULL == av->excess_cb)
172     return; /* nothing to do */
173   now = GNUNET_TIME_absolute_get ();
174   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
175   delta_avail =
176       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
177        500000LL) / 1000000LL;
178   current_consumption = av->consumption_since_last_update__ - delta_avail;
179   /* negative current_consumption means that we have savings */
180   max_carry = av->available_bytes_per_s__ * av->max_carry_s__;
181   if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
182     max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
183   left_bytes = max_carry + current_consumption;
184   /* left_bytes now contains the number of bytes needed until
185      we have more savings than allowed */
186   if (left_bytes < 0)
187   {
188     /* having excess already */
189     delay = GNUNET_TIME_UNIT_ZERO;
190   }
191   else
192   {
193     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
194                                            left_bytes);
195     delay = GNUNET_TIME_relative_divide (delay,
196                                          av->available_bytes_per_s__);
197   }
198   if (NULL != av->excess_task)
199     GNUNET_SCHEDULER_cancel (av->excess_task);
200   av->excess_task = GNUNET_SCHEDULER_add_delayed (delay,
201                                                   &excess_trigger,
202                                                   av);
203 }
204
205
206 /**
207  * Initialize bandwidth tracker.  Note that in addition to the
208  * 'max_carry_s' limit, we also always allow at least
209  * #GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
210  * bytes-per-second limit is so small that within 'max_carry_s' not
211  * even #GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
212  * ignored and replaced by #GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
213  * bytes).
214  *
215  * To stop notifications about updates and excess callbacks use
216  * #GNUNET_BANDWIDTH_tracker_notification_stop().
217  *
218  * @param av tracker to initialize
219  * @param update_cb callback to notify a client about the tracker being updated
220  * @param update_cb_cls cls for the callback
221  * @param bytes_per_second_limit initial limit to assume
222  * @param max_carry_s maximum number of seconds unused bandwidth
223  *        may accumulate before it expires
224  * @param excess_cb callback to notify if we have excess bandwidth
225  * @param excess_cb_cls closure for @a excess_cb
226  */
227 void
228 GNUNET_BANDWIDTH_tracker_init2 (struct GNUNET_BANDWIDTH_Tracker *av,
229                                 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
230                                 void *update_cb_cls,
231                                 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
232                                 uint32_t max_carry_s,
233                                 GNUNET_BANDWIDTH_ExcessNotificationCallback excess_cb,
234                                 void *excess_cb_cls)
235 {
236   av->update_cb = update_cb;
237   av->update_cb_cls = update_cb_cls;
238   av->consumption_since_last_update__ = 0;
239   av->last_update__ = GNUNET_TIME_absolute_get ();
240   av->available_bytes_per_s__ = ntohl (bytes_per_second_limit.value__);
241   av->max_carry_s__ = max_carry_s;
242   av->excess_cb = excess_cb;
243   av->excess_cb_cls = excess_cb_cls;
244   LOG (GNUNET_ERROR_TYPE_DEBUG,
245        "Tracker %p initialized with %u Bps and max carry %u\n",
246        av,
247        (unsigned int) av->available_bytes_per_s__,
248        (unsigned int) max_carry_s);
249   update_excess (av);
250 }
251
252
253 /**
254  * Initialize bandwidth tracker.  Note that in addition to the
255  * 'max_carry_s' limit, we also always allow at least
256  * GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
257  * bytes-per-second limit is so small that within 'max_carry_s' not
258  * even GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
259  * ignored and replaced by GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
260  * bytes).
261  *
262  * @param av tracker to initialize
263  * @param update_cb callback to notify a client about the tracker being updated
264  * @param update_cb_cls cls for the callback
265  * @param bytes_per_second_limit initial limit to assume
266  * @param max_carry_s maximum number of seconds unused bandwidth
267  *        may accumulate before it expires
268  */
269 void
270 GNUNET_BANDWIDTH_tracker_init (struct GNUNET_BANDWIDTH_Tracker *av,
271                                GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
272                                void *update_cb_cls,
273                                struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
274                                uint32_t max_carry_s)
275 {
276   GNUNET_BANDWIDTH_tracker_init2 (av, update_cb,
277                                   update_cb_cls,
278                                   bytes_per_second_limit,
279                                   max_carry_s,
280                                   NULL, NULL);
281 }
282
283
284 /**
285  * Stop notifying about tracker updates and excess notifications
286  *
287  * @param av the respective trackers
288  */
289 void
290 GNUNET_BANDWIDTH_tracker_notification_stop (struct GNUNET_BANDWIDTH_Tracker *av)
291 {
292   if (NULL != av->excess_task)
293     GNUNET_SCHEDULER_cancel (av->excess_task);
294   av->excess_task = NULL;
295   av->excess_cb = NULL;
296   av->excess_cb_cls = NULL;
297   av->update_cb = NULL;
298   av->update_cb_cls = NULL;
299 }
300
301
302
303 /**
304  * Update the tracker, looking at the current time and
305  * bandwidth consumption data.
306  *
307  * @param av tracker to update
308  */
309 static void
310 update_tracker (struct GNUNET_BANDWIDTH_Tracker *av)
311 {
312   struct GNUNET_TIME_Absolute now;
313   struct GNUNET_TIME_Relative delta;
314   uint64_t delta_time;
315   uint64_t delta_avail;
316   uint64_t left_bytes;
317   uint64_t max_carry;
318
319   now = GNUNET_TIME_absolute_get ();
320   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
321   delta_avail =
322       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
323        500000LL) / 1000000LL;
324   av->consumption_since_last_update__ -= delta_avail;
325   av->last_update__ = now;
326   if (av->consumption_since_last_update__ < 0)
327   {
328     left_bytes = -av->consumption_since_last_update__;
329     max_carry = av->available_bytes_per_s__ * av->max_carry_s__;
330     if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
331       max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
332     if (max_carry > left_bytes)
333       av->consumption_since_last_update__ = -left_bytes;
334     else
335       av->consumption_since_last_update__ = -max_carry;
336   }
337   delta.rel_value_us = delta_time;
338   LOG (GNUNET_ERROR_TYPE_DEBUG,
339        "Tracker %p updated, have %u Bps, last update was %s ago\n", av,
340        (unsigned int) av->available_bytes_per_s__,
341        GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES));
342 }
343
344
345 /**
346  * Notify the tracker that a certain number of bytes of bandwidth have
347  * been consumed.  Note that it is legal to consume bytes even if not
348  * enough bandwidth is available (in that case,
349  * #GNUNET_BANDWIDTH_tracker_get_delay may return non-zero delay values
350  * even for a size of zero for a while).
351  *
352  * @param av tracker to update
353  * @param size number of bytes consumed
354  * @return #GNUNET_YES if this consumption is above the limit
355  */
356 int
357 GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av,
358                                   ssize_t size)
359 {
360   int64_t nc;
361
362   LOG (GNUNET_ERROR_TYPE_DEBUG,
363        "Tracker %p consumes %d bytes\n",
364        av,
365        (int) size);
366   if (size > 0)
367   {
368     nc = av->consumption_since_last_update__ + size;
369     if (nc < av->consumption_since_last_update__)
370     {
371       GNUNET_break (0);
372       return GNUNET_SYSERR;
373     }
374     av->consumption_since_last_update__ = nc;
375     update_tracker (av);
376     update_excess (av);
377     if (av->consumption_since_last_update__ > 0)
378     {
379       LOG (GNUNET_ERROR_TYPE_DEBUG,
380            "Tracker %p consumption %llu bytes above limit\n", av,
381            (unsigned long long) av->consumption_since_last_update__);
382       return GNUNET_YES;
383     }
384   }
385   else
386   {
387     av->consumption_since_last_update__ += size;
388     update_excess (av);
389   }
390   return GNUNET_NO;
391 }
392
393
394 /**
395  * Compute how long we should wait until consuming 'size'
396  * bytes of bandwidth in order to stay within the given
397  * quota.
398  *
399  * @param av tracker to query
400  * @param size number of bytes we would like to consume
401  * @return time in ms to wait for consumption to be OK
402  */
403 struct GNUNET_TIME_Relative
404 GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av,
405                                     size_t size)
406 {
407   struct GNUNET_TIME_Relative ret;
408   int64_t bytes_needed;
409
410   if (0 == av->available_bytes_per_s__)
411   {
412     LOG (GNUNET_ERROR_TYPE_DEBUG,
413          "Tracker %p delay is infinity\n", av);
414     return GNUNET_TIME_UNIT_FOREVER_REL;
415   }
416   update_tracker (av);
417   bytes_needed = size + av->consumption_since_last_update__;
418   if (bytes_needed <= 0)
419   {
420     LOG (GNUNET_ERROR_TYPE_DEBUG,
421          "Tracker %p delay for %u bytes is zero\n", av,
422          (unsigned int) size);
423     return GNUNET_TIME_UNIT_ZERO;
424   }
425   ret.rel_value_us =
426       (1000LL * 1000LL * bytes_needed) /
427       (unsigned long long) av->available_bytes_per_s__;
428   LOG (GNUNET_ERROR_TYPE_DEBUG,
429        "Tracker %p delay for %u bytes is %s\n",
430        av, (unsigned int) size,
431        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
432   return ret;
433 }
434
435
436 /**
437  * Compute how many bytes are available for consumption right now.
438  * quota.
439  *
440  * @param av tracker to query
441  * @return number of bytes available for consumption right now
442  */
443 int64_t
444 GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av)
445 {
446   struct GNUNET_BANDWIDTH_Value32NBO bps;
447   uint64_t avail;
448   int64_t used;
449
450   update_tracker (av);
451   bps = GNUNET_BANDWIDTH_value_init (av->available_bytes_per_s__);
452   avail =
453       GNUNET_BANDWIDTH_value_get_available_until (bps,
454                                                   GNUNET_TIME_absolute_get_duration
455                                                   (av->last_update__));
456   used = av->consumption_since_last_update__;
457   LOG (GNUNET_ERROR_TYPE_DEBUG,
458        "Tracker %p available bandwidth is %lld bytes\n", av,
459        (long long) (int64_t) (avail - used));
460   return (int64_t) (avail - used);
461 }
462
463
464 /**
465  * Update quota of bandwidth tracker.
466  *
467  * @param av tracker to initialize
468  * @param bytes_per_second_limit new limit to assume
469  */
470 void
471 GNUNET_BANDWIDTH_tracker_update_quota (struct GNUNET_BANDWIDTH_Tracker *av,
472                                        struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit)
473 {
474   uint32_t old_limit;
475   uint32_t new_limit;
476
477   new_limit = ntohl (bytes_per_second_limit.value__);
478   LOG (GNUNET_ERROR_TYPE_DEBUG,
479        "Tracker %p bandwidth changed to %u Bps\n", av,
480        (unsigned int) new_limit);
481   update_tracker (av);
482   old_limit = av->available_bytes_per_s__;
483   av->available_bytes_per_s__ = new_limit;
484   if (NULL != av->update_cb)
485     av->update_cb (av->update_cb_cls);
486   if (old_limit > new_limit)
487     update_tracker (av);        /* maximum excess might be less now */
488   update_excess (av);
489 }
490
491
492 /* end of bandwidth.c */