server.cpp 12.0 KB
Newer Older
羽飞's avatar
羽飞 已提交
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
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
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 Longda on 2021
//

#include "net/server.h"

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
羽飞's avatar
羽飞 已提交
29
#include <event2/thread.h>
羽飞's avatar
羽飞 已提交
30 31 32

#include "common/lang/mutex.h"
#include "common/log/log.h"
羽飞's avatar
羽飞 已提交
33
#include "common/io/io.h"
羽飞's avatar
羽飞 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include "common/seda/seda_config.h"
#include "event/session_event.h"
#include "session/session.h"
#include "ini_setting.h"
#include <common/metrics/metrics_registry.h>

using namespace common;
static const std::string READ_SOCKET_METRIC_TAG = "SessionStage.readsocket";
static const std::string WRITE_SOCKET_METRIC_TAG = "SessionStage.writesocket";

Stage *Server::session_stage_ = nullptr;
common::SimpleTimer *Server::read_socket_metric_ = nullptr;
common::SimpleTimer *Server::write_socket_metric_ = nullptr;

48 49
ServerParam::ServerParam()
{
羽飞's avatar
羽飞 已提交
50 51 52 53 54
  listen_addr = INADDR_ANY;
  max_connection_num = MAX_CONNECTION_NUM_DEFAULT;
  port = PORT_DEFAULT;
}

55 56
Server::Server(ServerParam input_server_param) : server_param_(input_server_param)
{
羽飞's avatar
羽飞 已提交
57 58 59 60 61 62
  started_ = false;
  server_socket_ = 0;
  event_base_ = nullptr;
  listen_ev_ = nullptr;
}

63 64
Server::~Server()
{
羽飞's avatar
羽飞 已提交
65 66 67 68 69
  if (started_) {
    shutdown();
  }
}

70 71
void Server::init()
{
羽飞's avatar
羽飞 已提交
72 73 74 75 76 77 78 79 80 81 82
  session_stage_ = get_seda_config()->get_stage(SESSION_STAGE_NAME);

  MetricsRegistry &metricsRegistry = get_metrics_registry();
  if (Server::read_socket_metric_ == nullptr) {
    Server::read_socket_metric_ = new SimpleTimer();
    metricsRegistry.register_metric(READ_SOCKET_METRIC_TAG, Server::read_socket_metric_);
  }

  if (Server::write_socket_metric_ == nullptr) {
    Server::write_socket_metric_ = new SimpleTimer();
    metricsRegistry.register_metric(WRITE_SOCKET_METRIC_TAG, Server::write_socket_metric_);
83
  }
羽飞's avatar
羽飞 已提交
84 85
}

86 87
int Server::set_non_block(int fd)
{
羽飞's avatar
羽飞 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

  int flags = fcntl(fd, F_GETFL);
  if (flags == -1) {
    LOG_INFO("Failed to get flags of fd :%d. ", fd);
    return -1;
  }

  flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  if (flags == -1) {
    LOG_INFO("Failed to set non-block flags of fd :%d. ", fd);
    return -1;
  }
  return 0;
}

103 104
void Server::close_connection(ConnectionContext *client_context)
{
羽飞's avatar
羽飞 已提交
105 106 107 108 109 110 111 112
  LOG_INFO("Close connection of %s.", client_context->addr);
  event_del(&client_context->read_event);
  ::close(client_context->fd);
  delete client_context->session;
  client_context->session = nullptr;
  delete client_context;
}

113 114
void Server::recv(int fd, short ev, void *arg)
{
羽飞's avatar
羽飞 已提交
115
  ConnectionContext *client = (ConnectionContext *)arg;
116
  // Server::send(sev->getClient(), sev->getRequestBuf(), strlen(sev->getRequestBuf()));
羽飞's avatar
羽飞 已提交
117 118 119 120 121 122 123 124

  int data_len = 0;
  int read_len = 0;
  int buf_size = sizeof(client->buf);
  memset(client->buf, 0, buf_size);

  TimerStat timer_stat(*read_socket_metric_);
  MUTEX_LOCK(&client->mutex);
125
  // 持续接收消息,直到遇到'\0'。将'\0'遇到的后续数据直接丢弃没有处理,因为目前仅支持一收一发的模式
羽飞's avatar
羽飞 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  while (true) {
    read_len = ::read(client->fd, client->buf + data_len, buf_size - data_len);
    if (read_len < 0) {
      if (errno == EAGAIN) {
        continue;
      }
      break;
    }
    if (read_len == 0) {
      break;
    }

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

    bool msg_end = false;
144
    for (int i = 0; i < read_len; i++) {
羽飞's avatar
羽飞 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
      if (client->buf[data_len + i] == 0) {
        data_len += i + 1;
        msg_end = true;
        break;
      }
    }

    if (msg_end) {
      break;
    }

    data_len += read_len;
  }

  MUTEX_UNLOCK(&client->mutex);
  timer_stat.end();

162
  if (data_len > buf_size) {
羽飞's avatar
羽飞 已提交
163 164 165 166 167 168 169 170 171
    LOG_WARN("The length of sql exceeds the limitation %d\n", buf_size);
    close_connection(client);
    return;
  }
  if (read_len == 0) {
    LOG_INFO("The peer has been closed %s\n", client->addr);
    close_connection(client);
    return;
  } else if (read_len < 0) {
172
    LOG_ERROR("Failed to read socket of %s, %s\n", client->addr, strerror(errno));
羽飞's avatar
羽飞 已提交
173 174 175 176 177 178 179 180 181 182
    close_connection(client);
    return;
  }

  LOG_INFO("receive command(size=%d): %s", data_len, client->buf);
  SessionEvent *sev = new SessionEvent(client);
  session_stage_->add_event(sev);
}

// 这个函数仅负责发送数据,至于是否是一个完整的消息,由调用者控制
183 184
int Server::send(ConnectionContext *client, const char *buf, int data_len)
{
羽飞's avatar
羽飞 已提交
185 186 187 188 189 190 191
  if (buf == nullptr || data_len == 0) {
    return 0;
  }

  TimerStat writeStat(*write_socket_metric_);

  MUTEX_LOCK(&client->mutex);
羽飞's avatar
羽飞 已提交
192 193 194 195 196 197 198
  int ret = common::writen(client->fd, buf, data_len);
  if (ret < 0) {
    LOG_ERROR("Failed to send data back to client. ret=%d, error=%s", ret, strerror(errno));
    MUTEX_UNLOCK(&client->mutex);

    close_connection(client);
    return -STATUS_FAILED_NETWORK;
羽飞's avatar
羽飞 已提交
199 200 201 202 203 204
  }

  MUTEX_UNLOCK(&client->mutex);
  return 0;
}

205 206
void Server::accept(int fd, short ev, void *arg)
{
羽飞's avatar
羽飞 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
  Server *instance = (Server *)arg;
  struct sockaddr_in addr;
  socklen_t addrlen = sizeof(addr);

  int ret = 0;

  int client_fd = ::accept(fd, (struct sockaddr *)&addr, &addrlen);
  if (client_fd < 0) {
    LOG_ERROR("Failed to accept client's connection, %s", strerror(errno));
    return;
  }

  char ip_addr[24];
  if (inet_ntop(AF_INET, &addr.sin_addr, ip_addr, sizeof(ip_addr)) == nullptr) {
    LOG_ERROR("Failed to get ip address of client, %s", strerror(errno));
    ::close(client_fd);
    return;
  }
  std::stringstream address;
  address << ip_addr << ":" << addr.sin_port;
  std::string addr_str = address.str();

  ret = instance->set_non_block(client_fd);
  if (ret < 0) {
231
    LOG_ERROR("Failed to set socket of %s as non blocking, %s", addr_str.c_str(), strerror(errno));
羽飞's avatar
羽飞 已提交
232 233 234 235 236 237 238 239 240
    ::close(client_fd);
    return;
  }

  if (!instance->server_param_.use_unix_socket) {
    // unix socket不支持设置NODELAY
    int yes = 1;
    ret = setsockopt(client_fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
    if (ret < 0) {
241
      LOG_ERROR("Failed to set socket of %s option as : TCP_NODELAY %s\n", addr_str.c_str(), strerror(errno));
羽飞's avatar
羽飞 已提交
242 243 244 245 246 247 248 249 250 251 252
      ::close(client_fd);
      return;
    }
  }

  ConnectionContext *client_context = new ConnectionContext();
  memset(client_context, 0, sizeof(ConnectionContext));
  client_context->fd = client_fd;
  snprintf(client_context->addr, sizeof(client_context->addr), "%s", addr_str.c_str());
  pthread_mutex_init(&client_context->mutex, nullptr);

253
  event_set(&client_context->read_event, client_context->fd, EV_READ | EV_PERSIST, recv, client_context);
羽飞's avatar
羽飞 已提交
254 255 256 257

  ret = event_base_set(instance->event_base_, &client_context->read_event);
  if (ret < 0) {
    LOG_ERROR(
258
        "Failed to do event_base_set for read event of %s into libevent, %s", client_context->addr, strerror(errno));
羽飞's avatar
羽飞 已提交
259 260 261 262 263 264 265
    delete client_context;
    ::close(instance->server_socket_);
    return;
  }

  ret = event_add(&client_context->read_event, nullptr);
  if (ret < 0) {
266
    LOG_ERROR("Failed to event_add for read event of %s into libevent, %s", client_context->addr, strerror(errno));
羽飞's avatar
羽飞 已提交
267 268 269 270 271 272 273 274 275
    delete client_context;
    ::close(instance->server_socket_);
    return;
  }

  client_context->session = new Session(Session::default_session());
  LOG_INFO("Accepted connection from %s\n", client_context->addr);
}

276 277
int Server::start()
{
羽飞's avatar
羽飞 已提交
278 279 280 281 282 283
  if (server_param_.use_unix_socket) {
    return start_unix_socket_server();
  } else {
    return start_tcp_server();
  }
}
284 285
int Server::start_tcp_server()
{
羽飞's avatar
羽飞 已提交
286 287 288 289 290 291 292 293 294 295 296 297
  int ret = 0;
  struct sockaddr_in sa;

  server_socket_ = socket(AF_INET, SOCK_STREAM, 0);
  if (server_socket_ < 0) {
    LOG_ERROR("socket(): can not create server socket: %s.", strerror(errno));
    return -1;
  }

  int yes = 1;
  ret = setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  if (ret < 0) {
298
    LOG_ERROR("Failed to set socket option of reuse address: %s.", strerror(errno));
羽飞's avatar
羽飞 已提交
299 300 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 328 329 330 331 332 333 334 335 336 337 338
    ::close(server_socket_);
    return -1;
  }

  ret = set_non_block(server_socket_);
  if (ret < 0) {
    LOG_ERROR("Failed to set socket option non-blocking:%s. ", strerror(errno));
    ::close(server_socket_);
    return -1;
  }

  memset(&sa, 0, sizeof(sa));
  sa.sin_family = AF_INET;
  sa.sin_port = htons(server_param_.port);
  sa.sin_addr.s_addr = htonl(server_param_.listen_addr);

  ret = bind(server_socket_, (struct sockaddr *)&sa, sizeof(sa));
  if (ret < 0) {
    LOG_ERROR("bind(): can not bind server socket, %s", strerror(errno));
    ::close(server_socket_);
    return -1;
  }

  ret = listen(server_socket_, server_param_.max_connection_num);
  if (ret < 0) {
    LOG_ERROR("listen(): can not listen server socket, %s", strerror(errno));
    ::close(server_socket_);
    return -1;
  }
  LOG_INFO("Listen on port %d", server_param_.port);

  listen_ev_ = event_new(event_base_, server_socket_, EV_READ | EV_PERSIST, accept, this);
  if (listen_ev_ == nullptr) {
    LOG_ERROR("Failed to create listen event, %s.", strerror(errno));
    ::close(server_socket_);
    return -1;
  }

  ret = event_add(listen_ev_, nullptr);
  if (ret < 0) {
339
    LOG_ERROR("event_add(): can not add accept event into libevent, %s", strerror(errno));
羽飞's avatar
羽飞 已提交
340 341 342 343 344 345 346 347 348
    ::close(server_socket_);
    return -1;
  }

  started_ = true;
  LOG_INFO("Observer start success");
  return 0;
}

349 350
int Server::start_unix_socket_server()
{
羽飞's avatar
羽飞 已提交
351 352 353 354 355 356 357 358 359 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

  int ret = 0;
  server_socket_ = socket(PF_UNIX, SOCK_STREAM, 0);
  if (server_socket_ < 0) {
    LOG_ERROR("socket(): can not create unix socket: %s.", strerror(errno));
    return -1;
  }

  ret = set_non_block(server_socket_);
  if (ret < 0) {
    LOG_ERROR("Failed to set socket option non-blocking:%s. ", strerror(errno));
    ::close(server_socket_);
    return -1;
  }

  unlink(server_param_.unix_socket_path.c_str());

  struct sockaddr_un sockaddr;
  memset(&sockaddr, 0, sizeof(sockaddr));
  sockaddr.sun_family = PF_UNIX;
  snprintf(sockaddr.sun_path, sizeof(sockaddr.sun_path), "%s", server_param_.unix_socket_path.c_str());

  ret = bind(server_socket_, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
  if (ret < 0) {
    LOG_ERROR("bind(): can not bind server socket(path=%s), %s", sockaddr.sun_path, strerror(errno));
    ::close(server_socket_);
    return -1;
  }

  ret = listen(server_socket_, server_param_.max_connection_num);
  if (ret < 0) {
    LOG_ERROR("listen(): can not listen server socket, %s", strerror(errno));
    ::close(server_socket_);
    return -1;
  }
  LOG_INFO("Listen on unix socket: %s", sockaddr.sun_path);

  listen_ev_ = event_new(event_base_, server_socket_, EV_READ | EV_PERSIST, accept, this);
  if (listen_ev_ == nullptr) {
    LOG_ERROR("Failed to create listen event, %s.", strerror(errno));
    ::close(server_socket_);
    return -1;
  }

  ret = event_add(listen_ev_, nullptr);
  if (ret < 0) {
397
    LOG_ERROR("event_add(): can not add accept event into libevent, %s", strerror(errno));
羽飞's avatar
羽飞 已提交
398 399 400 401 402 403 404 405 406
    ::close(server_socket_);
    return -1;
  }

  started_ = true;
  LOG_INFO("Observer start success");
  return 0;
}

407 408
int Server::serve()
{
羽飞's avatar
羽飞 已提交
409
  evthread_use_pthreads();
羽飞's avatar
羽飞 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  event_base_ = event_base_new();
  if (event_base_ == nullptr) {
    LOG_ERROR("Failed to create event base, %s.", strerror(errno));
    exit(-1);
  }

  int retval = start();
  if (retval == -1) {
    LOG_PANIC("Failed to start network");
    exit(-1);
  }

  event_base_dispatch(event_base_);

  if (listen_ev_ != nullptr) {
    event_del(listen_ev_);
    event_free(listen_ev_);
    listen_ev_ = nullptr;
  }

  if (event_base_ != nullptr) {
    event_base_free(event_base_);
    event_base_ = nullptr;
  }

  started_ = false;
  LOG_INFO("Server quit");
羽飞's avatar
羽飞 已提交
437 438 439 440 441 442 443 444 445 446 447 448
  return 0;
}

void Server::shutdown()
{
  LOG_INFO("Server shutting down");

  // cleanup
  if (event_base_ != nullptr && started_) {
    started_ = false;
    event_base_loopexit(event_base_, nullptr);
  }
羽飞's avatar
羽飞 已提交
449
}