incubator-hugegraph icon indicating copy to clipboard operation
incubator-hugegraph copied to clipboard

[Question] If backend is hstore, how does the hugegraph server get the hstore address before hstore create partition

Open shirleyStorage opened this issue 2 years ago • 9 comments

Problem Type (问题类型)

struct / logic (架构 / 逻辑设计问题)

Before submit

  • [X] 我已经确认现有的 Issues 与 FAQ 中没有相同 / 重复问题 (I have confirmed and searched that there are no similar problems in the historical issue and documents)

Environment (环境信息)

  • Server Version: 1.5
  • Backend: hstore
  • OS: mac
  • Data Size: less than vertices

Your Question (问题描述)

If backend uses htore. To create a new graph, hugegraph server will send batch request to hstore. After receiving it, hstore will create partition and create raft group. And the raft group elects a leader. But how does the server know to send batch requests to this hstore? Did PD select this hstore from the list of existing hStores and tell the server

Vertex/Edge example (问题点 / 边数据举例)

No response

Schema [VertexLabel, EdgeLabel, IndexLabel] (元数据结构)

No response

shirleyStorage avatar Jul 29 '24 15:07 shirleyStorage

The HugeGraph server sends batch requests to a specific hstore by determining the partition ID for each batch entry. The Placement Driver (PD) is responsible for selecting the appropriate hstore from a list of existing hstores and informing the server. This is evident from the following code snippet:

@Override
public void batch(BatchReq request, StreamObserver<FeedbackRes> observer) {
    String graph = request.getHeader().getGraph();
    List<BatchEntry> list = request.getWriteReq().getEntryList();
    PdProvider pd = getPD();
    try {
        GraphManager graphManager = pd.getGraphManager();
        Graph managerGraph = graphManager.getGraph(graph);
        if (managerGraph != null && graph.endsWith("/g")) {
            Metapb.Graph g = managerGraph.getProtoObj();
            if (g == null || g.getGraphState() == null) {
                g = pd.getPDClient().getGraphWithOutException(graph);
                managerGraph.setGraph(g);
            }
            if (g != null) {
                Metapb.GraphState graphState = g.getGraphState();
                if (graphState != null) {
                    GraphMode graphMode = graphState.getMode();
                    if (graphMode != null &&
                        graphMode.getNumber() == GraphMode.ReadOnly_VALUE) {
                        Metapb.Graph pdGraph =
                                pd.getPDClient().getGraph(graph);
                        Metapb.GraphState pdGraphState =
                                pdGraph.getGraphState();
                        if (pdGraphState != null &&
                            pdGraphState.getMode() != null &&
                            pdGraphState.getMode().getNumber() ==
                            GraphMode.ReadOnly_VALUE) {
                            throw new PDException(-1,
                                                  "the graph space size " +
                                                  "has " +
                                                  "reached the threshold");
                        }
                        managerGraph.setProtoObj(pdGraph);
                    }
                }
            }
        }
    } catch (PDException e) {
        ResStatus status = ResStatus.newBuilder()
                                    .setCode(ResCode.RES_CODE_EXCESS)
                                    .setMsg(e.getMessage())
                                    .build();
        FeedbackRes feedbackRes = FeedbackRes.newBuilder()
                                             .setStatus(status)
                                             .build();
        observer.onNext(feedbackRes);
        observer.onCompleted();
        return;
    }
    Map<Integer, List<BatchEntry>> groups = new HashMap<>();
    list.forEach((entry) -> {
        Key startKey = entry.getStartKey();
        if (startKey.getCode() == HgStoreConst.SCAN_ALL_PARTITIONS_ID) {
            List<Integer> ids =
                    storeService.getGraphLeaderPartitionIds(graph);
            ids.forEach(id -> {
                if (!groups.containsKey(id)) {
                    groups.put(id, new LinkedList<>());
                }
                groups.get(id).add(entry);
            });
        } else {
            Integer partitionId =
                    pd.getPartitionByCode(graph, startKey.getCode())
                      .getId();
            if (!groups.containsKey(partitionId)) {
                groups.put(partitionId, new LinkedList<>());
            }
            groups.get(partitionId).add(entry);
        }
    });

    BatchGrpcClosure<FeedbackRes> closure =
            new BatchGrpcClosure<>(groups.size());
    groups.forEach((partition, entries) -> {
        storeService.addRaftTask(HgStoreNodeService.BATCH_OP, graph,
                                 partition,
                                 BatchReq.newBuilder()
                                         .setHeader(request.getHeader())
                                         .setWriteReq(
                                                 BatchWriteReq.newBuilder()
                                                              .addAllEntry(
                                                                      entries))
                                         .build(),
                                 closure.newRaftClosure());
    });
    if (!graph.isEmpty()) {
        closure.waitFinish(observer, r -> closure.selectError(r),
                           appConfig.getRaft().getRpcTimeOut());
    } else {
        observer.onNext(
                FeedbackRes.newBuilder().setStatus(HgGrpc.success())
                           .build());
        observer.onCompleted();
    }
}

This code shows that the PD is queried to get the graph manager and the appropriate graph state. The PD also provides the partition ID for each batch entry, which is then used to group the entries by partition. The server then sends the batch requests to the appropriate hstore based on these partition IDs [1].

Additionally, the PDClient class in the HugeGraph project provides methods to interact with the PD, such as getPartitionByCode and getGraphWithOutException, which are used to determine the appropriate hstore for each partition. The PDClient also handles events like partition changes and store updates, ensuring that the server always has the latest information about the hstores [2].

The FakePdServiceProvider class further illustrates how the PDClient is used to manage partition and store information. It includes methods like getPartitionByID, getPartitionByCode, and event listeners to handle changes in the PD, ensuring that the server is always informed of the latest hstore configurations [3].

To continue talking to Dosu, mention @dosu.

dosubot[bot] avatar Jul 29 '24 15:07 dosubot[bot]

@dosu-bot How does PD assign a partitionID when creating a graph?

shirleyStorage avatar Jul 29 '24 15:07 shirleyStorage

The Placement Driver (PD) assigns a partition ID when creating a graph in HugeGraph by calculating the partition ID based on a hash code derived from the key. The process involves the following steps:

  1. Calculate the Hash Code: The hash code is calculated using the key.
  2. Determine Partition Size: The partition size is determined by dividing a maximum value (PartitionUtils.MAX_VALUE) by the number of partitions in the graph.
  3. Calculate Partition ID: The partition ID is calculated by dividing the hash code by the partition size.
  4. Determine Start and End Keys: The start and end keys for the partition are calculated based on the partition size and partition ID.
  5. Check and Create Partition: If the partition does not already exist, it is created and assigned a store.

Here is the relevant code snippet:

private Metapb.Partition newPartition(String graphName, long code) throws PDException {
    Metapb.Graph graph = partitionMeta.getAndCreateGraph(graphName);
    int partitionSize = PartitionUtils.MAX_VALUE / graph.getPartitionCount();
    if (PartitionUtils.MAX_VALUE % graph.getPartitionCount() != 0) {
        // There is a remainder, and the partition is inexhaustible
        partitionSize++;
    }

    int partitionId = (int) (code / partitionSize);
    long startKey = (long) partitionSize * partitionId;
    long endKey = (long) partitionSize * (partitionId + 1);

    // Check Local
    Metapb.Partition partition = partitionMeta.getPartitionById(graphName, partitionId);
    if (partition == null) {
        storeService.allocShards(null, partitionId);

        // Assign a store
        partition = Metapb.Partition.newBuilder()
                                    .setId(partitionId)
                                    .setVersion(0)
                                    .setState(Metapb.PartitionState.PState_Normal)
                                    .setStartKey(startKey)
                                    .setEndKey(endKey)
                                    .setGraphName(graphName)
                                    .build();

        log.info("Create newPartition {}", partition);
    }

    partitionMeta.updatePartition(partition);

    return partition;
}

This code ensures that each partition is uniquely identified and appropriately assigned within the graph [1][2].

To continue talking to Dosu, mention @dosu.

dosubot[bot] avatar Jul 29 '24 15:07 dosubot[bot]

@dosu-bot How does hugegraph server get partition info from PD when create a new graph?

shirleyStorage avatar Jul 29 '24 16:07 shirleyStorage

The HugeGraph server retrieves partition information from the Placement Driver (PD) when creating a new graph by using the PDClient class. Specifically, it uses the getPartitionByCode method to find the partition based on a hash code. If the partition does not exist, it creates a new partition using the newPartition method.

Here is the relevant code:

public KVPair<Metapb.Partition, Metapb.Shard> getPartitionByCode(String graphName, long code) throws PDException {
    if (code < 0 || code >= PartitionUtils.MAX_VALUE) {
        throw new PDException(Pdpb.ErrorType.NOT_FOUND_VALUE, "code error");
    }
    // Find the partition ID based on the code, and if it doesn't find, create a new partition
    KVPair<Metapb.Partition, Metapb.Shard> partShard = cache.getPartitionByCode(graphName, code);

    if (partShard == null) {
        synchronized (this) {
            if (partShard == null) {
                partShard = newPartition(graphName, code);
            }
        }
    }

    log.debug("{} Partition get code = {}, partition id  = {}, start = {}, end = {}, leader = {}",
              graphName, (code), partShard.getKey().getId(), partShard.getKey().getStartKey(), partShard.getKey().getEndKey(), partShard.getValue());

    return partShard;
}

private KVPair<Metapb.Partition, Metapb.Shard> newPartition(String graphName, long code) throws PDException {
    Metapb.Graph graph = getGraph(graphName);
    int partitionSize = PartitionUtils.MAX_VALUE / graph.getPartitionCount();
    if (PartitionUtils.MAX_VALUE % graph.getPartitionCount() != 0) {
        // There is a remainder, and the partition is inexhaustible
        partitionSize++;
    }

    int partitionId = (int) (code / partitionSize);
    long startKey = (long) partitionSize * partitionId;
    long endKey = (long) partitionSize * (partitionId + 1);

    // Check Local
    KVPair<Metapb.Partition, Metapb.Shard> partShard = cache.getPartitionById(graphName, partitionId);
    if (partShard == null) {
        storeService.allocShards(null, partitionId);
        // Assign a store
        Metapb.Partition partition = Metapb.Partition.newBuilder()
                                    .setId(partitionId)
                                    .setVersion(0)
                                    .setState(Metapb.PartitionState.PState_Normal)
                                    .setStartKey(startKey)
                                    .setEndKey(endKey)
                                    .setGraphName(graphName)
                                    .build();

        log.info("Create newPartition {}", partition);
        partShard = new KVPair<>(partition, storeService.getLeader(partition, 0));
    }

    cache.updatePartition(partShard.getKey());

    return partShard;
}

This code shows how the server calculates the partition hash code, checks if the partition exists, and creates a new partition if necessary. The PDClient class handles the communication with the PD server, including caching and updating partition information [1][2].

To continue talking to Dosu, mention @dosu.

dosubot[bot] avatar Jul 29 '24 16:07 dosubot[bot]

@dosu-bot If backend is hstore, where does the hugegraph server call newPartition?

shirleyStorage avatar Jul 29 '24 16:07 shirleyStorage

The newPartition method is called in the PartitionService class within the getPartitionByCode method. Specifically, it is invoked when a partition is not found for a given code, and a new partition needs to be created.

Here is the relevant code snippet:

public Metapb.PartitionShard getPartitionByCode(String graphName, long code) throws PDException {
    if (code < 0 || code >= PartitionUtils.MAX_VALUE) {
        throw new PDException(Pdpb.ErrorType.NOT_FOUND_VALUE, "code error");
    }
    // Find the partition ID based on the code, and if it doesn't find, create a new partition
    Metapb.Partition partition = partitionMeta.getPartitionByCode(graphName, code);

    if (partition == null) {
        synchronized (this) {
            if (partition == null) {
                partition = newPartition(graphName, code);
            }
        }
    }

    Metapb.PartitionShard partShard = Metapb.PartitionShard.newBuilder()
                                                           .setPartition(partition)
                                                           .setLeader(storeService.getLeader(
                                                                   partition, 0))
                                                           .build();
    log.debug(
            "{} Partition get code = {}, partition id  = {}, start = {}, end = {}, leader = {}",
            graphName, (code), partition.getId(), partition.getStartKey(),
            partition.getEndKey(), partShard.getLeader());

    return partShard;
}

In this snippet, newPartition is called to handle the creation of a new partition when the partition for the given code does not exist [1][2].

To continue talking to Dosu, mention @dosu.

dosubot[bot] avatar Jul 29 '24 17:07 dosubot[bot]

@shirleyStorage When creating a new graph with hstore backend, the schema store and the graph store will be initialized. The schema store stores metadata (such as PropertyKey), and the graph store stores data (such as Vertex). When the two stores open, they will initialize HstoreSessionsImpl, which will construct PDClient and HgStoreClient based on pd addresses configured in the configuration file. Subsequently, this allows communication with pd nodes and store nodes, such as retrieving partition information of a store.

VGalaxies avatar Jul 30 '24 04:07 VGalaxies

Due to the lack of activity, the current issue is marked as stale and will be closed after 20 days, any update will remove the stale label

github-actions[bot] avatar Aug 14 '24 21:08 github-actions[bot]