]>
git.saurik.com Git - apt.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 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.
13 ##################################################################### */
15 // Include Files /*{{{*/
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>
42 #include <sys/select.h>
51 // Acquire::pkgAcquire - Constructor /*{{{*/
52 // ---------------------------------------------------------------------
53 /* We grab some runtime state from the configuration space */
54 pkgAcquire::pkgAcquire() : LockFD(-1), d(NULL
), Queues(0), Workers(0), Configs(0), Log(NULL
), ToFetch(0),
55 Debug(_config
->FindB("Debug::pkgAcquire",false)),
60 pkgAcquire::pkgAcquire(pkgAcquireStatus
*Progress
) : LockFD(-1), d(NULL
), Queues(0), Workers(0),
61 Configs(0), Log(NULL
), ToFetch(0),
62 Debug(_config
->FindB("Debug::pkgAcquire",false)),
68 void pkgAcquire::Initialize()
70 string
const Mode
= _config
->Find("Acquire::Queue-Mode","host");
71 if (strcasecmp(Mode
.c_str(),"host") == 0)
72 QueueMode
= QueueHost
;
73 if (strcasecmp(Mode
.c_str(),"access") == 0)
74 QueueMode
= QueueAccess
;
76 // chown the auth.conf file as it will be accessed by our methods
77 std::string
const SandboxUser
= _config
->Find("APT::Sandbox::User");
78 if (getuid() == 0 && SandboxUser
.empty() == false) // if we aren't root, we can't chown, so don't try it
80 struct passwd
const * const pw
= getpwnam(SandboxUser
.c_str());
81 struct group
const * const gr
= getgrnam("root");
82 if (pw
!= NULL
&& gr
!= NULL
)
84 std::string
const AuthConf
= _config
->FindFile("Dir::Etc::netrc");
85 if(AuthConf
.empty() == false && RealFileExists(AuthConf
) &&
86 chown(AuthConf
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
87 _error
->WarningE("SetupAPTPartialDirectory", "chown to %s:root of file %s failed", SandboxUser
.c_str(), AuthConf
.c_str());
92 // Acquire::GetLock - lock directory and prepare for action /*{{{*/
93 static bool SetupAPTPartialDirectory(std::string
const &grand
, std::string
const &parent
)
95 std::string
const partial
= parent
+ "partial";
96 mode_t
const mode
= umask(S_IWGRP
| S_IWOTH
);
97 bool const creation_fail
= (CreateAPTDirectoryIfNeeded(grand
, partial
) == false &&
98 CreateAPTDirectoryIfNeeded(parent
, partial
) == false);
100 if (creation_fail
== true)
103 std::string
const SandboxUser
= _config
->Find("APT::Sandbox::User");
104 if (getuid() == 0 && SandboxUser
.empty() == false) // if we aren't root, we can't chown, so don't try it
106 struct passwd
const * const pw
= getpwnam(SandboxUser
.c_str());
107 struct group
const * const gr
= getgrnam("root");
108 if (pw
!= NULL
&& gr
!= NULL
)
110 // chown the partial dir
111 if(chown(partial
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
112 _error
->WarningE("SetupAPTPartialDirectory", "chown to %s:root of directory %s failed", SandboxUser
.c_str(), partial
.c_str());
115 if (chmod(partial
.c_str(), 0700) != 0)
116 _error
->WarningE("SetupAPTPartialDirectory", "chmod 0700 of directory %s failed", partial
.c_str());
120 bool pkgAcquire::Setup(pkgAcquireStatus
*Progress
, string
const &Lock
)
125 string
const listDir
= _config
->FindDir("Dir::State::lists");
126 if (SetupAPTPartialDirectory(_config
->FindDir("Dir::State"), listDir
) == false)
127 return _error
->Errno("Acquire", _("List directory %spartial is missing."), listDir
.c_str());
128 string
const archivesDir
= _config
->FindDir("Dir::Cache::Archives");
129 if (SetupAPTPartialDirectory(_config
->FindDir("Dir::Cache"), archivesDir
) == false)
130 return _error
->Errno("Acquire", _("Archives directory %spartial is missing."), archivesDir
.c_str());
133 return GetLock(Lock
);
135 bool pkgAcquire::GetLock(std::string
const &Lock
)
137 if (Lock
.empty() == true)
140 // check for existence and possibly create auxiliary directories
141 string
const listDir
= _config
->FindDir("Dir::State::lists");
142 string
const archivesDir
= _config
->FindDir("Dir::Cache::Archives");
146 if (SetupAPTPartialDirectory(_config
->FindDir("Dir::State"), listDir
) == false)
147 return _error
->Errno("Acquire", _("List directory %spartial is missing."), listDir
.c_str());
149 if (Lock
== archivesDir
)
151 if (SetupAPTPartialDirectory(_config
->FindDir("Dir::Cache"), archivesDir
) == false)
152 return _error
->Errno("Acquire", _("Archives directory %spartial is missing."), archivesDir
.c_str());
155 if (_config
->FindB("Debug::NoLocking", false) == true)
158 // Lock the directory this acquire object will work in
161 LockFD
= ::GetLock(flCombine(Lock
, "lock"));
163 return _error
->Error(_("Unable to lock directory %s"), Lock
.c_str());
168 // Acquire::~pkgAcquire - Destructor /*{{{*/
169 // ---------------------------------------------------------------------
170 /* Free our memory, clean up the queues (destroy the workers) */
171 pkgAcquire::~pkgAcquire()
180 MethodConfig
*Jnk
= Configs
;
181 Configs
= Configs
->Next
;
186 // Acquire::Shutdown - Clean out the acquire object /*{{{*/
187 // ---------------------------------------------------------------------
189 void pkgAcquire::Shutdown()
191 while (Items
.empty() == false)
193 if (Items
[0]->Status
== Item::StatFetching
)
194 Items
[0]->Status
= Item::StatError
;
201 Queues
= Queues
->Next
;
206 // Acquire::Add - Add a new item /*{{{*/
207 // ---------------------------------------------------------------------
208 /* This puts an item on the acquire list. This list is mainly for tracking
210 void pkgAcquire::Add(Item
*Itm
)
212 Items
.push_back(Itm
);
215 // Acquire::Remove - Remove a item /*{{{*/
216 // ---------------------------------------------------------------------
217 /* Remove an item from the acquire list. This is usually not used.. */
218 void pkgAcquire::Remove(Item
*Itm
)
222 for (ItemIterator I
= Items
.begin(); I
!= Items
.end();)
234 // Acquire::Add - Add a worker /*{{{*/
235 // ---------------------------------------------------------------------
236 /* A list of workers is kept so that the select loop can direct their FD
238 void pkgAcquire::Add(Worker
*Work
)
240 Work
->NextAcquire
= Workers
;
244 // Acquire::Remove - Remove a worker /*{{{*/
245 // ---------------------------------------------------------------------
246 /* A worker has died. This can not be done while the select loop is running
247 as it would require that RunFds could handling a changing list state and
249 void pkgAcquire::Remove(Worker
*Work
)
254 Worker
**I
= &Workers
;
258 *I
= (*I
)->NextAcquire
;
260 I
= &(*I
)->NextAcquire
;
264 // Acquire::Enqueue - Queue an URI for fetching /*{{{*/
265 // ---------------------------------------------------------------------
266 /* This is the entry point for an item. An item calls this function when
267 it is constructed which creates a queue (based on the current queue
268 mode) and puts the item in that queue. If the system is running then
269 the queue might be started. */
270 void pkgAcquire::Enqueue(ItemDesc
&Item
)
272 // Determine which queue to put the item in
273 const MethodConfig
*Config
;
274 string Name
= QueueName(Item
.URI
,Config
);
275 if (Name
.empty() == true)
278 // Find the queue structure
280 for (; I
!= 0 && I
->Name
!= Name
; I
= I
->Next
);
283 I
= new Queue(Name
,this);
291 // See if this is a local only URI
292 if (Config
->LocalOnly
== true && Item
.Owner
->Complete
== false)
293 Item
.Owner
->Local
= true;
294 Item
.Owner
->Status
= Item::StatIdle
;
296 // Queue it into the named queue
303 clog
<< "Fetching " << Item
.URI
<< endl
;
304 clog
<< " to " << Item
.Owner
->DestFile
<< endl
;
305 clog
<< " Queue is: " << Name
<< endl
;
309 // Acquire::Dequeue - Remove an item from all queues /*{{{*/
310 // ---------------------------------------------------------------------
311 /* This is called when an item is finished being fetched. It removes it
312 from all the queues */
313 void pkgAcquire::Dequeue(Item
*Itm
)
318 clog
<< "Dequeuing " << Itm
->DestFile
<< endl
;
320 for (; I
!= 0; I
= I
->Next
)
326 clog
<< "Dequeued from " << I
->Name
<< endl
;
334 // Acquire::QueueName - Return the name of the queue for this URI /*{{{*/
335 // ---------------------------------------------------------------------
336 /* The string returned depends on the configuration settings and the
337 method parameters. Given something like http://foo.org/bar it can
338 return http://foo.org or http */
339 string
pkgAcquire::QueueName(string Uri
,MethodConfig
const *&Config
)
343 Config
= GetConfig(U
.Access
);
347 /* Single-Instance methods get exactly one queue per URI. This is
348 also used for the Access queue method */
349 if (Config
->SingleInstance
== true || QueueMode
== QueueAccess
)
352 string AccessSchema
= U
.Access
+ ':',
353 FullQueueName
= AccessSchema
+ U
.Host
;
354 unsigned int Instances
= 0, SchemaLength
= AccessSchema
.length();
357 for (; I
!= 0; I
= I
->Next
) {
358 // if the queue already exists, re-use it
359 if (I
->Name
== FullQueueName
)
360 return FullQueueName
;
362 if (I
->Name
.compare(0, SchemaLength
, AccessSchema
) == 0)
367 clog
<< "Found " << Instances
<< " instances of " << U
.Access
<< endl
;
370 if (Instances
>= (unsigned int)_config
->FindI("Acquire::QueueHost::Limit",10))
373 return FullQueueName
;
376 // Acquire::GetConfig - Fetch the configuration information /*{{{*/
377 // ---------------------------------------------------------------------
378 /* This locates the configuration structure for an access method. If
379 a config structure cannot be found a Worker will be created to
381 pkgAcquire::MethodConfig
*pkgAcquire::GetConfig(string Access
)
383 // Search for an existing config
385 for (Conf
= Configs
; Conf
!= 0; Conf
= Conf
->Next
)
386 if (Conf
->Access
== Access
)
389 // Create the new config class
390 Conf
= new MethodConfig
;
391 Conf
->Access
= Access
;
392 Conf
->Next
= Configs
;
395 // Create the worker to fetch the configuration
397 if (Work
.Start() == false)
400 /* if a method uses DownloadLimit, we switch to SingleInstance mode */
401 if(_config
->FindI("Acquire::"+Access
+"::Dl-Limit",0) > 0)
402 Conf
->SingleInstance
= true;
407 // Acquire::SetFds - Deal with readable FDs /*{{{*/
408 // ---------------------------------------------------------------------
409 /* Collect FDs that have activity monitors into the fd sets */
410 void pkgAcquire::SetFds(int &Fd
,fd_set
*RSet
,fd_set
*WSet
)
412 for (Worker
*I
= Workers
; I
!= 0; I
= I
->NextAcquire
)
414 if (I
->InReady
== true && I
->InFd
>= 0)
418 FD_SET(I
->InFd
,RSet
);
420 if (I
->OutReady
== true && I
->OutFd
>= 0)
424 FD_SET(I
->OutFd
,WSet
);
429 // Acquire::RunFds - Deal with active FDs /*{{{*/
430 // ---------------------------------------------------------------------
431 /* Dispatch active FDs over to the proper workers. It is very important
432 that a worker never be erased while this is running! The queue class
433 should never erase a worker except during shutdown processing. */
434 void pkgAcquire::RunFds(fd_set
*RSet
,fd_set
*WSet
)
436 for (Worker
*I
= Workers
; I
!= 0; I
= I
->NextAcquire
)
438 if (I
->InFd
>= 0 && FD_ISSET(I
->InFd
,RSet
) != 0)
440 if (I
->OutFd
>= 0 && FD_ISSET(I
->OutFd
,WSet
) != 0)
445 // Acquire::Run - Run the fetch sequence /*{{{*/
446 // ---------------------------------------------------------------------
447 /* This runs the queues. It manages a select loop for all of the
448 Worker tasks. The workers interact with the queues and items to
449 manage the actual fetch. */
450 static void CheckDropPrivsMustBeDisabled(pkgAcquire
const &Fetcher
)
455 std::string SandboxUser
= _config
->Find("APT::Sandbox::User");
456 if (SandboxUser
.empty())
459 struct passwd
const * const pw
= getpwnam(SandboxUser
.c_str());
463 gid_t
const old_euid
= geteuid();
464 gid_t
const old_egid
= getegid();
465 if (setegid(pw
->pw_gid
) != 0)
466 _error
->Errno("setegid", "setegid %u failed", pw
->pw_gid
);
467 if (seteuid(pw
->pw_uid
) != 0)
468 _error
->Errno("seteuid", "seteuid %u failed", pw
->pw_uid
);
470 for (pkgAcquire::ItemCIterator I
= Fetcher
.ItemsBegin();
471 I
!= Fetcher
.ItemsEnd(); ++I
)
473 std::string filename
= (*I
)->DestFile
;
474 if (filename
.empty())
477 // no need to drop privileges for a complete file
478 if ((*I
)->Complete
== true)
481 // we check directory instead of file as the file might or might not
482 // exist already as a link or not which complicates everything…
483 std::string dirname
= flNotFile(filename
);
484 if (unlikely(dirname
.empty()))
486 // translate relative to absolute for DirectoryExists
487 // FIXME: What about ../ and ./../ ?
488 if (dirname
.substr(0,2) == "./")
489 dirname
= SafeGetCWD() + dirname
.substr(2);
491 if (DirectoryExists(dirname
))
494 continue; // assume it is created correctly by the acquire system
496 if (faccessat(-1, dirname
.c_str(), R_OK
| W_OK
| X_OK
, AT_EACCESS
| AT_SYMLINK_NOFOLLOW
) != 0)
498 _error
->WarningE("pkgAcquire::Run", _("Can't drop privileges for downloading as file '%s' couldn't be accessed by user '%s'."),
499 filename
.c_str(), SandboxUser
.c_str());
500 _config
->Set("APT::Sandbox::User", "");
505 if (seteuid(old_euid
) != 0)
506 _error
->Errno("seteuid", "seteuid %u failed", old_euid
);
507 if (setegid(old_egid
) != 0)
508 _error
->Errno("setegid", "setegid %u failed", old_egid
);
510 pkgAcquire::RunResult
pkgAcquire::Run(int PulseIntervall
)
512 _error
->PushToStack();
513 CheckDropPrivsMustBeDisabled(*this);
517 for (Queue
*I
= Queues
; I
!= 0; I
= I
->Next
)
523 bool WasCancelled
= false;
525 // Run till all things have been acquired
528 tv
.tv_usec
= PulseIntervall
;
536 SetFds(Highest
,&RFds
,&WFds
);
541 Res
= select(Highest
+1,&RFds
,&WFds
,0,&tv
);
543 while (Res
< 0 && errno
== EINTR
);
547 _error
->Errno("select","Select has failed");
553 // Timeout, notify the log class
554 if (Res
== 0 || (Log
!= 0 && Log
->Update
== true))
556 tv
.tv_usec
= PulseIntervall
;
557 for (Worker
*I
= Workers
; I
!= 0; I
= I
->NextAcquire
)
559 if (Log
!= 0 && Log
->Pulse(this) == false)
570 // Shut down the acquire bits
572 for (Queue
*I
= Queues
; I
!= 0; I
= I
->Next
)
575 // Shut down the items
576 for (ItemIterator I
= Items
.begin(); I
!= Items
.end(); ++I
)
579 bool const newError
= _error
->PendingError();
580 _error
->MergeWithStack();
588 // Acquire::Bump - Called when an item is dequeued /*{{{*/
589 // ---------------------------------------------------------------------
590 /* This routine bumps idle queues in hopes that they will be able to fetch
592 void pkgAcquire::Bump()
594 for (Queue
*I
= Queues
; I
!= 0; I
= I
->Next
)
598 // Acquire::WorkerStep - Step to the next worker /*{{{*/
599 // ---------------------------------------------------------------------
600 /* Not inlined to advoid including acquire-worker.h */
601 pkgAcquire::Worker
*pkgAcquire::WorkerStep(Worker
*I
)
603 return I
->NextAcquire
;
606 // Acquire::Clean - Cleans a directory /*{{{*/
607 // ---------------------------------------------------------------------
608 /* This is a bit simplistic, it looks at every file in the dir and sees
609 if it is part of the download set. */
610 bool pkgAcquire::Clean(string Dir
)
612 // non-existing directories are by definition clean…
613 if (DirectoryExists(Dir
) == false)
617 return _error
->Error(_("Clean of %s is not supported"), Dir
.c_str());
619 DIR *D
= opendir(Dir
.c_str());
621 return _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
623 string StartDir
= SafeGetCWD();
624 if (chdir(Dir
.c_str()) != 0)
627 return _error
->Errno("chdir",_("Unable to change to %s"),Dir
.c_str());
630 for (struct dirent
*Dir
= readdir(D
); Dir
!= 0; Dir
= readdir(D
))
633 if (strcmp(Dir
->d_name
,"lock") == 0 ||
634 strcmp(Dir
->d_name
,"partial") == 0 ||
635 strcmp(Dir
->d_name
,".") == 0 ||
636 strcmp(Dir
->d_name
,"..") == 0)
639 // Look in the get list
640 ItemCIterator I
= Items
.begin();
641 for (; I
!= Items
.end(); ++I
)
642 if (flNotDir((*I
)->DestFile
) == Dir
->d_name
)
645 // Nothing found, nuke it
646 if (I
== Items
.end())
651 if (chdir(StartDir
.c_str()) != 0)
652 return _error
->Errno("chdir",_("Unable to change to %s"),StartDir
.c_str());
656 // Acquire::TotalNeeded - Number of bytes to fetch /*{{{*/
657 // ---------------------------------------------------------------------
658 /* This is the total number of bytes needed */
659 APT_PURE
unsigned long long pkgAcquire::TotalNeeded()
661 unsigned long long Total
= 0;
662 for (ItemCIterator I
= ItemsBegin(); I
!= ItemsEnd(); ++I
)
663 Total
+= (*I
)->FileSize
;
667 // Acquire::FetchNeeded - Number of bytes needed to get /*{{{*/
668 // ---------------------------------------------------------------------
669 /* This is the number of bytes that is not local */
670 APT_PURE
unsigned long long pkgAcquire::FetchNeeded()
672 unsigned long long Total
= 0;
673 for (ItemCIterator I
= ItemsBegin(); I
!= ItemsEnd(); ++I
)
674 if ((*I
)->Local
== false)
675 Total
+= (*I
)->FileSize
;
679 // Acquire::PartialPresent - Number of partial bytes we already have /*{{{*/
680 // ---------------------------------------------------------------------
681 /* This is the number of bytes that is not local */
682 APT_PURE
unsigned long long pkgAcquire::PartialPresent()
684 unsigned long long Total
= 0;
685 for (ItemCIterator I
= ItemsBegin(); I
!= ItemsEnd(); ++I
)
686 if ((*I
)->Local
== false)
687 Total
+= (*I
)->PartialSize
;
691 // Acquire::UriBegin - Start iterator for the uri list /*{{{*/
692 // ---------------------------------------------------------------------
694 pkgAcquire::UriIterator
pkgAcquire::UriBegin()
696 return UriIterator(Queues
);
699 // Acquire::UriEnd - End iterator for the uri list /*{{{*/
700 // ---------------------------------------------------------------------
702 pkgAcquire::UriIterator
pkgAcquire::UriEnd()
704 return UriIterator(0);
707 // Acquire::MethodConfig::MethodConfig - Constructor /*{{{*/
708 // ---------------------------------------------------------------------
710 pkgAcquire::MethodConfig::MethodConfig() : d(NULL
), Next(0), SingleInstance(false),
711 Pipeline(false), SendConfig(false), LocalOnly(false), NeedsCleanup(false),
716 // Queue::Queue - Constructor /*{{{*/
717 // ---------------------------------------------------------------------
719 pkgAcquire::Queue::Queue(string
const &name
,pkgAcquire
* const owner
) : d(NULL
), Next(0),
720 Name(name
), Items(0), Workers(0), Owner(owner
), PipeDepth(0), MaxPipeDepth(1)
724 // Queue::~Queue - Destructor /*{{{*/
725 // ---------------------------------------------------------------------
727 pkgAcquire::Queue::~Queue()
739 // Queue::Enqueue - Queue an item to the queue /*{{{*/
740 // ---------------------------------------------------------------------
742 bool pkgAcquire::Queue::Enqueue(ItemDesc
&Item
)
745 // move to the end of the queue and check for duplicates here
746 HashStringList
const hsl
= Item
.Owner
->GetExpectedHashes();
747 for (; *I
!= 0; I
= &(*I
)->Next
)
748 if (Item
.URI
== (*I
)->URI
|| hsl
== (*I
)->Owner
->GetExpectedHashes())
750 if (_config
->FindB("Debug::pkgAcquire::Worker",false) == true)
751 std::cerr
<< " @ Queue: Action combined for " << Item
.URI
<< " and " << (*I
)->URI
<< std::endl
;
752 (*I
)->Owners
.push_back(Item
.Owner
);
753 Item
.Owner
->Status
= (*I
)->Owner
->Status
;
758 QItem
*Itm
= new QItem
;
763 Item
.Owner
->QueueCounter
++;
764 if (Items
->Next
== 0)
769 // Queue::Dequeue - Remove an item from the queue /*{{{*/
770 // ---------------------------------------------------------------------
771 /* We return true if we hit something */
772 bool pkgAcquire::Queue::Dequeue(Item
*Owner
)
774 if (Owner
->Status
== pkgAcquire::Item::StatFetching
)
775 return _error
->Error("Tried to dequeue a fetching object");
782 if (Owner
== (*I
)->Owner
)
786 Owner
->QueueCounter
--;
797 // Queue::Startup - Start the worker processes /*{{{*/
798 // ---------------------------------------------------------------------
799 /* It is possible for this to be called with a pre-existing set of
801 bool pkgAcquire::Queue::Startup()
806 pkgAcquire::MethodConfig
*Cnf
= Owner
->GetConfig(U
.Access
);
810 Workers
= new Worker(this,Cnf
,Owner
->Log
);
812 if (Workers
->Start() == false)
815 /* When pipelining we commit 10 items. This needs to change when we
816 added other source retry to have cycle maintain a pipeline depth
818 if (Cnf
->Pipeline
== true)
819 MaxPipeDepth
= _config
->FindI("Acquire::Max-Pipeline-Depth",10);
827 // Queue::Shutdown - Shutdown the worker processes /*{{{*/
828 // ---------------------------------------------------------------------
829 /* If final is true then all workers are eliminated, otherwise only workers
830 that do not need cleanup are removed */
831 bool pkgAcquire::Queue::Shutdown(bool Final
)
833 // Delete all of the workers
834 pkgAcquire::Worker
**Cur
= &Workers
;
837 pkgAcquire::Worker
*Jnk
= *Cur
;
838 if (Final
== true || Jnk
->GetConf()->NeedsCleanup
== false)
840 *Cur
= Jnk
->NextQueue
;
845 Cur
= &(*Cur
)->NextQueue
;
851 // Queue::FindItem - Find a URI in the item list /*{{{*/
852 // ---------------------------------------------------------------------
854 pkgAcquire::Queue::QItem
*pkgAcquire::Queue::FindItem(string URI
,pkgAcquire::Worker
*Owner
)
856 for (QItem
*I
= Items
; I
!= 0; I
= I
->Next
)
857 if (I
->URI
== URI
&& I
->Worker
== Owner
)
862 // Queue::ItemDone - Item has been completed /*{{{*/
863 // ---------------------------------------------------------------------
864 /* The worker signals this which causes the item to be removed from the
865 queue. If this is the last queue instance then it is removed from the
867 bool pkgAcquire::Queue::ItemDone(QItem
*Itm
)
870 for (QItem::owner_iterator O
= Itm
->Owners
.begin(); O
!= Itm
->Owners
.end(); ++O
)
872 if ((*O
)->Status
== pkgAcquire::Item::StatFetching
)
873 (*O
)->Status
= pkgAcquire::Item::StatDone
;
876 if (Itm
->Owner
->QueueCounter
<= 1)
877 Owner
->Dequeue(Itm
->Owner
);
887 // Queue::Cycle - Queue new items into the method /*{{{*/
888 // ---------------------------------------------------------------------
889 /* This locates a new idle item and sends it to the worker. If pipelining
890 is enabled then it keeps the pipe full. */
891 bool pkgAcquire::Queue::Cycle()
893 if (Items
== 0 || Workers
== 0)
897 return _error
->Error("Pipedepth failure");
899 // Look for a queable item
901 while (PipeDepth
< (signed)MaxPipeDepth
)
903 for (; I
!= 0; I
= I
->Next
)
904 if (I
->Owner
->Status
== pkgAcquire::Item::StatIdle
)
907 // Nothing to do, queue is idle.
912 for (QItem::owner_iterator O
= I
->Owners
.begin(); O
!= I
->Owners
.end(); ++O
)
913 (*O
)->Status
= pkgAcquire::Item::StatFetching
;
915 if (Workers
->QueueItem(I
) == false)
922 // Queue::Bump - Fetch any pending objects if we are idle /*{{{*/
923 // ---------------------------------------------------------------------
924 /* This is called when an item in multiple queues is dequeued */
925 void pkgAcquire::Queue::Bump()
930 HashStringList
pkgAcquire::Queue::QItem::GetExpectedHashes() const /*{{{*/
932 /* each Item can have multiple owners and each owner might have different
933 hashes, even if that is unlikely in practice and if so at least some
934 owners will later fail. There is one situation through which is not a
935 failure and still needs this handling: Two owners who expect the same
936 file, but one owner only knows the SHA1 while the other only knows SHA256. */
937 HashStringList superhsl
;
938 for (pkgAcquire::Queue::QItem::owner_iterator O
= Owners
.begin(); O
!= Owners
.end(); ++O
)
940 HashStringList
const hsl
= (*O
)->GetExpectedHashes();
941 if (hsl
.usable() == false)
943 if (superhsl
.usable() == false)
947 // we merge both lists - if we find disagreement send no hashes
948 HashStringList::const_iterator hs
= hsl
.begin();
949 for (; hs
!= hsl
.end(); ++hs
)
950 if (superhsl
.push_back(*hs
) == false)
962 APT_PURE
unsigned long long pkgAcquire::Queue::QItem::GetMaximumSize() const /*{{{*/
964 unsigned long long Maximum
= std::numeric_limits
<unsigned long long>::max();
965 for (pkgAcquire::Queue::QItem::owner_iterator O
= Owners
.begin(); O
!= Owners
.end(); ++O
)
967 if ((*O
)->FileSize
== 0)
969 Maximum
= std::min(Maximum
, (*O
)->FileSize
);
971 if (Maximum
== std::numeric_limits
<unsigned long long>::max())
976 void pkgAcquire::Queue::QItem::SyncDestinationFiles() const /*{{{*/
978 /* ensure that the first owner has the best partial file of all and
979 the rest have (potentially dangling) symlinks to it so that
980 everything (like progress reporting) finds it easily */
981 std::string superfile
= Owner
->DestFile
;
983 for (pkgAcquire::Queue::QItem::owner_iterator O
= Owners
.begin(); O
!= Owners
.end(); ++O
)
985 if ((*O
)->DestFile
== superfile
)
988 if (lstat((*O
)->DestFile
.c_str(),&file
) == 0)
990 if ((file
.st_mode
& S_IFREG
) == 0)
991 unlink((*O
)->DestFile
.c_str());
992 else if (supersize
< file
.st_size
)
994 supersize
= file
.st_size
;
995 unlink(superfile
.c_str());
996 rename((*O
)->DestFile
.c_str(), superfile
.c_str());
999 unlink((*O
)->DestFile
.c_str());
1000 if (symlink(superfile
.c_str(), (*O
)->DestFile
.c_str()) != 0)
1002 ; // not a problem per-se and no real alternative
1008 std::string
pkgAcquire::Queue::QItem::Custom600Headers() const /*{{{*/
1010 /* The others are relatively easy to merge, but this one?
1011 Lets not merge and see how far we can run with it…
1012 Likely, nobody will ever notice as all the items will
1013 be of the same class and hence generate the same headers. */
1014 return Owner
->Custom600Headers();
1018 // AcquireStatus::pkgAcquireStatus - Constructor /*{{{*/
1019 // ---------------------------------------------------------------------
1021 pkgAcquireStatus::pkgAcquireStatus() : d(NULL
), Percent(-1), Update(true), MorePulses(false)
1026 // AcquireStatus::Pulse - Called periodically /*{{{*/
1027 // ---------------------------------------------------------------------
1028 /* This computes some internal state variables for the derived classes to
1029 use. It generates the current downloaded bytes and total bytes to download
1030 as well as the current CPS estimate. */
1031 bool pkgAcquireStatus::Pulse(pkgAcquire
*Owner
)
1038 // Compute the total number of bytes to fetch
1039 unsigned int Unknown
= 0;
1040 unsigned int Count
= 0;
1041 bool UnfetchedReleaseFiles
= false;
1042 for (pkgAcquire::ItemCIterator I
= Owner
->ItemsBegin();
1043 I
!= Owner
->ItemsEnd();
1047 if ((*I
)->Status
== pkgAcquire::Item::StatDone
)
1050 // Totally ignore local items
1051 if ((*I
)->Local
== true)
1054 // see if the method tells us to expect more
1055 TotalItems
+= (*I
)->ExpectedAdditionalItems
;
1057 // check if there are unfetched Release files
1058 if ((*I
)->Complete
== false && (*I
)->ExpectedAdditionalItems
> 0)
1059 UnfetchedReleaseFiles
= true;
1061 TotalBytes
+= (*I
)->FileSize
;
1062 if ((*I
)->Complete
== true)
1063 CurrentBytes
+= (*I
)->FileSize
;
1064 if ((*I
)->FileSize
== 0 && (*I
)->Complete
== false)
1068 // Compute the current completion
1069 unsigned long long ResumeSize
= 0;
1070 for (pkgAcquire::Worker
*I
= Owner
->WorkersBegin(); I
!= 0;
1071 I
= Owner
->WorkerStep(I
))
1073 if (I
->CurrentItem
!= 0 && I
->CurrentItem
->Owner
->Complete
== false)
1075 CurrentBytes
+= I
->CurrentSize
;
1076 ResumeSize
+= I
->ResumePoint
;
1078 // Files with unknown size always have 100% completion
1079 if (I
->CurrentItem
->Owner
->FileSize
== 0 &&
1080 I
->CurrentItem
->Owner
->Complete
== false)
1081 TotalBytes
+= I
->CurrentSize
;
1085 // Normalize the figures and account for unknown size downloads
1086 if (TotalBytes
<= 0)
1088 if (Unknown
== Count
)
1089 TotalBytes
= Unknown
;
1091 // Wha?! Is not supposed to happen.
1092 if (CurrentBytes
> TotalBytes
)
1093 CurrentBytes
= TotalBytes
;
1096 if (_config
->FindB("Debug::acquire::progress", false) == true)
1097 std::clog
<< " Bytes: "
1098 << SizeToStr(CurrentBytes
) << " / " << SizeToStr(TotalBytes
)
1102 struct timeval NewTime
;
1103 gettimeofday(&NewTime
,0);
1104 if ((NewTime
.tv_sec
- Time
.tv_sec
== 6 && NewTime
.tv_usec
> Time
.tv_usec
) ||
1105 NewTime
.tv_sec
- Time
.tv_sec
> 6)
1107 double Delta
= NewTime
.tv_sec
- Time
.tv_sec
+
1108 (NewTime
.tv_usec
- Time
.tv_usec
)/1000000.0;
1110 // Compute the CPS value
1114 CurrentCPS
= ((CurrentBytes
- ResumeSize
) - LastBytes
)/Delta
;
1115 LastBytes
= CurrentBytes
- ResumeSize
;
1116 ElapsedTime
= (unsigned long long)Delta
;
1120 double const OldPercent
= Percent
;
1121 // calculate the percentage, if we have too little data assume 1%
1122 if (TotalBytes
> 0 && UnfetchedReleaseFiles
)
1125 // use both files and bytes because bytes can be unreliable
1126 Percent
= (0.8 * (CurrentBytes
/float(TotalBytes
)*100.0) +
1127 0.2 * (CurrentItems
/float(TotalItems
)*100.0));
1128 double const DiffPercent
= Percent
- OldPercent
;
1129 if (DiffPercent
< 0.001 && _config
->FindB("Acquire::Progress::Diffpercent", false) == true)
1132 int fd
= _config
->FindI("APT::Status-Fd",-1);
1135 ostringstream status
;
1138 long i
= CurrentItems
< TotalItems
? CurrentItems
+ 1 : CurrentItems
;
1139 unsigned long long ETA
= 0;
1141 ETA
= (TotalBytes
- CurrentBytes
) / CurrentCPS
;
1143 // only show the ETA if it makes sense
1144 if (ETA
> 0 && ETA
< 172800 /* two days */ )
1145 snprintf(msg
,sizeof(msg
), _("Retrieving file %li of %li (%s remaining)"), i
, TotalItems
, TimeToStr(ETA
).c_str());
1147 snprintf(msg
,sizeof(msg
), _("Retrieving file %li of %li"), i
, TotalItems
);
1149 // build the status str
1150 status
<< "dlstatus:" << i
1151 << ":" << std::setprecision(3) << Percent
1155 std::string
const dlstatus
= status
.str();
1156 FileFd::Write(fd
, dlstatus
.c_str(), dlstatus
.size());
1162 // AcquireStatus::Start - Called when the download is started /*{{{*/
1163 // ---------------------------------------------------------------------
1164 /* We just reset the counters */
1165 void pkgAcquireStatus::Start()
1167 gettimeofday(&Time
,0);
1168 gettimeofday(&StartTime
,0);
1179 // AcquireStatus::Stop - Finished downloading /*{{{*/
1180 // ---------------------------------------------------------------------
1181 /* This accurately computes the elapsed time and the total overall CPS. */
1182 void pkgAcquireStatus::Stop()
1184 // Compute the CPS and elapsed time
1185 struct timeval NewTime
;
1186 gettimeofday(&NewTime
,0);
1188 double Delta
= NewTime
.tv_sec
- StartTime
.tv_sec
+
1189 (NewTime
.tv_usec
- StartTime
.tv_usec
)/1000000.0;
1191 // Compute the CPS value
1195 CurrentCPS
= FetchedBytes
/Delta
;
1196 LastBytes
= CurrentBytes
;
1197 ElapsedTime
= (unsigned long long)Delta
;
1200 // AcquireStatus::Fetched - Called when a byte set has been fetched /*{{{*/
1201 // ---------------------------------------------------------------------
1202 /* This is used to get accurate final transfer rate reporting. */
1203 void pkgAcquireStatus::Fetched(unsigned long long Size
,unsigned long long Resume
)
1205 FetchedBytes
+= Size
- Resume
;
1209 pkgAcquire::UriIterator::UriIterator(pkgAcquire::Queue
*Q
) : d(NULL
), CurQ(Q
), CurItem(0)
1211 while (CurItem
== 0 && CurQ
!= 0)
1213 CurItem
= CurQ
->Items
;
1218 APT_CONST
pkgAcquire::UriIterator::~UriIterator() {}
1219 APT_CONST
pkgAcquire::MethodConfig::~MethodConfig() {}
1220 APT_CONST
pkgAcquireStatus::~pkgAcquireStatus() {}