| 1 | /// @file |
| 2 | /// @author rfree (current maintainer in monero.cc project) |
| 3 | /// @brief implementaion for throttling of connection (count and rate-limit speed etc) |
| 4 | |
| 5 | // Copyright (c) 2014-2022, The Monero Project |
| 6 | // |
| 7 | // All rights reserved. |
| 8 | // |
| 9 | // Redistribution and use in source and binary forms, with or without modification, are |
| 10 | // permitted provided that the following conditions are met: |
| 11 | // |
| 12 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 13 | // conditions and the following disclaimer. |
| 14 | // |
| 15 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 16 | // of conditions and the following disclaimer in the documentation and/or other |
| 17 | // materials provided with the distribution. |
| 18 | // |
| 19 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 20 | // used to endorse or promote products derived from this software without specific |
| 21 | // prior written permission. |
| 22 | // |
| 23 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 24 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 25 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 26 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 27 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 28 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 29 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 30 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 31 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 32 | |
| 33 | /* rfree: implementation for throttle details */ |
| 34 | |
| 35 | #include <string> |
| 36 | #include <vector> |
| 37 | #include <atomic> |
| 38 | |
| 39 | #include <boost/asio.hpp> |
| 40 | |
| 41 | #include <memory> |
| 42 | |
| 43 | #include "syncobj.h" |
| 44 | |
| 45 | #include "net/net_utils_base.h" |
| 46 | #include "misc_log_ex.h" |
| 47 | #include <boost/chrono.hpp> |
| 48 | #include "misc_language.h" |
| 49 | #include <fstream> |
| 50 | #include <iomanip> |
| 51 | #include <algorithm> |
| 52 | |
| 53 | |
| 54 | |
| 55 | #include <boost/asio/basic_socket.hpp> |
| 56 | #include <boost/asio/ip/unicast.hpp> |
| 57 | #include "net/abstract_tcp_server2.h" |
| 58 | |
| 59 | // TODO: |
| 60 | #include "net/network_throttle-detail.hpp" |
| 61 | |
| 62 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 63 | #define MONERO_DEFAULT_LOG_CATEGORY "net.throttle" |
| 64 | |
| 65 | // ################################################################################################ |
| 66 | // ################################################################################################ |
| 67 | // the "header part". Not separeted out for .hpp because point of this modification is |
| 68 | // to rebuild just 1 translation unit while working on this code. |
| 69 | // (But maybe common parts will be separated out later though - if needed) |
| 70 | // ################################################################################################ |
| 71 | // ################################################################################################ |
| 72 | |
| 73 | namespace epee |
| 74 | { |
| 75 | namespace net_utils |
| 76 | { |
| 77 | |
| 78 | |
| 79 | /* ============================================================================ */ |
| 80 | |
| 81 | class connection_basic_pimpl { |
| 82 | public: |
| 83 | connection_basic_pimpl(const std::string &name); |
| 84 | |
| 85 | static int m_default_tos; |
| 86 | |
| 87 | network_throttle_bw m_throttle; // per-perr |
| 88 | critical_section m_throttle_lock; |
| 89 | |
| 90 | void _packet(size_t packet_size, int phase, int q_len); // execute a sleep ; phase is not really used now(?) could be used for different kinds of sleep e.g. direct/queue write |
| 91 | }; |
| 92 | |
| 93 | |
| 94 | } // namespace |
| 95 | } // namespace |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | // ################################################################################################ |
| 103 | // ################################################################################################ |
| 104 | // The implementation part |
| 105 | // ################################################################################################ |
| 106 | // ################################################################################################ |
| 107 | |
| 108 | namespace epee |
| 109 | { |
| 110 | namespace net_utils |
| 111 | { |
| 112 | |
| 113 | // ================================================================================================ |
| 114 | // network_throttle |
| 115 | // ================================================================================================ |
| 116 | |
| 117 | network_throttle::~network_throttle() { } |
| 118 | |
| 119 | network_throttle::packet_info::packet_info() |
| 120 | : m_size(0) |
| 121 | { |
| 122 | } |
| 123 | |
| 124 | network_throttle::network_throttle(const std::string &nameshort, const std::string &name, int window_size) |
| 125 | : m_window_size( (window_size==-1) ? 10 : window_size ), |
| 126 | m_history( m_window_size ), m_nameshort(nameshort) |
| 127 | { |
| 128 | set_name(name); |
| 129 | m_network_add_cost = 128; |
| 130 | m_network_minimal_segment = 256; |
| 131 | m_network_max_segment = 1024*1024; |
| 132 | m_start_time = 0; |
| 133 | m_any_packet_yet = false; |
| 134 | m_slot_size = 1.0; // hard coded in few places |
| 135 | m_target_speed = 16 * 1024; // other defaults are probably defined in the command-line parsing code when this class is used e.g. as main global throttle |
| 136 | m_last_sample_time = 0; |
| 137 | m_history.resize(m_window_size); |
| 138 | m_total_packets = 0; |
| 139 | m_total_bytes = 0; |
| 140 | } |
| 141 | |
| 142 | void network_throttle::set_name(const std::string &name) |
| 143 | { |
| 144 | m_name = name; |
| 145 | } |
| 146 | |
| 147 | void network_throttle::set_target_speed( network_speed_kbps target ) |
| 148 | { |
| 149 | m_target_speed = target * 1024; |
| 150 | MINFO("Setting LIMIT: " << target << " kbps"); |
| 151 | } |
| 152 | |
| 153 | network_speed_kbps network_throttle::get_target_speed() |
| 154 | { |
| 155 | return m_target_speed / 1024; |
| 156 | } |
| 157 | |
| 158 | void network_throttle::tick() |
| 159 | { |
| 160 | double time_now = get_time_seconds(); |
| 161 | if (!m_any_packet_yet) m_start_time = time_now; // starting now |
| 162 | |
| 163 | network_time_seconds current_sample_time_slot = time_to_slot( time_now ); // T=13.7 --> 13 (for 1-second smallwindow) |
| 164 | network_time_seconds last_sample_time_slot = time_to_slot( m_last_sample_time ); |
| 165 | |
| 166 | // moving to next position, and filling gaps |
| 167 | // !! during this loop the m_last_sample_time and last_sample_time_slot mean the variable moved in +1 |
| 168 | // TODO optimize when moving few slots at once |
| 169 | while ( (!m_any_packet_yet) || (last_sample_time_slot < current_sample_time_slot)) |
| 170 | { |
| 171 | _dbg3("Moving counter buffer by 1 second " << last_sample_time_slot << " < " << current_sample_time_slot << " (last time " << m_last_sample_time<<")"); |
| 172 | // rotate buffer |
| 173 | m_history.push_front(packet_info()); |
| 174 | if (! m_any_packet_yet) |
| 175 | { |
| 176 | m_last_sample_time = time_now; |
| 177 | } |
| 178 | m_last_sample_time += 1; last_sample_time_slot = time_to_slot( m_last_sample_time ); // increase and recalculate time, time slot |
| 179 | m_any_packet_yet=true; |
| 180 | } |
| 181 | m_last_sample_time = time_now; // the real exact last time |
| 182 | } |
| 183 | |
| 184 | void network_throttle::handle_trafic_exact(size_t packet_size) |
| 185 | { |
| 186 | _handle_trafic_exact(packet_size, packet_size); |
| 187 | } |
| 188 | |
| 189 | namespace |
| 190 | { |
| 191 | struct output_history |
| 192 | { |
| 193 | const boost::circular_buffer< network_throttle::packet_info >& history; |
| 194 | }; |
| 195 | |
| 196 | std::ostream& operator<<(std::ostream& out, const output_history& source) |
| 197 | { |
| 198 | out << '['; |
| 199 | for (auto sample: source.history) |
| 200 | out << sample.m_size << ' '; |
| 201 | out << ']'; |
| 202 | return out; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | void network_throttle::_handle_trafic_exact(size_t packet_size, size_t orginal_size) |
| 207 | { |
| 208 | tick(); |
| 209 | |
| 210 | calculate_times_struct cts ; calculate_times(packet_size, cts , false, -1); |
| 211 | calculate_times_struct cts2; calculate_times(packet_size, cts2, false, 5); |
| 212 | m_history.front().m_size += packet_size; |
| 213 | m_total_packets++; |
| 214 | m_total_bytes += packet_size; |
| 215 | |
| 216 | MTRACE("Throttle " << m_name << ": packet of ~"<<packet_size<<"b " << " (from "<<orginal_size<<" b)" |
| 217 | << " Speed AVG=" << std::setw(4) << ((long int)(cts .average/1024)) <<"[w="<<cts .window<<"]" |
| 218 | << " " << std::setw(4) << ((long int)(cts2.average/1024)) <<"[w="<<cts2.window<<"]" |
| 219 | <<" / " << " Limit="<< ((long int)(m_target_speed/1024)) <<" KiB/sec " |
| 220 | << " " << output_history{m_history} |
| 221 | ); |
| 222 | } |
| 223 | |
| 224 | void network_throttle::handle_trafic_tcp(size_t packet_size) |
| 225 | { |
| 226 | size_t all_size = packet_size + m_network_add_cost; |
| 227 | all_size = std::max( m_network_minimal_segment , all_size); |
| 228 | _handle_trafic_exact( all_size , packet_size ); |
| 229 | } |
| 230 | |
| 231 | network_time_seconds network_throttle::get_sleep_time_after_tick(size_t packet_size) { |
| 232 | tick(); |
| 233 | return get_sleep_time(packet_size); |
| 234 | } |
| 235 | |
| 236 | void network_throttle::logger_handle_net(const std::string &filename, double time, size_t size) { |
| 237 | static boost::mutex mutex; |
| 238 | |
| 239 | boost::lock_guard<boost::mutex> lock(mutex); |
| 240 | { |
| 241 | std::fstream file; |
| 242 | file.open(filename.c_str(), std::ios::app | std::ios::out ); |
| 243 | file.precision(6); |
| 244 | if(!file.is_open()) |
| 245 | _warn("Can't open file " << filename); |
| 246 | file << static_cast<int>(time) << " " << static_cast<double>(size/1024) << "\n"; |
| 247 | file.close(); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // fine tune this to decide about sending speed: |
| 252 | network_time_seconds network_throttle::get_sleep_time(size_t packet_size) const |
| 253 | { |
| 254 | double D2=0; |
| 255 | calculate_times_struct cts = { 0, 0, 0, 0}; |
| 256 | calculate_times(packet_size, cts, true, m_window_size); D2=cts.delay; |
| 257 | return D2; |
| 258 | } |
| 259 | |
| 260 | // MAIN LOGIC: |
| 261 | void network_throttle::calculate_times(size_t packet_size, calculate_times_struct &cts, bool dbg, double force_window) const |
| 262 | { |
| 263 | const double the_window_size = std::max( (double)m_window_size , |
| 264 | ((force_window>0) ? force_window : m_window_size) |
| 265 | ); |
| 266 | |
| 267 | if (!m_any_packet_yet) { |
| 268 | cts.window=0; cts.average=0; cts.delay=0; |
| 269 | cts.recomendetDataSize = m_network_minimal_segment; // should be overrided by caller anyway |
| 270 | return ; // no packet yet, I can not decide about sleep time |
| 271 | } |
| 272 | |
| 273 | network_time_seconds window_len = (the_window_size-1) * m_slot_size ; // -1 since current slot is not finished |
| 274 | window_len += (m_last_sample_time - time_to_slot(m_last_sample_time)); // add the time for current slot e.g. 13.7-13 = 0.7 |
| 275 | |
| 276 | auto time_passed = get_time_seconds() - m_start_time; |
| 277 | cts.window = std::max( std::min( window_len , time_passed ) , m_slot_size ) ; // window length resulting from size of history but limited by how long ago history was started, |
| 278 | // also at least slot size (e.g. 1 second) to not be ridiculous |
| 279 | // window_len e.g. 5.7 because takes into account current slot time |
| 280 | |
| 281 | size_t Epast = 0; // summ of traffic till now |
| 282 | for (auto sample : m_history) Epast += sample.m_size; |
| 283 | |
| 284 | const size_t E = Epast; |
| 285 | const size_t Enow = Epast + packet_size ; // including the data we're about to send now |
| 286 | |
| 287 | const double M = m_target_speed; // max |
| 288 | const double D1 = (Epast - M*cts.window) / M; // delay - how long to sleep to get back to target speed |
| 289 | const double D2 = (Enow - M*cts.window) / M; // delay - how long to sleep to get back to target speed (including current packet) |
| 290 | |
| 291 | cts.delay = (D1*0.80 + D2*0.20); // finall sleep depends on both with/without current packet |
| 292 | // update_overheat(); |
| 293 | cts.average = Epast/cts.window; // current avg. speed (for info) |
| 294 | |
| 295 | if (Epast <= 0) { |
| 296 | if (cts.delay>=0) cts.delay = 0; // no traffic in history so we will not wait |
| 297 | } |
| 298 | |
| 299 | double Wgood=-1; |
| 300 | { // how much data we recommend now to download |
| 301 | Wgood = the_window_size + 1; |
| 302 | cts.recomendetDataSize = M*cts.window - E; |
| 303 | } |
| 304 | |
| 305 | if (dbg) { |
| 306 | MTRACE((cts.delay > 0 ? "SLEEP" : "") |
| 307 | << "dbg " << m_name << ": " |
| 308 | << "speed is A=" << std::setw(8) <<cts.average<<" vs " |
| 309 | << "Max=" << std::setw(8) <<M<<" " |
| 310 | << " so sleep: " |
| 311 | << "D=" << std::setw(8) <<cts.delay<<" sec " |
| 312 | << "E="<< std::setw(8) << E << " (Enow="<<std::setw(8)<<Enow<<") " |
| 313 | << "M=" << std::setw(8) << M <<" W="<< std::setw(8) << cts.window << " " |
| 314 | << "R=" << std::setw(8) << cts.recomendetDataSize << " Wgood" << std::setw(8) << Wgood << " " |
| 315 | << "History: " << std::setw(8) << output_history{m_history} << " " |
| 316 | << "m_last_sample_time=" << std::setw(8) << m_last_sample_time |
| 317 | ); |
| 318 | |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | double network_throttle::get_time_seconds() const { |
| 323 | #if defined(__APPLE__) |
| 324 | auto point = std::chrono::system_clock::now(); |
| 325 | #else |
| 326 | auto point = std::chrono::steady_clock::now(); |
| 327 | #endif |
| 328 | auto time_from_epoh = point.time_since_epoch(); |
| 329 | auto ms = std::chrono::duration_cast< std::chrono::milliseconds >( time_from_epoh ).count(); |
| 330 | double ms_f = ms; |
| 331 | return ms_f / 1000.; |
| 332 | } |
| 333 | |
| 334 | size_t network_throttle::get_recommended_size_of_planned_transport_window(double force_window) const { |
| 335 | calculate_times_struct cts = { 0, 0, 0, 0}; |
| 336 | network_throttle::calculate_times(0, cts, true, force_window); |
| 337 | cts.recomendetDataSize += m_network_add_cost; |
| 338 | if (cts.recomendetDataSize<0) cts.recomendetDataSize=0; |
| 339 | if (cts.recomendetDataSize>m_network_max_segment) cts.recomendetDataSize=m_network_max_segment; |
| 340 | size_t RI = (long int)cts.recomendetDataSize; |
| 341 | return RI; |
| 342 | } |
| 343 | |
| 344 | size_t network_throttle::get_recommended_size_of_planned_transport() const { |
| 345 | size_t R1=0,R2=0,R3=0; |
| 346 | R1 = get_recommended_size_of_planned_transport_window( -1 ); |
| 347 | R2 = get_recommended_size_of_planned_transport_window(m_window_size / 2); |
| 348 | R3 = get_recommended_size_of_planned_transport_window( 5 ); |
| 349 | auto RM = std::min(R1, std::min(R2,R3)); |
| 350 | |
| 351 | const double a1=20, a2=10, a3=10, am=10; // weight of the various windows in decisssion // TODO 70 => 20 |
| 352 | return (R1*a1 + R2*a2 + R3*a3 + RM*am) / (a1+a2+a3+am); |
| 353 | } |
| 354 | |
| 355 | double network_throttle::get_current_speed() const { |
| 356 | unsigned int bytes_transferred = 0; |
| 357 | if (m_history.size() == 0 || m_slot_size == 0) |
| 358 | return 0; |
| 359 | |
| 360 | auto it = m_history.begin(); |
| 361 | while (it < m_history.end() - 1) |
| 362 | { |
| 363 | bytes_transferred += it->m_size; |
| 364 | it ++; |
| 365 | } |
| 366 | |
| 367 | return bytes_transferred / ((m_history.size() - 1) * m_slot_size); |
| 368 | } |
| 369 | |
| 370 | void network_throttle::get_stats(uint64_t &total_packets, uint64_t &total_bytes) const { |
| 371 | total_packets = m_total_packets; |
| 372 | total_bytes = m_total_bytes; |
| 373 | } |
| 374 | |
| 375 | |
| 376 | } // namespace |
| 377 | } // namespace |
| 378 |