def reconfigNode(self, new_hostname): """ Used when changing the hostname """ old_console = None if self.emudev: old_console = self.emudev.console links = self.getEdgeList() if len(links): QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AnyEmuDevice", "New hostname"), translate("AnyEmuDevice", "Cannot rename a connected emulated device")) return # if self.hostname != new_hostname: # self.emudev.rename(new_hostname) # self.set_hostname(new_hostname) self.delete_emudev() if self.hostname != new_hostname: try: qemu_name = self.qemu.host + ':' + str(self.qemu.port) shutil.move(self.dynagen.dynamips[qemu_name].workingdir + os.sep + self.hostname, self.dynagen.dynamips[qemu_name].workingdir + os.sep + new_hostname) except: debug("Cannot move emulator's working directory") self.set_hostname(new_hostname) try: self.create_emudev() if old_console: self.emudev.console = old_console except lib.DynamipsError, msg: QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AnyEmuDevice", "Dynamips error"), unicode(msg)) self.delete_emudev() globals.GApp.topology.deleteNode(self.id) return
def __setDynamipsPath(self): """ Open a file dialog for choosing the location of dynamips executable """ dynamips_default_directory = '.' if sys.platform.startswith('darwin') and os.path.exists('../Resources/') and hasattr(sys, "frozen"): dynamips_default_directory = '../Resources/' fb = fileBrowser(translate('UiConfig_PreferencesDynamips', 'Dynamips binary'), directory=dynamips_default_directory, parent=globals.preferencesWindow) (path, selected) = fb.getFile() if path is not None and path != '': # test if we can open it if not testOpenFile(path): QtGui.QMessageBox.critical(globals.preferencesWindow, 'Dynamips path', translate("UiConfig_PreferencesDynamips", "Can't open file: %s") % path) return self.dynamips_path.clear() self.dynamips_path.setText(os.path.normpath(path)) if sys.platform.startswith('win'): try: path.encode('ascii') except: QtGui.QMessageBox.warning(globals.preferencesWindow, translate("UiConfig_PreferencesDynamips", "Dynamips path"), translate("UiConfig_PreferencesDynamips", "The path you have selected should contains only ascii (English) characters. Dynamips (Cygwin DLL) doesn't support unicode on Windows!"))
def __init__(self): """ Initilize a preferences dialog """ # force the translation of Capture translate('PreferencesDialog', 'Capture') self.__prefsList = [ 'General', 'Dynamips', 'Capture', 'Qemu', ] QtGui.QDialog.__init__(self) self.setupUi(self) self.connect(self.listWidget, QtCore.SIGNAL('currentItemChanged(QListWidgetItem *, QListWidgetItem *)'), self.configItemChanged) self.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Apply), QtCore.SIGNAL('clicked()'), self.__applyChanges) self.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Ok), QtCore.SIGNAL('clicked()'), self.__applyChanges) # Init dialog self.__initDialog() # Raise a element in list self.__raiseWidgetByNum(0)
def __importConfiguration(self): config_path = os.path.normpath(unicode(ConfDB().fileName())) (path, selected) = fileBrowser( translate("UiConfig_PreferencesGeneral", "Import configuration"), filter="INI file (*.ini);;All files (*.*)", directory=os.path.dirname(config_path), parent=globals.preferencesWindow, ).getFile() if path != None and path != "": path = os.path.normpath(path) try: shutil.copyfile(path, config_path) except (OSError, IOError), e: QtGui.QMessageBox.critical( globals.preferencesWindow, translate("UiConfig_PreferencesGeneral", "Import configuration"), translate("UiConfig_PreferencesGeneral", "Cannot export configuration file: %s") % e.strerror, ) return except shutil.Error, e: QtGui.QMessageBox.critical( globals.preferencesWindow, translate("UiConfig_PreferencesGeneral", "Import configuration"), translate("UiConfig_PreferencesGeneral", "%s") % e, ) return
def saveProjectSettings(self): """ Save project settings """ projectName = unicode(self.ProjectName.text()) projectDir = os.path.normpath(unicode(self.ProjectPath.text())) if not projectName or not projectDir: return (None, None, None, False, False) if os.path.exists(projectDir): reply = QtGui.QMessageBox.question(self, translate('ProjectDialog', 'Projects Directory'), translate('ProjectDialog', "Project directory already exists, overwrite?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.No: return (None, None, None, False, False) else: try: os.makedirs(projectDir) except (OSError, IOError), e: QtGui.QMessageBox.critical(self, translate('ProjectDialog', 'Projects Directory'), translate("Workspace", "Cannot create directory %s: %s") % (projectDir, e.strerror)) return (None, None, None, False, False)
def do_save(self, args): """save {/all | router1 [router2] ...}\nstores router configs in the network file""" if not globals.GApp.workspace.projectFile: print translate("Console", "You have to save your topology before using save") else: Dynagen_Console.do_save(self, args)
def slotAdd(self): """ Add a symbol to the node list """ symbols = self.treeWidgetSymbols.selectedItems() for symbol in symbols: name = unicode(symbol.text(0)) resource_symbol = unicode(symbol.data(0, QtCore.Qt.UserRole).toString()) if resource_symbol.startswith(':/symbols/'): normal_svg_file = resource_symbol selected_svg_file = ':/symbols/' + name + '.selected.svg' else: normal_svg_file = selected_svg_file = resource_symbol SYMBOLS.append( {'name': name, 'object': DecorativeNode, 'normal_svg_file': normal_svg_file, 'select_svg_file': selected_svg_file, 'translated': False}) item = QtGui.QTreeWidgetItem(self.treeWidgetNodes) item.setText(0, name) item.setIcon(0, symbol.icon(0)) item.setData(0, QtCore.Qt.UserRole, QtCore.QVariant(translate("nodesDock", "Decorative node"))) item.setSelected(True) self.lineEditNodeName.setText(name) index = self.comboBoxNodeType.findText(translate("nodesDock", "Decorative node")) if index != -1: self.comboBoxNodeType.setCurrentIndex(index) self.treeWidgetNodes.setCurrentItem(item)
def __stopCaptureAction(self, showMessage=True): """ Stop capturing frames on the link """ try: if isinstance(globals.GApp.dynagen.devices[self.captureInfo[0]], qemu.AnyEmuDevice): (device, port) = self.captureInfo if showMessage and globals.GApp.dynagen.devices[device].state == 'running': QtGui.QMessageBox.warning(globals.GApp.mainWindow, translate("AbstractEdge", "Capture"), unicode(translate("AbstractEdge", "Device %s must be stopped to stop capturing traffic")) % device) # empty string means stop capturing traffic globals.GApp.dynagen.devices[device].capture(int(port), '') else: (device, slot, inttype, port) = self.captureInfo globals.GApp.dynagen.devices[device].slot[slot].filter(inttype, port, 'none', 'both') self.capturing = False self.captureInfo = None self.capfile = None except lib.DynamipsError, msg: if showMessage: QtGui.QMessageBox.critical(self, translate("AbstractEdge", "Dynamips error"), unicode(msg)) return
def do_push(self, args): """push {/all | router1 [router2] ...}\npushes router configs from the network file to the router's nvram""" if not globals.GApp.workspace.projectFile: print translate("Console", "You have to save your topology before using push") else: Dynagen_Console.do_push(self, args)
def showContextualMenu(self): menu = QtGui.QMenu() expandAll = QtGui.QAction(translate('topologySummaryDock', 'Expand all'), menu) expandAll.setIcon(QtGui.QIcon(":/icons/plus.svg")) self.connect(expandAll, QtCore.SIGNAL('triggered()'), self.slotExpandAll) collapseAll = QtGui.QAction(translate('topologySummaryDock', 'Collapse all'), menu) collapseAll.setIcon(QtGui.QIcon(":/icons/minus.svg")) self.connect(collapseAll, QtCore.SIGNAL('triggered()'), self.slotCollapseAll) menu.addAction(expandAll) menu.addAction(collapseAll) # add link actions to menu if link info item is selected curitem = self.currentItem() if curitem: menu.addSeparator() data = curitem.data(0, QtCore.Qt.UserRole).toStringList() if data.count() == 4: node_interface = data[0] node_hostname = data[3] node = globals.GApp.topology.getNode(globals.GApp.topology.getNodeID(node_hostname)) if node: link = node.getConnectedLinkByName(node_interface) if link: link.addLinkActionsToMenu(menu) menu.exec_(QtGui.QCursor.pos())
def slotAddMap(self): """ Add a new map """ srcport = self.spinBoxSrcPort.value() destport = self.spinBoxDestPort.value() destvpi = self.spinBoxDestVPI.value() destvci = self.spinBoxDestVCI.value() if srcport == destport: QtGui.QMessageBox.critical(globals.nodeConfiguratorWindow, translate("Page_ATMBR", "Add mapping"), translate("Page_ATMBR", "Same source and destination ports")) return source = str(srcport) destination = str(destport) + ':' + str(destvpi) + ':' + str(destvci) if self.mapping.has_key(destination): QtGui.QMessageBox.critical(globals.nodeConfiguratorWindow, translate("Page_ATMBR", "Add mapping"), translate("Page_ATMBR", "Mapping already defined")) return item = QtGui.QTreeWidgetItem(self.treeWidgetMapping) item.setText(0, source) item.setText(1, destination) self.treeWidgetMapping.addTopLevelItem(item) self.spinBoxSrcPort.setValue(srcport + 1) self.spinBoxDestPort.setValue(destport + 1) self.mapping[source] = destination
def do_clear(self, args): """clear [item] Examples: clear mac <ethernet_switch_name> -- clear the mac address table of an ethernet switch clear topology -- clear the network topology""" if '?' in args or args.strip() == '': print self.do_clear.__doc__ return try: command = args.split()[0].lower() params = args.split()[1:] if command == 'topology': globals.GApp.topology.clear() return if command == 'mac': try: Dynagen_Console.do_clear(self, args) except Exception, e: print e except ValueError: print translate("Console", "Incorrect number of paramaters or invalid parameters") return except KeyError: print translate("Console", "Unknown device: %s") % device return except lib.DynamipsError, e: print e return
def slotAddVC(self): """ Add a new virtual channel """ srcport = self.spinBoxSrcPort.value() srcdlci = self.spinBoxSrcDLCI.value() destport = self.spinBoxDestPort.value() destdlci = self.spinBoxDestDLCI.value() if srcport == destport: QtGui.QMessageBox.critical(globals.nodeConfiguratorWindow, translate("Page_FRSW", "Add virtual channel"), translate("Page_FRSW", "Same source and destination ports")) return source = str(srcport) + ':' + str(srcdlci) destination = str(destport) + ':' + str(destdlci) if self.mapping.has_key(source) or self.mapping.has_key(destination): QtGui.QMessageBox.critical(globals.nodeConfiguratorWindow, translate("Page_FRSW", "Add virtual channel"), translate("Page_FRSW", "Mapping already defined")) return item = QtGui.QTreeWidgetItem(self.treeWidgetVCmap) item.setText(0, source) item.setText(1, destination) self.treeWidgetVCmap.addTopLevelItem(item) self.spinBoxSrcPort.setValue(srcport + 1) self.spinBoxSrcDLCI.setValue(srcdlci + 1) self.spinBoxDestPort.setValue(destport + 1) self.spinBoxDestDLCI.setValue(destdlci + 1) self.mapping[source] = destination
def apply(self, message=False): """ Apply the IDLE PC to the router """ try: selection = str(self.comboBox.currentText()).split(':')[0].strip('* ') index = int(selection) for node in globals.GApp.topology.nodes.values(): if isinstance(node, IOSRouter) and node.hostname == self.router.hostname: dyn_router = node.get_dynagen_device() if globals.GApp.iosimages.has_key(dyn_router.dynamips.host + ':' + dyn_router.image): image = globals.GApp.iosimages[dyn_router.dynamips.host + ':' + dyn_router.image] debug("Register IDLE PC " + self.idles[index] + " for image " + image.filename) image.idlepc = self.idles[index] # Apply idle pc to devices with the same IOS image for device in globals.GApp.topology.nodes.values(): if isinstance(device, IOSRouter) and device.config['image'] == image.filename: debug("Apply IDLE PC " + self.idles[index] + " to " + device.hostname) device.get_dynagen_device().idlepc = self.idles[index] config = device.get_config() config['idlepc'] = self.idles[index] device.set_config(config) device.setCustomToolTip() break if message: QtGui.QMessageBox.information(self, translate("IDLEPCDialog", "IDLE PC"), unicode(translate("IDLEPCDialog", "IDLE PC value %s has been applied on %s")) % (self.idles[index], self.router.hostname)) except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("IDLEPCDialog", "Dynamips error"), unicode(msg)) return
def __clearConfiguration(self): reply = QtGui.QMessageBox.question( globals.preferencesWindow, translate("UiConfig_PreferencesGeneral", "Configuration file"), translate("UiConfig_PreferencesGeneral", "All GNS3 configuration will be lost. Do you want to proceed?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, ) if reply == QtGui.QMessageBox.Yes: from __main__ import VERSION ConfDB().clear() c = ConfDB() c.set("GNS3/version", VERSION) c.sync() QtGui.QMessageBox.information( globals.preferencesWindow, translate("UiConfig_PreferencesGeneral", "Configuration file"), translate( "UiConfig_PreferencesGeneral", "Configuration file cleared, default settings will be applied after a restart", ), ) globals.recordConfiguration = False globals.preferencesWindow.close()
def __slotSelectionChanged(self): """ Check and display title in the treeViewNodes """ items = self.treeViewNodes.selectedItems() count = len(items) if count == 0: return last_item = items[count - 1] self.__showConfigurationPage(last_item, 0) lasttype = type(globals.GApp.topology.getNode(last_item.getIDs()[0])) for item in items: itmtype = type(globals.GApp.topology.getNode(item.getIDs()[0])) if itmtype != lasttype: item.setSelected(False) count = count - 1 if not item.parent(): if last_item.parent(): newLabel = unicode(translate("NodeConfigurator", "%s node")) % (unicode(last_item.text(0))) self.titleLabel.setText(newLabel) newLabel = unicode(translate("NodeConfigurator", "%s group")) % (unicode(last_item.text(0))) self.titleLabel.setText(newLabel) return if count > 1: pageTitle = unicode(translate("NodeConfigurator", "Group of %d %s")) \ % (count, unicode(last_item.parent().text(0))) else: pageTitle = unicode(translate("NodeConfigurator", "%s node")) % (unicode(last_item.text(0)) ) self.titleLabel.setText(pageTitle)
def __setCaptureWorkdir(self): """ Open a file dialog for choosing the location of local hypervisor working directory """ capture_default_working_directory = '.' if os.environ.has_key("TEMP"): capture_default_working_directory = os.environ["TEMP"] elif os.environ.has_key("TMP"): capture_default_working_directory = os.environ["TMP"] elif os.path.exists('/tmp'): capture_default_working_directory = unicode('/tmp') fb = fileBrowser(translate('UiConfig_PreferencesCapture', 'Local capture working directory'), directory=capture_default_working_directory, parent=globals.preferencesWindow) path = fb.getDir() if path: path = os.path.normpath(path) self.CaptureWorkingDirectory.setText(path) if sys.platform.startswith('win'): try: path.encode('ascii') except: QtGui.QMessageBox.warning(globals.preferencesWindow, translate("Page_PreferencesCapture", "Capture directory"), translate("Page_PreferencesCapture", "The path you have selected should contains only ascii (English) characters. Dynamips (Cygwin DLL) doesn't support unicode on Windows!")) if not testIfWritableDir(path): QtGui.QMessageBox.critical(globals.preferencesWindow, translate("Page_PreferencesCapture", "Capture directory"), translate("Page_PreferencesCapture", "Capture directory must be writable!"))
def __init__(self, parent=None): """ Initilize a preferences dialog """ # force the translation of Capture translate('PreferencesDialog', 'Capture') self.__prefsList = [ 'General', 'Dynamips', 'Capture', 'Qemu', 'VirtualBox', #'DeployementWizard' #FIXME: TEMP DISABLED FOR GNS3 0.8.4 RC1. ] QtGui.QDialog.__init__(self, parent) self.setupUi(self) self.connect(self.listWidget, QtCore.SIGNAL('currentItemChanged(QListWidgetItem *, QListWidgetItem *)'), self.configItemChanged) self.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Apply), QtCore.SIGNAL('clicked()'), self.__applyChanges) # self.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Ok), QtCore.SIGNAL('clicked()'), self.__applyChanges) # Init dialog self.__initDialog() # Raise a element in list self.__raiseWidgetByNum(0)
def preloadQemuwrapper(self, port): """ Preload Qemuwrapper """ proc = QtCore.QProcess(globals.GApp.mainWindow) binding = globals.GApp.systconf['qemu'].QemuManager_binding self.port = port if globals.GApp.systconf['qemu'].qemuwrapper_workdir: if not os.access(globals.GApp.systconf['qemu'].qemuwrapper_workdir, os.F_OK | os.W_OK): raise Exception(translate("QemuManager", "Working directory %s seems to not exist or be writable, please check") % globals.GApp.systconf['qemu'].qemuwrapper_workdir) proc.setWorkingDirectory(globals.GApp.systconf['qemu'].qemuwrapper_workdir) # start Qemuwrapper, use python on all platform but Windows (in release mode) if sys.platform.startswith('win') and (globals.GApp.systconf['qemu'].qemuwrapper_path.split('.')[-1] == 'exe'): # On Windows hosts, we remove python dependency by pre-compiling Qemuwrapper. (release mode) proc.start('"' + globals.GApp.systconf['qemu'].qemuwrapper_path + '"', ['--listen', binding, '--no-path-check']) elif hasattr(sys, "frozen"): proc.start('python', [globals.GApp.systconf['qemu'].qemuwrapper_path, '--listen', binding, '--no-path-check']) else: proc.start(sys.executable, [globals.GApp.systconf['qemu'].qemuwrapper_path, '--listen', binding, '--no-path-check']) if proc.waitForStarted() == False: raise Exception(translate('QemuManager', 'Could not start qemuwrapper.py')) # give 3 seconds to the hypervisor to accept connections count = 3 connection_success = False timeout = 10 for nb in range(count + 1): try: s = socket.create_connection((binding, self.port), timeout) except: time.sleep(1) continue connection_success = True break if connection_success: # check qemuwrapper version proc.waitForReadyRead(5000) output = proc.readAllStandardOutput() ver = QtCore.QByteArray('(version ') verOffset = output.indexOf(ver) + len('(version ') if verOffset != -1: ver = QtCore.QByteArray(")" + os.linesep) endVerOffset = output.indexOf(ver, verOffset) - verOffset wrapperVer = output.mid(verOffset, endVerOffset) # AWP implementation case if wrapperVer[-4:] == '-atl': wrapperVer = wrapperVer[:-4] # In case of ATL-specific wrapper if wrapperVer != VERSION: proc.close() raise Exception(translate('QemuManager', 'Bad qemuwrapper.py version, expected (%s) got (%s)') % (VERSION, wrapperVer)) proc.close() return True elif proc.state(): proc.close() raise Exception(translate('QemuManager', 'Could not connect to qemuwrapper on %s:%s' % (binding, self.port)))
def startNewHypervisor(self, port, processcheck=True): """ Create a new dynamips process and start it """ proc = QtCore.QProcess(globals.GApp.mainWindow) if self.hypervisor_wd: # set the working directory proc.setWorkingDirectory(self.hypervisor_wd) if processcheck: # test if a hypervisor is already running on this port s = socket(AF_INET, SOCK_STREAM) s.setblocking(0) s.settimeout(300) try: s.connect(('localhost', port)) s.close() reply = QtGui.QMessageBox.question(globals.GApp.mainWindow, translate("HypervisorManager", "Hypervisor Manager"), unicode(translate("HypervisorManager", "Apparently an hypervisor is already running on port %i, would you like to kill all Dynamips processes?")) % port, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: killAll(os.path.basename(self.hypervisor_path)) time.sleep(1) else: print "Incrementing +100 for base console port, base AUX port, base hypervisor port and base UDP port" self.baseConsole += 100 if self.baseAUX: self.baseAUX += 100 globals.hypervisor_baseport += 100 globals.GApp.dynagen.globaludp += 100 port = globals.hypervisor_baseport s.connect(('localhost', port)) s.close() QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("HypervisorManager", "Hypervisor Manager"), unicode(translate("HypervisorManager", "A program is still running on port %i, you will have to stop it manually or change port settings")) % port) globals.hypervisor_baseport += 1 return None except: s.close() # start dynamips in hypervisor mode (-H) proc.start( self.hypervisor_path , ['-H', str(port)]) if proc.waitForStarted() == False: QtGui.QMessageBox.critical(globals.GApp.mainWindow, 'Hypervisor Manager', unicode(translate("HypervisorManager", "Can't start Dynamips on port %i")) % port) return None hypervisor = {'port': port, 'proc_instance': proc, 'load': 0, 'image_ref': ''} self.hypervisors.append(hypervisor) return hypervisor
def aux(self): """ Start a telnet console and connect it to this router's AUX port """ if not self.router.aux: print translate("IOSRouter", "AUX port not available for this router model or base AUX port is set to 0 in preferences") return if self.router and self.router.state == 'running': console.connect(self.hypervisor.host, self.router.aux, self.hostname)
def slotSaveASAImage(self): """ Add/Save ASA Image in the list of ASA images """ name = unicode(self.NameASAImage.text()) initrd = unicode(self.ASAInitrd.text()) kernel = unicode(self.ASAKernel.text()) if not name or not initrd or not kernel: QtGui.QMessageBox.critical(globals.preferencesWindow, translate("Page_PreferencesQemu", "ASA firewall"), translate("Page_PreferencesQemu", "Identifier, initrd and kernel must be set!")) return if globals.GApp.asaimages.has_key(name): # update an already existing ASA initrd + kernel item_to_update = self.treeWidgetASAImages.findItems(name, QtCore.Qt.MatchFixedString)[0] item_to_update.setText(1, initrd) item_to_update.setText(2, kernel) else: # else create a new entry item = QtGui.QTreeWidgetItem(self.treeWidgetASAImages) # image name column item.setText(0, name) # initrd path column item.setText(1, initrd) # kernel path column item.setText(2, kernel) # save settings if globals.GApp.asaimages.has_key(name): conf = globals.GApp.asaimages[name] else: conf = asaImageConf() conf.id = globals.GApp.asaimages_ids globals.GApp.asaimages_ids += 1 conf.name = name conf.initrd = initrd conf.kernel = kernel conf.kernel_cmdline = unicode(self.ASAKernelCmdLine.text()) conf.memory = self.ASAMemory.value() conf.nic_nb = self.ASANICNb.value() conf.nic = str(self.ASANIC.currentText()) conf.options = str(self.ASAOptions.text()) if self.ASAcheckBoxKqemu.checkState() == QtCore.Qt.Checked: conf.kqemu = True else: conf.kqemu = False if self.ASAcheckBoxKVM.checkState() == QtCore.Qt.Checked: conf.kvm = True else: conf.kvm = False globals.GApp.asaimages[name] = conf self.treeWidgetASAImages.resizeColumnToContents(0) QtGui.QMessageBox.information(globals.preferencesWindow, translate("Page_PreferencesQemu", "Save"), translate("Page_PreferencesQemu", "ASA settings have been saved"))
def slotTestSettings(self): """ Test the IOS image using Dynamips in a terminal """ image_path = unicode(self.lineEditIOSImage.text(), 'utf-8', errors='replace') if not image_path: return if self.checkBoxIntegratedHypervisor.checkState() == QtCore.Qt.Checked: QtGui.QMessageBox.critical(self, translate("IOSDialog", "Test Settings"), translate("IOSDialog", "Only local IOS images can be tested")) return if len(globals.GApp.topology.nodes): reply = QtGui.QMessageBox.question(self, translate("IOSDialog", "Test Settings"), translate("IOSDialog", "This action is going to delete your current topology, would you like to continue?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.No: return globals.GApp.workspace.clear() dynamips_path = globals.GApp.systconf['dynamips'].path dynamips_workdir = globals.GApp.systconf['dynamips'].workdir if not dynamips_path: QtGui.QMessageBox.critical(self, translate("IOSDialog", "Dynamips path"), translate("IOSDialog", "Dynamips path must be set")) return if not dynamips_workdir: QtGui.QMessageBox.critical(self, translate("IOSDialog", "Dynamips working directory"), translate("IOSDialog", "Dynamips working directory must be set")) return if not sys.platform.startswith('win') and self.testedSettings: if sys.platform.startswith('darwin'): killAll(os.path.basename(globals.GApp.systconf['dynamips'].path)) else: killAll(globals.GApp.systconf['dynamips'].path) platform = str(self.comboBoxPlatform.currentText())[1:] if platform == '3700': platform = str(self.comboBoxChassis.currentText()) ram = self.spinBoxDefaultRAM.value() idlepc = str(self.lineEditIdlePC.text()).strip() if not idlepc: idlepc = '0x0' cmd = '' if sys.platform.startswith('win'): cmd = 'set PATH=%%~dp0;%%PATH%% && cd "%s" && ' % dynamips_workdir dynamips_path = os.path.realpath(dynamips_path) cmd += '"%s" -P %s -r %i --idle-pc %s "%s"' % (dynamips_path, platform, ram, idlepc, image_path) elif sys.platform.startswith('darwin'): cmd += '%s -P %s -r %i --idle-pc %s \\"%s\\"' % (dynamips_path, platform, ram, idlepc, image_path) else: cmd += '%s -P %s -r %i --idle-pc %s "%s"' % (dynamips_path, platform, ram, idlepc, image_path) if os.path.basename(image_path).startswith("c7200p"): # set NPE-G2 for 7200p platform (PPC32 processor) cmd += " -t npe-g2" runTerminal(cmd, dynamips_workdir, False) self.testedSettings = True
def changeHostname(self): """ Called to change the hostname """ if self.router.state != 'stopped': QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("IOSRouter", "New hostname"), translate("IOSRouter", "Cannot change the hostname of a running device")) return AbstractNode.changeHostname(self)
def slotSaveIDSImage(self): """ Add/Save IDS Image in the list of IDS images """ name = unicode(self.NameIDSImage.text()) image1 = unicode(self.IDSImage1.text()) image2 = unicode(self.IDSImage2.text()) if not name or not image1 or not image2: QtGui.QMessageBox.critical(globals.preferencesWindow, translate("Page_PreferencesQemu", "IDS"), translate("Page_PreferencesQemu", "Identifier, image 1 and image 2 must be set!")) return if globals.GApp.idsimages.has_key(name): # update an already existing IDS image1 + image2 item_to_update = self.treeWidgetIDSImages.findItems(name, QtCore.Qt.MatchFixedString)[0] item_to_update.setText(1, image1) item_to_update.setText(2, image2) else: # else create a new entry item = QtGui.QTreeWidgetItem(self.treeWidgetIDSImages) # image name column item.setText(0, name) # image1 path column item.setText(1, image1) # image2 path column item.setText(2, image2) # save settings if globals.GApp.idsimages.has_key(name): conf = globals.GApp.idsimages[name] else: conf = idsImageConf() conf.id = globals.GApp.idsimages_ids globals.GApp.idsimages_ids += 1 conf.name = name conf.image1 = image1 conf.image2 = image2 conf.memory = self.IDSMemory.value() conf.nic_nb = self.IDSNICNb.value() conf.nic = str(self.IDSNIC.currentText()) conf.options = str(self.IDSOptions.text()) if self.IDScheckBoxKqemu.checkState() == QtCore.Qt.Checked: conf.kqemu = True else: conf.kqemu = False if self.IDScheckBoxKVM.checkState() == QtCore.Qt.Checked: conf.kvm = True else: conf.kvm = False globals.GApp.idsimages[name] = conf self.treeWidgetIDSImages.resizeColumnToContents(0) QtGui.QMessageBox.information(globals.preferencesWindow, translate("Page_PreferencesQemu", "Save"), translate("Page_PreferencesQemu", "IDS settings have been saved"))
def slotSelectIOS(self): """ Get an IOS image file from the file system Insert platforms and models """ # get the path to the ios image path = fileBrowser(translate("IOSDialog", "Select an IOS image"), directory=globals.GApp.systconf['general'].ios_path, parent=self).getFile() if path != None and path[0] != '': path = os.path.normpath(path[0]) # test if we can open it if not testOpenFile(path): QtGui.QMessageBox.critical(self, translate("IOSDialog", "IOS Configuration"), unicode(translate("IOSDialog", "Can't open file: %s")) % path) return if sys.platform.startswith('win'): try: path.encode('ascii') except: QtGui.QMessageBox.warning(self, translate("IOSDialog", "IOS Configuration"), translate("IOSDialog", "The path you have selected should contains only ascii (English) characters. Dynamips (Cygwin DLL) doesn't support unicode on Windows!")) self.lineEditIOSImage.clear() self.lineEditIOSImage.setText(path) # basename doesn't work on Unix with Windows paths, so let's use this little trick image = path if not sys.platform.startswith('win') and image[1] == ":": image = image[2:] image = image.replace("\\", "/") # try to guess the platform platform = self._getIOSplatform(os.path.basename(image)) if platform == '2600': # force c2600 platform index = self.comboBoxPlatform.findText('c2600') if index != -1: self.comboBoxPlatform.setCurrentIndex(index) index = self.comboBoxChassis.findText('2621') if index != -1: self.comboBoxChassis.setCurrentIndex(index) self.spinBoxDefaultRAM.setValue(64) return if (platform != None): for platformname in PLATFORMS.keys(): # retrieve all chassis for this platform for chassis in PLATFORMS[platformname]: if platform == chassis: index = self.comboBoxPlatform.findText(platformname) if index != -1: self.comboBoxPlatform.setCurrentIndex(index) index = self.comboBoxChassis.findText(chassis) if index != -1: self.comboBoxChassis.setCurrentIndex(index) if DEFAULT_RAM.has_key(platformname): self.spinBoxDefaultRAM.setValue(DEFAULT_RAM[platformname]) break
def __clearConfiguration(self): ConfDB().clear() c = ConfDB() c.set('GNS3/version', VERSION_INTEGER) c.sync() QtGui.QMessageBox.information(globals.preferencesWindow, translate("UiConfig_PreferencesGeneral", "Configuration file"), translate("UiConfig_PreferencesGeneral", "Configuration file cleared, default settings will be applied after a restart")) globals.recordConfiguration = False globals.preferencesWindow.close()
def waitQemu(self): """ Wait Qemu until it accepts connections """ # give 15 seconds to Qemu to accept connections count = 15 progress = None connection_success = False debug("Qemu manager: connect on " + str(self.port)) for nb in range(count + 1): s = socket(AF_INET, SOCK_STREAM) s.setblocking(0) s.settimeout(300) if nb == 3: progress = QtGui.QProgressDialog( unicode(translate("QemuManager", "Connecting to Qemu on port %i ...")) % self.port, translate("QemuManager", "Abort"), 0, count, globals.GApp.mainWindow, ) progress.setMinimum(1) progress.setWindowModality(QtCore.Qt.WindowModal) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 2000) if nb > 2: progress.setValue(nb) globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 2000) if progress.wasCanceled(): progress.reset() break try: s.connect(("localhost", self.port)) except: s.close() time.sleep(1) continue connection_success = True break if connection_success: s.close() time.sleep(0.2) else: QtGui.QMessageBox.critical( globals.GApp.mainWindow, "Qemu Manager", unicode(translate("QemuManager", "Can't connect to Qemu on port %i")) % self.port, ) self.stopQemu() return False if progress: progress.setValue(count) progress.deleteLater() progress = None return True
def changeHypervisor(self): """ Called to change an hypervisor """ if len(self.__edgeList) > 0: QtGui.QMessageBox.warning(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"), translate("AbstractNode", "The device must have no connection to other devices in order to change its hypervisor")) return if self.d: currentHypervisor = self.d else: currentHypervisor = "hostname:port" (text, ok) = QtGui.QInputDialog.getText(globals.GApp.mainWindow, translate("AbstractNode", "Set hypervisor"), translate("AbstractNode", "New hypervisor:"), QtGui.QLineEdit.Normal, currentHypervisor) if ok and text: hypervisor = unicode(text) if not re.search(r"""^.*:[0-9]*$""", text, re.UNICODE): QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"), translate("AbstractNode", "Invalid format for hypervisor (hostname:port is required)")) return (host, port) = hypervisor.rsplit(':', 1) if self.dynagen.dynamips.has_key(hypervisor): debug("Use an hypervisor: " + hypervisor) dynamips_hypervisor = self.dynagen.dynamips[hypervisor] else: debug("Connection to an hypervisor: " + hypervisor) # use project workdir if globals.GApp.workspace.projectWorkdir: self.dynagen.defaults_config['workingdir'] = globals.GApp.workspace.projectWorkdir elif globals.GApp.systconf['dynamips'].workdir: self.dynagen.defaults_config['workingdir'] = globals.GApp.systconf['dynamips'].workdir dynamips_hypervisor = self.dynagen.create_dynamips_hypervisor(host, int(port)) if not dynamips_hypervisor: QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"), translate("AbstractNode", "Can't connect to the hypervisor on %s") % hypervisor) if self.dynagen.dynamips.has_key(hypervisor): del self.dynagen.dynamips[hypervisor] return self.dynagen.update_running_config() if self.d and self.dynagen.running_config[self.d].has_key(self.get_running_config_name()): config = self.dynagen.running_config[self.d][self.get_running_config_name()] self.dynagen.running_config[host + ':' + port][self.get_running_config_name()] = config del self.dynagen.running_config[self.d][self.get_running_config_name()] self.set_hypervisor(dynamips_hypervisor) self.reconfigNode(self.hostname) self.dynagen.update_running_config() QtGui.QMessageBox.information(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"), translate("AbstractNode", "New hypervisor %s has been set on device %s") % (hypervisor, self.hostname))
def slotCheckBoxEnableGuestControl(self): if self.VBoxcheckBoxEnableGuestControl.checkState() == QtCore.Qt.Checked: self.VBoxGuestControl_User.setEnabled(True) self.VBoxGuestControl_Password.setEnabled(True) self.conf.enable_GuestControl = True QtGui.QMessageBox.warning(globals.preferencesWindow, translate("Page_PreferencesVirtualBox", "VirtualBox guest"), translate("Page_PreferencesVirtualBox", "WARNING ! GuestControl is insecure. Passwords are both stored and sent in clear-text. Use at your own risk.")) else: self.VBoxGuestControl_User.setEnabled(False) self.VBoxGuestControl_Password.setEnabled(False) self.conf.enable_GuestControl = False
def __clearTable(self): if self.node.ethsw: try: self.node.ethsw.clear_mac() QtGui.QMessageBox.information( self, translate("MACTableDialog", "MAC Table"), translate("MACTableDialog", "The MAC table has been cleared")) self.__refreshTable() except lib.DynamipsError, msg: QtGui.QMessageBox.critical( self, translate("MACTableDialog", "Dynamips error"), unicode(msg)) return except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical( self, translate("MACTableDialog", "Dynamips error"), translate("MACTableDialog", "Connection lost")) return
def retranslateUi(self, MainWindow): # Call parent retranslateUi Ui_PreferencesDialog.retranslateUi(self, self) # Update titleLabel currIdx = self.stackedWidget.currentIndex() if currIdx > -1 and len(self.__prefsList) > currIdx: self.titleLabel.setText(translate('PreferencesDialog', self.__prefsList[currIdx])) # For each widget retranslate too lnum = 0 for itemName in self.__prefsList: try: widget = self.stackedWidget.widget(lnum) widget.retranslateUi(widget) self.listWidget.item(lnum).setText(translate('PreferencesDialog', self.__prefsList[lnum])) except Exception: # In case widgets don't have restranslateUi method pass lnum += 1
def startNode(self, progress=False): """ Start the node """ if not self.emudev.initrd or not self.emudev.kernel: print translate(self.basehostname, "%s: no device initrd or kernel") % self.hostname return try: if self.emudev.state == 'stopped': self.emudev.start() except: if progress: raise else: return self.startupInterfaces() self.state = 'running' globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus( self.hostname, 'running')
def __init__(self, topology, srcid, srcif, dstid, dstif): QtGui.QUndoCommand.__init__(self) source = topology.getNode(srcid) dest = topology.getNode(dstid) self.setText(translate("UndoFramework", "New link: %s (%s) -> %s (%s)") % (source.hostname, srcif, dest.hostname, dstif)) self.topology = topology self.status = None self.srcid = srcid self.srcif = srcif self.dstid = dstid self.dstif = dstif
def __init__(self, item, defaultTextColor, font, rotation): QtGui.QUndoCommand.__init__(self) self.setText(translate("UndoFramework", "New style applied for annotation")) self.type = type self.item = item self.defaultTextColor = defaultTextColor self.font = font self.rotation = rotation self.prevDefaultTextColor = item.defaultTextColor() self.prevFont = item.font() self.prevRotation = item.rotation
def slotSelectVBoxWrapperWorkdir(self): """ Get a working directory for VBoxwrapper from the file system """ vboxwrapper_default_working_directory = '.' if os.environ.has_key("TEMP"): vboxwrapper_default_working_directory = os.environ["TEMP"] elif os.environ.has_key("TMP"): vboxwrapper_default_working_directory = os.environ["TMP"] elif os.path.exists('/tmp'): vboxwrapper_default_working_directory = unicode('/tmp') fb = fileBrowser(translate('UiConfig_PreferencesVirtualBox', 'Local VirtualBox working directory'), directory=vboxwrapper_default_working_directory, parent=globals.preferencesWindow) path = fb.getDir() if path: path = os.path.normpath(path) self.lineEditVBoxwrapperWorkdir.setText(path) if not testIfWritableDir(path): QtGui.QMessageBox.critical(globals.preferencesWindow, translate("UiConfig_PreferencesVirtualBox", "Working directory"), translate("UiConfig_PreferencesVirtualBox", "Vbox working directory must be writable!"))
def __init__(self, item, pen, brush, rotation): QtGui.QUndoCommand.__init__(self) self.setText(translate("UndoFramework", "New style applied for item")) self.type = type self.item = item self.pen = pen self.brush = brush self.rotation = rotation self.prevPen = item.pen() self.prevBrush = item.brush() self.prevRotation = item.rotation
def slotSelectStartupConfigFromNvram(self): """ Load/Refresh Startup-config (from nvram) """ try: config = base64.decodestring(self.router.config_b64) if config: config = config.replace('\r', "") self.EditStartupConfig.setPlainText(config) except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("StartupConfigDialog", "Dynamips error"), unicode(msg) + \ "\nMake sure you saved your config in IOS\ni.e. #copy run start")
def do_resume(self, args): """resume {/all | device1 [device2] ...}\nresume all or a specific device(s)""" try: Dynagen_Console.do_resume(self, args) devices = args.split(' ') for node in globals.GApp.topology.nodes.values(): if (isinstance(node, IOSRouter) or isinstance(node, AnyVBoxEmuDevice)) and (node.hostname in devices or '/all' in devices): node.startupInterfaces() globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus(node.hostname, 'running') except lib.DynamipsError, msg: QtGui.QMessageBox.critical(self, translate("Console", "%s: Dynamips error") % node.hostname, unicode(msg))
def showMenuInterface(self, unavailable_interfaces=[]): """ Show a contextual menu to choose an interface on a specific node """ globals.GApp.processEvents( QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000) menu = QtGui.QMenu() self.connect(menu, QtCore.SIGNAL("hovered(QAction *)"), self._actionHovered) interfaces_list = self.getInterfaces() if len(interfaces_list) == 0: QtGui.QMessageBox.critical( globals.GApp.mainWindow, translate("AbstractNode", "Connection"), translate( "AbstractNode", "No interface available, please configure this device")) return connected_list = self.getConnectedInterfaceList() for interface in interfaces_list: if interface in unavailable_interfaces: # interface cannot be chosen by user (grayed out) action = menu.addAction(QtGui.QIcon(':/icons/led_green.svg'), interface) action.setDisabled(True) elif interface in connected_list: # already connected interface menu.addAction(QtGui.QIcon(':/icons/led_green.svg'), interface) else: # disconnected interface menu.addAction(QtGui.QIcon(':/icons/led_red.svg'), interface) # connect the menu menu.connect(menu, QtCore.SIGNAL("triggered(QAction *)"), self.slotSelectedInterface) menu.exec_(QtGui.QCursor.pos()) globals.GApp.processEvents( QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 1000)
def __init__(self): QtGui.QDialog.__init__(self) self.setupUi(self) self.connect(self.pushButton_Color, QtCore.SIGNAL('clicked()'), self.__setColor) self.connect(self.pushButton_Font, QtCore.SIGNAL('clicked()'), self.__setFont) self.connect(self.pushButton_BorderColor, QtCore.SIGNAL('clicked()'), self.__setBorderColor) # default values self.color = QtCore.Qt.transparent self.borderColor = QtCore.Qt.black self.borderWidth = 2 self.borderStyle = QtCore.Qt.SolidLine self.font = QtGui.QFont("TypeWriter", 10, QtGui.QFont.Bold) self.rotation = 0 self.comboBox_borderStyle.addItem(translate("StyleDialog", "Solid"), QtCore.QVariant(QtCore.Qt.SolidLine)) self.comboBox_borderStyle.addItem(translate("StyleDialog", "Dash"), QtCore.QVariant(QtCore.Qt.DashLine)) self.comboBox_borderStyle.addItem(translate("StyleDialog", "Dot"), QtCore.QVariant(QtCore.Qt.DotLine)) self.comboBox_borderStyle.addItem( translate("StyleDialog", "Dash Dot"), QtCore.QVariant(QtCore.Qt.DashDotLine)) self.comboBox_borderStyle.addItem( translate("StyleDialog", "Dash Dot Dot"), QtCore.QVariant(QtCore.Qt.DashDotDotLine)) self.comboBox_borderStyle.addItem( translate("StyleDialog", "No border"), QtCore.QVariant(QtCore.Qt.NoPen))
def saveConfig(self, id, config = None): """ Save the config """ node = globals.GApp.topology.getNode(id) if config: asa_config = config else: asa_config = node.duplicate_config() initrd = unicode(self.lineEditInitrd.text(), 'utf-8', errors='replace') if initrd: asa_config['initrd'] = initrd kernel = unicode(self.lineEditKernel.text(), 'utf-8', errors='replace') if kernel: asa_config['kernel'] = kernel kernel_cmdline = unicode(self.lineEditKernelCmdLine.text(), 'utf-8', errors='replace') if kernel_cmdline: asa_config['kernel_cmdline'] = kernel_cmdline asa_config['ram'] = self.spinBoxRamSize.value() nics = self.spinBoxNics.value() if nics < asa_config['nics'] and len(node.getConnectedInterfaceList()): QtGui.QMessageBox.critical(globals.nodeConfiguratorWindow, translate("Page_ASA", "ASA firewall"), translate("Page_ASA", "You must remove the connected links first in order to reduce the number of interfaces")) else: asa_config['nics'] = self.spinBoxNics.value() asa_config['netcard'] = str(self.comboBoxNIC.currentText()) options = str(self.lineEditOptions.text()) if options: asa_config['options'] = options if self.checkBoxKVM.checkState() == QtCore.Qt.Checked: asa_config['kvm'] = True else: asa_config['kvm'] = False if self.checkBoxMonitor.checkState() == QtCore.Qt.Checked: asa_config['monitor'] = True else: asa_config['monitor'] = False if self.checkBoxUserMod.checkState() == QtCore.Qt.Checked: asa_config['usermod'] = True else: asa_config['usermod'] = False return asa_config
def clean_slot(self, module): """ Removes a module module: object """ try: if module.can_be_removed(): module.remove() self.router.slot[module.slot] = None except lib.DynamipsError, msg: QtGui.QMessageBox.critical( globals.GApp.mainWindow, translate("IOSRouter", "Dynamips error"), unicode(msg))
def __setDynamipsPath(self): """ Open a file dialog for choosing the location of dynamips executable """ dynamips_default_directory = '.' if sys.platform.startswith('darwin') and os.path.exists( '../Resources/') and hasattr(sys, "frozen"): dynamips_default_directory = '../Resources/' fb = fileBrowser(translate('UiConfig_PreferencesDynamips', 'Dynamips binary'), directory=dynamips_default_directory, parent=globals.preferencesWindow) (path, selected) = fb.getFile() if path is not None and path != '': # test if we can open it if not testOpenFile(path): QtGui.QMessageBox.critical( globals.preferencesWindow, 'Dynamips path', translate("UiConfig_PreferencesDynamips", "Can't open file: %s") % path) return self.dynamips_path.clear() self.dynamips_path.setText(os.path.normpath(path)) if sys.platform.startswith('win'): try: path.encode('ascii') except: QtGui.QMessageBox.warning( globals.preferencesWindow, translate("UiConfig_PreferencesDynamips", "Dynamips path"), translate( "UiConfig_PreferencesDynamips", "The path you have selected should contains only ascii (English) characters. Dynamips (Cygwin DLL) doesn't support unicode on Windows!" ))
def slotBaseConfig(self): """ Get an base config file from the file system """ # get the path to the ios configuration path = fileBrowser(translate("IOSDialog", "Select a Base configuration file"), directory=globals.GApp.systconf['general'].ios_path, parent=self).getFile() if path != None and path[0] != '': path = os.path.normpath(path[0]) # test if we can open it if not testOpenFile(path): QtGui.QMessageBox.critical(self, translate("IOSDialog", "IOS Configuration"), translate("IOSDialog", "Can't open file: %s") % path) return if sys.platform.startswith('win'): try: path.encode('ascii') except: QtGui.QMessageBox.warning(self, translate("IOSDialog", "IOS Configuration"), translate("IOSDialog", "The path you have selected should contains only ascii (English) characters. Dynamips (Cygwin DLL) doesn't support unicode on Windows!")) self.lineEditBaseConfig.clear() self.lineEditBaseConfig.setText(path)
def loadConfig(self, path): """ Load the startup-config from a file """ try: f = open(path, 'r') config = f.read() self.EditStartupConfig.setPlainText(config) f.close() except IOError, e: QtGui.QMessageBox.critical( self, translate("StartupConfigDialog", "IO Error"), unicode(e)) return
def changeConsolePort(self): """ Called to change the console port """ if self.emu_vboxdev.state != 'stopped': QtGui.QMessageBox.critical( globals.GApp.mainWindow, translate( "AnyVBoxEmuDevice", "Cannot change the console port while the node is running") ) return AbstractNode.changeConsolePort(self)
def suspendNode(self, progress=False): """ Suspend this node """ if self.router.state == 'running': try: self.router.suspend() except lib.DynamipsErrorHandled: if progress: raise else: print translate( "IOSRouter", "Cannot suspend router %s: lost communication with server %s:%s" ) % (self.router.name, self.router.dynamips.host, str(self.router.dynamips.port)) finally: self.suspendInterfaces() self.state = self.router.state self.updateToolTips() globals.GApp.mainWindow.treeWidget_TopologySummary.changeNodeStatus( self.hostname, self.router.state)
class MACTableDialog(QtGui.QDialog, Ui_MACTableDialog): """ MACTableDialog class """ def __init__(self, node, parent=None): QtGui.QDialog.__init__(self, parent) self.setupUi(self) self.connect(self.pushButtonRefresh, QtCore.SIGNAL('clicked()'), self.__refreshTable) self.connect(self.pushButtonClear, QtCore.SIGNAL('clicked()'), self.__clearTable) self.setWindowTitle( translate('MACTableDialog', "%s MAC Address Table") % node.hostname) self.node = node self.__refreshTable() def __refreshTable(self): self.plainTextEditMACTable.clear() if self.node.ethsw: try: result = self.node.ethsw.show_mac() except lib.DynamipsError, msg: QtGui.QMessageBox.critical( self, translate("MACTableDialog", "Dynamips error"), unicode(msg)) return except (lib.DynamipsErrorHandled, socket.error): QtGui.QMessageBox.critical( self, translate("MACTableDialog", "Dynamips error"), translate("MACTableDialog", "Connection lost")) return table = "" for chunks in result: lines = chunks.strip().split('\r\n') for line in lines: if line == '100-OK': continue infos = line.split() connected_interfaces = map( int, self.node.getConnectedInterfaceList()) for port in connected_interfaces: nio = self.node.ethsw.nio(port) if nio and nio.name == infos[3]: table = table + infos[1] + ' ' + translate( "MACTableDialog", "learned from port") + ' ' + str(port) + "\n" break self.plainTextEditMACTable.setPlainText(table)
def slotRemove(self): """ Remove a symbol from the node list """ nodes = self.treeWidgetNodes.selectedItems() for node in nodes: name = unicode(node.text(0)) self.treeWidgetNodes.takeTopLevelItem(self.treeWidgetNodes.indexOfTopLevelItem(node)) symbols = list(SYMBOLS) index = 0 for symbol in SYMBOLS: if (symbol['translated'] and name == translate("nodesDock", symbol['name'])) or symbol['name'] == name: del SYMBOLS[index] index += 1
def __init__(self, node, parent=None): QtGui.QDialog.__init__(self, parent) self.setupUi(self) self.connect(self.pushButtonRefresh, QtCore.SIGNAL('clicked()'), self.__refreshTable) self.connect(self.pushButtonClear, QtCore.SIGNAL('clicked()'), self.__clearTable) self.setWindowTitle( translate('MACTableDialog', "%s MAC Address Table") % node.hostname) self.node = node self.__refreshTable()
def retranslateItem(self, item): # Translate current item data = str(item.data(0, QtCore.Qt.UserRole).toString()) if data: item.setText(0, translate('nodesDock', data)) # Recurse for child-items translation childNum = 0 childCount = item.childCount() while childNum < childCount: child_item = item.child(childNum) self.retranslateItem(child_item) childNum += 1
def slotCheckRAMrequirement(self, link): """ Check for minimum RAM requirement """ image_file = unicode(self.lineEditIOSImage.text(), 'utf-8', errors='replace') if not image_file: QtGui.QMessageBox.warning(self, translate("IOSDialog", "IOS Configuration"), translate("IOSDialog", "Image file box is empty")) return ios_image = os.path.basename(image_file) ios_image = ios_image.replace(".unzipped", "") ios_image = ios_image.replace(".extracted", "") ios_image = ios_image.replace(".image", "") url = "http://www.gns3.net/check_ios_ram_requirement.php?image=" + ios_image QtGui.QDesktopServices.openUrl(QtCore.QUrl(url))
def __initDialog(self): # Insert config pages... lnum = 0 for itemName in self.__prefsList: cls = self.__loadWidget('Preferences', itemName) widget = cls() item = QtGui.QListWidgetItem(translate('PreferencesDialog', itemName), self.listWidget) # Insert widget / item into the dialog self.listWidget.insertItem(lnum, item) self.stackedWidget.insertWidget(lnum, widget) # increment for next item / widget lnum += 1
def showConfigurationPageByName(self, itm): """ Public slot to show a named configuration page. itm: reference to the selected item (QTreeWidgetItem) """ # if the same item, don't continue if self.previousItem and self.previousItem == itm: return pageName = itm.getPageName() pageData = self.configItems[pageName] pageTitle = translate("NodeConfigurator", "Node configuration") if pageData[-1] is None and pageData[2] is not None: # the page was not loaded yet, create it page = self.__initPage(pageData) else: page = pageData[-1] if page is None: page = self.emptyPage else: if itm.origConfig == None and itm.parent(): node = globals.GApp.topology.getNode(itm.getIDs()[0]) itm.origConfig = node.get_config() if self.previousItem: self.previousPage.saveConfig(self.previousItem.getIDs()[0], self.previousItem.tmpConfig) self.previousItem = itm self.previousPage = page if self.previousItem == None: self.previousItem = itm self.previousPage = page page.loadConfig(itm.getIDs()[0], itm.tmpConfig) self.configStack.setCurrentWidget(page) if page != self.emptyPage: self.buttonBox.button( QtGui.QDialogButtonBox.Apply).setEnabled(True) self.buttonBox.button( QtGui.QDialogButtonBox.Reset).setEnabled(True) else: self.buttonBox.button( QtGui.QDialogButtonBox.Apply).setEnabled(False) self.buttonBox.button( QtGui.QDialogButtonBox.Reset).setEnabled(False)
def slotCalcIdlePC(self): """ Calculate optimal IdlePC value """ dynamips = globals.GApp.systconf['dynamips'] # Check Dynamips version if dynamips.path: if os.path.exists(dynamips.path) == False or not dynamips.detected_version: QtGui.QMessageBox.critical(self, translate("IOSDialog", "IOS Configuration"), translate("IOSDialog", "Dynamips path doesn't exist or cannot detect its version, please check Dynamips settings")) return if dynamips.detected_version and not StrictVersion(dynamips.detected_version.replace("-RC", "b").split('-', 1)[0]) >= '0.2.8b4': QtGui.QMessageBox.critical(self, translate("IOSDialog", "IOS Configuration"), translate("IOSDialog", "You will need Dynamips version 0.2.8-RC4 and above to use this utility.\nVersion detected: %s\nYou have to test the settings in Dynamips preferences to update the detected version.") % dynamips.detected_version) return if len(globals.GApp.topology.nodes): reply = QtGui.QMessageBox.question(self, translate("IOSDialog", "Message"), translate("IOSDialog", "This operation will stop all your devices and last a few minutes. Do you want to continue?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.No: return globals.GApp.syncConf() CalcIDLEPCDialog(self)
def slotRemoveLibrary(self): """ Remove a library """ path = unicode(self.lineEditLibrary.text()) if not path: return library_name = os.path.basename(path) if not QtCore.QResource.unregisterResource(path, ":/" + library_name): QtGui.QMessageBox.critical(self, translate("SymbolManagement", "Library"), translate("SymbolManager", "Can't remove library: %s") % path) return library = self.treeWidgetSymbols.findItems(library_name, QtCore.Qt.MatchFixedString)[0] self.treeWidgetSymbols.takeTopLevelItem(self.treeWidgetSymbols.indexOfTopLevelItem(library)) del globals.GApp.libraries[library_name]
def slotDeleteVC(self): """ Delete a virtual channel """ item = self.treeWidgetVCmap.currentItem() if (item != None): connected_ports = self.node.getConnectedInterfaceList() source = str(item.text(0)) vc = source.split(':') port1 = vc[0] destination = str(item.text(1)) vc = destination.split(':') port2 = vc[0] if port1 in connected_ports and port2 in connected_ports: QtGui.QMessageBox.critical( globals.nodeConfiguratorWindow, translate("Page_ATMSW", "ATM switch"), translate("Page_ATMSW", "Links connected in port %i and port %i")) % ( int(port1), int(port2)) return del self.mapping[source] self.treeWidgetVCmap.takeTopLevelItem( self.treeWidgetVCmap.indexOfTopLevelItem(item))
def __loadFinished(self, result): self.disconnect(self.webView, QtCore.SIGNAL('loadFinished(bool)'), self.__loadFinished) if result == False: QtGui.QMessageBox.information( self, translate("TipsDialog", "Tips page"), unicode( "Couldn't load the online page, trying with your default browser ..." )) if QtGui.QDesktopServices.openUrl(self.webpage) == False: print "Failed to open the URL: %s\n" % self.webpage.toString() #url = QtCore.QUrl.fromLocalFile(QtCore.QDir.current().absoluteFilePath("default_tips.html")) #QtGui.QDesktopServices.openUrl(url) self.checkBoxDontShowAgain.setChecked(True) self.close()
def mousePressEvent(self, event): """ Call when the node is clicked event: QtGui.QGraphicsSceneMouseEvent instance """ if globals.addingLinkFlag and globals.currentLinkType != globals.Enum.LinkType.Manual and event.button() == QtCore.Qt.LeftButton: connected_interfaces = self.getConnectedInterfaceList() for interface in self.config['interfaces']: if not str(interface) in connected_interfaces: self.emit(QtCore.SIGNAL("Add link"), self.id, str(interface)) return QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("DecorativeNode", "Connection"), translate("DecorativeNode", "No interface available")) # tell the scene to cancel the link addition by sending a None id and None interface self.emit(QtCore.SIGNAL("Add link"), None, None) else: AbstractNode.mousePressEvent(self, event)