ConsoleStatCalc.cc 11 KB

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