aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp
blob: 35199ec1f84c42ec9e2868096b23135d1fe26f7c (plain) (blame)
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
#include <Storages/Distributed/DistributedAsyncInsertBatch.h>
#include <Storages/Distributed/DistributedAsyncInsertHeader.h>
#include <Storages/Distributed/DistributedAsyncInsertHelpers.h>
#include <Storages/Distributed/DistributedAsyncInsertDirectoryQueue.h>
#include <Storages/StorageDistributed.h>
#include <QueryPipeline/RemoteInserter.h>
#include <Formats/NativeReader.h>
#include <Processors/ISource.h>
#include <Interpreters/Context.h>
#include <Interpreters/Cluster.h>
#include <IO/ReadBufferFromFile.h>
#include <IO/WriteBufferFromFile.h>
#include <IO/ConnectionTimeouts.h>
#include <Compression/CompressedReadBuffer.h>
#include <Disks/IDisk.h>
#include <Common/CurrentMetrics.h>
#include <Common/StringUtils/StringUtils.h>
#include <Common/SipHash.h>
#include <Common/quoteString.h>
#include <base/hex.h>
#include <Common/ActionBlocker.h>
#include <Common/formatReadable.h>
#include <Common/Stopwatch.h>
#include <Common/logger_useful.h>
#include <Compression/CheckingCompressedReadBuffer.h>
#include <IO/Operators.h>
#include <boost/algorithm/string/find_iterator.hpp>
#include <boost/algorithm/string/finder.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <filesystem>


namespace CurrentMetrics
{
    extern const Metric DistributedSend;
    extern const Metric DistributedFilesToInsert;
    extern const Metric BrokenDistributedFilesToInsert;
    extern const Metric DistributedBytesToInsert;
    extern const Metric BrokenDistributedBytesToInsert;
}

namespace fs = std::filesystem;

namespace DB
{

namespace ErrorCodes
{
    extern const int INCORRECT_FILE_NAME;
    extern const int LOGICAL_ERROR;
}


namespace
{

template <typename PoolFactory>
ConnectionPoolPtrs createPoolsForAddresses(const std::string & name, PoolFactory && factory, const Cluster::ShardsInfo & shards_info, Poco::Logger * log)
{
    ConnectionPoolPtrs pools;

    auto make_connection = [&](const Cluster::Address & address)
    {
        try
        {
            pools.emplace_back(factory(address));
        }
        catch (const Exception & e)
        {
            if (e.code() == ErrorCodes::INCORRECT_FILE_NAME)
            {
                tryLogCurrentException(log);
                return;
            }
            throw;
        }
    };

    for (auto it = boost::make_split_iterator(name, boost::first_finder(",")); it != decltype(it){}; ++it)
    {
        const std::string & dirname = boost::copy_range<std::string>(*it);
        Cluster::Address address = Cluster::Address::fromFullString(dirname);
        if (address.shard_index && dirname.ends_with("_all_replicas"))
        {
            if (address.shard_index > shards_info.size())
            {
                LOG_ERROR(log, "No shard with shard_index={} ({})", address.shard_index, name);
                continue;
            }

            const auto & shard_info = shards_info[address.shard_index - 1];
            size_t replicas = shard_info.per_replica_pools.size();

            for (size_t replica_index = 1; replica_index <= replicas; ++replica_index)
            {
                address.replica_index = static_cast<UInt32>(replica_index);
                make_connection(address);
            }
        }
        else
            make_connection(address);
    }

    return pools;
}

uint64_t doubleToUInt64(double d)
{
    if (d >= static_cast<double>(std::numeric_limits<uint64_t>::max()))
        return std::numeric_limits<uint64_t>::max();
    return static_cast<uint64_t>(d);
}

}


DistributedAsyncInsertDirectoryQueue::DistributedAsyncInsertDirectoryQueue(
    StorageDistributed & storage_,
    const DiskPtr & disk_,
    const std::string & relative_path_,
    ConnectionPoolPtr pool_,
    ActionBlocker & monitor_blocker_,
    BackgroundSchedulePool & bg_pool)
    : storage(storage_)
    , pool(std::move(pool_))
    , disk(disk_)
    , relative_path(relative_path_)
    , path(fs::path(disk->getPath()) / relative_path / "")
    , broken_relative_path(fs::path(relative_path) / "broken")
    , broken_path(fs::path(path) / "broken" / "")
    , should_batch_inserts(storage.getDistributedSettingsRef().monitor_batch_inserts)
    , split_batch_on_failure(storage.getDistributedSettingsRef().monitor_split_batch_on_failure)
    , dir_fsync(storage.getDistributedSettingsRef().fsync_directories)
    , min_batched_block_size_rows(storage.getContext()->getSettingsRef().min_insert_block_size_rows)
    , min_batched_block_size_bytes(storage.getContext()->getSettingsRef().min_insert_block_size_bytes)
    , current_batch_file_path(path + "current_batch.txt")
    , pending_files(std::numeric_limits<size_t>::max())
    , default_sleep_time(storage.getDistributedSettingsRef().monitor_sleep_time_ms.totalMilliseconds())
    , sleep_time(default_sleep_time)
    , max_sleep_time(storage.getDistributedSettingsRef().monitor_max_sleep_time_ms.totalMilliseconds())
    , log(&Poco::Logger::get(getLoggerName()))
    , monitor_blocker(monitor_blocker_)
    , metric_pending_bytes(CurrentMetrics::DistributedBytesToInsert, 0)
    , metric_pending_files(CurrentMetrics::DistributedFilesToInsert, 0)
    , metric_broken_bytes(CurrentMetrics::BrokenDistributedBytesToInsert, 0)
    , metric_broken_files(CurrentMetrics::BrokenDistributedFilesToInsert, 0)
{
    fs::create_directory(broken_path);

    initializeFilesFromDisk();

    task_handle = bg_pool.createTask(getLoggerName() + "/Bg", [this]{ run(); });
    task_handle->activateAndSchedule();
}


DistributedAsyncInsertDirectoryQueue::~DistributedAsyncInsertDirectoryQueue()
{
    if (!pending_files.isFinished())
    {
        pending_files.clearAndFinish();
        task_handle->deactivate();
    }
}

void DistributedAsyncInsertDirectoryQueue::flushAllData()
{
    if (pending_files.isFinished())
        return;

    std::lock_guard lock{mutex};
    if (!hasPendingFiles())
        return;
    processFiles();
}

void DistributedAsyncInsertDirectoryQueue::shutdownAndDropAllData()
{
    if (!pending_files.isFinished())
    {
        pending_files.clearAndFinish();
        task_handle->deactivate();
    }

    auto dir_sync_guard = getDirectorySyncGuard(relative_path);
    fs::remove_all(path);
}

void DistributedAsyncInsertDirectoryQueue::shutdownWithoutFlush()
{
    /// It's incompatible with should_batch_inserts
    /// because processFilesWithBatching may push to the queue after shutdown
    chassert(!should_batch_inserts);
    pending_files.finish();
    task_handle->deactivate();
}


void DistributedAsyncInsertDirectoryQueue::run()
{
    constexpr const std::chrono::minutes decrease_error_count_period{5};

    std::lock_guard lock{mutex};

    bool do_sleep = false;
    while (!pending_files.isFinished())
    {
        do_sleep = true;

        if (!hasPendingFiles())
            break;

        if (!monitor_blocker.isCancelled())
        {
            try
            {
                processFiles();
                /// No errors while processing existing files.
                /// Let's see maybe there are more files to process.
                do_sleep = false;
            }
            catch (...)
            {
                tryLogCurrentException(getLoggerName().data());

                UInt64 q = doubleToUInt64(std::exp2(status.error_count));
                std::chrono::milliseconds new_sleep_time(default_sleep_time.count() * q);
                if (new_sleep_time.count() < 0)
                    sleep_time = max_sleep_time;
                else
                    sleep_time = std::min(new_sleep_time, max_sleep_time);

                do_sleep = true;
            }
        }
        else
            LOG_TEST(log, "Skipping send data over distributed table.");

        const auto now = std::chrono::system_clock::now();
        if (now - last_decrease_time > decrease_error_count_period)
        {
            std::lock_guard status_lock(status_mutex);

            status.error_count /= 2;
            last_decrease_time = now;
        }

        if (do_sleep)
            break;
    }

    if (!pending_files.isFinished() && do_sleep)
        task_handle->scheduleAfter(sleep_time.count());
}


ConnectionPoolPtr DistributedAsyncInsertDirectoryQueue::createPool(const std::string & name, const StorageDistributed & storage)
{
    const auto pool_factory = [&storage, &name] (const Cluster::Address & address) -> ConnectionPoolPtr
    {
        const auto & cluster = storage.getCluster();
        const auto & shards_info = cluster->getShardsInfo();
        const auto & shards_addresses = cluster->getShardsAddresses();

        /// Check new format shard{shard_index}_replica{replica_index}
        /// (shard_index and replica_index starts from 1).
        if (address.shard_index != 0)
        {
            if (!address.replica_index)
                throw Exception(ErrorCodes::INCORRECT_FILE_NAME,
                    "Wrong replica_index={} ({})", address.replica_index, name);

            if (address.shard_index > shards_info.size())
                throw Exception(ErrorCodes::INCORRECT_FILE_NAME,
                    "No shard with shard_index={} ({})", address.shard_index, name);

            const auto & shard_info = shards_info[address.shard_index - 1];
            if (address.replica_index > shard_info.per_replica_pools.size())
                throw Exception(ErrorCodes::INCORRECT_FILE_NAME,
                    "No shard with replica_index={} ({})", address.replica_index, name);

            return shard_info.per_replica_pools[address.replica_index - 1];
        }

        /// Existing connections pool have a higher priority.
        for (size_t shard_index = 0; shard_index < shards_info.size(); ++shard_index)
        {
            const Cluster::Addresses & replicas_addresses = shards_addresses[shard_index];

            for (size_t replica_index = 0; replica_index < replicas_addresses.size(); ++replica_index)
            {
                const Cluster::Address & replica_address = replicas_addresses[replica_index];

                if (address.user == replica_address.user &&
                    address.password == replica_address.password &&
                    address.host_name == replica_address.host_name &&
                    address.port == replica_address.port &&
                    address.default_database == replica_address.default_database &&
                    address.secure == replica_address.secure)
                {
                    return shards_info[shard_index].per_replica_pools[replica_index];
                }
            }
        }

        return std::make_shared<ConnectionPool>(
            1, /* max_connections */
            address.host_name,
            address.port,
            address.default_database,
            address.user,
            address.password,
            address.quota_key,
            address.cluster,
            address.cluster_secret,
            storage.getName() + '_' + address.user, /* client */
            Protocol::Compression::Enable,
            address.secure);
    };

    auto pools = createPoolsForAddresses(name, pool_factory, storage.getCluster()->getShardsInfo(), storage.log);

    const auto settings = storage.getContext()->getSettings();
    return pools.size() == 1 ? pools.front() : std::make_shared<ConnectionPoolWithFailover>(pools,
        settings.load_balancing,
        settings.distributed_replica_error_half_life.totalSeconds(),
        settings.distributed_replica_error_cap);
}

bool DistributedAsyncInsertDirectoryQueue::hasPendingFiles() const
{
    return fs::exists(current_batch_file_path) || !current_file.empty() || !pending_files.empty();
}

void DistributedAsyncInsertDirectoryQueue::addFile(const std::string & file_path)
{
    if (!pending_files.push(fs::absolute(file_path).string()))
        throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot schedule a file '{}'", file_path);
}

void DistributedAsyncInsertDirectoryQueue::initializeFilesFromDisk()
{
    /// NOTE: This method does not requires to hold status_mutex (because this
    /// object is not in the list that the caller may iterate over), hence, no
    /// TSA annotations in the header file.

    fs::directory_iterator end;

    /// Initialize pending files
    {
        size_t bytes_count = 0;

        for (fs::directory_iterator it{path}; it != end; ++it)
        {
            const auto & file_path = it->path();
            const auto & base_name = file_path.stem().string();
            if (!it->is_directory() && startsWith(fs::path(file_path).extension(), ".bin") && parse<UInt64>(base_name))
            {
                const std::string & file_path_str = file_path.string();
                addFile(file_path_str);
                bytes_count += fs::file_size(file_path);
            }
            else if (base_name != "tmp" && base_name != "broken")
            {
                /// It is OK to log current_batch.txt here too (useful for debugging).
                LOG_WARNING(log, "Unexpected file {} in {}", file_path.string(), path);
            }
        }

        LOG_TRACE(log, "Files set to {}", pending_files.size());
        LOG_TRACE(log, "Bytes set to {}", bytes_count);

        metric_pending_bytes.changeTo(bytes_count);
        metric_pending_files.changeTo(pending_files.size());
        status.files_count = pending_files.size();
        status.bytes_count = bytes_count;
    }

    /// Initialize broken files
    {
        size_t broken_bytes_count = 0;
        size_t broken_files = 0;

        for (fs::directory_iterator it{broken_path}; it != end; ++it)
        {
            const auto & file_path = it->path();
            if (!it->is_directory() && startsWith(fs::path(file_path).extension(), ".bin") && parse<UInt64>(file_path.stem()))
                broken_bytes_count += fs::file_size(file_path);
            else
                LOG_WARNING(log, "Unexpected file {} in {}", file_path.string(), broken_path);
        }

        LOG_TRACE(log, "Broken files set to {}", broken_files);
        LOG_TRACE(log, "Broken bytes set to {}", broken_bytes_count);

        metric_broken_files.changeTo(broken_files);
        metric_broken_bytes.changeTo(broken_bytes_count);
        status.broken_files_count = broken_files;
        status.broken_bytes_count = broken_bytes_count;
    }
}
void DistributedAsyncInsertDirectoryQueue::processFiles()
try
{
    if (should_batch_inserts)
        processFilesWithBatching();
    else
    {
        /// Process unprocessed file.
        if (!current_file.empty())
            processFile(current_file);

        while (!pending_files.isFinished() && pending_files.tryPop(current_file))
            processFile(current_file);
    }

    std::lock_guard status_lock(status_mutex);
    status.last_exception = std::exception_ptr{};
}
catch (...)
{
    std::lock_guard status_lock(status_mutex);

    ++status.error_count;
    status.last_exception = std::current_exception();
    status.last_exception_time = std::chrono::system_clock::now();

    throw;
}

void DistributedAsyncInsertDirectoryQueue::processFile(std::string & file_path)
{
    OpenTelemetry::TracingContextHolderPtr thread_trace_context;

    Stopwatch watch;
    try
    {
        CurrentMetrics::Increment metric_increment{CurrentMetrics::DistributedSend};

        ReadBufferFromFile in(file_path);
        const auto & distributed_header = DistributedAsyncInsertHeader::read(in, log);
        thread_trace_context = distributed_header.createTracingContextHolder(
            __PRETTY_FUNCTION__,
            storage.getContext()->getOpenTelemetrySpanLog());

        auto timeouts = ConnectionTimeouts::getTCPTimeoutsWithFailover(distributed_header.insert_settings);
        auto connection = pool->get(timeouts, &distributed_header.insert_settings);
        LOG_DEBUG(log, "Sending `{}` to {} ({} rows, {} bytes)",
            file_path,
            connection->getDescription(),
            formatReadableQuantity(distributed_header.rows),
            formatReadableSizeWithBinarySuffix(distributed_header.bytes));

        RemoteInserter remote{*connection, timeouts,
            distributed_header.insert_query,
            distributed_header.insert_settings,
            distributed_header.client_info};
        bool compression_expected = connection->getCompression() == Protocol::Compression::Enable;
        writeRemoteConvert(distributed_header, remote, compression_expected, in, log);
        remote.onFinish();
    }
    catch (Exception & e)
    {
        if (thread_trace_context)
            thread_trace_context->root_span.addAttribute(std::current_exception());

        e.addMessage(fmt::format("While sending {}", file_path));
        if (isDistributedSendBroken(e.code(), e.isRemoteException()))
        {
            markAsBroken(file_path);
            file_path.clear();
        }
        throw;
    }
    catch (...)
    {
        if (thread_trace_context)
            thread_trace_context->root_span.addAttribute(std::current_exception());

        throw;
    }

    auto dir_sync_guard = getDirectorySyncGuard(relative_path);
    markAsSend(file_path);
    LOG_TRACE(log, "Finished processing `{}` (took {} ms)", file_path, watch.elapsedMilliseconds());
    file_path.clear();
}

struct DistributedAsyncInsertDirectoryQueue::BatchHeader
{
    Settings settings;
    String query;
    ClientInfo client_info;
    Block header;

    BatchHeader(Settings settings_, String query_, ClientInfo client_info_, Block header_)
        : settings(std::move(settings_))
        , query(std::move(query_))
        , client_info(std::move(client_info_))
        , header(std::move(header_))
    {
    }

    bool operator==(const BatchHeader & other) const
    {
        return std::tie(settings, query, client_info.query_kind) ==
               std::tie(other.settings, other.query, other.client_info.query_kind) &&
               blocksHaveEqualStructure(header, other.header);
    }

    struct Hash
    {
        size_t operator()(const BatchHeader & batch_header) const
        {
            SipHash hash_state;
            hash_state.update(batch_header.query.data(), batch_header.query.size());
            batch_header.header.updateHash(hash_state);
            return hash_state.get64();
        }
    };
};

bool DistributedAsyncInsertDirectoryQueue::addFileAndSchedule(const std::string & file_path, size_t file_size, size_t ms)
{
    /// NOTE: It is better not to throw in this case, since the file is already
    /// on disk (see DistributedSink), and it will be processed next time.
    if (pending_files.isFinished())
    {
        LOG_DEBUG(log, "File {} had not been scheduled, since the table had been detached", file_path);
        return false;
    }

    addFile(file_path);

    {
        std::lock_guard lock(status_mutex);
        metric_pending_files.add();
        metric_pending_bytes.add(file_size);
        status.bytes_count += file_size;
        ++status.files_count;
    }

    return task_handle->scheduleAfter(ms, false);
}

DistributedAsyncInsertDirectoryQueue::Status DistributedAsyncInsertDirectoryQueue::getStatus()
{
    std::lock_guard status_lock(status_mutex);
    Status current_status{status, path, monitor_blocker.isCancelled()};
    return current_status;
}

void DistributedAsyncInsertDirectoryQueue::processFilesWithBatching()
{
    /// Possibly, we failed to send a batch on the previous iteration. Try to send exactly the same batch.
    if (fs::exists(current_batch_file_path))
    {
        LOG_DEBUG(log, "Restoring the batch");

        DistributedAsyncInsertBatch batch(*this);
        batch.deserialize();
        batch.send();

        auto dir_sync_guard = getDirectorySyncGuard(relative_path);
        fs::remove(current_batch_file_path);
    }

    std::unordered_map<BatchHeader, DistributedAsyncInsertBatch, BatchHeader::Hash> header_to_batch;

    std::string file_path;

    try
    {
        while (pending_files.tryPop(file_path))
        {
            if (!fs::exists(file_path))
            {
                LOG_WARNING(log, "File {} does not exists, likely due to current_batch.txt processing", file_path);
                continue;
            }

            size_t total_rows = 0;
            size_t total_bytes = 0;
            Block header;
            DistributedAsyncInsertHeader distributed_header;
            try
            {
                /// Determine metadata of the current file and check if it is not broken.
                ReadBufferFromFile in{file_path};
                distributed_header = DistributedAsyncInsertHeader::read(in, log);

                if (distributed_header.rows)
                {
                    total_rows += distributed_header.rows;
                    total_bytes += distributed_header.bytes;
                }

                if (distributed_header.block_header)
                    header = distributed_header.block_header;

                if (!total_rows || !header)
                {
                    LOG_DEBUG(log, "Processing batch {} with old format (no header/rows)", in.getFileName());

                    CompressedReadBuffer decompressing_in(in);
                    NativeReader block_in(decompressing_in, distributed_header.revision);

                    while (Block block = block_in.read())
                    {
                        total_rows += block.rows();
                        total_bytes += block.bytes();

                        if (!header)
                            header = block.cloneEmpty();
                    }
                }
            }
            catch (const Exception & e)
            {
                if (isDistributedSendBroken(e.code(), e.isRemoteException()))
                {
                    markAsBroken(file_path);
                    tryLogCurrentException(log, "File is marked broken due to");
                    continue;
                }
                else
                    throw;
            }

            BatchHeader batch_header(
                std::move(distributed_header.insert_settings),
                std::move(distributed_header.insert_query),
                std::move(distributed_header.client_info),
                std::move(header)
            );
            DistributedAsyncInsertBatch & batch = header_to_batch.try_emplace(batch_header, *this).first->second;

            batch.files.push_back(file_path);
            batch.total_rows += total_rows;
            batch.total_bytes += total_bytes;

            if (batch.isEnoughSize())
            {
                batch.send();
            }
        }

        for (auto & kv : header_to_batch)
        {
            DistributedAsyncInsertBatch & batch = kv.second;
            batch.send();
        }
    }
    catch (...)
    {
        /// Revert uncommitted files.
        for (const auto & [_, batch] : header_to_batch)
        {
            for (const auto & file : batch.files)
            {
                if (!pending_files.pushFront(file))
                    throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot re-schedule a file '{}'", file);
            }
        }
        /// Rethrow exception
        throw;
    }

    {
        auto dir_sync_guard = getDirectorySyncGuard(relative_path);

        /// current_batch.txt will not exist if there was no send
        /// (this is the case when all batches that was pending has been marked as pending)
        if (fs::exists(current_batch_file_path))
            fs::remove(current_batch_file_path);
    }
}

void DistributedAsyncInsertDirectoryQueue::markAsBroken(const std::string & file_path)
{
    const String & broken_file_path = fs::path(broken_path) / fs::path(file_path).filename();

    auto dir_sync_guard = getDirectorySyncGuard(relative_path);
    auto broken_dir_sync_guard = getDirectorySyncGuard(broken_relative_path);

    {
        std::lock_guard status_lock(status_mutex);

        size_t file_size = fs::file_size(file_path);

        --status.files_count;
        status.bytes_count -= file_size;

        ++status.broken_files_count;
        status.broken_bytes_count += file_size;

        metric_broken_files.add();
        metric_broken_bytes.add(file_size);
    }

    fs::rename(file_path, broken_file_path);
    LOG_ERROR(log, "Renamed `{}` to `{}`", file_path, broken_file_path);
}

void DistributedAsyncInsertDirectoryQueue::markAsSend(const std::string & file_path)
{
    size_t file_size = fs::file_size(file_path);

    {
        std::lock_guard status_lock(status_mutex);
        metric_pending_files.sub();
        metric_pending_bytes.sub(file_size);
        --status.files_count;
        status.bytes_count -= file_size;
    }

    fs::remove(file_path);
}

SyncGuardPtr DistributedAsyncInsertDirectoryQueue::getDirectorySyncGuard(const std::string & dir_path)
{
    if (dir_fsync)
        return disk->getDirectorySyncGuard(dir_path);
    return nullptr;
}

std::string DistributedAsyncInsertDirectoryQueue::getLoggerName() const
{
    return storage.getStorageID().getFullTableName() + ".DirectoryMonitor." + disk->getName();
}

void DistributedAsyncInsertDirectoryQueue::updatePath(const std::string & new_relative_path)
{
    task_handle->deactivate();
    std::lock_guard lock{mutex};

    {
        std::lock_guard status_lock(status_mutex);
        relative_path = new_relative_path;
        path = fs::path(disk->getPath()) / relative_path / "";
    }
    current_batch_file_path = path + "current_batch.txt";

    task_handle->activateAndSchedule();
}

}