-
-
Notifications
You must be signed in to change notification settings - Fork 125
/
DirReadJob.cpp
892 lines (688 loc) · 20 KB
/
DirReadJob.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
/*
* File name: DirReadJob.cpp
* Summary: Support classes for QDirStat
* License: GPL V2 - See file LICENSE for details.
*
* Author: Stefan Hundhammer <Stefan.Hundhammer@gmx.de>
*/
#include <dirent.h> // struct dirent
#include <fcntl.h> // AT_ constants (fstatat() flags)
#include <unistd.h> // R_OK, X_OK
#include <QMutableListIterator>
#include <QMultiMap>
#include "DirReadJob.h"
#include "DirTree.h"
#include "DirInfo.h"
#include "DirTreeCache.h"
#include "ExcludeRules.h"
#include "MountPoints.h"
#include "Exception.h"
#define DONT_TRUST_NTFS_HARD_LINKS 1
#define VERBOSE_NTFS_HARD_LINKS 0
using namespace QDirStat;
DirReadJob::DirReadJob( DirTree * tree,
DirInfo * dir ):
_tree( tree ),
_dir( dir ),
_queue( 0 )
{
_started = false;
if ( _dir )
_dir->readJobAdded();
}
DirReadJob::~DirReadJob()
{
if ( ! _tree->beingDestroyed() )
{
// Only do this if the tree is not in the process of being destroyed;
// otherwise all FileInfo / DirInfo pointers pointing into that tree
// may already be invalid. And even if they are not, it is now
// pointless to do all the housekeeping stuff to finalize the read job:
// We'd be beautifying the tree content that is now being destroyed.
//
// https://github.com/shundhammer/qdirstat/issues/122
if ( _dir )
_dir->readJobFinished( _dir );
}
}
/**
* Default implementation - derived classes should overwrite this method or
* startReading() (or both).
**/
void DirReadJob::read()
{
if ( ! _started )
{
_started = true;
startReading();
// Don't do anything after startReading() - startReading() might call
// finished() which in turn makes the queue destroy this object
}
}
void DirReadJob::setDir( DirInfo * dir )
{
_dir = dir;
}
void DirReadJob::finished()
{
if ( _queue )
_queue->jobFinishedNotify( this );
else
logError() << "No job queue for " << _dir << endl;
}
void DirReadJob::childAdded( FileInfo *newChild )
{
_tree->childAddedNotify( newChild );
}
void DirReadJob::deletingChild( FileInfo *deletedChild )
{
_tree->deletingChildNotify( deletedChild );
}
bool DirReadJob::crossingFilesystems( DirInfo * parent, DirInfo * child )
{
// Simple (and most common) case: Compare the device numbers (dev_t)
if ( parent->device() == child->device() )
return false; // Not crossing filesystems
// Less common case: Different device numbers. So let's also find the
// nearest mount point from /proc/mounts and compare the device names
// (/dev/sda2 etc.).
//
// This is important both for Btrfs subvolumes that all have the same
// device name, and for a directory tree that was originally read from a
// cache file, but now a subtree is being read from disk (F6 key).
//
// See also https://github.com/shundhammer/qdirstat/issues/273
QString parentDevice = device( parent );
QString childDevice = device( child );
bool crossing = ( parentDevice != childDevice );
if ( crossing )
{
logInfo() << "Filesystem boundary at mount point " << child
<< " on device " << ( childDevice.isEmpty() ? "<unknown>" : childDevice )
<< endl;
}
else
{
logInfo() << child << " is still on the same device " << childDevice << endl;
}
return crossing;
}
QString DirReadJob::device( const DirInfo * dir ) const
{
QString device;
if ( dir )
{
MountPoint * mountPoint = MountPoints::findByPath( dir->url() );
if ( ! mountPoint )
mountPoint = MountPoints::findNearestMountPoint( dir->url() );
if ( mountPoint )
{
device = mountPoint->device();
// logDebug() << "Found " << mountPoint << " for " << dir << endl;
}
}
return device;
}
bool DirReadJob::shouldCrossIntoFilesystem( const DirInfo * dir ) const
{
MountPoint * mountPoint = MountPoints::findByPath( dir->url() );
if ( ! mountPoint )
{
logError() << "Can't find mount point for " << dir->url() << endl;
return false;
}
bool doCross =
! mountPoint->isSystemMount() && // /dev, /proc, /sys, ...
! mountPoint->isDuplicate() && // bind mount or multiple mounted
! mountPoint->isNetworkMount(); // NFS or CIFS (Samba)
logDebug() << ( doCross ? "Reading" : "Not reading" )
<< " mounted filesystem " << mountPoint->path() << endl;
return doCross;
}
bool LocalDirReadJob::_warnedAboutNtfsHardLinks = false;
LocalDirReadJob::LocalDirReadJob( DirTree * tree,
DirInfo * dir ):
DirReadJob( tree, dir ),
_applyFileChildExcludeRules( false ),
_checkedForNtfs( false ),
_isNtfs( false )
{
if ( _dir )
_dirName = _dir->url();
}
LocalDirReadJob::~LocalDirReadJob()
{
// NOP
}
void LocalDirReadJob::startReading()
{
struct dirent * entry;
struct stat statInfo;
QString defaultCacheName = DEFAULT_CACHE_NAME;
DIR * diskDir;
// logDebug() << _dir << endl;
bool ok = true;
if ( access( _dirName.toUtf8(), X_OK | R_OK ) != 0 )
{
ok = false;
logWarning() << "No permission to read directory " << _dirName << endl;
finishReading( _dir, DirPermissionDenied );
}
if ( ok )
{
diskDir = ::opendir( _dirName.toUtf8() );
if ( ! diskDir )
{
logWarning() << "opendir(" << _dirName << ") failed" << endl;
ok = false;
// opendir() doesn't set 'errno' according to POSIX :-(
finishReading( _dir, DirError );
}
}
if ( ok )
{
_dir->setReadState( DirReading );
int dirFd = dirfd( diskDir );
int flags = AT_SYMLINK_NOFOLLOW;
#ifdef AT_NO_AUTOMOUNT
flags |= AT_NO_AUTOMOUNT;
#endif
QMultiMap<ino_t, QString> entryMap;
while ( ( entry = readdir( diskDir ) ) )
{
QString entryName = QString::fromUtf8( entry->d_name );
if ( entryName != "." &&
entryName != ".." )
{
entryMap.insert( entry->d_ino, entryName );
}
}
// QMultiMap (just like QMap) guarantees sort order by keys, so we are
// now iterating over the directory entries by i-number order. Most
// filesystems will benefit from that since they store i-nodes sorted
// by i-number on disk, so (at least with rotational disks) seek times
// are minimized by this strategy.
//
// Notice that we need a QMultiMap, not just a map: If a file has
// multiple hard links in the same directory, a QMap would store only
// one of them, all others would go missing in the DirTree.
foreach ( QString entryName, entryMap )
{
if ( fstatat( dirFd, entryName.toUtf8(), &statInfo, flags ) == 0 ) // OK?
{
if ( S_ISDIR( statInfo.st_mode ) ) // directory child?
{
DirInfo *subDir = new DirInfo( entryName, &statInfo, _tree, _dir );
CHECK_NEW( subDir );
processSubDir( entryName, subDir );
}
else // non-directory child
{
if ( entryName == defaultCacheName ) // .qdirstat.cache.gz found?
{
logDebug() << "Found cache file " << defaultCacheName << endl;
// Try to read the cache file. If that was successful and the toplevel
// path in that cache file matches the path of the directory we are
// reading right now, the directory is finished reading, the read job
// (this object) was just deleted, and we may no longer access any
// member variables; just return.
if ( readCacheFile( entryName ) )
return;
}
#if DONT_TRUST_NTFS_HARD_LINKS
if ( statInfo.st_nlink > 1 && isNtfs() )
{
// NTFS seems to return bogus hard link counts; use 1 instead.
// See https://github.com/shundhammer/qdirstat/issues/88
#if ! VERBOSE_NTFS_HARD_LINKS
if ( ! _warnedAboutNtfsHardLinks )
#endif
{
logWarning() << "Not trusting NTFS with hard links: \""
<< _dir->url() << "/" << entryName
<< "\" links: " << statInfo.st_nlink
<< " -> resetting to 1"
<< endl;
_warnedAboutNtfsHardLinks = true;
}
statInfo.st_nlink = 1;
}
#endif
FileInfo * child = new FileInfo( entryName, &statInfo, _tree, _dir );
CHECK_NEW( child );
if ( checkIgnoreFilters( entryName ) )
{
// logDebug() << "Ignoring " << child << endl;
_dir->addToAttic( child );
}
else
_dir->insertChild( child );
childAdded( child );
}
}
else // lstat() error
{
handleLstatError( entryName );
}
}
closedir( diskDir );
DirReadState readState = DirFinished;
//
// Check all entries against exclude rules that match against any
// direct non-directory entry.
//
// Doing this now is a performance optimization: This could also be
// done immediately after each entry is read, but that would mean
// iterating over all exclude rules for every single directory entry,
// even if there are no exclude rules that match against any
// files, so it would be a general performance penalty.
//
// Doing this after all entries are read means more cleanup if any
// exclude rule does match, but that is the exceptional case; if there
// are no such rules to begin with, the match function returns 'false'
// immediately, so the performance impact is minimal.
//
// Also intentionally not also checking the DirTree specific exclude
// rules here: They are meant strictly for directory exclude rules.
if ( _applyFileChildExcludeRules &&
ExcludeRules::instance()->matchDirectChildren( _dir ) )
{
excludeDirLate();
readState = DirOnRequestOnly;
}
finishReading( _dir, readState );
}
finished();
// Don't add anything after finished() since this deletes this job!
}
void LocalDirReadJob::finishReading( DirInfo * dir, DirReadState readState )
{
// logDebug() << dir << endl;
CHECK_PTR( dir );
dir->setReadState( readState );
dir->finalizeLocal();
_tree->sendReadJobFinished( dir );
}
void LocalDirReadJob::processSubDir( const QString & entryName, DirInfo * subDir )
{
_dir->insertChild( subDir );
childAdded( subDir );
if ( matchesExcludeRule( entryName ) )
{
subDir->setExcluded();
finishReading( subDir, DirOnRequestOnly );
}
else // No exclude rule matched
{
if ( ! crossingFilesystems(_dir, subDir ) ) // normal case
{
LocalDirReadJob * job = new LocalDirReadJob( _tree, subDir );
CHECK_NEW( job );
job->setApplyFileChildExcludeRules( true );
_tree->addJob( job );
}
else // The subdirectory we just found is a mount point.
{
subDir->setMountPoint();
if ( _tree->crossFilesystems() && shouldCrossIntoFilesystem( subDir ) )
{
LocalDirReadJob * job = new LocalDirReadJob( _tree, subDir );
CHECK_NEW( job );
job->setApplyFileChildExcludeRules( true );
_tree->addJob( job );
}
else
{
finishReading( subDir, DirOnRequestOnly );
}
}
}
}
bool LocalDirReadJob::matchesExcludeRule( const QString & entryName ) const
{
QString full = fullName( entryName );
if ( ExcludeRules::instance()->match( full, entryName ) )
return true;
if ( ! _tree->excludeRules() )
return false;
return _tree->excludeRules()->match( full, entryName );
}
bool LocalDirReadJob::checkIgnoreFilters( const QString & entryName ) const
{
if ( ! _tree->hasFilters() )
return false;
return _tree->checkIgnoreFilters( fullName( entryName ) );
}
bool LocalDirReadJob::readCacheFile( const QString & cacheFileName )
{
QString cacheFullName = fullName( cacheFileName );
CacheReadJob * cacheReadJob = new CacheReadJob( _tree, _dir->parent(), cacheFullName );
CHECK_NEW( cacheReadJob );
QString firstDirInCache = cacheReadJob->reader()->firstDir();
if ( firstDirInCache == _dirName ) // Does this cache file match this directory?
{
logDebug() << "Using cache file " << cacheFullName << " for " << _dirName << endl;
DirTree * tree = _tree; // Copy data members to local variables:
DirInfo * dir = _dir; // This object might be deleted soon by killAll()
if ( _tree->isToplevel( _dir ) )
{
logDebug() << "Clearing complete tree" << endl;
_tree->clearAndReadCache( cacheFullName );
// Since this clears the tree and thus the job queue and thus
// deletes this read job, it is important not to do anything after
// this point that might access any member variables or even just
// uses any virtual method.
return true;
}
else
{
cacheReadJob->reader()->rewind(); // Read offset was moved by firstDir()
_tree->addJob( cacheReadJob ); // The job queue will assume ownership of cacheReadJob
if ( _dir->parent() )
_dir->parent()->setReadState( DirReading );
//
// Clean up partially read directory content
//
_queue->killAll( _dir, cacheReadJob ); // Will delete this job as well!
// All data members of this object are invalid from here on!
logDebug() << "Deleting subtree " << dir << endl;
tree->deleteSubtree( dir );
}
return true;
}
else
{
logWarning() << "NOT using cache file " << cacheFullName
<< " with dir " << firstDirInCache
<< " for " << _dirName
<< endl;
delete cacheReadJob;
return false;
}
}
void LocalDirReadJob::excludeDirLate()
{
logDebug() << "Excluding dir " << _dir << endl;
// Kill all queued jobs for this dir except this one
_queue->killAll( _dir, this );
_tree->clearSubtree( _dir );
_dir->setExcluded();
}
void LocalDirReadJob::handleLstatError( const QString & entryName )
{
logWarning() << "lstat(" << fullName( entryName ) << ") failed: "
<< formatErrno() << endl;
/*
* Not much we can do when lstat() didn't work; let's at
* least create an (almost empty) entry as a placeholder.
*/
DirInfo *child = new DirInfo( _tree, _dir, entryName,
0, // mode
0, // size
false, 0, 0, // withUidGid, uid, gid
0 ); // mtime
CHECK_NEW( child );
child->finalizeLocal();
child->setReadState( DirError );
_dir->insertChild( child );
childAdded( child );
}
QString LocalDirReadJob::fullName( const QString & entryName ) const
{
QString result = _dirName == "/" ? "" : _dirName; // Avoid leading // when in root dir
result += "/" + entryName;
return result;
}
FileInfo * LocalDirReadJob::stat( const QString & url,
DirTree * tree,
DirInfo * parent,
bool doThrow )
{
struct stat statInfo;
// logDebug() << "url: \"" << url << "\"" << endl;
if ( lstat( url.toUtf8(), &statInfo ) == 0 ) // lstat() OK
{
QString name = url;
if ( parent && parent != tree->root() )
{
QStringList components = url.split( "/", QString::SkipEmptyParts );
name = components.last();
}
if ( S_ISDIR( statInfo.st_mode ) ) // directory?
{
DirInfo * dir = new DirInfo( name, &statInfo, tree, parent );
CHECK_NEW( dir );
if ( parent )
parent->insertChild( dir );
if ( dir && parent &&
! tree->isToplevel( dir ) &&
! parent->isPkgInfo() &&
dir->device() != parent->device() )
{
logDebug() << dir << " is a mount point" << endl;
dir->setMountPoint();
}
return dir;
}
else // no directory
{
FileInfo * file = new FileInfo( name, &statInfo, tree, parent );
CHECK_NEW( file );
if ( parent )
parent->insertChild( file );
return file;
}
}
else // lstat() failed
{
if ( doThrow )
THROW( SysCallFailedException( "lstat", url ) );
return 0;
}
}
bool LocalDirReadJob::isNtfs()
{
if ( ! MountPoints::hasNtfs() )
return false;
if ( ! _checkedForNtfs )
{
_isNtfs = false;
_checkedForNtfs = true;
if ( ! _dirName.isEmpty() )
{
MountPoint * mountPoint = MountPoints::findNearestMountPoint( _dirName );
_isNtfs = mountPoint && mountPoint->isNtfs();
}
}
return _isNtfs;
}
CacheReadJob::CacheReadJob( DirTree * tree,
DirInfo * parent,
CacheReader * reader )
: ObjDirReadJob( tree, parent )
, _reader( reader )
{
if ( _reader )
_reader->rewind();
init();
}
CacheReadJob::CacheReadJob( DirTree * tree,
DirInfo * parent,
const QString & cacheFileName )
: ObjDirReadJob( tree, parent )
{
_reader = new CacheReader( cacheFileName, tree, parent );
CHECK_NEW( _reader );
init();
}
void CacheReadJob::init()
{
if ( _reader )
{
if ( _reader->ok() )
{
connect( _reader, SIGNAL( childAdded ( FileInfo * ) ),
this, SLOT ( slotChildAdded( FileInfo * ) ) );
}
else
{
delete _reader;
_reader = 0;
}
}
}
CacheReadJob::~CacheReadJob()
{
if ( _reader )
delete _reader;
}
void CacheReadJob::read()
{
/*
* This will be called repeatedly from DirTree::timeSlicedRead() until
* finished() is called.
*/
if ( ! _reader )
{
finished();
return;
}
// logDebug() << "Reading 1000 cache lines" << endl;
_reader->read( 1000 );
if ( _reader->eof() || ! _reader->ok() )
{
// logDebug() << "Cache reading finished - ok: " << _reader->ok() << endl;
finished();
}
}
DirReadJobQueue::DirReadJobQueue()
: QObject()
{
connect( &_timer, SIGNAL( timeout() ),
this, SLOT ( timeSlicedRead() ) );
}
DirReadJobQueue::~DirReadJobQueue()
{
clear();
}
void DirReadJobQueue::enqueue( DirReadJob * job )
{
if ( job )
{
_queue.append( job );
job->setQueue( this );
if ( ! _timer.isActive() )
{
// logDebug() << "First job queued" << endl;
emit startingReading();
_timer.start( 0 );
}
}
}
DirReadJob * DirReadJobQueue::dequeue()
{
DirReadJob * job = _queue.takeFirst();
if ( job )
job->setQueue( 0 );
return job;
}
void DirReadJobQueue::clear()
{
qDeleteAll( _queue );
qDeleteAll( _blocked );
_queue.clear();
_blocked.clear();
}
void DirReadJobQueue::abort()
{
foreach ( DirReadJob * job, _queue )
{
if ( job->dir() )
job->dir()->readJobAborted( job->dir() );
}
foreach ( DirReadJob * job, _blocked )
{
if ( job->dir() )
job->dir()->readJobAborted( job->dir() );
}
clear();
}
void DirReadJobQueue::killAll( DirInfo * subtree, DirReadJob * exceptJob )
{
if ( ! subtree )
return;
QMutableListIterator<DirReadJob *> it( _queue );
int count = 0;
while ( it.hasNext() )
{
DirReadJob * job = it.next();
if ( exceptJob && job == exceptJob )
{
logDebug() << "NOT killing " << job << endl;
continue;
}
if ( job->dir() && job->dir()->isInSubtree( subtree ) )
{
// logDebug() << "Killing " << job << endl;
++count;
it.remove();
delete job;
}
}
it = QMutableListIterator<DirReadJob *>( _blocked );
while ( it.hasNext() )
{
DirReadJob * job = it.next();
if ( exceptJob && job == exceptJob )
{
logDebug() << "NOT killing " << job << endl;
continue;
}
if ( job->dir() && job->dir()->isInSubtree( subtree ) )
{
// logDebug() << "Killing " << job << endl;
++count;
it.remove();
delete job;
}
}
logDebug() << "Killed " << count << " read jobs for " << subtree << endl;
}
void DirReadJobQueue::timeSlicedRead()
{
if ( _queue.isEmpty() )
_timer.stop();
else
_queue.first()->read();
}
void DirReadJobQueue::jobFinishedNotify( DirReadJob *job )
{
if ( job )
{
// Get rid of the old (finished) job.
_queue.removeOne( job );
delete job;
}
// The timer will start a new job when it fires.
if ( _queue.isEmpty() && _blocked.isEmpty() ) // No new job available - we're done.
emit finished();
}
void DirReadJobQueue::deletingChildNotify( FileInfo * child )
{
if ( child && child->isDirInfo() )
{
logDebug() << "Killing all pending read jobs for " << child << endl;
killAll( child->toDirInfo() );
}
}
void DirReadJobQueue::addBlocked( DirReadJob * job )
{
_blocked.append( job );
}
void DirReadJobQueue::unblock( DirReadJob * job )
{
_blocked.removeAll( job );
enqueue( job );
if ( _blocked.isEmpty() )
logDebug() << "No more jobs waiting for external processes" << endl;
}