hdfs.py 18.7 KB
Newer Older
T
tangwei12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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.
14
"""HDFS Utils."""
T
tangwei12 已提交
15 16 17 18 19 20 21 22 23 24

import os
import sys
import subprocess
import multiprocessing
from datetime import datetime

import re
import copy
import errno
25
import time
T
tangwei12 已提交
26 27 28 29
import logging

__all__ = ["HDFSClient"]

30 31 32 33 34 35 36 37 38 39 40

def get_logger(name, level, fmt):
    logger = logging.getLogger(name)
    logger.setLevel(level)
    handler = logging.FileHandler('hdfs.log', mode='w')
    formatter = logging.Formatter(fmt=fmt)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


T
tangwei12 已提交
41 42 43 44 45 46
_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s')


class HDFSClient(object):
    """
47
    A tool of HDFS
T
tangwei12 已提交
48 49

    Args:
50
        hadoop_home (string): hadoop_home
T
tangwei12 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
        configs (dict): hadoop config, it is a dict, please contain \
            key "fs.default.name" and "hadoop.job.ugi"
        Can be a float value
    Examples:
        hadoop_home = "/home/client/hadoop-client/hadoop/"

        configs = {
            "fs.default.name": "hdfs://xxx.hadoop.com:54310",
            "hadoop.job.ugi": "hello,hello123"
        }

        client = HDFSClient(hadoop_home, configs)

        client.ls("/user/com/train-25")
        files = client.lsr("/user/com/train-25/models")
    """

    def __init__(self, hadoop_home, configs):
        self.pre_commands = []
        hadoop_bin = '%s/bin/hadoop' % hadoop_home
        self.pre_commands.append(hadoop_bin)
        dfs = 'fs'
        self.pre_commands.append(dfs)

        for k, v in configs.iteritems():
            config_command = '-D%s=%s' % (k, v)
            self.pre_commands.append(config_command)

    def __run_hdfs_cmd(self, commands, retry_times=5):
        whole_commands = copy.deepcopy(self.pre_commands)
        whole_commands.extend(commands)

        ret_code = 0
        ret_out = None
        ret_err = None
86
        retry_sleep_second = 3
T
tangwei12 已提交
87 88 89 90 91 92 93 94 95 96 97
        whole_commands = " ".join(whole_commands)
        for x in range(retry_times + 1):
            proc = subprocess.Popen(
                whole_commands,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True)
            (output, errors) = proc.communicate()
            ret_code, ret_out, ret_err = proc.returncode, output, errors

            _logger.info(
98
                'Times: %d, Running command: %s. Return code: %d, Msg: %s' %
T
tangwei12 已提交
99 100 101 102
                (x, whole_commands, proc.returncode, errors))

            if ret_code == 0:
                break
103
            time.sleep(retry_sleep_second)
T
tangwei12 已提交
104 105 106

        return ret_code, ret_out, ret_err

107
    def cat(self, hdfs_path=None):
108 109 110 111 112 113 114
        """
        cat hdfs file
        Args:
            hdfs_path(str): the hdfs file path
        Returns:
            file content
        """
115 116 117 118 119 120 121 122
        if self.is_file(hdfs_path):
            exist_cmd = ['-cat', hdfs_path]
            returncode, output, errors = self.__run_hdfs_cmd(
                exist_cmd, retry_times=1)
            if returncode != 0:
                _logger.error("HDFS cat HDFS path: {} failed".format(hdfs_path))
                return ""
            else:
123
                _logger.info("HDFS cat HDFS path: {} succeed".format(hdfs_path))
124 125 126 127 128
                return output.strip()

        else:
            return ""

T
tangwei12 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 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
    def is_exist(self, hdfs_path=None):
        """
        whether the remote HDFS path exists

        Args:
            hdfs_path(str): the hdfs file path

        Returns:
            True or False
        """
        exist_cmd = ['-test', '-e', hdfs_path]
        returncode, output, errors = self.__run_hdfs_cmd(
            exist_cmd, retry_times=1)

        if returncode:
            _logger.error("HDFS is_exist HDFS path: {} failed".format(
                hdfs_path))
            return False
        else:
            _logger.info("HDFS is_exist HDFS path: {} successfully".format(
                hdfs_path))
            return True

    def is_dir(self, hdfs_path=None):
        """
        whether the remote HDFS path is directory

        Args:
            hdfs_path(str): the hdfs file path

        Returns:
            True or False
        """

        if not self.is_exist(hdfs_path):
            return False

        dir_cmd = ['-test', '-d', hdfs_path]
        returncode, output, errors = self.__run_hdfs_cmd(dir_cmd, retry_times=1)

        if returncode:
            _logger.error("HDFS path: {} failed is not a directory".format(
                hdfs_path))
            return False
        else:
            _logger.info("HDFS path: {} successfully is a directory".format(
                hdfs_path))
            return True

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    def is_file(self, hdfs_path=None):
        """
        whether the remote HDFS path is file

        Args:
            hdfs_path(str): the hdfs file path

        Returns:
            True or False
        """

        if not self.is_exist(hdfs_path):
            return False

        dir_cmd = ['-test', '-d', hdfs_path]
        returncode, output, errors = self.__run_hdfs_cmd(dir_cmd, retry_times=1)

        if returncode == 0:
            _logger.error("HDFS path: {} failed is not a file".format(
                hdfs_path))
            return False
        else:
            _logger.info("HDFS path: {} successfully is a file".format(
                hdfs_path))
            return True

T
tangwei12 已提交
204 205 206 207 208 209 210
    def delete(self, hdfs_path):
        """
        Remove a file or directory from HDFS.

        whether the remote HDFS path exists

        Args:
211
            hdfs_path(str): HDFS path.
T
tangwei12 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

        Returns:
            True or False
            This function returns `True` if the deletion was successful and `False` if
            no file or directory previously existed at `hdfs_path`.
        """
        _logger.info('Deleting %r.', hdfs_path)

        if not self.is_exist(hdfs_path):
            _logger.warn("HDFS path: {} do not exist".format(hdfs_path))
            return True

        if self.is_dir(hdfs_path):
            del_cmd = ['-rmr', hdfs_path]
        else:
            del_cmd = ['-rm', hdfs_path]

        returncode, output, errors = self.__run_hdfs_cmd(del_cmd, retry_times=0)

        if returncode:
            _logger.error("HDFS path: {} delete files failure".format(
                hdfs_path))
            return False
        else:
            _logger.info("HDFS path: {} delete files successfully".format(
                hdfs_path))
            return True

    def rename(self, hdfs_src_path, hdfs_dst_path, overwrite=False):
        """
        Move a file or folder on HDFS.

        Args:
245 246 247 248
            hdfs_src_path(str): HDFS path
            hdfs_dst_path(str): HDFS path
            overwrite(bool|False): If the path already exists and overwrite is
                                   False, will return False.
T
tangwei12 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        Returns:
            True or False
        """
        assert hdfs_src_path is not None
        assert hdfs_dst_path is not None

        if not self.is_exist(hdfs_src_path):
            _logger.info("HDFS path do not exist: {}".format(hdfs_src_path))
        if self.is_exist(hdfs_dst_path) and not overwrite:
            _logger.error("HDFS path is exist: {} and overwrite=False".format(
                hdfs_dst_path))

        rename_command = ['-mv', hdfs_src_path, hdfs_dst_path]
        returncode, output, errors = self.__run_hdfs_cmd(
            rename_command, retry_times=1)

        if returncode:
            _logger.error("HDFS rename path: {} to {} failed".format(
                hdfs_src_path, hdfs_dst_path))
            return False
        else:
            _logger.info("HDFS rename path: {} to {} successfully".format(
                hdfs_src_path, hdfs_dst_path))
            return True

    @staticmethod
    def make_local_dirs(local_path):
        """
        create a directiory local, is same to mkdir
278

T
tangwei12 已提交
279
        Args:
280
            local_path(str): local path that wants to create a directiory.
T
tangwei12 已提交
281 282 283 284 285 286 287 288 289 290 291 292
        """
        try:
            os.makedirs(local_path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

    def makedirs(self, hdfs_path):
        """
        Create a remote directory, recursively if necessary.

        Args:
293 294
            hdfs_path(str): Remote path. Intermediate directories will be
                            created appropriately.
T
tangwei12 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

        Returns:
            True or False
        """
        _logger.info('Creating directories to %r.', hdfs_path)
        assert hdfs_path is not None

        if self.is_exist(hdfs_path):
            _logger.error("HDFS path is exist: {}".format(hdfs_path))
            return

        mkdirs_commands = ['-mkdir', hdfs_path]
        returncode, output, errors = self.__run_hdfs_cmd(
            mkdirs_commands, retry_times=1)

        if returncode:
            _logger.error("HDFS mkdir path: {} failed".format(hdfs_path))
            return False
        else:
314
            _logger.info("HDFS mkdir path: {} successfully".format(hdfs_path))
T
tangwei12 已提交
315 316 317 318 319 320 321
            return True

    def ls(self, hdfs_path):
        """
        ls directory contents about HDFS hdfs_path

        Args:
322
            hdfs_path(str): Remote HDFS path will be ls.
T
tangwei12 已提交
323 324 325 326 327 328 329 330 331 332 333

        Returns:
            List: a contents list about hdfs_path.
        """
        assert hdfs_path is not None

        if not self.is_exist(hdfs_path):
            return []

        ls_commands = ['-ls', hdfs_path]
        returncode, output, errors = self.__run_hdfs_cmd(
334
            ls_commands, retry_times=10)
T
tangwei12 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

        if returncode:
            _logger.error("HDFS list path: {} failed".format(hdfs_path))
            return []
        else:
            _logger.info("HDFS list path: {} successfully".format(hdfs_path))

            ret_lines = []
            regex = re.compile('\s+')
            out_lines = output.strip().split("\n")
            for line in out_lines:
                re_line = regex.split(line)
                if len(re_line) == 8:
                    ret_lines.append(re_line[7])
            return ret_lines

    def lsr(self, hdfs_path, excludes=[]):
        """
        list directory contents about HDFS hdfs_path recursively

        Args:
356 357
            hdfs_path(str): Remote HDFS path.
            excludes(list): excludes
T
tangwei12 已提交
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

        Returns:
            List: a contents list about hdfs_path.
        """

        assert hdfs_path is not None

        if not self.is_exist(hdfs_path):
            return []

        ls_commands = ['-lsr', hdfs_path]
        returncode, output, errors = self.__run_hdfs_cmd(
            ls_commands, retry_times=1)

        if returncode:
            _logger.error("HDFS list all files: {} failed".format(hdfs_path))
            return []
        else:
            _logger.info("HDFS list all files: {} successfully".format(
                hdfs_path))
            lines = []
            regex = re.compile('\s+')
            out_lines = output.strip().split("\n")
            for line_id, line in enumerate(out_lines):
                re_line = regex.split(line)
                if len(re_line) == 8:
                    if re_line[0][0] == "d":
                        continue
                    if re_line[7] in excludes:
                        continue
                    else:
                        lines.append((re_line[7], re_line[5] + " " + re_line[6],
                                      line_id))
            lines = sorted(lines, key=lambda line: line[2])
            ret_lines = [ret[0] for ret in lines]
            return ret_lines

    @staticmethod
396 397 398 399 400 401 402 403 404 405 406 407
    def split_files(files, trainer_id, trainers):
        """
        split file list

        Args:
            files(list): file list
            trainer_id(int): trainer mpi rank id
            trainers(int): all trainers num

        Returns:
            fileist(list): file list of current trainer
        """
T
tangwei12 已提交
408 409 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
        remainder = len(files) % trainers
        blocksize = len(files) / trainers

        blocks = [blocksize] * trainers
        for i in range(remainder):
            blocks[i] += 1

        trainer_files = [[]] * trainers
        begin = 0
        for i in range(trainers):
            trainer_files[i] = files[begin:begin + blocks[i]]
            begin += blocks[i]

        return trainer_files[trainer_id]

    def download(self,
                 hdfs_path,
                 local_path,
                 multi_processes=5,
                 overwrite=False,
                 retry_times=5):
        """
        Download files from HDFS using multi process.

        Args:
            hdfs_path(str): path on hdfs
            local_path(str): path on local
            multi_processes(int|5): the download data process at the same time, default=5
436 437
            overwrite(bool): is overwrite
            retry_times(int): retry times
T
tangwei12 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

        Returns:
            List:
            Download files in local folder.
        """

        def __subprocess_download(local_path, datas):
            """
            download file from HDFS

            Args:
                hdfs_path(str): the hdfs file path
                local_path(str): the local file path
                overwrite(bool|None): will overwrite the file on HDFS or not
                retry_times(int|5): retry times

            Returns:
                True or False
            """
            for data in datas:
                download_commands = ["-get", data, local_path]

                returncode, output, errors = self.__run_hdfs_cmd(
                    download_commands, retry_times=retry_times)

                if returncode:
                    _logger.error(
                        "Get local path: {} from HDFS path: {} failed".format(
                            local_path, hdfs_path))
                    return False
            return True

        self.make_local_dirs(local_path)

472
        all_files = self.ls(hdfs_path)
T
tangwei12 已提交
473 474 475

        procs = []
        for i in range(multi_processes):
476
            process_datas = HDFSClient.split_files(all_files, i,
T
tangwei12 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                                                   multi_processes)
            p = multiprocessing.Process(
                target=__subprocess_download,
                args=(
                    local_path,
                    process_datas, ))
            procs.append(p)
            p.start()

        # complete the processes
        for proc in procs:
            proc.join()

        _logger.info("Finish {} multi process to download datas".format(
            multi_processes))

        local_downloads = []
        for dirname, folder, files in os.walk(local_path):
            for i in files:
                t = os.path.join(dirname, i)
                local_downloads.append(t)
        return local_downloads

    def upload(self,
               hdfs_path,
               local_path,
               multi_processes=5,
               overwrite=False,
               retry_times=5):
        """
        Upload files to HDFS using multi process.

        Args:
            hdfs_path(str): path on hdfs
            local_path(str): path on local
            multi_processes(int|5): the upload data process at the same time, default=5
            overwrite(bool|False): will overwrite file on HDFS or not
514
            retry_times(int): upload file max retry time.
T
tangwei12 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

        Returns:
            None
        """

        def __subprocess_upload(hdfs_path_single, datas):
            for data in datas:
                put_commands = ["-put", data, hdfs_path_single]
                returncode, output, errors = self.__run_hdfs_cmd(put_commands,
                                                                 retry_times)

                if returncode:
                    _logger.error("Put local path: {} to HDFS path: {} failed".
                                  format(data, hdfs_path_single))
                    return False
            return True

        def get_local_files(path):
533 534 535 536 537 538 539 540 541
            """
            get local files

            Args:
                path(str): local path

            Returns:
                list of local files
            """
T
tangwei12 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
            rlist = []

            if not os.path.exists(path):
                return rlist

            if os.path.isdir(path):
                for file in os.listdir(path):
                    t = os.path.join(path, file)
                    rlist.append(t)
            else:
                rlist.append(path)
            return rlist

        all_files = get_local_files(local_path)
        if not all_files:
            _logger.info("there are nothing need to upload, exit")
            return

        if self.is_exist(hdfs_path) and overwrite:
            self.delete(hdfs_path)
            self.makedirs(hdfs_path)

        procs = []
        for i in range(multi_processes):
566
            process_datas = HDFSClient.split_files(all_files, i,
T
tangwei12 已提交
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
                                                   multi_processes)
            p = multiprocessing.Process(
                target=__subprocess_upload, args=(
                    hdfs_path,
                    process_datas, ))
            procs.append(p)
            p.start()

        # complete the processes
        for proc in procs:
            proc.join()

        _logger.info("Finish upload datas from {} to {}".format(local_path,
                                                                hdfs_path))

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
    def upload_dir(self, dest_dir, local_dir, overwrite=False):
        """
        upload dir to hdfs
        Args:
            dest_dir(str): hdfs dest dir
            local_dir(str): hdfs local dir
            overwrite(bool): is overwrite
        Returns:
            return code
        """
        local_dir = local_dir.rstrip("/")
        dest_dir = dest_dir.rstrip("/")
        local_basename = os.path.basename(local_dir)
        if self.is_exist(dest_dir + "/" + local_basename) and overwrite:
            self.delete(dest_dir + "/" + local_basename)
        if not self.is_exist(dest_dir):
            self.makedirs(dest_dir)
        put_command = ["-put", local_dir, dest_dir]
600
        returncode, output, errors = self.__run_hdfs_cmd(put_command)
601 602 603 604 605 606
        if returncode != 0:
            _logger.error("Put local dir: {} to HDFS dir: {} failed".format(
                local_dir, dest_dir))
            return False
        return True

T
tangwei12 已提交
607 608 609 610 611 612 613 614 615 616 617 618 619

if __name__ == "__main__":
    hadoop_home = "/home/client/hadoop-client/hadoop/"

    configs = {
        "fs.default.name": "hdfs://xxx.hadoop.com:54310",
        "hadoop.job.ugi": "hello,hello123"
    }

    client = HDFSClient(hadoop_home, configs)

    client.ls("/user/com/train-25")
    files = client.lsr("/user/com/train-25/models")