ConsoleStatCalc.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 "ConsoleStatCalc.h"
  36. #ifdef HAVE_TERMIOS_H
  37. #include <termios.h>
  38. #endif // HAVE_TERMIOS_H
  39. #ifdef HAVE_SYS_IOCTL_H
  40. #include <sys/ioctl.h>
  41. #endif // HAVE_SYS_IOCTL_H
  42. #include <unistd.h>
  43. #include <cstdio>
  44. #include <iomanip>
  45. #include <iostream>
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <sstream>
  49. #include <iterator>
  50. #include "DownloadEngine.h"
  51. #include "RequestGroupMan.h"
  52. #include "RequestGroup.h"
  53. #include "FileAllocationMan.h"
  54. #include "FileAllocationEntry.h"
  55. #include "CheckIntegrityMan.h"
  56. #include "CheckIntegrityEntry.h"
  57. #include "util.h"
  58. #include "DownloadContext.h"
  59. #include "wallclock.h"
  60. #include "FileEntry.h"
  61. #include "console.h"
  62. #include "ColorizedStream.h"
  63. #include "Option.h"
  64. #ifdef ENABLE_BITTORRENT
  65. #include "bittorrent_helper.h"
  66. #include "PeerStorage.h"
  67. #include "BtRegistry.h"
  68. #endif // ENABLE_BITTORRENT
  69. namespace aria2 {
  70. std::string SizeFormatter::operator()(int64_t size) const
  71. {
  72. return format(size);
  73. }
  74. namespace {
  75. class AbbrevSizeFormatter : public SizeFormatter {
  76. protected:
  77. virtual std::string format(int64_t size) const CXX11_OVERRIDE
  78. {
  79. return util::abbrevSize(size);
  80. }
  81. };
  82. } // namespace
  83. namespace {
  84. class PlainSizeFormatter : public SizeFormatter {
  85. protected:
  86. virtual std::string format(int64_t size) const CXX11_OVERRIDE
  87. {
  88. return util::itos(size);
  89. }
  90. };
  91. } // namespace
  92. namespace {
  93. void printSizeProgress(ColorizedStream& o,
  94. const std::shared_ptr<RequestGroup>& rg,
  95. const TransferStat& stat,
  96. const SizeFormatter& sizeFormatter)
  97. {
  98. #ifdef ENABLE_BITTORRENT
  99. if (rg->isSeeder()) {
  100. o << "SEED(";
  101. if (rg->getCompletedLength() > 0) {
  102. std::streamsize oldprec = o.precision();
  103. o << std::fixed << std::setprecision(1)
  104. << ((stat.allTimeUploadLength * 10) / rg->getCompletedLength()) / 10.0
  105. << std::setprecision(oldprec) << std::resetiosflags(std::ios::fixed);
  106. }
  107. else {
  108. o << "--";
  109. }
  110. o << ")";
  111. }
  112. else
  113. #endif // ENABLE_BITTORRENT
  114. {
  115. o << sizeFormatter(rg->getCompletedLength()) << "B/"
  116. << sizeFormatter(rg->getTotalLength()) << "B";
  117. if (rg->getTotalLength() > 0) {
  118. o << "(" << 100 * rg->getCompletedLength() / rg->getTotalLength() << "%)";
  119. }
  120. }
  121. }
  122. } // namespace
  123. namespace {
  124. void printProgressCompact(ColorizedStream& o, const DownloadEngine* e,
  125. const SizeFormatter& sizeFormatter)
  126. {
  127. if (!e->getRequestGroupMan()->downloadFinished()) {
  128. NetStat& netstat = e->getRequestGroupMan()->getNetStat();
  129. int dl = netstat.calculateDownloadSpeed();
  130. int ul = netstat.calculateUploadSpeed();
  131. o << "[DL:" << colors::green << sizeFormatter(dl) << "B" << colors::clear;
  132. if (ul) {
  133. o << " UL:" << colors::cyan << sizeFormatter(ul) << "B" << colors::clear;
  134. }
  135. o << "]";
  136. }
  137. const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups();
  138. size_t cnt = 0;
  139. const size_t MAX_ITEM = 5;
  140. for (auto i = groups.begin(), eoi = groups.end(); i != eoi && cnt < MAX_ITEM;
  141. ++i, ++cnt) {
  142. const std::shared_ptr<RequestGroup>& rg = *i;
  143. TransferStat stat = rg->calculateStat();
  144. o << "[#" << GroupId::toAbbrevHex(rg->getGID()) << " ";
  145. printSizeProgress(o, rg, stat, sizeFormatter);
  146. o << "]";
  147. }
  148. if (cnt < groups.size()) {
  149. o << "(+" << groups.size() - cnt << ")";
  150. }
  151. }
  152. } // namespace
  153. namespace {
  154. void printProgress(ColorizedStream& o, const std::shared_ptr<RequestGroup>& rg,
  155. const DownloadEngine* e, const SizeFormatter& sizeFormatter)
  156. {
  157. TransferStat stat = rg->calculateStat();
  158. int eta = 0;
  159. if (rg->getTotalLength() > 0 && stat.downloadSpeed > 0) {
  160. eta =
  161. (rg->getTotalLength() - rg->getCompletedLength()) / stat.downloadSpeed;
  162. }
  163. o << "[#" << GroupId::toAbbrevHex(rg->getGID()) << " ";
  164. printSizeProgress(o, rg, stat, sizeFormatter);
  165. o << " CN:" << rg->getNumConnection();
  166. #ifdef ENABLE_BITTORRENT
  167. auto btObj = e->getBtRegistry()->get(rg->getGID());
  168. if (btObj) {
  169. const PeerSet& peers = btObj->peerStorage->getUsedPeers();
  170. o << " SD:" << countSeeder(peers.begin(), peers.end());
  171. }
  172. #endif // ENABLE_BITTORRENT
  173. if (!rg->downloadFinished()) {
  174. o << " DL:" << colors::green << sizeFormatter(stat.downloadSpeed) << "B"
  175. << colors::clear;
  176. }
  177. if (stat.sessionUploadLength > 0) {
  178. o << " UL:" << colors::cyan << sizeFormatter(stat.uploadSpeed) << "B"
  179. << colors::clear;
  180. o << "(" << sizeFormatter(stat.allTimeUploadLength) << "B)";
  181. }
  182. if (eta > 0) {
  183. o << " ETA:" << colors::yellow << util::secfmt(eta) << colors::clear;
  184. }
  185. o << "]";
  186. }
  187. } // namespace
  188. namespace {
  189. class PrintSummary {
  190. private:
  191. size_t cols_;
  192. const DownloadEngine* e_;
  193. const SizeFormatter& sizeFormatter_;
  194. public:
  195. PrintSummary(size_t cols, const DownloadEngine* e,
  196. const SizeFormatter& sizeFormatter)
  197. : cols_(cols), e_(e), sizeFormatter_(sizeFormatter)
  198. {
  199. }
  200. void operator()(const RequestGroupList::value_type& rg)
  201. {
  202. const char SEP_CHAR = '-';
  203. ColorizedStream o;
  204. printProgress(o, rg, e_, sizeFormatter_);
  205. const std::vector<std::shared_ptr<FileEntry>>& fileEntries =
  206. rg->getDownloadContext()->getFileEntries();
  207. o << "\nFILE: ";
  208. writeFilePath(fileEntries.begin(), fileEntries.end(), o,
  209. rg->inMemoryDownload());
  210. o << "\n" << std::setfill(SEP_CHAR) << std::setw(cols_) << SEP_CHAR << "\n";
  211. auto str = o.str(false);
  212. global::cout()->write(str.c_str());
  213. }
  214. };
  215. } // namespace
  216. namespace {
  217. void printProgressSummary(const RequestGroupList& groups, size_t cols,
  218. const DownloadEngine* e,
  219. const SizeFormatter& sizeFormatter)
  220. {
  221. const char SEP_CHAR = '=';
  222. time_t now;
  223. time(&now);
  224. std::stringstream o;
  225. o << " *** Download Progress Summary";
  226. {
  227. time_t now;
  228. struct tm* staticNowtmPtr;
  229. char buf[26];
  230. if (time(&now) != (time_t)-1 &&
  231. (staticNowtmPtr = localtime(&now)) != nullptr &&
  232. asctime_r(staticNowtmPtr, buf) != nullptr) {
  233. char* lfptr = strchr(buf, '\n');
  234. if (lfptr) {
  235. *lfptr = '\0';
  236. }
  237. o << " as of " << buf;
  238. }
  239. }
  240. o << " *** \n" << std::setfill(SEP_CHAR) << std::setw(cols) << SEP_CHAR
  241. << "\n";
  242. global::cout()->write(o.str().c_str());
  243. std::for_each(groups.begin(), groups.end(),
  244. PrintSummary(cols, e, sizeFormatter));
  245. }
  246. } // namespace
  247. ConsoleStatCalc::ConsoleStatCalc(std::chrono::seconds summaryInterval,
  248. bool colorOutput, bool humanReadable)
  249. : summaryInterval_(std::move(summaryInterval)),
  250. readoutVisibility_(true),
  251. truncate_(true),
  252. #ifdef __MINGW32__
  253. isTTY_(true),
  254. #else // !__MINGW32__
  255. isTTY_(isatty(STDOUT_FILENO) == 1),
  256. #endif // !__MINGW32__
  257. colorOutput_(colorOutput)
  258. {
  259. if (humanReadable) {
  260. sizeFormatter_ = make_unique<AbbrevSizeFormatter>();
  261. }
  262. else {
  263. sizeFormatter_ = make_unique<PlainSizeFormatter>();
  264. }
  265. }
  266. void ConsoleStatCalc::calculateStat(const DownloadEngine* e)
  267. {
  268. if (cp_.difference(global::wallclock()) + A2_DELTA_MILLIS <
  269. std::chrono::milliseconds(1000)) {
  270. return;
  271. }
  272. cp_ = global::wallclock();
  273. const SizeFormatter& sizeFormatter = *sizeFormatter_.get();
  274. // Some terminals (e.g., Windows terminal) prints next line when the
  275. // character reached at the last column.
  276. unsigned short int cols = 79;
  277. if (isTTY_) {
  278. #ifndef __MINGW32__
  279. #ifdef HAVE_TERMIOS_H
  280. struct winsize size;
  281. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) {
  282. cols = std::max(0, (int)size.ws_col - 1);
  283. }
  284. #endif // HAVE_TERMIOS_H
  285. #else // __MINGW32__
  286. CONSOLE_SCREEN_BUFFER_INFO info;
  287. if (::GetConsoleScreenBufferInfo(::GetStdHandle(STD_OUTPUT_HANDLE),
  288. &info)) {
  289. cols = std::max(0, info.dwSize.X - 2);
  290. }
  291. #endif // !__MINGW32__
  292. std::string line(cols, ' ');
  293. global::cout()->printf("\r%s\r", line.c_str());
  294. }
  295. ColorizedStream o;
  296. if (e->getRequestGroupMan()->countRequestGroup() > 0) {
  297. if ((summaryInterval_ > 0_s) &&
  298. lastSummaryNotified_.difference(global::wallclock()) +
  299. A2_DELTA_MILLIS >=
  300. summaryInterval_) {
  301. lastSummaryNotified_ = global::wallclock();
  302. printProgressSummary(e->getRequestGroupMan()->getRequestGroups(), cols, e,
  303. sizeFormatter);
  304. global::cout()->write("\n");
  305. global::cout()->flush();
  306. }
  307. }
  308. if (!readoutVisibility_) {
  309. return;
  310. }
  311. size_t numGroup = e->getRequestGroupMan()->countRequestGroup();
  312. const bool color = global::cout()->supportsColor() && isTTY_ && colorOutput_;
  313. if (numGroup == 1) {
  314. const std::shared_ptr<RequestGroup>& rg =
  315. *e->getRequestGroupMan()->getRequestGroups().begin();
  316. printProgress(o, rg, e, sizeFormatter);
  317. }
  318. else if (numGroup > 1) {
  319. // For more than 2 RequestGroups, use compact readout form
  320. printProgressCompact(o, e, sizeFormatter);
  321. }
  322. {
  323. auto& entry = e->getFileAllocationMan()->getPickedEntry();
  324. if (entry) {
  325. o << " [FileAlloc:#"
  326. << GroupId::toAbbrevHex(entry->getRequestGroup()->getGID()) << " "
  327. << sizeFormatter(entry->getCurrentLength()) << "B/"
  328. << sizeFormatter(entry->getTotalLength()) << "B(";
  329. if (entry->getTotalLength() > 0) {
  330. o << 100LL * entry->getCurrentLength() / entry->getTotalLength();
  331. }
  332. else {
  333. o << "--";
  334. }
  335. o << "%)]";
  336. if (e->getFileAllocationMan()->hasNext()) {
  337. o << "(+" << e->getFileAllocationMan()->countEntryInQueue() << ")";
  338. }
  339. }
  340. }
  341. {
  342. auto& entry = e->getCheckIntegrityMan()->getPickedEntry();
  343. if (entry) {
  344. o << " [Checksum:#"
  345. << GroupId::toAbbrevHex(entry->getRequestGroup()->getGID()) << " "
  346. << sizeFormatter(entry->getCurrentLength()) << "B/"
  347. << sizeFormatter(entry->getTotalLength()) << "B(";
  348. if (entry->getTotalLength() > 0) {
  349. o << 100LL * entry->getCurrentLength() / entry->getTotalLength();
  350. }
  351. else {
  352. o << "--";
  353. }
  354. o << "%)]";
  355. if (e->getCheckIntegrityMan()->hasNext()) {
  356. o << "(+" << e->getCheckIntegrityMan()->countEntryInQueue() << ")";
  357. }
  358. }
  359. }
  360. if (isTTY_) {
  361. if (truncate_) {
  362. auto str = o.str(color, cols);
  363. global::cout()->write(str.c_str());
  364. }
  365. else {
  366. auto str = o.str(color);
  367. global::cout()->write(str.c_str());
  368. }
  369. global::cout()->flush();
  370. }
  371. else {
  372. auto str = o.str(false);
  373. global::cout()->write(str.c_str());
  374. global::cout()->write("\n");
  375. }
  376. }
  377. } // namespace aria2