fs.cc 15.7 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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
#include "paddle/fluid/framework/io/fs.h"
16

17
#include <sys/stat.h>
18

X
xjqbest 已提交
19
#include <memory>
D
dongdaxiang 已提交
20

21
#include "glog/logging.h"
22 23
#include "paddle/fluid/platform/enforce.h"

D
dongdaxiang 已提交
24 25 26 27 28 29 30 31 32 33 34
namespace paddle {
namespace framework {

static void fs_add_read_converter_internal(std::string& path,  // NOLINT
                                           bool& is_pipe,      // NOLINT
                                           const std::string& converter) {
  if (converter == "") {
    return;
  }

  if (!is_pipe) {
35 36
    path = string::format_string(
        "( %s ) < \"%s\"", converter.c_str(), path.c_str());
D
dongdaxiang 已提交
37 38
    is_pipe = true;
  } else {
39
    path = string::format_string("%s | %s", path.c_str(), converter.c_str());
D
dongdaxiang 已提交
40 41 42 43 44 45 46 47 48 49 50
  }
}

static void fs_add_write_converter_internal(std::string& path,  // NOLINT
                                            bool& is_pipe,      // NOLINT
                                            const std::string& converter) {
  if (converter == "") {
    return;
  }

  if (!is_pipe) {
51 52
    path = string::format_string(
        "( %s ) > \"%s\"", converter.c_str(), path.c_str());
D
dongdaxiang 已提交
53 54
    is_pipe = true;
  } else {
55
    path = string::format_string("%s | %s", converter.c_str(), path.c_str());
D
dongdaxiang 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  }
}

static std::shared_ptr<FILE> fs_open_internal(const std::string& path,
                                              bool is_pipe,
                                              const std::string& mode,
                                              size_t buffer_size,
                                              int* err_no = 0) {
  std::shared_ptr<FILE> fp = nullptr;

  if (!is_pipe) {
    fp = shell_fopen(path, mode);
  } else {
    fp = shell_popen(path, mode, err_no);
  }

  if (buffer_size > 0) {
    char* buffer = new char[buffer_size];
    CHECK_EQ(0, setvbuf(&*fp, buffer, _IOFBF, buffer_size));
D
dongdaxiang 已提交
75 76 77 78 79
    fp = {&*fp, [fp, buffer](FILE*) mutable {  // NOLINT
            CHECK(fp.unique());                // NOLINT
            fp = nullptr;
            delete[] buffer;
          }};
D
dongdaxiang 已提交
80 81
  }

D
dongdaxiang 已提交
82
  return fp;
D
dongdaxiang 已提交
83 84 85 86 87 88 89 90 91 92
}

static bool fs_begin_with_internal(const std::string& path,
                                   const std::string& str) {
  return strncmp(path.c_str(), str.c_str(), str.length()) == 0;
}

static bool fs_end_with_internal(const std::string& path,
                                 const std::string& str) {
  return path.length() >= str.length() &&
93 94
         strncmp(&path[path.length() - str.length()],
                 str.c_str(),
D
dongdaxiang 已提交
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
                 str.length()) == 0;
}

static size_t& localfs_buffer_size_internal() {
  static size_t x = 0;
  return x;
}

size_t localfs_buffer_size() { return localfs_buffer_size_internal(); }

void localfs_set_buffer_size(size_t x) { localfs_buffer_size_internal() = x; }

std::shared_ptr<FILE> localfs_open_read(std::string path,
                                        const std::string& converter) {
  bool is_pipe = false;

  if (fs_end_with_internal(path, ".gz")) {
    fs_add_read_converter_internal(path, is_pipe, "zcat");
  }

  fs_add_read_converter_internal(path, is_pipe, converter);
  return fs_open_internal(path, is_pipe, "r", localfs_buffer_size());
}

std::shared_ptr<FILE> localfs_open_write(std::string path,
                                         const std::string& converter) {
121 122
  shell_execute(
      string::format_string("mkdir -p $(dirname \"%s\")", path.c_str()));
D
dongdaxiang 已提交
123 124 125 126 127 128 129 130 131 132 133

  bool is_pipe = false;

  if (fs_end_with_internal(path, ".gz")) {
    fs_add_write_converter_internal(path, is_pipe, "gzip");
  }

  fs_add_write_converter_internal(path, is_pipe, converter);
  return fs_open_internal(path, is_pipe, "w", localfs_buffer_size());
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
std::shared_ptr<FILE> localfs_open_append_write(std::string path,
                                                const std::string& converter) {
  shell_execute(
      string::format_string("mkdir -p $(dirname \"%s\")", path.c_str()));

  bool is_pipe = false;

  if (fs_end_with_internal(path, ".gz")) {
    fs_add_write_converter_internal(path, is_pipe, "gzip");
  }

  fs_add_write_converter_internal(path, is_pipe, converter);
  return fs_open_internal(path, is_pipe, "a", localfs_buffer_size());
}

D
dongdaxiang 已提交
149 150 151
int64_t localfs_file_size(const std::string& path) {
  struct stat buf;
  if (0 != stat(path.c_str(), &buf)) {
152 153
    PADDLE_THROW(platform::errors::External(
        "Failed to get file status via stat function."));
D
dongdaxiang 已提交
154 155 156 157 158 159 160 161 162 163
    return -1;
  }
  return (int64_t)buf.st_size;
}

void localfs_remove(const std::string& path) {
  if (path == "") {
    return;
  }

164
  shell_execute(string::format_string("rm -rf %s", path.c_str()));
D
dongdaxiang 已提交
165 166 167 168 169 170 171 172 173
}

std::vector<std::string> localfs_list(const std::string& path) {
  if (path == "") {
    return {};
  }

  std::shared_ptr<FILE> pipe;
  int err_no = 0;
174
  pipe = shell_popen(
D
danleifeng 已提交
175
      string::format_string("find %s -type f -maxdepth 1 | sort", path.c_str()),
176
      "r",
177 178
      &err_no);
  string::LineFileReader reader;
D
dongdaxiang 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192
  std::vector<std::string> list;

  while (reader.getline(&*pipe)) {
    list.push_back(reader.get());
  }

  return list;
}

std::string localfs_tail(const std::string& path) {
  if (path == "") {
    return "";
  }

193 194
  return shell_get_command_output(
      string::format_string("tail -1 %s ", path.c_str()));
D
dongdaxiang 已提交
195 196 197 198
}

bool localfs_exists(const std::string& path) {
  std::string test_f = shell_get_command_output(
199
      string::format_string("[ -f %s ] ; echo $?", path.c_str()));
D
dongdaxiang 已提交
200

201
  if (string::trim_spaces(test_f) == "0") {
D
dongdaxiang 已提交
202 203 204 205
    return true;
  }

  std::string test_d = shell_get_command_output(
206
      string::format_string("[ -d %s ] ; echo $?", path.c_str()));
D
dongdaxiang 已提交
207

208
  if (string::trim_spaces(test_d) == "0") {
D
dongdaxiang 已提交
209 210 211 212 213 214 215 216 217 218 219
    return true;
  }

  return false;
}

void localfs_mkdir(const std::string& path) {
  if (path == "") {
    return;
  }

220
  shell_execute(string::format_string("mkdir -p %s", path.c_str()));
D
dongdaxiang 已提交
221 222
}

223 224 225 226 227 228 229
void localfs_mv(const std::string& src, const std::string& dest) {
  if (src == "" || dest == "") {
    return;
  }
  shell_execute(string::format_string("mv %s %s", src.c_str(), dest.c_str()));
}

D
dongdaxiang 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
static size_t& hdfs_buffer_size_internal() {
  static size_t x = 0;
  return x;
}

size_t hdfs_buffer_size() { return hdfs_buffer_size_internal(); }

void hdfs_set_buffer_size(size_t x) { hdfs_buffer_size_internal() = x; }

static std::string& hdfs_command_internal() {
  static std::string x = "hadoop fs";
  return x;
}

const std::string& hdfs_command() { return hdfs_command_internal(); }

void hdfs_set_command(const std::string& x) { hdfs_command_internal() = x; }

248 249 250 251 252 253 254 255 256 257 258 259 260 261
// dataset and model may be on different afs cluster
static std::string& dataset_hdfs_command_internal() {
  static std::string x = "hadoop fs";
  return x;
}

const std::string& dataset_hdfs_command() {
  return dataset_hdfs_command_internal();
}

void dataset_hdfs_set_command(const std::string& x) {
  dataset_hdfs_command_internal() = x;
}

262 263 264 265 266 267 268 269 270 271 272
static std::string& customized_download_cmd_internal() {
  static std::string x = "";
  return x;
}

const std::string& download_cmd() { return customized_download_cmd_internal(); }

void set_download_command(const std::string& x) {
  customized_download_cmd_internal() = x;
}

273 274
std::shared_ptr<FILE> hdfs_open_read(std::string path,
                                     int* err_no,
275 276
                                     const std::string& converter,
                                     bool read_data) {
277
  if (download_cmd() != "") {  // use customized download command
278 279
    path = string::format_string(
        "%s \"%s\"", download_cmd().c_str(), path.c_str());
D
dongdaxiang 已提交
280
  } else {
281
    if (fs_end_with_internal(path, ".gz")) {
282 283 284 285 286 287 288
      if (read_data) {
        path = string::format_string(
            "%s -text \"%s\"", dataset_hdfs_command().c_str(), path.c_str());
      } else {
        path = string::format_string(
            "%s -text \"%s\"", hdfs_command().c_str(), path.c_str());
      }
289
    } else {
290 291 292 293 294 295 296
      if (read_data) {
        path = string::format_string(
            "%s -cat \"%s\"", dataset_hdfs_command().c_str(), path.c_str());
      } else {
        path = string::format_string(
            "%s -cat \"%s\"", hdfs_command().c_str(), path.c_str());
      }
297
    }
D
dongdaxiang 已提交
298 299 300 301 302 303 304
  }

  bool is_pipe = true;
  fs_add_read_converter_internal(path, is_pipe, converter);
  return fs_open_internal(path, is_pipe, "r", hdfs_buffer_size(), err_no);
}

305 306
std::shared_ptr<FILE> hdfs_open_write(std::string path,
                                      int* err_no,
D
dongdaxiang 已提交
307
                                      const std::string& converter) {
308 309
  path = string::format_string(
      "%s -put - \"%s\"", hdfs_command().c_str(), path.c_str());
D
dongdaxiang 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  bool is_pipe = true;

  if (fs_end_with_internal(path, ".gz\"")) {
    fs_add_write_converter_internal(path, is_pipe, "gzip");
  }

  fs_add_write_converter_internal(path, is_pipe, converter);
  return fs_open_internal(path, is_pipe, "w", hdfs_buffer_size(), err_no);
}

void hdfs_remove(const std::string& path) {
  if (path == "") {
    return;
  }

325 326
  shell_execute(string::format_string(
      "%s -rmr %s &>/dev/null; true", hdfs_command().c_str(), path.c_str()));
D
dongdaxiang 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
}

std::vector<std::string> hdfs_list(const std::string& path) {
  if (path == "") {
    return {};
  }

  std::string prefix = "hdfs:";

  if (fs_begin_with_internal(path, "afs:")) {
    prefix = "afs:";
  }
  int err_no = 0;
  std::vector<std::string> list;
  do {
    err_no = 0;
    std::shared_ptr<FILE> pipe;
344 345
    pipe = shell_popen(
        string::format_string("%s -ls %s | ( grep ^- ; [ $? != 2 ] )",
346 347 348 349
                              hdfs_command().c_str(),
                              path.c_str()),
        "r",
        &err_no);
350
    string::LineFileReader reader;
D
dongdaxiang 已提交
351 352 353
    list.clear();

    while (reader.getline(&*pipe)) {
354
      std::vector<std::string> line = string::split_string(reader.get());
D
dongdaxiang 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368
      if (line.size() != 8) {
        continue;
      }
      list.push_back(prefix + line[7]);
    }
  } while (err_no == -1);
  return list;
}

std::string hdfs_tail(const std::string& path) {
  if (path == "") {
    return "";
  }

369
  return shell_get_command_output(string::format_string(
D
dongdaxiang 已提交
370 371 372 373
      "%s -text %s | tail -1 ", hdfs_command().c_str(), path.c_str()));
}

bool hdfs_exists(const std::string& path) {
374
  std::string test = shell_get_command_output(string::format_string(
D
dongdaxiang 已提交
375 376
      "%s -test -e %s ; echo $?", hdfs_command().c_str(), path.c_str()));

377
  if (string::trim_spaces(test) == "0") {
D
dongdaxiang 已提交
378 379 380 381 382 383 384 385 386 387 388
    return true;
  }

  return false;
}

void hdfs_mkdir(const std::string& path) {
  if (path == "") {
    return;
  }

389 390
  shell_execute(string::format_string(
      "%s -mkdir %s; true", hdfs_command().c_str(), path.c_str()));
D
dongdaxiang 已提交
391 392
}

393 394 395 396 397 398 399 400
void hdfs_mv(const std::string& src, const std::string& dest) {
  if (src == "" || dest == "") {
    return;
  }
  shell_execute(string::format_string(
      "%s -mv %s %s; true", hdfs_command().c_str(), src.c_str(), dest.c_str()));
}

D
dongdaxiang 已提交
401 402 403 404 405 406 407 408 409 410
int fs_select_internal(const std::string& path) {
  if (fs_begin_with_internal(path, "hdfs:")) {
    return 1;
  } else if (fs_begin_with_internal(path, "afs:")) {
    return 1;
  }

  return 0;
}

411 412
std::shared_ptr<FILE> fs_open_read(const std::string& path,
                                   int* err_no,
413 414
                                   const std::string& converter,
                                   bool read_data) {
D
dongdaxiang 已提交
415 416 417 418 419
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_open_read(path, converter);

    case 1:
420
      return hdfs_open_read(path, err_no, converter, read_data);
D
dongdaxiang 已提交
421 422

    default:
423 424 425
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
426 427 428 429 430
  }

  return {};
}

431 432
std::shared_ptr<FILE> fs_open_write(const std::string& path,
                                    int* err_no,
D
dongdaxiang 已提交
433 434 435 436 437 438 439 440
                                    const std::string& converter) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_open_write(path, converter);

    case 1:
      return hdfs_open_write(path, err_no, converter);

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    default:
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
  }

  return {};
}

std::shared_ptr<FILE> fs_open_append_write(const std::string& path,
                                           int* err_no,
                                           const std::string& converter) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_open_append_write(path, converter);

    case 1:
      return hdfs_open_write(path, err_no, converter);

D
dongdaxiang 已提交
460
    default:
461 462 463
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
464 465 466 467 468
  }

  return {};
}

469 470 471 472
std::shared_ptr<FILE> fs_open(const std::string& path,
                              const std::string& mode,
                              int* err_no,
                              const std::string& converter) {
D
dongdaxiang 已提交
473 474 475 476 477 478 479 480
  if (mode == "r" || mode == "rb") {
    return fs_open_read(path, err_no, converter);
  }

  if (mode == "w" || mode == "wb") {
    return fs_open_write(path, err_no, converter);
  }

481 482 483
  PADDLE_THROW(platform::errors::Unavailable(
      "Unsupport file open mode: %s. Only supports 'r', 'rb', 'w' or 'wb'.",
      mode));
D
dongdaxiang 已提交
484 485 486 487 488 489 490 491 492
  return {};
}

int64_t fs_file_size(const std::string& path) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_file_size(path);

    default:
493 494
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system."));
D
dongdaxiang 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508
  }

  return 0;
}

void fs_remove(const std::string& path) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_remove(path);

    case 1:
      return hdfs_remove(path);

    default:
509 510 511
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
512 513 514 515 516 517 518 519 520 521 522 523
  }
}

std::vector<std::string> fs_list(const std::string& path) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_list(path);

    case 1:
      return hdfs_list(path);

    default:
524 525 526
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540
  }

  return {};
}

std::string fs_tail(const std::string& path) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_tail(path);

    case 1:
      return hdfs_tail(path);

    default:
541 542 543
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557
  }

  return "";
}

bool fs_exists(const std::string& path) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_exists(path);

    case 1:
      return hdfs_exists(path);

    default:
558 559 560
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574
  }

  return false;
}

void fs_mkdir(const std::string& path) {
  switch (fs_select_internal(path)) {
    case 0:
      return localfs_mkdir(path);

    case 1:
      return hdfs_mkdir(path);

    default:
575 576 577
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupport file system. Now only supports local file system and "
          "HDFS."));
D
dongdaxiang 已提交
578 579
  }
}
580 581 582 583 584 585 586 587 588 589 590 591 592 593

void fs_mv(const std::string& src, const std::string& dest) {
  int s = fs_select_internal(src);
  int d = fs_select_internal(dest);
  CHECK_EQ(s, d);
  switch (s) {
    case 0:
      return localfs_mv(src, dest);

    case 1:
      return hdfs_mv(src, dest);
  }
}

594 595
}  // end namespace framework
}  // end namespace paddle