예제 #1
0
파일: main.py 프로젝트: madkrell/gns3-gui
def main():
    """
    Entry point for GNS3 GUI.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument('--version', help="show the version", action='version', version=__version__)
    parser.parse_args()
    exception_file_path = "exception.log"

    def exceptionHook(exception, value, tb):

        if exception == KeyboardInterrupt:
            sys.exit(0)

        lines = traceback.format_exception(exception, value, tb)
        print("****** Exception detected, traceback information saved in {} ******".format(exception_file_path))
        print("\nPLEASE REPORT ON http://forum.gns3.net/development-f14.html OR http://github.com/GNS3/gns3-gui/issues\n")
        print("".join(lines))
        try:
            curdate = time.strftime("%d %b %Y %H:%M:%S")
            logfile = open(exception_file_path, "a")
            logfile.write("=== GNS3 {} traceback on {} ===\n".format(__version__, curdate))
            logfile.write("".join(lines))
            logfile.close()
        except OSError as e:
            print("Could not save traceback to {}: {}".format(exception_file_path, e))

        if not sys.stdout.isatty():
            # if stdout is not a tty (redirected to the console view),
            # then print the exception on stderr too.
            print("".join(lines), file=sys.stderr)

    # catch exceptions to write them in a file
    sys.excepthook = exceptionHook

    current_year = datetime.date.today().year
    print("GNS3 GUI version {}".format(__version__))
    print("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year))

    # we only support Python 2 version >= 2.7 and Python 3 version >= 3.3
    if sys.version_info < (2, 7):
        raise RuntimeError("Python 2.7 or higher is required")
    elif sys.version_info[0] == 3 and sys.version_info < (3, 3):
        raise RuntimeError("Python 3.3 or higher is required")

    version = lambda version_string: [int(i) for i in version_string.split('.')]

    if version(QtCore.QT_VERSION_STR) < version("4.6"):
        raise RuntimeError("Requirement is Qt version 4.6 or higher, got version {}".format(QtCore.QT_VERSION_STR))

    # 4.8.3 because of QSettings (http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html)
    if DEFAULT_BINDING == "PyQt" and version(QtCore.BINDING_VERSION_STR) < version("4.8.3"):
        raise RuntimeError("Requirement is PyQt version 4.8.3 or higher, got version {}".format(QtCore.BINDING_VERSION_STR))

    if DEFAULT_BINDING == "PySide" and version(QtCore.BINDING_VERSION_STR) < version("1.0"):
        raise RuntimeError("Requirement is PySide version 1.0 or higher, got version {}".format(QtCore.BINDING_VERSION_STR))

    try:
        # if tornado is present then enable pretty logging.
        import tornado.log
        tornado.log.enable_pretty_logging()
    except ImportError:
        pass

    # check for the correct locale
    # (UNIX/Linux only)
    locale_check()

    try:
        os.getcwd()
    except FileNotFoundError:
        log.critical("the current working directory doesn't exist")
        return

    # always use the INI format on Windows and OSX (because we don't like the registry and plist files)
    if sys.platform.startswith('win') or sys.platform.startswith('darwin'):
        QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)

    if sys.platform.startswith('win'):
        try:
            import win32console
            import win32con
            import win32gui
        except ImportError:
            raise RuntimeError("Python for Windows extensions must be installed.")

        try:
            win32console.AllocConsole()
            #FIXME: do not hide the console for alpha releases to help with debugging
            #console_window = win32console.GetConsoleWindow()
            #win32gui.ShowWindow(console_window, win32con.SW_HIDE)
        except win32console.error as e:
            print("warning: could not allocate console: {}".format(e))

    exit_code = MainWindow.exit_code_reboot
    while exit_code == MainWindow.exit_code_reboot:

        exit_code = 0
        app = QtGui.QApplication(sys.argv)

        # this info is necessary for QSettings
        app.setOrganizationName("GNS3")
        app.setOrganizationDomain("gns3.net")
        app.setApplicationName("GNS3")
        app.setApplicationVersion(__version__)

        # save client logging info to a file
        logfile = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), "GNS3_client.log")
        try:
            logger = logging.getLogger("gns3")
            try:
                os.makedirs(os.path.dirname(QtCore.QSettings().fileName()))
            except FileExistsError:
                pass
            handler = logging.FileHandler(logfile, "w")
            handler.setLevel(logging.INFO)
            formatter = logging.Formatter("[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s",
                                          datefmt="%y%m%d %H:%M:%S")
            handler.setFormatter(formatter)
            logger.addHandler(handler)
        except OSError as e:
            log.warn("could not log to {}: {}".format(logfile, e))

        # update the exception file path to have it in the same directory as the settings file.
        exception_file_path = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), exception_file_path)

        mainwindow = MainWindow.instance()
        mainwindow.show()
        exit_code = app.exec_()
        delattr(MainWindow, "_instance")
        app.deleteLater()

    sys.exit(exit_code)
예제 #2
0
def main():
    """
    Entry point for GNS3 GUI.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("project",
                        help="load a GNS3 project (.gns3)",
                        metavar="path",
                        nargs="?")
    parser.add_argument("--version",
                        help="show the version",
                        action="version",
                        version=__version__)
    parser.add_argument("--debug",
                        help="print out debug messages",
                        action="store_true",
                        default=False)
    options = parser.parse_args()
    exception_file_path = "exceptions.log"

    if options.project and hasattr(sys, "frozen"):
        os.chdir(os.path.dirname(os.path.abspath(sys.executable)))

    def exceptionHook(exception, value, tb):

        if exception == KeyboardInterrupt:
            sys.exit(0)

        lines = traceback.format_exception(exception, value, tb)
        print(
            "****** Exception detected, traceback information saved in {} ******"
            .format(exception_file_path))
        print(
            "\nPLEASE REPORT ON https://community.gns3.com/community/support/bug\n"
        )
        print("".join(lines))
        try:
            curdate = time.strftime("%d %b %Y %H:%M:%S")
            logfile = open(exception_file_path, "a")
            logfile.write("=== GNS3 {} traceback on {} ===\n".format(
                __version__, curdate))
            logfile.write("".join(lines))
            logfile.close()
        except OSError as e:
            print("Could not save traceback to {}: {}".format(
                os.path.normpath(exception_file_path), e))

        if not sys.stdout.isatty():
            # if stdout is not a tty (redirected to the console view),
            # then print the exception on stderr too.
            print("".join(lines), file=sys.stderr)
        CrashReport.instance().captureException(exception, value, tb)

    # catch exceptions to write them in a file
    sys.excepthook = exceptionHook

    current_year = datetime.date.today().year
    print("GNS3 GUI version {}".format(__version__))
    print("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year))

    # we only support Python 2 version >= 2.7 and Python 3 version >= 3.3
    if sys.version_info < (2, 7):
        raise RuntimeError("Python 2.7 or higher is required")
    elif sys.version_info[0] == 3 and sys.version_info < (3, 3):
        raise RuntimeError("Python 3.3 or higher is required")

    def version(version_string):
        return [int(i) for i in version_string.split('.')]

    if version(QtCore.QT_VERSION_STR) < version("4.6"):
        raise RuntimeError(
            "Requirement is Qt version 4.6 or higher, got version {}".format(
                QtCore.QT_VERSION_STR))

    # 4.8.3 because of QSettings (http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html)
    if DEFAULT_BINDING == "PyQt" and version(
            QtCore.BINDING_VERSION_STR) < version("4.8.3"):
        raise RuntimeError(
            "Requirement is PyQt version 4.8.3 or higher, got version {}".
            format(QtCore.BINDING_VERSION_STR))

    if DEFAULT_BINDING == "PySide" and version(
            QtCore.BINDING_VERSION_STR) < version("1.0"):
        raise RuntimeError(
            "Requirement is PySide version 1.0 or higher, got version {}".
            format(QtCore.BINDING_VERSION_STR))

    # check for the correct locale
    # (UNIX/Linux only)
    locale_check()

    try:
        os.getcwd()
    except FileNotFoundError:
        log.critical("the current working directory doesn't exist")
        return

    # always use the INI format on Windows and OSX (because we don't like the registry and plist files)
    if sys.platform.startswith('win') or sys.platform.startswith('darwin'):
        QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)

    if sys.platform.startswith('win') and hasattr(sys, "frozen"):
        try:
            import win32console
            import win32con
            import win32gui
        except ImportError:
            raise RuntimeError(
                "Python for Windows extensions must be installed.")

        if not options.debug:
            try:
                # hide the console
                console_window = win32console.GetConsoleWindow()
                win32gui.ShowWindow(console_window, win32con.SW_HIDE)
            except win32console.error as e:
                print("warning: could not allocate console: {}".format(e))

    app = QtGui.QApplication(sys.argv)

    # this info is necessary for QSettings
    app.setOrganizationName("GNS3")
    app.setOrganizationDomain("gns3.net")
    app.setApplicationName("GNS3")
    app.setApplicationVersion(__version__)

    formatter = logging.Formatter(
        "[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s",
        datefmt="%y%m%d %H:%M:%S")

    # on debug enable logging to stdout
    if options.debug:
        root_logger = init_logger(logging.DEBUG)
    else:
        root_logger = init_logger(logging.INFO)

    # save client logging info to a file
    logfile = os.path.join(os.path.dirname(QtCore.QSettings().fileName()),
                           "gns3_gui.log")
    try:
        try:
            os.makedirs(os.path.dirname(QtCore.QSettings().fileName()))
        except FileExistsError:
            pass
        handler = logging.FileHandler(logfile, "w")
        root_logger.addHandler(handler)
    except OSError as e:
        log.warn("could not log to {}: {}".format(logfile, e))

    log.info('Log level: {}'.format(
        logging.getLevelName(log.getEffectiveLevel())))

    # update the exception file path to have it in the same directory as the settings file.
    exception_file_path = os.path.join(
        os.path.dirname(QtCore.QSettings().fileName()), exception_file_path)

    mainwindow = MainWindow(options.project)
    mainwindow.show()
    exit_code = app.exec_()
    delattr(MainWindow, "_instance")
    app.deleteLater()

    sys.exit(exit_code)