-
Notifications
You must be signed in to change notification settings - Fork 8.7k
Expand file tree
/
Copy pathAsynchronousInsertQueue.h
More file actions
345 lines (278 loc) · 11.6 KB
/
Copy pathAsynchronousInsertQueue.h
File metadata and controls
345 lines (278 loc) · 11.6 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#pragma once
#include <Core/Block.h>
#include <Parsers/IAST_fwd.h>
#include <Processors/Chunk.h>
#include <Common/Logger.h>
#include <Common/MemoryTrackerSwitcher.h>
#include <Common/SettingsChanges.h>
#include <Common/SharedMutex.h>
#include <Common/ThreadPool.h>
#include <Common/StringWithMemoryTracking.h>
#include <Interpreters/AsynchronousInsertQueueDataKind.h>
#include <Interpreters/StorageID.h>
#include <Interpreters/Context_fwd.h>
#include <future>
#include <variant>
namespace DB
{
class ThreadGroup;
using ThreadGroupPtr = std::shared_ptr<ThreadGroup>;
struct Settings;
/// Statistics of a successfully flushed async insert entry,
/// communicated back to the waiting client via the future.
struct AsyncInsertProgress
{
size_t rows = 0;
size_t bytes = 0;
};
/// A queue, that stores data for insert queries and periodically flushes it to tables.
/// The data is grouped by table, format and settings of insert query.
class AsynchronousInsertQueue : public WithContext
{
public:
using Milliseconds = std::chrono::milliseconds;
using ResultProgress = AsyncInsertProgress;
AsynchronousInsertQueue(ContextPtr context_, size_t pool_size_, bool flush_on_shutdown_);
~AsynchronousInsertQueue();
struct PushResult
{
enum Status
{
OK,
TOO_MUCH_DATA,
};
Status status;
/// Future that allows to wait until the query is flushed.
/// On success, returns the number of rows/bytes actually written.
std::future<ResultProgress> future{};
/// Read buffer that contains extracted
/// from query data in case of too much data.
std::unique_ptr<ReadBuffer> insert_data_buffer{};
/// Block that contains received by Native
/// protocol data in case of too much data.
Block insert_block{};
};
static void validateSettings(const Settings & settings, LoggerPtr log);
/// Force flush the whole queue.
void flushAll();
void flush(const std::vector<StorageID> & tables);
PushResult pushQueryWithInlinedData(ASTPtr query, ContextPtr query_context);
PushResult pushQueryWithBlock(ASTPtr query, Block && block, ContextPtr query_context);
size_t getPoolSize() const { return pool_size; }
/// This method should be called manually because it's not flushed automatically in dtor
/// because all tables may be already unloaded when we destroy AsynchronousInsertQueue
void flushAndShutdown();
struct InsertQuery
{
public:
ASTPtr query;
String query_str;
std::optional<UUID> user_id;
std::vector<UUID> current_roles;
/// Client identity of the originating INSERT query (ClientInfo user names).
/// Restored on the flush context so currentUser()/user()/authenticatedUser() and
/// the materialized views triggered by the flush observe the inserting user instead
/// of an empty string. Part of the batching key so inserts from different identities
/// (e.g. impersonation, forwarded distributed queries) are never coalesced.
String current_user;
String initial_user;
String authenticated_user;
std::unique_ptr<Settings> settings;
AsynchronousInsertQueueDataKind data_kind;
UInt128 hash{};
InsertQuery(
const ASTPtr & query_,
const std::optional<UUID> & user_id_,
const std::vector<UUID> & current_roles_,
const String & current_user_,
const String & initial_user_,
const String & authenticated_user_,
const Settings & settings_,
AsynchronousInsertQueueDataKind data_kind_);
InsertQuery(const InsertQuery & other);
InsertQuery & operator=(const InsertQuery & other);
bool operator==(const InsertQuery & other) const;
StorageID getStorageID() const;
private:
auto toTupleCmp() const { return std::tie(data_kind, query_str, user_id, current_roles, current_user, initial_user, authenticated_user, setting_changes); }
std::vector<SettingChange> setting_changes;
};
private:
struct DataChunk : public std::variant<StringWithMemoryTracking, Block>
{
using std::variant<StringWithMemoryTracking, Block>::variant;
size_t byteSize() const
{
return std::visit([]<typename T>(const T & arg)
{
if constexpr (std::is_same_v<T, Block>)
return arg.bytes();
else
return arg.size();
}, *this);
}
AsynchronousInsertQueueDataKind getDataKind() const
{
if (std::holds_alternative<Block>(*this))
return AsynchronousInsertQueueDataKind::Preprocessed;
return AsynchronousInsertQueueDataKind::Parsed;
}
bool empty() const
{
return std::visit([]<typename T>(const T & arg)
{
if constexpr (std::is_same_v<T, Block>)
return arg.rows() == 0;
else
return arg.empty();
}, *this);
}
const StringWithMemoryTracking * asString() const { return std::get_if<StringWithMemoryTracking>(this); }
const Block * asBlock() const { return std::get_if<Block>(this); }
};
struct InsertData
{
struct Entry
{
public:
DataChunk chunk;
const String query_id;
const String async_dedup_token;
const String format;
MemoryTracker * const user_memory_tracker;
const std::chrono::time_point<std::chrono::system_clock> create_time;
NameToNameMap query_parameters;
Entry(
DataChunk && chunk_,
String && query_id_,
const String & async_dedup_token_,
const String & format_,
MemoryTracker * user_memory_tracker_);
void resetChunk();
void finish(ResultProgress result = {});
void finish(std::exception_ptr exception_);
std::future<ResultProgress> getFuture() { return promise.get_future(); }
bool isFinished() const { return finished; }
private:
std::promise<ResultProgress> promise;
std::atomic_bool finished = false;
};
InsertData()
: ready_future(ready_promise.get_future().share())
{ }
explicit InsertData(Milliseconds timeout_ms_)
: ready_future(ready_promise.get_future().share())
, timeout_ms(timeout_ms_)
{ }
~InsertData()
{
auto it = entries.begin();
// Entries must be destroyed in context of user who runs async insert.
// Each entry in the list may correspond to a different user,
// so we need to switch current thread's MemoryTracker parent on each iteration.
while (it != entries.end())
{
MemoryTrackerSwitcher switcher((*it)->user_memory_tracker);
it = entries.erase(it);
}
ready_promise.set_value();
}
using EntryPtr = std::shared_ptr<Entry>;
std::list<EntryPtr> entries;
std::promise<void> ready_promise;
std::shared_future<void> ready_future;
size_t size_in_bytes = 0;
Milliseconds timeout_ms = Milliseconds::zero();
};
using InsertDataPtr = std::unique_ptr<InsertData>;
struct Container
{
InsertQuery key;
InsertDataPtr data;
};
/// Ordered container
/// Key is a timestamp of the first insert into batch.
/// Used to detect for how long the batch is active, so we can dump it by timer.
using Queue = std::map<std::chrono::steady_clock::time_point, Container>;
using QueueIterator = Queue::iterator;
using QueueIteratorByKey = std::unordered_map<UInt128, QueueIterator>;
using OptionalTimePoint = std::optional<std::chrono::steady_clock::time_point>;
struct QueueShard
{
mutable std::mutex mutex;
mutable std::condition_variable are_tasks_available;
Queue queue;
QueueIteratorByKey iterators;
OptionalTimePoint last_insert_time;
std::chrono::milliseconds busy_timeout_ms{};
};
/// Times of the two most recent queue flushes.
/// Used to calculate adaptive timeout.
struct QueueShardFlushTimeHistory
{
public:
using TimePoints = std::pair<OptionalTimePoint, OptionalTimePoint>;
TimePoints getRecentTimePoints() const;
void updateWithCurrentTime();
private:
mutable SharedMutex mutex;
TimePoints time_points;
};
const size_t pool_size;
const bool flush_on_shutdown;
std::vector<QueueShard> queue_shards;
std::vector<QueueShardFlushTimeHistory> flush_time_history_per_queue_shard;
/// Logic and events behind queue are as follows:
/// - async_insert_busy_timeout_ms:
/// if queue is active for too long and there are a lot of rapid inserts, then we dump the data, so it doesn't
/// grow for a long period of time and users will be able to select new data in deterministic manner.
///
/// During processing incoming INSERT queries we can also check whether the maximum size of data in buffer is reached
/// (async_insert_max_data_size setting). If so, then again we dump the data.
std::atomic<bool> shutdown{false};
std::atomic<bool> flush_stopped{false};
/// A mutex that prevents concurrent forced flushes of queue.
mutable std::mutex flush_mutex;
/// Dump the data only inside this pool.
ThreadPool pool;
/// Uses async_insert_busy_timeout_ms and processBatchDeadlines()
std::vector<ThreadFromGlobalPool> dump_by_first_update_threads;
LoggerPtr log = getLogger("AsynchronousInsertQueue");
PushResult pushDataChunk(ASTPtr query, DataChunk && chunk, ContextPtr query_context);
Milliseconds getBusyWaitTimeoutMs(
const Settings & settings,
const QueueShard & shard,
const QueueShardFlushTimeHistory::TimePoints & flush_time_points,
std::chrono::steady_clock::time_point now) const;
void preprocessInsertQuery(const ASTPtr & query, const ContextPtr & query_context);
void processBatchDeadlines(size_t shard_num);
void scheduleDataProcessingJob(const InsertQuery & key, InsertDataPtr data, ContextPtr global_context, size_t shard_num, ThreadGroupPtr current_query_thread_group = nullptr);
static void processData(
InsertQuery key, InsertDataPtr data, ContextPtr global_context, ThreadGroupPtr current_query_thread_group, QueueShardFlushTimeHistory & queue_shard_flush_time_history);
template <typename LogFunc>
static Chunk processEntriesWithParsing(
const InsertQuery & key,
const InsertDataPtr & data,
const Block & header,
const ContextPtr & insert_context,
LoggerPtr logger,
LogFunc && add_to_async_insert_log);
template <typename LogFunc>
static Chunk processPreprocessedEntries(
const InsertDataPtr & data,
const Block & header,
const ContextPtr & context_,
LoggerPtr logger,
LogFunc && add_to_async_insert_log);
template <typename E>
static void finishWithException(const ASTPtr & query, const std::list<InsertData::EntryPtr> & entries, const E & exception);
static std::vector<std::string> getInsertQueryIds(InsertData & data);
public:
auto getQueueLocked(size_t shard_num) const
{
const auto & shard = queue_shards[shard_num];
std::unique_lock lock(shard.mutex);
return std::make_pair(std::ref(shard.queue), std::move(lock));
}
};
}