server.cpp 10.4 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 45 46 47 48
#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;

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

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

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

71 72
void Server::init()
{
羽飞's avatar
羽飞 已提交
73 74 75 76 77 78 79 80 81 82 83
  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_);
84
  }
羽飞's avatar
羽飞 已提交
85 86
}

87 88
int Server::set_non_block(int fd)
{
羽飞's avatar
羽飞 已提交
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;
}

羽飞's avatar
羽飞 已提交
103
void Server::close_connection(Communicator *communicator)
104
{
羽飞's avatar
羽飞 已提交
105 106 107
  LOG_INFO("Close connection of %s.", communicator->addr());
  event_del(&communicator->read_event());
  delete communicator;
羽飞's avatar
羽飞 已提交
108 109
}

110 111
void Server::recv(int fd, short ev, void *arg)
{
羽飞's avatar
羽飞 已提交
112
  Communicator *comm = (Communicator *)arg;
羽飞's avatar
羽飞 已提交
113

羽飞's avatar
羽飞 已提交
114 115 116 117
  SessionEvent *event = nullptr;
  RC rc = comm->read_event(event);
  if (rc != RC::SUCCESS) {
    close_connection(comm);
羽飞's avatar
羽飞 已提交
118 119
    return;
  }
羽飞's avatar
羽飞 已提交
120 121 122

  if (event == nullptr) {
    LOG_WARN("event is null while read event return success");
羽飞's avatar
羽飞 已提交
123 124
    return;
  }
羽飞's avatar
羽飞 已提交
125
  session_stage_->add_event(event);
羽飞's avatar
羽飞 已提交
126 127
}

羽飞's avatar
羽飞 已提交
128
#if 0
羽飞's avatar
羽飞 已提交
129
// 这个函数仅负责发送数据,至于是否是一个完整的消息,由调用者控制
羽飞's avatar
羽飞 已提交
130
int Server::send( *client, const char *buf, int data_len)
131
{
羽飞's avatar
羽飞 已提交
132 133 134 135 136 137
  if (buf == nullptr || data_len == 0) {
    return 0;
  }

  TimerStat writeStat(*write_socket_metric_);

羽飞's avatar
羽飞 已提交
138 139 140 141 142 143 144
  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
羽飞 已提交
145 146 147 148
  }

  return 0;
}
羽飞's avatar
羽飞 已提交
149
#endif
羽飞's avatar
羽飞 已提交
150

151 152
void Server::accept(int fd, short ev, void *arg)
{
羽飞's avatar
羽飞 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  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) {
177
    LOG_ERROR("Failed to set socket of %s as non blocking, %s", addr_str.c_str(), strerror(errno));
羽飞's avatar
羽飞 已提交
178 179 180 181 182 183 184 185 186
    ::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) {
187
      LOG_ERROR("Failed to set socket of %s option as : TCP_NODELAY %s\n", addr_str.c_str(), strerror(errno));
羽飞's avatar
羽飞 已提交
188 189 190 191 192
      ::close(client_fd);
      return;
    }
  }

羽飞's avatar
羽飞 已提交
193 194 195 196 197 198 199
  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
羽飞 已提交
200

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

羽飞's avatar
羽飞 已提交
203
  ret = event_base_set(instance->event_base_, &communicator->read_event());
羽飞's avatar
羽飞 已提交
204
  if (ret < 0) {
L
Longda Feng 已提交
205 206
    LOG_ERROR(
        "Failed to do event_base_set for read event of %s into libevent, %s", communicator->addr(), strerror(errno));
羽飞's avatar
羽飞 已提交
207
    delete communicator;
羽飞's avatar
羽飞 已提交
208 209 210
    return;
  }

羽飞's avatar
羽飞 已提交
211
  ret = event_add(&communicator->read_event(), nullptr);
羽飞's avatar
羽飞 已提交
212
  if (ret < 0) {
羽飞's avatar
羽飞 已提交
213 214
    LOG_ERROR("Failed to event_add for read event of %s into libevent, %s", communicator->addr(), strerror(errno));
    delete communicator;
羽飞's avatar
羽飞 已提交
215 216 217
    return;
  }

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

221 222
int Server::start()
{
羽飞's avatar
羽飞 已提交
223 224 225 226 227 228
  if (server_param_.use_unix_socket) {
    return start_unix_socket_server();
  } else {
    return start_tcp_server();
  }
}
229 230
int Server::start_tcp_server()
{
羽飞's avatar
羽飞 已提交
231 232 233 234 235 236 237 238 239 240 241 242
  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) {
243
    LOG_ERROR("Failed to set socket option of reuse address: %s.", strerror(errno));
羽飞's avatar
羽飞 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    ::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
羽飞 已提交
260
  ret = ::bind(server_socket_, (struct sockaddr *)&sa, sizeof(sa));
羽飞's avatar
羽飞 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  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) {
284
    LOG_ERROR("event_add(): can not add accept event into libevent, %s", strerror(errno));
羽飞's avatar
羽飞 已提交
285 286 287 288 289 290 291 292 293
    ::close(server_socket_);
    return -1;
  }

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

294 295
int Server::start_unix_socket_server()
{
羽飞's avatar
羽飞 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

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

羽飞's avatar
羽飞 已提交
318
  ret = ::bind(server_socket_, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
羽飞's avatar
羽飞 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  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) {
342
    LOG_ERROR("event_add(): can not add accept event into libevent, %s", strerror(errno));
羽飞's avatar
羽飞 已提交
343 344 345 346 347 348 349 350 351
    ::close(server_socket_);
    return -1;
  }

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

352 353
int Server::serve()
{
羽飞's avatar
羽飞 已提交
354
  evthread_use_pthreads();
羽飞's avatar
羽飞 已提交
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
  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
羽飞 已提交
382 383 384 385 386 387 388 389 390 391 392 393
  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
羽飞 已提交
394
}