#!/usr/bin/python
#
# Participant list generator for 'throughput' task spec
#
# Input is a test spec, assumed to have been validated by spec-is-valid.
#
# Output is a list of hostnames or IPs that are participating.
#

import pscheduler
import sys


logger = pscheduler.Log(prefix='test-throughput', quiet=True)

json = pscheduler.json_load(exit_on_error=True, max_schema=1)

null_reason = None

#sender first participant, receiver the second
source = json.get('source-node', json.get('source', None))
if source is None:
    null_reason = "No source specified"

destination = json.get('dest-node', json.get('dest', None))
if destination is None:
    pscheduler.fail("Missing destination argument in spec")


######################################################################
# HACK: BWCTLBC
#Backward Compatibility Code: We can remove this once we drop BWCTL
#
# Check that both sides have pScheduler and do the following:
# * if both have pScheduler, proceed as normal
# * if only one has pscheduler, return just that one
# * if neither side does, fail the test

# This digs up everything we can on the hosts involved in a
# time-predictable way.
has = pscheduler.api_has_services([source, destination], timeout=3)

src_has_psc = has[source]["pscheduler"]
dst_has_psc = has[destination]["pscheduler"]


logger.debug("src_has_psc = %s, dst_has_psc = %s" % (src_has_psc, dst_has_psc))

if src_has_psc and dst_has_psc:
    participants = [ source, destination ]
elif src_has_psc:
    if not has[destination]["bwctl"]:
        pscheduler.fail("Can't find pScheduler or BWCTL on %s" % destination)
    participants = [ source ]
elif dst_has_psc:
    if not has[source]["bwctl"]:
        pscheduler.fail("Can't find pScheduler or BWCTL on %s " % source)
    participants = [ destination ]
else: 
    pscheduler.fail("Neither the source nor destination is running pScheduler.")


######################################################################


result = { "participants": participants }
if null_reason is not None:
    result["null-reason"] = null_reason

pscheduler.succeed_json(result)


