summaryrefslogtreecommitdiff
path: root/src/files_finder.cc
blob: fef05ba2f196a0399461553b67627a07e8c43537 (plain)
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
#include "common.hh"

#include "files_finder.hh"
#include "io.hh"
#include "logger.hh"
#include "task_runner.hh"
#include "unique_fd.hh"
#include "weak_ptr.hh"

#include <condition_variable>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <mutex>
#include <optional>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

namespace {

constexpr uint8_t kMaxQueued = 128;

class FilesFinderImpl : public FilesFinder {
public:
  FilesFinderImpl(
    std::shared_ptr<Logger> logger,
    std::shared_ptr<TaskRunner> runner,
    std::filesystem::path root,
    Delegate* delegate,
    size_t threads)
    : logger_(std::move(logger)), runner_(std::move(runner)),
      workers_(TaskRunner::create(threads)), root_(std::move(root)),
      delegate_(delegate) {
    workers_->post(std::bind(&FilesFinderImpl::open_root, this));
  }

private:
  void open_root() {
    unique_fd fd = io::open(
        root_, io::open_flags::rdonly | io::open_flags::directory);
    if (fd) {
      increment_queued();
      list_dir(std::move(fd), root_, 0);
    } else {
      logger_->warn("Unable to open %s: %s", root_.c_str(), strerror(errno));
      runner_->post(std::bind(&Delegate::done, delegate_));
    }
  }

  void open_dir(int fd, std::filesystem::path path, uint16_t depth) {
    list_dir(unique_fd(fd), path, depth);
  }

  void list_dir(unique_fd fd, std::filesystem::path path, uint16_t depth) {
    DIR* dh = fdopendir(fd.get());
    if (!dh) {
      logger_->warn("Unable to list %s: %s", path.c_str(), strerror(errno));
      return;
    }
    fd.release();  // fd is now owned by dh
    while (true) {
      errno = 0;
      auto* de = readdir(dh);
      if (!de) {
        if (errno)
          logger_->warn("Error listing %s: %s", path.c_str(), strerror(errno));
        break;
      }
      size_t namlen;
#ifdef _DIRENT_HAVE_D_NAMLEN
      namlen = de->d_namlen;
#else
      namlen = strlen(de->d_name);
#endif
      if (namlen == 2 && de->d_name[0] == '.' && de->d_name[1] == '.')
        continue;
      std::optional<bool> is_dir;
#ifdef _DIRENT_HAVE_D_TYPE
      switch (de->d_type) {
      case DT_DIR:
        is_dir = true;
        break;
      case DT_CHR:
      case DT_FIFO:
      case DT_BLK:
      case DT_REG:
      case DT_SOCK:
      case DT_WHT:
        is_dir = false;
        break;
      case DT_LNK:
      case DT_UNKNOWN:
      default:
        break;
      }
#endif
      if (!is_dir.has_value()) {
        struct stat buf;
        if (fstatat(dirfd(dh), de->d_name, &buf, 0)) {
          logger_->warn("Unable to stat: %s/%s: %s",
                        path.c_str(), de->d_name, strerror(errno));
          continue;
        }
        is_dir = S_ISDIR(buf.st_mode);
      }

      std::string_view name(de->d_name, namlen);

      if (is_dir.value()) {
        if (delegate_->include_dir(name, depth)) {
          unique_fd new_fd = io::openat(
              dirfd(dh), de->d_name,
              io::open_flags::rdonly | io::open_flags::directory);
          if (new_fd) {
            increment_queued();
            workers_->post(std::bind(&FilesFinderImpl::open_dir, this,
                                     new_fd.release(), path / name,
                                     depth + 1));
          } else {
            logger_->warn("Unable to open %s/%s: %s", path.c_str(), de->d_name,
                          strerror(errno));
          }
        }
      } else {
        if (delegate_->include_file(name, depth)) {
          increment_active();
          runner_->post(std::bind(
                            &FilesFinderImpl::weak_call_file,
                            weak_ptr_owner_.get(),
                            path / name));
        }
      }
    }
    closedir(dh);

    decrement_queued();
  }

  void increment_queued() {
    // Queued is used both to keep track of when done() should be called
    // but also to max sure we don't queued too many directories as
    // each queued entry costs one open file.
    std::unique_lock<std::mutex> lock(queued_mutex_);
    while (queued_ >= kMaxQueued) {
      queued_cond_.wait(lock);
    }
    ++queued_;
  }

  void increment_active() {
    std::lock_guard<std::mutex> lock(queued_mutex_);
    ++active_;
  }

  void decrement_queued() {
    bool notify;
    bool post_done;
    {
      std::lock_guard<std::mutex> lock(queued_mutex_);
      notify = queued_ >= kMaxQueued;
      --queued_;
      post_done = queued_ == 0 && active_ == 0;
    }
    if (notify)
      queued_cond_.notify_one();
    if (post_done)
      runner_->post(std::bind(&Delegate::done, delegate_));
  }

  void decrement_active() {
    bool post_done;
    {
      std::lock_guard<std::mutex> lock(queued_mutex_);
      --active_;
      post_done = queued_ == 0 && active_ == 0;
    }
    if (post_done)
      runner_->post(std::bind(&Delegate::done, delegate_));
  }

  static void weak_call_file(std::shared_ptr<WeakPtr<FilesFinderImpl>> weak_ptr,
                             std::filesystem::path path) {
    auto* ptr = weak_ptr->get();
    if (ptr)
      ptr->call_file(std::move(path));
  }

  void call_file(std::filesystem::path path) {
    delegate_->file(std::move(path));
    decrement_active();
  }

  std::shared_ptr<Logger> logger_;
  std::shared_ptr<TaskRunner> runner_;
  std::shared_ptr<TaskRunner> workers_;
  std::filesystem::path const root_;
  Delegate* const delegate_;

  std::mutex queued_mutex_;
  std::condition_variable queued_cond_;
  uint8_t queued_{0};
  size_t active_{0};

  WeakPtrOwner<FilesFinderImpl> weak_ptr_owner_{this};
};

}  // namespace

bool FilesFinder::Delegate::include_file(std::string_view name,
                                         uint16_t /* depth */) const {
  return name.empty() || name.front() != '.';
}

bool FilesFinder::Delegate::include_dir(std::string_view name,
                                        uint16_t /* depth */) const {
  return name.empty() || name.front() != '.';
}

void FilesFinder::Delegate::done() {}

std::unique_ptr<FilesFinder> FilesFinder::create(
    std::shared_ptr<Logger> logger,
    std::shared_ptr<TaskRunner> runner,
    std::filesystem::path root,
    Delegate* delegate,
    size_t threads) {
  return std::make_unique<FilesFinderImpl>(std::move(logger), std::move(runner),
                                           std::move(root), delegate, threads);
}