acquire.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: acquire.cc,v 1.50 2004/03/17 05:17:11 mdz Exp $
  4. /* ######################################################################
  5. Acquire - File Acquiration
  6. The core element for the schedual system is the concept of a named
  7. queue. Each queue is unique and each queue has a name derived from the
  8. URI. The degree of paralization can be controled by how the queue
  9. name is derived from the URI.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <apt-pkg/acquire.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/acquire-worker.h>
  16. #include <apt-pkg/configuration.h>
  17. #include <apt-pkg/error.h>
  18. #include <apt-pkg/strutl.h>
  19. #include <apt-pkg/fileutl.h>
  20. #include <apti18n.h>
  21. #include <iostream>
  22. #include <sstream>
  23. #include <stdio.h>
  24. #include <dirent.h>
  25. #include <sys/time.h>
  26. #include <errno.h>
  27. /*}}}*/
  28. using namespace std;
  29. // Acquire::pkgAcquire - Constructor /*{{{*/
  30. // ---------------------------------------------------------------------
  31. /* We grab some runtime state from the configuration space */
  32. pkgAcquire::pkgAcquire() : Queues(0), Workers(0), Configs(0), Log(NULL), ToFetch(0),
  33. Debug(_config->FindB("Debug::pkgAcquire",false)),
  34. Running(false), LockFD(-1)
  35. {
  36. string const Mode = _config->Find("Acquire::Queue-Mode","host");
  37. if (strcasecmp(Mode.c_str(),"host") == 0)
  38. QueueMode = QueueHost;
  39. if (strcasecmp(Mode.c_str(),"access") == 0)
  40. QueueMode = QueueAccess;
  41. }
  42. pkgAcquire::pkgAcquire(pkgAcquireStatus *Progress) : Queues(0), Workers(0),
  43. Configs(0), Log(Progress), ToFetch(0),
  44. Debug(_config->FindB("Debug::pkgAcquire",false)),
  45. Running(false), LockFD(-1)
  46. {
  47. string const Mode = _config->Find("Acquire::Queue-Mode","host");
  48. if (strcasecmp(Mode.c_str(),"host") == 0)
  49. QueueMode = QueueHost;
  50. if (strcasecmp(Mode.c_str(),"access") == 0)
  51. QueueMode = QueueAccess;
  52. Setup(Progress, "");
  53. }
  54. /*}}}*/
  55. // Acquire::Setup - Delayed Constructor /*{{{*/
  56. // ---------------------------------------------------------------------
  57. /* Do everything needed to be a complete Acquire object and report the
  58. success (or failure) back so the user knows that something is wrong… */
  59. bool pkgAcquire::Setup(pkgAcquireStatus *Progress, string const &Lock)
  60. {
  61. Log = Progress;
  62. // check for existence and possibly create auxiliary directories
  63. string const listDir = _config->FindDir("Dir::State::lists");
  64. string const partialListDir = listDir + "partial/";
  65. string const archivesDir = _config->FindDir("Dir::Cache::Archives");
  66. string const partialArchivesDir = archivesDir + "partial/";
  67. if (CheckDirectory(_config->FindDir("Dir::State"), partialListDir) == false &&
  68. CheckDirectory(listDir, partialListDir) == false)
  69. return _error->Errno("Acquire", _("List directory %spartial is missing."), listDir.c_str());
  70. if (CheckDirectory(_config->FindDir("Dir::Cache"), partialArchivesDir) == false &&
  71. CheckDirectory(archivesDir, partialArchivesDir) == false)
  72. return _error->Errno("Acquire", _("Archives directory %spartial is missing."), archivesDir.c_str());
  73. if (Lock.empty() == true || _config->FindB("Debug::NoLocking", false) == true)
  74. return true;
  75. // Lock the directory this acquire object will work in
  76. LockFD = GetLock(flCombine(Lock, "lock"));
  77. if (LockFD == -1)
  78. return _error->Error(_("Unable to lock directory %s"), Lock.c_str());
  79. return true;
  80. }
  81. /*}}}*/
  82. // Acquire::CheckDirectory - ensure that the given directory exists /*{{{*/
  83. // ---------------------------------------------------------------------
  84. /* a small wrapper around CreateDirectory to check if it exists and to
  85. remove the trailing "/apt/" from the parent directory if needed */
  86. bool pkgAcquire::CheckDirectory(string const &Parent, string const &Path) const
  87. {
  88. if (DirectoryExists(Path) == true)
  89. return true;
  90. size_t const len = Parent.size();
  91. if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5)
  92. {
  93. if (CreateDirectory(Parent.substr(0,len-5), Path) == true)
  94. return true;
  95. }
  96. else if (CreateDirectory(Parent, Path) == true)
  97. return true;
  98. return false;
  99. }
  100. /*}}}*/
  101. // Acquire::~pkgAcquire - Destructor /*{{{*/
  102. // ---------------------------------------------------------------------
  103. /* Free our memory, clean up the queues (destroy the workers) */
  104. pkgAcquire::~pkgAcquire()
  105. {
  106. Shutdown();
  107. if (LockFD != -1)
  108. close(LockFD);
  109. while (Configs != 0)
  110. {
  111. MethodConfig *Jnk = Configs;
  112. Configs = Configs->Next;
  113. delete Jnk;
  114. }
  115. }
  116. /*}}}*/
  117. // Acquire::Shutdown - Clean out the acquire object /*{{{*/
  118. // ---------------------------------------------------------------------
  119. /* */
  120. void pkgAcquire::Shutdown()
  121. {
  122. while (Items.size() != 0)
  123. {
  124. if (Items[0]->Status == Item::StatFetching)
  125. Items[0]->Status = Item::StatError;
  126. delete Items[0];
  127. }
  128. while (Queues != 0)
  129. {
  130. Queue *Jnk = Queues;
  131. Queues = Queues->Next;
  132. delete Jnk;
  133. }
  134. }
  135. /*}}}*/
  136. // Acquire::Add - Add a new item /*{{{*/
  137. // ---------------------------------------------------------------------
  138. /* This puts an item on the acquire list. This list is mainly for tracking
  139. item status */
  140. void pkgAcquire::Add(Item *Itm)
  141. {
  142. Items.push_back(Itm);
  143. }
  144. /*}}}*/
  145. // Acquire::Remove - Remove a item /*{{{*/
  146. // ---------------------------------------------------------------------
  147. /* Remove an item from the acquire list. This is usually not used.. */
  148. void pkgAcquire::Remove(Item *Itm)
  149. {
  150. Dequeue(Itm);
  151. for (ItemIterator I = Items.begin(); I != Items.end();)
  152. {
  153. if (*I == Itm)
  154. {
  155. Items.erase(I);
  156. I = Items.begin();
  157. }
  158. else
  159. I++;
  160. }
  161. }
  162. /*}}}*/
  163. // Acquire::Add - Add a worker /*{{{*/
  164. // ---------------------------------------------------------------------
  165. /* A list of workers is kept so that the select loop can direct their FD
  166. usage. */
  167. void pkgAcquire::Add(Worker *Work)
  168. {
  169. Work->NextAcquire = Workers;
  170. Workers = Work;
  171. }
  172. /*}}}*/
  173. // Acquire::Remove - Remove a worker /*{{{*/
  174. // ---------------------------------------------------------------------
  175. /* A worker has died. This can not be done while the select loop is running
  176. as it would require that RunFds could handling a changing list state and
  177. it cant.. */
  178. void pkgAcquire::Remove(Worker *Work)
  179. {
  180. if (Running == true)
  181. abort();
  182. Worker **I = &Workers;
  183. for (; *I != 0;)
  184. {
  185. if (*I == Work)
  186. *I = (*I)->NextAcquire;
  187. else
  188. I = &(*I)->NextAcquire;
  189. }
  190. }
  191. /*}}}*/
  192. // Acquire::Enqueue - Queue an URI for fetching /*{{{*/
  193. // ---------------------------------------------------------------------
  194. /* This is the entry point for an item. An item calls this function when
  195. it is constructed which creates a queue (based on the current queue
  196. mode) and puts the item in that queue. If the system is running then
  197. the queue might be started. */
  198. void pkgAcquire::Enqueue(ItemDesc &Item)
  199. {
  200. // Determine which queue to put the item in
  201. const MethodConfig *Config;
  202. string Name = QueueName(Item.URI,Config);
  203. if (Name.empty() == true)
  204. return;
  205. // Find the queue structure
  206. Queue *I = Queues;
  207. for (; I != 0 && I->Name != Name; I = I->Next);
  208. if (I == 0)
  209. {
  210. I = new Queue(Name,this);
  211. I->Next = Queues;
  212. Queues = I;
  213. if (Running == true)
  214. I->Startup();
  215. }
  216. // See if this is a local only URI
  217. if (Config->LocalOnly == true && Item.Owner->Complete == false)
  218. Item.Owner->Local = true;
  219. Item.Owner->Status = Item::StatIdle;
  220. // Queue it into the named queue
  221. if(I->Enqueue(Item))
  222. ToFetch++;
  223. // Some trace stuff
  224. if (Debug == true)
  225. {
  226. clog << "Fetching " << Item.URI << endl;
  227. clog << " to " << Item.Owner->DestFile << endl;
  228. clog << " Queue is: " << Name << endl;
  229. }
  230. }
  231. /*}}}*/
  232. // Acquire::Dequeue - Remove an item from all queues /*{{{*/
  233. // ---------------------------------------------------------------------
  234. /* This is called when an item is finished being fetched. It removes it
  235. from all the queues */
  236. void pkgAcquire::Dequeue(Item *Itm)
  237. {
  238. Queue *I = Queues;
  239. bool Res = false;
  240. for (; I != 0; I = I->Next)
  241. Res |= I->Dequeue(Itm);
  242. if (Debug == true)
  243. clog << "Dequeuing " << Itm->DestFile << endl;
  244. if (Res == true)
  245. ToFetch--;
  246. }
  247. /*}}}*/
  248. // Acquire::QueueName - Return the name of the queue for this URI /*{{{*/
  249. // ---------------------------------------------------------------------
  250. /* The string returned depends on the configuration settings and the
  251. method parameters. Given something like http://foo.org/bar it can
  252. return http://foo.org or http */
  253. string pkgAcquire::QueueName(string Uri,MethodConfig const *&Config)
  254. {
  255. URI U(Uri);
  256. Config = GetConfig(U.Access);
  257. if (Config == 0)
  258. return string();
  259. /* Single-Instance methods get exactly one queue per URI. This is
  260. also used for the Access queue method */
  261. if (Config->SingleInstance == true || QueueMode == QueueAccess)
  262. return U.Access;
  263. return U.Access + ':' + U.Host;
  264. }
  265. /*}}}*/
  266. // Acquire::GetConfig - Fetch the configuration information /*{{{*/
  267. // ---------------------------------------------------------------------
  268. /* This locates the configuration structure for an access method. If
  269. a config structure cannot be found a Worker will be created to
  270. retrieve it */
  271. pkgAcquire::MethodConfig *pkgAcquire::GetConfig(string Access)
  272. {
  273. // Search for an existing config
  274. MethodConfig *Conf;
  275. for (Conf = Configs; Conf != 0; Conf = Conf->Next)
  276. if (Conf->Access == Access)
  277. return Conf;
  278. // Create the new config class
  279. Conf = new MethodConfig;
  280. Conf->Access = Access;
  281. Conf->Next = Configs;
  282. Configs = Conf;
  283. // Create the worker to fetch the configuration
  284. Worker Work(Conf);
  285. if (Work.Start() == false)
  286. return 0;
  287. /* if a method uses DownloadLimit, we switch to SingleInstance mode */
  288. if(_config->FindI("Acquire::"+Access+"::Dl-Limit",0) > 0)
  289. Conf->SingleInstance = true;
  290. return Conf;
  291. }
  292. /*}}}*/
  293. // Acquire::SetFds - Deal with readable FDs /*{{{*/
  294. // ---------------------------------------------------------------------
  295. /* Collect FDs that have activity monitors into the fd sets */
  296. void pkgAcquire::SetFds(int &Fd,fd_set *RSet,fd_set *WSet)
  297. {
  298. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  299. {
  300. if (I->InReady == true && I->InFd >= 0)
  301. {
  302. if (Fd < I->InFd)
  303. Fd = I->InFd;
  304. FD_SET(I->InFd,RSet);
  305. }
  306. if (I->OutReady == true && I->OutFd >= 0)
  307. {
  308. if (Fd < I->OutFd)
  309. Fd = I->OutFd;
  310. FD_SET(I->OutFd,WSet);
  311. }
  312. }
  313. }
  314. /*}}}*/
  315. // Acquire::RunFds - Deal with active FDs /*{{{*/
  316. // ---------------------------------------------------------------------
  317. /* Dispatch active FDs over to the proper workers. It is very important
  318. that a worker never be erased while this is running! The queue class
  319. should never erase a worker except during shutdown processing. */
  320. void pkgAcquire::RunFds(fd_set *RSet,fd_set *WSet)
  321. {
  322. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  323. {
  324. if (I->InFd >= 0 && FD_ISSET(I->InFd,RSet) != 0)
  325. I->InFdReady();
  326. if (I->OutFd >= 0 && FD_ISSET(I->OutFd,WSet) != 0)
  327. I->OutFdReady();
  328. }
  329. }
  330. /*}}}*/
  331. // Acquire::Run - Run the fetch sequence /*{{{*/
  332. // ---------------------------------------------------------------------
  333. /* This runs the queues. It manages a select loop for all of the
  334. Worker tasks. The workers interact with the queues and items to
  335. manage the actual fetch. */
  336. pkgAcquire::RunResult pkgAcquire::Run(int PulseIntervall)
  337. {
  338. Running = true;
  339. for (Queue *I = Queues; I != 0; I = I->Next)
  340. I->Startup();
  341. if (Log != 0)
  342. Log->Start();
  343. bool WasCancelled = false;
  344. // Run till all things have been acquired
  345. struct timeval tv;
  346. tv.tv_sec = 0;
  347. tv.tv_usec = PulseIntervall;
  348. while (ToFetch > 0)
  349. {
  350. fd_set RFds;
  351. fd_set WFds;
  352. int Highest = 0;
  353. FD_ZERO(&RFds);
  354. FD_ZERO(&WFds);
  355. SetFds(Highest,&RFds,&WFds);
  356. int Res;
  357. do
  358. {
  359. Res = select(Highest+1,&RFds,&WFds,0,&tv);
  360. }
  361. while (Res < 0 && errno == EINTR);
  362. if (Res < 0)
  363. {
  364. _error->Errno("select","Select has failed");
  365. break;
  366. }
  367. RunFds(&RFds,&WFds);
  368. if (_error->PendingError() == true)
  369. break;
  370. // Timeout, notify the log class
  371. if (Res == 0 || (Log != 0 && Log->Update == true))
  372. {
  373. tv.tv_usec = PulseIntervall;
  374. for (Worker *I = Workers; I != 0; I = I->NextAcquire)
  375. I->Pulse();
  376. if (Log != 0 && Log->Pulse(this) == false)
  377. {
  378. WasCancelled = true;
  379. break;
  380. }
  381. }
  382. }
  383. if (Log != 0)
  384. Log->Stop();
  385. // Shut down the acquire bits
  386. Running = false;
  387. for (Queue *I = Queues; I != 0; I = I->Next)
  388. I->Shutdown(false);
  389. // Shut down the items
  390. for (ItemIterator I = Items.begin(); I != Items.end(); I++)
  391. (*I)->Finished();
  392. if (_error->PendingError())
  393. return Failed;
  394. if (WasCancelled)
  395. return Cancelled;
  396. return Continue;
  397. }
  398. /*}}}*/
  399. // Acquire::Bump - Called when an item is dequeued /*{{{*/
  400. // ---------------------------------------------------------------------
  401. /* This routine bumps idle queues in hopes that they will be able to fetch
  402. the dequeued item */
  403. void pkgAcquire::Bump()
  404. {
  405. for (Queue *I = Queues; I != 0; I = I->Next)
  406. I->Bump();
  407. }
  408. /*}}}*/
  409. // Acquire::WorkerStep - Step to the next worker /*{{{*/
  410. // ---------------------------------------------------------------------
  411. /* Not inlined to advoid including acquire-worker.h */
  412. pkgAcquire::Worker *pkgAcquire::WorkerStep(Worker *I)
  413. {
  414. return I->NextAcquire;
  415. };
  416. /*}}}*/
  417. // Acquire::Clean - Cleans a directory /*{{{*/
  418. // ---------------------------------------------------------------------
  419. /* This is a bit simplistic, it looks at every file in the dir and sees
  420. if it is part of the download set. */
  421. bool pkgAcquire::Clean(string Dir)
  422. {
  423. DIR *D = opendir(Dir.c_str());
  424. if (D == 0)
  425. return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  426. string StartDir = SafeGetCWD();
  427. if (chdir(Dir.c_str()) != 0)
  428. {
  429. closedir(D);
  430. return _error->Errno("chdir",_("Unable to change to %s"),Dir.c_str());
  431. }
  432. for (struct dirent *Dir = readdir(D); Dir != 0; Dir = readdir(D))
  433. {
  434. // Skip some files..
  435. if (strcmp(Dir->d_name,"lock") == 0 ||
  436. strcmp(Dir->d_name,"partial") == 0 ||
  437. strcmp(Dir->d_name,".") == 0 ||
  438. strcmp(Dir->d_name,"..") == 0)
  439. continue;
  440. // Look in the get list
  441. ItemCIterator I = Items.begin();
  442. for (; I != Items.end(); I++)
  443. if (flNotDir((*I)->DestFile) == Dir->d_name)
  444. break;
  445. // Nothing found, nuke it
  446. if (I == Items.end())
  447. unlink(Dir->d_name);
  448. };
  449. closedir(D);
  450. if (chdir(StartDir.c_str()) != 0)
  451. return _error->Errno("chdir",_("Unable to change to %s"),StartDir.c_str());
  452. return true;
  453. }
  454. /*}}}*/
  455. // Acquire::TotalNeeded - Number of bytes to fetch /*{{{*/
  456. // ---------------------------------------------------------------------
  457. /* This is the total number of bytes needed */
  458. double pkgAcquire::TotalNeeded()
  459. {
  460. double Total = 0;
  461. for (ItemCIterator I = ItemsBegin(); I != ItemsEnd(); I++)
  462. Total += (*I)->FileSize;
  463. return Total;
  464. }
  465. /*}}}*/
  466. // Acquire::FetchNeeded - Number of bytes needed to get /*{{{*/
  467. // ---------------------------------------------------------------------
  468. /* This is the number of bytes that is not local */
  469. double pkgAcquire::FetchNeeded()
  470. {
  471. double Total = 0;
  472. for (ItemCIterator I = ItemsBegin(); I != ItemsEnd(); I++)
  473. if ((*I)->Local == false)
  474. Total += (*I)->FileSize;
  475. return Total;
  476. }
  477. /*}}}*/
  478. // Acquire::PartialPresent - Number of partial bytes we already have /*{{{*/
  479. // ---------------------------------------------------------------------
  480. /* This is the number of bytes that is not local */
  481. double pkgAcquire::PartialPresent()
  482. {
  483. double Total = 0;
  484. for (ItemCIterator I = ItemsBegin(); I != ItemsEnd(); I++)
  485. if ((*I)->Local == false)
  486. Total += (*I)->PartialSize;
  487. return Total;
  488. }
  489. /*}}}*/
  490. // Acquire::UriBegin - Start iterator for the uri list /*{{{*/
  491. // ---------------------------------------------------------------------
  492. /* */
  493. pkgAcquire::UriIterator pkgAcquire::UriBegin()
  494. {
  495. return UriIterator(Queues);
  496. }
  497. /*}}}*/
  498. // Acquire::UriEnd - End iterator for the uri list /*{{{*/
  499. // ---------------------------------------------------------------------
  500. /* */
  501. pkgAcquire::UriIterator pkgAcquire::UriEnd()
  502. {
  503. return UriIterator(0);
  504. }
  505. /*}}}*/
  506. // Acquire::MethodConfig::MethodConfig - Constructor /*{{{*/
  507. // ---------------------------------------------------------------------
  508. /* */
  509. pkgAcquire::MethodConfig::MethodConfig()
  510. {
  511. SingleInstance = false;
  512. Pipeline = false;
  513. SendConfig = false;
  514. LocalOnly = false;
  515. Removable = false;
  516. Next = 0;
  517. }
  518. /*}}}*/
  519. // Queue::Queue - Constructor /*{{{*/
  520. // ---------------------------------------------------------------------
  521. /* */
  522. pkgAcquire::Queue::Queue(string Name,pkgAcquire *Owner) : Name(Name),
  523. Owner(Owner)
  524. {
  525. Items = 0;
  526. Next = 0;
  527. Workers = 0;
  528. MaxPipeDepth = 1;
  529. PipeDepth = 0;
  530. }
  531. /*}}}*/
  532. // Queue::~Queue - Destructor /*{{{*/
  533. // ---------------------------------------------------------------------
  534. /* */
  535. pkgAcquire::Queue::~Queue()
  536. {
  537. Shutdown(true);
  538. while (Items != 0)
  539. {
  540. QItem *Jnk = Items;
  541. Items = Items->Next;
  542. delete Jnk;
  543. }
  544. }
  545. /*}}}*/
  546. // Queue::Enqueue - Queue an item to the queue /*{{{*/
  547. // ---------------------------------------------------------------------
  548. /* */
  549. bool pkgAcquire::Queue::Enqueue(ItemDesc &Item)
  550. {
  551. QItem **I = &Items;
  552. // move to the end of the queue and check for duplicates here
  553. for (; *I != 0; I = &(*I)->Next)
  554. if (Item.URI == (*I)->URI)
  555. {
  556. Item.Owner->Status = Item::StatDone;
  557. return false;
  558. }
  559. // Create a new item
  560. QItem *Itm = new QItem;
  561. *Itm = Item;
  562. Itm->Next = 0;
  563. *I = Itm;
  564. Item.Owner->QueueCounter++;
  565. if (Items->Next == 0)
  566. Cycle();
  567. return true;
  568. }
  569. /*}}}*/
  570. // Queue::Dequeue - Remove an item from the queue /*{{{*/
  571. // ---------------------------------------------------------------------
  572. /* We return true if we hit something */
  573. bool pkgAcquire::Queue::Dequeue(Item *Owner)
  574. {
  575. if (Owner->Status == pkgAcquire::Item::StatFetching)
  576. return _error->Error("Tried to dequeue a fetching object");
  577. bool Res = false;
  578. QItem **I = &Items;
  579. for (; *I != 0;)
  580. {
  581. if ((*I)->Owner == Owner)
  582. {
  583. QItem *Jnk= *I;
  584. *I = (*I)->Next;
  585. Owner->QueueCounter--;
  586. delete Jnk;
  587. Res = true;
  588. }
  589. else
  590. I = &(*I)->Next;
  591. }
  592. return Res;
  593. }
  594. /*}}}*/
  595. // Queue::Startup - Start the worker processes /*{{{*/
  596. // ---------------------------------------------------------------------
  597. /* It is possible for this to be called with a pre-existing set of
  598. workers. */
  599. bool pkgAcquire::Queue::Startup()
  600. {
  601. if (Workers == 0)
  602. {
  603. URI U(Name);
  604. pkgAcquire::MethodConfig *Cnf = Owner->GetConfig(U.Access);
  605. if (Cnf == 0)
  606. return false;
  607. Workers = new Worker(this,Cnf,Owner->Log);
  608. Owner->Add(Workers);
  609. if (Workers->Start() == false)
  610. return false;
  611. /* When pipelining we commit 10 items. This needs to change when we
  612. added other source retry to have cycle maintain a pipeline depth
  613. on its own. */
  614. if (Cnf->Pipeline == true)
  615. MaxPipeDepth = _config->FindI("Acquire::Max-Pipeline-Depth",10);
  616. else
  617. MaxPipeDepth = 1;
  618. }
  619. return Cycle();
  620. }
  621. /*}}}*/
  622. // Queue::Shutdown - Shutdown the worker processes /*{{{*/
  623. // ---------------------------------------------------------------------
  624. /* If final is true then all workers are eliminated, otherwise only workers
  625. that do not need cleanup are removed */
  626. bool pkgAcquire::Queue::Shutdown(bool Final)
  627. {
  628. // Delete all of the workers
  629. pkgAcquire::Worker **Cur = &Workers;
  630. while (*Cur != 0)
  631. {
  632. pkgAcquire::Worker *Jnk = *Cur;
  633. if (Final == true || Jnk->GetConf()->NeedsCleanup == false)
  634. {
  635. *Cur = Jnk->NextQueue;
  636. Owner->Remove(Jnk);
  637. delete Jnk;
  638. }
  639. else
  640. Cur = &(*Cur)->NextQueue;
  641. }
  642. return true;
  643. }
  644. /*}}}*/
  645. // Queue::FindItem - Find a URI in the item list /*{{{*/
  646. // ---------------------------------------------------------------------
  647. /* */
  648. pkgAcquire::Queue::QItem *pkgAcquire::Queue::FindItem(string URI,pkgAcquire::Worker *Owner)
  649. {
  650. for (QItem *I = Items; I != 0; I = I->Next)
  651. if (I->URI == URI && I->Worker == Owner)
  652. return I;
  653. return 0;
  654. }
  655. /*}}}*/
  656. // Queue::ItemDone - Item has been completed /*{{{*/
  657. // ---------------------------------------------------------------------
  658. /* The worker signals this which causes the item to be removed from the
  659. queue. If this is the last queue instance then it is removed from the
  660. main queue too.*/
  661. bool pkgAcquire::Queue::ItemDone(QItem *Itm)
  662. {
  663. PipeDepth--;
  664. if (Itm->Owner->Status == pkgAcquire::Item::StatFetching)
  665. Itm->Owner->Status = pkgAcquire::Item::StatDone;
  666. if (Itm->Owner->QueueCounter <= 1)
  667. Owner->Dequeue(Itm->Owner);
  668. else
  669. {
  670. Dequeue(Itm->Owner);
  671. Owner->Bump();
  672. }
  673. return Cycle();
  674. }
  675. /*}}}*/
  676. // Queue::Cycle - Queue new items into the method /*{{{*/
  677. // ---------------------------------------------------------------------
  678. /* This locates a new idle item and sends it to the worker. If pipelining
  679. is enabled then it keeps the pipe full. */
  680. bool pkgAcquire::Queue::Cycle()
  681. {
  682. if (Items == 0 || Workers == 0)
  683. return true;
  684. if (PipeDepth < 0)
  685. return _error->Error("Pipedepth failure");
  686. // Look for a queable item
  687. QItem *I = Items;
  688. while (PipeDepth < (signed)MaxPipeDepth)
  689. {
  690. for (; I != 0; I = I->Next)
  691. if (I->Owner->Status == pkgAcquire::Item::StatIdle)
  692. break;
  693. // Nothing to do, queue is idle.
  694. if (I == 0)
  695. return true;
  696. I->Worker = Workers;
  697. I->Owner->Status = pkgAcquire::Item::StatFetching;
  698. PipeDepth++;
  699. if (Workers->QueueItem(I) == false)
  700. return false;
  701. }
  702. return true;
  703. }
  704. /*}}}*/
  705. // Queue::Bump - Fetch any pending objects if we are idle /*{{{*/
  706. // ---------------------------------------------------------------------
  707. /* This is called when an item in multiple queues is dequeued */
  708. void pkgAcquire::Queue::Bump()
  709. {
  710. Cycle();
  711. }
  712. /*}}}*/
  713. // AcquireStatus::pkgAcquireStatus - Constructor /*{{{*/
  714. // ---------------------------------------------------------------------
  715. /* */
  716. pkgAcquireStatus::pkgAcquireStatus() : Update(true), MorePulses(false)
  717. {
  718. Start();
  719. }
  720. /*}}}*/
  721. // AcquireStatus::Pulse - Called periodically /*{{{*/
  722. // ---------------------------------------------------------------------
  723. /* This computes some internal state variables for the derived classes to
  724. use. It generates the current downloaded bytes and total bytes to download
  725. as well as the current CPS estimate. */
  726. bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
  727. {
  728. TotalBytes = 0;
  729. CurrentBytes = 0;
  730. TotalItems = 0;
  731. CurrentItems = 0;
  732. // Compute the total number of bytes to fetch
  733. unsigned int Unknown = 0;
  734. unsigned int Count = 0;
  735. for (pkgAcquire::ItemCIterator I = Owner->ItemsBegin(); I != Owner->ItemsEnd();
  736. I++, Count++)
  737. {
  738. TotalItems++;
  739. if ((*I)->Status == pkgAcquire::Item::StatDone)
  740. CurrentItems++;
  741. // Totally ignore local items
  742. if ((*I)->Local == true)
  743. continue;
  744. TotalBytes += (*I)->FileSize;
  745. if ((*I)->Complete == true)
  746. CurrentBytes += (*I)->FileSize;
  747. if ((*I)->FileSize == 0 && (*I)->Complete == false)
  748. Unknown++;
  749. }
  750. // Compute the current completion
  751. unsigned long ResumeSize = 0;
  752. for (pkgAcquire::Worker *I = Owner->WorkersBegin(); I != 0;
  753. I = Owner->WorkerStep(I))
  754. if (I->CurrentItem != 0 && I->CurrentItem->Owner->Complete == false)
  755. {
  756. CurrentBytes += I->CurrentSize;
  757. ResumeSize += I->ResumePoint;
  758. // Files with unknown size always have 100% completion
  759. if (I->CurrentItem->Owner->FileSize == 0 &&
  760. I->CurrentItem->Owner->Complete == false)
  761. TotalBytes += I->CurrentSize;
  762. }
  763. // Normalize the figures and account for unknown size downloads
  764. if (TotalBytes <= 0)
  765. TotalBytes = 1;
  766. if (Unknown == Count)
  767. TotalBytes = Unknown;
  768. // Wha?! Is not supposed to happen.
  769. if (CurrentBytes > TotalBytes)
  770. CurrentBytes = TotalBytes;
  771. // Compute the CPS
  772. struct timeval NewTime;
  773. gettimeofday(&NewTime,0);
  774. if ((NewTime.tv_sec - Time.tv_sec == 6 && NewTime.tv_usec > Time.tv_usec) ||
  775. NewTime.tv_sec - Time.tv_sec > 6)
  776. {
  777. double Delta = NewTime.tv_sec - Time.tv_sec +
  778. (NewTime.tv_usec - Time.tv_usec)/1000000.0;
  779. // Compute the CPS value
  780. if (Delta < 0.01)
  781. CurrentCPS = 0;
  782. else
  783. CurrentCPS = ((CurrentBytes - ResumeSize) - LastBytes)/Delta;
  784. LastBytes = CurrentBytes - ResumeSize;
  785. ElapsedTime = (unsigned long)Delta;
  786. Time = NewTime;
  787. }
  788. int fd = _config->FindI("APT::Status-Fd",-1);
  789. if(fd > 0)
  790. {
  791. ostringstream status;
  792. char msg[200];
  793. long i = CurrentItems < TotalItems ? CurrentItems + 1 : CurrentItems;
  794. unsigned long ETA =
  795. (unsigned long)((TotalBytes - CurrentBytes) / CurrentCPS);
  796. // only show the ETA if it makes sense
  797. if (ETA > 0 && ETA < 172800 /* two days */ )
  798. snprintf(msg,sizeof(msg), _("Retrieving file %li of %li (%s remaining)"), i, TotalItems, TimeToStr(ETA).c_str());
  799. else
  800. snprintf(msg,sizeof(msg), _("Retrieving file %li of %li"), i, TotalItems);
  801. // build the status str
  802. status << "dlstatus:" << i
  803. << ":" << (CurrentBytes/float(TotalBytes)*100.0)
  804. << ":" << msg
  805. << endl;
  806. write(fd, status.str().c_str(), status.str().size());
  807. }
  808. return true;
  809. }
  810. /*}}}*/
  811. // AcquireStatus::Start - Called when the download is started /*{{{*/
  812. // ---------------------------------------------------------------------
  813. /* We just reset the counters */
  814. void pkgAcquireStatus::Start()
  815. {
  816. gettimeofday(&Time,0);
  817. gettimeofday(&StartTime,0);
  818. LastBytes = 0;
  819. CurrentCPS = 0;
  820. CurrentBytes = 0;
  821. TotalBytes = 0;
  822. FetchedBytes = 0;
  823. ElapsedTime = 0;
  824. TotalItems = 0;
  825. CurrentItems = 0;
  826. }
  827. /*}}}*/
  828. // AcquireStatus::Stop - Finished downloading /*{{{*/
  829. // ---------------------------------------------------------------------
  830. /* This accurately computes the elapsed time and the total overall CPS. */
  831. void pkgAcquireStatus::Stop()
  832. {
  833. // Compute the CPS and elapsed time
  834. struct timeval NewTime;
  835. gettimeofday(&NewTime,0);
  836. double Delta = NewTime.tv_sec - StartTime.tv_sec +
  837. (NewTime.tv_usec - StartTime.tv_usec)/1000000.0;
  838. // Compute the CPS value
  839. if (Delta < 0.01)
  840. CurrentCPS = 0;
  841. else
  842. CurrentCPS = FetchedBytes/Delta;
  843. LastBytes = CurrentBytes;
  844. ElapsedTime = (unsigned int)Delta;
  845. }
  846. /*}}}*/
  847. // AcquireStatus::Fetched - Called when a byte set has been fetched /*{{{*/
  848. // ---------------------------------------------------------------------
  849. /* This is used to get accurate final transfer rate reporting. */
  850. void pkgAcquireStatus::Fetched(unsigned long Size,unsigned long Resume)
  851. {
  852. FetchedBytes += Size - Resume;
  853. }
  854. /*}}}*/