Imported Upstream version 15.0.0
[platform/upstream/libzypp.git] / zypp / DiskUsageCounter.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/DiskUsageCounter.cc
10  *
11  */
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"
28 #include "zypp/sat/detail/PoolImpl.h"
29
30 using std::endl;
31
32 ///////////////////////////////////////////////////////////////////
33 namespace zypp
34 { /////////////////////////////////////////////////////////////////
35
36   ///////////////////////////////////////////////////////////////////
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
85     /////////////////////////////////////////////////////////////////
86   } // namespace
87   ///////////////////////////////////////////////////////////////////
88
89   DiskUsageCounter::MountPointSet DiskUsageCounter::disk_usage( const ResPool & pool_r ) const
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
105   DiskUsageCounter::MountPointSet DiskUsageCounter::disk_usage( sat::Solvable solv_r ) const
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
117   DiskUsageCounter::MountPointSet DiskUsageCounter::disk_usage( const Bitmap & bitmap_r ) const
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
126   DiskUsageCounter::MountPointSet DiskUsageCounter::detectMountPoints( const std::string & rootdir )
127   {
128     DiskUsageCounter::MountPointSet ret;
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
306   DiskUsageCounter::MountPointSet DiskUsageCounter::justRootPartition()
307   {
308     DiskUsageCounter::MountPointSet ret;
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
326   /////////////////////////////////////////////////////////////////
327 } // namespace zypp
328 ///////////////////////////////////////////////////////////////////