libzypp  15.3.0
DiskUsageCounter.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 extern "C"
13 {
14 #include <sys/statvfs.h>
15 }
16 
17 #include <iostream>
18 #include <fstream>
19 
20 #include "zypp/base/Easy.h"
21 #include "zypp/base/LogTools.h"
22 #include "zypp/base/DtorReset.h"
23 #include "zypp/base/String.h"
24 
25 #include "zypp/DiskUsageCounter.h"
26 #include "zypp/ExternalProgram.h"
27 #include "zypp/sat/Pool.h"
29 
30 using std::endl;
31 
33 namespace zypp
34 {
35 
37  namespace
38  {
39 
40  DiskUsageCounter::MountPointSet calcDiskUsage( DiskUsageCounter::MountPointSet result, const Bitmap & installedmap_r )
41  {
42  if ( result.empty() )
43  {
44  // partitioning is not set
45  return result;
46  }
47 
48  sat::Pool satpool( sat::Pool::instance() );
49 
50  // init libsolv result vector with mountpoints
51  static const ::DUChanges _initdu = { 0, 0, 0, 0 };
52  std::vector< ::DUChanges> duchanges( result.size(), _initdu );
53  {
54  unsigned idx = 0;
55  for_( it, result.begin(), result.end() )
56  {
57  duchanges[idx].path = it->dir.c_str();
58  if ( it->growonly )
59  duchanges[idx].flags |= DUCHANGES_ONLYADD;
60  ++idx;
61  }
62  }
63  // now calc...
64  ::pool_calc_duchanges( satpool.get(),
65  const_cast<Bitmap &>(installedmap_r),
66  &duchanges[0],
67  duchanges.size() );
68 
69  // and process the result
70  {
71  unsigned idx = 0;
72  for_( it, result.begin(), result.end() )
73  {
74  static const ByteCount blockAdjust( 2, ByteCount::K ); // (files * blocksize) / (2 * 1K)
75  it->pkg_size = it->used_size // current usage
76  + duchanges[idx].kbytes // package data size
77  + ( duchanges[idx].files * it->block_size / blockAdjust ); // half block per file
78  ++idx;
79  }
80  }
81 
82  return result;
83  }
84 
86  } // namespace
88 
90  {
91  Bitmap bitmap( Bitmap::poolSize );
92 
93  // build installedmap (installed != transact)
94  // stays installed or gets installed
95  for_( it, pool_r.begin(), pool_r.end() )
96  {
97  if ( it->status().isInstalled() != it->status().transacts() )
98  {
99  bitmap.set( sat::asSolvable()(*it).id() );
100  }
101  }
102  return calcDiskUsage( _mps, bitmap );
103  }
104 
106  {
107  Bitmap bitmap( Bitmap::poolSize );
108  bitmap.set( solv_r.id() );
109 
110  // temp. unset @system Repo
111  DtorReset tmp( sat::Pool::instance().get()->installed );
112  sat::Pool::instance().get()->installed = nullptr;
113 
114  return calcDiskUsage( _mps, bitmap );
115  }
116 
118  {
119  // temp. unset @system Repo
120  DtorReset tmp( sat::Pool::instance().get()->installed );
121  sat::Pool::instance().get()->installed = nullptr;
122 
123  return calcDiskUsage( _mps, bitmap_r );
124  }
125 
127  {
129 
130  std::ifstream procmounts( "/proc/mounts" );
131 
132  if ( !procmounts ) {
133  WAR << "Unable to read /proc/mounts" << std::endl;
134  } else {
135 
136  std::string prfx;
137  if ( rootdir != "/" )
138  prfx = rootdir; // rootdir not /
139 
140  while ( procmounts ) {
141  std::string l = str::getline( procmounts );
142  if ( !(procmounts.fail() || procmounts.bad()) ) {
143  // data to consume
144 
145  // rootfs / rootfs rw 0 0
146  // /dev/root / reiserfs rw 0 0
147  // proc /proc proc rw 0 0
148  // devpts /dev/pts devpts rw 0 0
149  // /dev/hda5 /boot ext2 rw 0 0
150  // shmfs /dev/shm shm rw 0 0
151  // usbdevfs /proc/bus/usb usbdevfs rw 0 0
152 
153  std::vector<std::string> words;
154  str::split( l, std::back_inserter(words) );
155 
156  if ( words.size() < 3 ) {
157  WAR << "Suspicious entry in /proc/mounts: " << l << std::endl;
158  continue;
159  }
160 
161  //
162  // Filter devices without '/' (proc,shmfs,..)
163  //
164  if ( words[0].find( '/' ) == std::string::npos ) {
165  DBG << "Discard mount point : " << l << std::endl;
166  continue;
167  }
168 
169  // remove /proc entry
170  if (words[0] == "/proc")
171  {
172  DBG << "Discard /proc filesystem: " << l << std::endl;
173  continue;
174  }
175 
176  //
177  // Filter mountpoints not at or below _rootdir
178  //
179  std::string mp = words[1];
180  if ( prfx.size() ) {
181  if ( mp.compare( 0, prfx.size(), prfx ) != 0 ) {
182  // mountpoint not below rootdir
183  DBG << "Unwanted mount point : " << l << std::endl;
184  continue;
185  }
186  // strip prfx
187  mp.erase( 0, prfx.size() );
188  if ( mp.empty() ) {
189  mp = "/";
190  } else if ( mp[0] != '/' ) {
191  // mountpoint not below rootdir
192  DBG << "Unwanted mount point : " << l << std::endl;
193  continue;
194  }
195  }
196 
197  //
198  // Filter cdrom
199  //
200  if ( words[2] == "iso9660" ) {
201  DBG << "Discard cdrom : " << l << std::endl;
202  continue;
203  }
204 
205  if ( words[2] == "vfat" || words[2] == "fat" || words[2] == "ntfs" || words[2] == "ntfs-3g")
206  {
207  MIL << words[1] << " contains ignored fs (" << words[2] << ')' << std::endl;
208  continue;
209  }
210 
211  //
212  // Filter some common unwanted mountpoints
213  //
214  const char * mpunwanted[] = {
215  "/mnt", "/media", "/mounts", "/floppy", "/cdrom",
216  "/suse", "/var/tmp", "/var/adm/mount", "/var/adm/YaST",
217  /*last*/0/*entry*/
218  };
219 
220  const char ** nomp = mpunwanted;
221  for ( ; *nomp; ++nomp ) {
222  std::string pre( *nomp );
223  if ( mp.compare( 0, pre.size(), pre ) == 0 // mp has prefix pre
224  && ( mp.size() == pre.size() || mp[pre.size()] == '/' ) ) {
225  break;
226  }
227  }
228  if ( *nomp ) {
229  DBG << "Filter mount point : " << l << std::endl;
230  continue;
231  }
232 
233  //
234  // Check whether mounted readonly
235  //
236  MountPoint::HintFlags hints;
237 
238  std::vector<std::string> flags;
239  str::split( words[3], std::back_inserter(flags), "," );
240 
241  for ( unsigned i = 0; i < flags.size(); ++i ) {
242  if ( flags[i] == "ro" ) {
243  hints |= MountPoint::Hint_readonly;
244  break;
245  }
246  }
247  if ( hints.testFlag( MountPoint::Hint_readonly ) ) {
248  DBG << "Filter ro mount point : " << l << std::endl;
249  continue;
250  }
251 
252  //
253  // check for snapshotting btrfs
254  //
255  if ( words[2] == "btrfs" )
256  {
257  if ( geteuid() != 0 )
258  {
259  DBG << "Assume snapshots on " << words[1] << ": non-root user can't check" << std::endl;
260  hints |= MountPoint::Hint_growonly;
261  }
262  else
263  {
264  // For now just check whether there is
265  // at least one snapshot on the volume:
266  ExternalProgram prog({"btrfs","subvolume","list","-s",words[1]});
267  std::string line( prog.receiveLine() );
268  if ( ! line.empty() )
269  {
270  DBG << "Found a snapshot on " << words[1] << ": " << line; // has trailing std::endl
271  hints |= MountPoint::Hint_growonly;
272  }
273  prog.kill();
274  }
275  }
276 
277  //
278  // statvfs (full path!) and get the data
279  //
280  struct statvfs sb;
281  if ( statvfs( words[1].c_str(), &sb ) != 0 ) {
282  WAR << "Unable to statvfs(" << words[1] << "); errno " << errno << std::endl;
283  ret.insert( DiskUsageCounter::MountPoint( mp, words[2], 0LL, 0LL, 0LL, 0LL, hints ) );
284  }
285  else
286  {
287  //
288  // Filter zero sized devices (bnc#769819)
289  //
290  if ( sb.f_blocks == 0 || sb.f_bsize == 0 )
291  {
292  DBG << "Filter zero-sized mount point : " << l << std::endl;
293  continue;
294  }
295  ret.insert( DiskUsageCounter::MountPoint( mp, words[2], sb.f_bsize,
296  ((long long)sb.f_blocks)*sb.f_bsize/1024,
297  ((long long)(sb.f_blocks - sb.f_bfree))*sb.f_bsize/1024, 0LL, hints ) );
298  }
299  }
300  }
301  }
302 
303  return ret;
304  }
305 
307  {
309  ret.insert( DiskUsageCounter::MountPoint() );
310  return ret;
311  }
312 
313  std::ostream & operator<<( std::ostream & str, const DiskUsageCounter::MountPoint & obj )
314  {
315  str << "dir:[" << obj.dir << "] [ bs: " << obj.blockSize()
316  << " ts: " << obj.totalSize()
317  << " us: " << obj.usedSize()
318  << " (+-: " << obj.commitDiff()
319  << ")" << (obj.readonly?"r":"") << (obj.growonly?"g":"") << " " << obj.fstype << "]";
320  return str;
321  }
322 
323  std::ostream & operator<<( std::ostream & str, const DiskUsageCounter::MountPointSet & obj )
324  { return dumpRange( str, obj.begin(), obj.end() ); }
325 
327 } // namespace zypp
::_Pool * get() const
Expert backdoor.
Definition: Pool.cc:49
ByteCount blockSize() const
Block size of the filesystem as ByteCount for convenience.
#define MIL
Definition: Logger.h:64
A Solvable object within the sat Pool.
Definition: Solvable.h:55
const_iterator begin() const
Definition: ResPool.h:85
ByteCount commitDiff() const
Size change due to installation as ByteCount for convenience.
unsigned split(const C_Str &line_r, _OutputIterator result_r, const C_Str &sepchars_r=" \t")
Split line_r into words.
Definition: String.h:471
growonly partitions (e.g. snapshotting btrfs)
size_type size() const
Size of the Map.
Definition: Map.cc:59
static MountPointSet justRootPartition()
Only one entry for "/" to collect total sizes.
bool readonly
hint for readonly partitions
void set(size_type idx_r)
Set bit idx_r.
Definition: Map.cc:79
String related utilities and Regular expression matching.
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
Definition: Easy.h:27
const_iterator end() const
Definition: ResPool.h:88
Assign a vaiable a certain value when going out of scope.
Definition: DtorReset.h:49
std::string fstype
Filesystem type (provided by detectMountPoints)
std::set< MountPoint > MountPointSet
static Pool instance()
Singleton ctor.
Definition: Pool.h:52
std::ostream & dumpRange(std::ostream &str, _Iterator begin, _Iterator end, const std::string &intro="{", const std::string &pfx="\n ", const std::string &sep="\n ", const std::string &sfx="\n", const std::string &extro="}")
Print range defined by iterators (multiline style).
Definition: LogTools.h:91
std::ostream & operator<<(std::ostream &str, const Exception &obj)
Definition: Exception.cc:120
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
sat::Map Bitmap
Definition: Bitmap.h:19
#define WAR
Definition: Logger.h:65
Mount point description If block_size is set DiskUsageCoutner will assume half a block_size is wasted...
std::string dir
Directory name.
std::string getline(std::istream &str, const Trim trim_r)
Return stream content up to (but not returning) the next newline.
Definition: String.cc:376
ByteCount totalSize() const
Total size of the filesystem as ByteCount for convenience.
static constexpr PoolSizeType poolSize
An object indicating the bitmap should match the current pools capacity.
Definition: Map.h:44
Global ResObject pool.
Definition: ResPool.h:48
static const Unit K
1024 Byte
Definition: ByteCount.h:45
IdType id() const
Expert backdoor.
Definition: Solvable.h:288
MountPointSet disk_usage(const ResPool &pool) const
Compute disk usage if the current transaction woud be commited.
bool growonly
hint for growonly partitions (e.g. snapshotting btrfs)
Libsolv (bit)Map wrapper.
Definition: Map.h:36
To Solvable transform functor.
Definition: Solvable.h:390
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
ByteCount usedSize() const
Used size of the filesystem as ByteCount for convenience.
#define DBG
Definition: Logger.h:63
static MountPointSet detectMountPoints(const std::string &rootdir="/")
Get mountpoints of system below rootdir If we happen to detect snapshotting btrfs partitions...