Coverage Report

Created: 2026-07-30 15:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/agent/task_worker_pool.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "agent/task_worker_pool.h"
19
20
#include <brpc/controller.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/AgentService_types.h>
23
#include <gen_cpp/DataSinks_types.h>
24
#include <gen_cpp/HeartbeatService_types.h>
25
#include <gen_cpp/MasterService_types.h>
26
#include <gen_cpp/Status_types.h>
27
#include <gen_cpp/Types_types.h>
28
#include <unistd.h>
29
30
#include <algorithm>
31
// IWYU pragma: no_include <bits/chrono.h>
32
#include <thrift/protocol/TDebugProtocol.h>
33
34
#include <atomic>
35
#include <chrono> // IWYU pragma: keep
36
#include <ctime>
37
#include <functional>
38
#include <memory>
39
#include <mutex>
40
#include <shared_mutex>
41
#include <sstream>
42
#include <string>
43
#include <thread>
44
#include <type_traits>
45
#include <utility>
46
#include <vector>
47
48
#include "agent/utils.h"
49
#include "cloud/cloud_delete_task.h"
50
#include "cloud/cloud_engine_calc_delete_bitmap_task.h"
51
#include "cloud/cloud_schema_change_job.h"
52
#include "cloud/cloud_snapshot_loader.h"
53
#include "cloud/cloud_snapshot_mgr.h"
54
#include "cloud/cloud_tablet.h"
55
#include "cloud/cloud_tablet_mgr.h"
56
#include "cloud/config.h"
57
#include "common/config.h"
58
#include "common/logging.h"
59
#include "common/metrics/doris_metrics.h"
60
#include "common/status.h"
61
#include "io/fs/file_system.h"
62
#include "io/fs/hdfs_file_system.h"
63
#include "io/fs/local_file_system.h"
64
#include "io/fs/obj_storage_client.h"
65
#include "io/fs/path.h"
66
#include "io/fs/remote_file_system.h"
67
#include "io/fs/s3_file_system.h"
68
#include "runtime/exec_env.h"
69
#include "runtime/fragment_mgr.h"
70
#include "runtime/index_policy/index_policy_mgr.h"
71
#include "runtime/memory/global_memory_arbitrator.h"
72
#include "runtime/snapshot_loader.h"
73
#include "runtime/user_function_cache.h"
74
#include "service/backend_options.h"
75
#include "storage/compaction/cumulative_compaction_binlog_policy.h"
76
#include "storage/compaction/cumulative_compaction_policy.h"
77
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
78
#include "storage/data_dir.h"
79
#include "storage/olap_common.h"
80
#include "storage/rowset/rowset_meta.h"
81
#include "storage/snapshot/snapshot_manager.h"
82
#include "storage/storage_engine.h"
83
#include "storage/storage_policy.h"
84
#include "storage/tablet/tablet.h"
85
#include "storage/tablet/tablet_manager.h"
86
#include "storage/tablet/tablet_meta.h"
87
#include "storage/tablet/tablet_schema.h"
88
#include "storage/task/engine_batch_load_task.h"
89
#include "storage/task/engine_checksum_task.h"
90
#include "storage/task/engine_clone_task.h"
91
#include "storage/task/engine_cloud_index_change_task.h"
92
#include "storage/task/engine_index_change_task.h"
93
#include "storage/task/engine_publish_version_task.h"
94
#include "storage/task/engine_storage_migration_task.h"
95
#include "storage/txn/txn_manager.h"
96
#include "storage/utils.h"
97
#include "udf/python/python_server.h"
98
#include "util/brpc_client_cache.h"
99
#include "util/debug_points.h"
100
#include "util/jni-util.h"
101
#include "util/mem_info.h"
102
#include "util/random.h"
103
#include "util/s3_util.h"
104
#include "util/stopwatch.hpp"
105
#include "util/threadpool.h"
106
#include "util/time.h"
107
#include "util/trace.h"
108
109
namespace doris {
110
using namespace ErrorCode;
111
112
namespace {
113
114
std::mutex s_task_signatures_mtx;
115
std::unordered_map<TTaskType::type, std::unordered_set<int64_t>> s_task_signatures;
116
117
std::atomic_ulong s_report_version(time(nullptr) * 100000);
118
119
22.0k
void increase_report_version() {
120
22.0k
    s_report_version.fetch_add(1, std::memory_order_relaxed);
121
22.0k
}
122
123
// FIXME(plat1ko): Paired register and remove task info
124
79.5k
bool register_task_info(const TTaskType::type task_type, int64_t signature) {
125
79.5k
    if (task_type == TTaskType::type::PUSH_STORAGE_POLICY ||
126
79.5k
        task_type == TTaskType::type::PUSH_COOLDOWN_CONF ||
127
79.5k
        task_type == TTaskType::type::COMPACTION) {
128
        // no need to report task of these types
129
16
        return true;
130
16
    }
131
132
79.5k
    if (signature == -1) { // No need to report task with unintialized signature
133
5.98k
        return true;
134
5.98k
    }
135
136
73.5k
    std::lock_guard lock(s_task_signatures_mtx);
137
73.5k
    auto& set = s_task_signatures[task_type];
138
73.5k
    return set.insert(signature).second;
139
79.5k
}
140
141
44.5k
void remove_task_info(const TTaskType::type task_type, int64_t signature) {
142
44.5k
    size_t queue_size;
143
44.5k
    {
144
44.5k
        std::lock_guard lock(s_task_signatures_mtx);
145
44.5k
        auto& set = s_task_signatures[task_type];
146
44.5k
        set.erase(signature);
147
44.5k
        queue_size = set.size();
148
44.5k
    }
149
150
18.4E
    VLOG_NOTICE << "remove task info. type=" << task_type << ", signature=" << signature
151
18.4E
                << ", queue_size=" << queue_size;
152
44.5k
}
153
154
43.7k
void finish_task(const TFinishTaskRequest& finish_task_request) {
155
    // Return result to FE
156
43.7k
    TMasterResult result;
157
43.7k
    uint32_t try_time = 0;
158
43.7k
    constexpr int TASK_FINISH_MAX_RETRY = 3;
159
44.2k
    while (try_time < TASK_FINISH_MAX_RETRY) {
160
44.2k
        DorisMetrics::instance()->finish_task_requests_total->increment(1);
161
44.2k
        Status client_status =
162
44.2k
                MasterServerClient::instance()->finish_task(finish_task_request, &result);
163
164
44.5k
        if (client_status.ok()) {
165
44.5k
            break;
166
18.4E
        } else {
167
18.4E
            DorisMetrics::instance()->finish_task_requests_failed->increment(1);
168
18.4E
            LOG_WARNING("failed to finish task")
169
18.4E
                    .tag("type", finish_task_request.task_type)
170
18.4E
                    .tag("signature", finish_task_request.signature)
171
18.4E
                    .error(result.status);
172
18.4E
            try_time += 1;
173
18.4E
        }
174
18.4E
        sleep(1);
175
18.4E
    }
176
43.7k
}
177
178
Status get_tablet_info(StorageEngine& engine, const TTabletId tablet_id,
179
20
                       const TSchemaHash schema_hash, TTabletInfo* tablet_info) {
180
20
    tablet_info->__set_tablet_id(tablet_id);
181
20
    tablet_info->__set_schema_hash(schema_hash);
182
20
    return engine.tablet_manager()->report_tablet_info(tablet_info);
183
20
}
184
185
1.35k
void random_sleep(int second) {
186
1.35k
    Random rnd(static_cast<uint32_t>(UnixMillis()));
187
1.35k
    sleep(rnd.Uniform(second) + 1);
188
1.35k
}
189
190
void alter_tablet(StorageEngine& engine, const TAgentTaskRequest& agent_task_req, int64_t signature,
191
20
                  const TTaskType::type task_type, TFinishTaskRequest* finish_task_request) {
192
20
    Status status;
193
194
20
    std::string_view process_name = "alter tablet";
195
    // Check last schema change status, if failed delete tablet file
196
    // Do not need to adjust delete success or not
197
    // Because if delete failed create rollup will failed
198
20
    TTabletId new_tablet_id = 0;
199
20
    TSchemaHash new_schema_hash = 0;
200
20
    if (status.ok()) {
201
20
        new_tablet_id = agent_task_req.alter_tablet_req_v2.new_tablet_id;
202
20
        new_schema_hash = agent_task_req.alter_tablet_req_v2.new_schema_hash;
203
20
        auto mem_tracker = MemTrackerLimiter::create_shared(
204
20
                MemTrackerLimiter::Type::SCHEMA_CHANGE,
205
20
                fmt::format("EngineAlterTabletTask#baseTabletId={}:newTabletId={}",
206
20
                            std::to_string(agent_task_req.alter_tablet_req_v2.base_tablet_id),
207
20
                            std::to_string(agent_task_req.alter_tablet_req_v2.new_tablet_id),
208
20
                            engine.memory_limitation_bytes_per_thread_for_schema_change()));
209
20
        SCOPED_ATTACH_TASK(mem_tracker);
210
20
        DorisMetrics::instance()->create_rollup_requests_total->increment(1);
211
20
        Status res = Status::OK();
212
20
        try {
213
20
            LOG_INFO("start {}", process_name)
214
20
                    .tag("signature", agent_task_req.signature)
215
20
                    .tag("base_tablet_id", agent_task_req.alter_tablet_req_v2.base_tablet_id)
216
20
                    .tag("new_tablet_id", new_tablet_id)
217
20
                    .tag("mem_limit",
218
20
                         engine.memory_limitation_bytes_per_thread_for_schema_change());
219
20
            SchemaChangeJob job(engine, agent_task_req.alter_tablet_req_v2,
220
20
                                std::to_string(agent_task_req.alter_tablet_req_v2.__isset.job_id
221
20
                                                       ? agent_task_req.alter_tablet_req_v2.job_id
222
20
                                                       : 0));
223
20
            status = job.process_alter_tablet(agent_task_req.alter_tablet_req_v2);
224
20
        } catch (const Exception& e) {
225
0
            status = e.to_status();
226
0
        }
227
20
        if (!status.ok()) {
228
0
            DorisMetrics::instance()->create_rollup_requests_failed->increment(1);
229
0
        }
230
20
    }
231
232
20
    if (status.ok()) {
233
20
        increase_report_version();
234
20
    }
235
236
    // Return result to fe
237
20
    finish_task_request->__set_backend(BackendOptions::get_local_backend());
238
20
    finish_task_request->__set_report_version(s_report_version);
239
20
    finish_task_request->__set_task_type(task_type);
240
20
    finish_task_request->__set_signature(signature);
241
242
20
    std::vector<TTabletInfo> finish_tablet_infos;
243
20
    if (status.ok()) {
244
20
        TTabletInfo tablet_info;
245
20
        status = get_tablet_info(engine, new_tablet_id, new_schema_hash, &tablet_info);
246
20
        if (status.ok()) {
247
20
            finish_tablet_infos.push_back(tablet_info);
248
20
        }
249
20
    }
250
251
20
    if (!status.ok() && !status.is<NOT_IMPLEMENTED_ERROR>()) {
252
0
        LOG_WARNING("failed to {}", process_name)
253
0
                .tag("signature", agent_task_req.signature)
254
0
                .tag("base_tablet_id", agent_task_req.alter_tablet_req_v2.base_tablet_id)
255
0
                .tag("new_tablet_id", new_tablet_id)
256
0
                .error(status);
257
20
    } else {
258
20
        finish_task_request->__set_finish_tablet_infos(finish_tablet_infos);
259
20
        LOG_INFO("successfully {}", process_name)
260
20
                .tag("signature", agent_task_req.signature)
261
20
                .tag("base_tablet_id", agent_task_req.alter_tablet_req_v2.base_tablet_id)
262
20
                .tag("new_tablet_id", new_tablet_id);
263
20
    }
264
20
    finish_task_request->__set_task_status(status.to_thrift());
265
20
}
266
267
void alter_cloud_tablet(CloudStorageEngine& engine, const TAgentTaskRequest& agent_task_req,
268
                        int64_t signature, const TTaskType::type task_type,
269
11.1k
                        TFinishTaskRequest* finish_task_request) {
270
11.1k
    Status status;
271
272
11.1k
    std::string_view process_name = "alter tablet";
273
    // Check last schema change status, if failed delete tablet file
274
    // Do not need to adjust delete success or not
275
    // Because if delete failed create rollup will failed
276
11.1k
    TTabletId new_tablet_id = 0;
277
11.1k
    new_tablet_id = agent_task_req.alter_tablet_req_v2.new_tablet_id;
278
11.1k
    auto mem_tracker = MemTrackerLimiter::create_shared(
279
11.1k
            MemTrackerLimiter::Type::SCHEMA_CHANGE,
280
11.1k
            fmt::format("EngineAlterTabletTask#baseTabletId={}:newTabletId={}",
281
11.1k
                        std::to_string(agent_task_req.alter_tablet_req_v2.base_tablet_id),
282
11.1k
                        std::to_string(agent_task_req.alter_tablet_req_v2.new_tablet_id),
283
11.1k
                        engine.memory_limitation_bytes_per_thread_for_schema_change()));
284
11.1k
    SCOPED_ATTACH_TASK(mem_tracker);
285
11.1k
    DorisMetrics::instance()->create_rollup_requests_total->increment(1);
286
287
11.1k
    LOG_INFO("start {}", process_name)
288
11.1k
            .tag("signature", agent_task_req.signature)
289
11.1k
            .tag("base_tablet_id", agent_task_req.alter_tablet_req_v2.base_tablet_id)
290
11.1k
            .tag("new_tablet_id", new_tablet_id)
291
11.1k
            .tag("mem_limit", engine.memory_limitation_bytes_per_thread_for_schema_change());
292
11.1k
    DCHECK(agent_task_req.alter_tablet_req_v2.__isset.job_id);
293
11.1k
    CloudSchemaChangeJob job(engine, std::to_string(agent_task_req.alter_tablet_req_v2.job_id),
294
11.1k
                             agent_task_req.alter_tablet_req_v2.expiration);
295
11.1k
    status = [&]() {
296
11.1k
        HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(
297
11.1k
                job.process_alter_tablet(agent_task_req.alter_tablet_req_v2),
298
11.1k
                [&](const doris::Exception& ex) {
299
11.1k
                    DorisMetrics::instance()->create_rollup_requests_failed->increment(1);
300
11.1k
                    job.clean_up_on_failure();
301
11.1k
                });
302
10.6k
        return Status::OK();
303
11.1k
    }();
304
305
11.1k
    if (status.ok()) {
306
10.4k
        increase_report_version();
307
10.4k
        LOG_INFO("successfully {}", process_name)
308
10.4k
                .tag("signature", agent_task_req.signature)
309
10.4k
                .tag("base_tablet_id", agent_task_req.alter_tablet_req_v2.base_tablet_id)
310
10.4k
                .tag("new_tablet_id", new_tablet_id);
311
10.4k
    } else {
312
650
        LOG_WARNING("failed to {}", process_name)
313
650
                .tag("signature", agent_task_req.signature)
314
650
                .tag("base_tablet_id", agent_task_req.alter_tablet_req_v2.base_tablet_id)
315
650
                .tag("new_tablet_id", new_tablet_id)
316
650
                .error(status);
317
650
    }
318
319
    // Return result to fe
320
11.1k
    finish_task_request->__set_backend(BackendOptions::get_local_backend());
321
11.1k
    finish_task_request->__set_report_version(s_report_version);
322
11.1k
    finish_task_request->__set_task_type(task_type);
323
11.1k
    finish_task_request->__set_signature(signature);
324
11.1k
    finish_task_request->__set_task_status(status.to_thrift());
325
11.1k
}
326
327
Status check_migrate_request(StorageEngine& engine, const TStorageMediumMigrateReq& req,
328
0
                             TabletSharedPtr& tablet, DataDir** dest_store) {
329
0
    int64_t tablet_id = req.tablet_id;
330
0
    tablet = engine.tablet_manager()->get_tablet(tablet_id);
331
0
    if (tablet == nullptr) {
332
0
        return Status::InternalError("could not find tablet {}", tablet_id);
333
0
    }
334
335
0
    if (req.__isset.data_dir) {
336
        // request specify the data dir
337
0
        *dest_store = engine.get_store(req.data_dir);
338
0
        if (*dest_store == nullptr) {
339
0
            return Status::InternalError("could not find data dir {}", req.data_dir);
340
0
        }
341
0
    } else {
342
        // this is a storage medium
343
        // get data dir by storage medium
344
345
        // judge case when no need to migrate
346
0
        uint32_t count = engine.available_storage_medium_type_count();
347
0
        if (count <= 1) {
348
0
            return Status::InternalError("available storage medium type count is less than 1");
349
0
        }
350
        // check current tablet storage medium
351
0
        TStorageMedium::type storage_medium = req.storage_medium;
352
0
        TStorageMedium::type src_storage_medium = tablet->data_dir()->storage_medium();
353
0
        if (src_storage_medium == storage_medium) {
354
0
            return Status::InternalError("tablet is already on specified storage medium {}",
355
0
                                         storage_medium);
356
0
        }
357
        // get a random store of specified storage medium
358
0
        auto stores = engine.get_stores_for_create_tablet(tablet->partition_id(), storage_medium);
359
0
        if (stores.empty()) {
360
0
            return Status::InternalError("failed to get root path for create tablet");
361
0
        }
362
363
0
        *dest_store = stores[0];
364
0
    }
365
0
    if (tablet->data_dir()->path() == (*dest_store)->path()) {
366
0
        LOG_WARNING("tablet is already on specified path").tag("path", tablet->data_dir()->path());
367
0
        return Status::Error<FILE_ALREADY_EXIST, false>("tablet is already on specified path: {}",
368
0
                                                        tablet->data_dir()->path());
369
0
    }
370
371
    // check local disk capacity
372
0
    int64_t tablet_size = tablet->tablet_local_size();
373
0
    if ((*dest_store)->reach_capacity_limit(tablet_size)) {
374
0
        return Status::Error<EXCEEDED_LIMIT>("reach the capacity limit of path {}, tablet_size={}",
375
0
                                             (*dest_store)->path(), tablet_size);
376
0
    }
377
0
    return Status::OK();
378
0
}
379
380
// Return `true` if report success
381
bool handle_report(const TReportRequest& request, const ClusterInfo* cluster_info,
382
3.04k
                   std::string_view name) {
383
3.04k
    TMasterResult result;
384
3.04k
    Status status = MasterServerClient::instance()->report(request, &result);
385
3.04k
    if (!status.ok()) [[unlikely]] {
386
0
        LOG_WARNING("failed to report {}", name)
387
0
                .tag("host", cluster_info->master_fe_addr.hostname)
388
0
                .tag("port", cluster_info->master_fe_addr.port)
389
0
                .error(status);
390
0
        return false;
391
0
    }
392
393
3.04k
    else if (result.status.status_code != TStatusCode::OK) [[unlikely]] {
394
0
        LOG_WARNING("failed to report {}", name)
395
0
                .tag("host", cluster_info->master_fe_addr.hostname)
396
0
                .tag("port", cluster_info->master_fe_addr.port)
397
0
                .error(result.status);
398
0
        return false;
399
0
    }
400
401
3.04k
    return true;
402
3.04k
}
403
404
Status _submit_task(const TAgentTaskRequest& task,
405
79.4k
                    std::function<Status(const TAgentTaskRequest&)> submit_op) {
406
79.4k
    const TTaskType::type task_type = task.task_type;
407
79.4k
    int64_t signature = task.signature;
408
409
79.4k
    std::string type_str;
410
79.4k
    EnumToString(TTaskType, task_type, type_str);
411
18.4E
    VLOG_CRITICAL << "submitting task. type=" << type_str << ", signature=" << signature;
412
413
79.4k
    if (!register_task_info(task_type, signature)) {
414
1.68k
        LOG_WARNING("failed to register task").tag("type", type_str).tag("signature", signature);
415
        // Duplicated task request, just return OK
416
1.68k
        return Status::OK();
417
1.68k
    }
418
419
    // TODO(plat1ko): check task request member
420
421
    // Set the receiving time of task so that we can determine whether it is timed out later
422
    // exist a path task_worker_pool <- agent_server <- backend_service <- BackendService
423
    // use the arg BackendService_submit_tasks_args.tasks is not const, so modify is ok
424
77.7k
    (const_cast<TAgentTaskRequest&>(task)).__set_recv_time(time(nullptr));
425
77.7k
    auto st = submit_op(task);
426
77.7k
    if (!st.ok()) [[unlikely]] {
427
1
        LOG_INFO("failed to submit task").tag("type", type_str).tag("signature", signature);
428
1
        return st;
429
1
    }
430
431
77.7k
    LOG_INFO("successfully submit task").tag("type", type_str).tag("signature", signature);
432
77.7k
    return Status::OK();
433
77.7k
}
434
435
bvar::LatencyRecorder g_publish_version_latency("doris_pk", "publish_version");
436
437
bvar::Adder<uint64_t> ALTER_INVERTED_INDEX_count("task", "ALTER_INVERTED_INDEX");
438
bvar::Adder<uint64_t> CHECK_CONSISTENCY_count("task", "CHECK_CONSISTENCY");
439
bvar::Adder<uint64_t> UPLOAD_count("task", "UPLOAD");
440
bvar::Adder<uint64_t> DOWNLOAD_count("task", "DOWNLOAD");
441
bvar::Adder<uint64_t> MAKE_SNAPSHOT_count("task", "MAKE_SNAPSHOT");
442
bvar::Adder<uint64_t> RELEASE_SNAPSHOT_count("task", "RELEASE_SNAPSHOT");
443
bvar::Adder<uint64_t> MOVE_count("task", "MOVE");
444
bvar::Adder<uint64_t> COMPACTION_count("task", "COMPACTION");
445
bvar::Adder<uint64_t> PUSH_STORAGE_POLICY_count("task", "PUSH_STORAGE_POLICY");
446
bvar::Adder<uint64_t> PUSH_INDEX_POLICY_count("task", "PUSH_INDEX_POLICY");
447
bvar::Adder<uint64_t> PUSH_COOLDOWN_CONF_count("task", "PUSH_COOLDOWN_CONF");
448
bvar::Adder<uint64_t> CREATE_count("task", "CREATE_TABLE");
449
bvar::Adder<uint64_t> DROP_count("task", "DROP_TABLE");
450
bvar::Adder<uint64_t> PUBLISH_VERSION_count("task", "PUBLISH_VERSION");
451
bvar::Adder<uint64_t> CLEAR_TRANSACTION_TASK_count("task", "CLEAR_TRANSACTION_TASK");
452
bvar::Adder<uint64_t> DELETE_count("task", "DELETE");
453
bvar::Adder<uint64_t> PUSH_count("task", "PUSH");
454
bvar::Adder<uint64_t> UPDATE_TABLET_META_INFO_count("task", "UPDATE_TABLET_META_INFO");
455
bvar::Adder<uint64_t> ALTER_count("task", "ALTER_TABLE");
456
bvar::Adder<uint64_t> CLONE_count("task", "CLONE");
457
bvar::Adder<uint64_t> STORAGE_MEDIUM_MIGRATE_count("task", "STORAGE_MEDIUM_MIGRATE");
458
bvar::Adder<uint64_t> GC_BINLOG_count("task", "GC_BINLOG");
459
bvar::Adder<uint64_t> UPDATE_VISIBLE_VERSION_count("task", "UPDATE_VISIBLE_VERSION");
460
bvar::Adder<uint64_t> CALCULATE_DELETE_BITMAP_count("task", "CALCULATE_DELETE_BITMAP");
461
462
155k
void add_task_count(const TAgentTaskRequest& task, int n) {
463
    // clang-format off
464
155k
    switch (task.task_type) {
465
0
    #define ADD_TASK_COUNT(type) \
466
72.1k
    case TTaskType::type:        \
467
144k
        type##_count << n;       \
468
72.1k
        return;
469
1.17k
    ADD_TASK_COUNT(ALTER_INVERTED_INDEX)
470
0
    ADD_TASK_COUNT(CHECK_CONSISTENCY)
471
32
    ADD_TASK_COUNT(UPLOAD)
472
44
    ADD_TASK_COUNT(DOWNLOAD)
473
638
    ADD_TASK_COUNT(MAKE_SNAPSHOT)
474
640
    ADD_TASK_COUNT(RELEASE_SNAPSHOT)
475
344
    ADD_TASK_COUNT(MOVE)
476
6
    ADD_TASK_COUNT(COMPACTION)
477
22
    ADD_TASK_COUNT(PUSH_STORAGE_POLICY)
478
34
    ADD_TASK_COUNT(PUSH_INDEX_POLICY)
479
4
    ADD_TASK_COUNT(PUSH_COOLDOWN_CONF)
480
16.1k
    ADD_TASK_COUNT(CREATE)
481
11.4k
    ADD_TASK_COUNT(DROP)
482
12.2k
    ADD_TASK_COUNT(PUBLISH_VERSION)
483
32
    ADD_TASK_COUNT(CLEAR_TRANSACTION_TASK)
484
0
    ADD_TASK_COUNT(UPDATE_TABLET_META_INFO)
485
0
    ADD_TASK_COUNT(CLONE)
486
0
    ADD_TASK_COUNT(STORAGE_MEDIUM_MIGRATE)
487
0
    ADD_TASK_COUNT(GC_BINLOG)
488
11.8k
    ADD_TASK_COUNT(UPDATE_VISIBLE_VERSION)
489
17.4k
    ADD_TASK_COUNT(CALCULATE_DELETE_BITMAP)
490
0
    #undef ADD_TASK_COUNT
491
6.42k
    case TTaskType::REALTIME_PUSH:
492
6.42k
    case TTaskType::PUSH:
493
6.42k
        if (task.push_req.push_type == TPushType::LOAD_V2) {
494
0
            PUSH_count << n;
495
6.42k
        } else if (task.push_req.push_type == TPushType::DELETE) {
496
6.42k
            DELETE_count << n;
497
6.42k
        }
498
6.42k
        return;
499
22.2k
    case TTaskType::ALTER:
500
22.2k
    {
501
22.2k
        ALTER_count << n;
502
        // cloud auto stop need sc jobs, a tablet's sc can also be considered a fragment
503
22.2k
        if (n > 0) {
504
            // only count fragment when task is actually starting
505
11.1k
            doris::g_fragment_executing_count << 1;
506
11.1k
            int64_t now = duration_cast<std::chrono::milliseconds>(
507
11.1k
                                std::chrono::system_clock::now().time_since_epoch())
508
11.1k
                                .count();
509
11.1k
            g_fragment_last_active_time.set_value(now);
510
11.1k
        }
511
22.2k
        return;
512
6.42k
    }
513
54.9k
    default:
514
54.9k
        return;
515
155k
    }
516
    // clang-format on
517
155k
}
518
519
bvar::Adder<uint64_t> report_task_total("report", "task_total");
520
bvar::Adder<uint64_t> report_task_failed("report", "task_failed");
521
bvar::Adder<uint64_t> report_disk_total("report", "disk_total");
522
bvar::Adder<uint64_t> report_disk_failed("report", "disk_failed");
523
bvar::Adder<uint64_t> report_tablet_total("report", "tablet_total");
524
bvar::Adder<uint64_t> report_tablet_failed("report", "tablet_failed");
525
bvar::Adder<uint64_t> report_index_policy_total("report", "index_policy_total");
526
bvar::Adder<uint64_t> report_index_policy_failed("report", "index_policy_failed");
527
528
} // namespace
529
530
TaskWorkerPool::TaskWorkerPool(
531
        std::string_view name, int worker_count,
532
        std::function<void(const TAgentTaskRequest& task)> callback,
533
        std::function<void(const TAgentTaskRequest& task)> pre_submit_callback)
534
152
        : _callback(std::move(callback)), _pre_submit_callback(std::move(pre_submit_callback)) {
535
152
    auto st = ThreadPoolBuilder(fmt::format("TaskWP_{}", name))
536
152
                      .set_min_threads(worker_count)
537
152
                      .set_max_threads(worker_count)
538
152
                      .build(&_thread_pool);
539
152
    CHECK(st.ok()) << name << ": " << st;
540
152
}
541
542
72
TaskWorkerPool::~TaskWorkerPool() {
543
72
    stop();
544
72
}
545
546
78
void TaskWorkerPool::stop() {
547
78
    if (_stopped.exchange(true)) {
548
6
        return;
549
6
    }
550
551
72
    if (_thread_pool) {
552
72
        _thread_pool->shutdown();
553
72
    }
554
72
}
555
556
79.4k
Status TaskWorkerPool::submit_task(const TAgentTaskRequest& task) {
557
79.4k
    return _submit_task(task, [this](auto&& task) {
558
77.9k
        if (_pre_submit_callback) {
559
11.1k
            _pre_submit_callback(task);
560
11.1k
        }
561
77.9k
        add_task_count(task, 1);
562
77.9k
        return _thread_pool->submit_func([this, task]() {
563
77.9k
            _callback(task);
564
77.9k
            add_task_count(task, -1);
565
77.9k
        });
566
77.9k
    });
567
79.4k
}
568
569
PriorTaskWorkerPool::PriorTaskWorkerPool(
570
        const std::string& name, int normal_worker_count, int high_prior_worker_count,
571
        std::function<void(const TAgentTaskRequest& task)> callback)
572
13
        : _callback(std::move(callback)) {
573
50
    for (int i = 0; i < normal_worker_count; ++i) {
574
37
        auto st = Thread::create(
575
37
                "Normal", name, [this] { normal_loop(); }, &_workers.emplace_back());
576
37
        CHECK(st.ok()) << name << ": " << st;
577
37
    }
578
579
50
    for (int i = 0; i < high_prior_worker_count; ++i) {
580
37
        auto st = Thread::create(
581
37
                "HighPrior", name, [this] { high_prior_loop(); }, &_workers.emplace_back());
582
37
        CHECK(st.ok()) << name << ": " << st;
583
37
    }
584
13
}
585
586
7
PriorTaskWorkerPool::~PriorTaskWorkerPool() {
587
7
    stop();
588
7
}
589
590
11
void PriorTaskWorkerPool::stop() {
591
11
    {
592
11
        std::lock_guard lock(_mtx);
593
11
        if (_stopped) {
594
4
            return;
595
4
        }
596
597
7
        _stopped = true;
598
7
    }
599
0
    _normal_condv.notify_all();
600
7
    _high_prior_condv.notify_all();
601
602
38
    for (auto&& w : _workers) {
603
38
        if (w) {
604
38
            w->join();
605
38
        }
606
38
    }
607
7
}
608
609
6
Status PriorTaskWorkerPool::submit_task(const TAgentTaskRequest& task) {
610
6
    return _submit_task(task, [this](auto&& task) {
611
6
        auto req = std::make_unique<TAgentTaskRequest>(task);
612
6
        add_task_count(*req, 1);
613
6
        if (req->__isset.priority && req->priority == TPriority::HIGH) {
614
4
            std::lock_guard lock(_mtx);
615
4
            _high_prior_queue.push_back(std::move(req));
616
4
            _high_prior_condv.notify_one();
617
4
            _normal_condv.notify_one();
618
4
        } else {
619
2
            std::lock_guard lock(_mtx);
620
2
            _normal_queue.push_back(std::move(req));
621
2
            _normal_condv.notify_one();
622
2
        }
623
6
        return Status::OK();
624
6
    });
625
6
}
626
627
0
Status PriorTaskWorkerPool::submit_high_prior_and_cancel_low(TAgentTaskRequest& task) {
628
0
    const TTaskType::type task_type = task.task_type;
629
0
    int64_t signature = task.signature;
630
0
    std::string type_str;
631
0
    EnumToString(TTaskType, task_type, type_str);
632
0
    auto req = std::make_unique<TAgentTaskRequest>(task);
633
634
0
    DCHECK(req->__isset.priority && req->priority == TPriority::HIGH);
635
0
    do {
636
0
        std::lock_guard lock(s_task_signatures_mtx);
637
0
        auto& set = s_task_signatures[task_type];
638
0
        if (!set.contains(signature)) {
639
            // If it doesn't exist, put it directly into the priority queue
640
0
            add_task_count(*req, 1);
641
0
            set.insert(signature);
642
0
            std::lock_guard temp_lock(_mtx);
643
0
            _high_prior_queue.push_back(std::move(req));
644
0
            _high_prior_condv.notify_one();
645
0
            _normal_condv.notify_one();
646
0
            break;
647
0
        } else {
648
0
            std::lock_guard temp_lock(_mtx);
649
0
            for (auto it = _normal_queue.begin(); it != _normal_queue.end();) {
650
                // If it exists in the normal queue, cancel the task in the normal queue
651
0
                if ((*it)->signature == signature) {
652
0
                    _normal_queue.erase(it);                     // cancel the original task
653
0
                    _high_prior_queue.push_back(std::move(req)); // add the new task to the queue
654
0
                    _high_prior_condv.notify_one();
655
0
                    _normal_condv.notify_one();
656
0
                    break;
657
0
                } else {
658
0
                    ++it; // doesn't meet the condition, continue to the next one
659
0
                }
660
0
            }
661
            // If it exists in the high priority queue, no operation is needed
662
0
            LOG_INFO("task has already existed in high prior queue.").tag("signature", signature);
663
0
        }
664
0
    } while (false);
665
666
    // Set the receiving time of task so that we can determine whether it is timed out later
667
0
    task.__set_recv_time(time(nullptr));
668
669
0
    LOG_INFO("successfully submit task").tag("type", type_str).tag("signature", signature);
670
0
    return Status::OK();
671
0
}
672
673
37
void PriorTaskWorkerPool::normal_loop() {
674
58
    while (true) {
675
40
        std::unique_ptr<TAgentTaskRequest> req;
676
677
40
        {
678
40
            std::unique_lock lock(_mtx);
679
62
            _normal_condv.wait(lock, [&] {
680
62
                return !_normal_queue.empty() || !_high_prior_queue.empty() || _stopped;
681
62
            });
682
683
40
            if (_stopped) {
684
19
                return;
685
19
            }
686
687
21
            if (!_high_prior_queue.empty()) {
688
1
                req = std::move(_high_prior_queue.front());
689
1
                _high_prior_queue.pop_front();
690
20
            } else if (!_normal_queue.empty()) {
691
2
                req = std::move(_normal_queue.front());
692
2
                _normal_queue.pop_front();
693
18
            } else {
694
18
                continue;
695
18
            }
696
21
        }
697
698
3
        _callback(*req);
699
3
        add_task_count(*req, -1);
700
3
    }
701
37
}
702
703
37
void PriorTaskWorkerPool::high_prior_loop() {
704
57
    while (true) {
705
39
        std::unique_ptr<TAgentTaskRequest> req;
706
707
39
        {
708
39
            std::unique_lock lock(_mtx);
709
60
            _high_prior_condv.wait(lock, [&] { return !_high_prior_queue.empty() || _stopped; });
710
711
39
            if (_stopped) {
712
19
                return;
713
19
            }
714
715
20
            if (_high_prior_queue.empty()) {
716
0
                continue;
717
0
            }
718
719
20
            req = std::move(_high_prior_queue.front());
720
20
            _high_prior_queue.pop_front();
721
20
        }
722
723
0
        _callback(*req);
724
20
        add_task_count(*req, -1);
725
20
    }
726
37
}
727
728
ReportWorker::ReportWorker(std::string name, const ClusterInfo* cluster_info, int report_interval_s,
729
                           std::function<void()> callback)
730
29
        : _name(std::move(name)) {
731
29
    auto report_loop = [this, cluster_info, report_interval_s, callback = std::move(callback)] {
732
29
        auto& engine = ExecEnv::GetInstance()->storage_engine();
733
29
        engine.register_report_listener(this);
734
3.14k
        while (true) {
735
3.13k
            {
736
3.13k
                std::unique_lock lock(_mtx);
737
3.13k
                _condv.wait_for(lock, std::chrono::seconds(report_interval_s),
738
6.24k
                                [&] { return _stopped || _signal; });
739
740
3.13k
                if (_stopped) {
741
13
                    break;
742
13
                }
743
744
3.11k
                if (_signal) {
745
                    // Consume received signal
746
60
                    _signal = false;
747
60
                }
748
3.11k
            }
749
750
3.11k
            if (cluster_info->master_fe_addr.port == 0) {
751
                // port == 0 means not received heartbeat yet
752
59
                LOG(INFO) << "waiting to receive first heartbeat from frontend before doing report";
753
59
                continue;
754
59
            }
755
756
3.06k
            callback();
757
3.06k
        }
758
29
        engine.deregister_report_listener(this);
759
29
    };
760
761
29
    auto st = Thread::create("ReportWorker", _name, report_loop, &_thread);
762
29
    CHECK(st.ok()) << _name << ": " << st;
763
29
}
764
765
13
ReportWorker::~ReportWorker() {
766
13
    stop();
767
13
}
768
769
61
void ReportWorker::notify() {
770
61
    {
771
61
        std::lock_guard lock(_mtx);
772
61
        _signal = true;
773
61
    }
774
61
    _condv.notify_all();
775
61
}
776
777
14
void ReportWorker::stop() {
778
14
    {
779
14
        std::lock_guard lock(_mtx);
780
14
        if (_stopped) {
781
1
            return;
782
1
        }
783
784
13
        _stopped = true;
785
13
    }
786
0
    _condv.notify_all();
787
13
    if (_thread) {
788
13
        _thread->join();
789
13
    }
790
13
}
791
792
586
void alter_cloud_index_callback(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
793
586
    const auto& alter_inverted_index_rq = req.alter_inverted_index_req;
794
586
    LOG(INFO) << "[index_change]get alter index task. signature=" << req.signature
795
586
              << ", tablet_id=" << alter_inverted_index_rq.tablet_id
796
586
              << ", job_id=" << alter_inverted_index_rq.job_id;
797
798
586
    Status status = Status::OK();
799
586
    auto tablet_ptr = engine.tablet_mgr().get_tablet(alter_inverted_index_rq.tablet_id);
800
586
    if (tablet_ptr != nullptr) {
801
586
        EngineCloudIndexChangeTask engine_task(engine, req.alter_inverted_index_req);
802
586
        status = engine_task.execute();
803
586
    } else {
804
0
        status = Status::NotFound("could not find tablet {}", alter_inverted_index_rq.tablet_id);
805
0
    }
806
807
    // Return result to fe
808
586
    TFinishTaskRequest finish_task_request;
809
586
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
810
586
    finish_task_request.__set_task_type(req.task_type);
811
586
    finish_task_request.__set_signature(req.signature);
812
586
    if (!status.ok()) {
813
9
        LOG(WARNING) << "[index_change]failed to alter inverted index task, signature="
814
9
                     << req.signature << ", tablet_id=" << alter_inverted_index_rq.tablet_id
815
9
                     << ", job_id=" << alter_inverted_index_rq.job_id << ", error=" << status;
816
577
    } else {
817
577
        LOG(INFO) << "[index_change]successfully alter inverted index task, signature="
818
577
                  << req.signature << ", tablet_id=" << alter_inverted_index_rq.tablet_id
819
577
                  << ", job_id=" << alter_inverted_index_rq.job_id;
820
577
    }
821
586
    finish_task_request.__set_task_status(status.to_thrift());
822
586
    finish_task(finish_task_request);
823
586
    remove_task_info(req.task_type, req.signature);
824
586
}
825
826
0
void alter_inverted_index_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
827
0
    const auto& alter_inverted_index_rq = req.alter_inverted_index_req;
828
0
    LOG(INFO) << "get alter inverted index task. signature=" << req.signature
829
0
              << ", tablet_id=" << alter_inverted_index_rq.tablet_id
830
0
              << ", job_id=" << alter_inverted_index_rq.job_id;
831
832
0
    Status status = Status::OK();
833
0
    auto tablet_ptr = engine.tablet_manager()->get_tablet(alter_inverted_index_rq.tablet_id);
834
0
    if (tablet_ptr != nullptr) {
835
0
        EngineIndexChangeTask engine_task(engine, alter_inverted_index_rq);
836
0
        SCOPED_ATTACH_TASK(engine_task.mem_tracker());
837
0
        status = engine_task.execute();
838
0
    } else {
839
0
        status = Status::NotFound("could not find tablet {}", alter_inverted_index_rq.tablet_id);
840
0
    }
841
842
    // Return result to fe
843
0
    TFinishTaskRequest finish_task_request;
844
0
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
845
0
    finish_task_request.__set_task_type(req.task_type);
846
0
    finish_task_request.__set_signature(req.signature);
847
0
    std::vector<TTabletInfo> finish_tablet_infos;
848
0
    if (!status.ok()) {
849
0
        LOG(WARNING) << "failed to alter inverted index task, signature=" << req.signature
850
0
                     << ", tablet_id=" << alter_inverted_index_rq.tablet_id
851
0
                     << ", job_id=" << alter_inverted_index_rq.job_id << ", error=" << status;
852
0
    } else {
853
0
        LOG(INFO) << "successfully alter inverted index task, signature=" << req.signature
854
0
                  << ", tablet_id=" << alter_inverted_index_rq.tablet_id
855
0
                  << ", job_id=" << alter_inverted_index_rq.job_id;
856
0
        TTabletInfo tablet_info;
857
0
        status = get_tablet_info(engine, alter_inverted_index_rq.tablet_id,
858
0
                                 alter_inverted_index_rq.schema_hash, &tablet_info);
859
0
        if (status.ok()) {
860
0
            finish_tablet_infos.push_back(tablet_info);
861
0
        }
862
0
        finish_task_request.__set_finish_tablet_infos(finish_tablet_infos);
863
0
    }
864
0
    finish_task_request.__set_task_status(status.to_thrift());
865
0
    finish_task(finish_task_request);
866
0
    remove_task_info(req.task_type, req.signature);
867
0
}
868
869
0
void update_tablet_meta_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
870
0
    LOG(INFO) << "get update tablet meta task. signature=" << req.signature;
871
872
0
    Status status;
873
0
    const auto& update_tablet_meta_req = req.update_tablet_meta_info_req;
874
0
    for (const auto& tablet_meta_info : update_tablet_meta_req.tabletMetaInfos) {
875
0
        auto tablet = engine.tablet_manager()->get_tablet(tablet_meta_info.tablet_id);
876
0
        if (tablet == nullptr) {
877
0
            status = Status::NotFound("tablet not found");
878
0
            LOG(WARNING) << "could not find tablet when update tablet meta. tablet_id="
879
0
                         << tablet_meta_info.tablet_id;
880
0
            continue;
881
0
        }
882
0
        bool need_to_save = false;
883
0
        if (tablet_meta_info.__isset.partition_id) {
884
            // for fix partition_id = 0
885
0
            LOG(WARNING) << "change be tablet id: " << tablet->tablet_meta()->tablet_id()
886
0
                         << "partition id from : " << tablet->tablet_meta()->partition_id()
887
0
                         << " to : " << tablet_meta_info.partition_id;
888
0
            auto succ = engine.tablet_manager()->update_tablet_partition_id(
889
0
                    tablet_meta_info.partition_id, tablet->tablet_meta()->tablet_id());
890
0
            if (!succ) {
891
0
                std::string err_msg = fmt::format(
892
0
                        "change be tablet id : {} partition_id : {} failed",
893
0
                        tablet->tablet_meta()->tablet_id(), tablet_meta_info.partition_id);
894
0
                LOG(WARNING) << err_msg;
895
0
                status = Status::InvalidArgument(err_msg);
896
0
                continue;
897
0
            }
898
0
            need_to_save = true;
899
0
        }
900
0
        if (tablet_meta_info.__isset.storage_policy_id) {
901
0
            tablet->tablet_meta()->set_storage_policy_id(tablet_meta_info.storage_policy_id);
902
0
            need_to_save = true;
903
0
        }
904
0
        if (tablet_meta_info.__isset.is_in_memory) {
905
0
            tablet->tablet_meta()->mutable_tablet_schema()->set_is_in_memory(
906
0
                    tablet_meta_info.is_in_memory);
907
0
            std::shared_lock rlock(tablet->get_header_lock());
908
0
            for (auto& [_, rowset_meta] : tablet->tablet_meta()->all_mutable_rs_metas()) {
909
0
                rowset_meta->tablet_schema()->set_is_in_memory(tablet_meta_info.is_in_memory);
910
0
            }
911
0
            tablet->tablet_schema_unlocked()->set_is_in_memory(tablet_meta_info.is_in_memory);
912
0
            need_to_save = true;
913
0
        }
914
0
        if (tablet_meta_info.__isset.compaction_policy) {
915
0
            if (tablet_meta_info.compaction_policy != CUMULATIVE_SIZE_BASED_POLICY &&
916
0
                tablet_meta_info.compaction_policy != CUMULATIVE_TIME_SERIES_POLICY &&
917
0
                tablet_meta_info.compaction_policy != CUMULATIVE_BINLOG_POLICY) {
918
0
                status = Status::InvalidArgument(
919
0
                        "invalid compaction policy, only support for size_based or "
920
0
                        "time_series or binlog");
921
0
                continue;
922
0
            }
923
0
            tablet->tablet_meta()->set_compaction_policy(tablet_meta_info.compaction_policy);
924
0
            need_to_save = true;
925
0
        }
926
0
        if (tablet_meta_info.__isset.time_series_compaction_goal_size_mbytes) {
927
0
            if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
928
0
                status = Status::InvalidArgument(
929
0
                        "only time series compaction policy support time series config");
930
0
                continue;
931
0
            }
932
0
            tablet->tablet_meta()->set_time_series_compaction_goal_size_mbytes(
933
0
                    tablet_meta_info.time_series_compaction_goal_size_mbytes);
934
0
            need_to_save = true;
935
0
        }
936
0
        if (tablet_meta_info.__isset.time_series_compaction_file_count_threshold) {
937
0
            if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
938
0
                status = Status::InvalidArgument(
939
0
                        "only time series compaction policy support time series config");
940
0
                continue;
941
0
            }
942
0
            tablet->tablet_meta()->set_time_series_compaction_file_count_threshold(
943
0
                    tablet_meta_info.time_series_compaction_file_count_threshold);
944
0
            need_to_save = true;
945
0
        }
946
0
        if (tablet_meta_info.__isset.time_series_compaction_time_threshold_seconds) {
947
0
            if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
948
0
                status = Status::InvalidArgument(
949
0
                        "only time series compaction policy support time series config");
950
0
                continue;
951
0
            }
952
0
            tablet->tablet_meta()->set_time_series_compaction_time_threshold_seconds(
953
0
                    tablet_meta_info.time_series_compaction_time_threshold_seconds);
954
0
            need_to_save = true;
955
0
        }
956
0
        if (tablet_meta_info.__isset.time_series_compaction_empty_rowsets_threshold) {
957
0
            if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
958
0
                status = Status::InvalidArgument(
959
0
                        "only time series compaction policy support time series config");
960
0
                continue;
961
0
            }
962
0
            tablet->tablet_meta()->set_time_series_compaction_empty_rowsets_threshold(
963
0
                    tablet_meta_info.time_series_compaction_empty_rowsets_threshold);
964
0
            need_to_save = true;
965
0
        }
966
0
        if (tablet_meta_info.__isset.time_series_compaction_level_threshold) {
967
0
            if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
968
0
                status = Status::InvalidArgument(
969
0
                        "only time series compaction policy support time series config");
970
0
                continue;
971
0
            }
972
0
            tablet->tablet_meta()->set_time_series_compaction_level_threshold(
973
0
                    tablet_meta_info.time_series_compaction_level_threshold);
974
0
            need_to_save = true;
975
0
        }
976
0
        if (tablet_meta_info.__isset.vertical_compaction_num_columns_per_group) {
977
0
            tablet->tablet_meta()->set_vertical_compaction_num_columns_per_group(
978
0
                    tablet_meta_info.vertical_compaction_num_columns_per_group);
979
0
            need_to_save = true;
980
0
        }
981
0
        if (tablet_meta_info.__isset.replica_id) {
982
0
            tablet->tablet_meta()->set_replica_id(tablet_meta_info.replica_id);
983
0
        }
984
0
        if (tablet_meta_info.__isset.binlog_config) {
985
            // check binlog_config require fields: enable, ttl_seconds, max_bytes, max_history_nums
986
0
            const auto& t_binlog_config = tablet_meta_info.binlog_config;
987
0
            if (!t_binlog_config.__isset.enable || !t_binlog_config.__isset.ttl_seconds ||
988
0
                !t_binlog_config.__isset.max_bytes || !t_binlog_config.__isset.max_history_nums) {
989
0
                status = Status::InvalidArgument("invalid binlog config, some fields not set");
990
0
                LOG(WARNING) << fmt::format(
991
0
                        "invalid binlog config, some fields not set, tablet_id={}, "
992
0
                        "t_binlog_config={}",
993
0
                        tablet_meta_info.tablet_id,
994
0
                        apache::thrift::ThriftDebugString(t_binlog_config));
995
0
                continue;
996
0
            }
997
998
0
            BinlogConfig new_binlog_config;
999
0
            new_binlog_config = tablet_meta_info.binlog_config;
1000
0
            LOG(INFO) << fmt::format(
1001
0
                    "update tablet meta binlog config. tablet_id={}, old_binlog_config={}, "
1002
0
                    "new_binlog_config={}",
1003
0
                    tablet_meta_info.tablet_id, tablet->tablet_meta()->binlog_config().to_string(),
1004
0
                    new_binlog_config.to_string());
1005
0
            tablet->set_binlog_config(new_binlog_config);
1006
0
            need_to_save = true;
1007
0
        }
1008
0
        if (tablet_meta_info.__isset.disable_auto_compaction) {
1009
0
            std::shared_lock rlock(tablet->get_header_lock());
1010
0
            tablet->tablet_meta()->mutable_tablet_schema()->set_disable_auto_compaction(
1011
0
                    tablet_meta_info.disable_auto_compaction);
1012
0
            for (auto& [_, rowset_meta] : tablet->tablet_meta()->all_mutable_rs_metas()) {
1013
0
                rowset_meta->tablet_schema()->set_disable_auto_compaction(
1014
0
                        tablet_meta_info.disable_auto_compaction);
1015
0
            }
1016
0
            tablet->tablet_schema_unlocked()->set_disable_auto_compaction(
1017
0
                    tablet_meta_info.disable_auto_compaction);
1018
0
            need_to_save = true;
1019
0
        }
1020
1021
0
        if (tablet_meta_info.__isset.skip_write_index_on_load) {
1022
0
            std::shared_lock rlock(tablet->get_header_lock());
1023
0
            tablet->tablet_meta()->mutable_tablet_schema()->set_skip_write_index_on_load(
1024
0
                    tablet_meta_info.skip_write_index_on_load);
1025
0
            for (auto& [_, rowset_meta] : tablet->tablet_meta()->all_mutable_rs_metas()) {
1026
0
                rowset_meta->tablet_schema()->set_skip_write_index_on_load(
1027
0
                        tablet_meta_info.skip_write_index_on_load);
1028
0
            }
1029
0
            tablet->tablet_schema_unlocked()->set_skip_write_index_on_load(
1030
0
                    tablet_meta_info.skip_write_index_on_load);
1031
0
            need_to_save = true;
1032
0
        }
1033
0
        if (need_to_save) {
1034
0
            std::shared_lock rlock(tablet->get_header_lock());
1035
0
            tablet->save_meta();
1036
0
        }
1037
0
    }
1038
1039
0
    LOG(INFO) << "finish update tablet meta task. signature=" << req.signature;
1040
0
    if (req.signature != -1) {
1041
0
        TFinishTaskRequest finish_task_request;
1042
0
        finish_task_request.__set_task_status(status.to_thrift());
1043
0
        finish_task_request.__set_backend(BackendOptions::get_local_backend());
1044
0
        finish_task_request.__set_task_type(req.task_type);
1045
0
        finish_task_request.__set_signature(req.signature);
1046
0
        finish_task(finish_task_request);
1047
0
        remove_task_info(req.task_type, req.signature);
1048
0
    }
1049
0
}
1050
1051
0
void check_consistency_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1052
0
    uint32_t checksum = 0;
1053
0
    const auto& check_consistency_req = req.check_consistency_req;
1054
0
    EngineChecksumTask engine_task(engine, check_consistency_req.tablet_id,
1055
0
                                   check_consistency_req.schema_hash, check_consistency_req.version,
1056
0
                                   &checksum);
1057
0
    SCOPED_ATTACH_TASK(engine_task.mem_tracker());
1058
0
    Status status = engine_task.execute();
1059
0
    if (!status.ok()) {
1060
0
        LOG_WARNING("failed to check consistency")
1061
0
                .tag("signature", req.signature)
1062
0
                .tag("tablet_id", check_consistency_req.tablet_id)
1063
0
                .error(status);
1064
0
    } else {
1065
0
        LOG_INFO("successfully check consistency")
1066
0
                .tag("signature", req.signature)
1067
0
                .tag("tablet_id", check_consistency_req.tablet_id)
1068
0
                .tag("checksum", checksum);
1069
0
    }
1070
1071
0
    TFinishTaskRequest finish_task_request;
1072
0
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1073
0
    finish_task_request.__set_task_type(req.task_type);
1074
0
    finish_task_request.__set_signature(req.signature);
1075
0
    finish_task_request.__set_task_status(status.to_thrift());
1076
0
    finish_task_request.__set_tablet_checksum(static_cast<int64_t>(checksum));
1077
0
    finish_task_request.__set_request_version(check_consistency_req.version);
1078
1079
0
    finish_task(finish_task_request);
1080
0
    remove_task_info(req.task_type, req.signature);
1081
0
}
1082
1083
1.03k
void report_task_callback(const ClusterInfo* cluster_info) {
1084
1.03k
    TReportRequest request;
1085
1.03k
    if (config::report_random_wait) {
1086
1.03k
        random_sleep(5);
1087
1.03k
    }
1088
1.03k
    request.__isset.tasks = true;
1089
1.03k
    {
1090
1.03k
        std::lock_guard lock(s_task_signatures_mtx);
1091
1.03k
        auto& tasks = request.tasks;
1092
6.97k
        for (auto&& [task_type, signatures] : s_task_signatures) {
1093
6.97k
            auto& set = tasks[task_type];
1094
4.27M
            for (auto&& signature : signatures) {
1095
4.27M
                set.insert(signature);
1096
4.27M
            }
1097
6.97k
        }
1098
1.03k
    }
1099
1.03k
    request.__set_backend(BackendOptions::get_local_backend());
1100
1.03k
    request.__set_running_tasks(ExecEnv::GetInstance()->fragment_mgr()->running_query_num());
1101
1.03k
    bool succ = handle_report(request, cluster_info, "task");
1102
1.03k
    report_task_total << 1;
1103
1.03k
    if (!succ) [[unlikely]] {
1104
0
        report_task_failed << 1;
1105
0
    }
1106
1.03k
}
1107
1108
333
void report_disk_callback(StorageEngine& engine, const ClusterInfo* cluster_info) {
1109
333
    TReportRequest request;
1110
333
    request.__set_backend(BackendOptions::get_local_backend());
1111
333
    request.__isset.disks = true;
1112
1113
333
    std::vector<DataDirInfo> data_dir_infos;
1114
333
    static_cast<void>(engine.get_all_data_dir_info(&data_dir_infos, true /* update */));
1115
1116
373
    for (auto& root_path_info : data_dir_infos) {
1117
373
        TDisk disk;
1118
373
        disk.__set_root_path(root_path_info.path);
1119
373
        disk.__set_path_hash(root_path_info.path_hash);
1120
373
        disk.__set_storage_medium(root_path_info.storage_medium);
1121
373
        disk.__set_disk_total_capacity(root_path_info.disk_capacity);
1122
373
        disk.__set_data_used_capacity(root_path_info.local_used_capacity);
1123
373
        disk.__set_remote_used_capacity(root_path_info.remote_used_capacity);
1124
373
        disk.__set_disk_available_capacity(root_path_info.available);
1125
373
        disk.__set_trash_used_capacity(root_path_info.trash_used_capacity);
1126
373
        disk.__set_used(root_path_info.is_used);
1127
373
        request.disks[root_path_info.path] = disk;
1128
373
    }
1129
333
    request.__set_num_cores(CpuInfo::num_cores());
1130
333
    request.__set_pipeline_executor_size(config::pipeline_executor_size > 0
1131
333
                                                 ? config::pipeline_executor_size
1132
333
                                                 : CpuInfo::num_cores());
1133
333
    bool succ = handle_report(request, cluster_info, "disk");
1134
333
    report_disk_total << 1;
1135
333
    if (!succ) [[unlikely]] {
1136
0
        report_disk_failed << 1;
1137
0
    }
1138
333
}
1139
1140
109
void report_disk_callback(CloudStorageEngine& engine, const ClusterInfo* cluster_info) {
1141
    // Random sleep 1~5 seconds before doing report.
1142
    // In order to avoid the problem that the FE receives many report requests at the same time
1143
    // and can not be processed.
1144
109
    if (config::report_random_wait) {
1145
109
        random_sleep(5);
1146
109
    }
1147
109
    (void)engine; // To be used in the future
1148
1149
109
    TReportRequest request;
1150
109
    request.__set_backend(BackendOptions::get_local_backend());
1151
109
    request.__isset.disks = true;
1152
1153
    // TODO(deardeng): report disk info in cloud mode. And make it more clear
1154
    //                 that report CPU by using a separte report procedure
1155
    //                 or abstracting disk report as "host info report"
1156
109
    request.__set_num_cores(CpuInfo::num_cores());
1157
109
    request.__set_pipeline_executor_size(config::pipeline_executor_size > 0
1158
109
                                                 ? config::pipeline_executor_size
1159
109
                                                 : CpuInfo::num_cores());
1160
109
    bool succ = handle_report(request, cluster_info, "disk");
1161
109
    report_disk_total << 1;
1162
109
    report_disk_failed << !succ;
1163
109
}
1164
1165
160
void report_tablet_callback(StorageEngine& engine, const ClusterInfo* cluster_info) {
1166
160
    if (config::report_random_wait) {
1167
160
        random_sleep(5);
1168
160
    }
1169
1170
160
    TReportRequest request;
1171
160
    request.__set_backend(BackendOptions::get_local_backend());
1172
160
    request.__isset.tablets = true;
1173
1174
160
    increase_report_version();
1175
160
    uint64_t report_version;
1176
160
    for (int i = 0; i < 5; i++) {
1177
160
        request.tablets.clear();
1178
160
        report_version = s_report_version;
1179
160
        engine.tablet_manager()->build_all_report_tablets_info(&request.tablets);
1180
160
        if (report_version == s_report_version) {
1181
160
            break;
1182
160
        }
1183
160
    }
1184
1185
160
    if (report_version < s_report_version) {
1186
        // TODO llj This can only reduce the possibility for report error, but can't avoid it.
1187
        // If FE create a tablet in FE meta and send CREATE task to this BE, the tablet may not be included in this
1188
        // report, and the report version has a small probability that it has not been updated in time. When FE
1189
        // receives this report, it is possible to delete the new tablet.
1190
0
        LOG(WARNING) << "report version " << report_version << " change to " << s_report_version;
1191
0
        DorisMetrics::instance()->report_all_tablets_requests_skip->increment(1);
1192
0
        return;
1193
0
    }
1194
1195
160
    std::map<int64_t, int64_t> partitions_version;
1196
160
    engine.tablet_manager()->get_partitions_visible_version(&partitions_version);
1197
160
    request.__set_partitions_version(std::move(partitions_version));
1198
1199
160
    int64_t max_compaction_score =
1200
160
            std::max(DorisMetrics::instance()->tablet_cumulative_max_compaction_score->value(),
1201
160
                     DorisMetrics::instance()->tablet_base_max_compaction_score->value());
1202
160
    request.__set_tablet_max_compaction_score(max_compaction_score);
1203
160
    request.__set_report_version(report_version);
1204
1205
    // report storage policy and resource
1206
160
    auto& storage_policy_list = request.storage_policy;
1207
160
    for (auto [id, version] : get_storage_policy_ids()) {
1208
84
        auto& storage_policy = storage_policy_list.emplace_back();
1209
84
        storage_policy.__set_id(id);
1210
84
        storage_policy.__set_version(version);
1211
84
    }
1212
160
    request.__isset.storage_policy = true;
1213
160
    auto& resource_list = request.resource;
1214
213
    for (auto [id_str, version] : get_storage_resource_ids()) {
1215
213
        auto& resource = resource_list.emplace_back();
1216
213
        int64_t id = -1;
1217
213
        if (auto [_, ec] = std::from_chars(id_str.data(), id_str.data() + id_str.size(), id);
1218
213
            ec != std::errc {}) [[unlikely]] {
1219
0
            LOG(ERROR) << "invalid resource id format: " << id_str;
1220
213
        } else {
1221
213
            resource.__set_id(id);
1222
213
            resource.__set_version(version);
1223
213
        }
1224
213
    }
1225
160
    request.__isset.resource = true;
1226
1227
160
    bool succ = handle_report(request, cluster_info, "tablet");
1228
160
    report_tablet_total << 1;
1229
160
    if (!succ) [[unlikely]] {
1230
0
        report_tablet_failed << 1;
1231
0
    }
1232
160
}
1233
1234
57
void report_tablet_callback(CloudStorageEngine& engine, const ClusterInfo* cluster_info) {
1235
    // Random sleep 1~5 seconds before doing report.
1236
    // In order to avoid the problem that the FE receives many report requests at the same time
1237
    // and can not be processed.
1238
57
    if (config::report_random_wait) {
1239
57
        random_sleep(5);
1240
57
    }
1241
1242
57
    TReportRequest request;
1243
57
    request.__set_backend(BackendOptions::get_local_backend());
1244
57
    request.__isset.tablets = true;
1245
1246
57
    increase_report_version();
1247
57
    uint64_t report_version;
1248
57
    uint64_t total_num_tablets = 0;
1249
71
    for (int i = 0; i < 5; i++) {
1250
70
        request.tablets.clear();
1251
70
        report_version = s_report_version;
1252
70
        engine.tablet_mgr().build_all_report_tablets_info(&request.tablets, &total_num_tablets);
1253
70
        if (report_version == s_report_version) {
1254
56
            break;
1255
56
        }
1256
70
    }
1257
1258
57
    if (report_version < s_report_version) {
1259
1
        LOG(WARNING) << "report version " << report_version << " change to " << s_report_version;
1260
1
        DorisMetrics::instance()->report_all_tablets_requests_skip->increment(1);
1261
1
        return;
1262
1
    }
1263
1264
56
    request.__set_report_version(report_version);
1265
56
    request.__set_num_tablets(total_num_tablets);
1266
1267
56
    bool succ = handle_report(request, cluster_info, "tablet");
1268
56
    report_tablet_total << 1;
1269
56
    if (!succ) [[unlikely]] {
1270
0
        report_tablet_failed << 1;
1271
0
    }
1272
56
}
1273
1274
16
void upload_callback(StorageEngine& engine, ExecEnv* env, const TAgentTaskRequest& req) {
1275
16
    const auto& upload_request = req.upload_req;
1276
1277
16
    LOG(INFO) << "get upload task. signature=" << req.signature
1278
16
              << ", job_id=" << upload_request.job_id;
1279
1280
16
    std::map<int64_t, std::vector<std::string>> tablet_files;
1281
16
    std::unique_ptr<SnapshotLoader> loader = std::make_unique<SnapshotLoader>(
1282
16
            engine, env, upload_request.job_id, req.signature, upload_request.broker_addr,
1283
16
            upload_request.broker_prop);
1284
16
    SCOPED_ATTACH_TASK(loader->resource_ctx());
1285
16
    Status status =
1286
16
            loader->init(upload_request.__isset.storage_backend ? upload_request.storage_backend
1287
16
                                                                : TStorageBackendType::type::BROKER,
1288
16
                         upload_request.__isset.location ? upload_request.location : "");
1289
16
    if (status.ok()) {
1290
16
        status = loader->upload(upload_request.src_dest_map, &tablet_files);
1291
16
    }
1292
1293
16
    if (!status.ok()) {
1294
0
        LOG_WARNING("failed to upload")
1295
0
                .tag("signature", req.signature)
1296
0
                .tag("job_id", upload_request.job_id)
1297
0
                .error(status);
1298
16
    } else {
1299
16
        LOG_INFO("successfully upload")
1300
16
                .tag("signature", req.signature)
1301
16
                .tag("job_id", upload_request.job_id);
1302
16
    }
1303
1304
16
    TFinishTaskRequest finish_task_request;
1305
16
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1306
16
    finish_task_request.__set_task_type(req.task_type);
1307
16
    finish_task_request.__set_signature(req.signature);
1308
16
    finish_task_request.__set_task_status(status.to_thrift());
1309
16
    finish_task_request.__set_tablet_files(tablet_files);
1310
1311
16
    finish_task(finish_task_request);
1312
16
    remove_task_info(req.task_type, req.signature);
1313
16
}
1314
1315
22
void download_callback(StorageEngine& engine, ExecEnv* env, const TAgentTaskRequest& req) {
1316
22
    const auto& download_request = req.download_req;
1317
22
    LOG(INFO) << "get download task. signature=" << req.signature
1318
22
              << ", job_id=" << download_request.job_id
1319
22
              << ", task detail: " << apache::thrift::ThriftDebugString(download_request);
1320
1321
    // TODO: download
1322
22
    std::vector<int64_t> downloaded_tablet_ids;
1323
1324
22
    auto status = Status::OK();
1325
22
    if (download_request.__isset.remote_tablet_snapshots) {
1326
0
        std::unique_ptr<SnapshotLoader> loader = std::make_unique<SnapshotLoader>(
1327
0
                engine, env, download_request.job_id, req.signature);
1328
0
        SCOPED_ATTACH_TASK(loader->resource_ctx());
1329
0
        status = loader->remote_http_download(download_request.remote_tablet_snapshots,
1330
0
                                              &downloaded_tablet_ids);
1331
22
    } else {
1332
22
        std::unique_ptr<SnapshotLoader> loader = std::make_unique<SnapshotLoader>(
1333
22
                engine, env, download_request.job_id, req.signature, download_request.broker_addr,
1334
22
                download_request.broker_prop);
1335
22
        SCOPED_ATTACH_TASK(loader->resource_ctx());
1336
22
        status = loader->init(download_request.__isset.storage_backend
1337
22
                                      ? download_request.storage_backend
1338
22
                                      : TStorageBackendType::type::BROKER,
1339
22
                              download_request.__isset.location ? download_request.location : "");
1340
22
        if (status.ok()) {
1341
22
            status = loader->download(download_request.src_dest_map, &downloaded_tablet_ids);
1342
22
        }
1343
22
    }
1344
1345
22
    if (!status.ok()) {
1346
0
        LOG_WARNING("failed to download")
1347
0
                .tag("signature", req.signature)
1348
0
                .tag("job_id", download_request.job_id)
1349
0
                .error(status);
1350
22
    } else {
1351
22
        LOG_INFO("successfully download")
1352
22
                .tag("signature", req.signature)
1353
22
                .tag("job_id", download_request.job_id);
1354
22
    }
1355
1356
22
    TFinishTaskRequest finish_task_request;
1357
22
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1358
22
    finish_task_request.__set_task_type(req.task_type);
1359
22
    finish_task_request.__set_signature(req.signature);
1360
22
    finish_task_request.__set_task_status(status.to_thrift());
1361
22
    finish_task_request.__set_downloaded_tablet_ids(downloaded_tablet_ids);
1362
1363
22
    finish_task(finish_task_request);
1364
22
    remove_task_info(req.task_type, req.signature);
1365
22
}
1366
1367
0
void download_callback(CloudStorageEngine& engine, ExecEnv* env, const TAgentTaskRequest& req) {
1368
0
    const auto& download_request = req.download_req;
1369
0
    LOG(INFO) << "get download task. signature=" << req.signature
1370
0
              << ", job_id=" << download_request.job_id
1371
0
              << ", task detail: " << apache::thrift::ThriftDebugString(download_request);
1372
1373
0
    std::vector<int64_t> transferred_tablet_ids;
1374
1375
0
    auto status = Status::OK();
1376
0
    if (download_request.__isset.remote_tablet_snapshots) {
1377
0
        status = Status::Error<ErrorCode::NOT_IMPLEMENTED_ERROR>(
1378
0
                "remote tablet snapshot is not supported.");
1379
0
    } else {
1380
0
        std::unique_ptr<CloudSnapshotLoader> loader = std::make_unique<CloudSnapshotLoader>(
1381
0
                engine, env, download_request.job_id, req.signature, download_request.broker_addr,
1382
0
                download_request.broker_prop);
1383
0
        SCOPED_ATTACH_TASK(loader->resource_ctx());
1384
0
        status = loader->init(download_request.__isset.storage_backend
1385
0
                                      ? download_request.storage_backend
1386
0
                                      : TStorageBackendType::type::BROKER,
1387
0
                              download_request.__isset.location ? download_request.location : "",
1388
0
                              download_request.vault_id);
1389
0
        if (status.ok()) {
1390
0
            status = loader->download(download_request.src_dest_map, &transferred_tablet_ids);
1391
0
        }
1392
1393
0
        if (!status.ok()) {
1394
0
            LOG_WARNING("failed to download")
1395
0
                    .tag("signature", req.signature)
1396
0
                    .tag("job_id", download_request.job_id)
1397
0
                    .error(status);
1398
0
        } else {
1399
0
            LOG_INFO("successfully download")
1400
0
                    .tag("signature", req.signature)
1401
0
                    .tag("job_id", download_request.job_id);
1402
0
        }
1403
1404
0
        TFinishTaskRequest finish_task_request;
1405
0
        finish_task_request.__set_backend(BackendOptions::get_local_backend());
1406
0
        finish_task_request.__set_task_type(req.task_type);
1407
0
        finish_task_request.__set_signature(req.signature);
1408
0
        finish_task_request.__set_task_status(status.to_thrift());
1409
0
        finish_task_request.__set_downloaded_tablet_ids(transferred_tablet_ids);
1410
1411
0
        finish_task(finish_task_request);
1412
0
        remove_task_info(req.task_type, req.signature);
1413
0
    }
1414
0
}
1415
1416
320
void make_snapshot_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1417
320
    const auto& snapshot_request = req.snapshot_req;
1418
1419
320
    LOG(INFO) << "get snapshot task. signature=" << req.signature;
1420
1421
320
    std::string snapshot_path;
1422
320
    bool allow_incremental_clone = false; // not used
1423
320
    std::vector<std::string> snapshot_files;
1424
320
    Status status = engine.snapshot_mgr()->make_snapshot(snapshot_request, &snapshot_path,
1425
320
                                                         &allow_incremental_clone);
1426
320
    if (status.ok() && snapshot_request.__isset.list_files) {
1427
        // list and save all snapshot files
1428
        // snapshot_path like: data/snapshot/20180417205230.1.86400
1429
        // we need to add subdir: tablet_id/schema_hash/
1430
320
        std::vector<io::FileInfo> files;
1431
320
        bool exists = true;
1432
320
        io::Path path = fmt::format("{}/{}/{}/", snapshot_path, snapshot_request.tablet_id,
1433
320
                                    snapshot_request.schema_hash);
1434
320
        status = io::global_local_filesystem()->list(path, true, &files, &exists);
1435
320
        if (status.ok()) {
1436
350
            for (auto& file : files) {
1437
350
                snapshot_files.push_back(file.file_name);
1438
350
            }
1439
314
        }
1440
320
    }
1441
320
    if (!status.ok()) {
1442
0
        LOG_WARNING("failed to make snapshot")
1443
0
                .tag("signature", req.signature)
1444
0
                .tag("tablet_id", snapshot_request.tablet_id)
1445
0
                .tag("version", snapshot_request.version)
1446
0
                .error(status);
1447
320
    } else {
1448
320
        LOG_INFO("successfully make snapshot")
1449
320
                .tag("signature", req.signature)
1450
320
                .tag("tablet_id", snapshot_request.tablet_id)
1451
320
                .tag("version", snapshot_request.version)
1452
320
                .tag("snapshot_path", snapshot_path);
1453
320
    }
1454
1455
320
    TFinishTaskRequest finish_task_request;
1456
320
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1457
320
    finish_task_request.__set_task_type(req.task_type);
1458
320
    finish_task_request.__set_signature(req.signature);
1459
320
    finish_task_request.__set_snapshot_path(snapshot_path);
1460
320
    finish_task_request.__set_snapshot_files(snapshot_files);
1461
320
    finish_task_request.__set_task_status(status.to_thrift());
1462
1463
320
    finish_task(finish_task_request);
1464
320
    remove_task_info(req.task_type, req.signature);
1465
320
}
1466
1467
320
void release_snapshot_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1468
320
    const auto& release_snapshot_request = req.release_snapshot_req;
1469
1470
320
    LOG(INFO) << "get release snapshot task. signature=" << req.signature;
1471
1472
320
    const std::string& snapshot_path = release_snapshot_request.snapshot_path;
1473
320
    Status status = engine.snapshot_mgr()->release_snapshot(snapshot_path);
1474
320
    if (!status.ok()) {
1475
0
        LOG_WARNING("failed to release snapshot")
1476
0
                .tag("signature", req.signature)
1477
0
                .tag("snapshot_path", snapshot_path)
1478
0
                .error(status);
1479
320
    } else {
1480
320
        LOG_INFO("successfully release snapshot")
1481
320
                .tag("signature", req.signature)
1482
320
                .tag("snapshot_path", snapshot_path);
1483
320
    }
1484
1485
320
    TFinishTaskRequest finish_task_request;
1486
320
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1487
320
    finish_task_request.__set_task_type(req.task_type);
1488
320
    finish_task_request.__set_signature(req.signature);
1489
320
    finish_task_request.__set_task_status(status.to_thrift());
1490
1491
320
    finish_task(finish_task_request);
1492
320
    remove_task_info(req.task_type, req.signature);
1493
320
}
1494
1495
0
void release_snapshot_callback(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
1496
0
    const auto& release_snapshot_request = req.release_snapshot_req;
1497
1498
0
    LOG(INFO) << "get release snapshot task. signature=" << req.signature;
1499
1500
0
    Status status = engine.cloud_snapshot_mgr().release_snapshot(
1501
0
            release_snapshot_request.tablet_id, release_snapshot_request.is_job_completed);
1502
1503
0
    if (!status.ok()) {
1504
0
        LOG_WARNING("failed to release snapshot")
1505
0
                .tag("signature", req.signature)
1506
0
                .tag("tablet_id", release_snapshot_request.tablet_id)
1507
0
                .tag("is_job_completed", release_snapshot_request.is_job_completed)
1508
0
                .error(status);
1509
0
    } else {
1510
0
        LOG_INFO("successfully release snapshot")
1511
0
                .tag("signature", req.signature)
1512
0
                .tag("tablet_id", release_snapshot_request.tablet_id)
1513
0
                .tag("is_job_completed", release_snapshot_request.is_job_completed);
1514
0
    }
1515
1516
0
    TFinishTaskRequest finish_task_request;
1517
0
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1518
0
    finish_task_request.__set_task_type(req.task_type);
1519
0
    finish_task_request.__set_signature(req.signature);
1520
0
    finish_task_request.__set_task_status(status.to_thrift());
1521
1522
0
    finish_task(finish_task_request);
1523
0
    remove_task_info(req.task_type, req.signature);
1524
0
}
1525
1526
172
void move_dir_callback(StorageEngine& engine, ExecEnv* env, const TAgentTaskRequest& req) {
1527
172
    const auto& move_dir_req = req.move_dir_req;
1528
1529
172
    LOG(INFO) << "get move dir task. signature=" << req.signature
1530
172
              << ", job_id=" << move_dir_req.job_id;
1531
172
    Status status;
1532
172
    auto tablet = engine.tablet_manager()->get_tablet(move_dir_req.tablet_id);
1533
172
    if (tablet == nullptr) {
1534
0
        status = Status::InvalidArgument("Could not find tablet");
1535
172
    } else {
1536
172
        SnapshotLoader loader(engine, env, move_dir_req.job_id, move_dir_req.tablet_id);
1537
172
        SCOPED_ATTACH_TASK(loader.resource_ctx());
1538
172
        status = loader.move(move_dir_req.src, tablet, true);
1539
172
    }
1540
1541
172
    if (!status.ok()) {
1542
0
        LOG_WARNING("failed to move dir")
1543
0
                .tag("signature", req.signature)
1544
0
                .tag("job_id", move_dir_req.job_id)
1545
0
                .tag("tablet_id", move_dir_req.tablet_id)
1546
0
                .tag("src", move_dir_req.src)
1547
0
                .error(status);
1548
172
    } else {
1549
172
        LOG_INFO("successfully move dir")
1550
172
                .tag("signature", req.signature)
1551
172
                .tag("job_id", move_dir_req.job_id)
1552
172
                .tag("tablet_id", move_dir_req.tablet_id)
1553
172
                .tag("src", move_dir_req.src);
1554
172
    }
1555
1556
172
    TFinishTaskRequest finish_task_request;
1557
172
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1558
172
    finish_task_request.__set_task_type(req.task_type);
1559
172
    finish_task_request.__set_signature(req.signature);
1560
172
    finish_task_request.__set_task_status(status.to_thrift());
1561
1562
172
    finish_task(finish_task_request);
1563
172
    remove_task_info(req.task_type, req.signature);
1564
172
}
1565
1566
0
void move_dir_callback(CloudStorageEngine& engine, ExecEnv* env, const TAgentTaskRequest& req) {
1567
0
    const auto& move_dir_req = req.move_dir_req;
1568
1569
0
    LOG(INFO) << "get move dir task. signature=" << req.signature
1570
0
              << ", job_id=" << move_dir_req.job_id;
1571
1572
0
    Status status = engine.cloud_snapshot_mgr().commit_snapshot(move_dir_req.tablet_id);
1573
0
    if (!status.ok()) {
1574
0
        LOG_WARNING("failed to move dir")
1575
0
                .tag("signature", req.signature)
1576
0
                .tag("job_id", move_dir_req.job_id)
1577
0
                .tag("tablet_id", move_dir_req.tablet_id)
1578
0
                .error(status);
1579
0
    } else {
1580
0
        LOG_INFO("successfully move dir")
1581
0
                .tag("signature", req.signature)
1582
0
                .tag("job_id", move_dir_req.job_id)
1583
0
                .tag("tablet_id", move_dir_req.tablet_id);
1584
0
    }
1585
1586
0
    TFinishTaskRequest finish_task_request;
1587
0
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1588
0
    finish_task_request.__set_task_type(req.task_type);
1589
0
    finish_task_request.__set_signature(req.signature);
1590
0
    finish_task_request.__set_task_status(status.to_thrift());
1591
1592
0
    finish_task(finish_task_request);
1593
0
    remove_task_info(req.task_type, req.signature);
1594
0
}
1595
1596
0
void submit_table_compaction_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1597
0
    const auto& compaction_req = req.compaction_req;
1598
1599
0
    LOG(INFO) << "get compaction task. signature=" << req.signature
1600
0
              << ", compaction_type=" << compaction_req.type
1601
0
              << ", tablet_id=" << compaction_req.tablet_id;
1602
1603
0
    CompactionType compaction_type;
1604
0
    if (compaction_req.type == "base") {
1605
0
        compaction_type = CompactionType::BASE_COMPACTION;
1606
0
    } else if (compaction_req.type == "cumulative") {
1607
0
        compaction_type = CompactionType::CUMULATIVE_COMPACTION;
1608
0
    } else if (compaction_req.type == "full") {
1609
0
        compaction_type = CompactionType::FULL_COMPACTION;
1610
0
    } else {
1611
0
        LOG(WARNING) << "unknown compaction type: " << compaction_req.type
1612
0
                     << ", tablet_id=" << compaction_req.tablet_id;
1613
0
        return;
1614
0
    }
1615
1616
0
    auto tablet_ptr = engine.tablet_manager()->get_tablet(compaction_req.tablet_id);
1617
0
    if (tablet_ptr == nullptr) {
1618
0
        LOG(WARNING) << "tablet not found. tablet_id=" << compaction_req.tablet_id;
1619
0
        return;
1620
0
    }
1621
1622
0
    if (compaction_type == CompactionType::FULL_COMPACTION) {
1623
        // Full compaction goes through the dedicated threadpool path (align with
1624
        // compaction_action.cpp _handle_run_compaction). `force=false` keeps the
1625
        // admission under permit limiter, matching the HTTP API default.
1626
0
        tablet_ptr->set_last_full_compaction_schedule_time(UnixMillis());
1627
0
        Status status = engine.submit_compaction_task(tablet_ptr, CompactionType::FULL_COMPACTION,
1628
0
                                                      /*force=*/false, /*eager=*/true,
1629
0
                                                      /*trigger_method=*/1);
1630
0
        if (!status.ok()) {
1631
0
            LOG(WARNING) << "failed to submit full compaction task. tablet_id="
1632
0
                         << tablet_ptr->tablet_id() << ", error=" << status;
1633
0
        }
1634
0
        return;
1635
0
    }
1636
1637
    // base / cumulative
1638
0
    auto* data_dir = tablet_ptr->data_dir();
1639
0
    if (!tablet_ptr->can_do_compaction(data_dir->path_hash(), compaction_type)) {
1640
0
        LOG(WARNING) << "could not do compaction. tablet_id=" << tablet_ptr->tablet_id()
1641
0
                     << ", compaction_type=" << compaction_type;
1642
0
        return;
1643
0
    }
1644
1645
0
    Status status = engine.submit_compaction_task(tablet_ptr, compaction_type, false);
1646
0
    if (!status.ok()) {
1647
0
        LOG(WARNING) << "failed to submit table compaction task. error=" << status;
1648
0
    }
1649
0
}
1650
1651
void cloud_submit_table_compaction_callback(CloudStorageEngine& engine,
1652
3
                                            const TAgentTaskRequest& req) {
1653
3
    const auto& compaction_req = req.compaction_req;
1654
1655
3
    LOG(INFO) << "get cloud compaction task. signature=" << req.signature
1656
3
              << ", compaction_type=" << compaction_req.type
1657
3
              << ", tablet_id=" << compaction_req.tablet_id;
1658
1659
3
    CompactionType compaction_type;
1660
3
    if (compaction_req.type == "base") {
1661
1
        compaction_type = CompactionType::BASE_COMPACTION;
1662
2
    } else if (compaction_req.type == "cumulative") {
1663
1
        compaction_type = CompactionType::CUMULATIVE_COMPACTION;
1664
1
    } else if (compaction_req.type == "full") {
1665
1
        compaction_type = CompactionType::FULL_COMPACTION;
1666
1
    } else {
1667
0
        LOG(WARNING) << "unknown cloud compaction type: " << compaction_req.type
1668
0
                     << ", tablet_id=" << compaction_req.tablet_id;
1669
0
        return;
1670
0
    }
1671
1672
    // Mirror cloud_compaction_action::_handle_run_compaction: base/cumu needs the
1673
    // delete bitmap synced eagerly, full does not (FullCompaction re-syncs itself).
1674
3
    bool sync_delete_bitmap = compaction_type != CompactionType::FULL_COMPACTION;
1675
3
    auto tablet_res = engine.tablet_mgr().get_tablet(compaction_req.tablet_id,
1676
3
                                                     /*warmup_data=*/false, sync_delete_bitmap);
1677
3
    if (!tablet_res.has_value()) {
1678
0
        LOG(WARNING) << "failed to get cloud tablet. tablet_id=" << compaction_req.tablet_id
1679
0
                     << ", error=" << tablet_res.error();
1680
0
        return;
1681
0
    }
1682
3
    CloudTabletSPtr tablet = std::move(tablet_res).value();
1683
3
    if (tablet == nullptr) {
1684
0
        LOG(WARNING) << "cloud tablet not found. tablet_id=" << compaction_req.tablet_id;
1685
0
        return;
1686
0
    }
1687
1688
3
    switch (compaction_type) {
1689
1
    case CompactionType::BASE_COMPACTION:
1690
1
        tablet->set_last_base_compaction_schedule_time(UnixMillis());
1691
1
        break;
1692
1
    case CompactionType::CUMULATIVE_COMPACTION:
1693
1
        tablet->set_last_cumu_compaction_schedule_time(UnixMillis());
1694
1
        break;
1695
1
    case CompactionType::FULL_COMPACTION:
1696
1
        tablet->set_last_full_compaction_schedule_time(UnixMillis());
1697
1
        break;
1698
0
    default:
1699
0
        break;
1700
3
    }
1701
1702
3
    Status status = engine.submit_compaction_task(tablet, compaction_type,
1703
3
                                                  /*trigger_method=*/1);
1704
3
    if (!status.ok()) {
1705
1
        LOG(WARNING) << "failed to submit cloud compaction task. tablet_id=" << tablet->tablet_id()
1706
1
                     << ", type=" << compaction_req.type << ", error=" << status;
1707
1
    }
1708
3
}
1709
1710
namespace {
1711
1712
33
void update_s3_resource(const TStorageResource& param, io::RemoteFileSystemSPtr existed_fs) {
1713
33
    Status st;
1714
33
    io::RemoteFileSystemSPtr fs;
1715
1716
33
    if (!existed_fs) {
1717
        // No such FS instance on BE
1718
33
        auto res = io::S3FileSystem::create(S3Conf::get_s3_conf(param.s3_storage_param),
1719
33
                                            std::to_string(param.id));
1720
33
        if (!res.has_value()) {
1721
9
            st = std::move(res).error();
1722
24
        } else {
1723
24
            fs = std::move(res).value();
1724
24
        }
1725
33
    } else {
1726
0
        DCHECK_EQ(existed_fs->type(), io::FileSystemType::S3) << param.id << ' ' << param.name;
1727
0
        auto client = static_cast<io::S3FileSystem*>(existed_fs.get())->client_holder();
1728
0
        auto new_s3_conf = S3Conf::get_s3_conf(param.s3_storage_param);
1729
0
        S3ClientConf conf = std::move(new_s3_conf.client_conf);
1730
0
        st = client->reset(conf);
1731
0
        fs = std::move(existed_fs);
1732
0
    }
1733
1734
33
    if (!st.ok()) {
1735
9
        LOG(WARNING) << "update s3 resource failed: " << st;
1736
24
    } else {
1737
24
        LOG_INFO("successfully update s3 resource")
1738
24
                .tag("resource_id", param.id)
1739
24
                .tag("resource_name", param.name);
1740
24
        put_storage_resource(param.id, {std::move(fs)}, param.version);
1741
24
    }
1742
33
}
1743
1744
38
void update_hdfs_resource(const TStorageResource& param, io::RemoteFileSystemSPtr existed_fs) {
1745
38
    Status st;
1746
38
    io::RemoteFileSystemSPtr fs;
1747
38
    std::string root_path =
1748
38
            param.hdfs_storage_param.__isset.root_path ? param.hdfs_storage_param.root_path : "";
1749
1750
38
    if (!existed_fs) {
1751
        // No such FS instance on BE
1752
38
        auto res = io::HdfsFileSystem::create(
1753
38
                param.hdfs_storage_param, param.hdfs_storage_param.fs_name,
1754
38
                std::to_string(param.id), nullptr, std::move(root_path));
1755
38
        if (!res.has_value()) {
1756
18
            st = std::move(res).error();
1757
20
        } else {
1758
20
            fs = std::move(res).value();
1759
20
        }
1760
1761
38
    } else {
1762
0
        DCHECK_EQ(existed_fs->type(), io::FileSystemType::HDFS) << param.id << ' ' << param.name;
1763
        // TODO(plat1ko): update hdfs conf
1764
0
        fs = std::move(existed_fs);
1765
0
    }
1766
1767
38
    if (!st.ok()) {
1768
18
        LOG(WARNING) << "update hdfs resource failed: " << st;
1769
20
    } else {
1770
20
        LOG_INFO("successfully update hdfs resource")
1771
20
                .tag("resource_id", param.id)
1772
20
                .tag("resource_name", param.name)
1773
20
                .tag("root_path", fs->root_path().string());
1774
20
        put_storage_resource(param.id, {std::move(fs)}, param.version);
1775
20
    }
1776
38
}
1777
1778
} // namespace
1779
1780
11
void push_storage_policy_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1781
11
    const auto& push_storage_policy_req = req.push_storage_policy_req;
1782
    // refresh resource
1783
71
    for (auto&& param : push_storage_policy_req.resource) {
1784
71
        io::RemoteFileSystemSPtr fs;
1785
71
        if (auto existed_resource = get_storage_resource(param.id); existed_resource) {
1786
0
            if (existed_resource->second >= param.version) {
1787
                // Stale request, ignore
1788
0
                continue;
1789
0
            }
1790
1791
0
            fs = std::move(existed_resource->first.fs);
1792
0
        }
1793
1794
71
        if (param.__isset.s3_storage_param) {
1795
33
            update_s3_resource(param, std::move(fs));
1796
38
        } else if (param.__isset.hdfs_storage_param) {
1797
38
            update_hdfs_resource(param, std::move(fs));
1798
38
        } else {
1799
0
            LOG(WARNING) << "unknown resource=" << param;
1800
0
        }
1801
71
    }
1802
    // drop storage policy
1803
11
    for (auto policy_id : push_storage_policy_req.dropped_storage_policy) {
1804
0
        delete_storage_policy(policy_id);
1805
0
    }
1806
    // refresh storage policy
1807
24
    for (auto&& storage_policy : push_storage_policy_req.storage_policy) {
1808
24
        auto existed_storage_policy = get_storage_policy(storage_policy.id);
1809
24
        if (existed_storage_policy == nullptr ||
1810
24
            existed_storage_policy->version < storage_policy.version) {
1811
24
            auto storage_policy1 = std::make_shared<StoragePolicy>();
1812
24
            storage_policy1->name = storage_policy.name;
1813
24
            storage_policy1->version = storage_policy.version;
1814
24
            storage_policy1->cooldown_datetime = storage_policy.cooldown_datetime;
1815
24
            storage_policy1->cooldown_ttl = storage_policy.cooldown_ttl;
1816
24
            storage_policy1->resource_id = storage_policy.resource_id;
1817
24
            LOG_INFO("successfully update storage policy")
1818
24
                    .tag("storage_policy_id", storage_policy.id)
1819
24
                    .tag("storage_policy", storage_policy1->to_string());
1820
24
            put_storage_policy(storage_policy.id, std::move(storage_policy1));
1821
24
        }
1822
24
    }
1823
11
}
1824
1825
17
void push_index_policy_callback(const TAgentTaskRequest& req) {
1826
17
    const auto& request = req.push_index_policy_req;
1827
17
    doris::ExecEnv::GetInstance()->index_policy_mgr()->apply_policy_changes(
1828
17
            request.index_policys, request.dropped_index_policys);
1829
17
}
1830
1831
2
void push_cooldown_conf_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1832
2
    const auto& push_cooldown_conf_req = req.push_cooldown_conf;
1833
326
    for (const auto& cooldown_conf : push_cooldown_conf_req.cooldown_confs) {
1834
326
        int64_t tablet_id = cooldown_conf.tablet_id;
1835
326
        TabletSharedPtr tablet = engine.tablet_manager()->get_tablet(tablet_id);
1836
326
        if (tablet == nullptr) {
1837
0
            LOG(WARNING) << "failed to get tablet. tablet_id=" << tablet_id;
1838
0
            continue;
1839
0
        }
1840
326
        if (tablet->update_cooldown_conf(cooldown_conf.cooldown_term,
1841
326
                                         cooldown_conf.cooldown_replica_id) &&
1842
326
            cooldown_conf.cooldown_replica_id == tablet->replica_id() &&
1843
326
            tablet->tablet_meta()->cooldown_meta_id().initialized()) {
1844
2
            Tablet::async_write_cooldown_meta(tablet);
1845
2
        }
1846
326
    }
1847
2
}
1848
1849
8.10k
void create_tablet_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1850
8.10k
    const auto& create_tablet_req = req.create_tablet_req;
1851
8.10k
    RuntimeProfile runtime_profile("CreateTablet");
1852
8.10k
    RuntimeProfile* profile = &runtime_profile;
1853
8.10k
    MonotonicStopWatch watch;
1854
8.10k
    watch.start();
1855
8.10k
    Defer defer = [&] {
1856
8.09k
        auto elapsed_time = static_cast<double>(watch.elapsed_time());
1857
8.09k
        if (elapsed_time / 1e9 > config::agent_task_trace_threshold_sec) {
1858
0
#include "common/compile_check_avoid_begin.h"
1859
0
            COUNTER_UPDATE(profile->total_time_counter(), elapsed_time);
1860
0
#include "common/compile_check_avoid_end.h"
1861
0
            std::stringstream ss;
1862
0
            profile->pretty_print(&ss);
1863
0
            LOG(WARNING) << "create tablet cost(s) " << elapsed_time / 1e9 << std::endl << ss.str();
1864
0
        }
1865
8.09k
    };
1866
8.10k
    DorisMetrics::instance()->create_tablet_requests_total->increment(1);
1867
8.10k
    VLOG_NOTICE << "start to create tablet " << create_tablet_req.tablet_id;
1868
1869
8.10k
    std::vector<TTabletInfo> finish_tablet_infos;
1870
8.10k
    VLOG_NOTICE << "create tablet: " << create_tablet_req;
1871
8.10k
    Status status = engine.create_tablet(create_tablet_req, profile);
1872
8.10k
    if (!status.ok()) {
1873
0
        DorisMetrics::instance()->create_tablet_requests_failed->increment(1);
1874
0
        LOG_WARNING("failed to create tablet, reason={}", status.to_string())
1875
0
                .tag("signature", req.signature)
1876
0
                .tag("tablet_id", create_tablet_req.tablet_id)
1877
0
                .error(status);
1878
8.10k
    } else {
1879
8.10k
        increase_report_version();
1880
        // get path hash of the created tablet
1881
8.10k
        TabletSharedPtr tablet;
1882
8.10k
        {
1883
8.10k
            SCOPED_TIMER(ADD_TIMER(profile, "GetTablet"));
1884
8.10k
            tablet = engine.tablet_manager()->get_tablet(create_tablet_req.tablet_id);
1885
8.10k
        }
1886
8.10k
        DCHECK(tablet != nullptr);
1887
8.10k
        TTabletInfo tablet_info;
1888
8.10k
        tablet_info.tablet_id = tablet->tablet_id();
1889
8.10k
        tablet_info.schema_hash = tablet->schema_hash();
1890
8.10k
        tablet_info.version = create_tablet_req.version;
1891
        // Useless but it is a required field in TTabletInfo
1892
8.10k
        tablet_info.version_hash = 0;
1893
8.10k
        tablet_info.row_count = 0;
1894
8.10k
        tablet_info.data_size = 0;
1895
8.10k
        tablet_info.__set_path_hash(tablet->data_dir()->path_hash());
1896
8.10k
        tablet_info.__set_replica_id(tablet->replica_id());
1897
8.10k
        finish_tablet_infos.push_back(tablet_info);
1898
8.10k
        LOG_INFO("successfully create tablet")
1899
8.10k
                .tag("signature", req.signature)
1900
8.10k
                .tag("tablet_id", create_tablet_req.tablet_id);
1901
8.10k
    }
1902
8.10k
    TFinishTaskRequest finish_task_request;
1903
8.10k
    finish_task_request.__set_finish_tablet_infos(finish_tablet_infos);
1904
8.10k
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1905
8.10k
    finish_task_request.__set_report_version(s_report_version);
1906
8.10k
    finish_task_request.__set_task_type(req.task_type);
1907
8.10k
    finish_task_request.__set_signature(req.signature);
1908
8.10k
    finish_task_request.__set_task_status(status.to_thrift());
1909
8.10k
    finish_task(finish_task_request);
1910
8.10k
    remove_task_info(req.task_type, req.signature);
1911
8.10k
}
1912
1913
5.71k
void drop_tablet_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
1914
5.71k
    const auto& drop_tablet_req = req.drop_tablet_req;
1915
5.71k
    Status status;
1916
5.71k
    auto dropped_tablet = engine.tablet_manager()->get_tablet(drop_tablet_req.tablet_id, false);
1917
5.71k
    if (dropped_tablet != nullptr) {
1918
5.71k
        status = engine.tablet_manager()->drop_tablet(drop_tablet_req.tablet_id,
1919
5.71k
                                                      drop_tablet_req.replica_id,
1920
5.71k
                                                      drop_tablet_req.is_drop_table_or_partition);
1921
5.71k
    } else {
1922
0
        status = Status::NotFound("could not find tablet {}", drop_tablet_req.tablet_id);
1923
0
    }
1924
5.71k
    if (status.ok()) {
1925
        // if tablet is dropped by fe, then the related txn should also be removed
1926
5.71k
        engine.txn_manager()->force_rollback_tablet_related_txns(
1927
5.71k
                dropped_tablet->data_dir()->get_meta(), drop_tablet_req.tablet_id,
1928
5.71k
                dropped_tablet->tablet_uid());
1929
5.71k
        LOG_INFO("successfully drop tablet")
1930
5.71k
                .tag("signature", req.signature)
1931
5.71k
                .tag("tablet_id", drop_tablet_req.tablet_id)
1932
5.71k
                .tag("replica_id", drop_tablet_req.replica_id);
1933
5.71k
    } else {
1934
0
        LOG_WARNING("failed to drop tablet")
1935
0
                .tag("signature", req.signature)
1936
0
                .tag("tablet_id", drop_tablet_req.tablet_id)
1937
0
                .tag("replica_id", drop_tablet_req.replica_id)
1938
0
                .error(status);
1939
0
    }
1940
1941
5.71k
    TFinishTaskRequest finish_task_request;
1942
5.71k
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
1943
5.71k
    finish_task_request.__set_task_type(req.task_type);
1944
5.71k
    finish_task_request.__set_signature(req.signature);
1945
5.71k
    finish_task_request.__set_task_status(status.to_thrift());
1946
1947
5.71k
    TTabletInfo tablet_info;
1948
5.71k
    tablet_info.tablet_id = drop_tablet_req.tablet_id;
1949
5.71k
    tablet_info.schema_hash = drop_tablet_req.schema_hash;
1950
5.71k
    tablet_info.version = 0;
1951
    // Useless but it is a required field in TTabletInfo
1952
5.71k
    tablet_info.version_hash = 0;
1953
5.71k
    tablet_info.row_count = 0;
1954
5.71k
    tablet_info.data_size = 0;
1955
1956
5.71k
    finish_task_request.__set_finish_tablet_infos({tablet_info});
1957
5.71k
    LOG_INFO("successfully drop tablet")
1958
5.71k
            .tag("signature", req.signature)
1959
5.71k
            .tag("tablet_id", drop_tablet_req.tablet_id);
1960
1961
5.71k
    finish_task(finish_task_request);
1962
5.71k
    remove_task_info(req.task_type, req.signature);
1963
5.71k
}
1964
1965
0
void drop_tablet_callback(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
1966
0
    const auto& drop_tablet_req = req.drop_tablet_req;
1967
    // here drop_tablet_req.tablet_id is the signature of the task, see DropReplicaTask in fe
1968
0
    Defer defer = [&] { remove_task_info(req.task_type, req.signature); };
1969
0
    DBUG_EXECUTE_IF("WorkPoolCloudDropTablet.drop_tablet_callback.failed", {
1970
0
        LOG_WARNING("WorkPoolCloudDropTablet.drop_tablet_callback.failed")
1971
0
                .tag("tablet_id", drop_tablet_req.tablet_id);
1972
0
        return;
1973
0
    });
1974
0
    MonotonicStopWatch watch;
1975
0
    watch.start();
1976
0
    auto weak_tablets = engine.tablet_mgr().get_weak_tablets();
1977
0
    std::ostringstream rowset_ids_stream;
1978
0
    bool found = false;
1979
0
    for (auto& weak_tablet : weak_tablets) {
1980
0
        auto tablet = weak_tablet.lock();
1981
0
        if (tablet == nullptr) {
1982
0
            continue;
1983
0
        }
1984
0
        if (tablet->tablet_id() != drop_tablet_req.tablet_id) {
1985
0
            continue;
1986
0
        }
1987
0
        found = true;
1988
0
        auto clean_rowsets = tablet->get_snapshot_rowset(true);
1989
        // Get first 10 rowset IDs as comma-separated string, just for log
1990
0
        int count = 0;
1991
0
        for (const auto& rowset : clean_rowsets) {
1992
0
            if (count >= 10) break;
1993
0
            if (count > 0) {
1994
0
                rowset_ids_stream << ",";
1995
0
            }
1996
0
            rowset_ids_stream << rowset->rowset_id().to_string();
1997
0
            count++;
1998
0
        }
1999
2000
0
        CloudTablet::recycle_cached_data(clean_rowsets);
2001
0
        break;
2002
0
    }
2003
2004
0
    if (!found) {
2005
0
        LOG(WARNING) << "tablet not found when dropping tablet_id=" << drop_tablet_req.tablet_id
2006
0
                     << ", cost " << static_cast<double>(watch.elapsed_time()) / 1e9 << "(s)";
2007
0
        return;
2008
0
    }
2009
2010
0
    engine.tablet_mgr().erase_tablet(drop_tablet_req.tablet_id);
2011
0
    LOG(INFO) << "drop cloud tablet_id=" << drop_tablet_req.tablet_id
2012
0
              << " and clean file cache first 10 rowsets {" << rowset_ids_stream.str() << "}, cost "
2013
0
              << static_cast<double>(watch.elapsed_time()) / 1e9 << "(s)";
2014
0
}
2015
2016
22
void push_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2017
22
    const auto& push_req = req.push_req;
2018
2019
22
    LOG(INFO) << "get push task. signature=" << req.signature
2020
22
              << " push_type=" << push_req.push_type;
2021
22
    std::vector<TTabletInfo> tablet_infos;
2022
2023
    // exist a path task_worker_pool <- agent_server <- backend_service <- BackendService
2024
    // use the arg BackendService_submit_tasks_args.tasks is not const
2025
    // and push_req will be modify, so modify is ok
2026
22
    EngineBatchLoadTask engine_task(engine, const_cast<TPushReq&>(push_req), &tablet_infos);
2027
22
    SCOPED_ATTACH_TASK(engine_task.mem_tracker());
2028
22
    auto status = engine_task.execute();
2029
2030
    // Return result to fe
2031
22
    TFinishTaskRequest finish_task_request;
2032
22
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2033
22
    finish_task_request.__set_task_type(req.task_type);
2034
22
    finish_task_request.__set_signature(req.signature);
2035
22
    if (push_req.push_type == TPushType::DELETE) {
2036
22
        finish_task_request.__set_request_version(push_req.version);
2037
22
    }
2038
2039
22
    if (status.ok()) {
2040
22
        LOG_INFO("successfully execute push task")
2041
22
                .tag("signature", req.signature)
2042
22
                .tag("tablet_id", push_req.tablet_id)
2043
22
                .tag("push_type", push_req.push_type);
2044
22
        increase_report_version();
2045
22
        finish_task_request.__set_finish_tablet_infos(tablet_infos);
2046
22
    } else {
2047
0
        LOG_WARNING("failed to execute push task")
2048
0
                .tag("signature", req.signature)
2049
0
                .tag("tablet_id", push_req.tablet_id)
2050
0
                .tag("push_type", push_req.push_type)
2051
0
                .error(status);
2052
0
    }
2053
22
    finish_task_request.__set_task_status(status.to_thrift());
2054
22
    finish_task_request.__set_report_version(s_report_version);
2055
2056
22
    finish_task(finish_task_request);
2057
22
    remove_task_info(req.task_type, req.signature);
2058
22
}
2059
2060
3.18k
void cloud_push_callback(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
2061
3.18k
    const auto& push_req = req.push_req;
2062
2063
3.18k
    LOG(INFO) << "get push task. signature=" << req.signature
2064
3.18k
              << " push_type=" << push_req.push_type;
2065
2066
    // Return result to fe
2067
3.18k
    TFinishTaskRequest finish_task_request;
2068
3.18k
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2069
3.18k
    finish_task_request.__set_task_type(req.task_type);
2070
3.18k
    finish_task_request.__set_signature(req.signature);
2071
2072
    // Only support DELETE in cloud mode now
2073
3.18k
    if (push_req.push_type != TPushType::DELETE) {
2074
0
        finish_task_request.__set_task_status(
2075
0
                Status::NotSupported("push_type {} not is supported",
2076
0
                                     std::to_string(push_req.push_type))
2077
0
                        .to_thrift());
2078
0
        return;
2079
0
    }
2080
2081
3.18k
    finish_task_request.__set_request_version(push_req.version);
2082
2083
3.18k
    DorisMetrics::instance()->delete_requests_total->increment(1);
2084
3.18k
    auto st = CloudDeleteTask::execute(engine, req.push_req);
2085
3.18k
    if (st.ok()) {
2086
3.17k
        LOG_INFO("successfully execute push task")
2087
3.17k
                .tag("signature", req.signature)
2088
3.17k
                .tag("tablet_id", push_req.tablet_id)
2089
3.17k
                .tag("push_type", push_req.push_type);
2090
3.17k
        increase_report_version();
2091
3.17k
        auto& tablet_info = finish_task_request.finish_tablet_infos.emplace_back();
2092
        // Just need tablet_id
2093
3.17k
        tablet_info.tablet_id = push_req.tablet_id;
2094
3.17k
        finish_task_request.__isset.finish_tablet_infos = true;
2095
3.17k
    } else {
2096
10
        DorisMetrics::instance()->delete_requests_failed->increment(1);
2097
10
        LOG_WARNING("failed to execute push task")
2098
10
                .tag("signature", req.signature)
2099
10
                .tag("tablet_id", push_req.tablet_id)
2100
10
                .tag("push_type", push_req.push_type)
2101
10
                .error(st);
2102
10
    }
2103
2104
3.18k
    finish_task_request.__set_task_status(st.to_thrift());
2105
3.18k
    finish_task_request.__set_report_version(s_report_version);
2106
2107
3.18k
    finish_task(finish_task_request);
2108
3.18k
    remove_task_info(req.task_type, req.signature);
2109
3.18k
}
2110
2111
PublishVersionWorkerPool::PublishVersionWorkerPool(StorageEngine& engine)
2112
6
        : TaskWorkerPool("PUBLISH_VERSION", config::publish_version_worker_count,
2113
6.12k
                         [this](const TAgentTaskRequest& task) { publish_version_callback(task); }),
2114
6
          _engine(engine) {}
2115
2116
PublishVersionWorkerPool::~PublishVersionWorkerPool() = default;
2117
2118
6.13k
void PublishVersionWorkerPool::publish_version_callback(const TAgentTaskRequest& req) {
2119
6.13k
    const auto& publish_version_req = req.publish_version_req;
2120
6.13k
    DorisMetrics::instance()->publish_task_request_total->increment(1);
2121
6.13k
    VLOG_NOTICE << "get publish version task. signature=" << req.signature;
2122
2123
6.13k
    std::set<TTabletId> error_tablet_ids;
2124
6.13k
    std::map<TTabletId, TVersion> succ_tablets;
2125
    // partition_id, tablet_id, publish_version, commit_tso
2126
6.13k
    std::vector<DiscontinuousVersionTablet> discontinuous_version_tablets;
2127
6.13k
    std::map<TTableId, std::map<TTabletId, int64_t>> table_id_to_tablet_id_to_num_delta_rows;
2128
6.13k
    uint32_t retry_time = 0;
2129
6.13k
    Status status;
2130
6.13k
    constexpr uint32_t PUBLISH_VERSION_MAX_RETRY = 3;
2131
6.13k
    while (retry_time < PUBLISH_VERSION_MAX_RETRY) {
2132
6.13k
        succ_tablets.clear();
2133
6.13k
        error_tablet_ids.clear();
2134
6.13k
        table_id_to_tablet_id_to_num_delta_rows.clear();
2135
6.13k
        EnginePublishVersionTask engine_task(_engine, publish_version_req, &error_tablet_ids,
2136
6.13k
                                             &succ_tablets, &discontinuous_version_tablets,
2137
6.13k
                                             &table_id_to_tablet_id_to_num_delta_rows);
2138
6.13k
        SCOPED_ATTACH_TASK(engine_task.mem_tracker());
2139
6.13k
        status = engine_task.execute();
2140
6.13k
        if (status.ok()) {
2141
6.12k
            break;
2142
6.12k
        }
2143
2144
6
        if (status.is<PUBLISH_VERSION_NOT_CONTINUOUS>()) {
2145
            // there are too many missing versions, it has been be added to async
2146
            // publish task, so no need to retry here.
2147
6
            if (discontinuous_version_tablets.empty()) {
2148
0
                break;
2149
0
            }
2150
6
            LOG_EVERY_SECOND(INFO) << "wait for previous publish version task to be done, "
2151
4
                                   << "transaction_id: " << publish_version_req.transaction_id;
2152
2153
6
            int64_t time_elapsed = time(nullptr) - req.recv_time;
2154
6
            if (time_elapsed > config::publish_version_task_timeout_s) {
2155
0
                LOG(INFO) << "task elapsed " << time_elapsed
2156
0
                          << " seconds since it is inserted to queue, it is timeout";
2157
0
                break;
2158
0
            }
2159
2160
            // Version not continuous, put to queue and wait pre version publish task execute
2161
6
            PUBLISH_VERSION_count << 1;
2162
6
            auto st = _thread_pool->submit_func([this, req] {
2163
6
                this->publish_version_callback(req);
2164
6
                PUBLISH_VERSION_count << -1;
2165
6
            });
2166
6
            if (!st.ok()) [[unlikely]] {
2167
0
                PUBLISH_VERSION_count << -1;
2168
0
                status = std::move(st);
2169
6
            } else {
2170
6
                return;
2171
6
            }
2172
6
        }
2173
2174
0
        LOG_WARNING("failed to publish version")
2175
0
                .tag("transaction_id", publish_version_req.transaction_id)
2176
0
                .tag("error_tablets_num", error_tablet_ids.size())
2177
0
                .tag("retry_time", retry_time)
2178
0
                .error(status);
2179
0
        ++retry_time;
2180
0
    }
2181
2182
6.12k
    for (auto& item : discontinuous_version_tablets) {
2183
0
        _engine.add_async_publish_task(item.partition_id, item.tablet_id, item.publish_version,
2184
0
                                       publish_version_req.transaction_id, false, item.commit_tso);
2185
0
    }
2186
6.12k
    TFinishTaskRequest finish_task_request;
2187
6.12k
    if (!status.ok()) [[unlikely]] {
2188
0
        DorisMetrics::instance()->publish_task_failed_total->increment(1);
2189
        // if publish failed, return failed, FE will ignore this error and
2190
        // check error tablet ids and FE will also republish this task
2191
0
        LOG_WARNING("failed to publish version")
2192
0
                .tag("signature", req.signature)
2193
0
                .tag("transaction_id", publish_version_req.transaction_id)
2194
0
                .tag("error_tablets_num", error_tablet_ids.size())
2195
0
                .error(status);
2196
6.12k
    } else {
2197
6.12k
        if (!config::disable_auto_compaction &&
2198
6.12k
            (!config::enable_compaction_pause_on_high_memory ||
2199
6.12k
             !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE))) {
2200
47.2k
            for (auto [tablet_id, _] : succ_tablets) {
2201
47.2k
                TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
2202
47.2k
                if (tablet != nullptr) {
2203
47.2k
                    if (!tablet->tablet_meta()->tablet_schema()->disable_auto_compaction()) {
2204
47.2k
                        tablet->published_count.fetch_add(1);
2205
47.2k
                        int64_t published_count = tablet->published_count.load();
2206
47.2k
                        int32_t max_version_config = tablet->max_version_config();
2207
47.2k
                        if (tablet->exceed_version_limit(
2208
47.2k
                                    max_version_config *
2209
47.2k
                                    config::load_trigger_compaction_version_percent / 100) &&
2210
47.2k
                            published_count % 20 == 0) {
2211
0
                            auto st = _engine.submit_compaction_task(
2212
0
                                    tablet, CompactionType::CUMULATIVE_COMPACTION, true, false);
2213
0
                            if (!st.ok()) [[unlikely]] {
2214
0
                                LOG(WARNING) << "trigger compaction failed, tablet_id=" << tablet_id
2215
0
                                             << ", published=" << published_count << " : " << st;
2216
0
                            } else {
2217
0
                                LOG(INFO) << "trigger compaction succ, tablet_id:" << tablet_id
2218
0
                                          << ", published:" << published_count;
2219
0
                            }
2220
0
                        }
2221
47.2k
                    }
2222
47.2k
                } else {
2223
0
                    LOG(WARNING) << "trigger compaction failed, tablet_id:" << tablet_id;
2224
0
                }
2225
47.2k
            }
2226
6.12k
        }
2227
6.12k
        int64_t cost_second = time(nullptr) - req.recv_time;
2228
6.12k
        g_publish_version_latency << cost_second;
2229
6.12k
        LOG_INFO("successfully publish version")
2230
6.12k
                .tag("signature", req.signature)
2231
6.12k
                .tag("transaction_id", publish_version_req.transaction_id)
2232
6.12k
                .tag("tablets_num", succ_tablets.size())
2233
6.12k
                .tag("cost(s)", cost_second);
2234
6.12k
    }
2235
2236
6.12k
    status.to_thrift(&finish_task_request.task_status);
2237
6.12k
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2238
6.12k
    finish_task_request.__set_task_type(req.task_type);
2239
6.12k
    finish_task_request.__set_signature(req.signature);
2240
6.12k
    finish_task_request.__set_report_version(s_report_version);
2241
6.12k
    finish_task_request.__set_succ_tablets(succ_tablets);
2242
6.12k
    finish_task_request.__set_error_tablet_ids(
2243
6.12k
            std::vector<TTabletId>(error_tablet_ids.begin(), error_tablet_ids.end()));
2244
6.12k
    finish_task_request.__set_table_id_to_tablet_id_to_delta_num_rows(
2245
6.12k
            table_id_to_tablet_id_to_num_delta_rows);
2246
6.12k
    finish_task(finish_task_request);
2247
6.12k
    remove_task_info(req.task_type, req.signature);
2248
6.12k
}
2249
2250
16
void clear_transaction_task_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2251
16
    const auto& clear_transaction_task_req = req.clear_transaction_task_req;
2252
16
    LOG(INFO) << "get clear transaction task. signature=" << req.signature
2253
16
              << ", transaction_id=" << clear_transaction_task_req.transaction_id
2254
16
              << ", partition_id_size=" << clear_transaction_task_req.partition_id.size();
2255
2256
16
    Status status;
2257
2258
16
    if (clear_transaction_task_req.transaction_id > 0) {
2259
        // transaction_id should be greater than zero.
2260
        // If it is not greater than zero, no need to execute
2261
        // the following clear_transaction_task() function.
2262
16
        if (!clear_transaction_task_req.partition_id.empty()) {
2263
4
            engine.clear_transaction_task(clear_transaction_task_req.transaction_id,
2264
4
                                          clear_transaction_task_req.partition_id);
2265
12
        } else {
2266
12
            engine.clear_transaction_task(clear_transaction_task_req.transaction_id);
2267
12
        }
2268
16
        LOG(INFO) << "finish to clear transaction task. signature=" << req.signature
2269
16
                  << ", transaction_id=" << clear_transaction_task_req.transaction_id;
2270
16
    } else {
2271
0
        LOG(WARNING) << "invalid transaction id " << clear_transaction_task_req.transaction_id
2272
0
                     << ". signature= " << req.signature;
2273
0
    }
2274
2275
16
    TFinishTaskRequest finish_task_request;
2276
16
    finish_task_request.__set_task_status(status.to_thrift());
2277
16
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2278
16
    finish_task_request.__set_task_type(req.task_type);
2279
16
    finish_task_request.__set_signature(req.signature);
2280
2281
16
    finish_task(finish_task_request);
2282
16
    remove_task_info(req.task_type, req.signature);
2283
16
}
2284
2285
20
void alter_tablet_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2286
20
    int64_t signature = req.signature;
2287
20
    LOG(INFO) << "get alter table task, signature: " << signature;
2288
20
    bool is_task_timeout = false;
2289
20
    if (req.__isset.recv_time) {
2290
20
        int64_t time_elapsed = time(nullptr) - req.recv_time;
2291
20
        if (time_elapsed > config::report_task_interval_seconds * 20) {
2292
0
            LOG(INFO) << "task elapsed " << time_elapsed
2293
0
                      << " seconds since it is inserted to queue, it is timeout";
2294
0
            is_task_timeout = true;
2295
0
        }
2296
20
    }
2297
20
    if (!is_task_timeout) {
2298
20
        TFinishTaskRequest finish_task_request;
2299
20
        TTaskType::type task_type = req.task_type;
2300
20
        alter_tablet(engine, req, signature, task_type, &finish_task_request);
2301
20
        finish_task(finish_task_request);
2302
20
    }
2303
20
    doris::g_fragment_executing_count << -1;
2304
20
    int64_t now = duration_cast<std::chrono::milliseconds>(
2305
20
                          std::chrono::system_clock::now().time_since_epoch())
2306
20
                          .count();
2307
20
    g_fragment_last_active_time.set_value(now);
2308
20
    remove_task_info(req.task_type, req.signature);
2309
20
}
2310
2311
11.1k
void alter_cloud_tablet_callback(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
2312
11.1k
    int64_t signature = req.signature;
2313
11.1k
    LOG(INFO) << "get alter table task, signature: " << signature;
2314
11.1k
    bool is_task_timeout = false;
2315
11.1k
    if (req.__isset.recv_time) {
2316
11.1k
        int64_t time_elapsed = time(nullptr) - req.recv_time;
2317
11.1k
        if (time_elapsed > config::report_task_interval_seconds * 20) {
2318
0
            LOG(INFO) << "task elapsed " << time_elapsed
2319
0
                      << " seconds since it is inserted to queue, it is timeout";
2320
0
            is_task_timeout = true;
2321
0
        }
2322
11.1k
    }
2323
11.1k
    if (!is_task_timeout) {
2324
11.1k
        TFinishTaskRequest finish_task_request;
2325
11.1k
        TTaskType::type task_type = req.task_type;
2326
11.1k
        alter_cloud_tablet(engine, req, signature, task_type, &finish_task_request);
2327
11.1k
        finish_task(finish_task_request);
2328
11.1k
    }
2329
11.1k
    doris::g_fragment_executing_count << -1;
2330
11.1k
    int64_t now = duration_cast<std::chrono::milliseconds>(
2331
11.1k
                          std::chrono::system_clock::now().time_since_epoch())
2332
11.1k
                          .count();
2333
11.1k
    g_fragment_last_active_time.set_value(now);
2334
2335
    // Clean up alter_version before remove_task_info to avoid race:
2336
    // remove_task_info allows same-signature re-submit, whose pre_submit_callback
2337
    // would set alter_version, then this cleanup would wipe it.
2338
11.1k
    if (req.__isset.alter_tablet_req_v2) {
2339
11.1k
        const auto& alter_req = req.alter_tablet_req_v2;
2340
11.1k
        auto new_tablet = engine.tablet_mgr().get_tablet(alter_req.new_tablet_id);
2341
11.1k
        auto base_tablet = engine.tablet_mgr().get_tablet(alter_req.base_tablet_id);
2342
11.1k
        if (new_tablet.has_value()) {
2343
11.1k
            new_tablet.value()->set_alter_version(-1);
2344
11.1k
        }
2345
11.1k
        if (base_tablet.has_value()) {
2346
11.1k
            base_tablet.value()->set_alter_version(-1);
2347
11.1k
        }
2348
11.1k
    }
2349
2350
11.1k
    remove_task_info(req.task_type, req.signature);
2351
11.1k
}
2352
2353
11.1k
void set_alter_version_before_enqueue(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
2354
11.1k
    if (!req.__isset.alter_tablet_req_v2) {
2355
0
        return;
2356
0
    }
2357
11.1k
    const auto& alter_req = req.alter_tablet_req_v2;
2358
11.1k
    if (alter_req.alter_version <= 1) {
2359
5.71k
        return;
2360
5.71k
    }
2361
5.40k
    auto new_tablet = engine.tablet_mgr().get_tablet(alter_req.new_tablet_id);
2362
5.40k
    if (!new_tablet.has_value() || new_tablet.value()->tablet_state() == TABLET_RUNNING) {
2363
18
        return;
2364
18
    }
2365
5.39k
    auto base_tablet = engine.tablet_mgr().get_tablet(alter_req.base_tablet_id);
2366
5.39k
    if (!base_tablet.has_value()) {
2367
0
        return;
2368
0
    }
2369
5.39k
    new_tablet.value()->set_alter_version(alter_req.alter_version);
2370
5.39k
    base_tablet.value()->set_alter_version(alter_req.alter_version);
2371
5.39k
    LOG(INFO) << "set alter_version=" << alter_req.alter_version
2372
5.39k
              << " before enqueue, base_tablet=" << alter_req.base_tablet_id
2373
5.39k
              << ", new_tablet=" << alter_req.new_tablet_id;
2374
5.39k
}
2375
2376
0
void gc_binlog_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2377
0
    std::unordered_map<int64_t, int64_t> gc_tablet_infos;
2378
0
    if (!req.__isset.gc_binlog_req) {
2379
0
        LOG(WARNING) << "gc binlog task is not valid";
2380
0
        return;
2381
0
    }
2382
0
    if (!req.gc_binlog_req.__isset.tablet_gc_binlog_infos) {
2383
0
        LOG(WARNING) << "gc binlog task tablet_gc_binlog_infos is not valid";
2384
0
        return;
2385
0
    }
2386
2387
0
    const auto& tablet_gc_binlog_infos = req.gc_binlog_req.tablet_gc_binlog_infos;
2388
0
    for (auto&& tablet_info : tablet_gc_binlog_infos) {
2389
        // gc_tablet_infos.emplace(tablet_info.tablet_id, tablet_info.schema_hash);
2390
0
        gc_tablet_infos.emplace(tablet_info.tablet_id, tablet_info.version);
2391
0
    }
2392
2393
0
    engine.gc_binlogs(gc_tablet_infos);
2394
0
}
2395
2396
5.94k
void visible_version_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2397
5.94k
    const TVisibleVersionReq& visible_version_req = req.visible_version_req;
2398
5.94k
    engine.tablet_manager()->update_partitions_visible_version(
2399
5.94k
            visible_version_req.partition_version);
2400
5.94k
}
2401
2402
void clone_callback(StorageEngine& engine, const ClusterInfo* cluster_info,
2403
0
                    const TAgentTaskRequest& req) {
2404
0
    const auto& clone_req = req.clone_req;
2405
2406
0
    DorisMetrics::instance()->clone_requests_total->increment(1);
2407
0
    LOG(INFO) << "get clone task. signature=" << req.signature;
2408
2409
0
    std::vector<TTabletInfo> tablet_infos;
2410
0
    EngineCloneTask engine_task(engine, clone_req, cluster_info, req.signature, &tablet_infos);
2411
0
    SCOPED_ATTACH_TASK(engine_task.mem_tracker());
2412
0
    auto status = engine_task.execute();
2413
    // Return result to fe
2414
0
    TFinishTaskRequest finish_task_request;
2415
0
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2416
0
    finish_task_request.__set_task_type(req.task_type);
2417
0
    finish_task_request.__set_signature(req.signature);
2418
0
    finish_task_request.__set_task_status(status.to_thrift());
2419
2420
0
    if (!status.ok()) {
2421
0
        DorisMetrics::instance()->clone_requests_failed->increment(1);
2422
0
        LOG_WARNING("failed to clone tablet")
2423
0
                .tag("signature", req.signature)
2424
0
                .tag("tablet_id", clone_req.tablet_id)
2425
0
                .error(status);
2426
0
    } else {
2427
0
        LOG_INFO("successfully clone tablet")
2428
0
                .tag("signature", req.signature)
2429
0
                .tag("tablet_id", clone_req.tablet_id)
2430
0
                .tag("copy_size", engine_task.get_copy_size())
2431
0
                .tag("copy_time_ms", engine_task.get_copy_time_ms());
2432
2433
0
        if (engine_task.is_new_tablet()) {
2434
0
            increase_report_version();
2435
0
            finish_task_request.__set_report_version(s_report_version);
2436
0
        }
2437
0
        finish_task_request.__set_finish_tablet_infos(tablet_infos);
2438
0
        finish_task_request.__set_copy_size(engine_task.get_copy_size());
2439
0
        finish_task_request.__set_copy_time_ms(engine_task.get_copy_time_ms());
2440
0
    }
2441
2442
0
    finish_task(finish_task_request);
2443
0
    remove_task_info(req.task_type, req.signature);
2444
0
}
2445
2446
0
void storage_medium_migrate_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2447
0
    const auto& storage_medium_migrate_req = req.storage_medium_migrate_req;
2448
2449
    // check request and get info
2450
0
    TabletSharedPtr tablet;
2451
0
    DataDir* dest_store = nullptr;
2452
2453
0
    auto status = check_migrate_request(engine, storage_medium_migrate_req, tablet, &dest_store);
2454
0
    if (status.ok()) {
2455
0
        EngineStorageMigrationTask engine_task(engine, tablet, dest_store);
2456
0
        SCOPED_ATTACH_TASK(engine_task.mem_tracker());
2457
0
        status = engine_task.execute();
2458
0
    }
2459
    // fe should ignore this err
2460
0
    if (status.is<FILE_ALREADY_EXIST>()) {
2461
0
        status = Status::OK();
2462
0
    }
2463
0
    if (!status.ok()) {
2464
0
        LOG_WARNING("failed to migrate storage medium")
2465
0
                .tag("signature", req.signature)
2466
0
                .tag("tablet_id", storage_medium_migrate_req.tablet_id)
2467
0
                .error(status);
2468
0
    } else {
2469
0
        LOG_INFO("successfully migrate storage medium")
2470
0
                .tag("signature", req.signature)
2471
0
                .tag("tablet_id", storage_medium_migrate_req.tablet_id);
2472
0
    }
2473
2474
0
    TFinishTaskRequest finish_task_request;
2475
0
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2476
0
    finish_task_request.__set_task_type(req.task_type);
2477
0
    finish_task_request.__set_signature(req.signature);
2478
0
    finish_task_request.__set_task_status(status.to_thrift());
2479
2480
0
    finish_task(finish_task_request);
2481
0
    remove_task_info(req.task_type, req.signature);
2482
0
}
2483
2484
8.75k
void calc_delete_bitmap_callback(CloudStorageEngine& engine, const TAgentTaskRequest& req) {
2485
8.75k
    std::vector<TTabletId> error_tablet_ids;
2486
8.75k
    std::vector<TTabletId> succ_tablet_ids;
2487
8.75k
    Status status;
2488
8.75k
    error_tablet_ids.clear();
2489
8.75k
    const auto& calc_delete_bitmap_req = req.calc_delete_bitmap_req;
2490
8.75k
    CloudEngineCalcDeleteBitmapTask engine_task(engine, calc_delete_bitmap_req, &error_tablet_ids,
2491
8.75k
                                                &succ_tablet_ids);
2492
8.75k
    SCOPED_ATTACH_TASK(engine_task.mem_tracker());
2493
8.75k
    if (req.signature != calc_delete_bitmap_req.transaction_id) {
2494
        // transaction_id may not be the same as req.signature, so add a log here
2495
0
        LOG_INFO("begin to execute calc delete bitmap task")
2496
0
                .tag("signature", req.signature)
2497
0
                .tag("transaction_id", calc_delete_bitmap_req.transaction_id);
2498
0
    }
2499
8.75k
    status = engine_task.execute();
2500
2501
8.75k
    TFinishTaskRequest finish_task_request;
2502
8.75k
    if (!status) {
2503
0
        DorisMetrics::instance()->publish_task_failed_total->increment(1);
2504
0
        LOG_WARNING("failed to calculate delete bitmap")
2505
0
                .tag("signature", req.signature)
2506
0
                .tag("transaction_id", calc_delete_bitmap_req.transaction_id)
2507
0
                .tag("error_tablets_num", error_tablet_ids.size())
2508
0
                .error(status);
2509
0
    }
2510
2511
8.75k
    status.to_thrift(&finish_task_request.task_status);
2512
8.75k
    finish_task_request.__set_backend(BackendOptions::get_local_backend());
2513
8.75k
    finish_task_request.__set_task_type(req.task_type);
2514
8.75k
    finish_task_request.__set_signature(req.signature);
2515
8.75k
    finish_task_request.__set_report_version(s_report_version);
2516
8.75k
    finish_task_request.__set_error_tablet_ids(error_tablet_ids);
2517
8.75k
    finish_task_request.__set_resp_partitions(calc_delete_bitmap_req.partitions);
2518
2519
8.75k
    finish_task(finish_task_request);
2520
8.75k
    remove_task_info(req.task_type, req.signature);
2521
8.75k
}
2522
2523
void make_cloud_committed_rs_visible_callback(CloudStorageEngine& engine,
2524
27.4k
                                              const TAgentTaskRequest& req) {
2525
27.4k
    if (!config::enable_cloud_make_rs_visible_on_be) {
2526
0
        return;
2527
0
    }
2528
27.4k
    LOG(INFO) << "begin to make cloud tmp rs visible, txn_id="
2529
27.4k
              << req.make_cloud_tmp_rs_visible_req.txn_id
2530
27.4k
              << ", tablet_count=" << req.make_cloud_tmp_rs_visible_req.tablet_ids.size();
2531
2532
27.4k
    const auto& make_visible_req = req.make_cloud_tmp_rs_visible_req;
2533
27.4k
    auto& tablet_mgr = engine.tablet_mgr();
2534
2535
27.4k
    int64_t txn_id = make_visible_req.txn_id;
2536
27.4k
    int64_t version_update_time_ms = make_visible_req.__isset.version_update_time_ms
2537
27.4k
                                             ? make_visible_req.version_update_time_ms
2538
27.4k
                                             : 0;
2539
2540
    // Process each tablet involved in this transaction on this BE
2541
174k
    for (int64_t tablet_id : make_visible_req.tablet_ids) {
2542
174k
        auto tablet_result =
2543
174k
                tablet_mgr.get_tablet(tablet_id, /* warmup_data */ false,
2544
174k
                                      /* sync_delete_bitmap */ false,
2545
174k
                                      /* sync_stats */ nullptr, /* force_use_only_cached */ true,
2546
174k
                                      /* cache_on_miss */ false);
2547
174k
        if (!tablet_result.has_value()) {
2548
0
            continue;
2549
0
        }
2550
174k
        auto cloud_tablet = tablet_result.value();
2551
2552
174k
        int64_t partition_id = cloud_tablet->partition_id();
2553
174k
        auto version_iter = make_visible_req.partition_version_map.find(partition_id);
2554
174k
        if (version_iter == make_visible_req.partition_version_map.end()) {
2555
65
            continue;
2556
65
        }
2557
174k
        int64_t visible_version = version_iter->second;
2558
174k
        DBUG_EXECUTE_IF("make_cloud_committed_rs_visible_callback.block", {
2559
174k
            auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
2560
174k
            auto target_table_id = dp->param<int64_t>("table_id", -1);
2561
174k
            auto version = dp->param<int64_t>("version", -1);
2562
174k
            if ((target_tablet_id == tablet_id || target_table_id == cloud_tablet->table_id()) &&
2563
174k
                version == visible_version) {
2564
174k
                DBUG_BLOCK
2565
174k
            }
2566
174k
        });
2567
174k
        cloud_tablet->try_make_committed_rs_visible(txn_id, visible_version,
2568
174k
                                                    version_update_time_ms);
2569
174k
    }
2570
27.4k
    LOG(INFO) << "make cloud tmp rs visible finished, txn_id=" << txn_id
2571
27.4k
              << ", processed_tablets=" << make_visible_req.tablet_ids.size();
2572
27.4k
}
2573
2574
0
void clean_trash_callback(StorageEngine& engine, const TAgentTaskRequest& req) {
2575
0
    LOG(INFO) << "clean trash start";
2576
0
    DBUG_EXECUTE_IF("clean_trash_callback_sleep", { sleep(100); })
2577
0
    static_cast<void>(engine.start_trash_sweep(nullptr, true));
2578
0
    static_cast<void>(engine.notify_listener("REPORT_DISK_STATE"));
2579
0
    LOG(INFO) << "clean trash finish";
2580
0
}
2581
2582
4
void clean_udf_cache_callback(const TAgentTaskRequest& req) {
2583
4
    const auto& clean_req = req.clean_udf_cache_req;
2584
2585
4
    if (doris::config::enable_java_support) {
2586
4
        static_cast<void>(Jni::Util::clean_udf_class_load_cache(clean_req.function_signature));
2587
4
    }
2588
2589
4
    if (clean_req.__isset.function_id && clean_req.function_id > 0) {
2590
0
        UserFunctionCache::instance()->drop_function_cache(clean_req.function_id);
2591
0
        PythonServerManager::instance().clear_udaf_state_cache(clean_req.function_id);
2592
0
    }
2593
2594
4
    LOG(INFO) << "clean udf cache finish: function_signature=" << clean_req.function_signature;
2595
4
}
2596
2597
1.34k
void report_index_policy_callback(const ClusterInfo* cluster_info) {
2598
1.34k
    TReportRequest request;
2599
1.34k
    auto& index_policy_list = request.index_policy;
2600
1.34k
    const auto& policys = doris::ExecEnv::GetInstance()->index_policy_mgr()->get_index_policys();
2601
21.3k
    for (const auto& policy : policys) {
2602
21.3k
        index_policy_list.emplace_back(policy.second);
2603
21.3k
    }
2604
1.34k
    request.__isset.index_policy = true;
2605
1.34k
    request.__set_backend(BackendOptions::get_local_backend());
2606
1.34k
    bool succ = handle_report(request, cluster_info, "index_policy");
2607
1.34k
    report_index_policy_total << 1;
2608
1.34k
    if (!succ) [[unlikely]] {
2609
0
        report_index_policy_failed << 1;
2610
0
    }
2611
1.34k
}
2612
2613
} // namespace doris