def __activeInterfaces(self): """ Active link (ifconfig nic up) for the NICs with no link @rtype : list @returns: list of NICs with link """ interfaces = self.__devices activeInterfaces = Network.getLinkedInterfaces(False) deactiveInterfaces = [f for f in interfaces.keys() if not f in activeInterfaces] Network.activeLinkInterfaces(deactiveInterfaces) activeInterfaces = Network.getLinkedInterfaces(False) return activeInterfaces
def onPreInstall(self, data): """ Handles the post install event @type data: dict @param data: relevant arguments for that given event @rtype : nothing @returns: nothing """ try: self.__logger.info("Executing InstallAuto module (EVT_PRE_INSTALL).") # work on bootline command file. with open(CMD_FILE) as fd: # parser and store bootline command cmdLine = fd.read().rstrip().split() self.__logger.debug("Bootline:") for line in pprint.pformat(cmdLine).split('\n'): self.__logger.debug(line) # liveDVD parser for i in cmdLine: if i == "root=live:LABEL=POWERKVM_LIVECD": self.__logger.debug("Boot from liveDVD, trying to start network...") Network.startLiveDVDNetwork() break # kickstart parser for i in cmdLine: if i.startswith('kvmp.inst.auto='): self.__kickstartFile = i[i.find('=')+1:] self.__logger.debug("Kickstart file from bootline: %s" % self.__kickstartFile) self.__parserFile() break self.__logger.debug("Data Structure:") for line in pprint.pformat(self.__data).split('\n'): self.__logger.debug(line) for key, value in self.__data.iteritems(): data['model'].insert(key, value) except PKVMError: self.__logger.critical("Failed InstallAuto module") raise except Exception as e: self.__logger.critical("Failed InstallAuto module") self.__logger.critical("EXCEPTION:" + str(type(e))) self.__logger.critical(str(e)) self.__logger.critical("Stacktrace:" + str(traceback.format_exc())) raise PKVMError("PREINSTALL", "INSTALLAUTO", "PRE_MODULES")
def __deactiveInterfaces(self): """ Deactive link (ifconfig nic down) for NICs not changes by user. Restore initial state for them, i.e., no link """ cmd = "grep -s ONBOOT /etc/sysconfig/network-scripts/ifcfg-*" proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode == 0: interfaces = self.__devices deactiveLinkInterfacesAll = [] for fname in out.split(): if fname.endswith("no"): iface = fname.split("-")[-1].split(":")[0] deactiveLinkInterfacesAll.append(iface) deactiveLinkInterfaces = [f for f in deactiveLinkInterfacesAll if f in interfaces.keys()] if len(deactiveLinkInterfaces): Network.deactiveLinkInterfaces(deactiveLinkInterfaces)
def onPreInstall(self, data): """ Handles the pre install event @type data: dict @param data: relevant arguments for that given event @rtype: None @returns: Nothing """ try: self.__logger.info("Executing NetworkTopology module (EVT_PRE_INSTALL).") # NIC status interfaces = Network.getAvailableInterfaces(False) activeLinkInterfaces = Network.getLinkedInterfaces(False) activeInterfaces = Network.getActiveInterfaces(False) udevInterfaces = Network.getAvailableInterfaces() udevActiveLinkInterfaces = Network.getLinkedInterfaces() udevActiveInterfaces = Network.getActiveInterfaces() self.__logger.debug("Network interfaces:") for line in pprint.pformat(interfaces).split('\n'): self.__logger.debug(line) self.__logger.debug("Network interfaces with link:") self.__logger.debug("%s" % activeLinkInterfaces) self.__logger.debug("Network interfaces with network configured:") self.__logger.debug("%s" % activeInterfaces) self.__logger.debug("Network interfaces (UDEV):") for line in pprint.pformat(udevInterfaces).split('\n'): self.__logger.debug(line) self.__logger.debug("Network interfaces with link (UDEV):") self.__logger.debug("%s" % udevActiveLinkInterfaces) self.__logger.debug("Network interfaces with network configured (UDEV):") self.__logger.debug("%s" % udevActiveInterfaces) # Configure network interfaces and bridges devDict = udevInterfaces devActiveList = udevActiveInterfaces if devDict: self.__fixDracutIfcfgFiles(devDict) for dev, mac in devDict.iteritems(): ifcfgFile = "/etc/sysconfig/network-scripts/ifcfg-%s" % dev if not os.path.isfile(ifcfgFile): self.__setEthConfigFile(dev, mac, devActiveList) self.__logger.debug("Writing on ISO image ifcfg file:") self.__logger.debug("%s" % ifcfgFile) for line in pprint.pformat(self.__configFile).split('\n'): self.__logger.debug(line) Network.writeConfigFile(self.__configFile) else: self.__logger.debug("No NIC available!") except Exception as e: self.__logger.critical("Failed NetworkTopology module") self.__logger.critical("EXCEPTION:" + str(type(e))) self.__logger.critical(str(e)) self.__logger.critical("Stacktrace:" + str(traceback.format_exc())) raise PKVMError("PREINSTALL", "NETWORKTOPOLOGY", "PRE_MODULES")
def __hasLink(self): """ Return the link status of the NIC @rtype: boolean @returns: True if NIC has link """ activeLinkInterfaces = Network.getLinkedInterfaces(False) link = False if self.__interface in activeLinkInterfaces: link = True return link
def onPostInstall(self, data): """ Handles the post install event @type data: dict @param data: relevant arguments for that given event @rtype: None @returns: Nothing """ try: self.__mountDir = data['model'].get('mountDir') self.__logger.debug("Copying network config files from image to installed system...") Network.copyConfigFile(self.__mountDir) self.__logger.debug("Restarting network services in chrooted installed system...") Network.restartNetworkService(self.__mountDir) if data['model'].get('ntpservers'): Network.setNTP(self.__mountDir) except Exception as e: self.__logger.critical("Failed NetSetup module!") self.__logger.critical("EXCEPTION:" + str(type(e))) self.__logger.critical(str(e)) self.__logger.critical("Stacktrace:" + str(traceback.format_exc())) raise PKVMError("POSTINSTALL", "NETSETUP", "POST_MODULES")
def __init__(self, screen): """ Constructor @type screen: SnackScreen @param screen: SnackScreen instance """ self.__screen = screen self.__msg = TextboxReflowed(40, "Select the device on the list to be configured:") self.__list = Listbox(5, scroll=1, returnExit=1) self.__buttonsBar = ButtonBar(self.__screen, [("OK", "ok"), ("Back", "back")]) self.__devices = Network.getAvailableInterfaces(False)
def __init__(self, screen): """ Constructor @type screen: SnackScreen @param screen: SnackScreen instance """ self.__screen = screen self.__msg = TextboxReflowed(40, LISTNETIFACE_SELECT_DEVICE.localize()) self.__list = Listbox(5, scroll=1, returnExit=1) self.__buttonsBar = ButtonBar(self.__screen, [(EDIT.localize(), "edit"), (BACK.localize(), "back"),(NEXT.localize(), "next")]) self.__devices = Network.getAvailableInterfaces()
def __setAllDHCP(self): """ Config all NIC's to DHCP. @rtype: None @returns: Nothing """ self.__logger.debug("Setting all NIC's to DHCP.") # Verify if there is a NIC redefined by bootline ifname = Network.getCmdLineNIC() if ifname is not None: # load previous configuration. self.__loadConfigFile(ifname) # set redefined NIC in bootline to DHCP self.enableDHCP(True) # Saving network cfg file self.__saveIfcfgFile()
def run(self): """ Draws the screen @rtype: integer @returns: status of operation """ devicesUp = Network.getLinkedInterfaces() #sortedDevices = sorted(self.__devices, key=self.__devices.get) sortedDevices = sorted(self.__devices) for dev in sortedDevices: bridge = "br%s" % dev if dev in devicesUp: active = UP.localize() elif bridge in devicesUp: active = UP.localize() + ' - %s' % bridge else: active = DOWN.localize() display = "%s [ %s ] (%s)" % (dev, self.__devices.get(dev), active) self.__list.append(display, dev) return self.__show()
def __saveIfcfgFile(self): """ Save ifcfg file for current NIC and for its bridge, if it is applicable. @rtype: None @returns: Nothing """ # Saving network cfg file self.__logger.debug("Writing on ISO image ethConfigFile:") for line in pprint.pformat(self.__ethConfigFile).split('\n'): self.__logger.debug(line) Network.writeConfigFile(self.__ethConfigFile) if self.__hasBridge: self.__logger.debug("Writing on ISO image brConfigFile:") for line in pprint.pformat(self.__brConfigFile).split('\n'): self.__logger.debug(line) Network.writeConfigFile(self.__brConfigFile) else: Network.deleteBrConfigFile(self.__ethConfigFile['DEVICE'])
def __saveConfig(self): """ Write the configuration into the file @rtype: None @returns: nothing """ # bridge if self.__bridge.selected(): self.__dev.setBridge(True) else: self.__dev.setBridge(False) # device self.__dev.setDev(self.__interface, self.__macaddr) # onboot if self.__hasLink(): if self.__enable.selected(): self.__dev.setOnBoot(True) else: self.__dev.setOnBoot(False) else: self.__dev.setOnBoot(False) # dns self.__dev.setDNS() # dhcp if self.__dhcp.selected(): self.__dev.enableDHCP(True) else: self.__dev.enableDHCP(False) self.__dev.setIp(self.__ip.value()) self.__dev.setNetmask(self.__netmask.value()) self.__dev.setGateway(self.__gateway.value()) # Saving network cfg file Network.writeConfigFile(self.__dev.getEthConfigFile()) if self.__dev.hasBridge(): Network.writeConfigFile(self.__dev.getBrConfigFile()) else: Network.deleteBrConfigFile(self.__interface)
if __name__ == "__main__": filewriter = Filewriter() local_test = len(sys.argv) > 2 if local_test: print("You are running in testing mode") my_host = _get_ip() if not local_test else "127.0.0.1" my_port = LISTEN_PORT if not local_test else int(sys.argv[2]) my_id = sys.argv[1] profile = Entity(my_host, my_port, my_id) network = Network(profile, local_test) manager = DFSM.DFSManager(network, my_id, filewriter, "modules/dfs/dfs.json") log = Log() logger = log.get_logger() log.toggle_debug() # hello logger.info("Starting up") listen = socket.socket() # tell os to recycle port quickly listen.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self): """ Draws the screen @rtype: integer @returns: status of operation """ # dhcp if self.__dev.getBootProto() == "dhcp": self.__dhcp.setValue('*') self.__grid.setCurrent(self.__dhcp) # bridge if self.__dev.hasBridge(): self.__bridge.setValue('*') # onboot if self.__hasLink(): if self.__dev.getOnBoot(): self.__enable.setValue('*') else: self.__enable.setFlags(FLAG_DISABLED, FLAGS_SET) self.__grid.setCurrent(self.__bridge) self.__ip.set(Network.removeDoubleQuotes(self.__dev.getIp())) self.__netmask.set(Network.removeDoubleQuotes(self.__dev.getNetmask())) self.__gateway.set(Network.removeDoubleQuotes(self.__dev.getGateway())) self.useDynamicCheckBox() result = self.__grid.run() self.__screen.popWindow() rc = self.__buttonsBar.buttonPressed(result) if rc == "save": if self.__dhcp.selected() or self.__ip.value() != "" or not self.__enable.selected(): self.__saveConfig() msg = TextboxReflowed(40, "Configuring %s interface..." % self.__hwdev.value()) g = GridForm(self.__screen, "IBM PowerKVM", 1, 2) g.add(msg, 0, 0) g.draw() self.__screen.refresh() try: # restart network service Network.restartNetworkService(None, self.__interface) return 0 except Exception as e: Network.disableNIC(None, self.__interface) ButtonChoiceWindow(self.__screen, "ERROR", "Failed to configure %s interface:\n%s" % (self.__interface, e), buttons=[BUTTON_OK], width=40) return -1 finally: self.__screen.popWindow() else: ButtonChoiceWindow(self.__screen, ERROR_INVALID_ENTRY, ERROR_INVALID_ENTRY_MSG, buttons=[BUTTON_OK], width=50) return 1 if rc == "back": return 1