acquire.cc 31 KB

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