def get_or_create_group_id(name, user):
    group = ServerGroup.query.filter_by(user_id=user.id, name=name).first()
    if group is None:
        group = ServerGroup()
        group.name = name
        group.user_id = user.id
        print("Created server group %r for user %r" % (name, user.email))
        db.session.add(group)

        commit("Error creating server group {}".format(name), "Successfully saved.")

    return group.id
示例#2
0
文件: setup.py 项目: wilj/pgadmin4
def load_servers(args):
    """Load server groups and servers.

    Args:
        args (ArgParser): The parsed command line options
    """

    # What user?
    load_user = args.user if args.user is not None else config.DESKTOP_USER

    # And the sqlite path
    if args.sqlite_path is not None:
        config.SQLITE_PATH = args.sqlite_path

    print('----------')
    print('Loading servers with:')
    print('User:'******'SQLite pgAdmin config:', config.SQLITE_PATH)
    print('----------')

    try:
        with open(args.load_servers) as f:
            data = json.load(f)
    except json.decoder.JSONDecodeError as e:
        print("Error parsing input file %s: %s" %
              (args.load_servers, e))
        sys.exit(1)
    except Exception as e:
        print("Error reading input file %s: [%d] %s" %
              (args.load_servers, e.errno, e.strerror))
        sys.exit(1)

    f.close()

    app = create_app(config.APP_NAME + '-cli')
    with app.app_context():
        user = User.query.filter_by(email=load_user).first()

        if user is None:
            print("The specified user ID (%s) could not be found." %
                  load_user)
            sys.exit(1)

        user_id = user.id

        # Counters
        groups_added = 0
        servers_added = 0

        # Get the server groups
        groups = ServerGroup.query.filter_by(user_id=user_id)

        def print_summary():
            print("Added %d Server Group(s) and %d Server(s)." %
                  (groups_added, servers_added))

        err_msg = _validate_servers_data(data, user.has_role("Administrator"))
        if err_msg is not None:
            print(err_msg)
            print_summary()
            sys.exit(1)

        for server in data["Servers"]:
            obj = data["Servers"][server]

            # Get the group. Create if necessary
            group_id = next(
                (g.id for g in groups if g.name == obj["Group"]), -1)

            if group_id == -1:
                new_group = ServerGroup()
                new_group.name = obj["Group"]
                new_group.user_id = user_id
                db.session.add(new_group)

                try:
                    db.session.commit()
                except Exception as e:
                    print("Error creating server group '%s': %s" %
                          (new_group.name, e))
                    print_summary()
                    sys.exit(1)

                group_id = new_group.id
                groups_added = groups_added + 1
                groups = ServerGroup.query.filter_by(user_id=user_id)

            # Create the server
            new_server = Server()
            new_server.name = obj["Name"]
            new_server.servergroup_id = group_id
            new_server.user_id = user_id
            new_server.ssl_mode = obj["SSLMode"]
            new_server.maintenance_db = obj["MaintenanceDB"]

            new_server.host = obj.get("Host", None)

            new_server.hostaddr = obj.get("HostAddr", None)

            new_server.port = obj.get("Port", None)

            new_server.username = obj.get("Username", None)

            new_server.role = obj.get("Role", None)

            new_server.ssl_mode = obj["SSLMode"]

            new_server.comment = obj.get("Comment", None)

            new_server.db_res = obj.get("DBRestriction", None)

            new_server.passfile = obj.get("PassFile", None)

            new_server.sslcert = obj.get("SSLCert", None)

            new_server.sslkey = obj.get("SSLKey", None)

            new_server.sslrootcert = obj.get("SSLRootCert", None)

            new_server.sslcrl = obj.get("SSLCrl", None)

            new_server.sslcompression = obj.get("SSLCompression", None)

            new_server.bgcolor = obj.get("BGColor", None)

            new_server.fgcolor = obj.get("FGColor", None)

            new_server.service = obj.get("Service", None)

            new_server.connect_timeout = obj.get("Timeout", None)

            new_server.use_ssh_tunnel = obj.get("UseSSHTunnel", None)

            new_server.tunnel_host = obj.get("TunnelHost", None)

            new_server.tunnel_port = obj.get("TunnelPort", None)

            new_server.tunnel_username = obj.get("TunnelUsername", None)

            new_server.tunnel_authentication = \
                obj.get("TunnelAuthentication", None)

            db.session.add(new_server)

            try:
                db.session.commit()
            except Exception as e:
                print("Error creating server '%s': %s" %
                      (new_server.name, e))
                print_summary()
                sys.exit(1)

            servers_added = servers_added + 1

        print_summary()
示例#3
0
def load_database_servers(input_file, selected_servers,
                          load_user=current_user, from_setup=False):
    """Load server groups and servers.
    """
    user = _does_user_exist(load_user, from_setup)
    if user is None:
        return False, USER_NOT_FOUND % load_user

    # retrieve storage directory path
    storage_manager_path = None
    if not from_setup:
        storage_manager_path = get_storage_directory(user)

    # generate full path of file
    file_path = unquote(input_file)
    if storage_manager_path:
        # generate full path of file
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    try:
        with open(file_path) as f:
            data = json.load(f)
    except json.decoder.JSONDecodeError as e:
        return _handle_error(gettext("Error parsing input file %s: %s" %
                             (file_path, e)), from_setup)
    except Exception as e:
        return _handle_error(gettext("Error reading input file %s: [%d] %s" %
                             (file_path, e.errno, e.strerror)), from_setup)

    f.close()

    user_id = user.id
    # Counters
    groups_added = 0
    servers_added = 0

    # Get the server groups
    groups = ServerGroup.query.filter_by(user_id=user_id)

    # Validate server data
    error_msg = validate_json_data(data, user.has_role("Administrator"))
    if error_msg is not None and from_setup:
        print(ADD_SERVERS_MSG % (groups_added, servers_added))
        return _handle_error(error_msg, from_setup)

    for server in data["Servers"]:
        if selected_servers is None or str(server) in selected_servers:
            obj = data["Servers"][server]

            # Get the group. Create if necessary
            group_id = next(
                (g.id for g in groups if g.name == obj["Group"]), -1)

            if group_id == -1:
                new_group = ServerGroup()
                new_group.name = obj["Group"]
                new_group.user_id = user_id
                db.session.add(new_group)

                try:
                    db.session.commit()
                except Exception as e:
                    if from_setup:
                        print(ADD_SERVERS_MSG % (groups_added, servers_added))
                    return _handle_error(
                        gettext("Error creating server group '%s': %s" %
                                (new_group.name, e)), from_setup)

                group_id = new_group.id
                groups_added = groups_added + 1
                groups = ServerGroup.query.filter_by(user_id=user_id)

            # Create the server
            new_server = Server()
            new_server.name = obj["Name"]
            new_server.servergroup_id = group_id
            new_server.user_id = user_id
            new_server.ssl_mode = obj["SSLMode"]
            new_server.maintenance_db = obj["MaintenanceDB"]

            new_server.host = obj.get("Host", None)

            new_server.hostaddr = obj.get("HostAddr", None)

            new_server.port = obj.get("Port", None)

            new_server.username = obj.get("Username", None)

            new_server.role = obj.get("Role", None)

            new_server.ssl_mode = obj["SSLMode"]

            new_server.comment = obj.get("Comment", None)

            new_server.db_res = obj.get("DBRestriction", None)

            new_server.passfile = obj.get("PassFile", None)

            new_server.sslcert = obj.get("SSLCert", None)

            new_server.sslkey = obj.get("SSLKey", None)

            new_server.sslrootcert = obj.get("SSLRootCert", None)

            new_server.sslcrl = obj.get("SSLCrl", None)

            new_server.sslcompression = obj.get("SSLCompression", None)

            new_server.bgcolor = obj.get("BGColor", None)

            new_server.fgcolor = obj.get("FGColor", None)

            new_server.service = obj.get("Service", None)

            new_server.connect_timeout = obj.get("Timeout", None)

            new_server.use_ssh_tunnel = obj.get("UseSSHTunnel", None)

            new_server.tunnel_host = obj.get("TunnelHost", None)

            new_server.tunnel_port = obj.get("TunnelPort", None)

            new_server.tunnel_username = obj.get("TunnelUsername", None)

            new_server.tunnel_authentication = \
                obj.get("TunnelAuthentication", None)

            new_server.shared = \
                obj.get("Shared", None)

            db.session.add(new_server)

            try:
                db.session.commit()
            except Exception as e:
                if from_setup:
                    print(ADD_SERVERS_MSG % (groups_added, servers_added))
                return _handle_error(gettext("Error creating server '%s': %s" %
                                             (new_server.name, e)), from_setup)

            servers_added = servers_added + 1

    msg = ADD_SERVERS_MSG % (groups_added, servers_added)
    print(msg)

    return True, msg
示例#4
0
def load_servers(args):
    """Load server groups and servers.

    Args:
        args (ArgParser): The parsed command line options
    """
    try:
        with open(args.load_servers) as f:
            data = json.load(f)
    except json.decoder.JSONDecodeError as e:
        print("Error parsing input file %s: %s" % (args.load_servers, e))
        sys.exit(1)
    except Exception as e:
        print("Error reading input file %s: [%d] %s" %
              (args.load_servers, e.errno, e.strerror))
        sys.exit(1)

    f.close()

    app = create_app()
    with app.app_context():

        # What user?
        if args.user is not None:
            dump_user = args.user
        else:
            dump_user = config.DESKTOP_USER

        user = User.query.filter_by(email=dump_user).first()

        if user is None:
            print("The specified user ID (%s) could not be found." % dump_user)
            sys.exit(1)

        user_id = user.id

        # Counters
        groups_added = 0
        servers_added = 0

        # Get the server group
        groups = ServerGroup.query.all()

        def print_summary():
            print("Added %d Server Group(s) and %d Server(s)." %
                  (groups_added, servers_added))

        # Loop through the servers...
        if "Servers" not in data:
            print("'Servers' attribute not found in file '%s'" %
                  args.load_servers)
            print_summary()
            sys.exit(1)

        for server in data["Servers"]:
            obj = data["Servers"][server]

            def check_attrib(attrib):
                if attrib not in obj:
                    print("'%s' attribute not found for server '%s'" %
                          (attrib, server))
                    print_summary()
                    sys.exit(1)

            check_attrib("Name")
            check_attrib("Group")
            check_attrib("Port")
            check_attrib("Username")
            check_attrib("SSLMode")
            check_attrib("MaintenanceDB")

            if "Host" not in obj and \
                "HostAddr" not in obj and \
                    "Service" not in obj:
                print("'Host', 'HostAddr' or 'Service' attribute not found "
                      "for server '%s'" % server)
                print_summary()
                sys.exit(1)

            # Get the group. Create if necessary
            group_id = -1
            for g in groups:
                if g.name == obj["Group"]:
                    group_id = g.id
                    break

            if group_id == -1:
                new_group = ServerGroup()
                new_group.name = obj["Group"]
                new_group.user_id = user_id
                db.session.add(new_group)

                try:
                    db.session.commit()
                except Exception as e:
                    print("Error creating server group '%s': %s" %
                          (new_group.name, e))
                    print_summary()
                    sys.exit(1)

                group_id = new_group.id
                groups_added = groups_added + 1
                groups = ServerGroup.query.all()

            # Create the server
            new_server = Server()
            new_server.name = obj["Name"]
            new_server.servergroup_id = group_id
            new_server.user_id = user_id

            new_server.host = obj["Host"]

            if "HostAddr" in obj:
                new_server.hostaddr = obj["HostAddr"]

            new_server.port = obj["Port"]
            new_server.maintenance_db = obj["MaintenanceDB"]
            new_server.username = obj["Username"]

            if "Role" in obj:
                new_server.role = obj["Role"]

            new_server.ssl_mode = obj["SSLMode"]

            if "Comment" in obj:
                new_server.comment = obj["Comment"]

            if "DBRestriction" in obj:
                new_server.db_res = obj["DBRestriction"]

            if "PassFile" in obj:
                new_server.passfile = obj["PassFile"]

            if "SSLCert" in obj:
                new_server.sslcert = obj["SSLCert"]

            if "SSLKey" in obj:
                new_server.sslkey = obj["SSLKey"]

            if "SSLRootCert" in obj:
                new_server.sslrootcert = obj["SSLRootCert"]

            if "SSLCrl" in obj:
                new_server.sslcrl = obj["SSLCrl"]

            if "SSLCompression" in obj:
                new_server.sslcompression = obj["SSLCompression"]

            if "BGColor" in obj:
                new_server.bgcolor = obj["BGColor"]

            if "FGColor" in obj:
                new_server.fgcolor = obj["FGColor"]

            if "Service" in obj:
                new_server.service = obj["Service"]

            if "Timeout" in obj:
                new_server.connect_timeout = obj["Timeout"]

            if "UseSSHTunnel" in obj:
                new_server.use_ssh_tunnel = obj["UseSSHTunnel"]

            if "TunnelHost" in obj:
                new_server.tunnel_host = obj["TunnelHost"]

            if "TunnelPort" in obj:
                new_server.tunnel_port = obj["TunnelPort"]

            if "TunnelUsername" in obj:
                new_server.tunnel_username = obj["TunnelUsername"]

            if "TunnelAuthentication" in obj:
                new_server.tunnel_authentication = obj["TunnelAuthentication"]

            db.session.add(new_server)

            try:
                db.session.commit()
            except Exception as e:
                print("Error creating server '%s': %s" % (new_server.name, e))
                print_summary()
                sys.exit(1)

            servers_added = servers_added + 1

        print_summary()