DefaultPeerStorage.cc 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "DefaultPeerStorage.h"
  36. #include <algorithm>
  37. #include "LogFactory.h"
  38. #include "Logger.h"
  39. #include "message.h"
  40. #include "a2time.h"
  41. #include "Peer.h"
  42. #include "BtContext.h"
  43. #include "BtRuntime.h"
  44. #include "BtSeederStateChoke.h"
  45. #include "BtLeecherStateChoke.h"
  46. #include "PieceStorage.h"
  47. namespace aria2 {
  48. static const int MAX_PEER_LIST_SIZE = 1024;
  49. DefaultPeerStorage::DefaultPeerStorage(const BtContextHandle& btContext,
  50. const Option* option):
  51. btContext(btContext),
  52. option(option),
  53. logger(LogFactory::getInstance()),
  54. removedPeerSessionDownloadLength(0),
  55. removedPeerSessionUploadLength(0),
  56. _seederStateChoke(new BtSeederStateChoke()),
  57. _leecherStateChoke(new BtLeecherStateChoke())
  58. {}
  59. DefaultPeerStorage::~DefaultPeerStorage()
  60. {
  61. delete _seederStateChoke;
  62. delete _leecherStateChoke;
  63. }
  64. class FindIdenticalPeer {
  65. private:
  66. PeerHandle _peer;
  67. public:
  68. FindIdenticalPeer(const PeerHandle& peer):_peer(peer) {}
  69. bool operator()(const PeerHandle& peer) const {
  70. return (_peer == peer) ||
  71. ((_peer->ipaddr == peer->ipaddr) && (_peer->port == peer->port));
  72. }
  73. };
  74. bool DefaultPeerStorage::isPeerAlreadyAdded(const PeerHandle& peer)
  75. {
  76. return std::find_if(peers.begin(), peers.end(), FindIdenticalPeer(peer)) != peers.end();
  77. }
  78. static size_t calculateMaxPeerListSize(const SharedHandle<BtRuntime>& btRuntime)
  79. {
  80. if(btRuntime.isNull()) {
  81. return MAX_PEER_LIST_SIZE;
  82. }
  83. return btRuntime->getMaxPeers() == 0 ?
  84. MAX_PEER_LIST_SIZE :
  85. btRuntime->getMaxPeers()+(btRuntime->getMaxPeers() >> 2);
  86. }
  87. bool DefaultPeerStorage::addPeer(const PeerHandle& peer) {
  88. if(isPeerAlreadyAdded(peer)) {
  89. logger->debug("Adding %s:%u is rejected because it has been already added.", peer->ipaddr.c_str(), peer->port);
  90. return false;
  91. }
  92. size_t maxPeerListSize = calculateMaxPeerListSize(_btRuntime);
  93. if(peers.size() >= maxPeerListSize) {
  94. deleteUnusedPeer(peers.size()-maxPeerListSize+1);
  95. }
  96. peers.push_front(peer);
  97. return true;
  98. }
  99. void DefaultPeerStorage::addPeer(const Peers& peers) {
  100. for(Peers::const_iterator itr = peers.begin();
  101. itr != peers.end(); itr++) {
  102. const PeerHandle& peer = *itr;
  103. if(addPeer(peer)) {
  104. logger->debug(MSG_ADDING_PEER,
  105. peer->ipaddr.c_str(), peer->port);
  106. }
  107. }
  108. }
  109. const Peers& DefaultPeerStorage::getPeers() {
  110. return peers;
  111. }
  112. class FindFinePeer {
  113. public:
  114. bool operator()(const PeerHandle& peer) const {
  115. return peer->unused() && peer->isGood();
  116. }
  117. };
  118. PeerHandle DefaultPeerStorage::getUnusedPeer() {
  119. Peers::const_iterator itr = std::find_if(peers.begin(), peers.end(),
  120. FindFinePeer());
  121. if(itr == peers.end()) {
  122. return SharedHandle<Peer>();
  123. } else {
  124. return *itr;
  125. }
  126. }
  127. class FindPeer {
  128. private:
  129. std::string ipaddr;
  130. uint16_t port;
  131. public:
  132. FindPeer(const std::string& ipaddr, uint16_t port):ipaddr(ipaddr), port(port) {}
  133. bool operator()(const PeerHandle& peer) const {
  134. return ipaddr == peer->ipaddr && port == peer->port;
  135. }
  136. };
  137. PeerHandle DefaultPeerStorage::getPeer(const std::string& ipaddr,
  138. uint16_t port) const {
  139. Peers::const_iterator itr = std::find_if(peers.begin(), peers.end(),
  140. FindPeer(ipaddr, port));
  141. if(itr == peers.end()) {
  142. return SharedHandle<Peer>();
  143. } else {
  144. return *itr;
  145. }
  146. }
  147. size_t DefaultPeerStorage::countPeer() const {
  148. return peers.size();
  149. }
  150. bool DefaultPeerStorage::isPeerAvailable() {
  151. return !getUnusedPeer().isNull();
  152. }
  153. class CollectActivePeer {
  154. private:
  155. std::deque<SharedHandle<Peer> >& _activePeers;
  156. public:
  157. CollectActivePeer(std::deque<SharedHandle<Peer> >& activePeers):
  158. _activePeers(activePeers) {}
  159. void operator()(const SharedHandle<Peer>& peer)
  160. {
  161. if(peer->isActive()) {
  162. _activePeers.push_back(peer);
  163. }
  164. }
  165. };
  166. void DefaultPeerStorage::getActivePeers(std::deque<SharedHandle<Peer> >& activePeers)
  167. {
  168. std::for_each(peers.begin(), peers.end(), CollectActivePeer(activePeers));
  169. }
  170. class CalculateStat {
  171. private:
  172. TransferStat _stat;
  173. struct timeval _now;
  174. public:
  175. CalculateStat()
  176. {
  177. gettimeofday(&_now, 0);
  178. }
  179. void operator()(const PeerHandle& peer)
  180. {
  181. if(peer->isActive()) {
  182. _stat.downloadSpeed += peer->calculateDownloadSpeed(_now);
  183. _stat.uploadSpeed += peer->calculateUploadSpeed(_now);
  184. _stat.sessionDownloadLength += peer->getSessionDownloadLength();
  185. _stat.sessionUploadLength += peer->getSessionUploadLength();
  186. }
  187. }
  188. const TransferStat& getTransferStat() { return _stat; }
  189. };
  190. TransferStat DefaultPeerStorage::calculateStat() {
  191. TransferStat stat = std::for_each(peers.begin(), peers.end(), CalculateStat()).getTransferStat();
  192. stat.sessionDownloadLength += removedPeerSessionDownloadLength;
  193. stat.sessionUploadLength += removedPeerSessionUploadLength;
  194. stat.setAllTimeUploadLength(_btRuntime->getUploadLengthAtStartup()+
  195. stat.getSessionUploadLength());
  196. return stat;
  197. }
  198. void DefaultPeerStorage::deleteUnusedPeer(size_t delSize) {
  199. Peers temp;
  200. for(Peers::reverse_iterator itr = peers.rbegin();
  201. itr != peers.rend(); ++itr) {
  202. const PeerHandle& p = *itr;
  203. if(p->unused() && delSize > 0) {
  204. onErasingPeer(p);
  205. delSize--;
  206. } else {
  207. temp.push_front(p);
  208. }
  209. }
  210. peers = temp;
  211. }
  212. void DefaultPeerStorage::onErasingPeer(const SharedHandle<Peer>& peer) {}
  213. void DefaultPeerStorage::onReturningPeer(const SharedHandle<Peer>& peer)
  214. {
  215. if(peer->isActive()) {
  216. removedPeerSessionDownloadLength += peer->getSessionDownloadLength();
  217. removedPeerSessionUploadLength += peer->getSessionUploadLength();
  218. // Execute choking algorithm if unchoked and interested peer is
  219. // disconnected.
  220. if(!peer->amChoking() && peer->peerInterested()) {
  221. executeChoke();
  222. }
  223. }
  224. }
  225. void DefaultPeerStorage::returnPeer(const PeerHandle& peer)
  226. {
  227. Peers::iterator itr = std::find(peers.begin(), peers.end(), peer);
  228. if(itr == peers.end()) {
  229. logger->debug("Cannot find peer %s:%u in PeerStorage.", peer->ipaddr.c_str(), peer->port);
  230. } else {
  231. peers.erase(itr);
  232. onReturningPeer(peer);
  233. onErasingPeer(peer);
  234. }
  235. }
  236. bool DefaultPeerStorage::chokeRoundIntervalElapsed()
  237. {
  238. const time_t CHOKE_ROUND_INTERVAL = 10;
  239. if(_pieceStorage->downloadFinished()) {
  240. return _seederStateChoke->getLastRound().elapsed(CHOKE_ROUND_INTERVAL);
  241. } else {
  242. return _leecherStateChoke->getLastRound().elapsed(CHOKE_ROUND_INTERVAL);
  243. }
  244. }
  245. void DefaultPeerStorage::executeChoke()
  246. {
  247. std::deque<SharedHandle<Peer> > activePeers;
  248. getActivePeers(activePeers);
  249. if(_pieceStorage->downloadFinished()) {
  250. return _seederStateChoke->executeChoke(activePeers);
  251. } else {
  252. return _leecherStateChoke->executeChoke(activePeers);
  253. }
  254. }
  255. void DefaultPeerStorage::setPieceStorage(const SharedHandle<PieceStorage>& ps)
  256. {
  257. _pieceStorage = ps;
  258. }
  259. void DefaultPeerStorage::setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
  260. {
  261. _btRuntime = btRuntime;
  262. }
  263. } // namespace aria2