distributed_agent.cpp 15.1 KB
Newer Older
M
mamingshuai 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "distributed_agent.h"

#include <cstring>
#include <cerrno>

#include <poll.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace OHOS {
namespace DistributeSystemTest {
using namespace std;
using namespace OHOS::HiviewDFX;

DistributedAgent::DistributedAgent()
{
    agentPort_ = 0;
    agentIpAddr_ = "";
    mpthCmdProcess_ = nullptr;
    mbStop_ = false;
    clientSockFd_ = -1;
    agentCfg_ = DistributedCfg();
}

DistributedAgent::~DistributedAgent()
{
    if (mpthCmdProcess_ != nullptr) {
        mbStop_ = true;
        if (mpthCmdProcess_->joinable()) {
            mpthCmdProcess_->join();
        }
    }
    close(clientSockFd_);
    clientSockFd_ = -1;
}

/*
 * The result of init test environment is returned. if false is return, the init operation failed.
 * Note that, the test environment should be inited for the test case.
 */
bool DistributedAgent::SetUp()
{
    return true;
}

/*
 * The result of reset test environment is returned. if false is return, the reset operation failed.
 * Note that, the test environment should be reset by the test case in the end.
 */
bool DistributedAgent::TearDown()
{
    return true;
}

int DistributedAgent::InitAgentServer() 
{
    HiLog::Info(DistributedAgent::LABEL, "begin create agent server.\n");
    volatile int serverSockFd = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSockFd < 0) {
        return -1;
    }

    int num = 1;
    if (setsockopt(serverSockFd, SOL_SOCKET, SO_REUSEADDR, &num, sizeof(num)) != 0) {
M
mamingshuai 已提交
82 83 84
        close(serverSockFd);
        serverSockFd = -1;
        return serverSockFd;
M
mamingshuai 已提交
85 86 87 88 89 90 91 92 93 94 95 96
    }

    struct sockaddr_in addr;
    memset_s(&addr, sizeof(addr), 0, sizeof(addr));
    addr.sin_family = AF_INET;
    if (agentIpAddr_ != "") {
        inet_pton(AF_INET, agentIpAddr_.c_str(), &addr.sin_addr);
    } else {
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
    }

    addr.sin_port = htons(agentPort_);
S
stivn 已提交
97
    int err = ::bind(serverSockFd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
M
mamingshuai 已提交
98 99 100 101 102 103 104 105 106
    if (err < 0) {
        HiLog::Error(DistributedAgent::LABEL, "agent bind error.\n");
        close(serverSockFd);
        serverSockFd = -1;
        return serverSockFd;
    }

    if (listen(serverSockFd, 1) < 0) {
        HiLog::Error(DistributedAgent::LABEL, "%s agent listen error.\n", agentIpAddr_.c_str());
M
mamingshuai 已提交
107 108 109
        close(serverSockFd);
        serverSockFd = -1;
        return serverSockFd;
M
mamingshuai 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    }
    HiLog::Info(DistributedAgent::LABEL, "listen %s .......", agentIpAddr_.c_str());
    mpthCmdProcess_ = std::make_unique<std::thread>([=]() {
        DoCmdServer(serverSockFd);
    });

    OnLocalInit();
    return serverSockFd;
}

int DistributedAgent::DoCmdServer(int serverSockFd)
{
    char buff[MAX_BUFF_LEN] = {0};
    char returnValue[MAX_BUFF_LEN] = {0};
    int rlen = 0;
    int receiveLen = 0;
    struct sockaddr_in clientAddr;
    socklen_t sinSize = 0;
    int clientSockFd = -1;
    sinSize = sizeof(struct sockaddr_in);
    bzero(&clientAddr, sizeof(clientAddr));
    receiveLen = DistributedAgent::RECE_LEN;
M
mamingshuai 已提交
132

M
mamingshuai 已提交
133 134
    while (receiveLen > 0) {
        HiLog::Info(DistributedAgent::LABEL, "wait client .......\n");
S
stivn 已提交
135
        if ((clientSockFd = accept(serverSockFd, reinterpret_cast<struct sockaddr *>(&clientAddr), &sinSize)) > 0) {
M
mamingshuai 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149
            break;
        }
        receiveLen--;
        continue;
    }
    if (receiveLen <= 0) {
        HiLog::Error(DistributedAgent::LABEL, "test case runner can not work because I can not accept it.");
        close(serverSockFd);
        return -1;
    }
    clientSockFd_ = clientSockFd;
    HiLog::Info(DistributedAgent::LABEL, "accept testcase runner IP:%s port:%d \n",
                inet_ntoa(clientAddr.sin_addr), clientAddr.sin_port);
    while (mbStop_ != true) {
150 151 152 153 154
        errno_t ret = EOK;
        ret = memset_s(buff, sizeof(buff), 0, MAX_BUFF_LEN);
        if (ret != EOK) {
            return -1;
        }
M
mamingshuai 已提交
155
        // every cmd length less than MAX_BUFF_LEN bytes;
S
stivn 已提交
156 157 158
        int recvCmdLen = recv(clientSockFd_, buff, DST_COMMAND_HEAD_LEN, 0);
        if (static_cast<unsigned long>(recvCmdLen) <  DST_COMMAND_HEAD_LEN) {
            if (recvCmdLen == 0) {
M
mamingshuai 已提交
159 160 161 162 163 164 165 166 167 168 169
                HiLog::Info(DistributedAgent::LABEL, "agent connect socket closed, IP:%s .\n",
                            inet_ntoa(clientAddr.sin_addr));
                mbStop_ = true;
            }
            continue;
        }
        auto pcline = reinterpret_cast<DistributedMsg *>(buff);
        pcline->cmdTestType = ntohs(pcline->cmdTestType);
        pcline->len = ntohs(pcline->len);
        HiLog::Info(DistributedAgent::LABEL, "test agent get message type:%d .\n", pcline->cmdTestType);
        if (pcline->len > 0 && static_cast<unsigned long>(pcline->len) <= (MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN)) {
M
mamingshuai 已提交
170
            receiveLen = recv(clientSockFd_, pcline->alignmentCmd, static_cast<size_t>(pcline->len), 0);
M
mamingshuai 已提交
171 172 173
            HiLog::Info(DistributedAgent::LABEL, "agent get message cmd=%s .\n", pcline->alignmentCmd);
            switch (pcline->cmdTestType) {
                case DST_COMMAND_CALL: {
M
mamingshuai 已提交
174 175
                    errno_t ret = EOK;
                    unsigned int cmdLen = ntohs(*reinterpret_cast<int *>(pcline->alignmentCmd));
M
mamingshuai 已提交
176 177 178
                    rlen = sizeof(int);
                    // check cmdLen length < 100, copy command + args data ;
                    char *pAlignmentCmd = new char[cmdLen + 1];
M
mamingshuai 已提交
179 180 181 182 183
                    ret = memcpy_s(pAlignmentCmd, cmdLen + 1, pcline->alignmentCmd + rlen, cmdLen);
                    if (ret != EOK) {
                        delete []pAlignmentCmd;
                        return -1;
                    }
M
mamingshuai 已提交
184 185
                    pAlignmentCmd[cmdLen] = '\0';
                    rlen += cmdLen + 1;
M
mamingshuai 已提交
186
                    unsigned int eValueLen = ntohs(*reinterpret_cast<int *>(pcline->alignmentCmd + rlen));
M
mamingshuai 已提交
187 188
                    rlen += sizeof(int);
                    char *pszEValue = new char[eValueLen + 1];
M
mamingshuai 已提交
189 190 191 192 193 194
                    ret = memcpy_s(pszEValue, eValueLen + 1, pcline->alignmentCmd + rlen, eValueLen);
                    if (ret != EOK) {
                        delete []pAlignmentCmd;
                        delete []pszEValue;
                        return -1;
                    }
M
mamingshuai 已提交
195 196
                    pszEValue[eValueLen] = '\0';
                    int nresult = OnProcessCmd(pAlignmentCmd, cmdLen, pszEValue, eValueLen);
197 198 199 200
                    ret = memset_s(returnValue, sizeof(returnValue), 0, MAX_BUFF_LEN);
                    if (ret != EOK) {
                        return -1;
                    }
M
mamingshuai 已提交
201 202 203 204 205 206 207 208
                    auto pclinereturn = reinterpret_cast<DistributedMsg *>(returnValue);
                    pclinereturn->no = pcline->no;
                    pclinereturn->cmdTestType = htons(DST_COMMAND_CALL);
                    sprintf_s(pclinereturn->alignmentCmd, (MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN), "%d", nresult);
                    rlen = strlen(pclinereturn->alignmentCmd) + 1;
                    pclinereturn->len = htons(rlen);
                    HiLog::Info(DistributedAgent::LABEL, "agent get message :%s .\n",
                                pclinereturn->alignmentCmd);
M
mamingshuai 已提交
209
                    send(clientSockFd_, pclinereturn, static_cast<size_t>(rlen + DST_COMMAND_HEAD_LEN), 0);
M
mamingshuai 已提交
210 211 212 213 214
                    delete []pAlignmentCmd;
                    delete []pszEValue;
                    break;
                }
                case DST_COMMAND_MSG: {
215
                    errno_t ret = EOK;
M
mamingshuai 已提交
216
                    int nresult = 0;
217 218 219 220
                    ret = memset_s(returnValue, sizeof(returnValue), 0, MAX_BUFF_LEN);
                    if (ret != EOK) {
                        return -1;
                    }
M
mamingshuai 已提交
221 222 223 224 225 226 227
                    auto pclinereturn = reinterpret_cast<DistributedMsg *>(returnValue);
                    pclinereturn->no = pcline->no;
                    pclinereturn->cmdTestType = htons(DST_COMMAND_MSG);
                    pclinereturn->len = MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN;
                    std::string resultcmd = pclinereturn->alignmentCmd;
                    nresult = OnProcessMsg(pcline->alignmentCmd, pcline->len, resultcmd, pclinereturn->len);
                    if (resultcmd == "") {
M
mamingshuai 已提交
228 229 230 231
                        resultcmd = "agent return message";
                    }
                    if (strcpy_s(pclinereturn->alignmentCmd, pclinereturn->len, resultcmd.c_str()) != EOK) {
                        return -1;
M
mamingshuai 已提交
232 233
                    }
                    pclinereturn->len = htons(nresult);
M
mamingshuai 已提交
234
                    send(clientSockFd_, pclinereturn, static_cast<size_t>(nresult + DST_COMMAND_HEAD_LEN), 0);
M
mamingshuai 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
                    break;
                }
                case DST_COMMAND_NOTIFY: {
                    OnNotifyImf(pcline);
                    break;
                }
                case DST_COMMAND_END:
                    mbStop_ = true;
                    break;
                default:
                    break;
            }
        }
        if (EAGAIN == errno) {
            continue;
        }
    }
    return 0;
}

void DistributedAgent::OnNotifyImf(DistributedMsg *pcline)
{
    char alignmentCmd[DistributedAgent::CMD_LENGTH];
    char szMsg[MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH];
    int cmdNo = 0;
260 261 262 263 264
    errno_t ret = EOK;
    ret = memset_s(alignmentCmd, sizeof(alignmentCmd), 0, DistributedAgent::CMD_LENGTH);
    if (ret != EOK) {
        return;
    }
M
mamingshuai 已提交
265 266 267
    (void)memset_s(szMsg,
        MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH, 0,
        MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH);
M
mamingshuai 已提交
268 269 270 271 272 273 274 275
    for (cmdNo = 0; cmdNo < DistributedAgent::CMD_LENGTH; cmdNo++) {
        if (pcline->alignmentCmd[cmdNo] == ':') {
            break;
        }
    }
    if (cmdNo >= DistributedAgent::CMD_LENGTH) {
        HiLog::Error(DistributedAgent::LABEL, "error command.\n");
    }  else {
M
mamingshuai 已提交
276
        errno_t ret = EOK;
277
        ret = memcpy_s(alignmentCmd, sizeof(alignmentCmd), pcline->alignmentCmd, cmdNo);
M
mamingshuai 已提交
278 279 280 281 282 283 284 285 286
        if (ret != EOK) {
            return;
        }
        ret = memcpy_s(szMsg, MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH,
            pcline->alignmentCmd + cmdNo + 1, pcline->len - cmdNo - 1);
        if (ret != EOK) {
            return;
        }
        OnNotify(alignmentCmd, szMsg, pcline->len - cmdNo);
M
mamingshuai 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299
    }
}

/*
 * function : when testcase need this device to do something, or tell device something, agent process it.
 *     this interface is opened for user.
 * param :
 *     strMsg: message from testcase .
 *     len : length of strMsg
 *     strReturnValue: return message buffer
 *     returnbuflen: max length of strReturnValue
 * return : real length of strReturnValue filled
 */
300
int DistributedAgent::OnProcessMsg(const std::string &strMsg, int msgLen,
M
mamingshuai 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    std::string &strReturnValue, int returnBufLen)
{
    // default test code
    std::string returnStr = "agent return message";
    int returnLen = returnStr.size();
    if (strReturnValue != "" && returnLen <= returnBufLen) {
        strReturnValue = returnStr;
    }
    return returnLen;
}

/*
 * function : execute command from testcase.
 * param :
 *     strCommand: command from testcase ,format is : command_string:args_string.
 *     cmdLen : length of strCommand
 *     strExpectValue: expectvalue string
 *     expectvaluelen: length of strExpectValue
 * return : return integer value, default 0 is returned.
 */
int DistributedAgent::OnProcessCmd(const std::string &strCommand, int cmdLen,
    const std::string &strExpectValue, int expectValueLen)
{
    int nresult = 0;
    char alignmentCmd[DistributedAgent::CMD_LENGTH];
    char szArgs[MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH];
    int cmdNo = 0;
328 329 330 331 332
    errno_t ret = EOK;
    ret = memset_s(alignmentCmd, sizeof(alignmentCmd), 0, DistributedAgent::CMD_LENGTH);
    if (ret != EOK) {
        return -1;
    }
M
mamingshuai 已提交
333 334 335
    (void)memset_s(szArgs,
        MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH, 0,
        MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH);
M
mamingshuai 已提交
336 337 338 339 340 341 342 343 344 345
    for (cmdNo = 0; cmdNo < DistributedAgent::CMD_LENGTH; cmdNo++) {
        if (strCommand[cmdNo] == ':') {
            break;
        }
    }
    if (cmdNo >= DistributedAgent::CMD_LENGTH) {
        HiLog::Error(DistributedAgent::LABEL, "error command.\n");
        nresult = -1;
        return nresult;
    }
M
mamingshuai 已提交
346 347

    errno_t ret = EOK;
348
    ret = memcpy_s(alignmentCmd, sizeof(alignmentCmd), strCommand.c_str(), cmdNo);
M
mamingshuai 已提交
349 350 351 352 353 354 355 356 357 358 359
    if (ret != EOK) {
        return -1;
    }
    ret = memcpy_s(szArgs,
        MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH,
        strCommand.c_str() + cmdNo + 1,
        cmdLen - cmdNo - 1);
    if (ret != EOK) {
        return -1;
    }

M
mamingshuai 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    nresult = OnProcessCmd(alignmentCmd, cmdNo, szArgs, cmdLen - cmdNo, strExpectValue, expectValueLen);
    return nresult;
}

int DistributedAgent::OnProcessCmd(const std::string &strCommand, int cmdLen, const std::string &strArgs,
    int argsLen, const std::string &strExpectValue, int expectValueLen)
{
    int nresult = 0;
    HiLog::Info(DistributedAgent::LABEL, "this is a agent.\n");
    if (static_cast<int>(strExpectValue.size()) > expectValueLen ||
        static_cast<int>(strCommand.size()) > cmdLen ||
        static_cast<int>(strArgs.size()) > argsLen) {
        return -1;
    }
    return nresult;
}

int DistributedAgent::Start(std::string cfgFile)
{
    std::string agentPort;
    agentCfg_.OpenCfg(cfgFile);
    if (!agentCfg_.GetCfgVal("agentport", agentPort)) {
        HiLog::Error(DistributedAgent::LABEL, "agent can not get port.\n");
        return 0;
    }
    if (sscanf_s(agentPort.c_str(), "%d", &agentPort_) < 1) {
        agentPort_ = DEFAULT_AGENT_PORT;
    }
    return InitAgentServer();
}

void DistributedAgent::Join()
{
    if (mpthCmdProcess_ != nullptr) {
        mpthCmdProcess_->join();
    }
}

int DistributedAgent::OnNotify(const std::string &notifyType, const std::string &msg, int msgLen)
{
    if (strcmp(notifyType.c_str(), "testcasename")) {
        HiLog::Error(DistributedAgent::LABEL, "onNotify: %s.\n", msg.c_str());
    }
    if (msgLen < 0) {
        HiLog::Error(DistributedAgent::LABEL, "msgLen < 0.");
    }
    return 0;
}

int DistributedAgent::Stop()
{
    return 0;
}
} // namespace DistributeSystemTest
} // namespace OHOS