acquire.cc 28 KB

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