Coverage Report

Created: 2026-07-09 20:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/agent/utils.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/utils.h"
19
20
// IWYU pragma: no_include <bthread/errno.h>
21
#include <errno.h> // IWYU pragma: keep
22
#include <fmt/format.h>
23
#include <gen_cpp/FrontendService.h>
24
#include <gen_cpp/HeartbeatService_types.h>
25
#include <gen_cpp/Types_types.h>
26
#include <glog/logging.h>
27
#include <rapidjson/document.h>
28
#include <rapidjson/encodings.h>
29
#include <rapidjson/rapidjson.h>
30
#include <rapidjson/stringbuffer.h>
31
#include <rapidjson/writer.h>
32
#include <stdint.h>
33
#include <stdlib.h>
34
#include <string.h>
35
#include <thrift/transport/TTransportException.h>
36
37
#include <cstdio>
38
#include <exception>
39
#include <fstream>
40
#include <memory>
41
#include <utility>
42
43
#include "common/config.h"
44
#include "common/status.h"
45
#include "runtime/cluster_info.h"
46
#include "util/client_cache.h"
47
48
namespace doris {
49
class TConfirmUnusedRemoteFilesRequest;
50
class TConfirmUnusedRemoteFilesResult;
51
class TFinishTaskRequest;
52
class TMasterResult;
53
class TReportRequest;
54
} // namespace doris
55
56
using apache::thrift::transport::TTransportException;
57
58
namespace doris {
59
60
static std::unique_ptr<MasterServerClient> s_client;
61
62
0
MasterServerClient* MasterServerClient::create(const ClusterInfo* cluster_info) {
63
0
    s_client.reset(new MasterServerClient(cluster_info));
64
0
    return s_client.get();
65
0
}
66
67
0
MasterServerClient* MasterServerClient::instance() {
68
0
    return s_client.get();
69
0
}
70
71
MasterServerClient::MasterServerClient(const ClusterInfo* cluster_info)
72
0
        : _cluster_info(cluster_info),
73
0
          _client_cache(std::make_unique<FrontendServiceClientCache>(
74
0
                  config::max_master_fe_client_cache_size)) {
75
0
    _client_cache->init_metrics("master_fe");
76
0
}
77
78
0
Status MasterServerClient::finish_task(const TFinishTaskRequest& request, TMasterResult* result) {
79
0
    Status client_status;
80
0
    FrontendServiceConnection client(_client_cache.get(), _cluster_info->master_fe_addr,
81
0
                                     config::thrift_rpc_timeout_ms, &client_status);
82
83
0
    if (!client_status.ok()) {
84
0
        LOG(WARNING) << "fail to get master client from cache. "
85
0
                     << "host=" << _cluster_info->master_fe_addr.hostname
86
0
                     << ", port=" << _cluster_info->master_fe_addr.port
87
0
                     << ", code=" << client_status.code();
88
0
        return Status::InternalError("Failed to get master client");
89
0
    }
90
91
0
    try {
92
0
        try {
93
0
            client->finishTask(*result, request);
94
0
        } catch (TTransportException& e) {
95
0
            LOG(WARNING) << "master client, retry finishTask: " << e.what();
96
0
            client_status = client.reopen(config::thrift_rpc_timeout_ms);
97
0
            if (!client_status.ok()) {
98
0
                LOG(WARNING) << "fail to get master client from cache. "
99
0
                             << "host=" << _cluster_info->master_fe_addr.hostname
100
0
                             << ", port=" << _cluster_info->master_fe_addr.port
101
0
                             << ", code=" << client_status.code();
102
0
                return Status::RpcError("Master client finish task failed");
103
0
            }
104
0
            client->finishTask(*result, request);
105
0
        }
106
0
    } catch (std::exception& e) {
107
0
        RETURN_IF_ERROR(client.reopen(config::thrift_rpc_timeout_ms));
108
0
        LOG(WARNING) << "fail to finish_task. "
109
0
                     << "host=" << _cluster_info->master_fe_addr.hostname
110
0
                     << ", port=" << _cluster_info->master_fe_addr.port << ", error=" << e.what();
111
0
        return Status::InternalError("Fail to finish task");
112
0
    }
113
114
0
    return Status::OK();
115
0
}
116
117
0
Status MasterServerClient::report(const TReportRequest& request, TMasterResult* result) {
118
0
    Status client_status;
119
0
    FrontendServiceConnection client(_client_cache.get(), _cluster_info->master_fe_addr,
120
0
                                     config::thrift_rpc_timeout_ms, &client_status);
121
122
0
    if (!client_status.ok()) {
123
0
        LOG(WARNING) << "fail to get master client from cache. "
124
0
                     << "host=" << _cluster_info->master_fe_addr.hostname
125
0
                     << ", port=" << _cluster_info->master_fe_addr.port
126
0
                     << ", code=" << client_status;
127
0
        return Status::InternalError("Fail to get master client from cache");
128
0
    }
129
130
0
    try {
131
0
        try {
132
0
            client->report(*result, request);
133
0
        } catch (TTransportException& e) {
134
0
            TTransportException::TTransportExceptionType type = e.getType();
135
0
            if (type != TTransportException::TTransportExceptionType::TIMED_OUT) {
136
                // if not TIMED_OUT, retry
137
0
                LOG(WARNING) << "master client, retry finishTask: " << e.what();
138
139
0
                client_status = client.reopen(config::thrift_rpc_timeout_ms);
140
0
                if (!client_status.ok()) {
141
0
                    LOG(WARNING) << "fail to get master client from cache. "
142
0
                                 << "host=" << _cluster_info->master_fe_addr.hostname
143
0
                                 << ", port=" << _cluster_info->master_fe_addr.port
144
0
                                 << ", code=" << client_status.code();
145
0
                    return Status::InternalError("Fail to get master client from cache");
146
0
                }
147
148
0
                client->report(*result, request);
149
0
            } else {
150
                // TIMED_OUT exception. do not retry
151
                // actually we don't care what FE returns.
152
0
                LOG(WARNING) << "fail to report to master: " << e.what();
153
0
                return Status::InternalError("Fail to report to master");
154
0
            }
155
0
        }
156
0
    } catch (std::exception& e) {
157
0
        RETURN_IF_ERROR(client.reopen(config::thrift_rpc_timeout_ms));
158
0
        LOG(WARNING) << "fail to report to master. "
159
0
                     << "host=" << _cluster_info->master_fe_addr.hostname
160
0
                     << ", port=" << _cluster_info->master_fe_addr.port
161
0
                     << ", code=" << client_status.code() << ", reason=" << e.what();
162
0
        return Status::InternalError("Fail to report to master");
163
0
    }
164
165
0
    return Status::OK();
166
0
}
167
168
Status MasterServerClient::confirm_unused_remote_files(
169
0
        const TConfirmUnusedRemoteFilesRequest& request, TConfirmUnusedRemoteFilesResult* result) {
170
0
    Status client_status;
171
0
    FrontendServiceConnection client(_client_cache.get(), _cluster_info->master_fe_addr,
172
0
                                     config::thrift_rpc_timeout_ms, &client_status);
173
174
0
    if (!client_status.ok()) {
175
0
        return Status::InternalError(
176
0
                "fail to get master client from cache. host={}, port={}, code={}",
177
0
                _cluster_info->master_fe_addr.hostname, _cluster_info->master_fe_addr.port,
178
0
                client_status.code());
179
0
    }
180
0
    try {
181
0
        try {
182
0
            client->confirmUnusedRemoteFiles(*result, request);
183
0
        } catch (TTransportException& e) {
184
0
            TTransportException::TTransportExceptionType type = e.getType();
185
0
            if (type != TTransportException::TTransportExceptionType::TIMED_OUT) {
186
                // if not TIMED_OUT, retry
187
0
                LOG(WARNING) << "master client, retry finishTask: " << e.what();
188
189
0
                client_status = client.reopen(config::thrift_rpc_timeout_ms);
190
0
                if (!client_status.ok()) {
191
0
                    return Status::InternalError(
192
0
                            "fail to get master client from cache. host={}, port={}, code={}",
193
0
                            _cluster_info->master_fe_addr.hostname,
194
0
                            _cluster_info->master_fe_addr.port, client_status.code());
195
0
                }
196
197
0
                client->confirmUnusedRemoteFiles(*result, request);
198
0
            } else {
199
                // TIMED_OUT exception. do not retry
200
                // actually we don't care what FE returns.
201
0
                return Status::InternalError(
202
0
                        "fail to confirm unused remote files. host={}, port={}, code={}, reason={}",
203
0
                        _cluster_info->master_fe_addr.hostname, _cluster_info->master_fe_addr.port,
204
0
                        client_status.code(), e.what());
205
0
            }
206
0
        }
207
0
    } catch (std::exception& e) {
208
0
        RETURN_IF_ERROR(client.reopen(config::thrift_rpc_timeout_ms));
209
0
        return Status::InternalError(
210
0
                "fail to confirm unused remote files. host={}, port={}, code={}, reason={}",
211
0
                _cluster_info->master_fe_addr.hostname, _cluster_info->master_fe_addr.port,
212
0
                client_status.code(), e.what());
213
0
    }
214
215
0
    return Status::OK();
216
0
}
217
218
0
bool AgentUtils::exec_cmd(const std::string& command, std::string* errmsg, bool redirect_stderr) {
219
    // The exit status of the command.
220
0
    uint32_t rc = 0;
221
222
    // Redirect stderr to stdout to get error message.
223
0
    std::string cmd = command;
224
0
    if (redirect_stderr) {
225
0
        cmd += " 2>&1";
226
0
    }
227
228
    // Execute command.
229
0
    FILE* fp = popen(cmd.c_str(), "r");
230
0
    if (fp == nullptr) {
231
0
        *errmsg = fmt::format("popen failed. {}, with errno: {}.\n", strerror(errno), errno);
232
0
        return false;
233
0
    }
234
235
    // Get command output.
236
0
    char result[1024] = {'\0'};
237
0
    while (fgets(result, sizeof(result), fp) != nullptr) {
238
0
        *errmsg += result;
239
0
    }
240
241
    // Waits for the associated process to terminate and returns.
242
0
    rc = pclose(fp);
243
0
    if (rc == -1) {
244
0
        if (errno == ECHILD) {
245
0
            *errmsg += "pclose cannot obtain the child status.\n";
246
0
        } else {
247
0
            *errmsg += fmt::format("Close popen failed. {}, with errno: {}.\n", strerror(errno),
248
0
                                   errno);
249
0
        }
250
0
        return false;
251
0
    }
252
253
    // Get return code of command.
254
0
    int32_t status_child = WEXITSTATUS(rc);
255
0
    if (status_child == 0) {
256
0
        return true;
257
0
    } else {
258
0
        return false;
259
0
    }
260
0
}
261
262
bool AgentUtils::write_json_to_file(const std::map<std::string, std::string>& info,
263
0
                                    const std::string& path) {
264
0
    rapidjson::Document json_info(rapidjson::kObjectType);
265
0
    for (auto& it : info) {
266
0
        json_info.AddMember(rapidjson::Value(it.first.c_str(), json_info.GetAllocator()).Move(),
267
0
                            rapidjson::Value(it.second.c_str(), json_info.GetAllocator()).Move(),
268
0
                            json_info.GetAllocator());
269
0
    }
270
0
    rapidjson::StringBuffer json_info_str;
271
0
    rapidjson::Writer<rapidjson::StringBuffer> writer(json_info_str);
272
0
    json_info.Accept(writer);
273
0
    std::ofstream fp(path);
274
0
    if (!fp) {
275
0
        return false;
276
0
    }
277
0
    fp << json_info_str.GetString() << std::endl;
278
0
    fp.close();
279
280
0
    return true;
281
0
}
282
283
} // namespace doris