Coverage Report

Created: 2026-07-01 20:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/http/action/compaction_action.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 "service/http/action/compaction_action.h"
19
20
// IWYU pragma: no_include <bits/chrono.h>
21
#include <chrono> // IWYU pragma: keep
22
#include <exception>
23
#include <future>
24
#include <memory>
25
#include <mutex>
26
#include <sstream>
27
#include <string>
28
#include <thread>
29
#include <utility>
30
31
#include "absl/strings/substitute.h"
32
#include "common/logging.h"
33
#include "common/metrics/doris_metrics.h"
34
#include "common/status.h"
35
#include "service/http/http_channel.h"
36
#include "service/http/http_headers.h"
37
#include "service/http/http_request.h"
38
#include "service/http/http_status.h"
39
#include "storage/compaction/base_compaction.h"
40
#include "storage/compaction/binlog_compaction.h"
41
#include "storage/compaction/cumulative_compaction.h"
42
#include "storage/compaction/cumulative_compaction_policy.h"
43
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
44
#include "storage/compaction_task_tracker.h"
45
#include "storage/olap_define.h"
46
#include "storage/storage_engine.h"
47
#include "storage/tablet/tablet_manager.h"
48
#include "util/stopwatch.hpp"
49
50
namespace doris {
51
using namespace ErrorCode;
52
53
namespace {
54
55
constexpr std::string_view HEADER_JSON = "application/json";
56
57
} // namespace
58
59
CompactionAction::CompactionAction(CompactionActionType ctype, ExecEnv* exec_env,
60
                                   StorageEngine& engine, TPrivilegeHier::type hier,
61
                                   TPrivilegeType::type ptype)
62
30
        : HttpHandlerWithAuth(exec_env, hier, ptype), _engine(engine), _compaction_type(ctype) {}
63
64
/// check param and fetch tablet_id & table_id from req
65
254
static Status _check_param(HttpRequest* req, uint64_t* tablet_id, uint64_t* table_id) {
66
    // req tablet id and table id, we have to set only one of them.
67
254
    const auto& req_tablet_id = req->param(TABLET_ID_KEY);
68
254
    const auto& req_table_id = req->param(TABLE_ID_KEY);
69
254
    if (req_tablet_id.empty()) {
70
2
        if (req_table_id.empty()) {
71
            // both tablet id and table id are empty, return error.
72
1
            return Status::InternalError(
73
1
                    "tablet id and table id can not be empty at the same time!");
74
1
        } else {
75
1
            try {
76
1
                *table_id = std::stoull(req_table_id);
77
1
            } catch (const std::exception& e) {
78
0
                return Status::InternalError("convert table_id failed, {}", e.what());
79
0
            }
80
1
            return Status::OK();
81
1
        }
82
252
    } else if (req_table_id.empty()) {
83
251
        try {
84
251
            *tablet_id = std::stoull(req_tablet_id);
85
251
        } catch (const std::exception& e) {
86
1
            return Status::InternalError("convert tablet_id failed, {}", e.what());
87
1
        }
88
250
        return Status::OK();
89
251
    } else {
90
        // both tablet id and table id are not empty, return err.
91
1
        return Status::InternalError("tablet id and table id can not be set at the same time!");
92
1
    }
93
254
}
94
95
/// retrieve specific id from req
96
1.24k
static Status _check_param(HttpRequest* req, uint64_t* id_param, const std::string param_name) {
97
1.24k
    const auto& req_id_param = req->param(param_name);
98
1.24k
    if (!req_id_param.empty()) {
99
1.24k
        try {
100
1.24k
            *id_param = std::stoull(req_id_param);
101
1.24k
        } catch (const std::exception& e) {
102
0
            return Status::InternalError("convert {} failed, {}", param_name, e.what());
103
0
        }
104
1.24k
    }
105
106
1.24k
    return Status::OK();
107
1.24k
}
108
109
// for viewing the compaction status
110
859
Status CompactionAction::_handle_show_compaction(HttpRequest* req, std::string* json_result) {
111
859
    uint64_t tablet_id = 0;
112
    // check & retrieve tablet_id from req if it contains
113
859
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_param(req, &tablet_id, TABLET_ID_KEY),
114
859
                                   "check param failed");
115
859
    if (tablet_id == 0) {
116
1
        return Status::InternalError("check param failed: missing tablet_id");
117
1
    }
118
119
858
    TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
120
858
    if (tablet == nullptr) {
121
1
        return Status::NotFound("Tablet not found. tablet_id={}", tablet_id);
122
1
    }
123
124
857
    tablet->get_compaction_status(json_result);
125
857
    return Status::OK();
126
858
}
127
128
254
Status CompactionAction::_handle_run_compaction(HttpRequest* req, std::string* json_result) {
129
    // 1. param check
130
    // check req_tablet_id or req_table_id is not empty and can not be set together.
131
254
    uint64_t tablet_id = 0;
132
254
    uint64_t table_id = 0;
133
254
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_param(req, &tablet_id, &table_id), "check param failed");
134
135
    // check compaction_type
136
251
    std::string compaction_type = req->param(PARAM_COMPACTION_TYPE);
137
251
    if (compaction_type != PARAM_COMPACTION_BASE &&
138
251
        compaction_type != PARAM_COMPACTION_CUMULATIVE &&
139
251
        compaction_type != PARAM_COMPACTION_FULL && compaction_type != PARAM_COMPACTION_BINLOG) {
140
1
        return Status::NotSupported("The compaction type '{}' is not supported", compaction_type);
141
1
    }
142
143
    // "force" = "true" means skip permit limiter when submitting full compaction to thread pool
144
250
    bool force = false;
145
250
    std::string param_force = req->param(PARAM_COMPACTION_FORCE);
146
250
    if (param_force == "true") {
147
2
        force = true;
148
248
    } else if (!param_force.empty() && param_force != "false") {
149
1
        return Status::NotSupported("The force = '{}' is not supported", param_force);
150
1
    }
151
152
249
    if (tablet_id == 0 && table_id != 0) {
153
1
        std::vector<TabletSharedPtr> tablet_vec = _engine.tablet_manager()->get_all_tablet(
154
1
                [table_id](Tablet* tablet) -> bool { return tablet->get_table_id() == table_id; });
155
1
        for (const auto& tablet : tablet_vec) {
156
0
            tablet->set_last_full_compaction_schedule_time(UnixMillis());
157
0
            RETURN_IF_ERROR(_engine.submit_compaction_task(tablet, CompactionType::FULL_COMPACTION,
158
0
                                                           force, true, 1));
159
0
        }
160
248
    } else {
161
        // 2. fetch the tablet by tablet_id
162
248
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
163
248
        if (tablet == nullptr) {
164
5
            return Status::NotFound("Tablet not found. tablet_id={}", tablet_id);
165
5
        }
166
167
243
        DBUG_EXECUTE_IF("CompactionAction._handle_run_compaction.submit_cumu_task", {
168
243
            RETURN_IF_ERROR(_engine.submit_compaction_task(
169
243
                    tablet, CompactionType::CUMULATIVE_COMPACTION, false));
170
243
            LOG(INFO) << "Manual debug compaction task is successfully triggered";
171
243
            *json_result =
172
243
                    R"({"status": "Success", "msg": "debug compaction task is successfully triggered. Table id: )" +
173
243
                    std::to_string(table_id) + ". Tablet id: " + std::to_string(tablet_id) + "\"}";
174
243
            return Status::OK();
175
243
        })
176
177
243
        if (compaction_type == PARAM_COMPACTION_FULL) {
178
            // 3. submit full compaction task to thread pool
179
166
            tablet->set_last_full_compaction_schedule_time(UnixMillis());
180
166
            RETURN_IF_ERROR(_engine.submit_compaction_task(tablet, CompactionType::FULL_COMPACTION,
181
166
                                                           force, true, 1));
182
166
        } else {
183
            // 3. execute base/cumulative/binlog compaction task in a detached thread
184
77
            std::packaged_task<Status()> task([this, tablet, compaction_type]() {
185
77
                return _execute_compaction_callback(tablet, compaction_type);
186
77
            });
187
77
            std::future<Status> future_obj = task.get_future();
188
77
            std::thread(std::move(task)).detach();
189
190
77
            if (compaction_type == PARAM_COMPACTION_BASE) {
191
1
                tablet->set_last_base_compaction_schedule_time(UnixMillis());
192
76
            } else if (compaction_type == PARAM_COMPACTION_CUMULATIVE) {
193
62
                tablet->set_last_cumu_compaction_schedule_time(UnixMillis());
194
62
            }
195
196
            // 4. wait for result for 2 seconds by async
197
77
            std::future_status status = future_obj.wait_for(std::chrono::seconds(2));
198
77
            if (status == std::future_status::ready) {
199
75
                Status olap_status = future_obj.get();
200
75
                if (!olap_status.ok()) {
201
2
                    return olap_status;
202
2
                }
203
75
            } else {
204
2
                LOG(INFO) << "Manual compaction task is timeout for waiting "
205
2
                          << (status == std::future_status::timeout);
206
2
            }
207
77
        }
208
243
    }
209
249
    LOG(INFO) << "Manual compaction task is successfully triggered";
210
242
    *json_result =
211
242
            R"({"status": "Success", "msg": "compaction task is successfully triggered. Table id: )" +
212
242
            std::to_string(table_id) + ". Tablet id: " + std::to_string(tablet_id) + "\"}";
213
242
    return Status::OK();
214
249
}
215
216
388
Status CompactionAction::_handle_run_status_compaction(HttpRequest* req, std::string* json_result) {
217
388
    uint64_t tablet_id = 0;
218
    // check & retrieve tablet_id from req if it contains
219
388
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_param(req, &tablet_id, TABLET_ID_KEY),
220
388
                                   "check param failed");
221
222
388
    if (tablet_id == 0) {
223
        // overall compaction status
224
1
        _engine.get_compaction_status_json(json_result);
225
1
        return Status::OK();
226
387
    } else {
227
        // fetch the tablet by tablet_id
228
387
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
229
387
        if (tablet == nullptr) {
230
1
            LOG(WARNING) << "invalid argument.tablet_id:" << tablet_id;
231
1
            return Status::InternalError("fail to get {}", tablet_id);
232
1
        }
233
234
386
        std::string json_template = R"({
235
386
            "status" : "Success",
236
386
            "run_status" : $0,
237
386
            "msg" : "$1",
238
386
            "tablet_id" : $2,
239
386
            "compact_type" : "$3"
240
386
        })";
241
242
386
        std::string msg = "compaction task for this tablet is not running";
243
386
        std::string compaction_type;
244
386
        bool run_status = false;
245
246
386
        {
247
            // Full compaction holds both base compaction lock and cumu compaction lock.
248
            // So we can not judge if full compaction is running by check these two locks holding.
249
            // Here, we use a variable 'is_full_compaction_running' to check if full compaction is running.
250
386
            if (tablet->is_full_compaction_running()) {
251
77
                msg = "compaction task for this tablet is running";
252
77
                compaction_type = "full";
253
77
                run_status = true;
254
77
                *json_result = absl::Substitute(json_template, run_status, msg, tablet_id,
255
77
                                                compaction_type);
256
77
                return Status::OK();
257
77
            }
258
386
        }
259
260
309
        {
261
            // use try lock to check this tablet is running cumulative compaction
262
309
            std::unique_lock<std::mutex> lock_cumulative(tablet->get_cumulative_compaction_lock(),
263
309
                                                         std::try_to_lock);
264
309
            if (!lock_cumulative.owns_lock()) {
265
74
                msg = "compaction task for this tablet is running";
266
74
                compaction_type = "cumulative";
267
74
                run_status = true;
268
74
                *json_result = absl::Substitute(json_template, run_status, msg, tablet_id,
269
74
                                                compaction_type);
270
74
                return Status::OK();
271
74
            }
272
309
        }
273
274
235
        {
275
            // use try lock to check this tablet is running binlog compaction
276
235
            std::unique_lock<std::mutex> lock_binlog(tablet->get_binlog_compaction_lock(),
277
235
                                                     std::try_to_lock);
278
235
            if (!lock_binlog.owns_lock()) {
279
0
                msg = "compaction task for this tablet is running";
280
0
                compaction_type = "binlog";
281
0
                run_status = true;
282
0
                *json_result = absl::Substitute(json_template, run_status, msg, tablet_id,
283
0
                                                compaction_type);
284
0
                return Status::OK();
285
0
            }
286
235
        }
287
288
235
        {
289
            // use try lock to check this tablet is running base compaction
290
235
            std::unique_lock<std::mutex> lock_base(tablet->get_base_compaction_lock(),
291
235
                                                   std::try_to_lock);
292
235
            if (!lock_base.owns_lock()) {
293
0
                msg = "compaction task for this tablet is running";
294
0
                compaction_type = "base";
295
0
                run_status = true;
296
0
                *json_result = absl::Substitute(json_template, run_status, msg, tablet_id,
297
0
                                                compaction_type);
298
0
                return Status::OK();
299
0
            }
300
235
        }
301
        // not running any compaction
302
235
        *json_result = absl::Substitute(json_template, run_status, msg, tablet_id, compaction_type);
303
235
        return Status::OK();
304
235
    }
305
388
}
306
307
Status CompactionAction::_execute_compaction_callback(TabletSharedPtr tablet,
308
                                                      const std::string& compaction_type,
309
77
                                                      int8_t prefer_compaction_level) {
310
77
    MonotonicStopWatch timer;
311
77
    timer.start();
312
313
77
    std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy =
314
77
            CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
315
77
                    tablet->tablet_meta()->compaction_policy());
316
77
    if (tablet->get_cumulative_compaction_policy() == nullptr) {
317
42
        tablet->set_cumulative_compaction_policy(cumulative_compaction_policy);
318
42
    }
319
77
    Status res = Status::OK();
320
77
    auto* tracker = CompactionTaskTracker::instance();
321
77
    auto do_compact = [&](Compaction& compaction, CompactionProfileType profile_type) {
322
77
        RETURN_IF_ERROR(compaction.prepare_compact());
323
        // Register task as RUNNING with tracker (manual trigger, direct execution path)
324
        // Use compaction.compaction_id() which was allocated in constructor.
325
75
        int64_t compaction_id = compaction.compaction_id();
326
75
        {
327
75
            CompactionTaskInfo info;
328
75
            info.compaction_id = compaction_id;
329
75
            info.tablet_id = tablet->tablet_id();
330
75
            info.table_id = tablet->get_table_id();
331
75
            info.partition_id = tablet->partition_id();
332
75
            info.compaction_type = profile_type;
333
75
            info.status = CompactionTaskStatus::RUNNING;
334
75
            info.trigger_method = TriggerMethod::MANUAL;
335
75
            auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
336
75
                                  std::chrono::system_clock::now().time_since_epoch())
337
75
                                  .count();
338
75
            info.scheduled_time_ms = now_ms;
339
75
            info.start_time_ms = now_ms;
340
75
            info.compaction_score = tablet->get_real_compaction_score();
341
75
            info.input_rowsets_count = compaction.input_rowsets_count();
342
75
            info.input_row_num = compaction.input_row_num_value();
343
75
            info.input_data_size = compaction.input_rowsets_data_size();
344
75
            info.input_index_size = compaction.input_rowsets_index_size();
345
75
            info.input_total_size = compaction.input_rowsets_total_size();
346
75
            info.input_segments_num = compaction.input_segments_num_value();
347
75
            info.input_version_range = compaction.input_version_range_str();
348
75
            info.is_vertical = compaction.is_vertical();
349
75
            info.backend_id = BackendOptions::get_backend_id();
350
75
            tracker->register_task(std::move(info));
351
75
        }
352
75
        auto st = compaction.execute_compact();
353
        // Idempotent cleanup: if execute returned early (e.g. TRY_LOCK_FAILED)
354
        // before submit_profile_record was called, task remains in active_tasks.
355
75
        tracker->remove_task(compaction_id);
356
75
        return st;
357
77
    };
358
77
    if (compaction_type == PARAM_COMPACTION_BASE) {
359
1
        BaseCompaction base_compaction(_engine, tablet);
360
1
        res = do_compact(base_compaction, CompactionProfileType::BASE);
361
1
        if (!res) {
362
0
            if (!res.is<BE_NO_SUITABLE_VERSION>()) {
363
0
                DorisMetrics::instance()->base_compaction_request_failed->increment(1);
364
0
            }
365
0
        }
366
76
    } else if (compaction_type == PARAM_COMPACTION_CUMULATIVE) {
367
62
        {
368
62
            CumulativeCompaction cumulative_compaction(_engine, tablet);
369
62
            res = do_compact(cumulative_compaction, CompactionProfileType::CUMULATIVE);
370
62
            if (!res) {
371
2
                if (res.is<CUMULATIVE_NO_SUITABLE_VERSION>()) {
372
                    // Ignore this error code.
373
2
                    VLOG_NOTICE
374
0
                            << "failed to init cumulative compaction due to no suitable version,"
375
0
                            << "tablet=" << tablet->tablet_id();
376
2
                } else {
377
0
                    DorisMetrics::instance()->cumulative_compaction_request_failed->increment(1);
378
0
                    LOG(WARNING) << "failed to do cumulative compaction. res=" << res
379
0
                                 << ", table=" << tablet->tablet_id();
380
0
                }
381
2
            }
382
62
        }
383
62
    } else if (compaction_type == PARAM_COMPACTION_BINLOG) {
384
14
        if (prefer_compaction_level < 0) {
385
14
            tablet->calc_compaction_score(CompactionType::BINLOG_COMPACTION,
386
14
                                          &prefer_compaction_level);
387
14
        }
388
14
        if (prefer_compaction_level < 0) {
389
0
            res = Status::Error<BINLOG_COMPACTION_NO_SUITABLE_VERSION>(
390
0
                    "failed to init binlog compaction due to no suitable version");
391
14
        } else {
392
14
            BinlogCompaction binlog_compaction(_engine, tablet, prefer_compaction_level);
393
14
            res = do_compact(binlog_compaction, CompactionProfileType::BINLOG);
394
14
            if (!res) {
395
0
                if (res.is<BINLOG_COMPACTION_NO_SUITABLE_VERSION>()) {
396
0
                    VLOG_NOTICE << "failed to init binlog compaction due to no suitable version,"
397
0
                                << "tablet=" << tablet->tablet_id() << ", compaction_level="
398
0
                                << static_cast<int>(prefer_compaction_level);
399
0
                } else {
400
0
                    LOG(WARNING) << "failed to do binlog compaction. res=" << res
401
0
                                 << ", table=" << tablet->tablet_id() << ", compaction_level="
402
0
                                 << static_cast<int>(prefer_compaction_level);
403
0
                }
404
0
            }
405
14
        }
406
14
    }
407
77
    timer.stop();
408
77
    LOG(INFO) << "Manual compaction task finish, status=" << res
409
77
              << ", compaction_use_time=" << timer.elapsed_time() / 1000000 << "ms";
410
77
    return res;
411
77
}
412
413
1.48k
void CompactionAction::handle(HttpRequest* req) {
414
1.48k
    req->add_output_header(HttpHeaders::CONTENT_TYPE, HEADER_JSON.data());
415
416
1.48k
    if (_compaction_type == CompactionActionType::SHOW_INFO) {
417
857
        std::string json_result;
418
857
        Status st = _handle_show_compaction(req, &json_result);
419
857
        if (!st.ok()) {
420
0
            HttpChannel::send_reply(req, HttpStatus::OK, st.to_json());
421
857
        } else {
422
857
            HttpChannel::send_reply(req, HttpStatus::OK, json_result);
423
857
        }
424
857
    } else if (_compaction_type == CompactionActionType::RUN_COMPACTION) {
425
243
        std::string json_result;
426
243
        Status st = _handle_run_compaction(req, &json_result);
427
243
        if (!st.ok()) {
428
2
            HttpChannel::send_reply(req, HttpStatus::OK, st.to_json());
429
241
        } else {
430
241
            HttpChannel::send_reply(req, HttpStatus::OK, json_result);
431
241
        }
432
386
    } else {
433
386
        std::string json_result;
434
386
        Status st = _handle_run_status_compaction(req, &json_result);
435
386
        if (!st.ok()) {
436
0
            HttpChannel::send_reply(req, HttpStatus::OK, st.to_json());
437
386
        } else {
438
386
            HttpChannel::send_reply(req, HttpStatus::OK, json_result);
439
386
        }
440
386
    }
441
1.48k
}
442
443
} // end namespace doris