Exemplo n.º 1
0
    def __init__(self, controlState, xml):
        controlState.displayHeaderBar = True
        controlState.windowIcon = 'network_configure.png'
        controlState.windowTitle = "Network Configuration"
        controlState.windowText = "Enter the network configuration information"

        self.controlState = controlState

        self.progressDialog = None

        self.networkAddressWidgets =\
            network_address_widgets.NetworkAddressWidgets(
                xml,
                self.controlState.gui.getWindow(),
                'Cosnetwork',
                ('ip', 'netmask', 'gateway', 'ns1', 'ns2', 'hostname'),
                'CosnetworkDHCPRadioButton', 'CosnetworkIPTable')

        #
        # Fill out "Network Adapter:" label.
        adapter = xml.get_widget("CosnetworkNetworkAdapterLabel")
        assert len(userchoices.getCosNICs()) > 0
        device = userchoices.getCosNICs()[0]['device']
        adapter.set_text(device.name)

        connectSignalHandlerByDict(self, CosNetworkWindow, xml,
          {('activate_button', 'clicked'): 'onActivateButtonClicked',
          })
Exemplo n.º 2
0
 def congrats(self):
     "Get IP address, Show congratulatory message."
     cosNICs = userchoices.getCosNICs()
     warn = ''
     if not cosNICs:
         log.error("No COS network adapter found")
         warn = warnText
     elif 'ip' not in cosNICs[0]:
         log.error("COS network adapter missing IP address")
         warn = warnText
     elif not cosNICs[0]['ip']:
         # COS NIC detected, using DHCP
         pass
     else:
         # COS NIC configured using static IP
         self.ipaddr = cosNICs[0]['ip']
     ui = {
         'title': title,
         'body': congratsText % {
             'ipaddr': self.ipaddr,
             'warn': warn
         },
         'menu': {
             '1': self.stepForward,
         }
     }
     self.setSubstepEnv(ui)
    def getNext(self):
        """Tell userchoices what choices were made on this screen.
        
           We don't know bootProto, ip or netmask yet.  They're set in the
           next screen.
        
           You can assign more than one NIC to the COS from scripted install,
           but not from the GUI installer.
        """
        # Case of no NICs found. Driver loading window should prevent this.
        if not self.nicSetup:
            msg = 'No NICs detected'
            MessageWindow(self.thisWindow, msg.title(), msg)
            raise StayOnScreen()

        chosenNics = userchoices.getCosNICs()

        if chosenNics:
            assert len(chosenNics) == 1, "Found more than one console NIC."
            userchoices.delCosNIC(chosenNics[0])

        physicalNic = self.nicSetup.getDevice()
        userchoices.addCosNIC(device=physicalNic,
                              vlanID=self.nicSetup.getVlanID(),
                              bootProto=None,
                              ip=None, netmask=None)
Exemplo n.º 4
0
    def getNext(self):

        stepDict = {
            'InstallHttpRadioButton': 'httpmedia',
            'InstallFtpRadioButton': 'ftpmedia',
            'InstallUsbRadioButton': 'usbmedia',
            'InstallNfsRadioButton': 'nfsmedia'
        }

        for step in stepDict.values():
            if step in self.controlState.gui.dispatch:
                self.controlState.removeStep(step)

        for step in stepDict.keys():
            if self.xml.get_widget(step).get_active():
                self.controlState.insertStep(stepDict[step], 'setupchoice')
                break

        # if the media requires a network connection, check that the ethernet
        # cable is plugged in
        if stepDict[step] in ['httpmedia', 'ftpmedia', 'nfsmedia']:
            chosenNics = userchoices.getCosNICs()
            assert len(chosenNics) == 1
            physicalNic = chosenNics[0]['device']
            if not physicalNic.isLinkUp:
                MessageWindow(
                    None, 'Network Adapter Error',
                    'The network adapter must be connected to '
                    'access FTP, HTTP, or NFS sources.')
                raise exception.StayOnScreen()
Exemplo n.º 5
0
    def setupMedia(self):
        """Set-up for currently implemented media.
        Includes:  NFS, HTTP, FTP.
        """
        setups = {     
            # engine is class for setup, tSuffix is title suffix.
            '2': {'engine': SetupNfs, 'tSuffix': "NFS"},
            '3': {'engine': SetupHttp, 'tSuffix': "HTTP"},
            '4': {'engine': SetupFtp, 'tSuffix': "FTP"},
        }
        # TODO: add title as parameter
        engineType = setups[self.userinput]['engine']
        title = 'Install Using ' + setups[self.userinput]['tSuffix']

        # check for network link
        chosenNics = userchoices.getCosNICs()
        assert len(chosenNics) == 1
        physicalNic = chosenNics[0]['device']

        if not physicalNic.isLinkUp:
            body = "%s\n%s" % (errNetLinkText, TransMenu.Back)
            self.errorPushPop(title, body)
            return

        engine = engineType(title)
        result = engine.run()
        assert result in (textengine.DISPATCH_BACK, textengine.DISPATCH_NEXT)
        if result == textengine.DISPATCH_NEXT:
            self.setSubstepEnv({'next': self.stepForward})
        else:
            self.setSubstepEnv({'next': self.start})  # start of installmedia
Exemplo n.º 6
0
    def getNext(self):

        stepDict = { 'InstallHttpRadioButton' : 'httpmedia',
                     'InstallFtpRadioButton' : 'ftpmedia',
                     'InstallUsbRadioButton' : 'usbmedia',
                     'InstallNfsRadioButton' : 'nfsmedia' }

        for step in stepDict.values():
            if step in self.controlState.gui.dispatch:
                self.controlState.removeStep(step)

        for step in stepDict.keys():
            if self.xml.get_widget(step).get_active():
                self.controlState.insertStep(stepDict[step], 'setupchoice')
                break

        # if the media requires a network connection, check that the ethernet
        # cable is plugged in
        if stepDict[step] in ['httpmedia', 'ftpmedia', 'nfsmedia']:
            chosenNics = userchoices.getCosNICs()
            assert len(chosenNics) == 1
            physicalNic = chosenNics[0]['device']
            if not physicalNic.isLinkUp:
                MessageWindow(None, 'Network Adapter Error',
                              'The network adapter must be connected to '
                              'access FTP, HTTP, or NFS sources.')
                raise exception.StayOnScreen()
Exemplo n.º 7
0
 def congrats(self):
     "Get IP address, Show congratulatory message."
     cosNICs = userchoices.getCosNICs()
     warn = ''
     if not cosNICs:
         log.error("No COS network adapter found")
         warn = warnText
     elif 'ip' not in cosNICs[0]:
         log.error("COS network adapter missing IP address")
         warn = warnText
     elif not cosNICs[0]['ip']:
         # COS NIC detected, using DHCP
         pass
     else:
         # COS NIC configured using static IP
         self.ipaddr = cosNICs[0]['ip']
     ui = {
         'title': title,
         'body': congratsText % {
             'ipaddr': self.ipaddr,
             'warn': warn },
         'menu': {
             '1': self.stepForward,
         }
     }
     self.setSubstepEnv(ui)
Exemplo n.º 8
0
    def setIpAddress(self):
        cosNics = userchoices.getCosNICs()

        assert cosNics

        if cosNics[0]['ip']:
            self.networkLabel.set_text("http://%s/" % cosNics[0]['ip'])
Exemplo n.º 9
0
    def updateCosNic(self):
        "Register COS NIC in userchoices."

        assert 'device' in self.nic, "COS NIC requires device"
        assert 'vlanID' in self.nic, "COS NIC requires VLAN ID"

        currentNics = userchoices.getCosNICs()
        if currentNics:
            # COS NIC was previously defined in userchoices.
            # get rid of existing one.
            assert len(currentNics) == 1, "should have only one COS NIC."
            userchoices.delCosNIC(currentNics[0])
            # Use previously set self.net.
        else:
            # Prior to network config, set as DHCP.
            self.nic['bootProto'] = userchoices.NIC_BOOT_DHCP
            self.nic['ip'] = None
            self.nic['netmask'] = None
            self.net = { 'gateway': None,
                'nameserver1': None, 'nameserver2': None, 'hostname': None }

        userchoices.addCosNIC(self.nic['device'], self.nic['vlanID'],
                              self.nic['bootProto'],
                              self.nic['ip'], self.nic['netmask'])

        self.setSubstepEnv( {'next': self.selectNetConfigMethod } )
Exemplo n.º 10
0
def _genNetwork():
    networkChoice = userchoices.getCosNetwork()
    nicChoice = userchoices.getCosNICs()[0]

    flags = ""

    flags += " --addvmportgroup=%s" % \
        str(userchoices.getAddVmPortGroup()).lower()

    flags += " --device=%s" % nicChoice['device'].name
    if nicChoice['vlanID']:
        flags += " --vlanid=%s" % nicChoice['vlanID']

    if nicChoice['bootProto'] == userchoices.NIC_BOOT_DHCP:
        flags += " --bootproto=dhcp"
    else:
        flags += " --bootproto=static"
        flags += " --ip=%s" % nicChoice['ip']
        flags += " --netmask=%s" % nicChoice['netmask']
        flags += " --gateway=%s" % networkChoice['gateway']
        if networkChoice['nameserver1']:
            # can be unset in a static setup.
            flags += " --nameserver=%s" % networkChoice['nameserver1']
            if networkChoice['nameserver2']:
                flags += ",%s" % networkChoice['nameserver2']
        if networkChoice['hostname']:
            flags += " --hostname=%s" % networkChoice['hostname']

    return "network%s\n" % flags
Exemplo n.º 11
0
def _genNetwork():
    networkChoice = userchoices.getCosNetwork()
    nicChoice = userchoices.getCosNICs()[0]

    flags = ""

    flags += " --addvmportgroup=%s" % \
        str(userchoices.getAddVmPortGroup()).lower()
    
    flags += " --device=%s" % nicChoice['device'].name
    if nicChoice['vlanID']:
        flags += " --vlanid=%s" % nicChoice['vlanID']

    if nicChoice['bootProto'] == userchoices.NIC_BOOT_DHCP:
        flags += " --bootproto=dhcp"
    else:
        flags += " --bootproto=static"
        flags += " --ip=%s" % nicChoice['ip']
        flags += " --netmask=%s" % nicChoice['netmask']
        flags += " --gateway=%s" % networkChoice['gateway']
        if networkChoice['nameserver1']:
            # can be unset in a static setup.
            flags += " --nameserver=%s" % networkChoice['nameserver1']
            if networkChoice['nameserver2']:
                flags += ",%s" % networkChoice['nameserver2']
        if networkChoice['hostname']:
            flags += " --hostname=%s" % networkChoice['hostname']

    return "network%s\n" % flags
Exemplo n.º 12
0
def hostAction(context):
    '''Enact the choices in userchoices, and save them permanently to
    the host system.
    First remove any network setup that may have been necessary to download
    the installation media.
    Leave iSCSI networking intact, though, as we don't want to lose access to
    the drive.
    '''
    # userchoices contains all the authoritative info for this host,
    # so clobber any previous settings.
    disconnectDownloadNetwork()


    cosNicChoices = userchoices.getCosNICs()
    if not cosNicChoices:
        return
    if len(cosNicChoices) > 1:
        log.warn('There were more than one group of choices for the COS NIC')
        log.warn('cosNicChoices: %s' % str(cosNicChoices))

    firstSuccessfullyEnabledVNic = None
    for nicChoices in cosNicChoices:
        pNic = nicChoices['device'] # a reference to a PhysicalNicFacade
        vlanID = nicChoices['vlanID']
        if not vlanID:
            vlanID = None
        # this will bump any previous ones that were occupying 'Service Console'
        portGroupName = makePermanentCosPortgroupName()
        vSwitch = VirtualSwitchFacade(portGroupName=portGroupName,
                                      vlanID=vlanID)
        if userchoices.getAddVmPortGroup():
            vmPortGroupName = makeVMPortgroupName()
            vSwitch.addPortGroup(vmPortGroupName)
        vSwitch.uplink = pNic
        if nicChoices['bootProto'] == userchoices.NIC_BOOT_STATIC:
            if not nicChoices['ip'] or not nicChoices['netmask']:
                msg = ('COS NIC %s is not fully defined. Missing '
                       'IP address or netmask' % str(pNic))
                raise Exception(msg)
            ipConf = StaticIPConfig(nicChoices['ip'], nicChoices['netmask'])
        elif nicChoices['bootProto'] == userchoices.NIC_BOOT_DHCP:
            ipConf = DHCPIPConfig()
        else:
            msg = 'Unknown bootProto specified for %s' % pNic
            raise Exception(msg)
        vNic = VirtualNicFacade(ipConfig=ipConf, portGroupName=portGroupName)
        try:
            vNic.enable()
        except vmkctl.HostCtlException, ex:
            # this is not an error since the install might be done in a 
            # "factory" where the network is not actually the production 
            # network, but may cause difficulties running the 
            # %postinstall script
            log.warn('Could not bring up network for NIC %s with IP Config %s'
                     % (pNic, ipConf))
            log.warn('Exception message: %s' % ex.GetMessage())
        else:
            if not firstSuccessfullyEnabledVNic:
                firstSuccessfullyEnabledVNic = vNic
Exemplo n.º 13
0
 def updateDHCPMethod(self):
     "update network settings using DHCP"
     userchoices.clearCosNetwork()
     nic_0 = userchoices.getCosNICs()[0]   # get old cosnic
     device, vlanID = nic_0['device'], nic_0['vlanID']
     userchoices.delCosNIC(nic_0)    # delete if exists in userchoices
     bootProto = userchoices.NIC_BOOT_DHCP
     userchoices.addCosNIC(device, vlanID, bootProto)   # add new cosnic
     self.setSubstepEnv( {'next': self.done } )
Exemplo n.º 14
0
    def _runtimeActions(self):
        errors = []
        warnings = []

        if userchoices.getActivateNetwork() and userchoices.getCosNICs() and \
           not networking.connected() and not userchoices.getUpgrade():
            try:
                networking.cosConnectForInstaller()
            except Exception, ex:
                log.exception(str(ex))
                warnings.append("warning: could not bring up network -- %s\n" %
                                str(ex))
Exemplo n.º 15
0
    def _runtimeActions(self):
        errors = []
        warnings = []

        if userchoices.getActivateNetwork() and userchoices.getCosNICs() and \
           not networking.connected() and not userchoices.getUpgrade():
            try:
                networking.cosConnectForInstaller()
            except Exception, ex:
                log.exception(str(ex))
                warnings.append("warning: could not bring up network -- %s\n" %
                                str(ex))
Exemplo n.º 16
0
    def askStaticIP(self):
        "ask if network should be configured using static IP"
        fields = {
            # NIC fields
            'ip': self.nic.get('ip', None),
            'netmask': self.nic.get('netmask', None),
            # net fields
            'gateway': self.net.get('gateway', None),
            'ns1': self.net.get('nameserver1', None),
            'ns2': self.net.get('nameserver2', None),
            'hostname': self.net.get('hostname', None),
        }

        netsetup = network_address_setup.NetworkAddressSetup(
                clientName="COS Network Configuration",
                task="COS network configuration",
                fields=fields)
        result = netsetup.run()

        assert(len(userchoices.getCosNICs()) == 1)
        nic_0 = userchoices.getCosNICs()[0]   # get old cosnic
        self.nic = {
            'device': nic_0['device'],
            'vlanID': nic_0['vlanID'],
            'bootProto': userchoices.NIC_BOOT_STATIC,
            'ip': fields['ip'],
            'netmask': fields['netmask']
        }
        self.net = {
            'gateway': fields['gateway'],
            'nameserver1': fields['ns1'],
            'nameserver2': fields['ns2'],
            'hostname': fields['hostname'],
        }

        if result == textengine.DISPATCH_NEXT:
            self.setSubstepEnv( {'next': self.configureStaticIP } )
        else:  # assume result == textengine.DISPATCH_BACK:
            self.setSubstepEnv( {'next': self.selectNetConfigMethod } )
Exemplo n.º 17
0
    def start(self):
        "Fetch initial COS NIC and network from userchoices."

        # userchoices.getCosNICS() returns a list of dicts.
        # It probably should have been a single (possibly empty) dict.
        cosnics = userchoices.getCosNICs()
        if cosnics:
            self.nic = cosnics[0]

        # Get existing COS network from userchoices.
        self.net = userchoices.getCosNetwork()

        self.setSubstepEnv({'next': self.askCosNic })
Exemplo n.º 18
0
    def getNext(self, *args):
        """Tell userchoices what choices were made on this screen.
        
           You can assign more than one NIC to the COS from scripted install,
           but not from the GUI installer.
        """
        assert len(userchoices.getVmkNICs()) <= 1, \
               "Found more than one Vmk nic in userchoices."

        if userchoices.getVmkNICs():
            userchoices.delVmkNIC(userchoices.getVmkNICs()[0])

        if self.nicSetup.getDevice() in userchoices.getCosNICDevices():
            window = \
                MessageWindow(self.thisWindow, "iSCSI network adapter",
                "You have already assigned this network interface to the\n"
                "management console.  Are you sure you would like to do that?",
                "okcancel")
            if not window.affirmativeResponse:
                return

            cosNIC = userchoices.getCosNICs()[0]
            cosNet = userchoices.getCosNetwork()
            userchoices.setVmkNetwork(cosNet["gateway"])
            userchoices.addVmkNIC(device=cosNIC["device"],
                                  vlanID=cosNIC["vlanID"],
                                  bootProto=cosNIC["bootProto"],
                                  ip=cosNIC["ip"],
                                  netmask=cosNIC["netmask"])
        else:
            try:
                if self.networkAddressWidgets.getUsingDHCP():
                    bootProto = userchoices.NIC_BOOT_DHCP
                    ipSettings = self.networkAddressWidgets.testIPSettings([])
                else:
                    bootProto = userchoices.NIC_BOOT_STATIC
                    tests = ["ip", "netmask", "gateway"]
                    ipSettings = self.networkAddressWidgets.testIPSettings(
                        tests)

                userchoices.setVmkNetwork(ipSettings["gateway"])
                userchoices.addVmkNIC(device=self.nicSetup.getDevice(),
                                      vlanID=self.nicSetup.getVlanID(),
                                      bootProto=bootProto,
                                      ip=ipSettings["ip"],
                                      netmask=ipSettings["netmask"])
            except exception.StayOnScreen:
                self.parent.response(DialogResponses.STAYONSCREEN)
                return

        self.parent.response(DialogResponses.NEXT)
Exemplo n.º 19
0
    def getNext(self, *args):
        """Tell userchoices what choices were made on this screen.
        
           You can assign more than one NIC to the COS from scripted install,
           but not from the GUI installer.
        """
        assert len(userchoices.getVmkNICs()) <= 1, \
               "Found more than one Vmk nic in userchoices."

        if userchoices.getVmkNICs():
            userchoices.delVmkNIC(userchoices.getVmkNICs()[0])

        if self.nicSetup.getDevice() in userchoices.getCosNICDevices():
            window = \
                MessageWindow(self.thisWindow, "iSCSI network adapter",
                "You have already assigned this network interface to the\n"
                "management console.  Are you sure you would like to do that?",
                "okcancel")
            if not window.affirmativeResponse:
                return

            cosNIC = userchoices.getCosNICs()[0]
            cosNet = userchoices.getCosNetwork()
            userchoices.setVmkNetwork(cosNet["gateway"])
            userchoices.addVmkNIC(device=cosNIC["device"],
                                  vlanID=cosNIC["vlanID"],
                                  bootProto=cosNIC["bootProto"],
                                  ip=cosNIC["ip"],
                                  netmask=cosNIC["netmask"])
        else:
            try:
                if self.networkAddressWidgets.getUsingDHCP():
                    bootProto = userchoices.NIC_BOOT_DHCP
                    ipSettings = self.networkAddressWidgets.testIPSettings([])
                else:
                    bootProto = userchoices.NIC_BOOT_STATIC
                    tests = ["ip", "netmask", "gateway"]
                    ipSettings = self.networkAddressWidgets.testIPSettings(tests)

                userchoices.setVmkNetwork(ipSettings["gateway"])
                userchoices.addVmkNIC(device=self.nicSetup.getDevice(),
                                      vlanID=self.nicSetup.getVlanID(),
                                      bootProto=bootProto,
                                      ip=ipSettings["ip"],
                                      netmask=ipSettings["netmask"])
            except exception.StayOnScreen:
                self.parent.response(DialogResponses.STAYONSCREEN)
                return

        self.parent.response(DialogResponses.NEXT)
Exemplo n.º 20
0
    def configureStaticIP(self):
        "do static IP configuration"
        # Retain COS NIC device and VLAN settings, update ip/netmask.
        currentNics = userchoices.getCosNICs()
        assert len(currentNics) == 1, "should have only one COS NIC."
        userchoices.delCosNIC(currentNics[0])
        userchoices.addCosNIC(self.nic['device'], self.nic['vlanID'],
                              self.nic['bootProto'],
                              self.nic['ip'], self.nic['netmask'])

        # Update network params.
        userchoices.setCosNetwork(self.net['gateway'],
                              self.net['nameserver1'], self.net['nameserver2'],
                              self.net['hostname'])

        self.setSubstepEnv( {'next': self.done } )
Exemplo n.º 21
0
def reviewNetwork(values, networkType):
    """
    networkType is either 'cos' or 'vmk'.

    Used by reviewCosNetwork() and reviewIscsi()
    """
    if networkType == 'cos':
        nics = userchoices.getCosNICs()
        net = userchoices.getCosNetwork()
        xtraNetItems = ('gateway', 'nameserver1', 'nameserver2', 'hostname')
    elif networkType == 'vmk':
        nics = userchoices.getVmkNICs()
        net = userchoices.getVmkNetwork()
        xtraNetItems = ('gateway',)
    else:
        raise ValueError("Illegal arg to reviewNetwork")

    for nic in nics:
        values[networkType + 'Nic'] = htmlEscape(str(nic['device'].name))
        if nic['vlanID']:
            values[networkType + 'VlanID'] = str(nic['vlanID'])
        else:
            values[networkType + 'VlanID'] = '(none)'

        if nic['bootProto'] == 'static':
            values['ip'] = nic['ip']
            values['netmask'] = nic['netmask']
            for value in ['gateway', 'nameserver1', 'nameserver2', 'hostname']:
                if not net[value]:
                    values[value] = '(none)'
                else:
                    values[value] = net[value]
            
            values[networkType + 'NetworkTemplate'] = \
                STATIC_NET_TEMPLATE % values
        else:
            values[networkType + 'NetworkTemplate'] = \
                DHCP_NET_TEMPLATE % values
Exemplo n.º 22
0
                networking.utils.sanityCheckIPSettings(ipSettings["ip"],
                                                       ipSettings["netmask"],
                                                       ipSettings["gateway"])
            except (ValueError, TypeError), msg:
                MessageWindow(self.controlState.gui.getWindow(),
                              "IP Settings Error",
                              str(msg))
                raise StayOnScreen
            userchoices.setCosNetwork(ipSettings["gateway"], ipSettings["ns1"],
                                      ipSettings["ns2"], ipSettings["hostname"])

        #
        # cosnetworkadapter_gui.py has called userchoices.addCosNIC(), but
        # it didn't know what IP or netmask to associate with the chosen NIC.
        # Now that we do know those things, we make that association (and it's
        # just an implementation detail that we do so by deleting and then re-
        # creating the userchoices.__cosNics element rather than editing it in
        # place).
        #
        assert(len(userchoices.getCosNICs()) == 1)
        nic_0 = userchoices.getCosNICs()[0]
        device, vlanID = nic_0['device'], nic_0['vlanID']
        userchoices.delCosNIC(nic_0)
        userchoices.addCosNIC(device, vlanID, bootProto,
                              ipSettings["ip"], ipSettings["netmask"])

    def getNext(self):
        self.saveChoices()
        if userchoices.getActivateNetwork():
            self.activateNetwork(dialogOnSuccess=False)
Exemplo n.º 23
0
def cosConnectForInstaller(failOnWarnings=True, onlyConfiguredNics=True):
    '''Like cosConnect, but it uses userchoices and if you use this
    function exclusively, it will keep only one connected Vnic at a time.
    Tries to make a connection in the following order, stopping after the
    first successful connection is made:
     1. try to use the config in userchoices.*DownloadNic and *DownloadNetwork
     2. try to use the config in userchoices.*CosNic and *CosNetwork
     3. try to use DHCP connections on any remaining NICs

    Arguments:
    failOnWarnings: if True, raise an exception on otherwise survivable
               warnings
    onlyConfiguredNics: if True, don't attempt any nics that haven't been
               configured by the user.  ie, don't try #3 above
    '''
    log.info('Attempting to bring up the network.')
    def doRaise(msg):
        raise Exception(msg)
    if failOnWarnings:
        logOrRaise = doRaise
    else:
        logOrRaise = log.warn

    # ensure we're only manipulating one COS nic
    disconnectDownloadNetwork()
    global _connectedVNic
    if _connectedVNic:
        log.info('Brought down the already-enabled Virtual NIC.')
        _connectedVNic = None

    argsForCosConnect = []
    allNicChoices = []

    downloadNicChoices = userchoices.getDownloadNic()
    if downloadNicChoices:
        log.info('The user chose specific network settings for downloading'
                 'remote media.  Those choices will be attempted first.')
        if not downloadNicChoices['device']:
            availableNIC = getPluggedInAvailableNIC(None)
            if availableNIC:
                downloadNicChoices.update(device=availableNIC)
                allNicChoices.append(downloadNicChoices)
            else:
                logOrRaise('Could not find a free Physical NIC to attach to'
                           ' download network specifications %s' 
                           % str(downloadNicChoices))
        else:
            allNicChoices.append(downloadNicChoices)

    cosNicChoices = userchoices.getCosNICs()
    if cosNicChoices:
        allNicChoices += cosNicChoices
    else:
        msg = 'No COS NICs have been added by the user.'
        logOrRaise(msg)

    for nicChoices in allNicChoices:
        log.debug('nicChoices %s' %str(nicChoices))
        log.debug('Setting vlan (%(vlanID)s), ipConf (%(bootProto)s, %(ip)s, %(netmask)s) '
                  'for NIC %(device)s' % nicChoices)
        assert nicChoices['device']
        nic = nicChoices['device'] # a reference to a PhysicalNicFacade
        vlanID = nicChoices['vlanID']
        if not vlanID:
            vlanID = None #make sure it's None, not just ''
        if nicChoices['bootProto'] == userchoices.NIC_BOOT_STATIC:
            if not nicChoices['ip'] or not nicChoices['netmask']:
                msg = ('COS NIC %s is not fully defined. Missing '
                       'IP address or netmask' % str(nic))
                logOrRaise(msg)
            ipConf = StaticIPConfig(nicChoices['ip'], nicChoices['netmask'])
        elif nicChoices['bootProto'] == userchoices.NIC_BOOT_DHCP:
            ipConf = DHCPIPConfig()
        else:
            msg = 'Unknown bootProto specified for %s' % nic
            logOrRaise(msg)
            ipConf = DHCPIPConfig()

        argsForCosConnect.append((nic, vlanID, ipConf))

    if not onlyConfiguredNics:
        # we've tried all the user-configured nics, now try the rest with DHCP
        configuredNics = [choices['device'] for choices in allNicChoices]
        unConfiguredNics =  set(getPhysicalNics()) - set(configuredNics)
        # sort these for repeatability's sake.
        unConfiguredNics = list(unConfiguredNics)
        unConfiguredNics.sort()
        for nic in unConfiguredNics:
            if not nic.isLinkUp:
                continue # it would be pointless to try unplugged NICs
            log.info('Setting unconfigured NIC %s to use DHCP' % nic)
            ipConf = DHCPIPConfig()
            argsForCosConnect.append((nic, None, ipConf))

    for nic, vlanID, ipConf in argsForCosConnect:
        try:
            log.info('Bringing up network interface for NIC %s. Using ipConf %s'
                     % (nic,ipConf))
            vnic = cosConnect(pNic=nic, vlanID=vlanID, ipConf=ipConf)
        except vmkctl.HostCtlException, ex:
            msg = 'vmkctl HostCtlException:'+ ex.GetMessage()
            logOrRaise(msg)
        else:
            log.info('COS has an enabled Virtual NIC %s.' % vnic)
            _connectedVNic = vnic
            break #we only need one to work
Exemplo n.º 24
0
 def queryCurrentCosNic():
     cosNics = userchoices.getCosNICs()
     if not cosNics:
         return None
     return cosNics[0]['device']