Example #1
0
    def _saveIOSRouters(self):
        """
        Saves the IOS routers to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, {"routers": list(self._ios_routers.values())})
Example #2
0
    def _saveQemuVMs(self):
        """
        Saves the QEMU VMs to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, {"vms": list(self._qemu_vms.values())})
Example #3
0
    def _saveIOSRouters(self):
        """
        Saves the IOS routers to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, {"routers": list(self._ios_routers.values())})
    def _exportDebugCallback(self, result, error=False, **kwargs):
        log.info("Export debug information to %s", self._path)

        try:
            with ZipFile(self._path, 'w') as zip:
                zip.writestr("debug.txt", self._getDebugData())
                dir = LocalConfig.instance().configDirectory()
                for filename in os.listdir(dir):
                    path = os.path.join(dir, filename)
                    if os.path.isfile(path):
                        zip.write(path, filename)

                dir = os.path.join(LocalConfig.instance().configDirectory(), "debug")
                if os.path.exists(dir):
                    for filename in os.listdir(dir):
                        path = os.path.join(dir, filename)
                        if os.path.isfile(path):
                            zip.write(path, filename)

                if self._project:
                    dir = self._project.filesDir()
                    if dir:
                        for filename in os.listdir(dir):
                            path = os.path.join(dir, filename)
                            if os.path.isfile(path):
                                zip.write(path, filename)
        except OSError as e:
            QtWidgets.QMessageBox.critical(self, "Debug", "Can't export debug information: {}".format(str(e)))
        self.accept()
Example #5
0
 def _event_received(self, result, *args, **kwargs):
     # Log only relevant events
     if result["action"] not in ("ping", "compute.updated"):
         log.debug("Event received: %s", result)
     if result["action"] == "node.created":
         node = Topology.instance().getNodeFromUuid(result["event"]["node_id"])
         if node is None:
             Topology.instance().createNode(result["event"])
     elif result["action"] == "node.updated":
         node = Topology.instance().getNodeFromUuid(result["event"]["node_id"])
         if node is not None:
             node.updateNodeCallback(result["event"])
     elif result["action"] == "node.deleted":
         node = Topology.instance().getNodeFromUuid(result["event"]["node_id"])
         if node is not None:
             node.delete(skip_controller=True)
     elif result["action"] == "link.created":
         link = Topology.instance().getLinkFromUuid(result["event"]["link_id"])
         if link is None:
             Topology.instance().createLink(result["event"])
     elif result["action"] == "link.updated":
         link = Topology.instance().getLinkFromUuid(result["event"]["link_id"])
         if link is not None:
             link.updateLinkCallback(result["event"])
     elif result["action"] == "link.deleted":
         link = Topology.instance().getLinkFromUuid(result["event"]["link_id"])
         if link is not None:
             link.deleteLink(skip_controller=True)
     elif result["action"] == "drawing.created":
         drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"])
         if drawing is None:
             Topology.instance().createDrawing(result["event"])
     elif result["action"] == "drawing.updated":
         drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"])
         if drawing is not None:
             drawing.updateDrawingCallback(result["event"])
     elif result["action"] == "drawing.deleted":
         drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"])
         if drawing is not None:
             drawing.delete(skip_controller=True)
     elif result["action"] == "project.closed":
         Topology.instance().setProject(None)
     elif result["action"] == "project.updated":
         self._projectUpdatedCallback(result["event"])
     elif result["action"] == "snapshot.restored":
         Topology.instance().createLoadProject({"project_id": result["event"]["project_id"]})
     elif result["action"] == "log.error":
         log.error(result["event"]["message"])
     elif result["action"] == "log.warning":
         log.warning(result["event"]["message"])
     elif result["action"] == "log.info":
         log.info(result["event"]["message"], extra={"show": True})
     elif result["action"] == "compute.created" or result["action"] == "compute.updated":
         cm = ComputeManager.instance()
         cm.computeDataReceivedCallback(result["event"])
     elif result["action"] == "settings.updated":
         LocalConfig.instance().refreshConfigFromController()
         ApplianceManager.instance().refresh()
     elif result["action"] == "ping":
         pass
Example #6
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__,
                                                   self._settings)

        # save some settings to the local server config file
        server_settings = {
            "allocate_aux_console_ports":
            self._settings["allocate_aux_console_ports"],
            "ghost_ios_support":
            self._settings["ghost_ios_support"],
            "sparse_memory_support":
            self._settings["sparse_memory_support"],
            "mmap_support":
            self._settings["mmap_support"],
        }

        if self._settings["dynamips_path"]:
            server_settings["dynamips_path"] = os.path.normpath(
                self._settings["dynamips_path"])
        config = LocalServerConfig.instance()
        config.saveSettings(self.__class__.__name__, server_settings)
Example #7
0
    def _saveIOUDevices(self):
        """
        Saves the IOU devices to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, {"devices": list(self._iou_devices.values())})
Example #8
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        LocalConfig.instance().saveSectionSettings(self.__class__.__name__,
                                                   self._settings)
Example #9
0
    def _saveVirtualBoxVMs(self):
        """
        Saves the VirtualBox VMs to the client settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, {"vms": list(self._virtualbox_vms.values())})
Example #10
0
    def __init__(self):

        self._id = None
        self._closed = True
        self._closing = False
        self._files_dir = None
        self._images_dir = None
        self._auto_start = False
        self._auto_open = False
        self._auto_close = False

        config = LocalConfig.instance()

        graphic_settings = LocalConfig.instance().loadSectionSettings(
            "GraphicsView", GRAPHICS_VIEW_SETTINGS)
        self._scene_width = graphic_settings["scene_width"]
        self._scene_height = graphic_settings["scene_height"]
        self._zoom = graphic_settings.get("zoom", None)
        self._show_layers = graphic_settings.get("show_layers", False)
        self._snap_to_grid = graphic_settings.get("snap_to_grid", False)
        self._show_grid = graphic_settings.get("show_grid", False)
        self._show_interface_labels = graphic_settings.get(
            "show_interface_labels", False)
        self._show_interface_labels_on_new_project = config.showInterfaceLabelsOnNewProject(
        )

        self._name = "untitled"
        self._filename = None

        # Due to bug in Qt on some version we need a dedicated network manager
        self._notification_network_manager = QtNetwork.QNetworkAccessManager()
        self._notification_stream = None

        super().__init__()
Example #11
0
    def _saveQemuVMs(self):
        """
        Saves the QEMU VMs to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, {"vms": list(self._qemu_vms.values())})
Example #12
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
 def removePushButtonClickedSlot(self):
     """
     Remove the custom command from the custom list
     """
     self._settings[self._console_type].pop(self.uiCommandComboBox.currentText())
     LocalConfig.instance().saveSectionSettings("CustomConsoleCommands", self._settings)
     self._current = None
     self._refreshList()
Example #14
0
def local_config():
    from gns3.local_config import LocalConfig

    (fd, config_path) = tempfile.mkstemp()
    os.close(fd)

    LocalConfig._instance = LocalConfig(config_file=config_path)
    return LocalConfig.instance()
Example #15
0
    def _saveVirtualBoxVMs(self):
        """
        Saves the VirtualBox VMs to the client settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(
            self.__class__.__name__,
            {"vms": list(self._virtualbox_vms.values())})
Example #16
0
    def startLocalServer(self):
        """
        Starts the local server process.
        """

        self._stopping = False
        path = self.localServerPath()
        command = '"{executable}" --local'.format(executable=path)

        if LocalConfig.instance().profile():
            command += " --profile {}".format(LocalConfig.instance().profile())

        if self._settings["allow_console_from_anywhere"]:
            # allow connections to console from remote addresses
            command += " --allow"

        if logging.getLogger().isEnabledFor(logging.DEBUG):
            command += " --debug"

        settings_dir = self._config_directory
        if os.path.isdir(settings_dir):
            # save server logging info to a file in the settings directory
            logpath = os.path.join(settings_dir, "gns3_server.log")
            if os.path.isfile(logpath):
                # delete the previous log file
                try:
                    os.remove(logpath)
                except FileNotFoundError:
                    pass
                except OSError as e:
                    log.warning(
                        "could not delete server log file {}: {}".format(
                            logpath, e))
            command += ' --log="{}" --pid="{}"'.format(logpath,
                                                       self._pid_path())

        log.debug("Starting local server process with {}".format(command))
        try:
            if sys.platform.startswith("win"):
                # use the string on Windows
                self._local_server_process = subprocess.Popen(
                    command,
                    creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
                    stderr=subprocess.PIPE)
            else:
                # use arguments on other platforms
                args = shlex.split(command)
                self._local_server_process = subprocess.Popen(
                    args, stderr=subprocess.PIPE)
        except (OSError, subprocess.SubprocessError) as e:
            log.warning('Could not start local server "{}": {}'.format(
                command, e))
            return False

        log.debug("Local server process has started (PID={})".format(
            self._local_server_process.pid))
        return True
Example #17
0
    def _saveIOUDevices(self):
        """
        Saves the IOU devices to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(
            self.__class__.__name__,
            {"devices": list(self._iou_devices.values())})
Example #18
0
def test_migrate13Config(tmpdir):
    config_file = str(tmpdir / "gns3_gui.conf")
    local_config = LocalConfig(config_file=config_file)

    server_config = {
        "allow_console_from_anywhere": True,
        "auth": False,
        "auto_start": True,
        "console_end_port_range": 5000,
        "console_start_port_range": 2001,
        "host": "127.0.0.1",
        "images_path": "/home/gns3/GNS3/images",
        "password": "",
        "path": "/bin/gns3server",
        "port": 8001,
        "projects_path": "/home/gns3/GNS3/projects",
        "report_errors": False,
        "udp_end_port_range": 20000,
        "udp_start_port_range": 10000,
        "user": ""
    }

    with open(config_file, "w+") as f:
        f.write(json.dumps({
            "LocalServer": server_config,
            "RemoteServers": [
                server_config
            ],
            "GUI": {
                "hide_getting_started_dialog": True
            },
            "type": "settings",
            "version": "1.3.7"}))

    local_config._readConfig(config_file)
    local_config._migrateOldConfig()

    # The old config should not be erased in order to avoid losing data when rollback to 1.3
    assert local_config._settings["LocalServer"] == server_config
    assert local_config._settings["RemoteServers"] == [server_config]
    assert local_config._settings["Servers"]["local_server"] == server_config
    assert local_config._settings["Servers"]["remote_servers"] == [server_config]
    assert local_config._settings["MainWindow"]["hide_getting_started_dialog"]

    # When the file is migrated to 1.4 we should not try to modify it
    with open(config_file, "w+") as f:
        f.write(json.dumps({
            "LocalServer": {"host": "error"},
            "type": "settings",
            "version": "1.4.2"}))

    local_config._readConfig(config_file)
    local_config._migrateOldConfig()

    assert local_config._settings["LocalServer"]["host"] == "error"
    assert local_config._settings["Servers"]["local_server"]["host"] == "127.0.0.1"
Example #19
0
 def removePushButtonClickedSlot(self):
     """
     Remove the custom command from the custom list
     """
     self._settings[self._console_type].pop(
         self.uiCommandComboBox.currentText())
     LocalConfig.instance().saveSectionSettings("CustomConsoleCommands",
                                                self._settings)
     self._current = None
     self._refreshList()
Example #20
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
        server_settings = {"enable_hardware_acceleration": self._settings["enable_hardware_acceleration"],
                           "require_hardware_acceleration": self._settings["require_hardware_acceleration"]}
        LocalServerConfig.instance().saveSettings(self.__class__.__name__, server_settings)
 def savePushButtonClickedSlot(self):
     """
     Save a custom command to the list
     """
     name, ok = QtWidgets.QInputDialog.getText(self, "Add a command", "Command name:", QtWidgets.QLineEdit.Normal)
     command = self.uiCommandPlainTextEdit.toPlainText().strip()
     if ok and len(command) > 0:
         if command not in self._consoles.values():
             self._settings[self._console_type][name] = command
             self._current = command
             LocalConfig.instance().saveSectionSettings("CustomConsoleCommands", self._settings)
             self._refreshList()
Example #22
0
    def _saveSettings(self):
        """
        Saves the settings to the server settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        # save some settings to the local server config file
        if self._settings["vboxmanage_path"]:
            server_settings = {"vboxmanage_path": os.path.normpath(self._settings["vboxmanage_path"])}
            LocalServerConfig.instance().saveSettings(self.__class__.__name__, server_settings)
Example #23
0
def test_migrate13Config(tmpdir):
    local_config = LocalConfig()

    config_file = str(tmpdir / "gns3_gui.conf")

    server_config = {
        "allow_console_from_anywhere": True,
        "auth": False,
        "auto_start": True,
        "console_end_port_range": 5000,
        "console_start_port_range": 2001,
        "host": "127.0.0.1",
        "images_path": "/home/gns3/GNS3/images",
        "password": "",
        "path": "/bin/gns3server",
        "port": 8001,
        "projects_path": "/home/gns3/GNS3/projects",
        "report_errors": False,
        "udp_end_port_range": 20000,
        "udp_start_port_range": 10000,
        "user": ""
    }

    with open(config_file, "w+") as f:
        f.write(json.dumps({
            "LocalServer": server_config,
            "RemoteServers": [
                server_config
            ],
            "GUI": {
                "hide_getting_started_dialog": True
            },
            "type": "settings",
            "version": "1.3.7"}))

    local_config._readConfig(config_file)
    local_config._migrateOldConfig()

    # The old config should not be erased in order to avoid losing data when rollback to 1.3
    assert local_config._settings["LocalServer"] == server_config
    assert local_config._settings["RemoteServers"] == [server_config]
    assert local_config._settings["Servers"]["local_server"] == server_config
    assert local_config._settings["Servers"]["remote_servers"] == [server_config]
    assert local_config._settings["MainWindow"]["hide_getting_started_dialog"] == True

    # When the file is migrated to 1.4 we should not try to modify it
    with open(config_file, "w+") as f:
        f.write(json.dumps({
            "LocalServer": {"host": "error"},
            "type": "settings",
            "version": "1.4.2"}))

    local_config._readConfig(config_file)
    local_config._migrateOldConfig()

    assert local_config._settings["LocalServer"]["host"] == "error"
    assert local_config._settings["Servers"]["local_server"]["host"] == "127.0.0.1"
Example #24
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        if self._settings["vpcs_path"]:
            # save some settings to the server config file
            server_settings = {"vpcs_path": os.path.normpath(self._settings["vpcs_path"])}
            config = LocalServerConfig.instance()
            config.saveSettings(self.__class__.__name__, server_settings)
    def _importConfigurationFileSlot(self):
        """
        Slot to import a configuration file.
        """

        configuration_file_path = LocalConfig.instance().configFilePath()
        directory = os.path.dirname(configuration_file_path)

        path = QtGui.QFileDialog.getOpenFileName(
            self, "Import configuration file", directory,
            "Configuration file (*.ini *.conf);;All files (*.*)")
        if not path:
            return

        try:
            with open(path, encoding="utf-8") as f:
                config_file = json.load(f)
            if "type" not in config_file or config_file["type"] != "settings":
                QtGui.QMessageBox.critical(
                    self, "Import configuration file",
                    "Not a GNS3 configuration file: {}".format(path))
                return
        except OSError as e:
            QtGui.QMessageBox.critical(
                self, "Import configuration file",
                "Could not load configuration file {}: {}".format(
                    os.path.basename(path), e))
            return
        except ValueError as e:
            QtGui.QMessageBox.critical(self, "Import configuration file",
                                       "Invalid file: {}".format(e))
            return

        try:
            shutil.copyfile(path, configuration_file_path)
        except (shutil.Error, IOError) as e:
            QtGui.QMessageBox.critical(
                self, "Import configuration file",
                "Cannot import configuration file: {}".format(e))
            return

        QtGui.QMessageBox.information(
            self, "Configuration file",
            "Configuration file imported, default settings will be applied after a restart"
        )

        # TODO: implement restart
        # QtCore.QProcess.startDetached(QtGui.QApplication.arguments()[0], QtGui.QApplication.arguments())
        # QtGui.QApplication.quit()
        LocalConfig.instance().setConfigFilePath(configuration_file_path)
        self._preferences_dialog.reject()
Example #26
0
    def _saveSettings(self):
        """
        Saves the settings to the server settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        # save some settings to the local server config file
        if self._settings["vboxmanage_path"]:
            server_settings = {
                "vboxmanage_path": os.path.normpath(self._settings["vboxmanage_path"])
            }
            LocalServerConfig.instance().saveSettings(self.__class__.__name__, server_settings)
Example #27
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        server_settings = {}
        if self._settings["vpcs_path"]:
            # save some settings to the server config file
            server_settings["vpcs_path"] = os.path.normpath(self._settings["vpcs_path"])
        config = LocalServerConfig.instance()
        config.saveSettings(self.__class__.__name__, server_settings)
Example #28
0
 def savePushButtonClickedSlot(self):
     """
     Save a custom command to the list
     """
     name, ok = QtWidgets.QInputDialog.getText(self, "Add a command",
                                               "Command name:",
                                               QtWidgets.QLineEdit.Normal)
     command = self.uiCommandPlainTextEdit.toPlainText().strip()
     if ok and len(command) > 0:
         if command not in self._consoles.values():
             self._settings[self._console_type][name] = command
             self._current = command
             LocalConfig.instance().saveSectionSettings(
                 "CustomConsoleCommands", self._settings)
             self._refreshList()
Example #29
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        # save some settings to the local server config file
        if sys.platform.startswith("linux"):
            server_settings = {
                "enable_kvm": self._settings["enable_kvm"],
            }

            LocalServerConfig.instance().saveSettings(self.__class__.__name__, server_settings)
Example #30
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        server_settings = {}
        config = LocalServerConfig.instance()
        if self._settings["default_nat_interface"]:
            # save some settings to the local server config file
            server_settings["default_nat_interface"] = self._settings["default_nat_interface"]
            config.saveSettings(self.__class__.__name__, server_settings)
        else:
            config.deleteSetting(self.__class__.__name__, "default_nat_interface")
Example #31
0
    def startLocalServer(self):
        """
        Starts the local server process.
        """

        self._stopping = False
        path = self.localServerPath()
        command = '"{executable}" --local'.format(executable=path)

        if LocalConfig.instance().profile():
            command += " --profile {}".format(LocalConfig.instance().profile())

        if self._settings["allow_console_from_anywhere"]:
            # allow connections to console from remote addresses
            command += " --allow"

        if logging.getLogger().isEnabledFor(logging.DEBUG):
            command += " --debug"

        settings_dir = self._config_directory
        if os.path.isdir(settings_dir):
            # save server logging info to a file in the settings directory
            logpath = os.path.join(settings_dir, "gns3_server.log")
            if os.path.isfile(logpath):
                # delete the previous log file
                try:
                    os.remove(logpath)
                except FileNotFoundError:
                    pass
                except OSError as e:
                    log.warn("could not delete server log file {}: {}".format(logpath, e))
            command += ' --log="{}" --pid="{}"'.format(logpath, self._pid_path())

        log.info("Starting local server process with {}".format(command))
        try:
            if sys.platform.startswith("win"):
                # use the string on Windows
                self._local_server_process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP, stderr=subprocess.PIPE)
            else:
                # use arguments on other platforms
                args = shlex.split(command)
                self._local_server_process = subprocess.Popen(args, stderr=subprocess.PIPE)
        except (OSError, subprocess.SubprocessError) as e:
            log.warning('Could not start local server "{}": {}'.format(command, e))
            return False

        log.info("Local server process has started (PID={})".format(self._local_server_process.pid))
        return True
Example #32
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()
        # restore the Dynamips settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in DYNAMIPS_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(name, type=DYNAMIPS_SETTING_TYPES[name])
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__, legacy_settings)
        self._settings = local_config.loadSectionSettings(self.__class__.__name__, DYNAMIPS_SETTINGS)

        if not os.path.exists(self._settings["dynamips_path"]):
            self._settings["dynamips_path"] = self._findDynamips(self)

        # keep the config file sync
        self._saveSettings()
Example #33
0
    def _loadSettings(self):
        """
        Loads the settings from the server settings file.
        """

        local_config = LocalConfig.instance()

        # restore the VirtualBox settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in VBOX_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(
                    name, type=VBOX_SETTING_TYPES[name])
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__,
                                             legacy_settings)
        self._settings = local_config.loadSectionSettings(
            self.__class__.__name__, VBOX_SETTINGS)

        if not os.path.exists(self._settings["vboxmanage_path"]):
            self._settings["vboxmanage_path"] = self._findVBoxManage(self)

        # keep the config file sync
        self._saveSettings()
Example #34
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()

        # restore the VPCS settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in VPCS_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(name, type=VPCS_SETTING_TYPES[name])
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__, legacy_settings)
        self._settings = local_config.loadSectionSettings(self.__class__.__name__, VPCS_SETTINGS)

        if not self._settings["base_script_file"]:
            self._settings["base_script_file"] = get_default_base_config(get_resource(os.path.join("configs", "vpcs_base_config.txt")))

        if not os.path.exists(self._settings["vpcs_path"]):
            self._settings["vpcs_path"] = self._findVPCS(self)

        # keep the config file sync
        self._saveSettings()
    def __init__(self, parent=None):

        super().__init__()
        self.setupUi(self)
        self._remote_servers = {}
        self._preferences_dialog = parent

        # Display the path of the config file
        config_file_path = LocalConfig.instance().configFilePath()
        self.uiConfigurationFileLabel.setText(config_file_path)

        self.uiProjectsPathToolButton.clicked.connect(self._projectsPathSlot)
        self.uiSymbolsPathToolButton.clicked.connect(self._symbolsPathSlot)
        self.uiImagesPathToolButton.clicked.connect(self._imagesPathSlot)
        self.uiConfigsPathToolButton.clicked.connect(self._configsPathSlot)
        self.uiImportConfigurationFilePushButton.clicked.connect(self._importConfigurationFileSlot)
        self.uiExportConfigurationFilePushButton.clicked.connect(self._exportConfigurationFileSlot)
        self.uiRestoreDefaultsPushButton.clicked.connect(self._restoreDefaultsSlot)
        self.uiTelnetConsolePreconfiguredCommandPushButton.clicked.connect(self._telnetConsolePreconfiguredCommandSlot)
        self.uiSerialConsolePreconfiguredCommandPushButton.clicked.connect(self._serialConsolePreconfiguredCommandSlot)
        self.uiVNCConsolePreconfiguredCommandPushButton.clicked.connect(self._vncConsolePreconfiguredCommandSlot)
        self.uiDefaultLabelFontPushButton.clicked.connect(self._setDefaultLabelFontSlot)
        self.uiDefaultLabelColorPushButton.clicked.connect(self._setDefaultLabelColorSlot)
        self._default_label_color = QtGui.QColor(QtCore.Qt.black)
        self.uiStyleComboBox.addItems(STYLES)
Example #36
0
    def __init__(self, parent=None):

        if parent is None:
            self._main = QtWidgets.QMainWindow()
            self._main.hide()
            parent = self._main
        super().__init__(parent)
        self.setupUi(self)

        self.uiNewPushButton.clicked.connect(self._newPushButtonSlot)
        self.uiDeletePushButton.clicked.connect(self._deletePushButtonSlot)

        # Center on screen
        screen = QtWidgets.QApplication.desktop().screenGeometry()
        self.move(screen.center() - self.rect().center())

        if sys.platform.startswith("win"):
            appdata = os.path.expandvars("%APPDATA%")
            path = os.path.join(appdata, "GNS3")
        else:
            home = os.path.expanduser("~")
            path = os.path.join(home, ".config", "GNS3")
        self.profiles_path = os.path.join(path, "profiles")

        self.uiShowAtStartupCheckBox.setChecked(LocalConfig.instance().multiProfiles())
        self._refresh()
Example #37
0
    def _loadVMwareVMs(self):
        """
        Load the VMware VMs from the client settings file.
        """

        local_config = LocalConfig.instance()
        settings = local_config.settings()
        if "vms" in settings.get(self.__class__.__name__, {}):
            for vm in settings[self.__class__.__name__]["vms"]:
                name = vm.get("name")
                server = vm.get("server")
                key = "{server}:{name}".format(server=server, name=name)
                if key in self._vmware_vms or not name or not server:
                    continue
                vm_settings = VMWARE_VM_SETTINGS.copy()
                vm_settings.update(vm)
                # for backward compatibility before version 1.4
                if "symbol" not in vm_settings:
                    vm_settings["symbol"] = vm_settings.get(
                        "default_symbol", vm_settings["symbol"])
                    vm_settings["symbol"] = vm_settings[
                        "symbol"][:-11] + ".svg" if vm_settings[
                            "symbol"].endswith(
                                "normal.svg") else vm_settings["symbol"]
                self._vmware_vms[key] = vm_settings
Example #38
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()

        # restore the VPCS settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in VPCS_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(
                    name, type=VPCS_SETTING_TYPES[name])
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__,
                                             legacy_settings)
        self._settings = local_config.loadSectionSettings(
            self.__class__.__name__, VPCS_SETTINGS)

        if not self._settings["base_script_file"]:
            self._settings["base_script_file"] = get_default_base_config(
                get_resource(os.path.join("configs", "vpcs_base_config.txt")))

        if not os.path.exists(self._settings["vpcs_path"]):
            self._settings["vpcs_path"] = self._findVPCS(self)

        # keep the config file sync
        self._saveSettings()
Example #39
0
    def _loadVirtualBoxVMs(self):
        """
        Load the VirtualBox VMs from the client settings file.
        """

        self._virtualbox_vms = {}
        settings = LocalConfig.instance().settings()
        if "vms" in settings.get(self.__class__.__name__, {}):
            for vm in settings[self.__class__.__name__]["vms"]:
                vmname = vm.get("vmname")
                server = vm.get("server")
                key = "{server}:{vmname}".format(server=server, vmname=vmname)
                if key in self._virtualbox_vms or not vmname or not server:
                    continue
                vm_settings = VBOX_VM_SETTINGS.copy()
                vm_settings.update(vm)
                # For backward compatibility we use vmname
                if not vm_settings["name"]:
                    vm_settings["name"] = vmname
                # for backward compatibility before version 1.4
                if "symbol" not in vm_settings:
                    vm_settings["symbol"] = vm_settings.get(
                        "default_symbol", vm_settings["symbol"])
                    vm_settings["symbol"] = vm_settings[
                        "symbol"][:-11] + ".svg" if vm_settings[
                            "symbol"].endswith(
                                "normal.svg") else vm_settings["symbol"]
                self._virtualbox_vms[key] = vm_settings
Example #40
0
    def _loadIOUDevices(self):
        """
        Load the IOU devices from the persistent settings file.
        """

        settings = LocalConfig.instance().settings()
        if "devices" in settings.get(self.__class__.__name__, {}):
            for device in settings[self.__class__.__name__]["devices"]:
                name = device.get("name")
                server = device.get("server")
                key = "{server}:{name}".format(server=server, name=name)
                if key in self._iou_devices or not name or not server:
                    continue
                device_settings = IOU_DEVICE_SETTINGS.copy()
                device_settings.update(device)
                # for backward compatibility before version 1.4
                if "symbol" not in device_settings:
                    device_settings["symbol"] = device_settings[
                        "default_symbol"]
                    device_settings["symbol"] = device_settings[
                        "symbol"][:-11] + ".svg" if device_settings[
                            "symbol"].endswith(
                                "normal.svg") else device_settings["symbol"]
                device_settings["startup_config"] = device_settings.get(
                    "initial_config", device_settings["startup_config"])
                self._iou_devices[key] = device_settings
Example #41
0
    def _loadSettings(self):
        """
        Loads the settings from the server settings file.
        """

        local_config = LocalConfig.instance()

        # restore the VirtualBox settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in VBOX_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(name, type=VBOX_SETTING_TYPES[name])
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__, legacy_settings)
        self._settings = local_config.loadSectionSettings(self.__class__.__name__, VBOX_SETTINGS)

        if not os.path.exists(self._settings["vboxmanage_path"]):
            self._settings["vboxmanage_path"] = self._findVBoxManage(self)

        # keep the config file sync
        self._saveSettings()
Example #42
0
 def _configurationFile(self):
     if sys.platform.startswith("win"):
         filename = "gns3_gui.ini"
     else:
         filename = "gns3_gui.conf"
     directory = LocalConfig.configDirectory()
     return os.path.join(directory, filename)
Example #43
0
    def __init__(self):

        self._id = None
        self._closed = True
        self._closing = False
        self._files_dir = None
        self._images_dir = None
        self._auto_start = False
        self._auto_open = False
        self._auto_close = False

        graphic_settings = LocalConfig.instance().loadSectionSettings(self.__class__.__name__, GRAPHICS_VIEW_SETTINGS)
        self._scene_width = graphic_settings["scene_width"]
        self._scene_height = graphic_settings["scene_height"]
        self._zoom = graphic_settings.get("zoom", None)
        self._show_layers = graphic_settings.get("show_layers", False)
        self._snap_to_grid = graphic_settings.get("snap_to_grid", False)
        self._show_grid = graphic_settings.get("show_grid", False)
        self._show_interface_labels = graphic_settings.get("show_interface_labels", False)

        self._name = "untitled"
        self._filename = None

        # Due to bug in Qt on some version we need a dedicated network manager
        self._notification_network_manager = QtNetwork.QNetworkAccessManager()
        self._notification_stream = None

        super().__init__()
Example #44
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()
        self._settings = local_config.loadSectionSettings(self.__class__.__name__, BUILTIN_SETTINGS)
    def __init__(self, parent=None):

        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self._remote_servers = {}
        self._preferences_dialog = parent

        # Load the pre-configured console commands
        for name, cmd in sorted(PRECONFIGURED_TELNET_CONSOLE_COMMANDS.items()):
            self.uiTelnetConsolePreconfiguredCommandComboBox.addItem(name, cmd)
        for name, cmd in sorted(PRECONFIGURED_SERIAL_CONSOLE_COMMANDS.items()):
            self.uiSerialConsolePreconfiguredCommandComboBox.addItem(name, cmd)

        # Display the path of the config file
        config_file_path = LocalConfig.instance().configFilePath()
        self.uiConfigurationFileLabel.setText(config_file_path)

        self.uiProjectsPathToolButton.clicked.connect(self._projectsPathSlot)
        self.uiImagesPathToolButton.clicked.connect(self._imagesPathSlot)
        self.uiImportConfigurationFilePushButton.clicked.connect(
            self._importConfigurationFileSlot)
        self.uiExportConfigurationFilePushButton.clicked.connect(
            self._exportConfigurationFileSlot)
        self.uiRestoreDefaultsPushButton.clicked.connect(
            self._restoreDefaultsSlot)
        self.uiTelnetConsolePreconfiguredCommandPushButton.clicked.connect(
            self._telnetConsolePreconfiguredCommandSlot)
        self.uiSerialConsolePreconfiguredCommandPushButton.clicked.connect(
            self._serialConsolePreconfiguredCommandSlot)
        self.uiDefaultLabelFontPushButton.clicked.connect(
            self._setDefaultLabelFontSlot)
        self.uiDefaultLabelColorPushButton.clicked.connect(
            self._setDefaultLabelColorSlot)
        self._default_label_color = QtGui.QColor(QtCore.Qt.black)
        self.uiStyleComboBox.addItems(STYLES)
Example #46
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()

        # restore the Qemu settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in QEMU_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(
                    name, type=QEMU_SETTING_TYPES[name])
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__,
                                             legacy_settings)
        self._settings = local_config.loadSectionSettings(
            self.__class__.__name__, QEMU_SETTINGS)

        # keep the config file sync
        self._saveSettings()
Example #47
0
    def _saveSettings(self):
        """
        Saves the settings to the persistent settings file.
        """

        # save the settings
        LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)

        # save some settings to the local server config file
        server_settings = {
            "iourc_path": self._settings["iourc_path"],
            "iouyap_path": self._settings["iouyap_path"],
            "license_check": self._settings["license_check"]
        }
        config = LocalServerConfig.instance()
        config.saveSettings(self.__class__.__name__, server_settings)
    def __init__(self, parent=None):

        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self._remote_servers = {}
        self._preferences_dialog = parent

        # Load the pre-configured console commands
        for name, cmd in sorted(PRECONFIGURED_TELNET_CONSOLE_COMMANDS.items()):
            self.uiTelnetConsolePreconfiguredCommandComboBox.addItem(name, cmd)
        for name, cmd in sorted(PRECONFIGURED_SERIAL_CONSOLE_COMMANDS.items()):
            self.uiSerialConsolePreconfiguredCommandComboBox.addItem(name, cmd)

        # Display the path of the config file
        config_file_path = LocalConfig.instance().configFilePath()
        self.uiConfigurationFileLabel.setText(config_file_path)

        self.uiProjectsPathToolButton.clicked.connect(self._projectsPathSlot)
        self.uiImagesPathToolButton.clicked.connect(self._imagesPathSlot)
        self.uiImportConfigurationFilePushButton.clicked.connect(self._importConfigurationFileSlot)
        self.uiExportConfigurationFilePushButton.clicked.connect(self._exportConfigurationFileSlot)
        self.uiRestoreDefaultsPushButton.clicked.connect(self._restoreDefaultsSlot)
        self.uiTelnetConsolePreconfiguredCommandPushButton.clicked.connect(self._telnetConsolePreconfiguredCommandSlot)
        self.uiSerialConsolePreconfiguredCommandPushButton.clicked.connect(self._serialConsolePreconfiguredCommandSlot)
        self.uiDefaultLabelFontPushButton.clicked.connect(self._setDefaultLabelFontSlot)
        self.uiDefaultLabelColorPushButton.clicked.connect(self._setDefaultLabelColorSlot)
        self._default_label_color = QtGui.QColor(QtCore.Qt.black)
        self.uiStyleComboBox.addItems(STYLES)
Example #49
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()

        # restore the IOU settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in IOU_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(
                    name, type=IOU_SETTING_TYPES[name])
        if "iourc" in legacy_settings:
            legacy_settings["iourc_path"] = legacy_settings["iourc"]
            del legacy_settings["iourc"]
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__,
                                             legacy_settings)
        self._settings = local_config.loadSectionSettings(
            self.__class__.__name__, IOU_SETTINGS)

        if sys.platform.startswith("linux") and not os.path.exists(
                self._settings["iouyap_path"]):
            iouyap_path = shutil.which("iouyap")
            if iouyap_path:
                self._settings["iouyap_path"] = iouyap_path

        # keep the config file sync
        self._saveSettings()
Example #50
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        self._settings = LocalConfig.instance().loadSectionSettings(self.__class__.__name__, QEMU_SETTINGS)
        self._loadQemuVMs()
Example #51
0
    def _loadSettings(self):
        """
        Loads the settings from the persistent settings file.
        """

        local_config = LocalConfig.instance()

        # restore the IOU settings from QSettings (for backward compatibility)
        legacy_settings = {}
        settings = QtCore.QSettings()
        settings.beginGroup(self.__class__.__name__)
        for name in IOU_SETTINGS.keys():
            if settings.contains(name):
                legacy_settings[name] = settings.value(name, type=IOU_SETTING_TYPES[name])
        if "iourc" in legacy_settings:
            legacy_settings["iourc_path"] = legacy_settings["iourc"]
            del legacy_settings["iourc"]
        settings.remove("")
        settings.endGroup()

        if legacy_settings:
            local_config.saveSectionSettings(self.__class__.__name__, legacy_settings)
        self._settings = local_config.loadSectionSettings(self.__class__.__name__, IOU_SETTINGS)

        if sys.platform.startswith("linux") and not os.path.exists(self._settings["iouyap_path"]):
            iouyap_path = shutil.which("iouyap")
            if iouyap_path:
                self._settings["iouyap_path"] = iouyap_path

        # keep the config file sync
        self._saveSettings()
Example #52
0
    def _okButtonClickedSlot(self):
        path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Export debug file", None, "Zip file (*.zip)", "Zip file (*.zip)")

        if len(path) == 0:
            self.reject()
            return

        log.info("Export debug information to %s", path)

        try:
            with ZipFile(path, 'w') as zip:
                zip.writestr("debug.txt", self._getDebugData())
                dir = LocalConfig.configDirectory()
                for filename in os.listdir(dir):
                    path = os.path.join(dir, filename)
                    if os.path.isfile(path):
                        zip.write(path, filename)

                dir = self._project.filesDir()
                if dir:
                    for filename in os.listdir(dir):
                        path = os.path.join(dir, filename)
                        if os.path.isfile(path):
                            zip.write(path, filename)
        except OSError as e:
            QtWidgets.QMessageBox.critical(self, "Debug", "Can't export debug information: {}".format(str(e)))
        self.accept()
Example #53
0
 def _configurationFile(self):
     if sys.platform.startswith("win"):
         filename = "gns3_gui.ini"
     else:
         filename = "gns3_gui.conf"
     directory = LocalConfig.configDirectory()
     return os.path.join(directory, filename)
Example #54
0
def local_config():
    from gns3.local_config import LocalConfig

    (fd, config_path) = tempfile.mkstemp()
    os.close(fd)

    LocalConfig._instance = LocalConfig(config_file=config_path)
    return LocalConfig.instance()