communicator.cpp 8.1 KB
Newer Older
羽飞's avatar
羽飞 已提交
1
/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
羽飞's avatar
羽飞 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/11/17.
//

#include "net/communicator.h"
#include "net/mysql_communicator.h"
#include "sql/expr/tuple.h"
#include "event/session_event.h"
#include "common/lang/mutex.h"
#include "common/io/io.h"
#include "session/session.h"

RC Communicator::init(int fd, Session *session, const std::string &addr)
{
  fd_ = fd;
  session_ = session;
  addr_ = addr;
  return RC::SUCCESS;
}

Communicator::~Communicator()
{
  if (fd_ >= 0) {
    close(fd_);
    fd_ = -1;
  }
  if (session_ != nullptr) {
    delete session_;
    session_ = nullptr;
  }
}

/////////////////////////////////////////////////////////////////////////////////
RC PlainCommunicator::read_event(SessionEvent *&event)
{
  RC rc = RC::SUCCESS;

  event = nullptr;

  int data_len = 0;
  int read_len = 0;

  const int max_packet_size = 8192;
  std::vector<char> buf(max_packet_size);

  // 持续接收消息,直到遇到'\0'。将'\0'遇到的后续数据直接丢弃没有处理,因为目前仅支持一收一发的模式
  while (true) {
    read_len = ::read(fd_, buf.data() + data_len, max_packet_size - data_len);
    if (read_len < 0) {
      if (errno == EAGAIN) {
        continue;
      }
      break;
    }
    if (read_len == 0) {
      break;
    }

    if (read_len + data_len > max_packet_size) {
      data_len += read_len;
      break;
    }

    bool msg_end = false;
    for (int i = 0; i < read_len; i++) {
      if (buf[data_len + i] == 0) {
        data_len += i + 1;
        msg_end = true;
        break;
      }
    }

    if (msg_end) {
      break;
    }

    data_len += read_len;
  }

  if (data_len > max_packet_size) {
    LOG_WARN("The length of sql exceeds the limitation %d", max_packet_size);
    return RC::IOERR;
  }
  if (read_len == 0) {
    LOG_INFO("The peer has been closed %s\n", addr());
    return RC::IOERR;
  } else if (read_len < 0) {
    LOG_ERROR("Failed to read socket of %s, %s\n", addr(), strerror(errno));
    return RC::IOERR;
  }

  LOG_INFO("receive command(size=%d): %s", data_len, buf.data());
  event = new SessionEvent(this);
  event->set_query(std::string(buf.data()));
  return rc;
}

RC PlainCommunicator::write_state(SessionEvent *event, bool &need_disconnect)
{
  SqlResult *sql_result = event->sql_result();
  const int buf_size = 2048;
  char *buf = new char[buf_size];
  const std::string &state_string = sql_result->state_string();
  if (state_string.empty()) {
    const char *result = RC::SUCCESS == sql_result->return_code() ? "SUCCESS" : "FAILURE";
    snprintf(buf, buf_size, "%s\n", result);
  } else {
    snprintf(buf, buf_size, "%s > %s\n", strrc(sql_result->return_code()), state_string.c_str());
  }

  int ret = common::writen(fd_, buf, strlen(buf) + 1);
  if (ret != 0) {
    LOG_WARN("failed to send data to client. err=%s", strerror(errno));
    need_disconnect = true;
    delete[] buf;
    return RC::IOERR;
  }

  need_disconnect = false;
  delete[] buf;
  return RC::SUCCESS;
}

RC PlainCommunicator::write_result(SessionEvent *event, bool &need_disconnect)
{
  need_disconnect = true;
L
Longda Feng 已提交
137

羽飞's avatar
羽飞 已提交
138 139 140 141
  const char message_terminate = '\0';

  SqlResult *sql_result = event->sql_result();
  if (nullptr == sql_result) {
L
Longda Feng 已提交
142

羽飞's avatar
羽飞 已提交
143 144
    const char *response = "Unexpected error: no result";
    int len = strlen(response);
羽飞's avatar
羽飞 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

    int ret = common::writen(fd_, response, len);
    if (ret < 0) {
      LOG_ERROR("Failed to send data back to client. ret=%d, error=%s", ret, strerror(errno));

      return RC::IOERR;
    }
    ret = common::writen(fd_, &message_terminate, sizeof(message_terminate));
    if (ret < 0) {
      LOG_ERROR("Failed to send data back to client. ret=%d, error=%s", ret, strerror(errno));
      return RC::IOERR;
    }

    need_disconnect = false;
    return RC::SUCCESS;
  }

  if (RC::SUCCESS != sql_result->return_code() || !sql_result->has_operator()) {
    return write_state(event, need_disconnect);
  }

  RC rc = sql_result->open();
  if (rc != RC::SUCCESS) {
    sql_result->set_return_code(rc);
    return write_state(event, need_disconnect);
  }

  const TupleSchema &schema = sql_result->tuple_schema();
  const int cell_num = schema.cell_num();

  for (int i = 0; i < cell_num; i++) {
    const TupleCellSpec &spec = schema.cell_at(i);
    const char *alias = spec.alias();
    if (nullptr != alias || alias[0] != 0) {
      if (0 != i) {
        const char *delim = " | ";
        int ret = common::writen(fd_, delim, strlen(delim));
        if (ret != 0) {
          LOG_WARN("failed to send data to client. err=%s", strerror(errno));
          return RC::IOERR;
        }
      }

      int len = strlen(alias);
      int ret = common::writen(fd_, alias, len);
      if (ret != 0) {
        LOG_WARN("failed to send data to client. err=%s", strerror(errno));
羽飞's avatar
羽飞 已提交
192
        sql_result->close();
羽飞's avatar
羽飞 已提交
193 194 195 196 197 198 199 200 201 202
        return RC::IOERR;
      }
    }
  }

  if (cell_num > 0) {
    char newline = '\n';
    int ret = common::writen(fd_, &newline, 1);
    if (ret != 0) {
      LOG_WARN("failed to send data to client. err=%s", strerror(errno));
羽飞's avatar
羽飞 已提交
203
      sql_result->close();
羽飞's avatar
羽飞 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
      return RC::IOERR;
    }
  }

  rc = RC::SUCCESS;
  Tuple *tuple = nullptr;
  while (RC::SUCCESS == (rc = sql_result->next_tuple(tuple))) {
    assert(tuple != nullptr);

    int cell_num = tuple->cell_num();
    for (int i = 0; i < cell_num; i++) {
      if (i != 0) {
        const char *delim = " | ";
        int ret = common::writen(fd_, delim, strlen(delim));
        if (ret != 0) {
          LOG_WARN("failed to send data to client. err=%s", strerror(errno));
羽飞's avatar
羽飞 已提交
220
          sql_result->close();
羽飞's avatar
羽飞 已提交
221 222 223 224 225 226 227
          return RC::IOERR;
        }
      }

      TupleCell cell;
      rc = tuple->cell_at(i, cell);
      if (rc != RC::SUCCESS) {
羽飞's avatar
羽飞 已提交
228
        sql_result->close();
羽飞's avatar
羽飞 已提交
229 230 231 232 233 234 235 236 237
        return rc;
      }

      std::stringstream ss;
      cell.to_string(ss);
      std::string cell_str = ss.str();
      int ret = common::writen(fd_, cell_str.data(), cell_str.size());
      if (ret != RC::SUCCESS) {
        LOG_WARN("failed to send data to client. err=%s", strerror(errno));
羽飞's avatar
羽飞 已提交
238
        sql_result->close();
羽飞's avatar
羽飞 已提交
239 240 241 242 243 244 245 246
        return RC::IOERR;
      }
    }

    char newline = '\n';
    int ret = common::writen(fd_, &newline, 1);
    if (ret != 0) {
      LOG_WARN("failed to send data to client. err=%s", strerror(errno));
羽飞's avatar
羽飞 已提交
247
      sql_result->close();
羽飞's avatar
羽飞 已提交
248 249 250 251
      return RC::IOERR;
    }
  }

羽飞's avatar
羽飞 已提交
252
  if (rc == RC::RECORD_EOF) {
羽飞's avatar
羽飞 已提交
253
    rc = RC::SUCCESS;
羽飞's avatar
羽飞 已提交
254
  }
L
Longda Feng 已提交
255

羽飞's avatar
羽飞 已提交
256 257 258 259
  if (cell_num == 0) {
    // 除了select之外,其它的消息通常不会通过operator来返回结果,表头和行数据都是空的
    // 这里针对这种情况做特殊处理,当表头和行数据都是空的时候,就返回处理的结果
    // 可能是insert/delete等操作,不直接返回给客户端数据,这里把处理结果返回给客户端
羽飞's avatar
羽飞 已提交
260 261 262 263
    RC rc_close = sql_result->close();
    if (rc == RC::SUCCESS) {
      rc = rc_close;
    }
羽飞's avatar
羽飞 已提交
264 265 266 267
    sql_result->set_return_code(rc);
    return write_state(event, need_disconnect);
  } else {

羽飞's avatar
羽飞 已提交
268 269 270
    int ret = common::writen(fd_, &message_terminate, sizeof(message_terminate));
    if (ret < 0) {
      LOG_ERROR("Failed to send data back to client. ret=%d, error=%s", ret, strerror(errno));
羽飞's avatar
羽飞 已提交
271
      sql_result->close();
羽飞's avatar
羽飞 已提交
272 273 274 275 276
      return RC::IOERR;
    }

    need_disconnect = false;
  }
羽飞's avatar
羽飞 已提交
277 278 279 280 281

  RC rc_close = sql_result->close();
  if (rc == RC::SUCCESS) {
    rc = rc_close;
  }
羽飞's avatar
羽飞 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  return rc;
}

/////////////////////////////////////////////////////////////////////////////////

Communicator *CommunicatorFactory::create(CommunicateProtocol protocol)
{
  switch (protocol) {
    case CommunicateProtocol::PLAIN: {
      return new PlainCommunicator;
    } break;
    case CommunicateProtocol::MYSQL: {
      return new MysqlCommunicator;
    } break;
    default: {
      return nullptr;
    }
  }
}