#!/usr/bin/python3

# This file is part of Cockpit.
#
# Copyright (C) 2013 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import parent
from netlib import *
from testlib import *

from machine_core.constants import TEST_OS_DEFAULT


@nondestructive
class TestBonding(NetworkCase):
    def testBasic(self):
        b = self.browser
        m = self.machine

        self.login_and_go("/network")

        iface1 = "cockpit1"
        self.add_veth(iface1, dhcp_cidr="10.111.113.1/24", dhcp_range=['10.111.113.2', '10.111.113.254'])
        self.nm_activate_eth(iface1)
        iface2 = "cockpit2"
        self.add_veth(iface2, dhcp_cidr="10.111.114.1/24", dhcp_range=['10.111.114.2', '10.111.114.254'])
        self.nm_activate_eth(iface2)
        self.wait_for_iface(iface1)
        self.wait_for_iface(iface2)

        # Bond them
        b.click("button:contains('Add Bond')")
        b.wait_popup("network-bond-settings-dialog")
        if m.image != "rhel-8-2-distropkg": # Introduced in #13507
            b.click("#network-bond-settings-dialog .close.pficon-close")
            b.wait_popdown("network-bond-settings-dialog")
            b.click("button:contains('Add Bond')")
            b.wait_popup("network-bond-settings-dialog")
            b.click("#network-bond-settings-dialog .close.pficon-help")
            b.wait_visible(".popover .popover-title:contains('Network bond')")
            b.click("#network-bond-settings-dialog .close.pficon-help")
            b.wait_not_present(".popover .popover-title:contains('Network bond')")

        b.set_val("#network-bond-settings-interface-name-input", "tbond")
        b.set_checked("input[data-iface='%s']" % iface1, True)
        b.set_checked("input[data-iface='%s']" % iface2, True)
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")
        b.wait_present("#networking-interfaces tr[data-interface='tbond']")

        # Check that the configuration file has the expected sane name
        # on systems that use "network-scripts".
        if m.image not in ["fedora-coreos"]:
            m.execute("! test -d /etc/sysconfig || test -f /etc/sysconfig/network-scripts/ifcfg-tbond")

        # Check that the members are displayed and both On
        b.click("#networking-interfaces tr[data-interface='tbond'] td:first-child")
        b.wait_visible("#network-interface")
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface1)
        self.wait_onoff("#network-interface-slaves tr[data-interface='%s']" % iface1, True)
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface2)
        self.wait_onoff("#network-interface-slaves tr[data-interface='%s']" % iface2, True)

        # Check that it has the expected mode
        if m.image not in [ "rhel-8-2-distropkg" ]: #13866
            b.wait_in_text("#network-interface-settings", "Active Backup")

        # Deactivate the bond and make sure it is still there after a
        # reload.
        b.wait_text_not("#network-interface-mac", "")
        self.wait_onoff(".panel-heading:contains('tbond')", True)
        self.toggle_onoff(".panel-heading:contains('tbond')")
        b.wait_in_text("tr:contains('Status')", "Inactive")
        b.wait_not_present(".panel-heading:contains('tbond') .onoff-ct input:disabled")

        b.reload()
        b.enter_page("/network")
        b.wait_text("#network-interface-name", "tbond")
        b.wait_text("#network-interface-hw", "Bond")
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface1)
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface2)

        # Delete the bond
        b.click("#network-interface button:contains('Delete')")
        b.wait_visible("#networking")
        b.wait_not_present("#networking-interfaces tr[data-interface='tbond']")

        # Check that the former members are displayed and both On
        self.wait_for_iface(iface1)
        self.wait_for_iface(iface2)

        # Due to above reload
        self.allow_journal_messages(".*Connection reset by peer.*",
                                    "connection unexpectedly closed by peer")

    def testNonDefaultSettings(self):
        b = self.browser
        m = self.machine

        iface1 = "cockpit1"
        self.add_veth(iface1, dhcp_cidr="10.111.113.1/24", dhcp_range=['10.111.113.2', '10.111.113.254'])
        wait(lambda: m.execute('nmcli device | grep %s | grep -v unavailable' % iface1))

        iface2 = "cockpit2"
        self.add_veth(iface2, dhcp_cidr="10.111.114.1/24", dhcp_range=['10.111.114.2', '10.111.114.254'])
        wait(lambda: m.execute('nmcli device | grep %s | grep -v unavailable' % iface2))

        m.execute("nmcli con add type ethernet ifname %s con-name TEST1" % iface1)
        m.execute("nmcli con add type ethernet ifname %s con-name TEST2" % iface2)

        self.login_and_go("/network")
        self.wait_for_iface(iface1)
        self.wait_for_iface(iface2)

        m.execute("nmcli con mod TEST1 ipv4.method link-local && nmcli con up TEST1")
        m.execute("nmcli dev dis %s" % iface2)

        b.wait_in_text("tr[data-interface='%s'] td:nth-child(2)" % iface1, "169.254.")
        b.wait_not_in_text("tr[data-interface='%s'] td:nth-child(2)" % iface1, "10.111.")
        b.wait_text("tr[data-interface='%s'] td:nth-child(3)" % iface2, "Inactive")

        b.click("button:contains('Add Bond')")
        b.wait_popup("network-bond-settings-dialog")
        b.set_val("#network-bond-settings-interface-name-input", "tbond")
        b.set_checked("input[data-iface='%s']" % iface1, True)
        b.set_checked("input[data-iface='%s']" % iface2, True)
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")

        b.click("#networking-interfaces tr[data-interface='tbond'] td:first-child")
        b.wait_visible("#network-interface")
        b.wait_in_text("tr:contains('IPv4')", "Link local")

    def testRename(self):
        b = self.browser
        m = self.machine

        self.login_and_go("/network")

        # Wait until the page is really ready by waiting for some ethernet interface
        # to show up in some row.
        iface = m.execute("cd /sys/class/net && ls -d e* | head -n1").strip()
        b.wait_present("tr[data-interface='%s']" % iface)

        # Make a simple bond without any members.  This is enough to
        # test the renaming.

        b.click("button:contains('Add Bond')")
        b.wait_popup("network-bond-settings-dialog")
        b.set_val("#network-bond-settings-interface-name-input", "tbond")
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")

        # Rename while it is active
        self.addCleanup(m.execute, "nmcli dev delete tbond3000 2>/dev/null || true")

        b.click("#networking-interfaces tr[data-interface='tbond'] td:first-child")
        self.wait_onoff("#network-interface .panel-heading", True)
        b.wait_in_text("tr:contains('Status')", "Configuring")

        b.click("tr:contains('Bond') a")
        b.wait_popup("network-bond-settings-dialog")
        b.set_val("#network-bond-settings-interface-name-input", "tbond3000")
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")
        b.wait_text("#network-interface-name", "tbond3000")

    def testActive(self):
        b = self.browser

        self.login_and_go("/network")

        iface = "cockpit1"
        self.add_veth(iface, dhcp_cidr="10.111.112.2/20")
        self.nm_activate_eth(iface)
        self.wait_for_iface(iface)
        ip = b.text("#networking-interfaces tr[data-interface='%s'] td:nth-child(2)" % iface)

        # Put an active interface into a bond.  The bond should get
        # the same IP as the active interface.

        b.click("button:contains('Add Bond')")
        b.wait_popup("network-bond-settings-dialog")
        b.set_val("#network-bond-settings-interface-name-input", "tbond")
        b.set_checked("input[data-iface='%s']" % iface, True)
        b.click("#network-bond-settings-mac-input + .dropdown .dropdown-toggle")
        b.click("#network-bond-settings-mac-input + .dropdown a:contains('(cockpit1)')")
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")

        # Check that it has the interface enslaved and the right IP address
        b.click("#networking-interfaces tr[data-interface='tbond'] td:first-child")
        b.wait_visible("#network-interface")
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface)
        b.wait_in_text("#network-interface .panel:contains('tbond')", ip)

    def testAmbiguousSlave(self):
        b = self.browser
        m = self.machine

        self.login_and_go("/network")

        iface = "cockpit1"
        self.add_veth(iface, dhcp_cidr="10.111.113.2/20")
        self.nm_activate_eth(iface)
        self.wait_for_iface(iface)

        # Now 'iface' has a normal connection
        con_id = self.iface_con_id(iface)
        self.assertTrue(con_id)

        # Manually create a bond and make 'iface' its slave via a
        # second connection.  Cockpit should ignore that second
        # connection and still show iface as a normal interface.
        m.execute("nmcli con add type bond-slave ifname %s  con-name bond0-slave-1 master bond0" % iface)
        m.execute("nmcli con add type bond ifname bond0 con-name bond0")

        self.wait_for_iface("bond0", state="Configuring")
        self.wait_for_iface(iface)

        # Now activate 'iface' as a slave.  Cockpit should now ignore
        # the first connection and show 'iface' as a slave of bond0.

        m.execute("nmcli con up bond0-slave-1")
        b.wait_not_present("#networking-interfaces tr[data-interface='%s']" % iface)

        b.click("#networking-interfaces tr[data-interface='bond0'] td:first-child")
        b.wait_visible("#network-interface")
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface)


class TestBondingVirt(NetworkCase):
    provision = {
        "machine1": {"address": "10.111.113.1/20"},
        "machine2": {"image": TEST_OS_DEFAULT, "address": "10.111.113.2/20", "dhcp": True}
    }

    @skipImage("Main interface can't be managed", "debian-stable", "debian-testing", "ubuntu-2004", "ubuntu-stable")
    def testMain(self):
        b = self.browser
        m = self.machine

        iface = self.get_iface(m, m.networking["mac"])

        self.login_and_go("/network")
        self.wait_for_iface(iface)

        # Put the main interface into a bond.  Everything should keep working.
        b.click("button:contains('Add Bond')")
        b.wait_popup("network-bond-settings-dialog")
        b.set_val("#network-bond-settings-interface-name-input", "tbond")
        b.set_checked("input[data-iface='%s']" % iface, True)
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")

        # Check that it has the main connection enslaved and the right IP address
        b.click("#networking-interfaces tr[data-interface='tbond'] td:first-child")
        b.wait_visible("#network-interface")
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface)
        b.wait_in_text("#network-interface .panel:contains('tbond')", "10.111.113.1")

        # Delete the bond
        b.click("#network-interface button:contains('Delete')")
        b.wait_visible("#networking")
        b.wait_not_present("#networking-interfaces tr[data-interface='tbond']")
        b.wait_present("#networking-interfaces tr[data-interface='%s']" % iface)

    @skipImage("Main interface can't be managed", "debian-stable", "debian-testing", "ubuntu-2004", "ubuntu-stable")
    @skipImage("not using dhclient", "fedora-coreos")
    def testSlowly(self):
        b = self.browser
        m = self.machine

        iface = self.get_iface(m, m.networking["mac"])
        self.ensure_nm_uses_dhclient()

        self.login_and_go("/network")
        self.wait_for_iface(iface)

        # Slow down DHCP enough that it would trigger a rollback.
        self.slow_down_dhclient(20)

        # Put the main interface into a bond.  Everything should keep
        # working since checkpoints are not used and thus no rollback
        # is actually triggered.

        b.click("button:contains('Add Bond')")
        b.wait_popup("network-bond-settings-dialog")
        b.set_val("#network-bond-settings-interface-name-input", "tbond")
        b.set_checked("input[data-iface='%s']" % iface, True)
        b.click("#network-bond-settings-dialog button:contains('Apply')")
        b.wait_popdown("network-bond-settings-dialog")

        # Check that it has the main connection enslaved and the right IP address
        b.click("#networking-interfaces tr[data-interface='tbond'] td:first-child")
        b.wait_visible("#network-interface")
        b.wait_present("#network-interface-slaves tr[data-interface='%s']" % iface)
        b.wait_in_text("#network-interface .panel:contains('tbond')", "10.111.113.1")


if __name__ == '__main__':
    test_main()
