AUTHOR = "gps@google.com (Gregory P. Smith)"
TIME = "SHORT"
NAME = "barrier_2client"
TEST_CATEGORY = "Functional"
TEST_CLASS = 'Network'
TEST_TYPE = "Server"
SYNC_COUNT = 2
DOC = """
A functional test of autotest's Barrier mechanisms for synchronizing
events between two clients without the help of the server.
"""

from autotest_lib.server import utils

def run(pair):
    logging.info('Running on %s and %s', pair[0], pair[1])
    host_objs = [hosts.create_host(machine) for machine in pair]
    host_at_objs = [autotest.Autotest(host) for host in host_objs]

    client_control_template = """
import logging, platform, socket, traceback
try:
    client_hostnames = %r
    master_hostname = client_hostnames[0]
    client_hostname = client_hostnames[1]

    logging.info('Testing hostname only barrier')
    barrier = job.barrier(platform.node(), 'barriertest_2client', 120)
    logging.info('rendezvous-ing')
    barrier.rendezvous(master_hostname, client_hostname)
    logging.info('done.')

    logging.info('Testing local identifier barrier')
    barrier = job.barrier(platform.node() + '#id0', 'barriertest_2client', 120)
    logging.info('rendezvous-ing')
    barrier.rendezvous(master_hostname + '#id0',
                       client_hostname + '#id0')
    logging.info('done.')

    logging.info('Testing IP@ barrier')
    barrier = job.barrier(socket.gethostbyname(platform.node()),
                          'barriertest_2client', 120)
    logging.info('rendezvous-ing')
    barrier.rendezvous(socket.gethostbyname(master_hostname),
                       socket.gethostbyname(client_hostname))
    logging.info('done.')

    logging.info('Testing IP@ barrier with ids')
    barrier = job.barrier(socket.gethostbyname(platform.node()) + '#42',
                          'barriertest_2client', 120)
    logging.info('rendezvous-ing')
    barrier.rendezvous(socket.gethostbyname(master_hostname) + '#42',
                       socket.gethostbyname(client_hostname) + '#42')
    logging.info('done.')
except:
    traceback.print_exc()
    raise
"""
    client_controls = [client_control_template % (pair,) for host in host_objs]

    subcommand_list = []
    for host, host_at, control in zip(host_objs, host_at_objs, client_controls):
        subcommand_list.append(subcommand(host_at.run,
                                          (control, host.hostname)))

    parallel(subcommand_list)


# grab the pairs (and failures)
(pairs, failures) = utils.form_ntuples_from_machines(machines, 2)

# log the failures
for failure in failures:
    job.record("FAIL", failure[0], "barrier_2client", failure[1])

# now run through each pair and run
job.parallel_simple(run, pairs, log=False)