acquire.cc 30 KB

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