acquire.cc 30 KB

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