DefaultBtMessageDispatcher.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 "DefaultBtMessageDispatcher.h"
  36. #include <algorithm>
  37. #include "prefs.h"
  38. #include "BtAbortOutstandingRequestEvent.h"
  39. #include "BtCancelSendingPieceEvent.h"
  40. #include "BtChokedEvent.h"
  41. #include "BtChokingEvent.h"
  42. #include "BtMessageFactory.h"
  43. #include "message.h"
  44. #include "BtContext.h"
  45. #include "PeerStorage.h"
  46. #include "PieceStorage.h"
  47. #include "BtMessage.h"
  48. #include "Peer.h"
  49. #include "Piece.h"
  50. #include "LogFactory.h"
  51. #include "Logger.h"
  52. #include "a2functional.h"
  53. namespace aria2 {
  54. DefaultBtMessageDispatcher::DefaultBtMessageDispatcher():
  55. cuid(0),
  56. maxUploadSpeedLimit(0),
  57. requestTimeout(0),
  58. logger(LogFactory::getInstance()) {}
  59. DefaultBtMessageDispatcher::~DefaultBtMessageDispatcher()
  60. {
  61. logger->debug("DefaultBtMessageDispatcher::deleted");
  62. }
  63. void DefaultBtMessageDispatcher::addMessageToQueue(const BtMessageHandle& btMessage)
  64. {
  65. btMessage->onQueued();
  66. messageQueue.push_back(btMessage);
  67. }
  68. void DefaultBtMessageDispatcher::addMessageToQueue(const BtMessages& btMessages)
  69. {
  70. for(BtMessages::const_iterator itr = btMessages.begin(); itr != btMessages.end(); itr++) {
  71. addMessageToQueue(*itr);
  72. }
  73. }
  74. void DefaultBtMessageDispatcher::sendMessages() {
  75. BtMessages tempQueue;
  76. while(!messageQueue.empty()) {
  77. BtMessageHandle msg = messageQueue.front();
  78. messageQueue.pop_front();
  79. if(maxUploadSpeedLimit > 0 &&
  80. msg->isUploading() && !msg->isSendingInProgress()) {
  81. TransferStat stat = _peerStorage->calculateStat();
  82. if(maxUploadSpeedLimit < stat.getUploadSpeed()) {
  83. tempQueue.push_back(msg);
  84. continue;
  85. }
  86. }
  87. msg->send();
  88. if(msg->isSendingInProgress()) {
  89. messageQueue.push_front(msg);
  90. break;
  91. }
  92. }
  93. if(!tempQueue.empty()) {
  94. // Insert pending message to the front, so that message is likely sent in
  95. // the same order as it is queued.
  96. if(!messageQueue.empty() && messageQueue.front()->isSendingInProgress()) {
  97. messageQueue.insert(messageQueue.begin()+1,
  98. tempQueue.begin(), tempQueue.end());
  99. } else {
  100. messageQueue.insert(messageQueue.begin(),
  101. tempQueue.begin(), tempQueue.end());
  102. }
  103. }
  104. }
  105. class HandleEvent {
  106. private:
  107. SharedHandle<BtEvent> _event;
  108. public:
  109. HandleEvent(const SharedHandle<BtEvent>& event):_event(event) {}
  110. void operator()(const SharedHandle<BtMessage>& msg) const
  111. {
  112. msg->handleEvent(_event);
  113. }
  114. };
  115. // Cancel sending piece message to peer.
  116. void DefaultBtMessageDispatcher::doCancelSendingPieceAction(size_t index, uint32_t begin, size_t length)
  117. {
  118. BtCancelSendingPieceEventHandle event
  119. (new BtCancelSendingPieceEvent(index, begin, length));
  120. BtMessages tempQueue = messageQueue;
  121. std::for_each(tempQueue.begin(), tempQueue.end(), HandleEvent(event));
  122. }
  123. // Cancel sending piece message to peer.
  124. // TODO Is this method really necessary?
  125. void DefaultBtMessageDispatcher::doCancelSendingPieceAction(const PieceHandle& piece)
  126. {
  127. }
  128. class AbortOutstandingRequest {
  129. private:
  130. SharedHandle<Piece> _piece;
  131. int32_t _cuid;
  132. Logger* _logger;
  133. public:
  134. AbortOutstandingRequest(const SharedHandle<Piece>& piece, int32_t cuid):
  135. _piece(piece),
  136. _cuid(cuid),
  137. _logger(LogFactory::getInstance()) {}
  138. void operator()(const RequestSlot& slot) const
  139. {
  140. _logger->debug(MSG_DELETING_REQUEST_SLOT,
  141. _cuid,
  142. slot.getIndex(),
  143. slot.getBlockIndex());
  144. _logger->debug("index=%d, begin=%d", slot.getIndex(), slot.getBegin());
  145. _piece->cancelBlock(slot.getBlockIndex());
  146. }
  147. };
  148. // localhost cancels outstanding download requests to the peer.
  149. void DefaultBtMessageDispatcher::doAbortOutstandingRequestAction(const PieceHandle& piece) {
  150. RequestSlot rs(piece->getIndex(), 0, 0, 0);
  151. std::deque<RequestSlot>::iterator first =
  152. std::lower_bound(requestSlots.begin(), requestSlots.end(), rs);
  153. rs.setIndex(piece->getIndex()+1);
  154. std::deque<RequestSlot>::iterator last =
  155. std::lower_bound(requestSlots.begin(), requestSlots.end(), rs);
  156. std::for_each(first, last, AbortOutstandingRequest(piece, cuid));
  157. requestSlots.erase(first, last);
  158. BtAbortOutstandingRequestEventHandle event
  159. (new BtAbortOutstandingRequestEvent(piece));
  160. BtMessages tempQueue = messageQueue;
  161. std::for_each(tempQueue.begin(), tempQueue.end(), HandleEvent(event));
  162. }
  163. class ProcessChokedRequestSlot {
  164. private:
  165. int32_t _cuid;
  166. SharedHandle<Peer> _peer;
  167. SharedHandle<PieceStorage> _pieceStorage;
  168. Logger* _logger;
  169. public:
  170. ProcessChokedRequestSlot(int32_t cuid,
  171. const SharedHandle<Peer>& peer,
  172. const SharedHandle<PieceStorage>& pieceStorage):
  173. _cuid(cuid),
  174. _peer(peer),
  175. _pieceStorage(pieceStorage),
  176. _logger(LogFactory::getInstance()) {}
  177. void operator()(const RequestSlot& slot) const
  178. {
  179. if(!_peer->isInPeerAllowedIndexSet(slot.getIndex())) {
  180. _logger->debug(MSG_DELETING_REQUEST_SLOT_CHOKED,
  181. _cuid,
  182. slot.getIndex(),
  183. slot.getBlockIndex());
  184. _logger->debug("index=%d, begin=%d", slot.getIndex(), slot.getBegin());
  185. SharedHandle<Piece> piece = _pieceStorage->getPiece(slot.getIndex());
  186. piece->cancelBlock(slot.getBlockIndex());
  187. }
  188. }
  189. };
  190. class FindChokedRequestSlot {
  191. private:
  192. SharedHandle<Peer> _peer;
  193. public:
  194. FindChokedRequestSlot(const SharedHandle<Peer>& peer):
  195. _peer(peer) {}
  196. bool operator()(const RequestSlot& slot) const
  197. {
  198. return !_peer->isInPeerAllowedIndexSet(slot.getIndex());
  199. }
  200. };
  201. // localhost received choke message from the peer.
  202. void DefaultBtMessageDispatcher::doChokedAction()
  203. {
  204. std::for_each(requestSlots.begin(), requestSlots.end(),
  205. ProcessChokedRequestSlot(cuid, peer, _pieceStorage));
  206. requestSlots.erase(std::remove_if(requestSlots.begin(), requestSlots.end(),
  207. FindChokedRequestSlot(peer)),
  208. requestSlots.end());
  209. BtChokedEventHandle event(new BtChokedEvent());
  210. BtMessages tempQueue = messageQueue;
  211. std::for_each(tempQueue.begin(), tempQueue.end(), HandleEvent(event));
  212. }
  213. // localhost dispatched choke message to the peer.
  214. void DefaultBtMessageDispatcher::doChokingAction()
  215. {
  216. BtChokingEventHandle event(new BtChokingEvent());
  217. BtMessages tempQueue = messageQueue;
  218. std::for_each(tempQueue.begin(), tempQueue.end(), HandleEvent(event));
  219. }
  220. class ProcessStaleRequestSlot {
  221. private:
  222. int32_t _cuid;
  223. SharedHandle<Peer> _peer;
  224. SharedHandle<PieceStorage> _pieceStorage;
  225. BtMessageDispatcher* _messageDispatcher;
  226. WeakHandle<BtMessageFactory> _messageFactory;
  227. const struct timeval& _now;
  228. time_t _requestTimeout;
  229. Logger* _logger;
  230. public:
  231. ProcessStaleRequestSlot(int32_t cuid, const SharedHandle<Peer>& peer,
  232. const SharedHandle<PieceStorage>& pieceStorage,
  233. BtMessageDispatcher* dispatcher,
  234. const WeakHandle<BtMessageFactory>& factory,
  235. const struct timeval& now,
  236. time_t requestTimeout):
  237. _cuid(cuid),
  238. _peer(peer),
  239. _pieceStorage(pieceStorage),
  240. _messageDispatcher(dispatcher),
  241. _messageFactory(factory),
  242. _now(now),
  243. _requestTimeout(requestTimeout),
  244. _logger(LogFactory::getInstance()) {}
  245. void operator()(const RequestSlot& slot)
  246. {
  247. if(slot.isTimeout(_now, _requestTimeout)) {
  248. _logger->debug(MSG_DELETING_REQUEST_SLOT_TIMEOUT,
  249. _cuid,
  250. slot.getBlockIndex());
  251. _logger->debug("index=%d, begin=%d", slot.getIndex(), slot.getBegin());
  252. slot.getPiece()->cancelBlock(slot.getBlockIndex());
  253. _peer->snubbing(true);
  254. } else if(slot.getPiece()->hasBlock(slot.getBlockIndex())) {
  255. _logger->debug(MSG_DELETING_REQUEST_SLOT_ACQUIRED,
  256. _cuid,
  257. slot.getBlockIndex());
  258. _logger->debug("index=%d, begin=%d", slot.getIndex(), slot.getBegin());
  259. _messageDispatcher->addMessageToQueue
  260. (_messageFactory->createCancelMessage(slot.getIndex(),
  261. slot.getBegin(),
  262. slot.getLength()));
  263. }
  264. }
  265. };
  266. class FindStaleRequestSlot {
  267. private:
  268. SharedHandle<PieceStorage> _pieceStorage;
  269. const struct timeval& _now;
  270. time_t _requestTimeout;
  271. public:
  272. FindStaleRequestSlot(const SharedHandle<PieceStorage>& pieceStorage,
  273. const struct timeval& now,
  274. time_t requestTimeout):
  275. _pieceStorage(pieceStorage),
  276. _now(now),
  277. _requestTimeout(requestTimeout) {}
  278. bool operator()(const RequestSlot& slot)
  279. {
  280. if(slot.isTimeout(_now, _requestTimeout)) {
  281. return true;
  282. } else {
  283. if(slot.getPiece()->hasBlock(slot.getBlockIndex())) {
  284. return true;
  285. } else {
  286. return false;
  287. }
  288. }
  289. }
  290. };
  291. void DefaultBtMessageDispatcher::checkRequestSlotAndDoNecessaryThing()
  292. {
  293. struct timeval now;
  294. gettimeofday(&now, 0);
  295. std::for_each(requestSlots.begin(), requestSlots.end(),
  296. ProcessStaleRequestSlot(cuid,
  297. peer,
  298. _pieceStorage,
  299. this,
  300. messageFactory,
  301. now,
  302. requestTimeout));
  303. requestSlots.erase(std::remove_if(requestSlots.begin(), requestSlots.end(),
  304. FindStaleRequestSlot(_pieceStorage,
  305. now,
  306. requestTimeout)),
  307. requestSlots.end());
  308. }
  309. bool DefaultBtMessageDispatcher::isSendingInProgress()
  310. {
  311. if(messageQueue.size() > 0) {
  312. return messageQueue.front()->isSendingInProgress();
  313. } else {
  314. return false;
  315. }
  316. }
  317. size_t DefaultBtMessageDispatcher::countOutstandingRequest()
  318. {
  319. return requestSlots.size();
  320. }
  321. class BlockIndexLess {
  322. public:
  323. bool operator()(const RequestSlot& lhs, const RequestSlot& rhs) const
  324. {
  325. if(lhs.getIndex() == rhs.getIndex()) {
  326. return lhs.getBlockIndex() < rhs.getBlockIndex();
  327. } else {
  328. return lhs.getIndex() < rhs.getIndex();
  329. }
  330. }
  331. };
  332. bool DefaultBtMessageDispatcher::isOutstandingRequest(size_t index, size_t blockIndex) {
  333. RequestSlot rs(index, 0, 0, blockIndex);
  334. std::deque<RequestSlot>::iterator i =
  335. std::lower_bound(requestSlots.begin(), requestSlots.end(), rs, BlockIndexLess());
  336. return i != requestSlots.end() &&
  337. (*i).getIndex() == index && (*i).getBlockIndex() == blockIndex;
  338. }
  339. RequestSlot
  340. DefaultBtMessageDispatcher::getOutstandingRequest(size_t index, uint32_t begin, size_t length)
  341. {
  342. RequestSlot ret;
  343. RequestSlot rs(index, begin, length, 0);
  344. std::deque<RequestSlot>::iterator i =
  345. std::lower_bound(requestSlots.begin(), requestSlots.end(), rs);
  346. if(i != requestSlots.end() && (*i) == rs) {
  347. ret = *i;
  348. } else {
  349. ret = RequestSlot::nullSlot;
  350. }
  351. return ret;
  352. }
  353. void DefaultBtMessageDispatcher::removeOutstandingRequest(const RequestSlot& slot)
  354. {
  355. std::deque<RequestSlot>::iterator i =
  356. std::lower_bound(requestSlots.begin(), requestSlots.end(), slot);
  357. if(i != requestSlots.end() && (*i) == slot) {
  358. requestSlots.erase(i);
  359. }
  360. }
  361. void DefaultBtMessageDispatcher::addOutstandingRequest(const RequestSlot& slot)
  362. {
  363. std::deque<RequestSlot>::iterator i =
  364. std::lower_bound(requestSlots.begin(), requestSlots.end(), slot);
  365. if(i == requestSlots.end() || (*i) != slot) {
  366. requestSlots.insert(i, slot);
  367. }
  368. }
  369. size_t DefaultBtMessageDispatcher::countOutstandingUpload()
  370. {
  371. return std::count_if(messageQueue.begin(), messageQueue.end(),
  372. mem_fun_sh(&BtMessage::isUploading));
  373. }
  374. const std::deque<SharedHandle<BtMessage> >&
  375. DefaultBtMessageDispatcher::getMessageQueue()
  376. {
  377. return messageQueue;
  378. }
  379. const std::deque<RequestSlot>& DefaultBtMessageDispatcher::getRequestSlots()
  380. {
  381. return requestSlots;
  382. }
  383. void DefaultBtMessageDispatcher::setPeer(const SharedHandle<Peer>& peer)
  384. {
  385. this->peer = peer;
  386. }
  387. void DefaultBtMessageDispatcher::setBtContext(const BtContextHandle& btContext)
  388. {
  389. this->btContext = btContext;
  390. }
  391. void DefaultBtMessageDispatcher::setPieceStorage
  392. (const SharedHandle<PieceStorage>& pieceStorage)
  393. {
  394. _pieceStorage = pieceStorage;
  395. }
  396. void DefaultBtMessageDispatcher::setPeerStorage
  397. (const SharedHandle<PeerStorage>& peerStorage)
  398. {
  399. _peerStorage = peerStorage;
  400. }
  401. void DefaultBtMessageDispatcher::setBtMessageFactory(const WeakHandle<BtMessageFactory>& factory)
  402. {
  403. this->messageFactory = factory;
  404. }
  405. } // namespace aria2