server.cpp 10.0 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
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
#include "common/seda/seda_config.h"
#include "event/session_event.h"
#include "session/session.h"
羽飞's avatar
羽飞 已提交
37
#include "common/ini_setting.h"
羽飞's avatar
羽飞 已提交
38
#include "net/communicator.h"
羽飞's avatar
羽飞 已提交
39 40 41 42 43 44
#include <common/metrics/metrics_registry.h>

using namespace common;

Stage *Server::session_stage_ = nullptr;

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

52 53
Server::Server(ServerParam input_server_param) : server_param_(input_server_param)
{
羽飞's avatar
羽飞 已提交
54 55
}

56 57
Server::~Server()
{
羽飞's avatar
羽飞 已提交
58 59 60 61 62
  if (started_) {
    shutdown();
  }
}

63 64
void Server::init()
{
羽飞's avatar
羽飞 已提交
65 66 67
  session_stage_ = get_seda_config()->get_stage(SESSION_STAGE_NAME);
}

68 69
int Server::set_non_block(int fd)
{
羽飞's avatar
羽飞 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83
  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;
}

羽飞's avatar
羽飞 已提交
84
void Server::close_connection(Communicator *communicator)
85
{
羽飞's avatar
羽飞 已提交
86 87 88
  LOG_INFO("Close connection of %s.", communicator->addr());
  event_del(&communicator->read_event());
  delete communicator;
羽飞's avatar
羽飞 已提交
89 90
}

91 92
void Server::recv(int fd, short ev, void *arg)
{
羽飞's avatar
羽飞 已提交
93
  Communicator *comm = (Communicator *)arg;
羽飞's avatar
羽飞 已提交
94

羽飞's avatar
羽飞 已提交
95 96 97 98
  SessionEvent *event = nullptr;
  RC rc = comm->read_event(event);
  if (rc != RC::SUCCESS) {
    close_connection(comm);
羽飞's avatar
羽飞 已提交
99 100
    return;
  }
羽飞's avatar
羽飞 已提交
101 102 103

  if (event == nullptr) {
    LOG_WARN("event is null while read event return success");
羽飞's avatar
羽飞 已提交
104 105
    return;
  }
羽飞's avatar
羽飞 已提交
106
  session_stage_->add_event(event);
羽飞's avatar
羽飞 已提交
107 108
}

109 110
void Server::accept(int fd, short ev, void *arg)
{
羽飞's avatar
羽飞 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  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) {
135
    LOG_ERROR("Failed to set socket of %s as non blocking, %s", addr_str.c_str(), strerror(errno));
羽飞's avatar
羽飞 已提交
136 137 138 139 140 141 142 143 144
    ::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) {
145
      LOG_ERROR("Failed to set socket of %s option as : TCP_NODELAY %s\n", addr_str.c_str(), strerror(errno));
羽飞's avatar
羽飞 已提交
146 147 148 149 150
      ::close(client_fd);
      return;
    }
  }

羽飞's avatar
羽飞 已提交
151 152 153 154 155 156 157
  Communicator *communicator = instance->communicator_factory_.create(instance->server_param_.protocol);
  RC rc = communicator->init(client_fd, new Session(Session::default_session()), addr_str);
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to init communicator. rc=%s", strrc(rc));
    delete communicator;
    return;
  }
羽飞's avatar
羽飞 已提交
158

羽飞's avatar
羽飞 已提交
159
  event_set(&communicator->read_event(), client_fd, EV_READ | EV_PERSIST, recv, communicator);
羽飞's avatar
羽飞 已提交
160

羽飞's avatar
羽飞 已提交
161
  ret = event_base_set(instance->event_base_, &communicator->read_event());
羽飞's avatar
羽飞 已提交
162
  if (ret < 0) {
163 164
    LOG_ERROR("Failed to do event_base_set for read event of %s into libevent, %s", 
              communicator->addr(), strerror(errno));
羽飞's avatar
羽飞 已提交
165
    delete communicator;
羽飞's avatar
羽飞 已提交
166 167 168
    return;
  }

羽飞's avatar
羽飞 已提交
169
  ret = event_add(&communicator->read_event(), nullptr);
羽飞's avatar
羽飞 已提交
170
  if (ret < 0) {
羽飞's avatar
羽飞 已提交
171 172
    LOG_ERROR("Failed to event_add for read event of %s into libevent, %s", communicator->addr(), strerror(errno));
    delete communicator;
羽飞's avatar
羽飞 已提交
173 174 175
    return;
  }

羽飞's avatar
羽飞 已提交
176
  LOG_INFO("Accepted connection from %s\n", communicator->addr());
羽飞's avatar
羽飞 已提交
177 178
}

179 180
int Server::start()
{
181 182 183
  if (server_param_.use_std_io) {
    return start_stdin_server();
  } else if (server_param_.use_unix_socket) {
羽飞's avatar
羽飞 已提交
184 185 186 187 188
    return start_unix_socket_server();
  } else {
    return start_tcp_server();
  }
}
189

190 191
int Server::start_tcp_server()
{
羽飞's avatar
羽飞 已提交
192 193 194 195 196 197 198 199 200 201 202 203
  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) {
204
    LOG_ERROR("Failed to set socket option of reuse address: %s.", strerror(errno));
羽飞's avatar
羽飞 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    ::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);

羽飞's avatar
羽飞 已提交
221
  ret = ::bind(server_socket_, (struct sockaddr *)&sa, sizeof(sa));
羽飞's avatar
羽飞 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  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) {
245
    LOG_ERROR("event_add(): can not add accept event into libevent, %s", strerror(errno));
羽飞's avatar
羽飞 已提交
246 247 248 249 250 251 252 253 254
    ::close(server_socket_);
    return -1;
  }

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

255 256
int Server::start_unix_socket_server()
{
羽飞's avatar
羽飞 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270
  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;
  }

271
  unlink(server_param_.unix_socket_path.c_str());  /// 如果不删除源文件,可能会导致bind失败
羽飞's avatar
羽飞 已提交
272 273 274 275 276 277

  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());

羽飞's avatar
羽飞 已提交
278
  ret = ::bind(server_socket_, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
羽飞's avatar
羽飞 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  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) {
302
    LOG_ERROR("event_add(): can not add accept event into libevent, %s", strerror(errno));
羽飞's avatar
羽飞 已提交
303 304 305 306 307 308 309 310 311
    ::close(server_socket_);
    return -1;
  }

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

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 339 340 341 342 343
int Server::start_stdin_server()
{
  Communicator *communicator = communicator_factory_.create(server_param_.protocol);
  RC rc = communicator->init(STDIN_FILENO, new Session(Session::default_session()), "stdin");
  if (OB_FAIL(rc)) {
    LOG_WARN("failed to init cli communicator. rc=%s", strrc(rc));
    return -1;
  }

  started_ = true;

  while (started_) {
    SessionEvent *event = nullptr;
    rc = communicator->read_event(event);
    if (OB_FAIL(rc)) {
      LOG_WARN("failed to read event. rc=%s", strrc(rc));
      return -1;
    }

    if (event == nullptr) {
      break;
    }

    /// 在当前线程立即处理对应的事件
    session_stage_->handle_event(event);
  }

  delete communicator;
  communicator = nullptr;
  return 0;
}

344 345
int Server::serve()
{
羽飞's avatar
羽飞 已提交
346
  evthread_use_pthreads();
羽飞's avatar
羽飞 已提交
347 348 349 350 351 352 353 354 355 356 357 358
  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);
  }

359 360 361
  if (!server_param_.use_std_io) {
    event_base_dispatch(event_base_);
  }
羽飞's avatar
羽飞 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375

  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
羽飞 已提交
376 377 378 379 380 381 382 383 384 385 386 387
  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
羽飞 已提交
388
}