You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1145 lines
34 KiB

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