]>
git.saurik.com Git - apt-legacy.git/blob - apt-pkg/acquire.cc
1 // -*- mode: cpp; mode: fold -*-
3 // $Id: acquire.cc,v 1.50 2004/03/17 05:17:11 mdz Exp $
4 /* ######################################################################
6 Acquire - File Acquiration
8 The core element for the schedual 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 controled by how the queue
11 name is derived from the URI.
13 ##################################################################### */
15 // Include Files /*{{{*/
16 #include <apt-pkg/acquire.h>
17 #include <apt-pkg/acquire-item.h>
18 #include <apt-pkg/acquire-worker.h>
19 #include <apt-pkg/configuration.h>
20 #include <apt-pkg/error.h>
21 #include <apt-pkg/strutl.h>
36 // Acquire::pkgAcquire - Constructor /*{{{*/
37 // ---------------------------------------------------------------------
38 /* We grab some runtime state from the configuration space */
39 pkgAcquire::pkgAcquire(pkgAcquireStatus
*Log
) : Log(Log
)
47 string Mode
= _config
->Find("Acquire::Queue-Mode","host");
48 if (strcasecmp(Mode
.c_str(),"host") == 0)
49 QueueMode
= QueueHost
;
50 if (strcasecmp(Mode
.c_str(),"access") == 0)
51 QueueMode
= QueueAccess
;
53 Debug
= _config
->FindB("Debug::pkgAcquire",false);
55 // This is really a stupid place for this
57 if (stat((_config
->FindDir("Dir::State::lists") + "partial/").c_str(),&St
) != 0 ||
58 S_ISDIR(St
.st_mode
) == 0)
59 _error
->Error(_("Lists directory %spartial is missing."),
60 _config
->FindDir("Dir::State::lists").c_str());
61 if (stat((_config
->FindDir("Dir::Cache::Archives") + "partial/").c_str(),&St
) != 0 ||
62 S_ISDIR(St
.st_mode
) == 0)
63 _error
->Error(_("Archive directory %spartial is missing."),
64 _config
->FindDir("Dir::Cache::Archives").c_str());
67 // Acquire::~pkgAcquire - Destructor /*{{{*/
68 // ---------------------------------------------------------------------
69 /* Free our memory, clean up the queues (destroy the workers) */
70 pkgAcquire::~pkgAcquire()
76 MethodConfig
*Jnk
= Configs
;
77 Configs
= Configs
->Next
;
82 // Acquire::Shutdown - Clean out the acquire object /*{{{*/
83 // ---------------------------------------------------------------------
85 void pkgAcquire::Shutdown()
87 while (Items
.size() != 0)
89 if (Items
[0]->Status
== Item::StatFetching
)
90 Items
[0]->Status
= Item::StatError
;
97 Queues
= Queues
->Next
;
102 // Acquire::Add - Add a new item /*{{{*/
103 // ---------------------------------------------------------------------
104 /* This puts an item on the acquire list. This list is mainly for tracking
106 void pkgAcquire::Add(Item
*Itm
)
108 Items
.push_back(Itm
);
111 // Acquire::Remove - Remove a item /*{{{*/
112 // ---------------------------------------------------------------------
113 /* Remove an item from the acquire list. This is usually not used.. */
114 void pkgAcquire::Remove(Item
*Itm
)
118 for (ItemIterator I
= Items
.begin(); I
!= Items
.end();)
130 // Acquire::Add - Add a worker /*{{{*/
131 // ---------------------------------------------------------------------
132 /* A list of workers is kept so that the select loop can direct their FD
134 void pkgAcquire::Add(Worker
*Work
)
136 Work
->NextAcquire
= Workers
;
140 // Acquire::Remove - Remove a worker /*{{{*/
141 // ---------------------------------------------------------------------
142 /* A worker has died. This can not be done while the select loop is running
143 as it would require that RunFds could handling a changing list state and
145 void pkgAcquire::Remove(Worker
*Work
)
150 Worker
**I
= &Workers
;
154 *I
= (*I
)->NextAcquire
;
156 I
= &(*I
)->NextAcquire
;
160 // Acquire::Enqueue - Queue an URI for fetching /*{{{*/
161 // ---------------------------------------------------------------------
162 /* This is the entry point for an item. An item calls this function when
163 it is constructed which creates a queue (based on the current queue
164 mode) and puts the item in that queue. If the system is running then
165 the queue might be started. */
166 void pkgAcquire::Enqueue(ItemDesc
&Item
)
168 // Determine which queue to put the item in
169 const MethodConfig
*Config
;
170 string Name
= QueueName(Item
.URI
,Config
);
171 if (Name
.empty() == true)
174 // Find the queue structure
176 for (; I
!= 0 && I
->Name
!= Name
; I
= I
->Next
);
179 I
= new Queue(Name
,this);
187 // See if this is a local only URI
188 if (Config
->LocalOnly
== true && Item
.Owner
->Complete
== false)
189 Item
.Owner
->Local
= true;
190 Item
.Owner
->Status
= Item::StatIdle
;
192 // Queue it into the named queue
199 clog
<< "Fetching " << Item
.URI
<< endl
;
200 clog
<< " to " << Item
.Owner
->DestFile
<< endl
;
201 clog
<< " Queue is: " << Name
<< endl
;
205 // Acquire::Dequeue - Remove an item from all queues /*{{{*/
206 // ---------------------------------------------------------------------
207 /* This is called when an item is finished being fetched. It removes it
208 from all the queues */
209 void pkgAcquire::Dequeue(Item
*Itm
)
213 for (; I
!= 0; I
= I
->Next
)
214 Res
|= I
->Dequeue(Itm
);
217 clog
<< "Dequeuing " << Itm
->DestFile
<< endl
;
222 // Acquire::QueueName - Return the name of the queue for this URI /*{{{*/
223 // ---------------------------------------------------------------------
224 /* The string returned depends on the configuration settings and the
225 method parameters. Given something like http://foo.org/bar it can
226 return http://foo.org or http */
227 string
pkgAcquire::QueueName(string Uri
,MethodConfig
const *&Config
)
231 Config
= GetConfig(U
.Access
);
235 /* Single-Instance methods get exactly one queue per URI. This is
236 also used for the Access queue method */
237 if (Config
->SingleInstance
== true || QueueMode
== QueueAccess
)
239 string
name(U
.Access
+ ':' + U
.Host
);
241 int parallel(_config
->FindI("Acquire::"+U
.Access
+"::MaxParallel",8));
245 typedef map
<string
, int> indexmap
;
246 static indexmap indices
;
248 pair
<indexmap::iterator
, bool> cache(indices
.insert(indexmap::value_type(name
, -1)));
249 if (cache
.second
|| cache
.first
->second
== -1) {
250 int &index(indices
[U
.Access
]);
251 if (index
>= parallel
)
253 cache
.first
->second
= index
++;
257 value
<< U
.Access
<< "::" << cache
.first
->second
;
261 // Acquire::GetConfig - Fetch the configuration information /*{{{*/
262 // ---------------------------------------------------------------------
263 /* This locates the configuration structure for an access method. If
264 a config structure cannot be found a Worker will be created to
266 pkgAcquire::MethodConfig
*pkgAcquire::GetConfig(string Access
)
268 // Search for an existing config
270 for (Conf
= Configs
; Conf
!= 0; Conf
= Conf
->Next
)
271 if (Conf
->Access
== Access
)
274 // Create the new config class
275 Conf
= new MethodConfig
;
276 Conf
->Access
= Access
;
277 Conf
->Next
= Configs
;
280 // Create the worker to fetch the configuration
282 if (Work
.Start() == false)
285 /* if a method uses DownloadLimit, we switch to SingleInstance mode */
286 if(_config
->FindI("Acquire::"+Access
+"::Dl-Limit",0) > 0)
287 Conf
->SingleInstance
= true;
292 // Acquire::SetFds - Deal with readable FDs /*{{{*/
293 // ---------------------------------------------------------------------
294 /* Collect FDs that have activity monitors into the fd sets */
295 void pkgAcquire::SetFds(int &Fd
,fd_set
*RSet
,fd_set
*WSet
)
297 for (Worker
*I
= Workers
; I
!= 0; I
= I
->NextAcquire
)
299 if (I
->InReady
== true && I
->InFd
>= 0)
303 FD_SET(I
->InFd
,RSet
);
305 if (I
->OutReady
== true && I
->OutFd
>= 0)
309 FD_SET(I
->OutFd
,WSet
);
314 // Acquire::RunFds - Deal with active FDs /*{{{*/
315 // ---------------------------------------------------------------------
316 /* Dispatch active FDs over to the proper workers. It is very important
317 that a worker never be erased while this is running! The queue class
318 should never erase a worker except during shutdown processing. */
319 void pkgAcquire::RunFds(fd_set
*RSet
,fd_set
*WSet
)
321 for (Worker
*I
= Workers
; I
!= 0; I
= I
->NextAcquire
)
323 if (I
->InFd
>= 0 && FD_ISSET(I
->InFd
,RSet
) != 0)
325 if (I
->OutFd
>= 0 && FD_ISSET(I
->OutFd
,WSet
) != 0)
330 // Acquire::Run - Run the fetch sequence /*{{{*/
331 // ---------------------------------------------------------------------
332 /* This runs the queues. It manages a select loop for all of the
333 Worker tasks. The workers interact with the queues and items to
334 manage the actual fetch. */
335 pkgAcquire::RunResult
pkgAcquire::Run(int PulseIntervall
)
339 for (Queue
*I
= Queues
; I
!= 0; I
= I
->Next
)
345 bool WasCancelled
= false;
347 // Run till all things have been acquired
350 tv
.tv_usec
= PulseIntervall
;
358 SetFds(Highest
,&RFds
,&WFds
);
363 Res
= select(Highest
+1,&RFds
,&WFds
,0,&tv
);
365 while (Res
< 0 && errno
== EINTR
);
369 _error
->Errno("select","Select has failed");
374 if (_error
->PendingError() == true)
377 // Timeout, notify the log class
378 if (Res
== 0 || (Log
!= 0 && Log
->Update
== true))
380 tv
.tv_usec
= PulseIntervall
;
381 for (Worker
*I
= Workers
; I
!= 0; I
= I
->NextAcquire
)
383 if (Log
!= 0 && Log
->Pulse(this) == false)
394 // Shut down the acquire bits
396 for (Queue
*I
= Queues
; I
!= 0; I
= I
->Next
)
399 // Shut down the items
400 for (ItemIterator I
= Items
.begin(); I
!= Items
.end(); I
++)
403 if (_error
->PendingError())
410 // Acquire::Bump - Called when an item is dequeued /*{{{*/
411 // ---------------------------------------------------------------------
412 /* This routine bumps idle queues in hopes that they will be able to fetch
414 void pkgAcquire::Bump()
416 for (Queue
*I
= Queues
; I
!= 0; I
= I
->Next
)
420 // Acquire::WorkerStep - Step to the next worker /*{{{*/
421 // ---------------------------------------------------------------------
422 /* Not inlined to advoid including acquire-worker.h */
423 pkgAcquire::Worker
*pkgAcquire::WorkerStep(Worker
*I
)
425 return I
->NextAcquire
;
428 // Acquire::Clean - Cleans a directory /*{{{*/
429 // ---------------------------------------------------------------------
430 /* This is a bit simplistic, it looks at every file in the dir and sees
431 if it is part of the download set. */
432 bool pkgAcquire::Clean(string Dir
)
434 DIR *D
= opendir(Dir
.c_str());
436 return _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
438 string StartDir
= SafeGetCWD();
439 if (chdir(Dir
.c_str()) != 0)
442 return _error
->Errno("chdir",_("Unable to change to %s"),Dir
.c_str());
445 for (struct dirent
*Dir
= readdir(D
); Dir
!= 0; Dir
= readdir(D
))
448 if (strcmp(Dir
->d_name
,"lock") == 0 ||
449 strcmp(Dir
->d_name
,"partial") == 0 ||
450 strcmp(Dir
->d_name
,".") == 0 ||
451 strcmp(Dir
->d_name
,"..") == 0)
454 // Look in the get list
455 ItemCIterator I
= Items
.begin();
456 for (; I
!= Items
.end(); I
++)
457 if (flNotDir((*I
)->DestFile
) == Dir
->d_name
)
460 // Nothing found, nuke it
461 if (I
== Items
.end())
466 if (chdir(StartDir
.c_str()) != 0)
467 return _error
->Errno("chdir",_("Unable to change to %s"),StartDir
.c_str());
471 // Acquire::TotalNeeded - Number of bytes to fetch /*{{{*/
472 // ---------------------------------------------------------------------
473 /* This is the total number of bytes needed */
474 double pkgAcquire::TotalNeeded()
477 for (ItemCIterator I
= ItemsBegin(); I
!= ItemsEnd(); I
++)
478 Total
+= (*I
)->FileSize
;
482 // Acquire::FetchNeeded - Number of bytes needed to get /*{{{*/
483 // ---------------------------------------------------------------------
484 /* This is the number of bytes that is not local */
485 double pkgAcquire::FetchNeeded()
488 for (ItemCIterator I
= ItemsBegin(); I
!= ItemsEnd(); I
++)
489 if ((*I
)->Local
== false)
490 Total
+= (*I
)->FileSize
;
494 // Acquire::PartialPresent - Number of partial bytes we already have /*{{{*/
495 // ---------------------------------------------------------------------
496 /* This is the number of bytes that is not local */
497 double pkgAcquire::PartialPresent()
500 for (ItemCIterator I
= ItemsBegin(); I
!= ItemsEnd(); I
++)
501 if ((*I
)->Local
== false)
502 Total
+= (*I
)->PartialSize
;
506 // Acquire::UriBegin - Start iterator for the uri list /*{{{*/
507 // ---------------------------------------------------------------------
509 pkgAcquire::UriIterator
pkgAcquire::UriBegin()
511 return UriIterator(Queues
);
514 // Acquire::UriEnd - End iterator for the uri list /*{{{*/
515 // ---------------------------------------------------------------------
517 pkgAcquire::UriIterator
pkgAcquire::UriEnd()
519 return UriIterator(0);
523 // Acquire::MethodConfig::MethodConfig - Constructor /*{{{*/
524 // ---------------------------------------------------------------------
526 pkgAcquire::MethodConfig::MethodConfig()
528 SingleInstance
= false;
537 // Queue::Queue - Constructor /*{{{*/
538 // ---------------------------------------------------------------------
540 pkgAcquire::Queue::Queue(string Name
,pkgAcquire
*Owner
) : Name(Name
),
550 // Queue::~Queue - Destructor /*{{{*/
551 // ---------------------------------------------------------------------
553 pkgAcquire::Queue::~Queue()
565 // Queue::Enqueue - Queue an item to the queue /*{{{*/
566 // ---------------------------------------------------------------------
568 bool pkgAcquire::Queue::Enqueue(ItemDesc
&Item
)
571 // move to the end of the queue and check for duplicates here
572 for (; *I
!= 0; I
= &(*I
)->Next
)
573 if (Item
.URI
== (*I
)->URI
)
575 Item
.Owner
->Status
= Item::StatDone
;
580 QItem
*Itm
= new QItem
;
585 Item
.Owner
->QueueCounter
++;
586 if (Items
->Next
== 0)
591 // Queue::Dequeue - Remove an item from the queue /*{{{*/
592 // ---------------------------------------------------------------------
593 /* We return true if we hit something */
594 bool pkgAcquire::Queue::Dequeue(Item
*Owner
)
596 if (Owner
->Status
== pkgAcquire::Item::StatFetching
)
597 return _error
->Error("Tried to dequeue a fetching object");
604 if ((*I
)->Owner
== Owner
)
608 Owner
->QueueCounter
--;
619 // Queue::Startup - Start the worker processes /*{{{*/
620 // ---------------------------------------------------------------------
621 /* It is possible for this to be called with a pre-existing set of
623 bool pkgAcquire::Queue::Startup()
628 pkgAcquire::MethodConfig
*Cnf
= Owner
->GetConfig(U
.Access
);
632 Workers
= new Worker(this,Cnf
,Owner
->Log
);
634 if (Workers
->Start() == false)
637 /* When pipelining we commit 10 items. This needs to change when we
638 added other source retry to have cycle maintain a pipeline depth
640 if (Cnf
->Pipeline
== true)
649 // Queue::Shutdown - Shutdown the worker processes /*{{{*/
650 // ---------------------------------------------------------------------
651 /* If final is true then all workers are eliminated, otherwise only workers
652 that do not need cleanup are removed */
653 bool pkgAcquire::Queue::Shutdown(bool Final
)
655 // Delete all of the workers
656 pkgAcquire::Worker
**Cur
= &Workers
;
659 pkgAcquire::Worker
*Jnk
= *Cur
;
660 if (Final
== true || Jnk
->GetConf()->NeedsCleanup
== false)
662 *Cur
= Jnk
->NextQueue
;
667 Cur
= &(*Cur
)->NextQueue
;
673 // Queue::FindItem - Find a URI in the item list /*{{{*/
674 // ---------------------------------------------------------------------
676 pkgAcquire::Queue::QItem
*pkgAcquire::Queue::FindItem(string URI
,pkgAcquire::Worker
*Owner
)
678 for (QItem
*I
= Items
; I
!= 0; I
= I
->Next
)
679 if (I
->URI
== URI
&& I
->Worker
== Owner
)
684 // Queue::ItemDone - Item has been completed /*{{{*/
685 // ---------------------------------------------------------------------
686 /* The worker signals this which causes the item to be removed from the
687 queue. If this is the last queue instance then it is removed from the
689 bool pkgAcquire::Queue::ItemDone(QItem
*Itm
)
692 if (Itm
->Owner
->Status
== pkgAcquire::Item::StatFetching
)
693 Itm
->Owner
->Status
= pkgAcquire::Item::StatDone
;
695 if (Itm
->Owner
->QueueCounter
<= 1)
696 Owner
->Dequeue(Itm
->Owner
);
706 // Queue::Cycle - Queue new items into the method /*{{{*/
707 // ---------------------------------------------------------------------
708 /* This locates a new idle item and sends it to the worker. If pipelining
709 is enabled then it keeps the pipe full. */
710 bool pkgAcquire::Queue::Cycle()
712 if (Items
== 0 || Workers
== 0)
716 return _error
->Error("Pipedepth failure");
718 // Look for a queable item
720 while (PipeDepth
< (signed)MaxPipeDepth
)
722 for (; I
!= 0; I
= I
->Next
)
723 if (I
->Owner
->Status
== pkgAcquire::Item::StatIdle
)
726 // Nothing to do, queue is idle.
731 I
->Owner
->Status
= pkgAcquire::Item::StatFetching
;
733 if (Workers
->QueueItem(I
) == false)
740 // Queue::Bump - Fetch any pending objects if we are idle /*{{{*/
741 // ---------------------------------------------------------------------
742 /* This is called when an item in multiple queues is dequeued */
743 void pkgAcquire::Queue::Bump()
749 // AcquireStatus::pkgAcquireStatus - Constructor /*{{{*/
750 // ---------------------------------------------------------------------
752 pkgAcquireStatus::pkgAcquireStatus() : Update(true), MorePulses(false)
757 // AcquireStatus::Pulse - Called periodically /*{{{*/
758 // ---------------------------------------------------------------------
759 /* This computes some internal state variables for the derived classes to
760 use. It generates the current downloaded bytes and total bytes to download
761 as well as the current CPS estimate. */
762 bool pkgAcquireStatus::Pulse(pkgAcquire
*Owner
)
769 // Compute the total number of bytes to fetch
770 unsigned int Unknown
= 0;
771 unsigned int Count
= 0;
772 for (pkgAcquire::ItemCIterator I
= Owner
->ItemsBegin(); I
!= Owner
->ItemsEnd();
776 if ((*I
)->Status
== pkgAcquire::Item::StatDone
)
779 // Totally ignore local items
780 if ((*I
)->Local
== true)
783 TotalBytes
+= (*I
)->FileSize
;
784 if ((*I
)->Complete
== true)
785 CurrentBytes
+= (*I
)->FileSize
;
786 if ((*I
)->FileSize
== 0 && (*I
)->Complete
== false)
790 // Compute the current completion
791 unsigned long ResumeSize
= 0;
792 for (pkgAcquire::Worker
*I
= Owner
->WorkersBegin(); I
!= 0;
793 I
= Owner
->WorkerStep(I
))
794 if (I
->CurrentItem
!= 0 && I
->CurrentItem
->Owner
->Complete
== false)
796 CurrentBytes
+= I
->CurrentSize
;
797 ResumeSize
+= I
->ResumePoint
;
799 // Files with unknown size always have 100% completion
800 if (I
->CurrentItem
->Owner
->FileSize
== 0 &&
801 I
->CurrentItem
->Owner
->Complete
== false)
802 TotalBytes
+= I
->CurrentSize
;
805 // Normalize the figures and account for unknown size downloads
808 if (Unknown
== Count
)
809 TotalBytes
= Unknown
;
811 // Wha?! Is not supposed to happen.
812 if (CurrentBytes
> TotalBytes
)
813 CurrentBytes
= TotalBytes
;
816 struct timeval NewTime
;
817 gettimeofday(&NewTime
,0);
818 if ((NewTime
.tv_sec
- Time
.tv_sec
== 6 && NewTime
.tv_usec
> Time
.tv_usec
) ||
819 NewTime
.tv_sec
- Time
.tv_sec
> 6)
821 double Delta
= NewTime
.tv_sec
- Time
.tv_sec
+
822 (NewTime
.tv_usec
- Time
.tv_usec
)/1000000.0;
824 // Compute the CPS value
828 CurrentCPS
= ((CurrentBytes
- ResumeSize
) - LastBytes
)/Delta
;
829 LastBytes
= CurrentBytes
- ResumeSize
;
830 ElapsedTime
= (unsigned long)Delta
;
834 int fd
= _config
->FindI("APT::Status-Fd",-1);
837 ostringstream status
;
840 long i
= CurrentItems
< TotalItems
? CurrentItems
+ 1 : CurrentItems
;
842 (unsigned long)((TotalBytes
- CurrentBytes
) / CurrentCPS
);
844 // only show the ETA if it makes sense
845 if (ETA
> 0 && ETA
< 172800 /* two days */ )
846 snprintf(msg
,sizeof(msg
), _("Retrieving file %li of %li (%s remaining)"), i
, TotalItems
, TimeToStr(ETA
).c_str());
848 snprintf(msg
,sizeof(msg
), _("Retrieving file %li of %li"), i
, TotalItems
);
852 // build the status str
853 status
<< "dlstatus:" << i
854 << ":" << (CurrentBytes
/float(TotalBytes
)*100.0)
857 write(fd
, status
.str().c_str(), status
.str().size());
863 // AcquireStatus::Start - Called when the download is started /*{{{*/
864 // ---------------------------------------------------------------------
865 /* We just reset the counters */
866 void pkgAcquireStatus::Start()
868 gettimeofday(&Time
,0);
869 gettimeofday(&StartTime
,0);
880 // AcquireStatus::Stop - Finished downloading /*{{{*/
881 // ---------------------------------------------------------------------
882 /* This accurately computes the elapsed time and the total overall CPS. */
883 void pkgAcquireStatus::Stop()
885 // Compute the CPS and elapsed time
886 struct timeval NewTime
;
887 gettimeofday(&NewTime
,0);
889 double Delta
= NewTime
.tv_sec
- StartTime
.tv_sec
+
890 (NewTime
.tv_usec
- StartTime
.tv_usec
)/1000000.0;
892 // Compute the CPS value
896 CurrentCPS
= FetchedBytes
/Delta
;
897 LastBytes
= CurrentBytes
;
898 ElapsedTime
= (unsigned int)Delta
;
901 // AcquireStatus::Fetched - Called when a byte set has been fetched /*{{{*/
902 // ---------------------------------------------------------------------
903 /* This is used to get accurate final transfer rate reporting. */
904 void pkgAcquireStatus::Fetched(unsigned long Size
,unsigned long Resume
)
906 FetchedBytes
+= Size
- Resume
;