RequestGroup.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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 "SharedHandle.h"
  42. #include "TransferStat.h"
  43. #include "TimeA2.h"
  44. #include "Request.h"
  45. #include "DownloadResultCode.h"
  46. #include "MetadataInfo.h"
  47. namespace aria2 {
  48. class DownloadEngine;
  49. class SegmentMan;
  50. class Command;
  51. class DownloadCommand;
  52. class DownloadContext;
  53. class PieceStorage;
  54. class BtProgressInfoFile;
  55. class Dependency;
  56. class PreDownloadHandler;
  57. class PostDownloadHandler;
  58. class DiskWriterFactory;
  59. class Option;
  60. class Logger;
  61. class RequestGroup;
  62. class CheckIntegrityEntry;
  63. class DownloadResult;
  64. class URISelector;
  65. class URIResult;
  66. class RequestGroupMan;
  67. #ifdef ENABLE_BITTORRENT
  68. class BtRuntime;
  69. class PeerStorage;
  70. #endif // ENABLE_BITTORRENT
  71. typedef int64_t gid_t;
  72. class RequestGroup {
  73. public:
  74. enum HaltReason {
  75. NONE,
  76. SHUTDOWN_SIGNAL,
  77. USER_REQUEST
  78. };
  79. private:
  80. static gid_t _gidCounter;
  81. gid_t _gid;
  82. SharedHandle<Option> _option;
  83. size_t _numConcurrentCommand;
  84. /**
  85. * This is the number of connections used in streaming protocol(http/ftp)
  86. */
  87. unsigned int _numStreamConnection;
  88. unsigned int _numCommand;
  89. SharedHandle<SegmentMan> _segmentMan;
  90. SharedHandle<DownloadContext> _downloadContext;
  91. SharedHandle<PieceStorage> _pieceStorage;
  92. bool _saveControlFile;
  93. SharedHandle<BtProgressInfoFile> _progressInfoFile;
  94. SharedHandle<DiskWriterFactory> _diskWriterFactory;
  95. SharedHandle<Dependency> _dependency;
  96. bool _fileAllocationEnabled;
  97. bool _preLocalFileCheckEnabled;
  98. bool _haltRequested;
  99. bool _forceHaltRequested;
  100. HaltReason _haltReason;
  101. bool _pauseRequested;
  102. std::vector<SharedHandle<PreDownloadHandler> > _preDownloadHandlers;
  103. std::vector<SharedHandle<PostDownloadHandler> > _postDownloadHandlers;
  104. std::vector<std::string> _acceptTypes;
  105. SharedHandle<URISelector> _uriSelector;
  106. Time _lastModifiedTime;
  107. unsigned int _fileNotFoundCount;
  108. // Timeout used for HTTP/FTP downloads.
  109. time_t _timeout;
  110. #ifdef ENABLE_BITTORRENT
  111. WeakHandle<BtRuntime> _btRuntime;
  112. WeakHandle<PeerStorage> _peerStorage;
  113. #endif // ENABLE_BITTORRENT
  114. // This flag just indicates that the downloaded file is not saved disk but
  115. // just sits in memory.
  116. bool _inMemoryDownload;
  117. unsigned int _maxDownloadSpeedLimit;
  118. unsigned int _maxUploadSpeedLimit;
  119. SharedHandle<URIResult> _lastUriResult;
  120. // If this download generates another downloads when completed(for
  121. // example, downloads generated by PostDownloadHandler), this field
  122. // has the GID of generated RequestGroups. empty list means there is
  123. // no such RequestGroup.
  124. std::vector<gid_t> _followedByGIDs;
  125. // If this download is a part of another download(for example,
  126. // downloading torrent file described in Metalink file), this field
  127. // has the GID of parent RequestGroup. 0 means this is a parent
  128. // RequestGroup.
  129. gid_t _belongsToGID;
  130. SharedHandle<MetadataInfo> _metadataInfo;
  131. RequestGroupMan* _requestGroupMan;
  132. int _resumeFailureCount;
  133. Logger* _logger;
  134. void validateFilename(const std::string& expectedFilename,
  135. const std::string& actualFilename) const;
  136. void initializePreDownloadHandler();
  137. void initializePostDownloadHandler();
  138. bool tryAutoFileRenaming();
  139. // Returns the result code of this RequestGroup. If the download
  140. // finished, then returns downloadresultcode::FINISHED. If the
  141. // download didn't finish and error result is available in
  142. // _uriResults, then last result code is returned. Otherwise
  143. // returns downloadresultcode::UNKNOWN_ERROR.
  144. downloadresultcode::RESULT downloadResult() const;
  145. void removeDefunctControlFile
  146. (const SharedHandle<BtProgressInfoFile>& progressInfoFile);
  147. public:
  148. // The copy of option is stored in RequestGroup object.
  149. RequestGroup(const SharedHandle<Option>& option);
  150. ~RequestGroup();
  151. const SharedHandle<SegmentMan>& getSegmentMan() const
  152. {
  153. return _segmentMan;
  154. }
  155. // Returns first bootstrap commands to initiate a download.
  156. // If this is HTTP/FTP download and file size is unknown, only 1 command
  157. // (usually, HttpInitiateConnection or FtpInitiateConnection) will be created.
  158. void createInitialCommand(std::vector<Command*>& commands,
  159. DownloadEngine* e);
  160. void createNextCommandWithAdj(std::vector<Command*>& commands,
  161. DownloadEngine* e, int numAdj);
  162. void createNextCommand(std::vector<Command*>& commands,
  163. DownloadEngine* e, unsigned int numCommand);
  164. void createNextCommand(std::vector<Command*>& commands, DownloadEngine* e);
  165. bool downloadFinished() const;
  166. bool allDownloadFinished() const;
  167. void closeFile();
  168. std::string getFirstFilePath() const;
  169. uint64_t getTotalLength() const;
  170. uint64_t getCompletedLength() const;
  171. /**
  172. * Compares expected filename with specified actualFilename.
  173. * The expected filename refers to FileEntry::getBasename() of the first
  174. * element of DownloadContext::getFileEntries()
  175. */
  176. void validateFilename(const std::string& actualFilename) const;
  177. void validateTotalLength(uint64_t expectedTotalLength,
  178. uint64_t actualTotalLength) const;
  179. void validateTotalLength(uint64_t actualTotalLength) const;
  180. void setNumConcurrentCommand(unsigned int num)
  181. {
  182. _numConcurrentCommand = num;
  183. }
  184. unsigned int getNumConcurrentCommand() const
  185. {
  186. return _numConcurrentCommand;
  187. }
  188. gid_t getGID() const
  189. {
  190. return _gid;
  191. }
  192. TransferStat calculateStat();
  193. const SharedHandle<DownloadContext>& getDownloadContext() const
  194. {
  195. return _downloadContext;
  196. }
  197. // This function also calls
  198. // downloadContext->setOwnerRequestGroup(this).
  199. void setDownloadContext(const SharedHandle<DownloadContext>& downloadContext);
  200. const SharedHandle<PieceStorage>& getPieceStorage() const
  201. {
  202. return _pieceStorage;
  203. }
  204. void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
  205. void setProgressInfoFile(const SharedHandle<BtProgressInfoFile>& progressInfoFile);
  206. void increaseStreamConnection();
  207. void decreaseStreamConnection();
  208. // Returns the number of connections used in HTTP(S)/FTP.
  209. unsigned int getNumStreamConnection() { return _numStreamConnection; }
  210. unsigned int getNumConnection() const;
  211. void increaseNumCommand();
  212. void decreaseNumCommand();
  213. unsigned int getNumCommand() const
  214. {
  215. return _numCommand;
  216. }
  217. // TODO is it better to move the following 2 methods to SingleFileDownloadContext?
  218. void setDiskWriterFactory(const SharedHandle<DiskWriterFactory>& diskWriterFactory);
  219. const SharedHandle<DiskWriterFactory>& getDiskWriterFactory() const
  220. {
  221. return _diskWriterFactory;
  222. }
  223. void setFileAllocationEnabled(bool f)
  224. {
  225. _fileAllocationEnabled = f;
  226. }
  227. bool isFileAllocationEnabled() const
  228. {
  229. return _fileAllocationEnabled;
  230. }
  231. bool needsFileAllocation() const;
  232. /**
  233. * Setting _preLocalFileCheckEnabled to false, then skip the check to see
  234. * if a file is already exists and control file exists etc.
  235. * Always open file with DiskAdaptor::initAndOpenFile()
  236. */
  237. void setPreLocalFileCheckEnabled(bool f)
  238. {
  239. _preLocalFileCheckEnabled = f;
  240. }
  241. bool isPreLocalFileCheckEnabled() const
  242. {
  243. return _preLocalFileCheckEnabled;
  244. }
  245. void setHaltRequested(bool f, HaltReason = SHUTDOWN_SIGNAL);
  246. void setForceHaltRequested(bool f, HaltReason = SHUTDOWN_SIGNAL);
  247. bool isHaltRequested() const
  248. {
  249. return _haltRequested;
  250. }
  251. bool isForceHaltRequested() const
  252. {
  253. return _forceHaltRequested;
  254. }
  255. void setPauseRequested(bool f);
  256. bool isPauseRequested() const
  257. {
  258. return _pauseRequested;
  259. }
  260. void dependsOn(const SharedHandle<Dependency>& dep);
  261. bool isDependencyResolved();
  262. void releaseRuntimeResource(DownloadEngine* e);
  263. void postDownloadProcessing(std::vector<SharedHandle<RequestGroup> >& groups);
  264. void addPostDownloadHandler(const SharedHandle<PostDownloadHandler>& handler);
  265. void clearPostDownloadHandler();
  266. void preDownloadProcessing();
  267. void addPreDownloadHandler(const SharedHandle<PreDownloadHandler>& handler);
  268. void clearPreDownloadHandler();
  269. void processCheckIntegrityEntry(std::vector<Command*>& commands,
  270. const SharedHandle<CheckIntegrityEntry>& entry,
  271. DownloadEngine* e);
  272. // Initializes _pieceStorage and _segmentMan. We guarantee that
  273. // either both of _pieceStorage and _segmentMan are initialized or
  274. // they are not.
  275. void initPieceStorage();
  276. bool downloadFinishedByFileLength();
  277. void loadAndOpenFile(const SharedHandle<BtProgressInfoFile>& progressInfoFile);
  278. void shouldCancelDownloadForSafety();
  279. void adjustFilename(const SharedHandle<BtProgressInfoFile>& infoFile);
  280. SharedHandle<DownloadResult> createDownloadResult() const;
  281. const SharedHandle<Option>& getOption() const
  282. {
  283. return _option;
  284. }
  285. void reportDownloadFinished();
  286. const std::vector<std::string>& getAcceptTypes() const
  287. {
  288. return _acceptTypes;
  289. }
  290. void addAcceptType(const std::string& type);
  291. template<typename InputIterator>
  292. void addAcceptType(InputIterator first, InputIterator last)
  293. {
  294. for(; first != last; ++first) {
  295. if(std::find(_acceptTypes.begin(), _acceptTypes.end(), *first) ==
  296. _acceptTypes.end()) {
  297. _acceptTypes.push_back(*first);
  298. }
  299. }
  300. }
  301. void removeAcceptType(const std::string& type);
  302. void setURISelector(const SharedHandle<URISelector>& uriSelector);
  303. const SharedHandle<URISelector>& getURISelector() const
  304. {
  305. return _uriSelector;
  306. }
  307. void applyLastModifiedTimeToLocalFiles();
  308. void updateLastModifiedTime(const Time& time);
  309. void increaseAndValidateFileNotFoundCount();
  310. // Just set inMemoryDownload flag true.
  311. void markInMemoryDownload();
  312. // Returns inMemoryDownload flag.
  313. bool inMemoryDownload() const
  314. {
  315. return _inMemoryDownload;
  316. }
  317. void setTimeout(time_t timeout);
  318. time_t getTimeout() const
  319. {
  320. return _timeout;
  321. }
  322. // Returns true if current download speed exceeds
  323. // _maxDownloadSpeedLimit. Always returns false if
  324. // _maxDownloadSpeedLimit == 0. Otherwise returns false.
  325. bool doesDownloadSpeedExceed();
  326. // Returns true if current upload speed exceeds
  327. // _maxUploadSpeedLimit. Always returns false if
  328. // _maxUploadSpeedLimit == 0. Otherwise returns false.
  329. bool doesUploadSpeedExceed();
  330. unsigned int getMaxDownloadSpeedLimit() const
  331. {
  332. return _maxDownloadSpeedLimit;
  333. }
  334. void setMaxDownloadSpeedLimit(unsigned int speed)
  335. {
  336. _maxDownloadSpeedLimit = speed;
  337. }
  338. unsigned int getMaxUploadSpeedLimit() const
  339. {
  340. return _maxUploadSpeedLimit;
  341. }
  342. void setMaxUploadSpeedLimit(unsigned int speed)
  343. {
  344. _maxUploadSpeedLimit = speed;
  345. }
  346. void setLastUriResult(std::string uri, downloadresultcode::RESULT result);
  347. void saveControlFile() const;
  348. void removeControlFile() const;
  349. void enableSaveControlFile() { _saveControlFile = true; }
  350. void disableSaveControlFile() { _saveControlFile = false; }
  351. template<typename InputIterator>
  352. void followedBy(InputIterator groupFirst, InputIterator groupLast)
  353. {
  354. _followedByGIDs.clear();
  355. for(; groupFirst != groupLast; ++groupFirst) {
  356. _followedByGIDs.push_back((*groupFirst)->getGID());
  357. }
  358. }
  359. const std::vector<gid_t>& followedBy() const
  360. {
  361. return _followedByGIDs;
  362. }
  363. void belongsTo(gid_t gid)
  364. {
  365. _belongsToGID = gid;
  366. }
  367. gid_t belongsTo() const
  368. {
  369. return _belongsToGID;
  370. }
  371. void setRequestGroupMan(RequestGroupMan* requestGroupMan)
  372. {
  373. _requestGroupMan = requestGroupMan;
  374. }
  375. int getResumeFailureCount() const
  376. {
  377. return _resumeFailureCount;
  378. }
  379. void increaseResumeFailureCount()
  380. {
  381. ++_resumeFailureCount;
  382. }
  383. bool p2pInvolved() const;
  384. void setMetadataInfo(const SharedHandle<MetadataInfo>& info)
  385. {
  386. _metadataInfo = info;
  387. }
  388. const SharedHandle<MetadataInfo>& getMetadataInfo() const
  389. {
  390. return _metadataInfo;
  391. }
  392. static void resetGIDCounter() { _gidCounter = 0; }
  393. static gid_t newGID();
  394. };
  395. } // namespace aria2
  396. #endif // _D_REQUEST_GROUP_H_