#!/usr/bin/env python
# -*- Mode: python -*-
#
# Usage: pssh [OPTIONS] -h hosts.txt prog [arg0] [arg1] ..
#
# Parallel ssh to the set of nodes in hosts.txt. For each node, this
# essentially does an "ssh host -l user prog [arg0] [arg1] ...". The -o
# option can be used to store stdout from each remote node in a
# directory.  Each output file in that directory will be named by the
# corresponding remote node's hostname or IP address.
#
# Created: 16 August 2003
#
# $Id: pssh 348 2008-06-05 06:57:26Z bnc $
#
import fcntl, os, popen2, pwd, select, signal, sys, threading, time

basedir, bin = os.path.split(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.path.append("%s" % basedir)

import psshlib
from psshlib.basethread import BaseThread

_DEFAULT_PARALLELISM = 32
_DEFAULT_TIMEOUT     = 60

def print_usage():
    print "Usage: pssh [OPTIONS] -h hosts.txt prog [arg0] .."
    print
    print "  -h --hosts   hosts file (each line \"host[:port] [user]\")"
    print "  -l --user    username (OPTIONAL)"
    print "  -p --par     max number of parallel threads (OPTIONAL)"
    print "  -o --outdir  output directory for stdout files (OPTIONAL)"
    print "  -e --errdir  output directory for stderr files (OPTIONAL)"
    print "  -t --timeout timeout in seconds to do ssh to a host (OPTIONAL)"
    print "  -v --verbose turn on warning and diagnostic messages (OPTIONAL)"
    print "  -O --options SSH options (OPTIONAL)"
    print "  -P --print   print output as we get it (OPTIONAL)"
    print "  -i --inline  inline aggregated output for each server (OPTIONAL)"
    print
    print "Example: pssh -h nodes.txt -l irb2 -o /tmp/foo uptime"
    print

def read_envvars(flags):
    if os.getenv("PSSH_HOSTS"):
        flags["hosts"] = os.getenv("PSSH_HOSTS")
    if os.getenv("PSSH_USER"):
        flags["user"] = os.getenv("PSSH_USER")
    if os.getenv("PSSH_PAR"):
        flags["par"] = int(os.getenv("PSSH_PAR"))
    if os.getenv("PSSH_OUTDIR"):
        flags["outdir"] = os.getenv("PSSH_OUTDIR")
    if os.getenv("PSSH_ERRDIR"):
        flags["errdir"] = os.getenv("PSSH_ERRDIR")
    if os.getenv("PSSH_TIMEOUT"):
        flags["timeout"] = int(os.getenv("PSSH_TIMEOUT"))
    if os.getenv("PSSH_VERBOSE"): # "0" or "1"
        flags["verbose"] = int(os.getenv("PSSH_VERBOSE"))
    if os.getenv("PSSH_OPTIONS"):
        flags["options"] = os.getenv("PSSH_OPTIONS")

def parsecmdline(argv):
    import getopt
    shortopts = "h:l:p:o:e:t:vO:Pi"
    longopts = [ "hosts", "user", "par", "outdir", "errdir", "timeout",
                 "verbose", "options", "print", "inline" ]
    flags = { "hosts" : None, "user" : None, "par" : _DEFAULT_PARALLELISM,
              "outdir" : None, "errdir" : None, "timeout" : _DEFAULT_TIMEOUT,
              "verbose" : None, "options" : None, "print" : None, "inline": None }
    read_envvars(flags)
    if not flags["user"]: flags["user"] = pwd.getpwuid(os.getuid())[0] # Default to current user
    opts, args = getopt.getopt(argv[1:], shortopts, longopts)
    for o, v in opts:
        if o in ("-h", "--hosts"):
            flags["hosts"] = v
        elif o in ("-l", "--user"):
            flags["user"] = v
        elif o in ("-p", "--par"):
            flags["par"] = int(v)
        elif o in ("-o", "--outdir"):
            flags["outdir"] = v
        elif o in ("-e", "--errdir"):
            flags["errdir"] = v
        elif o in ("-t", "--timeout"):
            flags["timeout"] = int(v)
        elif o in ("-v", "--verbose"):
            flags["verbose"] = 1
        elif o in ("-O", "--options"):
            flags["options"] = v
        elif o in ("-P", "--print"):
            flags["print"] = 1
        elif o in ("-i", "--inline"):
            flags["inline"] = 1
    # Required flags
    if not flags["hosts"]:
        print_usage()
        sys.exit(3)
    return args, flags

def buffer_input():
    fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
    try:
        return sys.stdin.read()
    except IOError: # Stdin contained no information
        return ''

def do_pssh(hosts, ports, users, cmdline, flags):
    import os, re
    if flags["outdir"] and not os.path.exists(flags["outdir"]):
        os.makedirs(flags["outdir"])
    if flags["errdir"] and not os.path.exists(flags["errdir"]):
        os.makedirs(flags["errdir"])
    input = buffer_input()
    sem = threading.Semaphore(flags["par"])
    threads = []
    for i in range(len(hosts)):
        sem.acquire()
        if flags["verbose"]:
            quietswitch = ""
        else:
            quietswitch = "-q"
        if flags["options"]:
            cmd = "ssh -o \"%s\" %s -p %s -l %s %s \"%s\"" % \
                       (flags["options"], hosts[i], ports[i], users[i],
                        quietswitch, cmdline)
        else:
            cmd = "ssh %s -p %s -l %s %s \"%s\"" % \
                       (hosts[i], ports[i], users[i], quietswitch, cmdline)
        t = BaseThread(hosts[i], ports[i], cmd, flags, sem, input)
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

def main():
    from psshlib import psshutil
    args, flags = parsecmdline(sys.argv)
    if len(args) == 0:
        print_usage()
        sys.exit(3)
    cmdline = " ".join(args)
    hosts, ports, users = psshutil.read_hosts(flags["hosts"])
    psshutil.patch_users(hosts, ports, users, flags["user"])
    signal.signal(signal.SIGCHLD, psshutil.reaper)
    os.setpgid(0, 0)
    do_pssh(hosts, ports, users, cmdline, flags)

if __name__ == "__main__":
    main()
