Esempio n. 1
0
    def setNetworkDetails(self):
        self.net_text1.set_text(
            "Interface: %-13s  Link: %s" %
            (self.activeiface,
             self.netsettings[self.activeiface]['link'].upper()))

        self.net_text2.set_text("IP:      %-15s  MAC: %s" %
                                (self.netsettings[self.activeiface]['addr'],
                                 self.netsettings[self.activeiface]['mac']))
        self.net_text3.set_text(
            "Netmask: %-15s  Gateway: %s" %
            (self.netsettings[self.activeiface]['netmask'], self.gateway))
        #Set text fields to current netsettings
        for index, fieldname in enumerate(self.fields):
            if fieldname == "ifname":
                self.edits[index].base_widget.set_edit_text(self.activeiface)
            elif fieldname == "bootproto":
                rb_group = self.edits[index].rb_group
                for rb in rb_group:
                    if self.netsettings[self.activeiface]["bootproto"].lower()\
                            == "dhcp":
                        rb_group[0].set_state(True)
                        rb_group[1].set_state(False)
                    else:
                        rb_group[0].set_state(False)
                        rb_group[1].set_state(True)
            elif fieldname == "onboot":
                rb_group = self.edits[index].rb_group
                for rb in rb_group:
                    if self.netsettings[self.activeiface]["onboot"].lower()\
                            == "yes":
                        rb_group[0].set_state(True)
                        rb_group[1].set_state(False)
                else:
                    #onboot should only be no if the interface is also down
                    if self.netsettings[self.activeiface]['addr'] == "":
                        rb_group[0].set_state(False)
                        rb_group[1].set_state(True)
                    else:
                        rb_group[0].set_state(True)
                        rb_group[1].set_state(False)

            elif fieldname == "ipaddr":
                self.edits[index].set_edit_text(
                    self.netsettings[self.activeiface]['addr'])
            elif fieldname == "netmask":
                self.edits[index].set_edit_text(
                    self.netsettings[self.activeiface]['netmask'])
            elif fieldname == "gateway":
                #Gateway is for this iface only if gateway is matches subnet
                if network.inSameSubnet(
                        self.netsettings[self.activeiface]['addr'],
                        self.gateway,
                        self.netsettings[self.activeiface]['netmask']):
                    self.edits[index].set_edit_text(self.gateway)
                else:
                    self.edits[index].set_edit_text("")
Esempio n. 2
0
    def setNetworkDetails(self):
        self.net_text1.set_text("Interface: %-13s  Link: %s" % (
            self.activeiface,
            self.netsettings[self.activeiface]['link'].upper()))

        self.net_text2.set_text("IP:      %-15s  MAC: %s" % (
            self.netsettings[self.activeiface]['addr'],
            self.netsettings[self.activeiface]['mac']))
        self.net_text3.set_text("Netmask: %-15s  Gateway: %s" % (
            self.netsettings[self.activeiface]['netmask'],
            self.gateway))
        # Set text fields to current netsettings
        for index, fieldname in enumerate(self.fields):
            if fieldname == "ifname":
                self.edits[index].base_widget.set_edit_text(self.activeiface)
            elif fieldname == "bootproto":
                rb_group = self.edits[index].rb_group
                for rb in rb_group:
                    if self.netsettings[self.activeiface]["bootproto"].lower()\
                            == "dhcp":
                        rb_group[1].set_state(True)
                        rb_group[0].set_state(False)
                    else:
                        rb_group[1].set_state(False)
                        rb_group[0].set_state(True)
            elif fieldname == "onboot":
                rb_group = self.edits[index].rb_group
                for rb in rb_group:
                    if self.netsettings[self.activeiface]["onboot"].lower()\
                            == "yes":
                        rb_group[0].set_state(True)
                        rb_group[1].set_state(False)
                else:
                    # onboot should only be no if the interface is also down
                    if self.netsettings[self.activeiface]['addr'] == "":
                        rb_group[0].set_state(False)
                        rb_group[1].set_state(True)
                    else:
                        rb_group[0].set_state(True)
                        rb_group[1].set_state(False)

            elif fieldname == "ipaddr":
                self.edits[index].set_edit_text(self.netsettings[
                    self.activeiface]['addr'])
            elif fieldname == "netmask":
                self.edits[index].set_edit_text(self.netsettings[
                    self.activeiface]['netmask'])
            elif fieldname == "gateway":
                # Gateway is for this iface only if gateway is matches subnet
                if network.inSameSubnet(
                        self.netsettings[self.activeiface]['addr'],
                        self.gateway,
                        self.netsettings[self.activeiface]['netmask']):
                    self.edits[index].set_edit_text(self.gateway)
                else:
                    self.edits[index].set_edit_text("")
    def check(self, args):
        """Validates all fields have valid values and some sanity checks."""
        self.parent.footer.set_text("Checking data...")
        self.parent.refreshScreen()

        #Refresh networking to make sure IP matches
        self.getNetwork()

        #Get field information
        responses = dict()

        for index, fieldname in enumerate(self.fields):
            if fieldname != "blank" and "label" not in fieldname:
                responses[fieldname] = self.edits[index].get_edit_text()

        ###Validate each field
        errors = []

        #Set internal_{ipaddress,netmask,interface}
        responses["ADMIN_NETWORK/interface"] = self.activeiface
        responses["ADMIN_NETWORK/netmask"] = self.netsettings[
            self.activeiface]["netmask"]
        responses["ADMIN_NETWORK/mac"] = self.netsettings[
            self.activeiface]["mac"]
        responses["ADMIN_NETWORK/ipaddress"] = self.netsettings[
            self.activeiface]["addr"]

        #ensure management interface is valid
        if responses["ADMIN_NETWORK/interface"] not in self.netsettings.keys():
            errors.append("Management interface not valid")
        else:
            self.parent.footer.set_text("Scanning for DHCP servers. \
Please wait...")
            self.parent.refreshScreen()

            ###Start DHCP check on this interface
            #dhcp_server_data=[{'server_id': '192.168.200.2', 'iface': 'eth2',
            #                   'yiaddr': '192.168.200.15', 'mac':
            #                '52:54:00:12:35:02', 'server_ip': '192.168.200.2',
            #                   'dport': 67, 'message': 'offer',
            #                   'gateway': '0.0.0.0'}]
            try:
                dhcptimeout = 5
                default = []
                with timeout.run_with_timeout(dhcp_checker.utils.IfaceState,
                                              [self.activeiface],
                                              timeout=dhcptimeout) as iface:
                    dhcp_server_data = timeout.run_with_timeout(
                        dhcp_checker.api.check_dhcp_on_eth,
                        [iface, dhcptimeout], timeout=dhcptimeout,
                        default=default)
            except (KeyboardInterrupt, timeout.TimeoutError):
                log.debug("DHCP scan timed out")
                log.warning(traceback.format_exc())
                dhcp_server_data = default

            num_dhcp = len(dhcp_server_data)
            if num_dhcp == 0:
                log.debug("No DHCP servers found")
            else:
                #Problem exists, but permit user to continue
                log.error("%s foreign DHCP server(s) found: %s" %
                          (num_dhcp, dhcp_server_data))

                #Build dialog elements
                dhcp_info = []
                dhcp_info.append(urwid.Padding(
                                 urwid.Text(("header", "!!! WARNING !!!")),
                                 "center"))
                dhcp_info.append(widget.TextLabel("You have selected an \
interface that contains one or more DHCP servers. This will impact \
provisioning. You should disable these DHCP servers before you continue, or \
else deployment will likely fail."))
                dhcp_info.append(widget.TextLabel(""))
                for index, dhcp_server in enumerate(dhcp_server_data):
                    dhcp_info.append(widget.TextLabel("DHCP Server #%s:" %
                                     (index + 1)))
                    dhcp_info.append(widget.TextLabel("IP address: %-10s" %
                                     dhcp_server['server_ip']))
                    dhcp_info.append(widget.TextLabel("MAC address: %-10s" %
                                     dhcp_server['mac']))
                    dhcp_info.append(widget.TextLabel(""))
                dialog.display_dialog(self, urwid.Pile(dhcp_info),
                                      "DHCP Servers Found on %s"
                                      % self.activeiface)
            ###Ensure pool start and end are on the same subnet as mgmt_if
            #Ensure mgmt_if has an IP first
            if len(self.netsettings[responses[
               "ADMIN_NETWORK/interface"]]["addr"]) == 0:
                errors.append("Go to Interfaces to configure management \
interface first.")
            else:
                #Ensure ADMIN_NETWORK/interface is not running DHCP
                if self.netsettings[responses[
                        "ADMIN_NETWORK/interface"]]["bootproto"] == "dhcp":
                    errors.append("%s is running DHCP. Change it to static "
                                  "first." % self.activeiface)
                #Ensure DHCP Pool Start and DHCP Pool are valid IPs
                try:
                    if netaddr.valid_ipv4(responses[
                                          "ADMIN_NETWORK/dhcp_pool_start"]):
                        dhcp_start = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_start"])
                        if not dhcp_start:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool Start")
                try:
                    if netaddr.valid_ipv4(responses[
                            "ADMIN_NETWORK/dhcp_gateway"]):
                        dhcp_gateway = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_gateway"])
                        if not dhcp_gateway:
                            raise BadIPException("Not a valid IP address")
                    else:
                            raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Gateway")

                try:
                    if netaddr.valid_ipv4(responses[
                            "ADMIN_NETWORK/dhcp_pool_end"]):
                        dhcp_end = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_end"])
                        if not dhcp_end:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool end")

                #Ensure pool start and end are in the same subnet of each other
                netmask = self.netsettings[responses[
                                           "ADMIN_NETWORK/interface"
                                           ]]["netmask"]
                if not network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_pool_start"],
                        responses["ADMIN_NETWORK/dhcp_pool_end"], netmask):
                    errors.append("DHCP Pool start and end are not in the "
                                  "same subnet.")

                #Ensure pool start and end are in the right netmask
                mgmt_if_ipaddr = self.netsettings[responses[
                    "ADMIN_NETWORK/interface"]]["addr"]
                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_pool_start"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool start does not match management"
                                  " network.")
                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_pool_end"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool end does not match management "
                                  "network.")

                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_gateway"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Gateway does not match management "
                                  "network.")

                self.parent.footer.set_text("Scanning for duplicate IP address"
                                            "es. Please wait...")
                # Bind arping to mgmt_if_ipaddr if it assigned
                assigned_ips = [v.get('addr') for v in
                                self.netsettings.itervalues()]
                arping_bind = mgmt_if_ipaddr in assigned_ips
                if network.duplicateIPExists(mgmt_if_ipaddr, self.activeiface,
                                             arping_bind):
                    errors.append("Duplicate host found with IP {0}.".format(
                        mgmt_if_ipaddr))

        if len(errors) > 0:
            self.parent.footer.set_text("Error: %s" % (errors[0]))
            log.error("Errors: %s %s" % (len(errors), errors))
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
    def setNetworkDetails(self):
        self.net_text1.set_text("Interface: %-13s  Link: %s" % (
            self.activeiface, self.netsettings[self.activeiface]['link'].
            upper()))
        self.net_text2.set_text("IP:      %-15s  MAC: %s" % (self.netsettings[
            self.activeiface]['addr'],
            self.netsettings[self.activeiface]['mac']))
        self.net_text3.set_text("Netmask: %-15s  Gateway: %s" % (
            self.netsettings[self.activeiface]['netmask'],
            self.gateway))
        log.debug("bootproto for %s: %s" % (self.netsettings[self.activeiface],
                  self.netsettings[self.activeiface]['bootproto']))
        if self.netsettings[self.activeiface]['link'].upper() == "UP":
            if self.netsettings[self.activeiface]['bootproto'] == "dhcp":
                self.net_text4.set_text("WARNING: Cannot use interface running"
                                        " DHCP.\nReconfigure as static in "
                                        "Network Setup screen.")
            else:
                self.net_text4.set_text("")
        else:
            self.net_text4.set_text("WARNING: This interface is DOWN. "
                                    "Configure it first.")

        #If DHCP pool start and matches activeiface network, don't update
        #This means if you change your pool values, go to another page, then
        #go back, it will not reset your changes. But what is more likely is
        #you will change the network settings for interface eth0 and then come
        #back to this page to update your DHCP settings. If the inSameSubnet
        #test fails, just recalculate and set new values.
        for index, key in enumerate(self.fields):
            if key == "ADMIN_NETWORK/dhcp_pool_start":
                dhcp_start = self.edits[index].get_edit_text()
                break
        if network.inSameSubnet(dhcp_start,
                                self.netsettings[self.activeiface]['addr'],
                                self.netsettings[self.activeiface]['netmask']):
            log.debug("Existing network settings exist. Not changing.")
            return
        else:
            log.debug("Existing network settings missing or invalid. "
                      "Updating...")

        #Calculate and set Static/DHCP pool fields
        #Max IPs = net size - 2 (master node + bcast)
        #Add gateway so we exclude it
        net_ip_list = network.getNetwork(
            self.netsettings[self.activeiface]['addr'],
            self.netsettings[self.activeiface]['netmask'],
            self.gateway)
        try:
            dhcp_pool = net_ip_list[1:]
            dynamic_start = str(dhcp_pool[0])
            dynamic_end = str(dhcp_pool[-1])
            if self.net_text4.get_text() == "":
                self.net_text4.set_text("This network configuration can "
                                        "support %s nodes." % len(dhcp_pool))
        except Exception:
            #We don't have valid values, so mark all fields empty
            dynamic_start = ""
            dynamic_end = ""
        for index, key in enumerate(self.fields):
            if key == "ADMIN_NETWORK/dhcp_pool_start":
                self.edits[index].set_edit_text(dynamic_start)
            elif key == "ADMIN_NETWORK/dhcp_pool_end":
                self.edits[index].set_edit_text(dynamic_end)
            elif key == "ADMIN_NETWORK/dhcp_gateway":
                self.edits[index].set_edit_text(self.netsettings[
                    self.activeiface]['addr'])
Esempio n. 5
0
    def check(self, args):
        """Validate that all fields have valid values and sanity checks."""
        # Get field information
        responses = dict()
        self.parent.footer.set_text("Checking data...")
        for index, fieldname in enumerate(self.fields):
            if fieldname == "blank" or fieldname == "ifname":
                pass
            elif fieldname == "bootproto":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["bootproto"] = "none"
                else:
                    responses["bootproto"] = "dhcp"
            elif fieldname == "onboot":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["onboot"] = "yes"
                else:
                    responses["onboot"] = "no"
            else:
                responses[fieldname] = self.edits[index].get_edit_text()

        # Validate each field
        errors = []

        # Check for the duplicate IP provided
        for k, v in six.iteritems(self.netsettings):
            if (k != self.activeiface and responses["ipaddr"] != ''
                    and responses["ipaddr"] == v.get('addr')):
                errors.append("The same IP address {0} is assigned for "
                              "interfaces '{1}' and '{2}'.".format(
                                  responses["ipaddr"], k, self.activeiface))
                break

        if responses["onboot"] == "no":
            numactiveifaces = 0
            for iface in self.netsettings:
                if self.netsettings[iface]['addr'] != "":
                    numactiveifaces += 1
            if numactiveifaces < 2 and \
                    self.netsettings[self.activeiface]['addr'] != "":
                # Block user because puppet l23network fails if all interfaces
                # are disabled.
                errors.append("Cannot disable all interfaces.")
        elif responses["bootproto"] == "dhcp":
            self.parent.footer.set_text("Scanning for DHCP servers. "
                                        "Please wait...")
            self.parent.refreshScreen()
            try:
                dhcptimeout = 5
                dhcp_server_data = network.search_external_dhcp(
                    self.activeiface, dhcptimeout)
            except network.NetworkException:
                self.log.warning("dhcp_checker failed to check on %s"
                                 % self.activeiface)
                dhcp_server_data = []

            if len(dhcp_server_data) < 1:
                errors.append("No DHCP servers found. Cannot enable DHCP")

        # Check ipaddr, netmask, gateway only if static
        elif responses["bootproto"] == "none":
            try:
                if netaddr.valid_ipv4(responses["ipaddr"]):
                    if not netaddr.IPAddress(responses["ipaddr"]):
                        raise BadIPException("Not a valid IP address")
                else:
                    raise BadIPException("Not a valid IP address")
            except (BadIPException, Exception):
                errors.append("Not a valid IP address: %s" %
                              responses["ipaddr"])
            try:
                if netaddr.valid_ipv4(responses["netmask"]):
                    netmask = netaddr.IPAddress(responses["netmask"])
                    if netmask.is_netmask is False:
                        raise BadIPException("Not a valid IP address")
                else:
                    raise BadIPException("Not a valid IP address")
            except (BadIPException, Exception):
                errors.append("Not a valid netmask: %s" % responses["netmask"])
            try:
                if len(responses["gateway"]) > 0:
                    # Check if gateway is valid
                    if netaddr.valid_ipv4(responses["gateway"]) is False:
                        raise BadIPException("Gateway IP address is not valid")
                    # Check if gateway is in same subnet
                    if network.inSameSubnet(responses["ipaddr"],
                                            responses["gateway"],
                                            responses["netmask"]) is False:
                        raise BadIPException("Gateway IP is not in same "
                                             "subnet as IP address")
            except (BadIPException, Exception) as e:
                errors.append(e)
            self.parent.footer.set_text("Scanning for duplicate IP address..")
            if len(responses["ipaddr"]) > 0:
                if self.netsettings[self.activeiface]['link'].upper() != "UP":
                    try:
                        network.upIface(self.activeiface)
                    except NetworkException as e:
                        errors.append("Cannot activate {0} to check for "
                                      "duplicate IP.".format(self.activeiface))

                # Bind arping to requested IP if it's already assigned
                assigned_ips = [v.get('addr') for v in
                                self.netsettings.itervalues()]
                arping_bind = responses["ipaddr"] in assigned_ips

                if network.duplicateIPExists(responses["ipaddr"],
                                             self.activeiface, arping_bind):
                    errors.append("Duplicate host found with IP {0}.".format(
                        responses["ipaddr"]))
        if len(errors) > 0:
            self.log.error("Errors: %s %s" % (len(errors), errors))
            ModuleHelper.display_failed_check_dialog(self, errors)
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
Esempio n. 6
0
    def check(self, args):
        """Validate that all fields have valid values and sanity checks."""
        #Get field information
        responses = dict()
        self.parent.footer.set_text("Checking data...")
        for index, fieldname in enumerate(self.fields):
            if fieldname == "blank" or fieldname == "ifname":
                pass
            elif fieldname == "bootproto":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["bootproto"] = "dhcp"
                else:
                    responses["bootproto"] = "none"
            elif fieldname == "onboot":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["onboot"] = "yes"
                else:
                    responses["onboot"] = "no"
            else:
                responses[fieldname] = self.edits[index].get_edit_text()

        ###Validate each field
        errors = []
        if responses["onboot"] == "no":
            numactiveifaces = 0
            for iface in self.netsettings:
                if self.netsettings[iface]['addr'] != "":
                    numactiveifaces += 1
            if numactiveifaces < 2 and \
                    self.netsettings[self.activeiface]['addr'] != "":
                #Block user because puppet l23network fails if all intefaces
                #are disabled.
                errors.append("Cannot disable all interfaces.")
        elif responses["bootproto"] == "dhcp":
            self.parent.footer.set_text("Scanning for DHCP servers. "
                                        "Please wait...")
            self.parent.refreshScreen()
            try:
                dhcptimeout = 5
                with timeout.run_with_timeout(dhcp_checker.utils.IfaceState,
                                              [self.activeiface],
                                              timeout=dhcptimeout) as iface:
                    dhcp_server_data = timeout.run_with_timeout(
                        dhcp_checker.api.check_dhcp_on_eth,
                        [iface, dhcptimeout],
                        timeout=dhcptimeout)
            except (KeyboardInterrupt, timeout.TimeoutError):
                self.log.debug("DHCP scan timed out")
                self.log.warning(traceback.format_exc())
                dhcp_server_data = []
            except Exception:
                self.log.warning("dhcp_checker failed to check on %s" %
                                 self.activeiface)
                dhcp_server_data = []
                responses["dhcp_nowait"] = False

            if len(dhcp_server_data) < 1:
                self.log.debug("No DHCP servers found. Warning user about "
                               "dhcp_nowait.")
                #Build dialog elements
                dhcp_info = []
                dhcp_info.append(
                    urwid.Padding(urwid.Text(("header", "!!! WARNING !!!")),
                                  "center"))
                dhcp_info.append(
                    widget.TextLabel(
                        "Unable to detect DHCP server" + "on interface %s." %
                        (self.activeiface) +
                        "\nDHCP will be set up in the background, " +
                        "but may not receive an IP address. You may " +
                        "want to check your DHCP connection manually " +
                        "using the Shell Login menu to the left."))
                dialog.display_dialog(
                    self, urwid.Pile(dhcp_info),
                    "DHCP Servers Found on %s" % self.activeiface)
                self.parent.refreshScreen()
                responses["dhcp_nowait"] = True
        #Check ipaddr, netmask, gateway only if static
        elif responses["bootproto"] == "none":
            try:
                if netaddr.valid_ipv4(responses["ipaddr"]):
                    if not netaddr.IPAddress(responses["ipaddr"]):
                        raise BadIPException("Not a valid IP address")
                else:
                    raise BadIPException("Not a valid IP address")
            except (BadIPException, Exception):
                errors.append("Not a valid IP address: %s" %
                              responses["ipaddr"])
            try:
                if netaddr.valid_ipv4(responses["netmask"]):
                    netmask = netaddr.IPAddress(responses["netmask"])
                    if netmask.is_netmask is False:
                        raise BadIPException("Not a valid IP address")
                else:
                    raise BadIPException("Not a valid IP address")
            except (BadIPException, Exception):
                errors.append("Not a valid netmask: %s" % responses["netmask"])
            try:
                if len(responses["gateway"]) > 0:
                    #Check if gateway is valid
                    if netaddr.valid_ipv4(responses["gateway"]) is False:
                        raise BadIPException("Gateway IP address is not valid")
                    #Check if gateway is in same subnet
                    if network.inSameSubnet(responses["ipaddr"],
                                            responses["gateway"],
                                            responses["netmask"]) is False:
                        raise BadIPException("Gateway IP is not in same "
                                             "subnet as IP address")
            except (BadIPException, Exception) as e:
                errors.append(e)
            self.parent.footer.set_text("Scanning for duplicate IP address..")
            if len(responses["ipaddr"]) > 0:
                if self.netsettings[self.activeiface]['link'].upper() != "UP":
                    try:
                        network.upIface(self.activeiface)
                    except NetworkException as e:
                        errors.append("Cannot activate {0} to check for "
                                      "duplicate IP.".format(self.activeiface))
                if network.duplicateIPExists(responses["ipaddr"],
                                             self.activeiface):
                    errors.append("Duplicate host found with IP {0}.".format(
                        responses["ipaddr"]))
        if len(errors) > 0:
            self.parent.footer.set_text("Error: %s" % (errors[0]))
            self.log.error("Errors: %s %s" % (len(errors), errors))
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
Esempio n. 7
0
    def apply(self, args):
        responses = self.check(args)
        if responses is False:
            self.log.error("Check failed. Not applying")
            self.parent.footer.set_text("Check failed. Not applying.")
            self.log.error("%s" % (responses))
            return False

        self.parent.footer.set_text("Applying changes... (May take up to 20s)")
        puppetclasses = []
        l3ifconfig = {'type': "resource",
                      'class': "l23network::l3::ifconfig",
                      'name': self.activeiface}
        if responses["onboot"].lower() == "no":
            params = {"ipaddr": "none"}
        elif responses["bootproto"] == "dhcp":
            if "dhcp_nowait" in responses.keys():
                params = {"ipaddr": "dhcp",
                          "dhcp_nowait": responses["dhcp_nowait"]}
            else:
                params = {"ipaddr": "dhcp"}
        else:
            params = {"ipaddr": responses["ipaddr"],
                      "netmask": responses["netmask"],
                      "check_by_ping": "none"}
        if len(responses["gateway"]) > 1:
            params["gateway"] = responses["gateway"]
        elif network.inSameSubnet(self.get_default_gateway_linux(),
                                  responses["ipaddr"], responses["netmask"]):
            #If the current gateway is in the same subnet AND the user
            #sets the gateway to empty, unset gateway
            expr = '^GATEWAY=.*'
            replace.replaceInFile("/etc/sysconfig/network", expr,
                                  "GATEWAY=")
        l3ifconfig['params'] = params
        puppetclasses.append(l3ifconfig)
        self.log.info("Puppet data: %s" % (puppetclasses))
        try:
            #Gateway handling so DHCP will set gateway
            if responses["bootproto"] == "dhcp":
                expr = '^GATEWAY=.*'
                replace.replaceInFile("/etc/sysconfig/network", expr,
                                      "GATEWAY=")
            self.parent.refreshScreen()
            puppet.puppetApply(puppetclasses)
            self.getNetwork()
            expr = '^GATEWAY=.*'
            gateway = self.get_default_gateway_linux()
            if gateway is None:
                gateway = ""
            replace.replaceInFile("/etc/sysconfig/network", expr, "GATEWAY=%s"
                                  % gateway)
            self.fixEtcHosts()

        except Exception as e:
            self.log.error(e)
            self.parent.footer.set_text("Error applying changes. Check logs "
                                        "for details.")
            self.getNetwork()
            self.setNetworkDetails()
            return False
        self.parent.footer.set_text("Changes successfully applied.")
        self.getNetwork()
        self.setNetworkDetails()

        return True
Esempio n. 8
0
    def check(self, args):
        """Validates all fields have valid values and some sanity checks."""
        self.parent.footer.set_text("Checking data...")
        self.parent.refreshScreen()

        # Refresh networking to make sure IP matches
        self.getNetwork()

        # Get field information
        responses = dict()

        for index, fieldname in enumerate(self.fields):
            if fieldname != "blank" and "label" not in fieldname:
                responses[fieldname] = self.edits[index].get_edit_text()

        # Validate each field
        errors = []

        # Set internal_{ipaddress,netmask,interface}
        responses["ADMIN_NETWORK/interface"] = self.activeiface
        responses["ADMIN_NETWORK/netmask"] = self.netsettings[
            self.activeiface]["netmask"]
        responses["ADMIN_NETWORK/mac"] = self.netsettings[
            self.activeiface]["mac"]
        responses["ADMIN_NETWORK/ipaddress"] = self.netsettings[
            self.activeiface]["addr"]

        # ensure management interface is valid
        if responses["ADMIN_NETWORK/interface"] not in self.netsettings.keys():
            errors.append("Management interface not valid")
        else:
            self.parent.footer.set_text("Scanning for DHCP servers. \
Please wait...")
            self.parent.refreshScreen()

            try:
                dhcptimeout = 5
                dhcp_server_data = network.search_external_dhcp(
                    self.activeiface, dhcptimeout)
            except network.NetworkException:
                log.warning('DHCP scan failed.')
                dhcp_server_data = []

            num_dhcp = len(dhcp_server_data)
            if num_dhcp == 0:
                log.debug("No DHCP servers found")
            else:
                # Problem exists, but permit user to continue
                log.error("%s foreign DHCP server(s) found: %s" %
                          (num_dhcp, dhcp_server_data))

                # Build dialog elements
                dhcp_info = []
                dhcp_info.append(urwid.Padding(
                                 urwid.Text(("header", "!!! WARNING !!!")),
                                 "center"))
                dhcp_info.append(widget.TextLabel("You have selected an \
interface that contains one or more DHCP servers. This will impact \
provisioning. You should disable these DHCP servers before you continue, or \
else deployment will likely fail."))
                dhcp_info.append(widget.TextLabel(""))
                for index, dhcp_server in enumerate(dhcp_server_data):
                    dhcp_info.append(widget.TextLabel("DHCP Server #%s:" %
                                     (index + 1)))
                    dhcp_info.append(widget.TextLabel("IP address: %-10s" %
                                     dhcp_server['server_ip']))
                    dhcp_info.append(widget.TextLabel("MAC address: %-10s" %
                                     dhcp_server['mac']))
                    dhcp_info.append(widget.TextLabel(""))
                dialog.display_dialog(self, urwid.Pile(dhcp_info),
                                      "DHCP Servers Found on %s"
                                      % self.activeiface)
            # Ensure pool start and end are on the same subnet as mgmt_if
            # Ensure mgmt_if has an IP first
            if len(self.netsettings[responses[
               "ADMIN_NETWORK/interface"]]["addr"]) == 0:
                errors.append("Go to Interfaces to configure management \
interface first.")
            else:
                # Ensure ADMIN_NETWORK/interface is not running DHCP
                if self.netsettings[responses[
                        "ADMIN_NETWORK/interface"]]["bootproto"] == "dhcp":
                    errors.append("%s is running DHCP. Change it to static "
                                  "first." % self.activeiface)
                # Ensure DHCP Pool Start and DHCP Pool are valid IPs
                try:
                    if netaddr.valid_ipv4(responses[
                                          "ADMIN_NETWORK/dhcp_pool_start"]):
                        dhcp_start = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_start"])
                        if not dhcp_start:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool Start")
                try:
                    if netaddr.valid_ipv4(responses[
                            "ADMIN_NETWORK/dhcp_gateway"]):
                        dhcp_gateway = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_gateway"])
                        if not dhcp_gateway:
                            raise BadIPException("Not a valid IP address")
                    else:
                            raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Gateway")

                try:
                    if netaddr.valid_ipv4(responses[
                            "ADMIN_NETWORK/dhcp_pool_end"]):
                        dhcp_end = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_end"])
                        if not dhcp_end:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool end")

                # Ensure pool start and end are in the same
                # subnet of each other
                netmask = self.netsettings[responses[
                                           "ADMIN_NETWORK/interface"
                                           ]]["netmask"]
                if not network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_pool_start"],
                        responses["ADMIN_NETWORK/dhcp_pool_end"], netmask):
                    errors.append("DHCP Pool start and end are not in the "
                                  "same subnet.")

                # Ensure pool start and end are in the right netmask
                mgmt_if_ipaddr = self.netsettings[responses[
                    "ADMIN_NETWORK/interface"]]["addr"]
                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_pool_start"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool start does not match management"
                                  " network.")
                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_pool_end"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool end does not match management "
                                  "network.")

                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_gateway"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Gateway does not match management "
                                  "network.")

                self.parent.footer.set_text("Scanning for duplicate IP address"
                                            "es. Please wait...")
                # Bind arping to mgmt_if_ipaddr if it assigned
                assigned_ips = [v.get('addr') for v in
                                self.netsettings.itervalues()]
                arping_bind = mgmt_if_ipaddr in assigned_ips
                if network.duplicateIPExists(mgmt_if_ipaddr, self.activeiface,
                                             arping_bind):
                    errors.append("Duplicate host found with IP {0}.".format(
                        mgmt_if_ipaddr))

        # Extra checks for post-deployment changes
        if utils.is_post_deployment():
            settings = self.parent.settings

            # Admin interface cannot change
            if self.activeiface != settings["ADMIN_NETWORK"]["interface"]:
                errors.append("Cannot change admin interface after deployment")

            # PXE network range must contain previous PXE network range
            old_range = network.range(
                settings["ADMIN_NETWORK"]["dhcp_pool_start"],
                settings["ADMIN_NETWORK"]["dhcp_pool_end"])
            new_range = network.range(
                responses["ADMIN_NETWORK/dhcp_pool_start"],
                responses["ADMIN_NETWORK/dhcp_pool_end"])
            if old_range[0] not in new_range:
                errors.append("DHCP range must contain previous values.")
            if old_range[-1] not in new_range:
                errors.append("DHCP range can only be increased after "
                              "deployment.")

        if len(errors) > 0:
            log.error("Errors: %s %s" % (len(errors), errors))
            ModuleHelper.display_failed_check_dialog(self, errors)
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
Esempio n. 9
0
    def check(self, args):
        """Validates all fields have valid values and some sanity checks."""
        self.parent.footer.set_text("Checking data...")
        self.parent.refreshScreen()

        #Refresh networking to make sure IP matches
        self.getNetwork()

        #Get field information
        responses = dict()

        for index, fieldname in enumerate(self.fields):
            if fieldname != "blank" and "label" not in fieldname:
                responses[fieldname] = self.edits[index].get_edit_text()

        ###Validate each field
        errors = []

        #Set internal_{ipaddress,netmask,interface}
        responses["ADMIN_NETWORK/interface"] = self.activeiface
        responses["ADMIN_NETWORK/netmask"] = self.netsettings[
            self.activeiface]["netmask"]
        responses["ADMIN_NETWORK/mac"] = self.netsettings[
            self.activeiface]["mac"]
        responses["ADMIN_NETWORK/ipaddress"] = self.netsettings[
            self.activeiface]["addr"]

        #ensure management interface is valid
        if responses["ADMIN_NETWORK/interface"] not in self.netsettings.keys():
            errors.append("Management interface not valid")
        else:
            self.parent.footer.set_text("Scanning for DHCP servers. \
Please wait...")
            self.parent.refreshScreen()

            ###Start DHCP check on this interface
            #dhcp_server_data=[{'server_id': '192.168.200.2', 'iface': 'eth2',
            #                   'yiaddr': '192.168.200.15', 'mac':
            #                '52:54:00:12:35:02', 'server_ip': '192.168.200.2',
            #                   'dport': 67, 'message': 'offer',
            #                   'gateway': '0.0.0.0'}]
            try:
                dhcptimeout = 5
                default = []
                with timeout.run_with_timeout(dhcp_checker.utils.IfaceState,
                                              [self.activeiface],
                                              timeout=dhcptimeout) as iface:
                    dhcp_server_data = timeout.run_with_timeout(
                        dhcp_checker.api.check_dhcp_on_eth,
                        [iface, dhcptimeout], timeout=dhcptimeout,
                        default=default)
            except (KeyboardInterrupt, timeout.TimeoutError):
                log.debug("DHCP scan timed out")
                log.warning(traceback.format_exc())
                dhcp_server_data = default

            num_dhcp = len(dhcp_server_data)
            if num_dhcp == 0:
                log.debug("No DHCP servers found")
            else:
                #Problem exists, but permit user to continue
                log.error("%s foreign DHCP server(s) found: %s" %
                          (num_dhcp, dhcp_server_data))

                #Build dialog elements
                dhcp_info = []
                dhcp_info.append(urwid.Padding(
                                 urwid.Text(("header", "!!! WARNING !!!")),
                                 "center"))
                dhcp_info.append(widget.TextLabel("You have selected an \
interface that contains one or more DHCP servers. This will impact \
provisioning. You should disable these DHCP servers before you continue, or \
else deployment will likely fail."))
                dhcp_info.append(widget.TextLabel(""))
                for index, dhcp_server in enumerate(dhcp_server_data):
                    dhcp_info.append(widget.TextLabel("DHCP Server #%s:" %
                                     (index + 1)))
                    dhcp_info.append(widget.TextLabel("IP address: %-10s" %
                                     dhcp_server['server_ip']))
                    dhcp_info.append(widget.TextLabel("MAC address: %-10s" %
                                     dhcp_server['mac']))
                    dhcp_info.append(widget.TextLabel(""))
                dialog.display_dialog(self, urwid.Pile(dhcp_info),
                                      "DHCP Servers Found on %s"
                                      % self.activeiface)
            ###Ensure pool start and end are on the same subnet as mgmt_if
            #Ensure mgmt_if has an IP first
            if len(self.netsettings[responses[
               "ADMIN_NETWORK/interface"]]["addr"]) == 0:
                errors.append("Go to Interfaces to configure management \
interface first.")
            else:
                #Ensure ADMIN_NETWORK/interface is not running DHCP
                if self.netsettings[responses[
                        "ADMIN_NETWORK/interface"]]["bootproto"] == "dhcp":
                    errors.append("%s is running DHCP. Change it to static "
                                  "first." % self.activeiface)
                #Ensure DHCP Pool Start and DHCP Pool are valid IPs
                try:
                    if netaddr.valid_ipv4(responses[
                                          "ADMIN_NETWORK/dhcp_pool_start"]):
                        dhcp_start = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_start"])
                        if not dhcp_start:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool Start")
                try:
                    if netaddr.valid_ipv4(responses[
                            "ADMIN_NETWORK/dhcp_gateway"]):
                        dhcp_gateway = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_gateway"])
                        if not dhcp_gateway:
                            raise BadIPException("Not a valid IP address")
                    else:
                            raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Gateway")

                try:
                    if netaddr.valid_ipv4(responses[
                            "ADMIN_NETWORK/dhcp_pool_end"]):
                        dhcp_end = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_end"])
                        if not dhcp_end:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool end")

                #Ensure pool start and end are in the same subnet of each other
                netmask = self.netsettings[responses[
                                           "ADMIN_NETWORK/interface"
                                           ]]["netmask"]
                if not network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_pool_start"],
                        responses["ADMIN_NETWORK/dhcp_pool_end"], netmask):
                    errors.append("DHCP Pool start and end are not in the "
                                  "same subnet.")

                #Ensure pool start and end are in the right netmask
                mgmt_if_ipaddr = self.netsettings[responses[
                    "ADMIN_NETWORK/interface"]]["addr"]
                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_pool_start"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool start does not match management"
                                  " network.")
                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_pool_end"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool end does not match management "
                                  "network.")

                if network.inSameSubnet(responses[
                                        "ADMIN_NETWORK/dhcp_gateway"],
                                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Gateway does not match management "
                                  "network.")

                self.parent.footer.set_text("Scanning for duplicate IP address"
                                            "es. Please wait...")
                if network.duplicateIPExists(mgmt_if_ipaddr, self.activeiface):
                    errors.append("Duplicate host found with IP {0}.".format(
                        mgmt_if_ipaddr))

        if len(errors) > 0:
            self.parent.footer.set_text("Error: %s" % (errors[0]))
            log.error("Errors: %s %s" % (len(errors), errors))
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
Esempio n. 10
0
    def check(self, args):
        """Validate that all fields have valid values and sanity checks."""
        #Get field information
        responses = dict()
        self.parent.footer.set_text("Checking data...")
        for index, fieldname in enumerate(fields):
            if fieldname == "blank" or fieldname == "ifname":
                pass
            elif fieldname == "bootproto":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["bootproto"] = "dhcp"
                else:
                    responses["bootproto"] = "none"
            elif fieldname == "onboot":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["onboot"] = "yes"
                else:
                    responses["onboot"] = "no"
            else:
                responses[fieldname] = self.edits[index].get_edit_text()

        ###Validate each field
        errors = []
        if responses["onboot"] == "no":
            numactiveifaces = 0
            for iface in self.netsettings:
                if self.netsettings[iface]['addr'] != "":
                    numactiveifaces += 1
            if numactiveifaces < 2 and \
                    self.netsettings[self.activeiface]['addr'] != "":
                #Block user because puppet l23network fails if all intefaces
                #are disabled.
                errors.append("Cannot disable all interfaces.")
        elif responses["bootproto"] == "dhcp":
            self.parent.footer.set_text("Scanning for DHCP servers. "
                                        "Please wait...")
            self.parent.refreshScreen()
            try:
                dhcptimeout = 5
                with timeout.run_with_timeout(dhcp_checker.utils.IfaceState,
                                              [self.activeiface],
                                              timeout=dhcptimeout) as iface:
                    dhcp_server_data = timeout.run_with_timeout(
                        dhcp_checker.api.check_dhcp_on_eth,
                        [iface, dhcptimeout], timeout=dhcptimeout)
            except (KeyboardInterrupt, timeout.TimeoutError):
                self.log.debug("DHCP scan timed out")
                self.log.warning(traceback.format_exc())
                dhcp_server_data = []
            except Exception:
                self.log.warning("dhcp_checker failed to check on %s"
                                 % self.activeiface)
                dhcp_server_data = []
                responses["dhcp_nowait"] = False

            if len(dhcp_server_data) < 1:
                self.log.debug("No DHCP servers found. Warning user about "
                               "dhcp_nowait.")
                #Build dialog elements
                dhcp_info = []
                dhcp_info.append(urwid.Padding(
                                 urwid.Text(("header", "!!! WARNING !!!")),
                                 "center"))
                dhcp_info.append(
                    widget.TextLabel(
                        "Unable to detect DHCP server" +
                        "on interface %s." % (self.activeiface) +
                        "\nDHCP will be set up in the background, " +
                        "but may not receive an IP address. You may " +
                        "want to check your DHCP connection manually " +
                        "using the Shell Login menu to the left."))
                dialog.display_dialog(self, urwid.Pile(dhcp_info),
                                      "DHCP Servers Found on %s"
                                      % self.activeiface)
                self.parent.refreshScreen()
                responses["dhcp_nowait"] = True
        #Check ipaddr, netmask, gateway only if static
        elif responses["bootproto"] == "none":
            try:
                if netaddr.valid_ipv4(responses["ipaddr"]):
                    if not netaddr.IPAddress(responses["ipaddr"]):
                        raise BadIPException("Not a valid IP address")
                else:
                    raise BadIPException("Not a valid IP address")
            except (BadIPException, Exception):
                errors.append("Not a valid IP address: %s" %
                              responses["ipaddr"])
            try:
                if netaddr.valid_ipv4(responses["netmask"]):
                    netmask = netaddr.IPAddress(responses["netmask"])
                    if netmask.is_netmask is False:
                        raise BadIPException("Not a valid IP address")
                else:
                    raise BadIPException("Not a valid IP address")
            except (BadIPException, Exception):
                errors.append("Not a valid netmask: %s" % responses["netmask"])
            try:
                if len(responses["gateway"]) > 0:
                    #Check if gateway is valid
                    if netaddr.valid_ipv4(responses["gateway"]) is False:
                        raise BadIPException("Gateway IP address is not valid")
                    #Check if gateway is in same subnet
                    if network.inSameSubnet(responses["ipaddr"],
                                            responses["gateway"],
                                            responses["netmask"]) is False:
                        raise BadIPException("Gateway IP is not in same "
                                             "subnet as IP address")
            except (BadIPException, Exception) as e:
                errors.append(e)
        if len(errors) > 0:
            self.parent.footer.set_text("Error: %s" % (errors[0]))
            self.log.error("Errors: %s %s" % (len(errors), errors))
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
Esempio n. 11
0
    def setNetworkDetails(self):
        self.net_text1.set_text("Interface: %-13s  Link: %s" % (
            self.activeiface, self.netsettings[self.activeiface]['link'].
            upper()))
        self.net_text2.set_text("IP:      %-15s  MAC: %s" % (self.netsettings[
            self.activeiface]['addr'],
            self.netsettings[self.activeiface]['mac']))
        self.net_text3.set_text("Netmask: %-15s  Gateway: %s" % (
            self.netsettings[self.activeiface]['netmask'],
            self.gateway))
        log.debug("bootproto for %s: %s" % (self.netsettings[self.activeiface],
                  self.netsettings[self.activeiface]['bootproto']))
        if self.netsettings[self.activeiface]['link'].upper() == "UP":
            if self.netsettings[self.activeiface]['bootproto'] == "dhcp":
                self.net_text4.set_text("WARNING: Cannot use interface running"
                                        " DHCP.\nReconfigure as static in "
                                        "Network Setup screen.")
            else:
                self.net_text4.set_text("")
        else:
            self.net_text4.set_text("WARNING: This interface is DOWN. "
                                    "Configure it first.")

        #If DHCP pool start and matches activeiface network, don't update
        #This means if you change your pool values, go to another page, then
        #go back, it will not reset your changes. But what is more likely is
        #you will change the network settings for interface eth0 and then come
        #back to this page to update your DHCP settings. If the inSameSubnet
        #test fails, just recalculate and set new values.
        for index, key in enumerate(self.fields):
            if key == "ADMIN_NETWORK/dhcp_pool_start":
                dhcp_start = self.edits[index].get_edit_text()
                break
        if network.inSameSubnet(dhcp_start,
                                self.netsettings[self.activeiface]['addr'],
                                self.netsettings[self.activeiface]['netmask']):
            log.debug("Existing network settings exist. Not changing.")
            return
        else:
            log.debug("Existing network settings missing or invalid. "
                      "Updating...")

        #Calculate and set Static/DHCP pool fields
        #Max IPs = net size - 2 (master node + bcast)
        #Add gateway so we exclude it
        net_ip_list = network.getNetwork(
            self.netsettings[self.activeiface]['addr'],
            self.netsettings[self.activeiface]['netmask'],
            self.gateway)
        try:
            dhcp_pool = net_ip_list[1:]
            dynamic_start = str(dhcp_pool[0])
            dynamic_end = str(dhcp_pool[-1])
            if self.net_text4.get_text() == "":
                self.net_text4.set_text("This network configuration can "
                                        "support %s nodes." % len(dhcp_pool))
        except Exception:
            #We don't have valid values, so mark all fields empty
            dynamic_start = ""
            dynamic_end = ""
        for index, key in enumerate(self.fields):
            if key == "ADMIN_NETWORK/dhcp_pool_start":
                self.edits[index].set_edit_text(dynamic_start)
            elif key == "ADMIN_NETWORK/dhcp_pool_end":
                self.edits[index].set_edit_text(dynamic_end)
            elif key == "ADMIN_NETWORK/dhcp_gateway":
                self.edits[index].set_edit_text(self.netsettings[
                    self.activeiface]['addr'])
Esempio n. 12
0
    def apply(self, args):
        responses = self.check(args)
        if responses is False:
            self.log.error("Check failed. Not applying")
            self.parent.footer.set_text("Check failed. Not applying.")
            self.log.error("%s" % (responses))
            return False

        self.parent.footer.set_text("Applying changes... (May take up to 20s)")

        # Build puppet resources to apply l23network puppet module to enable
        # network changes
        puppetclasses = []

        # FIXME(mattymo): install_bondtool param does not work (LP#1541028)
        # The following 4 lines should be removed when fixed.
        disable_bond = {
            'type': "literal",
            'name': 'K_mod <| title == "bonding" |> {ensure => absent} '}
        puppetclasses.append(disable_bond)

        # If there is a gateway configured in /etc/sysconfig/network, unset it
        expr = '^GATEWAY=.*'
        replace.replaceInFile("/etc/sysconfig/network", expr, "")

        # Initialize l23network class for NetworkManager fixes
        l23network = {'type': "resource",
                      'class': "class",
                      'name': "l23network",
                      'params': {'install_bondtool': False}}
        puppetclasses.append(l23network)

        # Prepare l23network interface configuration
        l3ifconfig = {'type': "resource",
                      'class': "l23network::l3::ifconfig",
                      'name': self.activeiface}

        if responses["onboot"].lower() == "no":
            params = {"ipaddr": "none",
                      "gateway": ""}
        elif responses["bootproto"] == "dhcp":
            self.unset_gateway()
            params = {"ipaddr": "dhcp"}
        else:
            cidr = network.netmaskToCidr(responses["netmask"])
            params = {"ipaddr": "{0}/{1}".format(responses["ipaddr"], cidr),
                      "check_by_ping": "none"}
            if len(responses["gateway"]) > 1:
                params["gateway"] = responses["gateway"]
                self.unset_gateway()
            if network.inSameSubnet(responses["ipaddr"],
                                    self.get_default_gateway_linux(),
                                    responses["netmask"]):
                # Unset if clearing currently set gateway on same subnet
                self.unset_gateway()

        l3ifconfig['params'] = params
        puppetclasses.append(l3ifconfig)
        self.log.info("Puppet data: %s" % (puppetclasses))
        try:
            self.parent.refreshScreen()
            result = puppet.puppetApply(puppetclasses)
            if result is False:
                raise Exception("Puppet apply failed")
            ModuleHelper.getNetwork(self)
            gateway = self.get_default_gateway_linux()
            if gateway is None:
                gateway = ""
            self.fixEtcHosts()

        except Exception as e:
            self.log.error(e)
            self.parent.footer.set_text("Error applying changes. Check logs "
                                        "for details.")
            ModuleHelper.getNetwork(self)
            self.setNetworkDetails()
            return False
        self.parent.footer.set_text("Changes successfully applied.")
        ModuleHelper.getNetwork(self)
        self.setNetworkDetails()

        return True
Esempio n. 13
0
    def apply(self, args):
        responses = self.check(args)
        if responses is False:
            self.log.error("Check failed. Not applying")
            self.parent.footer.set_text("Check failed. Not applying.")
            self.log.error("%s" % (responses))
            return False

        self.parent.footer.set_text("Applying changes... (May take up to 20s)")
        puppetclasses = []
        l3ifconfig = {
            'type': "resource",
            'class': "l23network::l3::ifconfig",
            'name': self.activeiface
        }
        if responses["onboot"].lower() == "no":
            params = {"ipaddr": "none"}
        elif responses["bootproto"] == "dhcp":
            if "dhcp_nowait" in responses.keys():
                params = {
                    "ipaddr": "dhcp",
                    "dhcp_nowait": responses["dhcp_nowait"]
                }
            else:
                params = {"ipaddr": "dhcp"}
        else:
            params = {
                "ipaddr": responses["ipaddr"],
                "netmask": responses["netmask"],
                "check_by_ping": "none"
            }
        if len(responses["gateway"]) > 1:
            params["gateway"] = responses["gateway"]
            params["default_gateway"] = True
        elif network.inSameSubnet(self.get_default_gateway_linux(),
                                  responses["ipaddr"], responses["netmask"]):
            #If the current gateway is in the same subnet AND the user
            #sets the gateway to empty, unset gateway
            expr = '^GATEWAY=.*'
            replace.replaceInFile("/etc/sysconfig/network", expr, "GATEWAY=")
        l3ifconfig['params'] = params
        puppetclasses.append(l3ifconfig)
        self.log.info("Puppet data: %s" % (puppetclasses))
        try:
            #Gateway handling so DHCP will set gateway
            if responses["bootproto"] == "dhcp":
                expr = '^GATEWAY=.*'
                replace.replaceInFile("/etc/sysconfig/network", expr,
                                      "GATEWAY=")
            self.parent.refreshScreen()
            puppet.puppetApply(puppetclasses)
            ModuleHelper.getNetwork(self)
            expr = '^GATEWAY=.*'
            gateway = self.get_default_gateway_linux()
            if gateway is None:
                gateway = ""
            replace.replaceInFile("/etc/sysconfig/network", expr,
                                  "GATEWAY=%s" % gateway)
            self.fixEtcHosts()

        except Exception as e:
            self.log.error(e)
            self.parent.footer.set_text("Error applying changes. Check logs "
                                        "for details.")
            ModuleHelper.getNetwork(self)
            self.setNetworkDetails()
            return False
        self.parent.footer.set_text("Changes successfully applied.")
        ModuleHelper.getNetwork(self)
        self.setNetworkDetails()

        return True
Esempio n. 14
0
    def check(self, args):
        """Validate that all fields have valid values and sanity checks."""
        # Get field information
        responses = dict()
        self.parent.footer.set_text("Checking data...")
        for index, fieldname in enumerate(self.fields):
            if fieldname == "blank" or fieldname == "ifname":
                pass
            elif fieldname == "bootproto":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["bootproto"] = "none"
                else:
                    responses["bootproto"] = "dhcp"
            elif fieldname == "onboot":
                rb_group = self.edits[index].rb_group
                if rb_group[0].state:
                    responses["onboot"] = "yes"
                else:
                    responses["onboot"] = "no"
            else:
                responses[fieldname] = self.edits[index].get_edit_text()

        # Validate each field
        errors = []

        # Check for the duplicate IP provided
        for k, v in self.netsettings.items():
            if (k != self.activeiface and responses["ipaddr"] != ''
                    and responses["ipaddr"] == v.get('addr')):
                errors.append("The same IP address {0} is assigned for "
                              "interfaces '{1}' and '{2}'.".format(
                                  responses["ipaddr"], k, self.activeiface))
                break

        if responses["onboot"] == "no":
            numactiveifaces = 0
            for iface in self.netsettings:
                if self.netsettings[iface]['addr'] != "":
                    numactiveifaces += 1
            if numactiveifaces < 2 and \
                    self.netsettings[self.activeiface]['addr'] != "":
                # Block user because puppet l23network fails if all interfaces
                # are disabled.
                errors.append("Cannot disable all interfaces.")
        elif responses["bootproto"] == "dhcp":
            self.parent.footer.set_text("Scanning for DHCP servers. "
                                        "Please wait...")
            self.parent.refreshScreen()
            try:
                dhcptimeout = 5
                dhcp_server_data = network.search_external_dhcp(
                    self.activeiface, dhcptimeout)
            except network.NetworkException:
                self.log.warning("dhcp_checker failed to check on %s" %
                                 self.activeiface)
                dhcp_server_data = []

            if len(dhcp_server_data) < 1:
                errors.append("No DHCP servers found. Cannot enable DHCP")

        # Check ipaddr, netmask, gateway only if static
        elif responses["bootproto"] == "none":
            try:
                if netaddr.valid_ipv4(responses["ipaddr"]):
                    if not netaddr.IPAddress(responses["ipaddr"]):
                        raise f_errors.BadIPException("Not a valid IP address")
                else:
                    raise f_errors.BadIPException("Not a valid IP address")
            except (f_errors.BadIPException, Exception):
                errors.append("Not a valid IP address: %s" %
                              responses["ipaddr"])
            try:
                if netaddr.valid_ipv4(responses["netmask"]):
                    netmask = netaddr.IPAddress(responses["netmask"])
                    if netmask.is_netmask is False:
                        raise f_errors.BadIPException("Not a valid IP address")
                else:
                    raise f_errors.BadIPException("Not a valid IP address")
            except (f_errors.BadIPException, Exception):
                errors.append("Not a valid netmask: %s" % responses["netmask"])
            try:
                if len(responses["gateway"]) > 0:
                    # Check if gateway is valid
                    if netaddr.valid_ipv4(responses["gateway"]) is False:
                        raise f_errors.BadIPException(
                            "Gateway IP address is not valid")
                    # Check if gateway is in same subnet
                    if network.inSameSubnet(responses["ipaddr"],
                                            responses["gateway"],
                                            responses["netmask"]) is False:
                        raise f_errors.BadIPException(
                            "Gateway IP is not in same "
                            "subnet as IP address")
            except (f_errors.BadIPException, Exception) as e:
                errors.append(e)
            self.parent.footer.set_text("Scanning for duplicate IP address..")
            if len(responses["ipaddr"]) > 0:
                if self.netsettings[self.activeiface]['link'].upper() != "UP":
                    try:
                        network.upIface(self.activeiface)
                    except f_errors.NetworkException as e:
                        errors.append("Cannot activate {0} to check for "
                                      "duplicate IP.".format(self.activeiface))

                # Bind arping to requested IP if it's already assigned
                assigned_ips = [
                    v.get('addr') for v in self.netsettings.itervalues()
                ]
                arping_bind = responses["ipaddr"] in assigned_ips

                if network.duplicateIPExists(responses["ipaddr"],
                                             self.activeiface, arping_bind):
                    errors.append("Duplicate host found with IP {0}.".format(
                        responses["ipaddr"]))
        if len(errors) > 0:
            self.log.error("Errors: %s %s" % (len(errors), errors))
            modulehelper.ModuleHelper.display_failed_check_dialog(self, errors)
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses
Esempio n. 15
0
    def check(self, args):
        """Validates all fields have valid values and some sanity checks."""
        self.parent.footer.set_text("Checking data...")
        self.parent.refreshScreen()

        # Refresh networking to make sure IP matches
        self.getNetwork()

        # Get field information
        responses = dict()

        for index, fieldname in enumerate(self.fields):
            if fieldname != "blank" and "label" not in fieldname:
                responses[fieldname] = self.edits[index].get_edit_text()

        # Validate each field
        errors = []

        # Set internal_{ipaddress,netmask,interface}
        responses["ADMIN_NETWORK/interface"] = self.activeiface
        responses["ADMIN_NETWORK/netmask"] = self.netsettings[
            self.activeiface]["netmask"]
        responses["ADMIN_NETWORK/mac"] = self.netsettings[
            self.activeiface]["mac"]
        responses["ADMIN_NETWORK/ipaddress"] = self.netsettings[
            self.activeiface]["addr"]

        # ensure management interface is valid
        if responses["ADMIN_NETWORK/interface"] not in self.netsettings.keys():
            errors.append("Management interface not valid")
        else:
            self.parent.footer.set_text("Scanning for DHCP servers. \
Please wait...")
            self.parent.refreshScreen()

            try:
                dhcptimeout = 5
                dhcp_server_data = network.search_external_dhcp(
                    self.activeiface, dhcptimeout)
            except network.NetworkException:
                log.warning('DHCP scan failed.')
                dhcp_server_data = []

            num_dhcp = len(dhcp_server_data)
            if num_dhcp == 0:
                log.debug("No DHCP servers found")
            else:
                # Problem exists, but permit user to continue
                log.error("%s foreign DHCP server(s) found: %s" %
                          (num_dhcp, dhcp_server_data))

                # Build dialog elements
                dhcp_info = []
                dhcp_info.append(
                    urwid.Padding(urwid.Text(("header", "!!! WARNING !!!")),
                                  "center"))
                dhcp_info.append(
                    widget.TextLabel("You have selected an \
interface that contains one or more DHCP servers. This will impact \
provisioning. You should disable these DHCP servers before you continue, or \
else deployment will likely fail."))
                dhcp_info.append(widget.TextLabel(""))
                for index, dhcp_server in enumerate(dhcp_server_data):
                    dhcp_info.append(
                        widget.TextLabel("DHCP Server #%s:" % (index + 1)))
                    dhcp_info.append(
                        widget.TextLabel("IP address: %-10s" %
                                         dhcp_server['server_ip']))
                    dhcp_info.append(
                        widget.TextLabel("MAC address: %-10s" %
                                         dhcp_server['mac']))
                    dhcp_info.append(widget.TextLabel(""))
                dialog.display_dialog(
                    self, urwid.Pile(dhcp_info),
                    "DHCP Servers Found on %s" % self.activeiface)
            # Ensure pool start and end are on the same subnet as mgmt_if
            # Ensure mgmt_if has an IP first
            if len(self.netsettings[responses["ADMIN_NETWORK/interface"]]
                   ["addr"]) == 0:
                errors.append("Go to Interfaces to configure management \
interface first.")
            else:
                # Ensure ADMIN_NETWORK/interface is not running DHCP
                if self.netsettings[responses["ADMIN_NETWORK/interface"]][
                        "bootproto"] == "dhcp":
                    errors.append("%s is running DHCP. Change it to static "
                                  "first." % self.activeiface)
                # Ensure DHCP Pool Start and DHCP Pool are valid IPs
                try:
                    if netaddr.valid_ipv4(
                            responses["ADMIN_NETWORK/dhcp_pool_start"]):
                        dhcp_start = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_start"])
                        if not dhcp_start:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool Start")
                try:
                    if netaddr.valid_ipv4(
                            responses["ADMIN_NETWORK/dhcp_gateway"]):
                        dhcp_gateway = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_gateway"])
                        if not dhcp_gateway:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Gateway")

                try:
                    if netaddr.valid_ipv4(
                            responses["ADMIN_NETWORK/dhcp_pool_end"]):
                        dhcp_end = netaddr.IPAddress(
                            responses["ADMIN_NETWORK/dhcp_pool_end"])
                        if not dhcp_end:
                            raise BadIPException("Not a valid IP address")
                    else:
                        raise BadIPException("Not a valid IP address")
                except Exception:
                    errors.append("Invalid IP address for DHCP Pool end")

                # Ensure pool start and end are in the same
                # subnet of each other
                netmask = self.netsettings[
                    responses["ADMIN_NETWORK/interface"]]["netmask"]
                if not network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_pool_start"],
                        responses["ADMIN_NETWORK/dhcp_pool_end"], netmask):
                    errors.append("DHCP Pool start and end are not in the "
                                  "same subnet.")

                # Ensure pool start and end are in the right netmask
                mgmt_if_ipaddr = self.netsettings[
                    responses["ADMIN_NETWORK/interface"]]["addr"]
                if network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_pool_start"],
                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool start does not match management"
                                  " network.")
                if network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_pool_end"],
                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Pool end does not match management "
                                  "network.")

                if network.inSameSubnet(
                        responses["ADMIN_NETWORK/dhcp_gateway"],
                        mgmt_if_ipaddr, netmask) is False:
                    errors.append("DHCP Gateway does not match management "
                                  "network.")

                self.parent.footer.set_text("Scanning for duplicate IP address"
                                            "es. Please wait...")
                # Bind arping to mgmt_if_ipaddr if it assigned
                assigned_ips = [
                    v.get('addr') for v in self.netsettings.itervalues()
                ]
                arping_bind = mgmt_if_ipaddr in assigned_ips
                if network.duplicateIPExists(mgmt_if_ipaddr, self.activeiface,
                                             arping_bind):
                    errors.append("Duplicate host found with IP {0}.".format(
                        mgmt_if_ipaddr))

        # Extra checks for post-deployment changes
        if utils.is_post_deployment():
            settings = self.parent.settings

            # Admin interface cannot change
            if self.activeiface != settings["ADMIN_NETWORK"]["interface"]:
                errors.append("Cannot change admin interface after deployment")

            # PXE network range must contain previous PXE network range
            old_range = network.range(
                settings["ADMIN_NETWORK"]["dhcp_pool_start"],
                settings["ADMIN_NETWORK"]["dhcp_pool_end"])
            new_range = network.range(
                responses["ADMIN_NETWORK/dhcp_pool_start"],
                responses["ADMIN_NETWORK/dhcp_pool_end"])
            if old_range[0] not in new_range:
                errors.append("DHCP range must contain previous values.")
            if old_range[-1] not in new_range:
                errors.append("DHCP range can only be increased after "
                              "deployment.")

        if len(errors) > 0:
            log.error("Errors: %s %s" % (len(errors), errors))
            ModuleHelper.display_failed_check_dialog(self, errors)
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses