-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Expand file tree
/
Copy pathIDisk.cpp
More file actions
331 lines (288 loc) · 10.9 KB
/
IDisk.cpp
File metadata and controls
331 lines (288 loc) · 10.9 KB
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
#include <Disks/IDisk.h>
#include <Core/ServerUUID.h>
#include <Disks/FakeDiskTransaction.h>
#include <IO/ReadBufferFromFileBase.h>
#include <IO/WriteBufferFromFileBase.h>
#include <IO/WriteHelpers.h>
#include <IO/copyData.h>
#include <Interpreters/Context.h>
#include <Storages/PartitionCommands.h>
#include <Poco/Logger.h>
#include <Poco/Util/AbstractConfiguration.h>
#include <Common/ThreadPool.h>
#include <Common/ZooKeeper/ZooKeeperCommon.h>
#include <Common/logger_useful.h>
#include <Common/setThreadName.h>
#include <Common/threadPoolCallbackRunner.h>
#include <boost/algorithm/string.hpp>
namespace CurrentMetrics
{
extern const Metric IDiskCopierThreads;
extern const Metric IDiskCopierThreadsActive;
extern const Metric IDiskCopierThreadsScheduled;
}
namespace DB
{
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
extern const int CANNOT_READ_ALL_DATA;
extern const int LOGICAL_ERROR;
}
IDisk::IDisk(const String & name_, const Poco::Util::AbstractConfiguration & config, const String & config_prefix)
: name(name_)
, copying_thread_pool(std::make_unique<ThreadPool>(
CurrentMetrics::IDiskCopierThreads,
CurrentMetrics::IDiskCopierThreadsActive,
CurrentMetrics::IDiskCopierThreadsScheduled,
config.getUInt(config_prefix + ".thread_pool_size", 16)))
{
}
IDisk::IDisk(const String & name_)
: name(name_)
, copying_thread_pool(std::make_unique<ThreadPool>(
CurrentMetrics::IDiskCopierThreads, CurrentMetrics::IDiskCopierThreadsActive, CurrentMetrics::IDiskCopierThreadsScheduled, 16))
{
}
IDisk::~IDisk() = default;
bool IDisk::isDirectoryEmpty(const String & path) const
{
return !iterateDirectory(path)->isValid();
}
void IDisk::copyFile( /// NOLINT
const String & from_file_path,
IDisk & to_disk,
const String & to_file_path,
const ReadSettings & read_settings,
const WriteSettings & write_settings,
const std::function<void()> & cancellation_hook
)
{
LOG_DEBUG(getLogger("IDisk"), "Copying from {} (path: {}) {} to {} (path: {}) {}.",
getName(), getPath(), from_file_path, to_disk.getName(), to_disk.getPath(), to_file_path);
auto in = readFile(from_file_path, read_settings);
auto out = to_disk.writeFile(to_file_path, DBMS_DEFAULT_BUFFER_SIZE, WriteMode::Rewrite, write_settings);
copyData(*in, *out, cancellation_hook);
out->finalize();
}
std::unique_ptr<ReadBufferFromFileBase> IDisk::readFileIfExists( /// NOLINT
const String & path,
const ReadSettings & settings,
std::optional<size_t> read_hint) const
{
if (existsFile(path))
return readFile(path, settings, read_hint);
else
return {};
}
DiskTransactionPtr IDisk::createTransaction()
{
return std::make_shared<FakeDiskTransaction>(*this);
}
void IDisk::removeSharedFiles(const RemoveBatchRequest & files, bool keep_all_batch_data, const NameSet & file_names_remove_metadata_only)
{
for (const auto & file : files)
{
bool keep_file = keep_all_batch_data || file_names_remove_metadata_only.contains(fs::path(file.path).filename());
if (file.if_exists)
removeSharedFileIfExists(file.path, keep_file);
else
removeSharedFile(file.path, keep_file);
}
}
std::unique_ptr<ReadBufferFromFileBase> IDisk::readEncryptedFile(const String &, const ReadSettings &) const
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "File encryption is not implemented for disk of type {}", getDataSourceDescription().type);
}
std::unique_ptr<WriteBufferFromFileBase> IDisk::writeEncryptedFile(const String &, size_t, WriteMode, const WriteSettings &) const
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "File encryption is not implemented for disk of type {}", getDataSourceDescription().type);
}
size_t IDisk::getEncryptedFileSize(const String &) const
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "File encryption is not implemented for disk of type {}", getDataSourceDescription().type);
}
size_t IDisk::getEncryptedFileSize(size_t) const
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "File encryption is not implemented for disk of type {}", getDataSourceDescription().type);
}
UInt128 IDisk::getEncryptedFileIV(const String &) const
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "File encryption is not implemented for disk of type {}", getDataSourceDescription().type);
}
void asyncCopy(
IDisk & from_disk,
String from_path,
IDisk & to_disk,
String to_path,
ThreadPoolCallbackRunnerLocal<void> & runner,
const ReadSettings & read_settings,
const WriteSettings & write_settings,
const std::function<void()> & cancellation_hook)
{
if (from_disk.existsFile(from_path))
{
runner.enqueueAndKeepTrack(
[&from_disk, from_path, &to_disk, to_path, &read_settings, &write_settings, &cancellation_hook] {
from_disk.copyFile(
from_path, to_disk, to_path, read_settings, write_settings, cancellation_hook);
});
}
else /// Directory
{
fs::path dest(to_path);
to_disk.createDirectories(dest);
/// Calling asyncCopy recursively is fine here. Each call will capture by reference what were already references
/// dest is an exception, but it's passed as value, not reference
for (auto it = from_disk.iterateDirectory(from_path); it->isValid(); it->next())
asyncCopy(from_disk, it->path(), to_disk, dest / it->name(), runner, read_settings, write_settings, cancellation_hook);
}
}
void IDisk::copyThroughBuffers(
const String & from_path,
const std::shared_ptr<IDisk> & to_disk,
const String & to_path,
const ReadSettings & read_settings,
WriteSettings write_settings,
const std::function<void()> & cancellation_hook)
{
ThreadPoolCallbackRunnerLocal<void> runner(*copying_thread_pool, ThreadName::ASYNC_COPY);
/// Disable parallel write. We already copy in parallel.
/// Avoid high memory usage. See test_s3_zero_copy_ttl/test.py::test_move_and_s3_memory_usage
write_settings.s3_allow_parallel_part_upload = false;
write_settings.azure_allow_parallel_part_upload = false;
/// This will capture by reference, which is fine since we got references ourselves and runner will be destroyed before returning
asyncCopy(*this, from_path, *to_disk, to_path, runner, read_settings, write_settings, cancellation_hook);
runner.waitForAllToFinishAndRethrowFirstError();
}
void IDisk::copyDirectoryContent(
const String & from_dir,
const std::shared_ptr<IDisk> & to_disk,
const String & to_dir,
const ReadSettings & read_settings,
const WriteSettings & write_settings,
const std::function<void()> & cancellation_hook)
{
copyThroughBuffers(from_dir, to_disk, to_dir, read_settings, write_settings, cancellation_hook);
}
void IDisk::truncateFile(const String &, size_t)
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Truncate operation is not implemented for disk of type {}", getDataSourceDescription().type);
}
SyncGuardPtr IDisk::getDirectorySyncGuard(const String & /* path */) const
{
return nullptr;
}
void IDisk::startup(bool skip_access_check)
{
auto component_guard = Coordination::setCurrentComponent("IDisk::startup");
if (!skip_access_check)
{
if (isReadOnly())
{
LOG_DEBUG(getLogger("IDisk"),
"Skip access check for disk {} (read-only disk).",
getName());
}
else
checkAccess();
}
startupImpl();
}
void IDisk::checkAccess()
{
DB::UUID server_uuid = DB::ServerUUID::get();
if (server_uuid == DB::UUIDHelpers::Nil)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Server UUID is not initialized");
const String path = fmt::format("clickhouse_access_check_{}", toString(server_uuid));
checkAccessImpl(path);
}
/// NOTE: should we mark the disk readonly if the write/unlink fails instead of throws?
void IDisk::checkAccessImpl(const String & path)
try
{
const std::string_view payload("test", 4);
const auto read_settings = getReadSettings();
auto write_settings = getWriteSettings();
write_settings.is_initial_access_check = true;
/// write
{
auto file = writeFile(path, std::min<size_t>(DBMS_DEFAULT_BUFFER_SIZE, payload.size()), WriteMode::Rewrite, write_settings);
try
{
file->write(payload.data(), payload.size());
file->finalize();
}
catch (...)
{
/// Log current exception, because finalize() can throw a different exception.
tryLogCurrentException(__PRETTY_FUNCTION__);
throw;
}
}
/// read
{
auto file = readFile(path, read_settings);
String buf(payload.size(), '0');
file->readStrict(buf.data(), buf.size());
if (buf != payload)
{
throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA,
"Content of {}::{} does not matches after read ({} vs {})", name, path, buf, payload);
}
}
/// read with offset
{
auto file = readFile(path, read_settings);
auto offset = 2;
String buf(payload.size() - offset, '0');
file->seek(offset, 0);
file->readStrict(buf.data(), buf.size());
if (buf != payload.substr(offset))
{
throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA,
"Content of {}::{} does not matches after read with offset ({} vs {})", name, path, buf, payload.substr(offset));
}
}
/// check case sensitivity
{
std::unique_lock lock(case_sensitivity_check_mutex);
is_case_insensitive = existsFile(boost::to_upper_copy(path));
is_case_sensitivity_checked = true;
}
/// remove
removeFile(path);
}
catch (Exception & e)
{
e.addMessage(fmt::format("While checking access for disk {}", name));
throw;
}
bool IDisk::isCaseInsensitive()
{
/// For readonly disk we cannot perform the case sensitivity check.
if (isReadOnly())
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot check if filesystem is case insensitive: disk {} is readonly", name);
if (is_case_sensitivity_checked)
return is_case_insensitive;
std::unique_lock lock(case_sensitivity_check_mutex);
const String path = fmt::format("clickhouse_case_sensitivity_check_{}", toString(DB::UUIDHelpers::generateV4()));
try
{
createFile(path);
is_case_insensitive = existsFile(boost::to_upper_copy(path));
is_case_sensitivity_checked = true;
removeFile(path);
}
catch (Exception & e)
{
e.addMessage(fmt::format("While checking case sensitivity for disk {}", name));
throw;
}
return is_case_insensitive;
}
void IDisk::applyNewSettings(const Poco::Util::AbstractConfiguration & config, ContextPtr /*context*/, const String & config_prefix, const DisksMap & /*map*/)
{
copying_thread_pool->setMaxThreads(config.getInt(config_prefix + ".thread_pool_size", 16));
}
}