acquire.cc 31 KB

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