Completes a heartbeat by replacing the current heartbeatFuture with the nextHeartbeatFuture, updating the
current heartbeatTime, and starting a new {@link AppendRequest} to all active members.
323746
private void completeHeartbeat() {
    heartbeatFailures = 0;
    heartbeatFuture = nextHeartbeatFuture;
    nextHeartbeatFuture = null;
    updateGlobalIndex();
    if (heartbeatFuture != null) {
      heartbeatTime = System.currentTimeMillis();
      for (MemberState member : context.getClusterState().getRemoteMemberStates()) {
        appendEntries(member);
      }
    }
  }
712356
void setComplete() {
    this.complete = true;
    try {
      // If we haven't gotten any results back, make sure to create an
      // empty one
      if (this.states.size() == 0) {
        this.states.put(new WorldState());
      }
      // Special WorldState to indicate that the request has completed and
      // interrupt
      // any blocking threads
      else {
        this.states.put(RESPONSE_COMPLETE);
      }
    } catch (InterruptedException e) {
      log.error("Interrupted trying to indicate a completed condition.", e);
    }
  }
635952
public void finishAppending()
  {
    checkStateTransition(this.state, SegmentState.APPENDING, SegmentState.APPEND_FINISHED);
    this.state = SegmentState.APPEND_FINISHED;
  }
942975
protected AppendResponse handleAppend(AppendRequest request) {
    // If the request term is less than the current term then immediately
    // reply false and return our current term. The leader will receive
    // the updated term and step down.
    if (request.term() < context.getTerm()) {
      LOGGER.debug("{} - Rejected {}: request term is less than the current term ({})", context.getCluster().member().address(), request, context.getTerm());
      return AppendResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withSucceeded(false)
        .withLogIndex(context.getLog().lastIndex())
        .build();
    } else {
      return checkGlobalIndex(request);
    }
  }
1319301
public CompletableFuture<Void> commitAsync() {
        if (this.messagingFactory == null) {
            CompletableFuture<Void> exceptionCompletion = new CompletableFuture<>();
            exceptionCompletion.completeExceptionally(new ServiceBusException(false, "MessagingFactory should not be null"));
            return exceptionCompletion;
        }

        return this.messagingFactory.endTransactionAsync(this, true);
    }
1363867
private CompletionStage<Void> emitMembershipUpdateEvent() {
        final IRI membershipResource = parent.getMembershipResource().map(MutatingLdpHandler::removeHashFragment)
            .orElse(null);
        if (membershipResource != null) {
            return allOf(getServices().getResourceService().touch(membershipResource).toCompletableFuture(),
                getServices().getResourceService().get(membershipResource).thenAccept(res -> {
                    if (res.getIdentifier() != null) {
                        getServices().getEventService().emit(new SimpleEvent(getUrl(res.getIdentifier()),
                                    getSession().getAgent(), asList(PROV.Activity, AS.Update),
                                    asList(res.getInteractionModel())));
                    }
                }).toCompletableFuture());
        }
        return completedFuture(null);
    }
334922
@Override
    public void append(Append append) {
        log.trace("Processing append received from client {}", append);
        UUID id = append.getWriterId();
        synchronized (lock) {
            Long lastEventNumber = latestEventNumbers.get(Pair.of(append.getSegment(), id));
            Preconditions.checkState(lastEventNumber != null, "Data from unexpected connection: %s.", id);
            Preconditions.checkState(append.getEventNumber() >= lastEventNumber, "Event was already appended.");
            waitingAppends.put(id, append);
        }
        pauseOrResumeReading();
        performNextWrite();
    }
1080113
protected void sendAppendRequest(RaftMemberContext member, AppendRequest request) {
    // If this is a heartbeat message and a heartbeat is already in progress, skip the request.
    if (request.entries().isEmpty() && !member.canHeartbeat()) {
      return;
    }

    // Start the append to the member.
    member.startAppend();

    long timestamp = System.currentTimeMillis();

    log.trace("Sending {} to {}", request, member.getMember().memberId());
    raft.getProtocol().append(member.getMember().memberId(), request).whenCompleteAsync((response, error) -> {
      // Complete the append to the member.
      if (!request.entries().isEmpty()) {
        member.completeAppend(System.currentTimeMillis() - timestamp);
      } else {
        member.completeAppend();
      }

      if (open) {
        if (error == null) {
          log.trace("Received {} from {}", response, member.getMember().memberId());
          handleAppendResponse(member, request, response, timestamp);
        } else {
          handleAppendResponseFailure(member, request, error);
        }
      }
    }, raft.getThreadContext());

    if (!request.entries().isEmpty() && hasMoreEntries(member)) {
      appendEntries(member);
    }
  }
778147
public Map<String, OperationResult<String>> sendHeartBeat(Map<String, ServiceInstanceHeartbeat> heartbeatMap){
        String body = _serialize(heartbeatMap);
        HttpResponse result = invoker.invoke("/service/heartbeat", body,
                HttpMethod.PUT);

        if (result.getHttpCode() != HTTP_OK) {
           throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
                    "HTTP Code is not OK, code=%s", result.getHttpCode());
        }

        Map<String, OperationResult<String>> operateResult = _deserialize(
                result.getRetBody(), new TypeReference<Map<String, OperationResult<String>>>(){});
        return operateResult;

    }
879528
private CompletableFuture<Void> sendHeartbeat(GossipMember member) {
    return bootstrapService.getMessagingService().sendAndReceive(member.address(), HEARTBEAT_MESSAGE, SERIALIZER.encode(localMember))
        .whenCompleteAsync((response, error) -> {
          if (error == null) {
            Collection<GossipMember> remoteMembers = SERIALIZER.decode(response);
            for (GossipMember remoteMember : remoteMembers) {
              if (!remoteMember.id().equals(localMember.id())) {
                updateMember(remoteMember, remoteMember.id().equals(member.id()));
              }
            }
          } else {
            LOGGER.debug("{} - Sending heartbeat to {} failed", localMember.id(), member, error);
            if (member.isReachable()) {
              member.setReachable(false);
              post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, member));
            }

            PhiAccrualFailureDetector failureDetector = failureDetectors.computeIfAbsent(member.id(), n -> new PhiAccrualFailureDetector());
            double phi = failureDetector.phi();
            if (phi >= config.getPhiFailureThreshold()
                || (phi == 0.0 && System.currentTimeMillis() - failureDetector.lastUpdated() > config.getFailureTimeout().toMillis())) {
              if (members.remove(member.id()) != null) {
                failureDetectors.remove(member.id());
                post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, member));
              }
            }
          }
        }, heartbeatScheduler).exceptionally(e -> null)
        .thenApply(v -> null);
  }
369432
@Path("{snapshotId}/complete")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response complete(@PathParam("snapshotId") String snapshotId,
                             CompleteSnapshotBridgeParameters params) {
        try {
            Snapshot snapshot = this.snapshotRepo.findByName(snapshotId);

            // parse alternate IDs if provided
            List<String> alternateIds = params.getAlternateIds();
            String altIds = "[]";
            if (alternateIds != null && !alternateIds.isEmpty()) {
                // add alternate IDs to snapshot
                snapshot = this.snapshotManager.addAlternateSnapshotIds(snapshot,
                                                                        alternateIds);
                // build alternate IDs for history
                StringBuilder history = new StringBuilder();
                history.append("[");
                boolean first = true;
                for (String id : alternateIds) {
                    if (!first) {
                        history.append(",");
                    }
                    history.append("'" + id + "'");
                    first = false;
                }
                history.append("]");
                altIds = history.toString();
            }

            // Add history event
            String history =
                "[{'" + SNAPSHOT_ACTION_TITLE + "':'" + SNAPSHOT_ACTION_COMPLETED + "'}," +
                "{'" + SNAPSHOT_ID_TITLE + "':'" + snapshotId + "'}," +
                "{'" + SNAPSHOT_ALT_IDS_TITLE + "':" + altIds + "}]";
            snapshotManager.updateHistory(snapshot, history);

            snapshot = this.snapshotManager.transferToStorageComplete(snapshotId);

            log.info("successfully processed snapshot complete notification: {}", snapshot);

            return Response.ok(null)
                           .entity(new CompleteSnapshotBridgeResult(snapshot.getStatus(),
                                                                    snapshot.getStatusText()))
                           .build();
        } catch (AlternateIdAlreadyExistsException ex) {
            log.warn(ex.getMessage());
            return Response.status(HttpStatus.SC_BAD_REQUEST)
                           .entity(new ResponseDetails(ex.getMessage()))
                           .build();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return Response.serverError()
                           .entity(new ResponseDetails(ex.getMessage()))
                           .build();
        }
    }
801174
public void doHeartbeat() throws IOException {
        int curTime = TimeUtils.current_time_secs();
        WorkerHeartbeat hb = new WorkerHeartbeat(curTime, topologyId, taskIds, port);

        LOG.debug("Doing heartbeat:" + workerId + ",port:" + port + ",hb" + hb.toString());
        LocalState state = getWorkerState();
        state.put(Common.LS_WORKER_HEARTBEAT, hb);
    }
918539
void updateRack(HeartbeatImpl heartbeat,
                  UpdateRackHeartbeat updateRack)
  {
    for (UpdateServerHeartbeat serverUpdate : updateRack.getServers()) {
      if (serverUpdate == null) {
        continue;
      }
 
      update(serverUpdate);
      // updateTargetServers();
 
      ServerHeartbeat peerServer = findServer(serverUpdate.getAddress(),
                                              serverUpdate.getPort());
 
      if (peerServer.isSelf()) {
        continue;
      }
      
      heartbeat.updateServer(peerServer, serverUpdate);
      /*
      String externalId = serverUpdate.getExternalId();

      heartbeat.updateExternal(peerServer, externalId);

      if (peerServer.onHeartbeatUpdate(serverUpdate)) {
        if (peerServer.isUp()) {
          onServerStart(peerServer);
        }
        else {
          onServerStop(peerServer);
        }
      }
      */
    }

    update();
  }
167320
protected void handleAppendResponseFailure(MemberState member, AppendRequest request, Throwable error) {
    // Trigger commit futures if necessary.
    updateHeartbeatTime(member, error);

    super.handleAppendResponseFailure(member, request, error);
  }
523904
protected AppendResponse appendEntries(AppendRequest request) {
    // Get the last entry index or default to the request log index.
    long lastEntryIndex = request.logIndex();
    if (!request.entries().isEmpty()) {
      lastEntryIndex = request.entries().get(request.entries().size() - 1).getIndex();
    }

    // Ensure the commitIndex is not increased beyond the index of the last entry in the request.
    long commitIndex = Math.max(context.getCommitIndex(), Math.min(request.commitIndex(), lastEntryIndex));

    // Append entries to the log starting at the last log index.
    for (Entry entry : request.entries()) {
      // If the entry index is greater than the last index and less than the commit index, append the entry.
      // We perform no additional consistency checks here since passive members may only receive committed entries.
      if (context.getLog().lastIndex() < entry.getIndex() && entry.getIndex() <= commitIndex) {
        context.getLog().skip(entry.getIndex() - context.getLog().lastIndex() - 1).append(entry);
        LOGGER.trace("{} - Appended {} to log at index {}", context.getCluster().member().address(), entry, entry.getIndex());
      }
    }

    // Update the context commit and global indices.
    long previousCommitIndex = context.getCommitIndex();
    context.setCommitIndex(commitIndex);
    context.setGlobalIndex(request.globalIndex());

    if (context.getCommitIndex() > previousCommitIndex) {
      LOGGER.trace("{} - Committed entries up to index {}", context.getCluster().member().address(), commitIndex);
    }

    // Apply commits to the state machine in batch.
    context.getStateMachine().applyAll(context.getCommitIndex());

    return AppendResponse.builder()
      .withStatus(Response.Status.OK)
      .withTerm(context.getTerm())
      .withSucceeded(true)
      .withLogIndex(context.getLog().lastIndex())
      .build();
  }
387631
@SuppressWarnings("unchecked")
  private <T extends Request> void resendRequest(Throwable cause, T request, BiFunction sender, Connection connection, CompletableFuture future) {
    // If the connection has not changed, reset it and connect to the next server.
    if (this.connection == connection) {
      LOGGER.trace("{} - Resetting connection. Reason: {}", id, cause);
      this.connection = null;
      connection.close();
    }

    // Create a new connection and resend the request. This will force retries to piggyback on any existing
    // connect attempts.
    connect().whenComplete((c, e) -> sendRequest(request, sender, c, e, future));
  }
1322329
public function onHeartbeat()
    {
        $now = microtime(true);
        $nextHeartbeat = ($this->lastWrite ?: $now) + $this->options["heartbeat"];

        if ($now >= $nextHeartbeat) {
            $this->writer->appendFrame(new HeartbeatFrame(), $this->writeBuffer);
            $this->flushWriteBuffer()->done(function () {
                $this->heartbeatTimer = $this->eventLoop->addTimer($this->options["heartbeat"], [$this, "onHeartbeat"]);
            });

        } else {
            $this->heartbeatTimer = $this->eventLoop->addTimer($nextHeartbeat - $now, [$this, "onHeartbeat"]);
        }
    }