pypftp.py 22.9 KB
Newer Older
1 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 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 86 87 88 89 90 91 92 93 94 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 121 122 123 124 125 126 127 128 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 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 204 205 206 207 208 209 210 211 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 245 246 247 248 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 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 307 308 309 310 311 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 344 345 346 347 348 349 350 351 352 353 354 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 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 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
# -*- coding: utf-8 -*-

# ppftp.py

"""
python interface to HPSS's pftp

"""

import os
import re
import sys
import time
import netrc
import ftplib
import getpass
import fnmatch
import posixpath
import subprocess as sp

from concurrent.futures import ProcessPoolExecutor


HOST = 'tape.dkrz.de'
PORT = 4021


__all__ = ['upload', 'download', 'Pftp']


def _create_netrc(username=None, password=None, skip_header=True):
    username = username or getpass.getuser()
    userhome = os.environ.get('HOME')
    password = password or getpass.unix_getpass()
    header = "# machine <machine_name> login <user_name> password <password>"
    entry_fmt = "machine {0} login {1} password {2}"
    entry = entry_fmt.format(HOST, username, password)
    if skip_header:
        entries = "\n".join((entry, ''))
    else:
        entries = "\n".join((header, entry, ''))
    fname = os.path.join(userhome, '.netrc')
    with open(fname, 'w') as fid:
        fid.writelines(entries)
    os.chmod(fname, 0o600)
    return


def connect(username=None, password=None):

    ftp_obj = ftplib.FTP()
    ftp_obj.connect(HOST, PORT)

    username = username or getpass.getuser()
    if password is None:
        try:
            n = netrc.netrc()
        except IOError:
            _create_netrc(username, skip_header=False)
    n = netrc.netrc()
    credentials = n.hosts.get(HOST)
    if credentials is None:
        _create_netrc(username, password)
        n = netrc.netrc()
        credentials = n.hosts.get(HOST)
    username, account, password = credentials

    ftp_obj.login(username, password, account)
    return ftp_obj


_msg_re = re.compile('^[0-9]+-?\s?[A-Za-z].*').match


def filter_msg(lines):
    try:
        lines = lines.splitlines()
    except AttributeError:
        pass
    for line in lines:
        if line and not _msg_re(line):
            yield line


def msgs(lines):
    try:
        lines = lines.splitlines()
    except AttributeError:
        pass
    for line in lines:
        if _msg_re(line):
            yield line


class Pftp(object):
    HOST = HOST
    PORT = PORT

    def __init__(self, username=None, password=None):
        self.username = username = username or getpass.getuser()
        self.ftp_obj = connect(username, password)
        self._auth = {'username': username, 'password': password}

    def __repr__(self):
        is_active = self.is_connected()
        status = 'alive' if is_active else 'stale'
        s = ("<{0.__class__.__name__} connected to "
             "{0.HOST}:{0.PORT} "
             "as {0.username}>")
        s = s.format(self)
        s += "; connection={}".format(status)
        return repr(s)

    def is_connected(self):
        'check if the connection is still active'
        try:
            self.ftp_obj.voidcmd('NOOP')
        except:
            return False
        return True

    def reconnect(self):
        'reconnects to the ftp server'
        try:
            self.ftp_obj.close()
        except:
            pass
        self.ftp_obj = connect(self._auth['username'], self._auth['password'])

    def quit(self):
        self.ftp_obj.quit()

    def close(self):
        self.quit()
        self.ftp_obj.close()

    def pwd(self):
        'present working directory'
        return self.ftp_obj.pwd()

    def cwd(self, path):
        'change working directory'
        try:
            if path.startswith(self.pwd()):
                path = path.replace(self.pwd(), '').lstrip('/')
            self.ftp_obj.cwd(path)
        except:
            raise ValueError('Path does not exists: ' + path)

    def exists(self, path):
        "check if a path exists"
        try:
            result = self.stat(path)
        except:
            result = None
        return True if result else False

    def stat(self, pathname):
        "Returns stat of the path"
        try:
            _stat = self.ftp_obj.sendcmd('STAT {}'.format(pathname))
        except ftplib.error_perm:
            return None
        return list(filter_msg(_stat))

    def size(self, pathname):
        "Returns size of path in bytes"
        return int(self.stat(pathname)[0].split()[6])

    def isfile(self, pathname):
        "Returns true if pathname refers to an existing file"
        _stat = self.stat(pathname)
        if _stat is None:
            raise ValueError("path does not exists %s" % pathname)
        line = _stat.pop(0)
        if line[0] == '-':
            return True
        if line[0] == 'l':
            pwd = self.pwd()
            name = line.split()[-1]
            _flag = False
            try:
                self.cwd(name)
            except:
                _flag = True
            finally:
                self.cwd(pwd)
            return _flag
        return False

    def isdir(self, pathname):
        "Returns true if pathname refers to an existing directory"
        _stat = self.stat(pathname)
        if _stat is None:
            raise ValueError("path does not exists %s" % pathname)
        line = _stat.pop(0)
        if line[0] == 'd':
            return True
        if line[0] == 'l':
            pwd = self.pwd()
            name = line.split()[-1]
            try:
                self.cwd(name)
                _flag = True
            except ftplib.error_perm:
                _flag = False
            finally:
                self.cwd(pwd)
            return _flag
        return False

    def islink(self, pathname):
        _stat = self.stat(pathname)
        if _stat is None:
            raise ValueError("path does not exists %s" % pathname)
        line = _stat.pop(0)
        if line[0] == 'l':
            return True
        return False

    def listing(self, path=None):
        "list directory contents"
        path = path or self.pwd()
        return self.ftp_obj.nlst(path)

    listdir = listing

    def listing2(self, path=None):
        'directory listing in long form. similar to "ls -l"'
        path = path or self.pwd()
        tmp = []
        self.ftp_obj.dir(path, tmp.append)
        return tmp

    def files(self, path=None):
        "gather files at the given path"
        path = path or self.pwd()
        result = []
        for entry in self.listing2(path):
            name = entry.split()[-1]
            if entry.startswith('-'):
                result.append(name)
            if entry.startswith('l'):
                if self.isfile(name):
                    result.append(name)
        return result

    def directories(self, path=None):
        "gather directories at the given path"
        path = path or self.pwd()
        result = []
        for entry in self.listing2(path):
            name = entry.split()[-1]
            if entry.startswith('d'):
                result.append(name)
            if entry.startswith('l'):
                if self.isdir(name):
                    result.append(name)
        return result

    def walk(self, path=None):
        "recursively walk the directory tree from the given path. Similar to os.walk"
        path = path or self.pwd()
        _files = self.files(path)
        _subdirs = self.directories(path)
        yield (path, _subdirs, _files)
        for subdir in _subdirs:
            for x in self.walk(subdir):
                yield x

    def walk_for_files(self, path=None):
        "recursively gather files"
        for root, _dirs, _files in self.walk(path):
            for f in _files:
                yield f

    def walk_for_directories(self, path=None):
        "recursively gather directories"
        for root, _dirs, _files in self.walk(path):
            for d in _dirs:
                yield d

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    # ========== MANIPULATIONS ==========
    
    def mkdir(self, path):
        if not self.exists(path):
            print('Created directory: ' + path)
            self.ftp_obj.mkd(path)

    def makedirs(self, path):
        '''Recursively create dirs as required walking up to an existing
        parent dir'''
        try:
            _isdir = self.isdir(path)
        except ValueError:
            pass
        else:
            if _isdir:
                return
        dirname = posixpath.dirname(path)
        if dirname:
            self.makedirs(dirname)
        self.mkdir(path)
        return

    def rmdir(self, path):
        'remove directory'
        if self.exists(path):
            self.ftp_obj.rmd(path)
            print('Removed directory: ' + path)
        return

    def remove(self, filename):
        if self.exists(filename):
            self.ftp_obj.delete(filename)
            print('Deleted file: ' + filename)
        return

    def removedirs(self, path):
        remove = self.remove
        rmdir = self.rmdir
        path = posixpath.normpath(path)
        dirs = set()
        for topdir, subdirs, files in self.walk(path):
            for _file in files:
                remove(_file)
            if subdirs:
                dirs.update(subdirs)
            dirs.add(topdir)
        dirs = sorted(dirs, key=lambda x: len(x.split(posixpath.sep)),
                      reverse=True)
        for d in dirs:
            rmdir(d)
        return None

    def rename(self, from_name, to_name):
        if os.path.dirname(to_name) and (
                os.path.dirname(from_name) != os.path.dirname(to_name)):
            raise ValueError('Must rename a file within the same directory')
        self.ftp_obj.rename(from_name, to_name)
        return to_name

    # ========== FILE-TRANSFERS ==========

    @staticmethod
    def upload(source, destination):
        'uses pftp binary for transfering the file'
        return upload(source, destination)

    @staticmethod
    def download(source, destination):
        'uses pftp binary for transfering the file'
        return download(source, destination)


def printProgressBar(iteration, total, prefix='', suffix='',
                     decimals=1, length=80, fill=u'+'):
    "https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console"
    percent = ("{0:." + str(decimals) + "f}").format(
        100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),
          end='\r')
    # Print New Line on Complete
    # if iteration == total:
    #    print()
    return


def _transfer(cmdlines):
    client = sp.Popen('pftp', stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    o, e = client.communicate(cmdlines.encode('utf-8'))
    # for line in o:
    #    print(line)
    return


def _file_stripe_count(filename):
    cmd = ['lfs', 'getstripe', '-c', filename]
    return int(sp.check_output(cmd))


def _pftp_upload_commands(source, destination):
    source_filename = os.path.basename(source)
    source_dirname = os.path.dirname(source) or os.curdir
    cmd = ['prompt']
    stripe_count = _file_stripe_count(source)
    if stripe_count > 1:
        if stripe_count > 8:
            stripe_count = 8  # limit to 8 parallel tasks
        cmd.append('setpwidth {}'.format(stripe_count))
        cmd.append('setpblocksize {}'.format(1024 * 1024))  # 1MB
    if source_dirname != os.curdir:
        cmd.append('lcd {}'.format(source_dirname))
    cmd.append('cd {}'.format(destination))
    cmd.append('put {}'.format(source_filename))
    cmd.append('bye')
    cmd = '\n'.join(cmd)
    return cmd


def upload(source, destination):
    source = source.rstrip('/')
    destination = destination.rstrip('/')
    source_filename = os.path.basename(source)
    destination_maybe_filename = os.path.basename(destination)
    destination_dirname = os.path.dirname(destination)

    p = Pftp()
    
    requires_renaming = False
    if not p.exists(destination):
        if source_filename == destination_maybe_filename:
            destination = destination_dirname
        elif os.path.splitext(destination_maybe_filename)[-1]:
            destination = destination_dirname
            requires_renaming = True

    destination_filepath = os.path.join(destination, source_filename)

    p = Pftp()
    if not p.exists(destination):
        p.makedirs(destination)

    source_filesize = os.stat(source).st_size

    def get_filesize(filepath):
        if not p.is_connected():
            p.reconnect()
        if not p.exists(filepath):
            return 0
        return p.size(filepath)

    cmdlines = _pftp_upload_commands(source, destination)
    pool = ProcessPoolExecutor(1)
    fut = pool.submit(_transfer, cmdlines)

    # print('Uploading file: {}'.format(source_filename))
    while fut.running():
        time.sleep(1)
        current_size = get_filesize(destination_filepath)
        # if not current_size:
        #    print('\rWaiting for tape to respond...', end='\r')
        # else:
        #    printProgressBar(current_size, source_filesize, source_filename)
        printProgressBar(current_size, source_filesize, source_filename)

459 460 461
    # complete the progress bar
    printProgressBar(source_filesize, source_filesize, source_filename)
        
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    fut.result()
    if requires_renaming:
        p.cwd(destination_dirname)
        p.rename(source_filename, destination_maybe_filename)

    try:
        p.close()
    except:
        pass

    if requires_renaming:
        return os.path.join(destination, destination_maybe_filename)
    return os.path.join(destination, source_filename)


def _pftp_download_commands(source, destination):
    source_filename = os.path.basename(source)
    source_dirname = os.path.dirname(source) or os.curdir
    cmd = ['prompt']
    cmd.append('cd {}'.format(source_dirname))
    if source_dirname != os.curdir:
        cmd.append('lcd {}'.format(destination))
    cmd.append('get {}'.format(source_filename))
    cmd.append('bye')
    cmd = '\n'.join(cmd)
    return cmd


def download(source, destination):
    source = source.rstrip('/')
    destination = destination.rstrip('/')
    source_filename = os.path.basename(source)
    destination_maybe_filename = os.path.basename(destination)
    destination_dirname = os.path.dirname(destination)

    requires_renaming = False
    if not os.path.exists(destination):
        if source_filename == destination_maybe_filename:
            destination = destination_dirname
        elif os.path.splitext(destination_maybe_filename)[-1]:
            destination = destination_dirname
            requires_renaming = True

    destination_filepath = os.path.join(destination, source_filename)

    if not os.path.exists(destination):
        try:
            os.makedirs(destination)
        except:
            pass

    with Pftp() as p:
        source_filesize = p.size(source)

    def get_filesize(filepath):
        if not os.path.exists(filepath):
            return 0
        return os.path.getsize(filepath)

    cmdlines = _pftp_download_commands(source, destination)
    pool = ProcessPoolExecutor(1)
    fut = pool.submit(_transfer, cmdlines)

    # print('Downloading file: {}'.format(source_filename))
    while fut.running():
        time.sleep(1)
        current_size = get_filesize(destination_filepath)
        printProgressBar(current_size, source_filesize,
                         os.path.basename(destination_filepath))

532 533 534 535
    # Finish printing progress bar
    printProgressBar(current_size, source_filesize,
                     os.path.basename(destination_filepath))

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    fut.result()
    if requires_renaming:
        curdir = os.path.abspath(os.curdir)
        os.chdir(destination_dirname)
        os.rename(source_filename, destination_maybe_filename)
        os.chdir(curdir)

    if requires_renaming:
        return os.path.join(destination, destination_maybe_filename)
    return os.path.join(destination, source_filename)


def command_line_interface():
    import click

    wildcard_check = re.compile('[*?[]')

    def has_wildcard(path):
        return wildcard_check.search(path) is not None

    class WildcardInDirectoryPath(click.ParamType):
        name = 'PathWildcard'

        def convert(self, value, param, ctx):
            try:
                dirname = os.path.dirname(value)
                if has_wildcard(dirname):
                    raise ValueError
                return value
            except ValueError:
                msg = 'Wildcard only in file names are allowed {}'.format(value)
                self.fail(msg, param, ctx)

    WILDCARD_PATH = WildcardInDirectoryPath()

    def sizeof_fmt(num, suffix='B'):
        for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
            if abs(num) < 1024.0:
                return "%3.1f %s%s" % (num, unit, suffix)
            num /= 1024.0
        return "%.1f %s%s" % (num, 'Yi', suffix)

    @click.group()
    def main():
        """A command line interface for HPSS (tape archive)."""

    @main.command('download', short_help='Download files from tape')
    @click.argument('src', nargs=-1, type=WILDCARD_PATH)
    @click.argument('dst', nargs=1, type=click.Path())
    def _download(src, dst):
        """Download files from tape.

        \b
        SRC: file on tape
        DST: path on mistral
        """
        p = Pftp()
        files = []
        for entry in src:
            basename = os.path.basename(entry)
            if has_wildcard(basename):
                dirname = os.path.dirname(entry)
                contents = p.listdir(dirname)
                for fullname in contents:
                    if fnmatch.fnmatch(os.path.basename(fullname), basename):
                        files.append(fullname)
            else:
                if p.exists(entry):
                    files.append(entry)
        total_size = sum(map(p.size, files))
        nfiles = len(files)
        p.close()

        click.echo('{} files to download. Total size: {}'.format(
            nfiles, sizeof_fmt(total_size)))
        width = str(len(str(nfiles)))
        msg = '[{:>' + width + '}/{:>' + width + '}]'
        for index, fname in enumerate(files, 1):
            downloaded_file = download(fname, dst)
            count = msg.format(index, nfiles)
            click.echo(count + ' Downloaded: ' + downloaded_file + '  ')

    @main.command('upload', short_help='Upload files to tape')
    @click.argument('src', nargs=-1, type=click.Path())
    @click.argument('dst', nargs=1, type=click.Path())
    def _upload(src, dst):
        """Upload files to tape.

        \b
        SRC: file on mistral
        DST: path on tape
        """
        nfiles = len(src)
        total_size = sum(map(os.path.getsize, src))
        width = str(len(str(nfiles)))
        msg = '[{:>' + width + '}/{:>' + width + '}]'
        click.echo('{} files to upload. Total size: {}'.format(
            nfiles, sizeof_fmt(total_size)))
        for index, fname in enumerate(src, 1):
            uploaded_file = upload(fname, dst)
            count = msg.format(index, nfiles)
            click.echo(count + ' Uploaded: ' + uploaded_file + '  ')

    @main.command()
    @click.option('-l', default=False, is_flag=True, help="long listing")
    @click.argument('path', type=WILDCARD_PATH)
    def ls(path, l):
        """List directory contents on tape.

        \b
        PATH: path on tape
        """
        p = Pftp()
        if has_wildcard(path):
            listings = p.listdir(os.path.dirname(path))
            files = fnmatch.filter(listings, path)
            if l:
                listings2 = p.listing2(os.path.dirname(path))
                files = [long_path for short_path, long_path in zip(listings, listings2)
                         if short_path in files]
            for fname in files:
                click.echo(fname)
        else:
            if not p.exists(path):
                raise ValueError('Path does not exists')
                # click.echo('Path not found...')
            if l:
                contents = p.listing2(path)
            else:
                contents = p.listdir(path)
            for line in contents:
                click.echo(line)
        p.close()
        return

    @main.command()
    @click.argument('path')
    def exists(path):
        """check if PATH exists on tape.
        
        \b
        PATH: path on tape
        """
        with Pftp() as p:
            if not p.exists(path):
                click.echo('False')
            else:
                click.echo('True')

    @main.command()
    @click.option('-h', is_flag=True, help='human readable format')
    @click.argument('path')
    def size(path, h):
        """Prints file size in bytes. Use -h option for human readable format.
        
        \b
        PATH: path on tape
        """
        
        with Pftp() as p:
            if not p.exists(path):
                click.echo('File not found')
            else:
                fsize = p.size(path)
                if h:
                    fsize = sizeof_fmt(fsize)
                click.echo("{}".format(fsize))

    @main.command()
    @click.argument('path')
    def mkdir(path):
        """creates PATH on tape.
        
        \b
        PATH: path on tape
        """
        with Pftp() as p:
            if p.exists(path):
                click.echo('Already exists')
            else:
                p.makedirs(path)

    @main.command()
    @click.argument('path')
    def isdir(path):
        """checks if PATH is a directory.
        
        \b
        PATH: path on tape
        """
        with Pftp() as p:
            if not p.exists(path):
                click.echo('path not found')
            elif p.isdir(path):
                click.echo('True')
            else:
                click.echo('False')

    @main.command()
    @click.argument('path')
    def isfile(path):
        """checks if PATH is a file.
        
        \b
        PATH: path on tape
        """
        res = 1
        with Pftp() as p:
            if not p.exists(path):
                click.echo('path not found')
            elif p.isfile(path):
                click.echo('True')
                res = 0
            else:
                click.echo('False')
        sys.exit(res)

    @main.command()
    @click.argument('path')
    def islink(path):
        """checks if PATH is a link.
        
        \b
        PATH: path on tape
        """
        with Pftp() as p:
            if not p.exists(path):
                click.echo('path not found')
            elif p.islink(path):
                click.echo('True')
            else:
                click.echo('False')

    def pyversion_check():
        import os
        supported_versions = ('python/3.5.2', 'python/2.7.12')
        modules = os.environ.get('LOADEDMODULES', '')
        for version in supported_versions:
            if version in modules:
                break
        else:
            pyversion = ''.join([
                v for v in modules.split(':') if 'python' in v])
            msg = """\nLOADED VERSION: {}
SUPPORTED VERSIONS: {}
USE "module load" COMMAND TO LOAD A SUPPORTED PYTHON VERSION.
""".format(pyversion, " or ".join(supported_versions))
            import warnings
            warnings.warn(msg, RuntimeWarning, stacklevel=2)


    pyversion_check()
    main()


if __name__ == '__main__':
    command_line_interface()