tcp_store.cc 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// 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.

15 16
#include "paddle/fluid/distributed/store/tcp_store.h"

17 18 19 20 21 22
#include <chrono>
#include <iostream>
#include <thread>

#include "paddle/fluid/distributed/store/tcp_utils.h"
#include "paddle/fluid/platform/enforce.h"
23
#include "paddle/fluid/platform/flags.h"
24 25 26 27 28 29

namespace paddle {
namespace distributed {

namespace detail {

30
constexpr int INFTIME = 10000;  // 10 seconds
31

G
gongweibao 已提交
32 33 34 35 36
std::unique_ptr<MasterDaemon> MasterDaemon::start(SocketType socket,
                                                  int nranks,
                                                  int timeout) {
  VLOG(4) << ("begin to run start");
  return std::make_unique<MasterDaemon>(socket, nranks, timeout);
37 38
}

G
gongweibao 已提交
39 40 41
MasterDaemon::MasterDaemon(SocketType socket, int nranks, int timeout)
    : _listen_socket(socket), _nranks(nranks), _timeout(timeout) {
  InitControlFd();
42 43 44 45
  _background_thread = std::thread{&MasterDaemon::run, this};
}

MasterDaemon::~MasterDaemon() {
G
gongweibao 已提交
46 47
  VLOG(4) << ("begin to destruct MasterDaemon");
  StopByControlFd();
48 49 50 51 52
  _background_thread.join();
  tcputils::close_socket(_listen_socket);
  for (SocketType socket : _sockets) {
    tcputils::close_socket(socket);
  }
G
gongweibao 已提交
53
  CloseControlFd();
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
}

void MasterDaemon::_do_add(SocketType socket) {
  int64_t new_value{};
  std::string key = tcputils::receive_string(socket);
  new_value = tcputils::receive_value<int64_t>(socket);
  std::vector<uint8_t> old_value;
  auto it = _store.find(key);
  if (it != _store.end()) {
    old_value = it->second;
    char* buffer = reinterpret_cast<char*>(it->second.data());
    size_t len = old_value.size();
    new_value += std::stoll(std::string(buffer, len));
  }

  std::string new_value_str = std::to_string(new_value);
  _store[key] =
      std::vector<uint8_t>(new_value_str.begin(), new_value_str.end());
G
gongweibao 已提交
72 73
  VLOG(4) << "TCPStore: new value (" << new_value << ") for key (" << key
          << ") " << GetSockName(socket);
74 75 76
  tcputils::send_value<int64_t>(socket, new_value);
}

77 78
void MasterDaemon::_do_set(SocketType socket) {
  std::string key = tcputils::receive_string(socket);
G
gongweibao 已提交
79 80
  VLOG(4) << "MasterDaemon::_do_set key(" << key << ") " << GetSockName(socket);

81 82 83 84
  auto value = tcputils::receive_vector<uint8_t>(socket);
  _store[key] = value;
}

85 86
void MasterDaemon::_do_get(SocketType socket) {
  std::string key = tcputils::receive_string(socket);
G
gongweibao 已提交
87 88
  VLOG(4) << "MasterDaemon::_do_get key(" << key << ") " << GetSockName(socket);

89 90
  auto iter = _store.find(key);
  PADDLE_ENFORCE_NE(
G
gongweibao 已提交
91 92
      iter,
      _store.end(),
93 94 95 96 97
      platform::errors::InvalidArgument("Key %s not found in TCPStore.", key));
  std::vector<uint8_t> value = iter->second;
  tcputils::send_vector<uint8_t>(socket, value);
}

G
gongweibao 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
#ifndef _WIN32
void MasterDaemon::InitControlFd() {
  PADDLE_ENFORCE_NE(
      pipe(_control_fd.data()),
      -1,
      platform::errors::Fatal("failed to cread control pipe errno:%d", errno));
}
void MasterDaemon::CloseControlFd() {
  for (int fd : _control_fd) {
    if (fd != -1) {
      ::close(fd);
    }
  }
}
void MasterDaemon::StopByControlFd() {
  VLOG(4) << ("begin to run StopByControlFd");
  if (_control_fd[1] != -1) {
115 116 117 118
    PADDLE_ENFORCE_NE(::write(_control_fd[1], "\0", 1),
                      -1,
                      platform::errors::Fatal(
                          "failed to write control pipe errno:%d", errno));
G
gongweibao 已提交
119 120 121 122 123 124
    // close the write end of the pipe
    ::close(_control_fd[1]);
    _control_fd[1] = -1;
  }
}
#else
L
LiYuRio 已提交
125 126 127 128 129 130 131
void MasterDaemon::InitControlFd() {
  ghStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL);
  PADDLE_ENFORCE(ghStopEvent_,
                 platform::errors::Fatal("failed to cread control pipe"));
}
void MasterDaemon::CloseControlFd() { CloseHandle(ghStopEvent_); }
void MasterDaemon::StopByControlFd() { SetEvent(ghStopEvent_); }
G
gongweibao 已提交
132 133
#endif

134 135
void MasterDaemon::_do_wait(SocketType socket) {
  std::string key = tcputils::receive_string(socket);
G
gongweibao 已提交
136 137 138
  VLOG(4) << "MasterDaemon::_do_wait key(" << key << ") "
          << GetSockName(socket);

139 140 141 142 143 144 145 146 147 148
  auto iter = _store.find(key);
  auto reply = ReplyType::STOP_WAIT;
  if (iter == _store.end()) {
    reply = ReplyType::WAITING;
  }
  VLOG(3) << "TCPStore: wait reply (" << static_cast<int>(reply)
          << ") for key (" << key << ").";
  tcputils::send_value<ReplyType>(socket, reply);
}

G
gongweibao 已提交
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
void MasterDaemon::ProcessCommands(std::vector<struct pollfd>* p_fds) {
  std::vector<struct pollfd>& fds = *p_fds;
  // FIXME(gongwb): Don't loop all fds of set just the fds who have event.
#ifdef _WIN32
  // 0: listen socket, so loop from 1.
  for (size_t i = 1; i < fds.size(); i++) {
#else
  // 0: listen socket, 1:controller pipe, so loop from 2.
  for (size_t i = 2; i < fds.size(); i++) {
#endif
    try {
      if (fds[i].revents == 0) {
        continue;
      }

      Command command = tcputils::receive_value<Command>(fds[i].fd);
      VLOG(3) << "TCPStore: recv command: " << static_cast<int>(command) << ".";

      switch (command) {
        case Command::ADD:
          _do_add(fds[i].fd);
          break;
        case Command::GET:
          _do_get(fds[i].fd);
          break;
        case Command::SET:
          _do_set(fds[i].fd);
          break;
        case Command::WAIT:
          _do_wait(fds[i].fd);
          break;
        default:
          LOG(WARNING) << "Unknown command: " << static_cast<int>(command)
                       << " from addr info:" << GetSockName(fds[i].fd);
      }
    } catch (const std::exception& ex) {
      tcputils::close_socket(fds[i].fd);
186
      fds.erase(fds.begin() + i);
G
gongweibao 已提交
187 188 189 190 191 192 193 194 195 196 197
#ifdef _WIN32
      _sockets.erase(_sockets.begin() + i - 1);
#else
      _sockets.erase(_sockets.begin() + i - 2);
#endif

      VLOG(3) << "Meet some exceptions during run:" << ex.what();
    }
  }
}

198 199 200 201 202 203
void MasterDaemon::run() {
  std::vector<struct pollfd> fds;
#ifdef _WIN32
  fds.push_back({_listen_socket, POLLIN});
#else
  fds.push_back({.fd = _listen_socket, .events = POLLIN, .revents = 0});
G
gongweibao 已提交
204 205
  fds.push_back(
      {.fd = _control_fd[0], .events = POLLIN | POLLHUP, .revents = 0});
206 207
#endif

L
LiYuRio 已提交
208 209
  bool finished = false;
  while (!finished) {
210 211 212 213
    for (size_t i = 0; i < fds.size(); i++) {
      fds[i].revents = 0;
    }

G
gongweibao 已提交
214 215
    VLOG(9) << "begin to poll fds_size:"
            << paddle::string::Sprintf("%d", fds.size());
216
#ifdef _WIN32
L
LiYuRio 已提交
217 218 219 220 221 222 223 224 225
    int res = ::WSAPoll(fds.data(), fds.size(), INFTIME);
    if (res == 0) {
      auto rv = WaitForSingleObject(ghStopEvent_, 0);
      if (rv != WAIT_TIMEOUT) {
        finished = true;
        break;
      }
      continue;
    }
226 227
#else
    ::poll(fds.data(), fds.size(), INFTIME);
G
gongweibao 已提交
228 229 230 231 232 233 234 235 236 237 238

    VLOG(9) << "begin to fds[1].revents:"
            << paddle::string::Sprintf("%d", fds[1].revents);
    // The control pipe receive shutdown event, and begin to close it.
    if (fds[1].revents != 0) {
      if (fds[1].revents & ~(POLLIN | POLLHUP)) {
        PADDLE_THROW(paddle::platform::errors::Fatal("Undefined event type:%d",
                                                     fds[1].revents));
      }
      VLOG(0)
          << "receive shutdown event and so quit from MasterDaemon run loop";
L
LiYuRio 已提交
239
      finished = true;
G
gongweibao 已提交
240 241
      break;
    }
242 243
#endif

G
gongweibao 已提交
244
    // accept connect request.
245 246 247 248 249 250 251 252 253 254
    if (fds[0].revents != 0) {
      auto socket = tcputils::tcp_accept(_listen_socket);
      _sockets.emplace_back(socket);
#ifdef _WIN32
      fds.push_back({socket, POLLIN});
#else
      fds.push_back({.fd = socket, .events = POLLIN, .revents = 0});
#endif
    }

G
gongweibao 已提交
255
    ProcessCommands(&fds);
256 257 258
  }
}

G
gongweibao 已提交
259 260
std::unique_ptr<TCPServer> TCPServer::create(uint16_t port,
                                             int nranks,
261
                                             int stop_check_timeout) {
262 263
  int socket = tcputils::tcp_listen("", std::to_string(port), AF_INET);
  auto server = std::make_unique<TCPServer>();
264 265
  server->_master_daemon =
      MasterDaemon::start(socket, nranks, stop_check_timeout);
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  return server;
}

std::unique_ptr<TCPClient> TCPClient::connect(const std::string host,
                                              uint16_t port) {
  int socket = tcputils::tcp_connect(host, std::to_string(port), AF_INET);
  return std::make_unique<TCPClient>(socket);
}

void TCPClient::send_command_for_key(Command type, const std::string& key) {
  tcputils::send_value<Command>(_socket, type);
  if (key.empty()) {
    return;
  }
  tcputils::send_string(_socket, key);
}

template <typename T>
void TCPClient::send_value(const T& value) {
  tcputils::send_bytes<T>(_socket, &value, 1);
}

template <typename T>
T TCPClient::receive_value() {
  T res;
  tcputils::receive_bytes<T>(_socket, &res, 1);
  return res;
}

template <typename T>
void TCPClient::send_vector(const std::vector<T>& value) {
  tcputils::send_vector<T>(_socket, value);
}

template <typename T>
std::vector<T> TCPClient::receive_vector() {
  return tcputils::receive_vector<T>(_socket);
}

}  // namespace detail

G
gongweibao 已提交
307 308 309 310 311
TCPStore::TCPStore(std::string host,
                   uint16_t port,
                   bool is_master,
                   size_t num_workers,
                   int timeout)
312
    : Store(timeout), _is_master(is_master), _num_workers(num_workers) {
G
gongweibao 已提交
313 314 315 316 317 318 319
  _timeout = timeout;
  PADDLE_ENFORCE_GT(
      timeout,
      0,
      platform::errors::InvalidArgument("timeout must >= %d", timeout));

  VLOG(3) << "input timeout" << timeout << ", member timeout:" << _timeout;
320
  if (_is_master) {
G
gongweibao 已提交
321
    _server = detail::TCPServer::create(port, num_workers, timeout);
322 323 324 325 326 327 328 329 330 331 332 333
  }

  _client = detail::TCPClient::connect(host, port);
  waitWorkers();
}

void TCPStore::waitWorkers() {
  if (_num_workers == 0) {
    return;
  }
  add(_init_key, 1);

G
gongweibao 已提交
334
  VLOG(3) << paddle::string::Sprintf("_timeout:%d", _timeout);
335 336 337 338
  auto begin = std::chrono::steady_clock::now();
  do {
    auto value = get(_init_key);
    int completed = std::stoi(std::string(value.begin(), value.end()));
G
gongweibao 已提交
339 340
    VLOG(3) << completed << " worker ready, total " << _num_workers
            << ", _timeout:" << _timeout;
341 342 343 344 345 346 347
    if (completed >= _num_workers) {
      break;
    }
    const auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::steady_clock::now() - begin);

    std::this_thread::sleep_for(std::chrono::milliseconds(100));
G
gongweibao 已提交
348 349 350 351 352 353 354
    if (_timeout != 0 && elapsed.count() > _timeout) {
      LOG(FATAL) << paddle::string::Sprintf(
          "_timeout:%d elapsed:%d (elapsed > _timeout)=%d",
          _timeout,
          elapsed.count(),
          elapsed.count() > _timeout);

355
      PADDLE_ENFORCE_EQ(
G
gongweibao 已提交
356 357
          completed,
          _num_workers,
358 359 360 361
          platform::errors::InvalidArgument(
              "TCPStore timeouted and not all workers got ready."));
    }
  } while (true);
362 363 364 365
  VLOG(3) << "TCPStore initialized.";
}

int64_t TCPStore::add(const std::string& key, int64_t value) {
366
  VLOG(3) << "TCPStore add.";
367 368 369 370 371
  _client->send_command_for_key(Command::ADD, _key_prefix + key);
  _client->send_value<std::int64_t>(value);
  return _client->receive_value<std::int64_t>();
}

372 373 374
void TCPStore::set(const std::string& key, const std::vector<uint8_t>& value) {
  VLOG(3) << "TCPStore set.";
  _client->send_command_for_key(Command::SET, _key_prefix + key);
G
gongweibao 已提交
375
  _client->send_vector<uint8_t>(value);
376 377
}

378 379 380 381 382 383 384 385 386
std::vector<uint8_t> TCPStore::get(const std::string& key) {
  wait(key);
  _client->send_command_for_key(Command::GET, _key_prefix + key);
  VLOG(3) << "TCPStore get.";
  return _client->receive_vector<uint8_t>();
}

void TCPStore::wait(const std::string& key) {
  ReplyType reply;
387
  VLOG(3) << "TCPStore wait.";
388 389 390 391
  _client->send_command_for_key(Command::WAIT, _key_prefix + key);
  reply = _client->receive_value<ReplyType>();
  while (reply != ReplyType::STOP_WAIT) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
392

393
    _client->send_command_for_key(Command::WAIT, _key_prefix + key);
394
    reply = _client->receive_value<ReplyType>();
395
  }
396 397
}

G
gongweibao 已提交
398
TCPStore::~TCPStore() { VLOG(3) << "TCPStore destructure"; }
399 400 401

}  // namespace distributed
}  // namespace paddle