ConsoleStatCalc.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 << colors::cyan << "("
  119. << 100 * rg->getCompletedLength() / rg->getTotalLength() << "%)";
  120. o << colors::clear;
  121. }
  122. }
  123. }
  124. } // namespace
  125. namespace {
  126. void printProgressCompact(ColorizedStream& o, const DownloadEngine* e,
  127. const SizeFormatter& sizeFormatter)
  128. {
  129. if (!e->getRequestGroupMan()->downloadFinished()) {
  130. NetStat& netstat = e->getRequestGroupMan()->getNetStat();
  131. int dl = netstat.calculateDownloadSpeed();
  132. int ul = netstat.calculateUploadSpeed();
  133. o << colors::magenta << "[" << colors::clear << "DL:" << colors::green
  134. << sizeFormatter(dl) << "B" << colors::clear;
  135. if (ul) {
  136. o << " UL:" << colors::cyan << sizeFormatter(ul) << "B" << colors::clear;
  137. }
  138. o << colors::magenta << "]" << colors::clear;
  139. }
  140. const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups();
  141. size_t cnt = 0;
  142. const size_t MAX_ITEM = 5;
  143. for (auto i = groups.begin(), eoi = groups.end(); i != eoi && cnt < MAX_ITEM;
  144. ++i, ++cnt) {
  145. const std::shared_ptr<RequestGroup>& rg = *i;
  146. TransferStat stat = rg->calculateStat();
  147. o << colors::magenta << "[" << colors::clear << "#"
  148. << GroupId::toAbbrevHex(rg->getGID()) << " ";
  149. printSizeProgress(o, rg, stat, sizeFormatter);
  150. o << colors::magenta << "]" << colors::clear;
  151. }
  152. if (cnt < groups.size()) {
  153. o << "(+" << groups.size() - cnt << ")";
  154. }
  155. }
  156. } // namespace
  157. namespace {
  158. void printProgress(ColorizedStream& o, const std::shared_ptr<RequestGroup>& rg,
  159. const DownloadEngine* e, const SizeFormatter& sizeFormatter)
  160. {
  161. TransferStat stat = rg->calculateStat();
  162. int eta = 0;
  163. if (rg->getTotalLength() > 0 && stat.downloadSpeed > 0) {
  164. eta =
  165. (rg->getTotalLength() - rg->getCompletedLength()) / stat.downloadSpeed;
  166. }
  167. o << colors::magenta << "[" << colors::clear << "#"
  168. << GroupId::toAbbrevHex(rg->getGID()) << " ";
  169. printSizeProgress(o, rg, stat, sizeFormatter);
  170. o << " CN:" << rg->getNumConnection();
  171. #ifdef ENABLE_BITTORRENT
  172. auto btObj = e->getBtRegistry()->get(rg->getGID());
  173. if (btObj) {
  174. const PeerSet& peers = btObj->peerStorage->getUsedPeers();
  175. o << " SD:" << countSeeder(peers.begin(), peers.end());
  176. }
  177. #endif // ENABLE_BITTORRENT
  178. if (!rg->downloadFinished()) {
  179. o << " DL:" << colors::green << sizeFormatter(stat.downloadSpeed) << "B"
  180. << colors::clear;
  181. }
  182. if (stat.sessionUploadLength > 0) {
  183. o << " UL:" << colors::cyan << sizeFormatter(stat.uploadSpeed) << "B"
  184. << colors::clear;
  185. o << "(" << sizeFormatter(stat.allTimeUploadLength) << "B)";
  186. }
  187. if (eta > 0) {
  188. o << " ETA:" << colors::yellow << util::secfmt(eta) << colors::clear;
  189. }
  190. o << colors::magenta << "]" << colors::clear;
  191. }
  192. } // namespace
  193. namespace {
  194. class PrintSummary {
  195. private:
  196. size_t cols_;
  197. const DownloadEngine* e_;
  198. const SizeFormatter& sizeFormatter_;
  199. public:
  200. PrintSummary(size_t cols, const DownloadEngine* e,
  201. const SizeFormatter& sizeFormatter)
  202. : cols_(cols), e_(e), sizeFormatter_(sizeFormatter)
  203. {
  204. }
  205. void operator()(const RequestGroupList::value_type& rg)
  206. {
  207. const char SEP_CHAR = '-';
  208. ColorizedStream o;
  209. printProgress(o, rg, e_, sizeFormatter_);
  210. const std::vector<std::shared_ptr<FileEntry>>& fileEntries =
  211. rg->getDownloadContext()->getFileEntries();
  212. o << "\nFILE: ";
  213. writeFilePath(fileEntries.begin(), fileEntries.end(), o,
  214. rg->inMemoryDownload());
  215. o << "\n" << std::setfill(SEP_CHAR) << std::setw(cols_) << SEP_CHAR << "\n";
  216. auto str = o.str(false);
  217. global::cout()->write(str.c_str());
  218. }
  219. };
  220. } // namespace
  221. namespace {
  222. void printProgressSummary(const RequestGroupList& groups, size_t cols,
  223. const DownloadEngine* e,
  224. const SizeFormatter& sizeFormatter)
  225. {
  226. const char SEP_CHAR = '=';
  227. time_t now;
  228. time(&now);
  229. std::stringstream o;
  230. o << " *** Download Progress Summary";
  231. {
  232. time_t now;
  233. struct tm* staticNowtmPtr;
  234. char buf[26];
  235. if (time(&now) != (time_t)-1 &&
  236. (staticNowtmPtr = localtime(&now)) != nullptr &&
  237. asctime_r(staticNowtmPtr, buf) != nullptr) {
  238. char* lfptr = strchr(buf, '\n');
  239. if (lfptr) {
  240. *lfptr = '\0';
  241. }
  242. o << " as of " << buf;
  243. }
  244. }
  245. o << " *** \n" << std::setfill(SEP_CHAR) << std::setw(cols) << SEP_CHAR
  246. << "\n";
  247. global::cout()->write(o.str().c_str());
  248. std::for_each(groups.begin(), groups.end(),
  249. PrintSummary(cols, e, sizeFormatter));
  250. }
  251. } // namespace
  252. ConsoleStatCalc::ConsoleStatCalc(std::chrono::seconds summaryInterval,
  253. bool colorOutput, bool humanReadable)
  254. : summaryInterval_(std::move(summaryInterval)),
  255. readoutVisibility_(true),
  256. truncate_(true),
  257. #ifdef __MINGW32__
  258. isTTY_(true),
  259. #else // !__MINGW32__
  260. isTTY_(isatty(STDOUT_FILENO) == 1),
  261. #endif // !__MINGW32__
  262. colorOutput_(colorOutput)
  263. {
  264. if (humanReadable) {
  265. sizeFormatter_ = make_unique<AbbrevSizeFormatter>();
  266. }
  267. else {
  268. sizeFormatter_ = make_unique<PlainSizeFormatter>();
  269. }
  270. }
  271. void ConsoleStatCalc::calculateStat(const DownloadEngine* e)
  272. {
  273. if (cp_.difference(global::wallclock()) + A2_DELTA_MILLIS <
  274. std::chrono::milliseconds(1000)) {
  275. return;
  276. }
  277. cp_ = global::wallclock();
  278. const SizeFormatter& sizeFormatter = *sizeFormatter_.get();
  279. // Some terminals (e.g., Windows terminal) prints next line when the
  280. // character reached at the last column.
  281. unsigned short int cols = 79;
  282. if (isTTY_) {
  283. #ifndef __MINGW32__
  284. #ifdef HAVE_TERMIOS_H
  285. struct winsize size;
  286. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) {
  287. cols = std::max(0, (int)size.ws_col - 1);
  288. }
  289. #endif // HAVE_TERMIOS_H
  290. #else // __MINGW32__
  291. CONSOLE_SCREEN_BUFFER_INFO info;
  292. if (::GetConsoleScreenBufferInfo(::GetStdHandle(STD_OUTPUT_HANDLE),
  293. &info)) {
  294. cols = std::max(0, info.dwSize.X - 2);
  295. }
  296. #endif // !__MINGW32__
  297. std::string line(cols, ' ');
  298. global::cout()->printf("\r%s\r", line.c_str());
  299. }
  300. ColorizedStream o;
  301. if (e->getRequestGroupMan()->countRequestGroup() > 0) {
  302. if ((summaryInterval_ > 0_s) &&
  303. lastSummaryNotified_.difference(global::wallclock()) +
  304. A2_DELTA_MILLIS >=
  305. summaryInterval_) {
  306. lastSummaryNotified_ = global::wallclock();
  307. printProgressSummary(e->getRequestGroupMan()->getRequestGroups(), cols, e,
  308. sizeFormatter);
  309. global::cout()->write("\n");
  310. global::cout()->flush();
  311. }
  312. }
  313. if (!readoutVisibility_) {
  314. return;
  315. }
  316. size_t numGroup = e->getRequestGroupMan()->countRequestGroup();
  317. const bool color = global::cout()->supportsColor() && isTTY_ && colorOutput_;
  318. if (numGroup == 1) {
  319. const std::shared_ptr<RequestGroup>& rg =
  320. *e->getRequestGroupMan()->getRequestGroups().begin();
  321. printProgress(o, rg, e, sizeFormatter);
  322. }
  323. else if (numGroup > 1) {
  324. // For more than 2 RequestGroups, use compact readout form
  325. printProgressCompact(o, e, sizeFormatter);
  326. }
  327. {
  328. auto& entry = e->getFileAllocationMan()->getPickedEntry();
  329. if (entry) {
  330. o << " [FileAlloc:#"
  331. << GroupId::toAbbrevHex(entry->getRequestGroup()->getGID()) << " "
  332. << sizeFormatter(entry->getCurrentLength()) << "B/"
  333. << sizeFormatter(entry->getTotalLength()) << "B(";
  334. if (entry->getTotalLength() > 0) {
  335. o << 100LL * entry->getCurrentLength() / entry->getTotalLength();
  336. }
  337. else {
  338. o << "--";
  339. }
  340. o << "%)]";
  341. if (e->getFileAllocationMan()->hasNext()) {
  342. o << "(+" << e->getFileAllocationMan()->countEntryInQueue() << ")";
  343. }
  344. }
  345. }
  346. {
  347. auto& entry = e->getCheckIntegrityMan()->getPickedEntry();
  348. if (entry) {
  349. o << " [Checksum:#"
  350. << GroupId::toAbbrevHex(entry->getRequestGroup()->getGID()) << " "
  351. << sizeFormatter(entry->getCurrentLength()) << "B/"
  352. << sizeFormatter(entry->getTotalLength()) << "B(";
  353. if (entry->getTotalLength() > 0) {
  354. o << 100LL * entry->getCurrentLength() / entry->getTotalLength();
  355. }
  356. else {
  357. o << "--";
  358. }
  359. o << "%)]";
  360. if (e->getCheckIntegrityMan()->hasNext()) {
  361. o << "(+" << e->getCheckIntegrityMan()->countEntryInQueue() << ")";
  362. }
  363. }
  364. }
  365. if (isTTY_) {
  366. if (truncate_) {
  367. auto str = o.str(color, cols);
  368. global::cout()->write(str.c_str());
  369. }
  370. else {
  371. auto str = o.str(color);
  372. global::cout()->write(str.c_str());
  373. }
  374. global::cout()->flush();
  375. }
  376. else {
  377. auto str = o.str(false);
  378. global::cout()->write(str.c_str());
  379. global::cout()->write("\n");
  380. }
  381. }
  382. } // namespace aria2