acquire.cc 27 KB

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