DefaultBtMessageDispatcher.cc 13 KB

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