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