acquire.cc 28 KB

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