acquire.cc 31 KB

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