acquire.cc 31 KB

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