acquire.cc 31 KB

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