#! @PYTHON@
#
# 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.

"""
ovs test utility that allows to do tests between remote hosts
"""

import fcntl
import math
import os
import select
import signal
import socket
import subprocess
import sys
import time
import xmlrpclib

import argparse
import twisted

import ovstest.args as args
import ovstest.rpcserver as rpcserver
import ovstest.tests as tests
import ovstest.util as util

DEFAULT_TEST_BRIDGE = "ovstestbr0"
DEFAULT_TEST_PORT = "ovstestport0"
DEFAULT_TEST_TUN = "ovstestport1"


def collect_information(node):
    """Print information about hosts that will do testing"""
    print "Node %s:%u " % (node[0], node[1])
    server = util.rpc_client(node[0], node[1])
    interface_name = server.get_interface(node[0])
    phys_iface = None
    uname = server.uname()
    mtu = 1500

    if not interface_name:
        print ("Could not find interface that has %s IP address."
               "Make sure that you specified correct Outer IP." % (node[0]))
    else:
        if server.is_ovs_bridge(interface_name):
            phys_iface = server.get_iface_from_bridge(interface_name)
        else:
            phys_iface = interface_name

    if phys_iface:
        driver = server.get_driver(phys_iface)
        mtu = server.get_interface_mtu(phys_iface)

        print "Will be using %s (%s) with MTU %u" % (phys_iface, node[0],
                                                    mtu)
        if not driver:
            print "Unable to get driver information from ethtool."
        else:
            print "On this host %s has %s." % (phys_iface, driver)

    if not uname:
        print "Unable to retrieve kernel information. Is this Linux?"
    else:
        print "Running kernel %s." % uname
    print "\n"

    return mtu


if __name__ == '__main__':
    local_server = None
    try:
        ovs_args = args.ovs_initialize_args()

        if ovs_args.port is not None:  # Start in pure server mode
            rpcserver.start_rpc_server(ovs_args.port)

        elif ovs_args.servers is not None:  # Run in client mode
            node1 = ovs_args.servers[0]
            node2 = ovs_args.servers[1]

            # Verify whether client will need to spawn a local instance of
            # ovs-test server by looking at the first OuterIP. if it is a
            # 127.0.0.1 then spawn local ovs-test server.
            if node1[0] == "127.0.0.1":
                local_server = util.start_local_server(node1[1])
                # We must determine the IP address that local ovs-test server
                # will use:
                me = util.rpc_client(node1[0], node1[1])
                my_ip = me.get_my_address_from(node2[0], node2[1])
                node1 = (my_ip, node1[1], node1[2], node1[3])

            mtu_node2 = collect_information(node2)
            mtu_node1 = collect_information(node1)

            bandwidth = ovs_args.targetBandwidth
            interval = ovs_args.testInterval
            ps = util.get_datagram_sizes(mtu_node1, mtu_node2)

            direct = ovs_args.direct
            vlan_tag = ovs_args.vlanTag
            tunnel_modes = ovs_args.tunnelModes

            if direct is not None:
                print "Performing direct tests"
                tests.do_direct_tests(node2, node1, bandwidth, interval, ps)

            if vlan_tag is not None:
                print "Performing VLAN tests"
                tests.do_vlan_tests(node2, node1, bandwidth, interval, ps,
                                    vlan_tag)

            for tmode in tunnel_modes:
                print "Performing", tmode, "tests"
                tests.do_l3_tests(node2, node1, bandwidth, interval, ps,
                                  tmode)

    except KeyboardInterrupt:
        pass
    except xmlrpclib.Fault:
        print "Couldn't establish XMLRPC control channel"
    except socket.error:
        print "Couldn't establish XMLRPC control channel"
    except xmlrpclib.ProtocolError:
        print "XMLRPC control channel was abruptly terminated"
    except twisted.internet.error.CannotListenError:
        print "Couldn't start XMLRPC server on port %u" % ovs_args.port
    finally:
        if local_server is not None:
            local_server.terminate()
