acquire.cc 35 KB

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