RequestGroup.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. #ifndef D_REQUEST_GROUP_H
  36. #define D_REQUEST_GROUP_H
  37. #include "common.h"
  38. #include <string>
  39. #include <algorithm>
  40. #include <vector>
  41. #include <memory>
  42. #include <utility>
  43. #include "TransferStat.h"
  44. #include "TimeA2.h"
  45. #include "Request.h"
  46. #include "error_code.h"
  47. #include "MetadataInfo.h"
  48. #include "GroupId.h"
  49. namespace aria2 {
  50. class DownloadEngine;
  51. class SegmentMan;
  52. class Command;
  53. class DownloadCommand;
  54. class DownloadContext;
  55. class PieceStorage;
  56. class BtProgressInfoFile;
  57. class Dependency;
  58. class PreDownloadHandler;
  59. class PostDownloadHandler;
  60. class DiskWriterFactory;
  61. class Option;
  62. class RequestGroup;
  63. class CheckIntegrityEntry;
  64. struct DownloadResult;
  65. class URISelector;
  66. class URIResult;
  67. class RequestGroupMan;
  68. #ifdef ENABLE_BITTORRENT
  69. class BtRuntime;
  70. class PeerStorage;
  71. #endif // ENABLE_BITTORRENT
  72. class RequestGroup {
  73. public:
  74. enum HaltReason { NONE, SHUTDOWN_SIGNAL, USER_REQUEST };
  75. enum State {
  76. // Waiting in the reserved queue
  77. STATE_WAITING,
  78. // Download has begun
  79. STATE_ACTIVE
  80. };
  81. private:
  82. // If this download is a part of another download(for example,
  83. // downloading torrent file described in Metalink file), this field
  84. // has the GID of parent RequestGroup. 0 means this is a parent
  85. // RequestGroup.
  86. a2_gid_t belongsToGID_;
  87. std::shared_ptr<GroupId> gid_;
  88. std::shared_ptr<Option> option_;
  89. std::shared_ptr<SegmentMan> segmentMan_;
  90. std::shared_ptr<DownloadContext> downloadContext_;
  91. std::shared_ptr<PieceStorage> pieceStorage_;
  92. std::shared_ptr<BtProgressInfoFile> progressInfoFile_;
  93. std::shared_ptr<DiskWriterFactory> diskWriterFactory_;
  94. std::shared_ptr<Dependency> dependency_;
  95. std::unique_ptr<URISelector> uriSelector_;
  96. std::shared_ptr<MetadataInfo> metadataInfo_;
  97. RequestGroupMan* requestGroupMan_;
  98. #ifdef ENABLE_BITTORRENT
  99. BtRuntime* btRuntime_;
  100. PeerStorage* peerStorage_;
  101. #endif // ENABLE_BITTORRENT
  102. // If this download generates another downloads when completed(for
  103. // example, downloads generated by PostDownloadHandler), this field
  104. // has the GID of generated RequestGroups. empty list means there is
  105. // no such RequestGroup.
  106. std::vector<a2_gid_t> followedByGIDs_;
  107. // This is a reverse link against followedByGIDs_. For example, a
  108. // download included in followedByGIDs_ has this download's GID in
  109. // followingGID_.
  110. a2_gid_t followingGID_;
  111. std::vector<const PreDownloadHandler*> preDownloadHandlers_;
  112. std::vector<const PostDownloadHandler*> postDownloadHandlers_;
  113. Time lastModifiedTime_;
  114. // Timeout used for HTTP/FTP downloads.
  115. std::chrono::seconds timeout_;
  116. int state_;
  117. int numConcurrentCommand_;
  118. /**
  119. * This is the number of connections used in streaming protocol(http/ftp)
  120. */
  121. int numStreamConnection_;
  122. int numStreamCommand_;
  123. int numCommand_;
  124. int fileNotFoundCount_;
  125. int maxDownloadSpeedLimit_;
  126. int maxUploadSpeedLimit_;
  127. int resumeFailureCount_;
  128. HaltReason haltReason_;
  129. error_code::Value lastErrorCode_;
  130. std::string lastErrorMessage_;
  131. bool saveControlFile_;
  132. bool fileAllocationEnabled_;
  133. bool preLocalFileCheckEnabled_;
  134. bool haltRequested_;
  135. bool forceHaltRequested_;
  136. bool pauseRequested_;
  137. // This flag just indicates that the downloaded file is not saved disk but
  138. // just sits in memory.
  139. bool inMemoryDownload_;
  140. bool seedOnly_;
  141. void validateFilename(const std::string& expectedFilename,
  142. const std::string& actualFilename) const;
  143. void initializePreDownloadHandler();
  144. void initializePostDownloadHandler();
  145. void tryAutoFileRenaming();
  146. // Returns the result code of this RequestGroup. If the download
  147. // finished, then returns error_code::FINISHED. If the
  148. // download didn't finish and error result is available in
  149. // _uriResults, then last result code is returned. Otherwise
  150. // returns error_code::UNKNOWN_ERROR.
  151. std::pair<error_code::Value, std::string> downloadResult() const;
  152. void removeDefunctControlFile(
  153. const std::shared_ptr<BtProgressInfoFile>& progressInfoFile);
  154. public:
  155. RequestGroup(const std::shared_ptr<GroupId>& gid,
  156. const std::shared_ptr<Option>& option);
  157. ~RequestGroup();
  158. bool isCheckIntegrityReady();
  159. const std::shared_ptr<SegmentMan>& getSegmentMan() const
  160. {
  161. return segmentMan_;
  162. }
  163. std::unique_ptr<CheckIntegrityEntry> createCheckIntegrityEntry();
  164. // Returns first bootstrap commands to initiate a download.
  165. // If this is HTTP/FTP download and file size is unknown, only 1 command
  166. // (usually, HttpInitiateConnection or FtpInitiateConnection) will be created.
  167. void createInitialCommand(std::vector<std::unique_ptr<Command>>& commands,
  168. DownloadEngine* e);
  169. void createNextCommandWithAdj(std::vector<std::unique_ptr<Command>>& commands,
  170. DownloadEngine* e, int numAdj);
  171. void createNextCommand(std::vector<std::unique_ptr<Command>>& commands,
  172. DownloadEngine* e, int numCommand);
  173. void createNextCommand(std::vector<std::unique_ptr<Command>>& commands,
  174. DownloadEngine* e);
  175. bool downloadFinished() const;
  176. bool allDownloadFinished() const;
  177. void closeFile();
  178. std::string getFirstFilePath() const;
  179. int64_t getTotalLength() const;
  180. int64_t getCompletedLength() const;
  181. inline int64_t getPendingLength() const
  182. {
  183. return getTotalLength() - getCompletedLength();
  184. }
  185. /**
  186. * Compares expected filename with specified actualFilename.
  187. * The expected filename refers to FileEntry::getBasename() of the first
  188. * element of DownloadContext::getFileEntries()
  189. */
  190. void validateFilename(const std::string& actualFilename) const;
  191. void validateTotalLength(int64_t expectedTotalLength,
  192. int64_t actualTotalLength) const;
  193. void validateTotalLength(int64_t actualTotalLength) const;
  194. void setNumConcurrentCommand(int num) { numConcurrentCommand_ = num; }
  195. int getNumConcurrentCommand() const { return numConcurrentCommand_; }
  196. a2_gid_t getGID() const { return gid_->getNumericId(); }
  197. const std::shared_ptr<GroupId>& getGroupId() const { return gid_; }
  198. TransferStat calculateStat() const;
  199. const std::shared_ptr<DownloadContext>& getDownloadContext() const
  200. {
  201. return downloadContext_;
  202. }
  203. // This function also calls
  204. // downloadContext->setOwnerRequestGroup(this).
  205. void
  206. setDownloadContext(const std::shared_ptr<DownloadContext>& downloadContext);
  207. const std::shared_ptr<PieceStorage>& getPieceStorage() const
  208. {
  209. return pieceStorage_;
  210. }
  211. void setPieceStorage(const std::shared_ptr<PieceStorage>& pieceStorage);
  212. void setProgressInfoFile(
  213. const std::shared_ptr<BtProgressInfoFile>& progressInfoFile);
  214. void increaseStreamCommand();
  215. void decreaseStreamCommand();
  216. void increaseStreamConnection();
  217. void decreaseStreamConnection();
  218. int getNumConnection() const;
  219. void increaseNumCommand();
  220. void decreaseNumCommand();
  221. int getNumCommand() const { return numCommand_; }
  222. // TODO is it better to move the following 2 methods to
  223. // SingleFileDownloadContext?
  224. void setDiskWriterFactory(
  225. const std::shared_ptr<DiskWriterFactory>& diskWriterFactory);
  226. const std::shared_ptr<DiskWriterFactory>& getDiskWriterFactory() const
  227. {
  228. return diskWriterFactory_;
  229. }
  230. void setFileAllocationEnabled(bool f) { fileAllocationEnabled_ = f; }
  231. bool isFileAllocationEnabled() const { return fileAllocationEnabled_; }
  232. bool needsFileAllocation() const;
  233. /**
  234. * Setting preLocalFileCheckEnabled_ to false, then skip the check to see
  235. * if a file is already exists and control file exists etc.
  236. * Always open file with DiskAdaptor::initAndOpenFile()
  237. */
  238. void setPreLocalFileCheckEnabled(bool f) { preLocalFileCheckEnabled_ = f; }
  239. bool isPreLocalFileCheckEnabled() const { return preLocalFileCheckEnabled_; }
  240. void setHaltRequested(bool f, HaltReason = SHUTDOWN_SIGNAL);
  241. void setForceHaltRequested(bool f, HaltReason = SHUTDOWN_SIGNAL);
  242. bool isHaltRequested() const { return haltRequested_; }
  243. bool isForceHaltRequested() const { return forceHaltRequested_; }
  244. void setPauseRequested(bool f);
  245. bool isPauseRequested() const { return pauseRequested_; }
  246. void dependsOn(const std::shared_ptr<Dependency>& dep);
  247. bool isDependencyResolved();
  248. void releaseRuntimeResource(DownloadEngine* e);
  249. void
  250. postDownloadProcessing(std::vector<std::shared_ptr<RequestGroup>>& groups);
  251. void addPostDownloadHandler(const PostDownloadHandler* handler);
  252. void clearPostDownloadHandler();
  253. void preDownloadProcessing();
  254. void addPreDownloadHandler(const PreDownloadHandler* handler);
  255. void clearPreDownloadHandler();
  256. void
  257. processCheckIntegrityEntry(std::vector<std::unique_ptr<Command>>& commands,
  258. std::unique_ptr<CheckIntegrityEntry> entry,
  259. DownloadEngine* e);
  260. // Initializes pieceStorage_ and segmentMan_. We guarantee that
  261. // either both of pieceStorage_ and segmentMan_ are initialized or
  262. // they are not.
  263. void initPieceStorage();
  264. void dropPieceStorage();
  265. bool downloadFinishedByFileLength();
  266. void
  267. loadAndOpenFile(const std::shared_ptr<BtProgressInfoFile>& progressInfoFile);
  268. void shouldCancelDownloadForSafety();
  269. void adjustFilename(const std::shared_ptr<BtProgressInfoFile>& infoFile);
  270. std::shared_ptr<DownloadResult> createDownloadResult() const;
  271. const std::shared_ptr<Option>& getOption() const { return option_; }
  272. void reportDownloadFinished();
  273. void setURISelector(std::unique_ptr<URISelector> uriSelector);
  274. const std::unique_ptr<URISelector>& getURISelector() const
  275. {
  276. return uriSelector_;
  277. }
  278. void applyLastModifiedTimeToLocalFiles();
  279. void updateLastModifiedTime(const Time& time);
  280. void increaseAndValidateFileNotFoundCount();
  281. // Just set inMemoryDownload flag true.
  282. void markInMemoryDownload();
  283. // Returns inMemoryDownload flag.
  284. bool inMemoryDownload() const { return inMemoryDownload_; }
  285. void setTimeout(std::chrono::seconds timeout);
  286. const std::chrono::seconds& getTimeout() const { return timeout_; }
  287. // Returns true if current download speed exceeds
  288. // maxDownloadSpeedLimit_. Always returns false if
  289. // maxDownloadSpeedLimit_ == 0. Otherwise returns false.
  290. bool doesDownloadSpeedExceed();
  291. // Returns true if current upload speed exceeds
  292. // maxUploadSpeedLimit_. Always returns false if
  293. // maxUploadSpeedLimit_ == 0. Otherwise returns false.
  294. bool doesUploadSpeedExceed();
  295. int getMaxDownloadSpeedLimit() const { return maxDownloadSpeedLimit_; }
  296. void setMaxDownloadSpeedLimit(int speed) { maxDownloadSpeedLimit_ = speed; }
  297. int getMaxUploadSpeedLimit() const { return maxUploadSpeedLimit_; }
  298. void setMaxUploadSpeedLimit(int speed) { maxUploadSpeedLimit_ = speed; }
  299. void setLastErrorCode(error_code::Value code, const char* message = "")
  300. {
  301. lastErrorCode_ = code;
  302. lastErrorMessage_ = message;
  303. }
  304. error_code::Value getLastErrorCode() const { return lastErrorCode_; }
  305. void saveControlFile() const;
  306. void removeControlFile() const;
  307. void enableSaveControlFile() { saveControlFile_ = true; }
  308. void disableSaveControlFile() { saveControlFile_ = false; }
  309. template <typename InputIterator>
  310. void followedBy(InputIterator groupFirst, InputIterator groupLast)
  311. {
  312. followedByGIDs_.clear();
  313. for (; groupFirst != groupLast; ++groupFirst) {
  314. followedByGIDs_.push_back((*groupFirst)->getGID());
  315. }
  316. }
  317. const std::vector<a2_gid_t>& followedBy() const { return followedByGIDs_; }
  318. void following(a2_gid_t gid) { followingGID_ = gid; }
  319. a2_gid_t following() const { return followingGID_; }
  320. void belongsTo(a2_gid_t gid) { belongsToGID_ = gid; }
  321. a2_gid_t belongsTo() const { return belongsToGID_; }
  322. void setRequestGroupMan(RequestGroupMan* requestGroupMan)
  323. {
  324. requestGroupMan_ = requestGroupMan;
  325. }
  326. RequestGroupMan* getRequestGroupMan() { return requestGroupMan_; }
  327. int getResumeFailureCount() const { return resumeFailureCount_; }
  328. void increaseResumeFailureCount() { ++resumeFailureCount_; }
  329. bool p2pInvolved() const;
  330. void setMetadataInfo(const std::shared_ptr<MetadataInfo>& info)
  331. {
  332. metadataInfo_ = info;
  333. }
  334. const std::shared_ptr<MetadataInfo>& getMetadataInfo() const
  335. {
  336. return metadataInfo_;
  337. }
  338. int getState() const { return state_; }
  339. void setState(int state) { state_ = state; }
  340. bool isSeedOnlyEnabled() { return seedOnly_; }
  341. void enableSeedOnly();
  342. // Returns true if this download is now seeding.
  343. bool isSeeder() const;
  344. };
  345. } // namespace aria2
  346. #endif // D_REQUEST_GROUP_H