id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,300 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/partition/impl/RaftPartitionServer.java | RaftPartitionServer.delete | public void delete() {
try {
Files.walkFileTree(partition.dataDirectory().toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
log.error("Failed to delete partition: {}", e);
}
} | java | public void delete() {
try {
Files.walkFileTree(partition.dataDirectory().toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
log.error("Failed to delete partition: {}", e);
}
} | [
"public",
"void",
"delete",
"(",
")",
"{",
"try",
"{",
"Files",
".",
"walkFileTree",
"(",
"partition",
".",
"dataDirectory",
"(",
")",
".",
"toPath",
"(",
")",
",",
"new",
"SimpleFileVisitor",
"<",
"Path",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"FileVisitResult",
"visitFile",
"(",
"Path",
"file",
",",
"BasicFileAttributes",
"attrs",
")",
"throws",
"IOException",
"{",
"Files",
".",
"delete",
"(",
"file",
")",
";",
"return",
"FileVisitResult",
".",
"CONTINUE",
";",
"}",
"@",
"Override",
"public",
"FileVisitResult",
"postVisitDirectory",
"(",
"Path",
"dir",
",",
"IOException",
"exc",
")",
"throws",
"IOException",
"{",
"Files",
".",
"delete",
"(",
"dir",
")",
";",
"return",
"FileVisitResult",
".",
"CONTINUE",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Failed to delete partition: {}\"",
",",
"e",
")",
";",
"}",
"}"
] | Deletes the server. | [
"Deletes",
"the",
"server",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/impl/RaftPartitionServer.java#L136-L154 |
27,301 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/session/impl/RecoveringSessionClient.java | RecoveringSessionClient.openProxy | private void openProxy(CompletableFuture<SessionClient> future) {
log.debug("Opening proxy session");
proxyFactory.get().thenCompose(proxy -> proxy.connect()).whenComplete((proxy, error) -> {
if (error == null) {
synchronized (this) {
this.log = ContextualLoggerFactory.getLogger(getClass(), LoggerContext.builder(SessionClient.class)
.addValue(proxy.sessionId())
.add("type", proxy.type())
.add("name", proxy.name())
.build());
this.session = proxy;
proxy.addStateChangeListener(this::onStateChange);
eventListeners.entries().forEach(entry -> proxy.addEventListener(entry.getKey(), entry.getValue()));
onStateChange(PrimitiveState.CONNECTED);
}
future.complete(this);
} else {
recoverTask = context.schedule(Duration.ofSeconds(1), () -> openProxy(future));
}
});
} | java | private void openProxy(CompletableFuture<SessionClient> future) {
log.debug("Opening proxy session");
proxyFactory.get().thenCompose(proxy -> proxy.connect()).whenComplete((proxy, error) -> {
if (error == null) {
synchronized (this) {
this.log = ContextualLoggerFactory.getLogger(getClass(), LoggerContext.builder(SessionClient.class)
.addValue(proxy.sessionId())
.add("type", proxy.type())
.add("name", proxy.name())
.build());
this.session = proxy;
proxy.addStateChangeListener(this::onStateChange);
eventListeners.entries().forEach(entry -> proxy.addEventListener(entry.getKey(), entry.getValue()));
onStateChange(PrimitiveState.CONNECTED);
}
future.complete(this);
} else {
recoverTask = context.schedule(Duration.ofSeconds(1), () -> openProxy(future));
}
});
} | [
"private",
"void",
"openProxy",
"(",
"CompletableFuture",
"<",
"SessionClient",
">",
"future",
")",
"{",
"log",
".",
"debug",
"(",
"\"Opening proxy session\"",
")",
";",
"proxyFactory",
".",
"get",
"(",
")",
".",
"thenCompose",
"(",
"proxy",
"->",
"proxy",
".",
"connect",
"(",
")",
")",
".",
"whenComplete",
"(",
"(",
"proxy",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"this",
".",
"log",
"=",
"ContextualLoggerFactory",
".",
"getLogger",
"(",
"getClass",
"(",
")",
",",
"LoggerContext",
".",
"builder",
"(",
"SessionClient",
".",
"class",
")",
".",
"addValue",
"(",
"proxy",
".",
"sessionId",
"(",
")",
")",
".",
"add",
"(",
"\"type\"",
",",
"proxy",
".",
"type",
"(",
")",
")",
".",
"add",
"(",
"\"name\"",
",",
"proxy",
".",
"name",
"(",
")",
")",
".",
"build",
"(",
")",
")",
";",
"this",
".",
"session",
"=",
"proxy",
";",
"proxy",
".",
"addStateChangeListener",
"(",
"this",
"::",
"onStateChange",
")",
";",
"eventListeners",
".",
"entries",
"(",
")",
".",
"forEach",
"(",
"entry",
"->",
"proxy",
".",
"addEventListener",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
")",
";",
"onStateChange",
"(",
"PrimitiveState",
".",
"CONNECTED",
")",
";",
"}",
"future",
".",
"complete",
"(",
"this",
")",
";",
"}",
"else",
"{",
"recoverTask",
"=",
"context",
".",
"schedule",
"(",
"Duration",
".",
"ofSeconds",
"(",
"1",
")",
",",
"(",
")",
"->",
"openProxy",
"(",
"future",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Opens a new client, completing the provided future only once the client has been opened.
@param future the future to be completed once the client is opened | [
"Opens",
"a",
"new",
"client",
"completing",
"the",
"provided",
"future",
"only",
"once",
"the",
"client",
"has",
"been",
"opened",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/session/impl/RecoveringSessionClient.java#L168-L188 |
27,302 | atomix/atomix | utils/src/main/java/io/atomix/utils/concurrent/Threads.java | Threads.namedThreads | public static ThreadFactory namedThreads(String pattern, Logger log) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern)
.setThreadFactory(new AtomixThreadFactory())
.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
.build();
} | java | public static ThreadFactory namedThreads(String pattern, Logger log) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern)
.setThreadFactory(new AtomixThreadFactory())
.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
.build();
} | [
"public",
"static",
"ThreadFactory",
"namedThreads",
"(",
"String",
"pattern",
",",
"Logger",
"log",
")",
"{",
"return",
"new",
"ThreadFactoryBuilder",
"(",
")",
".",
"setNameFormat",
"(",
"pattern",
")",
".",
"setThreadFactory",
"(",
"new",
"AtomixThreadFactory",
"(",
")",
")",
".",
"setUncaughtExceptionHandler",
"(",
"(",
"t",
",",
"e",
")",
"->",
"log",
".",
"error",
"(",
"\"Uncaught exception on \"",
"+",
"t",
".",
"getName",
"(",
")",
",",
"e",
")",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns a thread factory that produces threads named according to the
supplied name pattern.
@param pattern name pattern
@return thread factory | [
"Returns",
"a",
"thread",
"factory",
"that",
"produces",
"threads",
"named",
"according",
"to",
"the",
"supplied",
"name",
"pattern",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/Threads.java#L35-L41 |
27,303 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java | HashBasedPrimaryElection.handleClusterMembershipEvent | private void handleClusterMembershipEvent(ClusterMembershipEvent event) {
if (event.type() == ClusterMembershipEvent.Type.MEMBER_ADDED || event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
recomputeTerm(groupMembershipService.getMembership(partitionId.group()));
}
} | java | private void handleClusterMembershipEvent(ClusterMembershipEvent event) {
if (event.type() == ClusterMembershipEvent.Type.MEMBER_ADDED || event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
recomputeTerm(groupMembershipService.getMembership(partitionId.group()));
}
} | [
"private",
"void",
"handleClusterMembershipEvent",
"(",
"ClusterMembershipEvent",
"event",
")",
"{",
"if",
"(",
"event",
".",
"type",
"(",
")",
"==",
"ClusterMembershipEvent",
".",
"Type",
".",
"MEMBER_ADDED",
"||",
"event",
".",
"type",
"(",
")",
"==",
"ClusterMembershipEvent",
".",
"Type",
".",
"MEMBER_REMOVED",
")",
"{",
"recomputeTerm",
"(",
"groupMembershipService",
".",
"getMembership",
"(",
"partitionId",
".",
"group",
"(",
")",
")",
")",
";",
"}",
"}"
] | Handles a cluster membership event. | [
"Handles",
"a",
"cluster",
"membership",
"event",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java#L122-L126 |
27,304 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java | HashBasedPrimaryElection.incrementTerm | private long incrementTerm() {
counters.compute(clusterMembershipService.getLocalMember().id(), (id, value) -> value != null ? value + 1 : 1);
broadcastCounters();
return currentTerm();
} | java | private long incrementTerm() {
counters.compute(clusterMembershipService.getLocalMember().id(), (id, value) -> value != null ? value + 1 : 1);
broadcastCounters();
return currentTerm();
} | [
"private",
"long",
"incrementTerm",
"(",
")",
"{",
"counters",
".",
"compute",
"(",
"clusterMembershipService",
".",
"getLocalMember",
"(",
")",
".",
"id",
"(",
")",
",",
"(",
"id",
",",
"value",
")",
"->",
"value",
"!=",
"null",
"?",
"value",
"+",
"1",
":",
"1",
")",
";",
"broadcastCounters",
"(",
")",
";",
"return",
"currentTerm",
"(",
")",
";",
"}"
] | Increments and returns the current term.
@return the current term | [
"Increments",
"and",
"returns",
"the",
"current",
"term",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java#L142-L146 |
27,305 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java | HashBasedPrimaryElection.recomputeTerm | private synchronized void recomputeTerm(PartitionGroupMembership membership) {
if (membership == null) {
return;
}
// Create a list of candidates based on the availability of members in the group.
List<GroupMember> candidates = new ArrayList<>();
for (MemberId memberId : membership.members()) {
Member member = clusterMembershipService.getMember(memberId);
if (member != null && member.isReachable()) {
candidates.add(new GroupMember(memberId, MemberGroupId.from(memberId.id())));
}
}
// Sort the candidates by a hash of their member ID.
candidates.sort((a, b) -> {
int aoffset = Hashing.murmur3_32().hashString(a.memberId().id(), StandardCharsets.UTF_8).asInt() % partitionId.id();
int boffset = Hashing.murmur3_32().hashString(b.memberId().id(), StandardCharsets.UTF_8).asInt() % partitionId.id();
return aoffset - boffset;
});
// Store the current term in a local variable avoid repeated volatile reads.
PrimaryTerm currentTerm = this.currentTerm;
// Compute the primary from the sorted candidates list.
GroupMember primary = candidates.isEmpty() ? null : candidates.get(0);
// Remove the primary from the candidates list.
candidates = candidates.isEmpty() ? Collections.emptyList() : candidates.subList(1, candidates.size());
// If the primary has changed, increment the term. Otherwise, use the current term from the replicated counter.
long term = currentTerm != null
&& Objects.equals(currentTerm.primary(), primary)
&& Objects.equals(currentTerm.candidates(), candidates)
? currentTerm() : incrementTerm();
// Create the new primary term. If the term has changed update the term and trigger an event.
PrimaryTerm newTerm = new PrimaryTerm(term, primary, candidates);
if (!Objects.equals(currentTerm, newTerm)) {
this.currentTerm = newTerm;
LOGGER.debug("{} - Recomputed term for partition {}: {}", clusterMembershipService.getLocalMember().id(), partitionId, newTerm);
post(new PrimaryElectionEvent(PrimaryElectionEvent.Type.CHANGED, partitionId, newTerm));
broadcastCounters();
}
} | java | private synchronized void recomputeTerm(PartitionGroupMembership membership) {
if (membership == null) {
return;
}
// Create a list of candidates based on the availability of members in the group.
List<GroupMember> candidates = new ArrayList<>();
for (MemberId memberId : membership.members()) {
Member member = clusterMembershipService.getMember(memberId);
if (member != null && member.isReachable()) {
candidates.add(new GroupMember(memberId, MemberGroupId.from(memberId.id())));
}
}
// Sort the candidates by a hash of their member ID.
candidates.sort((a, b) -> {
int aoffset = Hashing.murmur3_32().hashString(a.memberId().id(), StandardCharsets.UTF_8).asInt() % partitionId.id();
int boffset = Hashing.murmur3_32().hashString(b.memberId().id(), StandardCharsets.UTF_8).asInt() % partitionId.id();
return aoffset - boffset;
});
// Store the current term in a local variable avoid repeated volatile reads.
PrimaryTerm currentTerm = this.currentTerm;
// Compute the primary from the sorted candidates list.
GroupMember primary = candidates.isEmpty() ? null : candidates.get(0);
// Remove the primary from the candidates list.
candidates = candidates.isEmpty() ? Collections.emptyList() : candidates.subList(1, candidates.size());
// If the primary has changed, increment the term. Otherwise, use the current term from the replicated counter.
long term = currentTerm != null
&& Objects.equals(currentTerm.primary(), primary)
&& Objects.equals(currentTerm.candidates(), candidates)
? currentTerm() : incrementTerm();
// Create the new primary term. If the term has changed update the term and trigger an event.
PrimaryTerm newTerm = new PrimaryTerm(term, primary, candidates);
if (!Objects.equals(currentTerm, newTerm)) {
this.currentTerm = newTerm;
LOGGER.debug("{} - Recomputed term for partition {}: {}", clusterMembershipService.getLocalMember().id(), partitionId, newTerm);
post(new PrimaryElectionEvent(PrimaryElectionEvent.Type.CHANGED, partitionId, newTerm));
broadcastCounters();
}
} | [
"private",
"synchronized",
"void",
"recomputeTerm",
"(",
"PartitionGroupMembership",
"membership",
")",
"{",
"if",
"(",
"membership",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// Create a list of candidates based on the availability of members in the group.",
"List",
"<",
"GroupMember",
">",
"candidates",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"MemberId",
"memberId",
":",
"membership",
".",
"members",
"(",
")",
")",
"{",
"Member",
"member",
"=",
"clusterMembershipService",
".",
"getMember",
"(",
"memberId",
")",
";",
"if",
"(",
"member",
"!=",
"null",
"&&",
"member",
".",
"isReachable",
"(",
")",
")",
"{",
"candidates",
".",
"add",
"(",
"new",
"GroupMember",
"(",
"memberId",
",",
"MemberGroupId",
".",
"from",
"(",
"memberId",
".",
"id",
"(",
")",
")",
")",
")",
";",
"}",
"}",
"// Sort the candidates by a hash of their member ID.",
"candidates",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"->",
"{",
"int",
"aoffset",
"=",
"Hashing",
".",
"murmur3_32",
"(",
")",
".",
"hashString",
"(",
"a",
".",
"memberId",
"(",
")",
".",
"id",
"(",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
".",
"asInt",
"(",
")",
"%",
"partitionId",
".",
"id",
"(",
")",
";",
"int",
"boffset",
"=",
"Hashing",
".",
"murmur3_32",
"(",
")",
".",
"hashString",
"(",
"b",
".",
"memberId",
"(",
")",
".",
"id",
"(",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
".",
"asInt",
"(",
")",
"%",
"partitionId",
".",
"id",
"(",
")",
";",
"return",
"aoffset",
"-",
"boffset",
";",
"}",
")",
";",
"// Store the current term in a local variable avoid repeated volatile reads.",
"PrimaryTerm",
"currentTerm",
"=",
"this",
".",
"currentTerm",
";",
"// Compute the primary from the sorted candidates list.",
"GroupMember",
"primary",
"=",
"candidates",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"candidates",
".",
"get",
"(",
"0",
")",
";",
"// Remove the primary from the candidates list.",
"candidates",
"=",
"candidates",
".",
"isEmpty",
"(",
")",
"?",
"Collections",
".",
"emptyList",
"(",
")",
":",
"candidates",
".",
"subList",
"(",
"1",
",",
"candidates",
".",
"size",
"(",
")",
")",
";",
"// If the primary has changed, increment the term. Otherwise, use the current term from the replicated counter.",
"long",
"term",
"=",
"currentTerm",
"!=",
"null",
"&&",
"Objects",
".",
"equals",
"(",
"currentTerm",
".",
"primary",
"(",
")",
",",
"primary",
")",
"&&",
"Objects",
".",
"equals",
"(",
"currentTerm",
".",
"candidates",
"(",
")",
",",
"candidates",
")",
"?",
"currentTerm",
"(",
")",
":",
"incrementTerm",
"(",
")",
";",
"// Create the new primary term. If the term has changed update the term and trigger an event.",
"PrimaryTerm",
"newTerm",
"=",
"new",
"PrimaryTerm",
"(",
"term",
",",
"primary",
",",
"candidates",
")",
";",
"if",
"(",
"!",
"Objects",
".",
"equals",
"(",
"currentTerm",
",",
"newTerm",
")",
")",
"{",
"this",
".",
"currentTerm",
"=",
"newTerm",
";",
"LOGGER",
".",
"debug",
"(",
"\"{} - Recomputed term for partition {}: {}\"",
",",
"clusterMembershipService",
".",
"getLocalMember",
"(",
")",
".",
"id",
"(",
")",
",",
"partitionId",
",",
"newTerm",
")",
";",
"post",
"(",
"new",
"PrimaryElectionEvent",
"(",
"PrimaryElectionEvent",
".",
"Type",
".",
"CHANGED",
",",
"partitionId",
",",
"newTerm",
")",
")",
";",
"broadcastCounters",
"(",
")",
";",
"}",
"}"
] | Recomputes the current term. | [
"Recomputes",
"the",
"current",
"term",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java#L173-L217 |
27,306 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java | HashBasedPrimaryElection.close | void close() {
broadcastFuture.cancel(false);
groupMembershipService.removeListener(groupMembershipEventListener);
clusterMembershipService.removeListener(clusterMembershipEventListener);
} | java | void close() {
broadcastFuture.cancel(false);
groupMembershipService.removeListener(groupMembershipEventListener);
clusterMembershipService.removeListener(clusterMembershipEventListener);
} | [
"void",
"close",
"(",
")",
"{",
"broadcastFuture",
".",
"cancel",
"(",
"false",
")",
";",
"groupMembershipService",
".",
"removeListener",
"(",
"groupMembershipEventListener",
")",
";",
"clusterMembershipService",
".",
"removeListener",
"(",
"clusterMembershipEventListener",
")",
";",
"}"
] | Closes the election. | [
"Closes",
"the",
"election",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/HashBasedPrimaryElection.java#L222-L226 |
27,307 | atomix/atomix | utils/src/main/java/io/atomix/utils/time/LogicalClock.java | LogicalClock.update | public LogicalTimestamp update(LogicalTimestamp timestamp) {
if (timestamp.value() > currentTimestamp.value()) {
this.currentTimestamp = timestamp;
}
return currentTimestamp;
} | java | public LogicalTimestamp update(LogicalTimestamp timestamp) {
if (timestamp.value() > currentTimestamp.value()) {
this.currentTimestamp = timestamp;
}
return currentTimestamp;
} | [
"public",
"LogicalTimestamp",
"update",
"(",
"LogicalTimestamp",
"timestamp",
")",
"{",
"if",
"(",
"timestamp",
".",
"value",
"(",
")",
">",
"currentTimestamp",
".",
"value",
"(",
")",
")",
"{",
"this",
".",
"currentTimestamp",
"=",
"timestamp",
";",
"}",
"return",
"currentTimestamp",
";",
"}"
] | Updates the clock using the given timestamp.
@param timestamp the timestamp with which to update the clock
@return the updated clock time | [
"Updates",
"the",
"clock",
"using",
"the",
"given",
"timestamp",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/time/LogicalClock.java#L54-L59 |
27,308 | atomix/atomix | utils/src/main/java/io/atomix/utils/time/LogicalClock.java | LogicalClock.incrementAndUpdate | public LogicalTimestamp incrementAndUpdate(LogicalTimestamp timestamp) {
long nextValue = currentTimestamp.value() + 1;
if (timestamp.value() > nextValue) {
return update(timestamp);
}
return increment();
} | java | public LogicalTimestamp incrementAndUpdate(LogicalTimestamp timestamp) {
long nextValue = currentTimestamp.value() + 1;
if (timestamp.value() > nextValue) {
return update(timestamp);
}
return increment();
} | [
"public",
"LogicalTimestamp",
"incrementAndUpdate",
"(",
"LogicalTimestamp",
"timestamp",
")",
"{",
"long",
"nextValue",
"=",
"currentTimestamp",
".",
"value",
"(",
")",
"+",
"1",
";",
"if",
"(",
"timestamp",
".",
"value",
"(",
")",
">",
"nextValue",
")",
"{",
"return",
"update",
"(",
"timestamp",
")",
";",
"}",
"return",
"increment",
"(",
")",
";",
"}"
] | Increments the clock and updates it using the given timestamp.
@param timestamp the timestamp with which to update the clock
@return the updated clock time | [
"Increments",
"the",
"clock",
"and",
"updates",
"it",
"using",
"the",
"given",
"timestamp",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/time/LogicalClock.java#L67-L73 |
27,309 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java | PassiveRole.handleAppend | protected CompletableFuture<AppendResponse> handleAppend(final AppendRequest request) {
CompletableFuture<AppendResponse> future = new CompletableFuture<>();
// Check that the term of the given request matches the local term or update the term.
if (!checkTerm(request, future)) {
return future;
}
// Check that the previous index/term matches the local log's last entry.
if (!checkPreviousEntry(request, future)) {
return future;
}
// Append the entries to the log.
appendEntries(request, future);
return future;
} | java | protected CompletableFuture<AppendResponse> handleAppend(final AppendRequest request) {
CompletableFuture<AppendResponse> future = new CompletableFuture<>();
// Check that the term of the given request matches the local term or update the term.
if (!checkTerm(request, future)) {
return future;
}
// Check that the previous index/term matches the local log's last entry.
if (!checkPreviousEntry(request, future)) {
return future;
}
// Append the entries to the log.
appendEntries(request, future);
return future;
} | [
"protected",
"CompletableFuture",
"<",
"AppendResponse",
">",
"handleAppend",
"(",
"final",
"AppendRequest",
"request",
")",
"{",
"CompletableFuture",
"<",
"AppendResponse",
">",
"future",
"=",
"new",
"CompletableFuture",
"<>",
"(",
")",
";",
"// Check that the term of the given request matches the local term or update the term.",
"if",
"(",
"!",
"checkTerm",
"(",
"request",
",",
"future",
")",
")",
"{",
"return",
"future",
";",
"}",
"// Check that the previous index/term matches the local log's last entry.",
"if",
"(",
"!",
"checkPreviousEntry",
"(",
"request",
",",
"future",
")",
")",
"{",
"return",
"future",
";",
"}",
"// Append the entries to the log.",
"appendEntries",
"(",
"request",
",",
"future",
")",
";",
"return",
"future",
";",
"}"
] | Handles an AppendRequest. | [
"Handles",
"an",
"AppendRequest",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java#L112-L128 |
27,310 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java | PassiveRole.checkTerm | protected boolean checkTerm(AppendRequest request, CompletableFuture<AppendResponse> future) {
RaftLogWriter writer = raft.getLogWriter();
if (request.term() < raft.getTerm()) {
log.debug("Rejected {}: request term is less than the current term ({})", request, raft.getTerm());
return failAppend(writer.getLastIndex(), future);
}
return true;
} | java | protected boolean checkTerm(AppendRequest request, CompletableFuture<AppendResponse> future) {
RaftLogWriter writer = raft.getLogWriter();
if (request.term() < raft.getTerm()) {
log.debug("Rejected {}: request term is less than the current term ({})", request, raft.getTerm());
return failAppend(writer.getLastIndex(), future);
}
return true;
} | [
"protected",
"boolean",
"checkTerm",
"(",
"AppendRequest",
"request",
",",
"CompletableFuture",
"<",
"AppendResponse",
">",
"future",
")",
"{",
"RaftLogWriter",
"writer",
"=",
"raft",
".",
"getLogWriter",
"(",
")",
";",
"if",
"(",
"request",
".",
"term",
"(",
")",
"<",
"raft",
".",
"getTerm",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Rejected {}: request term is less than the current term ({})\"",
",",
"request",
",",
"raft",
".",
"getTerm",
"(",
")",
")",
";",
"return",
"failAppend",
"(",
"writer",
".",
"getLastIndex",
"(",
")",
",",
"future",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Checks the leader's term of the given AppendRequest, returning a boolean indicating whether to continue
handling the request. | [
"Checks",
"the",
"leader",
"s",
"term",
"of",
"the",
"given",
"AppendRequest",
"returning",
"a",
"boolean",
"indicating",
"whether",
"to",
"continue",
"handling",
"the",
"request",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java#L134-L141 |
27,311 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java | PassiveRole.checkPreviousEntry | protected boolean checkPreviousEntry(AppendRequest request, CompletableFuture<AppendResponse> future) {
RaftLogWriter writer = raft.getLogWriter();
RaftLogReader reader = raft.getLogReader();
// If the previous term is set, validate that it matches the local log.
// We check the previous log term since that indicates whether any entry is present in the leader's
// log at the previous log index. It's possible that the leader can send a non-zero previous log index
// with a zero term in the event the leader has compacted its logs and is sending the first entry.
if (request.prevLogTerm() != 0) {
// Get the last entry written to the log.
Indexed<RaftLogEntry> lastEntry = writer.getLastEntry();
// If the local log is non-empty...
if (lastEntry != null) {
// If the previous log index is greater than the last entry index, fail the attempt.
if (request.prevLogIndex() > lastEntry.index()) {
log.debug("Rejected {}: Previous index ({}) is greater than the local log's last index ({})", request, request.prevLogIndex(), lastEntry.index());
return failAppend(lastEntry.index(), future);
}
// If the previous log index is less than the last written entry index, look up the entry.
if (request.prevLogIndex() < lastEntry.index()) {
// Reset the reader to the previous log index.
if (reader.getNextIndex() != request.prevLogIndex()) {
reader.reset(request.prevLogIndex());
}
// The previous entry should exist in the log if we've gotten this far.
if (!reader.hasNext()) {
log.debug("Rejected {}: Previous entry does not exist in the local log", request);
return failAppend(lastEntry.index(), future);
}
// Read the previous entry and validate that the term matches the request previous log term.
Indexed<RaftLogEntry> previousEntry = reader.next();
if (request.prevLogTerm() != previousEntry.entry().term()) {
log.debug("Rejected {}: Previous entry term ({}) does not match local log's term for the same entry ({})", request, request.prevLogTerm(), previousEntry.entry().term());
return failAppend(request.prevLogIndex() - 1, future);
}
}
// If the previous log term doesn't equal the last entry term, fail the append, sending the prior entry.
else if (request.prevLogTerm() != lastEntry.entry().term()) {
log.debug("Rejected {}: Previous entry term ({}) does not equal the local log's last term ({})", request, request.prevLogTerm(), lastEntry.entry().term());
return failAppend(request.prevLogIndex() - 1, future);
}
} else {
// If the previous log index is set and the last entry is null, fail the append.
if (request.prevLogIndex() > 0) {
log.debug("Rejected {}: Previous index ({}) is greater than the local log's last index (0)", request, request.prevLogIndex());
return failAppend(0, future);
}
}
}
return true;
} | java | protected boolean checkPreviousEntry(AppendRequest request, CompletableFuture<AppendResponse> future) {
RaftLogWriter writer = raft.getLogWriter();
RaftLogReader reader = raft.getLogReader();
// If the previous term is set, validate that it matches the local log.
// We check the previous log term since that indicates whether any entry is present in the leader's
// log at the previous log index. It's possible that the leader can send a non-zero previous log index
// with a zero term in the event the leader has compacted its logs and is sending the first entry.
if (request.prevLogTerm() != 0) {
// Get the last entry written to the log.
Indexed<RaftLogEntry> lastEntry = writer.getLastEntry();
// If the local log is non-empty...
if (lastEntry != null) {
// If the previous log index is greater than the last entry index, fail the attempt.
if (request.prevLogIndex() > lastEntry.index()) {
log.debug("Rejected {}: Previous index ({}) is greater than the local log's last index ({})", request, request.prevLogIndex(), lastEntry.index());
return failAppend(lastEntry.index(), future);
}
// If the previous log index is less than the last written entry index, look up the entry.
if (request.prevLogIndex() < lastEntry.index()) {
// Reset the reader to the previous log index.
if (reader.getNextIndex() != request.prevLogIndex()) {
reader.reset(request.prevLogIndex());
}
// The previous entry should exist in the log if we've gotten this far.
if (!reader.hasNext()) {
log.debug("Rejected {}: Previous entry does not exist in the local log", request);
return failAppend(lastEntry.index(), future);
}
// Read the previous entry and validate that the term matches the request previous log term.
Indexed<RaftLogEntry> previousEntry = reader.next();
if (request.prevLogTerm() != previousEntry.entry().term()) {
log.debug("Rejected {}: Previous entry term ({}) does not match local log's term for the same entry ({})", request, request.prevLogTerm(), previousEntry.entry().term());
return failAppend(request.prevLogIndex() - 1, future);
}
}
// If the previous log term doesn't equal the last entry term, fail the append, sending the prior entry.
else if (request.prevLogTerm() != lastEntry.entry().term()) {
log.debug("Rejected {}: Previous entry term ({}) does not equal the local log's last term ({})", request, request.prevLogTerm(), lastEntry.entry().term());
return failAppend(request.prevLogIndex() - 1, future);
}
} else {
// If the previous log index is set and the last entry is null, fail the append.
if (request.prevLogIndex() > 0) {
log.debug("Rejected {}: Previous index ({}) is greater than the local log's last index (0)", request, request.prevLogIndex());
return failAppend(0, future);
}
}
}
return true;
} | [
"protected",
"boolean",
"checkPreviousEntry",
"(",
"AppendRequest",
"request",
",",
"CompletableFuture",
"<",
"AppendResponse",
">",
"future",
")",
"{",
"RaftLogWriter",
"writer",
"=",
"raft",
".",
"getLogWriter",
"(",
")",
";",
"RaftLogReader",
"reader",
"=",
"raft",
".",
"getLogReader",
"(",
")",
";",
"// If the previous term is set, validate that it matches the local log.",
"// We check the previous log term since that indicates whether any entry is present in the leader's",
"// log at the previous log index. It's possible that the leader can send a non-zero previous log index",
"// with a zero term in the event the leader has compacted its logs and is sending the first entry.",
"if",
"(",
"request",
".",
"prevLogTerm",
"(",
")",
"!=",
"0",
")",
"{",
"// Get the last entry written to the log.",
"Indexed",
"<",
"RaftLogEntry",
">",
"lastEntry",
"=",
"writer",
".",
"getLastEntry",
"(",
")",
";",
"// If the local log is non-empty...",
"if",
"(",
"lastEntry",
"!=",
"null",
")",
"{",
"// If the previous log index is greater than the last entry index, fail the attempt.",
"if",
"(",
"request",
".",
"prevLogIndex",
"(",
")",
">",
"lastEntry",
".",
"index",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Rejected {}: Previous index ({}) is greater than the local log's last index ({})\"",
",",
"request",
",",
"request",
".",
"prevLogIndex",
"(",
")",
",",
"lastEntry",
".",
"index",
"(",
")",
")",
";",
"return",
"failAppend",
"(",
"lastEntry",
".",
"index",
"(",
")",
",",
"future",
")",
";",
"}",
"// If the previous log index is less than the last written entry index, look up the entry.",
"if",
"(",
"request",
".",
"prevLogIndex",
"(",
")",
"<",
"lastEntry",
".",
"index",
"(",
")",
")",
"{",
"// Reset the reader to the previous log index.",
"if",
"(",
"reader",
".",
"getNextIndex",
"(",
")",
"!=",
"request",
".",
"prevLogIndex",
"(",
")",
")",
"{",
"reader",
".",
"reset",
"(",
"request",
".",
"prevLogIndex",
"(",
")",
")",
";",
"}",
"// The previous entry should exist in the log if we've gotten this far.",
"if",
"(",
"!",
"reader",
".",
"hasNext",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Rejected {}: Previous entry does not exist in the local log\"",
",",
"request",
")",
";",
"return",
"failAppend",
"(",
"lastEntry",
".",
"index",
"(",
")",
",",
"future",
")",
";",
"}",
"// Read the previous entry and validate that the term matches the request previous log term.",
"Indexed",
"<",
"RaftLogEntry",
">",
"previousEntry",
"=",
"reader",
".",
"next",
"(",
")",
";",
"if",
"(",
"request",
".",
"prevLogTerm",
"(",
")",
"!=",
"previousEntry",
".",
"entry",
"(",
")",
".",
"term",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Rejected {}: Previous entry term ({}) does not match local log's term for the same entry ({})\"",
",",
"request",
",",
"request",
".",
"prevLogTerm",
"(",
")",
",",
"previousEntry",
".",
"entry",
"(",
")",
".",
"term",
"(",
")",
")",
";",
"return",
"failAppend",
"(",
"request",
".",
"prevLogIndex",
"(",
")",
"-",
"1",
",",
"future",
")",
";",
"}",
"}",
"// If the previous log term doesn't equal the last entry term, fail the append, sending the prior entry.",
"else",
"if",
"(",
"request",
".",
"prevLogTerm",
"(",
")",
"!=",
"lastEntry",
".",
"entry",
"(",
")",
".",
"term",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Rejected {}: Previous entry term ({}) does not equal the local log's last term ({})\"",
",",
"request",
",",
"request",
".",
"prevLogTerm",
"(",
")",
",",
"lastEntry",
".",
"entry",
"(",
")",
".",
"term",
"(",
")",
")",
";",
"return",
"failAppend",
"(",
"request",
".",
"prevLogIndex",
"(",
")",
"-",
"1",
",",
"future",
")",
";",
"}",
"}",
"else",
"{",
"// If the previous log index is set and the last entry is null, fail the append.",
"if",
"(",
"request",
".",
"prevLogIndex",
"(",
")",
">",
"0",
")",
"{",
"log",
".",
"debug",
"(",
"\"Rejected {}: Previous index ({}) is greater than the local log's last index (0)\"",
",",
"request",
",",
"request",
".",
"prevLogIndex",
"(",
")",
")",
";",
"return",
"failAppend",
"(",
"0",
",",
"future",
")",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] | Checks the previous index of the given AppendRequest, returning a boolean indicating whether to continue
handling the request. | [
"Checks",
"the",
"previous",
"index",
"of",
"the",
"given",
"AppendRequest",
"returning",
"a",
"boolean",
"indicating",
"whether",
"to",
"continue",
"handling",
"the",
"request",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java#L147-L201 |
27,312 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java | PassiveRole.completeAppend | protected boolean completeAppend(boolean succeeded, long lastLogIndex, CompletableFuture<AppendResponse> future) {
future.complete(logResponse(AppendResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withSucceeded(succeeded)
.withLastLogIndex(lastLogIndex)
.build()));
return succeeded;
} | java | protected boolean completeAppend(boolean succeeded, long lastLogIndex, CompletableFuture<AppendResponse> future) {
future.complete(logResponse(AppendResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withSucceeded(succeeded)
.withLastLogIndex(lastLogIndex)
.build()));
return succeeded;
} | [
"protected",
"boolean",
"completeAppend",
"(",
"boolean",
"succeeded",
",",
"long",
"lastLogIndex",
",",
"CompletableFuture",
"<",
"AppendResponse",
">",
"future",
")",
"{",
"future",
".",
"complete",
"(",
"logResponse",
"(",
"AppendResponse",
".",
"builder",
"(",
")",
".",
"withStatus",
"(",
"RaftResponse",
".",
"Status",
".",
"OK",
")",
".",
"withTerm",
"(",
"raft",
".",
"getTerm",
"(",
")",
")",
".",
"withSucceeded",
"(",
"succeeded",
")",
".",
"withLastLogIndex",
"(",
"lastLogIndex",
")",
".",
"build",
"(",
")",
")",
")",
";",
"return",
"succeeded",
";",
"}"
] | Returns a successful append response.
@param succeeded whether the append succeeded
@param lastLogIndex the last log index
@param future the append response future
@return the append response status | [
"Returns",
"a",
"successful",
"append",
"response",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java#L362-L370 |
27,313 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java | BackupRole.applyOperations | private void applyOperations(long fromIndex, long toIndex) {
for (long i = fromIndex + 1; i <= toIndex; i++) {
BackupOperation operation = operations.poll();
if (operation == null) {
requestRestore(context.primary());
break;
}
if (context.nextIndex(operation.index())) {
switch (operation.type()) {
case EXECUTE:
applyExecute((ExecuteOperation) operation);
break;
case HEARTBEAT:
applyHeartbeat((HeartbeatOperation) operation);
break;
case EXPIRE:
applyExpire((ExpireOperation) operation);
break;
case CLOSE:
applyClose((CloseOperation) operation);
break;
}
} else if (operation.index() < i) {
continue;
} else {
requestRestore(context.primary());
break;
}
}
} | java | private void applyOperations(long fromIndex, long toIndex) {
for (long i = fromIndex + 1; i <= toIndex; i++) {
BackupOperation operation = operations.poll();
if (operation == null) {
requestRestore(context.primary());
break;
}
if (context.nextIndex(operation.index())) {
switch (operation.type()) {
case EXECUTE:
applyExecute((ExecuteOperation) operation);
break;
case HEARTBEAT:
applyHeartbeat((HeartbeatOperation) operation);
break;
case EXPIRE:
applyExpire((ExpireOperation) operation);
break;
case CLOSE:
applyClose((CloseOperation) operation);
break;
}
} else if (operation.index() < i) {
continue;
} else {
requestRestore(context.primary());
break;
}
}
} | [
"private",
"void",
"applyOperations",
"(",
"long",
"fromIndex",
",",
"long",
"toIndex",
")",
"{",
"for",
"(",
"long",
"i",
"=",
"fromIndex",
"+",
"1",
";",
"i",
"<=",
"toIndex",
";",
"i",
"++",
")",
"{",
"BackupOperation",
"operation",
"=",
"operations",
".",
"poll",
"(",
")",
";",
"if",
"(",
"operation",
"==",
"null",
")",
"{",
"requestRestore",
"(",
"context",
".",
"primary",
"(",
")",
")",
";",
"break",
";",
"}",
"if",
"(",
"context",
".",
"nextIndex",
"(",
"operation",
".",
"index",
"(",
")",
")",
")",
"{",
"switch",
"(",
"operation",
".",
"type",
"(",
")",
")",
"{",
"case",
"EXECUTE",
":",
"applyExecute",
"(",
"(",
"ExecuteOperation",
")",
"operation",
")",
";",
"break",
";",
"case",
"HEARTBEAT",
":",
"applyHeartbeat",
"(",
"(",
"HeartbeatOperation",
")",
"operation",
")",
";",
"break",
";",
"case",
"EXPIRE",
":",
"applyExpire",
"(",
"(",
"ExpireOperation",
")",
"operation",
")",
";",
"break",
";",
"case",
"CLOSE",
":",
"applyClose",
"(",
"(",
"CloseOperation",
")",
"operation",
")",
";",
"break",
";",
"}",
"}",
"else",
"if",
"(",
"operation",
".",
"index",
"(",
")",
"<",
"i",
")",
"{",
"continue",
";",
"}",
"else",
"{",
"requestRestore",
"(",
"context",
".",
"primary",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
"}"
] | Applies operations in the given range. | [
"Applies",
"operations",
"in",
"the",
"given",
"range",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java#L74-L105 |
27,314 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java | BackupRole.applyExecute | private void applyExecute(ExecuteOperation operation) {
Session session = context.getOrCreateSession(operation.session(), operation.node());
if (operation.operation() != null) {
try {
context.service().apply(new DefaultCommit<>(
context.setIndex(operation.index()),
operation.operation().id(),
operation.operation().value(),
context.setSession(session),
context.setTimestamp(operation.timestamp())));
} catch (Exception e) {
log.warn("Failed to apply operation: {}", e);
} finally {
context.setSession(null);
}
}
} | java | private void applyExecute(ExecuteOperation operation) {
Session session = context.getOrCreateSession(operation.session(), operation.node());
if (operation.operation() != null) {
try {
context.service().apply(new DefaultCommit<>(
context.setIndex(operation.index()),
operation.operation().id(),
operation.operation().value(),
context.setSession(session),
context.setTimestamp(operation.timestamp())));
} catch (Exception e) {
log.warn("Failed to apply operation: {}", e);
} finally {
context.setSession(null);
}
}
} | [
"private",
"void",
"applyExecute",
"(",
"ExecuteOperation",
"operation",
")",
"{",
"Session",
"session",
"=",
"context",
".",
"getOrCreateSession",
"(",
"operation",
".",
"session",
"(",
")",
",",
"operation",
".",
"node",
"(",
")",
")",
";",
"if",
"(",
"operation",
".",
"operation",
"(",
")",
"!=",
"null",
")",
"{",
"try",
"{",
"context",
".",
"service",
"(",
")",
".",
"apply",
"(",
"new",
"DefaultCommit",
"<>",
"(",
"context",
".",
"setIndex",
"(",
"operation",
".",
"index",
"(",
")",
")",
",",
"operation",
".",
"operation",
"(",
")",
".",
"id",
"(",
")",
",",
"operation",
".",
"operation",
"(",
")",
".",
"value",
"(",
")",
",",
"context",
".",
"setSession",
"(",
"session",
")",
",",
"context",
".",
"setTimestamp",
"(",
"operation",
".",
"timestamp",
"(",
")",
")",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"Failed to apply operation: {}\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"context",
".",
"setSession",
"(",
"null",
")",
";",
"}",
"}",
"}"
] | Applies an execute operation to the service. | [
"Applies",
"an",
"execute",
"operation",
"to",
"the",
"service",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java#L110-L126 |
27,315 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java | BackupRole.applyExpire | private void applyExpire(ExpireOperation operation) {
context.setTimestamp(operation.timestamp());
PrimaryBackupSession session = context.getSession(operation.session());
if (session != null) {
context.expireSession(session.sessionId().id());
}
} | java | private void applyExpire(ExpireOperation operation) {
context.setTimestamp(operation.timestamp());
PrimaryBackupSession session = context.getSession(operation.session());
if (session != null) {
context.expireSession(session.sessionId().id());
}
} | [
"private",
"void",
"applyExpire",
"(",
"ExpireOperation",
"operation",
")",
"{",
"context",
".",
"setTimestamp",
"(",
"operation",
".",
"timestamp",
"(",
")",
")",
";",
"PrimaryBackupSession",
"session",
"=",
"context",
".",
"getSession",
"(",
"operation",
".",
"session",
"(",
")",
")",
";",
"if",
"(",
"session",
"!=",
"null",
")",
"{",
"context",
".",
"expireSession",
"(",
"session",
".",
"sessionId",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"}",
"}"
] | Applies an expire operation. | [
"Applies",
"an",
"expire",
"operation",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java#L138-L144 |
27,316 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java | BackupRole.applyClose | private void applyClose(CloseOperation operation) {
context.setTimestamp(operation.timestamp());
PrimaryBackupSession session = context.getSession(operation.session());
if (session != null) {
context.closeSession(session.sessionId().id());
}
} | java | private void applyClose(CloseOperation operation) {
context.setTimestamp(operation.timestamp());
PrimaryBackupSession session = context.getSession(operation.session());
if (session != null) {
context.closeSession(session.sessionId().id());
}
} | [
"private",
"void",
"applyClose",
"(",
"CloseOperation",
"operation",
")",
"{",
"context",
".",
"setTimestamp",
"(",
"operation",
".",
"timestamp",
"(",
")",
")",
";",
"PrimaryBackupSession",
"session",
"=",
"context",
".",
"getSession",
"(",
"operation",
".",
"session",
"(",
")",
")",
";",
"if",
"(",
"session",
"!=",
"null",
")",
"{",
"context",
".",
"closeSession",
"(",
"session",
".",
"sessionId",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"}",
"}"
] | Applies a close operation. | [
"Applies",
"a",
"close",
"operation",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java#L149-L155 |
27,317 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java | BackupRole.requestRestore | private void requestRestore(MemberId primary) {
context.protocol().restore(primary, RestoreRequest.request(context.descriptor(), context.currentTerm()))
.whenCompleteAsync((response, error) -> {
if (error == null && response.status() == PrimaryBackupResponse.Status.OK) {
context.resetIndex(response.index(), response.timestamp());
Buffer buffer = HeapBuffer.wrap(response.data());
int sessions = buffer.readInt();
for (int i = 0; i < sessions; i++) {
context.getOrCreateSession(buffer.readLong(), MemberId.from(buffer.readString()));
}
context.service().restore(new DefaultBackupInput(buffer, context.service().serializer()));
operations.clear();
}
}, context.threadContext());
} | java | private void requestRestore(MemberId primary) {
context.protocol().restore(primary, RestoreRequest.request(context.descriptor(), context.currentTerm()))
.whenCompleteAsync((response, error) -> {
if (error == null && response.status() == PrimaryBackupResponse.Status.OK) {
context.resetIndex(response.index(), response.timestamp());
Buffer buffer = HeapBuffer.wrap(response.data());
int sessions = buffer.readInt();
for (int i = 0; i < sessions; i++) {
context.getOrCreateSession(buffer.readLong(), MemberId.from(buffer.readString()));
}
context.service().restore(new DefaultBackupInput(buffer, context.service().serializer()));
operations.clear();
}
}, context.threadContext());
} | [
"private",
"void",
"requestRestore",
"(",
"MemberId",
"primary",
")",
"{",
"context",
".",
"protocol",
"(",
")",
".",
"restore",
"(",
"primary",
",",
"RestoreRequest",
".",
"request",
"(",
"context",
".",
"descriptor",
"(",
")",
",",
"context",
".",
"currentTerm",
"(",
")",
")",
")",
".",
"whenCompleteAsync",
"(",
"(",
"response",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
"&&",
"response",
".",
"status",
"(",
")",
"==",
"PrimaryBackupResponse",
".",
"Status",
".",
"OK",
")",
"{",
"context",
".",
"resetIndex",
"(",
"response",
".",
"index",
"(",
")",
",",
"response",
".",
"timestamp",
"(",
")",
")",
";",
"Buffer",
"buffer",
"=",
"HeapBuffer",
".",
"wrap",
"(",
"response",
".",
"data",
"(",
")",
")",
";",
"int",
"sessions",
"=",
"buffer",
".",
"readInt",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"sessions",
";",
"i",
"++",
")",
"{",
"context",
".",
"getOrCreateSession",
"(",
"buffer",
".",
"readLong",
"(",
")",
",",
"MemberId",
".",
"from",
"(",
"buffer",
".",
"readString",
"(",
")",
")",
")",
";",
"}",
"context",
".",
"service",
"(",
")",
".",
"restore",
"(",
"new",
"DefaultBackupInput",
"(",
"buffer",
",",
"context",
".",
"service",
"(",
")",
".",
"serializer",
"(",
")",
")",
")",
";",
"operations",
".",
"clear",
"(",
")",
";",
"}",
"}",
",",
"context",
".",
"threadContext",
"(",
")",
")",
";",
"}"
] | Requests a restore from the primary. | [
"Requests",
"a",
"restore",
"from",
"the",
"primary",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/BackupRole.java#L160-L176 |
27,318 | atomix/atomix | rest/src/main/java/io/atomix/rest/resources/EventsResource.java | EventsResource.getEventLogName | private String getEventLogName(String subject, String id) {
return String.format("%s-%s", subject, id);
} | java | private String getEventLogName(String subject, String id) {
return String.format("%s-%s", subject, id);
} | [
"private",
"String",
"getEventLogName",
"(",
"String",
"subject",
",",
"String",
"id",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"%s-%s\"",
",",
"subject",
",",
"id",
")",
";",
"}"
] | Returns an event log name. | [
"Returns",
"an",
"event",
"log",
"name",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/rest/src/main/java/io/atomix/rest/resources/EventsResource.java#L58-L60 |
27,319 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/proxy/impl/LogProxySession.java | LogProxySession.getOrCreateSession | private Session getOrCreateSession(SessionId sessionId) {
Session session = sessions.get(sessionId);
if (session == null) {
session = new LocalSession(sessionId, name(), type(), null, service.serializer());
sessions.put(session.sessionId(), session);
service.register(session);
}
return session;
} | java | private Session getOrCreateSession(SessionId sessionId) {
Session session = sessions.get(sessionId);
if (session == null) {
session = new LocalSession(sessionId, name(), type(), null, service.serializer());
sessions.put(session.sessionId(), session);
service.register(session);
}
return session;
} | [
"private",
"Session",
"getOrCreateSession",
"(",
"SessionId",
"sessionId",
")",
"{",
"Session",
"session",
"=",
"sessions",
".",
"get",
"(",
"sessionId",
")",
";",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"session",
"=",
"new",
"LocalSession",
"(",
"sessionId",
",",
"name",
"(",
")",
",",
"type",
"(",
")",
",",
"null",
",",
"service",
".",
"serializer",
"(",
")",
")",
";",
"sessions",
".",
"put",
"(",
"session",
".",
"sessionId",
"(",
")",
",",
"session",
")",
";",
"service",
".",
"register",
"(",
"session",
")",
";",
"}",
"return",
"session",
";",
"}"
] | Gets or creates a session.
@param sessionId the session identifier
@return the session | [
"Gets",
"or",
"creates",
"a",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/proxy/impl/LogProxySession.java#L170-L178 |
27,320 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/proxy/impl/LogProxySession.java | LogProxySession.consume | @SuppressWarnings("unchecked")
private void consume(LogRecord record) {
// Decode the raw log operation from the record.
LogOperation operation = decodeInternal(record.value());
// If this operation is not destined for this primitive, ignore it.
// TODO: If multiple primitives of different types are created and destroyed on the same distributed log,
// we need to be able to differentiate between different instances of a service by the service ID.
if (!operation.primitive().equals(name())) {
return;
}
// Create a session from the log record.
Session session = getOrCreateSession(operation.sessionId());
// Update the local context for the service.
currentIndex = record.index();
currentSession = session;
currentOperation = operation.operationId().type();
currentTimestamp = record.timestamp();
// Apply the operation to the service.
byte[] output = service.apply(new DefaultCommit<>(
currentIndex,
operation.operationId(),
operation.operation(),
currentSession,
currentTimestamp));
// If the operation session matches the local session, complete the write future.
if (operation.sessionId().equals(this.session.sessionId())) {
CompletableFuture future = writeFutures.remove(operation.operationIndex());
if (future != null) {
future.complete(decode(output));
}
}
// Iterate through pending reads and complete any reads at indexes less than or equal to the applied index.
PendingRead pendingRead = pendingReads.peek();
while (pendingRead != null && pendingRead.index <= record.index()) {
session = getOrCreateSession(this.session.sessionId());
currentSession = session;
currentOperation = OperationType.QUERY;
try {
output = service.apply(new DefaultCommit<>(
currentIndex,
pendingRead.operationId,
pendingRead.bytes,
session,
currentTimestamp));
pendingRead.future.complete(output);
} catch (Exception e) {
pendingRead.future.completeExceptionally(new PrimitiveException.ServiceException());
}
pendingReads.remove();
pendingRead = pendingReads.peek();
}
} | java | @SuppressWarnings("unchecked")
private void consume(LogRecord record) {
// Decode the raw log operation from the record.
LogOperation operation = decodeInternal(record.value());
// If this operation is not destined for this primitive, ignore it.
// TODO: If multiple primitives of different types are created and destroyed on the same distributed log,
// we need to be able to differentiate between different instances of a service by the service ID.
if (!operation.primitive().equals(name())) {
return;
}
// Create a session from the log record.
Session session = getOrCreateSession(operation.sessionId());
// Update the local context for the service.
currentIndex = record.index();
currentSession = session;
currentOperation = operation.operationId().type();
currentTimestamp = record.timestamp();
// Apply the operation to the service.
byte[] output = service.apply(new DefaultCommit<>(
currentIndex,
operation.operationId(),
operation.operation(),
currentSession,
currentTimestamp));
// If the operation session matches the local session, complete the write future.
if (operation.sessionId().equals(this.session.sessionId())) {
CompletableFuture future = writeFutures.remove(operation.operationIndex());
if (future != null) {
future.complete(decode(output));
}
}
// Iterate through pending reads and complete any reads at indexes less than or equal to the applied index.
PendingRead pendingRead = pendingReads.peek();
while (pendingRead != null && pendingRead.index <= record.index()) {
session = getOrCreateSession(this.session.sessionId());
currentSession = session;
currentOperation = OperationType.QUERY;
try {
output = service.apply(new DefaultCommit<>(
currentIndex,
pendingRead.operationId,
pendingRead.bytes,
session,
currentTimestamp));
pendingRead.future.complete(output);
} catch (Exception e) {
pendingRead.future.completeExceptionally(new PrimitiveException.ServiceException());
}
pendingReads.remove();
pendingRead = pendingReads.peek();
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"void",
"consume",
"(",
"LogRecord",
"record",
")",
"{",
"// Decode the raw log operation from the record.",
"LogOperation",
"operation",
"=",
"decodeInternal",
"(",
"record",
".",
"value",
"(",
")",
")",
";",
"// If this operation is not destined for this primitive, ignore it.",
"// TODO: If multiple primitives of different types are created and destroyed on the same distributed log,",
"// we need to be able to differentiate between different instances of a service by the service ID.",
"if",
"(",
"!",
"operation",
".",
"primitive",
"(",
")",
".",
"equals",
"(",
"name",
"(",
")",
")",
")",
"{",
"return",
";",
"}",
"// Create a session from the log record.",
"Session",
"session",
"=",
"getOrCreateSession",
"(",
"operation",
".",
"sessionId",
"(",
")",
")",
";",
"// Update the local context for the service.",
"currentIndex",
"=",
"record",
".",
"index",
"(",
")",
";",
"currentSession",
"=",
"session",
";",
"currentOperation",
"=",
"operation",
".",
"operationId",
"(",
")",
".",
"type",
"(",
")",
";",
"currentTimestamp",
"=",
"record",
".",
"timestamp",
"(",
")",
";",
"// Apply the operation to the service.",
"byte",
"[",
"]",
"output",
"=",
"service",
".",
"apply",
"(",
"new",
"DefaultCommit",
"<>",
"(",
"currentIndex",
",",
"operation",
".",
"operationId",
"(",
")",
",",
"operation",
".",
"operation",
"(",
")",
",",
"currentSession",
",",
"currentTimestamp",
")",
")",
";",
"// If the operation session matches the local session, complete the write future.",
"if",
"(",
"operation",
".",
"sessionId",
"(",
")",
".",
"equals",
"(",
"this",
".",
"session",
".",
"sessionId",
"(",
")",
")",
")",
"{",
"CompletableFuture",
"future",
"=",
"writeFutures",
".",
"remove",
"(",
"operation",
".",
"operationIndex",
"(",
")",
")",
";",
"if",
"(",
"future",
"!=",
"null",
")",
"{",
"future",
".",
"complete",
"(",
"decode",
"(",
"output",
")",
")",
";",
"}",
"}",
"// Iterate through pending reads and complete any reads at indexes less than or equal to the applied index.",
"PendingRead",
"pendingRead",
"=",
"pendingReads",
".",
"peek",
"(",
")",
";",
"while",
"(",
"pendingRead",
"!=",
"null",
"&&",
"pendingRead",
".",
"index",
"<=",
"record",
".",
"index",
"(",
")",
")",
"{",
"session",
"=",
"getOrCreateSession",
"(",
"this",
".",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"currentSession",
"=",
"session",
";",
"currentOperation",
"=",
"OperationType",
".",
"QUERY",
";",
"try",
"{",
"output",
"=",
"service",
".",
"apply",
"(",
"new",
"DefaultCommit",
"<>",
"(",
"currentIndex",
",",
"pendingRead",
".",
"operationId",
",",
"pendingRead",
".",
"bytes",
",",
"session",
",",
"currentTimestamp",
")",
")",
";",
"pendingRead",
".",
"future",
".",
"complete",
"(",
"output",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"pendingRead",
".",
"future",
".",
"completeExceptionally",
"(",
"new",
"PrimitiveException",
".",
"ServiceException",
"(",
")",
")",
";",
"}",
"pendingReads",
".",
"remove",
"(",
")",
";",
"pendingRead",
"=",
"pendingReads",
".",
"peek",
"(",
")",
";",
"}",
"}"
] | Consumes a record from the log.
@param record the record to consume | [
"Consumes",
"a",
"record",
"from",
"the",
"log",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/proxy/impl/LogProxySession.java#L185-L242 |
27,321 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.valuesEqual | protected boolean valuesEqual(MapEntryValue oldValue, MapEntryValue newValue) {
return (oldValue == null && newValue == null)
|| (oldValue != null && newValue != null && valuesEqual(oldValue.value(), newValue.value()));
} | java | protected boolean valuesEqual(MapEntryValue oldValue, MapEntryValue newValue) {
return (oldValue == null && newValue == null)
|| (oldValue != null && newValue != null && valuesEqual(oldValue.value(), newValue.value()));
} | [
"protected",
"boolean",
"valuesEqual",
"(",
"MapEntryValue",
"oldValue",
",",
"MapEntryValue",
"newValue",
")",
"{",
"return",
"(",
"oldValue",
"==",
"null",
"&&",
"newValue",
"==",
"null",
")",
"||",
"(",
"oldValue",
"!=",
"null",
"&&",
"newValue",
"!=",
"null",
"&&",
"valuesEqual",
"(",
"oldValue",
".",
"value",
"(",
")",
",",
"newValue",
".",
"value",
"(",
")",
")",
")",
";",
"}"
] | Returns a boolean indicating whether the given MapEntryValues are equal.
@param oldValue the first value to compare
@param newValue the second value to compare
@return indicates whether the two values are equal | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"given",
"MapEntryValues",
"are",
"equal",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L222-L225 |
27,322 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.valuesEqual | protected boolean valuesEqual(byte[] oldValue, byte[] newValue) {
return (oldValue == null && newValue == null)
|| (oldValue != null && newValue != null && Arrays.equals(oldValue, newValue));
} | java | protected boolean valuesEqual(byte[] oldValue, byte[] newValue) {
return (oldValue == null && newValue == null)
|| (oldValue != null && newValue != null && Arrays.equals(oldValue, newValue));
} | [
"protected",
"boolean",
"valuesEqual",
"(",
"byte",
"[",
"]",
"oldValue",
",",
"byte",
"[",
"]",
"newValue",
")",
"{",
"return",
"(",
"oldValue",
"==",
"null",
"&&",
"newValue",
"==",
"null",
")",
"||",
"(",
"oldValue",
"!=",
"null",
"&&",
"newValue",
"!=",
"null",
"&&",
"Arrays",
".",
"equals",
"(",
"oldValue",
",",
"newValue",
")",
")",
";",
"}"
] | Returns a boolean indicating whether the given entry values are equal.
@param oldValue the first value to compare
@param newValue the second value to compare
@return indicates whether the two values are equal | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"given",
"entry",
"values",
"are",
"equal",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L234-L237 |
27,323 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.valueIsNull | protected boolean valueIsNull(MapEntryValue value) {
return value == null || value.type() == MapEntryValue.Type.TOMBSTONE;
} | java | protected boolean valueIsNull(MapEntryValue value) {
return value == null || value.type() == MapEntryValue.Type.TOMBSTONE;
} | [
"protected",
"boolean",
"valueIsNull",
"(",
"MapEntryValue",
"value",
")",
"{",
"return",
"value",
"==",
"null",
"||",
"value",
".",
"type",
"(",
")",
"==",
"MapEntryValue",
".",
"Type",
".",
"TOMBSTONE",
";",
"}"
] | Returns a boolean indicating whether the given MapEntryValue is null or a tombstone.
@param value the value to check
@return indicates whether the given value is null or is a tombstone | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"given",
"MapEntryValue",
"is",
"null",
"or",
"a",
"tombstone",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L245-L247 |
27,324 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.putValue | protected void putValue(K key, MapEntryValue value) {
MapEntryValue oldValue = entries().put(key, value);
cancelTtl(oldValue);
scheduleTtl(key, value);
} | java | protected void putValue(K key, MapEntryValue value) {
MapEntryValue oldValue = entries().put(key, value);
cancelTtl(oldValue);
scheduleTtl(key, value);
} | [
"protected",
"void",
"putValue",
"(",
"K",
"key",
",",
"MapEntryValue",
"value",
")",
"{",
"MapEntryValue",
"oldValue",
"=",
"entries",
"(",
")",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"cancelTtl",
"(",
"oldValue",
")",
";",
"scheduleTtl",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Updates the given value.
@param key the key to update
@param value the value to update | [
"Updates",
"the",
"given",
"value",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L255-L259 |
27,325 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.scheduleTtl | protected void scheduleTtl(K key, MapEntryValue value) {
if (value.ttl() > 0) {
value.timer = getScheduler().schedule(Duration.ofMillis(value.ttl()), () -> {
entries().remove(key, value);
publish(new AtomicMapEvent<>(AtomicMapEvent.Type.REMOVE, key, null, toVersioned(value)));
});
}
} | java | protected void scheduleTtl(K key, MapEntryValue value) {
if (value.ttl() > 0) {
value.timer = getScheduler().schedule(Duration.ofMillis(value.ttl()), () -> {
entries().remove(key, value);
publish(new AtomicMapEvent<>(AtomicMapEvent.Type.REMOVE, key, null, toVersioned(value)));
});
}
} | [
"protected",
"void",
"scheduleTtl",
"(",
"K",
"key",
",",
"MapEntryValue",
"value",
")",
"{",
"if",
"(",
"value",
".",
"ttl",
"(",
")",
">",
"0",
")",
"{",
"value",
".",
"timer",
"=",
"getScheduler",
"(",
")",
".",
"schedule",
"(",
"Duration",
".",
"ofMillis",
"(",
"value",
".",
"ttl",
"(",
")",
")",
",",
"(",
")",
"->",
"{",
"entries",
"(",
")",
".",
"remove",
"(",
"key",
",",
"value",
")",
";",
"publish",
"(",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"REMOVE",
",",
"key",
",",
"null",
",",
"toVersioned",
"(",
"value",
")",
")",
")",
";",
"}",
")",
";",
"}",
"}"
] | Schedules the TTL for the given value.
@param value the value for which to schedule the TTL | [
"Schedules",
"the",
"TTL",
"for",
"the",
"given",
"value",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L266-L273 |
27,326 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.cancelTtl | protected void cancelTtl(MapEntryValue value) {
if (value != null && value.timer != null) {
value.timer.cancel();
}
} | java | protected void cancelTtl(MapEntryValue value) {
if (value != null && value.timer != null) {
value.timer.cancel();
}
} | [
"protected",
"void",
"cancelTtl",
"(",
"MapEntryValue",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
"&&",
"value",
".",
"timer",
"!=",
"null",
")",
"{",
"value",
".",
"timer",
".",
"cancel",
"(",
")",
";",
"}",
"}"
] | Cancels the TTL for the given value.
@param value the value for which to cancel the TTL | [
"Cancels",
"the",
"TTL",
"for",
"the",
"given",
"value",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L280-L284 |
27,327 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.removeIf | private MapEntryUpdateResult<K, byte[]> removeIf(long index, K key, Predicate<MapEntryValue> predicate) {
MapEntryValue value = entries().get(key);
// If the value does not exist or doesn't match the predicate, return a PRECONDITION_FAILED error.
if (valueIsNull(value) || !predicate.test(value)) {
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.PRECONDITION_FAILED, index, key, null);
}
// If the key has been locked by a transaction, return a WRITE_LOCK error.
if (preparedKeys.contains(key)) {
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.WRITE_LOCK, index, key, null);
}
// If no transactions are active, remove the key. Otherwise, replace it with a tombstone.
if (activeTransactions.isEmpty()) {
entries().remove(key);
} else {
entries().put(key, new MapEntryValue(MapEntryValue.Type.TOMBSTONE, index, null, 0, 0));
}
// Cancel the timer if one is scheduled.
cancelTtl(value);
Versioned<byte[]> result = toVersioned(value);
publish(new AtomicMapEvent<>(AtomicMapEvent.Type.REMOVE, key, null, result));
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.OK, index, key, result);
} | java | private MapEntryUpdateResult<K, byte[]> removeIf(long index, K key, Predicate<MapEntryValue> predicate) {
MapEntryValue value = entries().get(key);
// If the value does not exist or doesn't match the predicate, return a PRECONDITION_FAILED error.
if (valueIsNull(value) || !predicate.test(value)) {
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.PRECONDITION_FAILED, index, key, null);
}
// If the key has been locked by a transaction, return a WRITE_LOCK error.
if (preparedKeys.contains(key)) {
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.WRITE_LOCK, index, key, null);
}
// If no transactions are active, remove the key. Otherwise, replace it with a tombstone.
if (activeTransactions.isEmpty()) {
entries().remove(key);
} else {
entries().put(key, new MapEntryValue(MapEntryValue.Type.TOMBSTONE, index, null, 0, 0));
}
// Cancel the timer if one is scheduled.
cancelTtl(value);
Versioned<byte[]> result = toVersioned(value);
publish(new AtomicMapEvent<>(AtomicMapEvent.Type.REMOVE, key, null, result));
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.OK, index, key, result);
} | [
"private",
"MapEntryUpdateResult",
"<",
"K",
",",
"byte",
"[",
"]",
">",
"removeIf",
"(",
"long",
"index",
",",
"K",
"key",
",",
"Predicate",
"<",
"MapEntryValue",
">",
"predicate",
")",
"{",
"MapEntryValue",
"value",
"=",
"entries",
"(",
")",
".",
"get",
"(",
"key",
")",
";",
"// If the value does not exist or doesn't match the predicate, return a PRECONDITION_FAILED error.",
"if",
"(",
"valueIsNull",
"(",
"value",
")",
"||",
"!",
"predicate",
".",
"test",
"(",
"value",
")",
")",
"{",
"return",
"new",
"MapEntryUpdateResult",
"<>",
"(",
"MapEntryUpdateResult",
".",
"Status",
".",
"PRECONDITION_FAILED",
",",
"index",
",",
"key",
",",
"null",
")",
";",
"}",
"// If the key has been locked by a transaction, return a WRITE_LOCK error.",
"if",
"(",
"preparedKeys",
".",
"contains",
"(",
"key",
")",
")",
"{",
"return",
"new",
"MapEntryUpdateResult",
"<>",
"(",
"MapEntryUpdateResult",
".",
"Status",
".",
"WRITE_LOCK",
",",
"index",
",",
"key",
",",
"null",
")",
";",
"}",
"// If no transactions are active, remove the key. Otherwise, replace it with a tombstone.",
"if",
"(",
"activeTransactions",
".",
"isEmpty",
"(",
")",
")",
"{",
"entries",
"(",
")",
".",
"remove",
"(",
"key",
")",
";",
"}",
"else",
"{",
"entries",
"(",
")",
".",
"put",
"(",
"key",
",",
"new",
"MapEntryValue",
"(",
"MapEntryValue",
".",
"Type",
".",
"TOMBSTONE",
",",
"index",
",",
"null",
",",
"0",
",",
"0",
")",
")",
";",
"}",
"// Cancel the timer if one is scheduled.",
"cancelTtl",
"(",
"value",
")",
";",
"Versioned",
"<",
"byte",
"[",
"]",
">",
"result",
"=",
"toVersioned",
"(",
"value",
")",
";",
"publish",
"(",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"REMOVE",
",",
"key",
",",
"null",
",",
"result",
")",
")",
";",
"return",
"new",
"MapEntryUpdateResult",
"<>",
"(",
"MapEntryUpdateResult",
".",
"Status",
".",
"OK",
",",
"index",
",",
"key",
",",
"result",
")",
";",
"}"
] | Handles a remove commit.
@param index the commit index
@param key the key to remove
@param predicate predicate to determine whether to remove the entry
@return map entry update result | [
"Handles",
"a",
"remove",
"commit",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L406-L432 |
27,328 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.replaceIf | private MapEntryUpdateResult<K, byte[]> replaceIf(
long index, K key, MapEntryValue newValue, Predicate<MapEntryValue> predicate) {
MapEntryValue oldValue = entries().get(key);
// If the key is not set or the current value doesn't match the predicate, return a PRECONDITION_FAILED error.
if (valueIsNull(oldValue) || !predicate.test(oldValue)) {
return new MapEntryUpdateResult<>(
MapEntryUpdateResult.Status.PRECONDITION_FAILED,
index,
key,
toVersioned(oldValue));
}
// If the key has been locked by a transaction, return a WRITE_LOCK error.
if (preparedKeys.contains(key)) {
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.WRITE_LOCK, index, key, null);
}
putValue(key, newValue);
Versioned<byte[]> result = toVersioned(oldValue);
publish(new AtomicMapEvent<>(AtomicMapEvent.Type.UPDATE, key, toVersioned(newValue), result));
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.OK, index, key, result);
} | java | private MapEntryUpdateResult<K, byte[]> replaceIf(
long index, K key, MapEntryValue newValue, Predicate<MapEntryValue> predicate) {
MapEntryValue oldValue = entries().get(key);
// If the key is not set or the current value doesn't match the predicate, return a PRECONDITION_FAILED error.
if (valueIsNull(oldValue) || !predicate.test(oldValue)) {
return new MapEntryUpdateResult<>(
MapEntryUpdateResult.Status.PRECONDITION_FAILED,
index,
key,
toVersioned(oldValue));
}
// If the key has been locked by a transaction, return a WRITE_LOCK error.
if (preparedKeys.contains(key)) {
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.WRITE_LOCK, index, key, null);
}
putValue(key, newValue);
Versioned<byte[]> result = toVersioned(oldValue);
publish(new AtomicMapEvent<>(AtomicMapEvent.Type.UPDATE, key, toVersioned(newValue), result));
return new MapEntryUpdateResult<>(MapEntryUpdateResult.Status.OK, index, key, result);
} | [
"private",
"MapEntryUpdateResult",
"<",
"K",
",",
"byte",
"[",
"]",
">",
"replaceIf",
"(",
"long",
"index",
",",
"K",
"key",
",",
"MapEntryValue",
"newValue",
",",
"Predicate",
"<",
"MapEntryValue",
">",
"predicate",
")",
"{",
"MapEntryValue",
"oldValue",
"=",
"entries",
"(",
")",
".",
"get",
"(",
"key",
")",
";",
"// If the key is not set or the current value doesn't match the predicate, return a PRECONDITION_FAILED error.",
"if",
"(",
"valueIsNull",
"(",
"oldValue",
")",
"||",
"!",
"predicate",
".",
"test",
"(",
"oldValue",
")",
")",
"{",
"return",
"new",
"MapEntryUpdateResult",
"<>",
"(",
"MapEntryUpdateResult",
".",
"Status",
".",
"PRECONDITION_FAILED",
",",
"index",
",",
"key",
",",
"toVersioned",
"(",
"oldValue",
")",
")",
";",
"}",
"// If the key has been locked by a transaction, return a WRITE_LOCK error.",
"if",
"(",
"preparedKeys",
".",
"contains",
"(",
"key",
")",
")",
"{",
"return",
"new",
"MapEntryUpdateResult",
"<>",
"(",
"MapEntryUpdateResult",
".",
"Status",
".",
"WRITE_LOCK",
",",
"index",
",",
"key",
",",
"null",
")",
";",
"}",
"putValue",
"(",
"key",
",",
"newValue",
")",
";",
"Versioned",
"<",
"byte",
"[",
"]",
">",
"result",
"=",
"toVersioned",
"(",
"oldValue",
")",
";",
"publish",
"(",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"UPDATE",
",",
"key",
",",
"toVersioned",
"(",
"newValue",
")",
",",
"result",
")",
")",
";",
"return",
"new",
"MapEntryUpdateResult",
"<>",
"(",
"MapEntryUpdateResult",
".",
"Status",
".",
"OK",
",",
"index",
",",
"key",
",",
"result",
")",
";",
"}"
] | Handles a replace commit.
@param index the commit index
@param key the key to replace
@param newValue the value with which to replace the key
@param predicate a predicate to determine whether to replace the key
@return map entry update result | [
"Handles",
"a",
"replace",
"commit",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L459-L481 |
27,329 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.commitTransaction | private CommitResult commitTransaction(TransactionScope<K> transactionScope) {
TransactionLog<MapUpdate<K, byte[]>> transactionLog = transactionScope.transactionLog();
boolean retainTombstones = !activeTransactions.isEmpty();
List<AtomicMapEvent<K, byte[]>> eventsToPublish = Lists.newArrayList();
for (MapUpdate<K, byte[]> record : transactionLog.records()) {
if (record.type() == MapUpdate.Type.VERSION_MATCH) {
continue;
}
K key = record.key();
checkState(preparedKeys.remove(key), "key is not prepared");
if (record.type() == MapUpdate.Type.LOCK) {
continue;
}
MapEntryValue previousValue = entries().remove(key);
// Cancel the previous timer if set.
cancelTtl(previousValue);
MapEntryValue newValue = null;
// If the record is not a delete, create a transactional commit.
if (record.type() != MapUpdate.Type.REMOVE_IF_VERSION_MATCH) {
newValue = new MapEntryValue(MapEntryValue.Type.VALUE, currentVersion, record.value(), 0, 0);
} else if (retainTombstones) {
// For deletes, if tombstones need to be retained then create and store a tombstone commit.
newValue = new MapEntryValue(MapEntryValue.Type.TOMBSTONE, currentVersion, null, 0, 0);
}
AtomicMapEvent<K, byte[]> event;
if (newValue != null) {
entries().put(key, newValue);
if (!valueIsNull(newValue)) {
if (!valueIsNull(previousValue)) {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.UPDATE,
key,
toVersioned(newValue),
toVersioned(previousValue));
} else {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.INSERT,
key,
toVersioned(newValue),
null);
}
} else {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.REMOVE,
key,
null,
toVersioned(previousValue));
}
} else {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.REMOVE,
key,
null,
toVersioned(previousValue));
}
eventsToPublish.add(event);
}
publish(eventsToPublish);
return CommitResult.OK;
} | java | private CommitResult commitTransaction(TransactionScope<K> transactionScope) {
TransactionLog<MapUpdate<K, byte[]>> transactionLog = transactionScope.transactionLog();
boolean retainTombstones = !activeTransactions.isEmpty();
List<AtomicMapEvent<K, byte[]>> eventsToPublish = Lists.newArrayList();
for (MapUpdate<K, byte[]> record : transactionLog.records()) {
if (record.type() == MapUpdate.Type.VERSION_MATCH) {
continue;
}
K key = record.key();
checkState(preparedKeys.remove(key), "key is not prepared");
if (record.type() == MapUpdate.Type.LOCK) {
continue;
}
MapEntryValue previousValue = entries().remove(key);
// Cancel the previous timer if set.
cancelTtl(previousValue);
MapEntryValue newValue = null;
// If the record is not a delete, create a transactional commit.
if (record.type() != MapUpdate.Type.REMOVE_IF_VERSION_MATCH) {
newValue = new MapEntryValue(MapEntryValue.Type.VALUE, currentVersion, record.value(), 0, 0);
} else if (retainTombstones) {
// For deletes, if tombstones need to be retained then create and store a tombstone commit.
newValue = new MapEntryValue(MapEntryValue.Type.TOMBSTONE, currentVersion, null, 0, 0);
}
AtomicMapEvent<K, byte[]> event;
if (newValue != null) {
entries().put(key, newValue);
if (!valueIsNull(newValue)) {
if (!valueIsNull(previousValue)) {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.UPDATE,
key,
toVersioned(newValue),
toVersioned(previousValue));
} else {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.INSERT,
key,
toVersioned(newValue),
null);
}
} else {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.REMOVE,
key,
null,
toVersioned(previousValue));
}
} else {
event = new AtomicMapEvent<>(
AtomicMapEvent.Type.REMOVE,
key,
null,
toVersioned(previousValue));
}
eventsToPublish.add(event);
}
publish(eventsToPublish);
return CommitResult.OK;
} | [
"private",
"CommitResult",
"commitTransaction",
"(",
"TransactionScope",
"<",
"K",
">",
"transactionScope",
")",
"{",
"TransactionLog",
"<",
"MapUpdate",
"<",
"K",
",",
"byte",
"[",
"]",
">",
">",
"transactionLog",
"=",
"transactionScope",
".",
"transactionLog",
"(",
")",
";",
"boolean",
"retainTombstones",
"=",
"!",
"activeTransactions",
".",
"isEmpty",
"(",
")",
";",
"List",
"<",
"AtomicMapEvent",
"<",
"K",
",",
"byte",
"[",
"]",
">",
">",
"eventsToPublish",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"MapUpdate",
"<",
"K",
",",
"byte",
"[",
"]",
">",
"record",
":",
"transactionLog",
".",
"records",
"(",
")",
")",
"{",
"if",
"(",
"record",
".",
"type",
"(",
")",
"==",
"MapUpdate",
".",
"Type",
".",
"VERSION_MATCH",
")",
"{",
"continue",
";",
"}",
"K",
"key",
"=",
"record",
".",
"key",
"(",
")",
";",
"checkState",
"(",
"preparedKeys",
".",
"remove",
"(",
"key",
")",
",",
"\"key is not prepared\"",
")",
";",
"if",
"(",
"record",
".",
"type",
"(",
")",
"==",
"MapUpdate",
".",
"Type",
".",
"LOCK",
")",
"{",
"continue",
";",
"}",
"MapEntryValue",
"previousValue",
"=",
"entries",
"(",
")",
".",
"remove",
"(",
"key",
")",
";",
"// Cancel the previous timer if set.",
"cancelTtl",
"(",
"previousValue",
")",
";",
"MapEntryValue",
"newValue",
"=",
"null",
";",
"// If the record is not a delete, create a transactional commit.",
"if",
"(",
"record",
".",
"type",
"(",
")",
"!=",
"MapUpdate",
".",
"Type",
".",
"REMOVE_IF_VERSION_MATCH",
")",
"{",
"newValue",
"=",
"new",
"MapEntryValue",
"(",
"MapEntryValue",
".",
"Type",
".",
"VALUE",
",",
"currentVersion",
",",
"record",
".",
"value",
"(",
")",
",",
"0",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"retainTombstones",
")",
"{",
"// For deletes, if tombstones need to be retained then create and store a tombstone commit.",
"newValue",
"=",
"new",
"MapEntryValue",
"(",
"MapEntryValue",
".",
"Type",
".",
"TOMBSTONE",
",",
"currentVersion",
",",
"null",
",",
"0",
",",
"0",
")",
";",
"}",
"AtomicMapEvent",
"<",
"K",
",",
"byte",
"[",
"]",
">",
"event",
";",
"if",
"(",
"newValue",
"!=",
"null",
")",
"{",
"entries",
"(",
")",
".",
"put",
"(",
"key",
",",
"newValue",
")",
";",
"if",
"(",
"!",
"valueIsNull",
"(",
"newValue",
")",
")",
"{",
"if",
"(",
"!",
"valueIsNull",
"(",
"previousValue",
")",
")",
"{",
"event",
"=",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"UPDATE",
",",
"key",
",",
"toVersioned",
"(",
"newValue",
")",
",",
"toVersioned",
"(",
"previousValue",
")",
")",
";",
"}",
"else",
"{",
"event",
"=",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"INSERT",
",",
"key",
",",
"toVersioned",
"(",
"newValue",
")",
",",
"null",
")",
";",
"}",
"}",
"else",
"{",
"event",
"=",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"REMOVE",
",",
"key",
",",
"null",
",",
"toVersioned",
"(",
"previousValue",
")",
")",
";",
"}",
"}",
"else",
"{",
"event",
"=",
"new",
"AtomicMapEvent",
"<>",
"(",
"AtomicMapEvent",
".",
"Type",
".",
"REMOVE",
",",
"key",
",",
"null",
",",
"toVersioned",
"(",
"previousValue",
")",
")",
";",
"}",
"eventsToPublish",
".",
"add",
"(",
"event",
")",
";",
"}",
"publish",
"(",
"eventsToPublish",
")",
";",
"return",
"CommitResult",
".",
"OK",
";",
"}"
] | Applies committed operations to the state machine. | [
"Applies",
"committed",
"operations",
"to",
"the",
"state",
"machine",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L754-L821 |
27,330 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.discardTombstones | private void discardTombstones() {
if (activeTransactions.isEmpty()) {
Iterator<Map.Entry<K, MapEntryValue>> iterator = entries().entrySet().iterator();
while (iterator.hasNext()) {
MapEntryValue value = iterator.next().getValue();
if (value.type() == MapEntryValue.Type.TOMBSTONE) {
iterator.remove();
}
}
} else {
long lowWaterMark = activeTransactions.values().stream()
.mapToLong(TransactionScope::version)
.min().getAsLong();
Iterator<Map.Entry<K, MapEntryValue>> iterator = entries().entrySet().iterator();
while (iterator.hasNext()) {
MapEntryValue value = iterator.next().getValue();
if (value.type() == MapEntryValue.Type.TOMBSTONE && value.version < lowWaterMark) {
iterator.remove();
}
}
}
} | java | private void discardTombstones() {
if (activeTransactions.isEmpty()) {
Iterator<Map.Entry<K, MapEntryValue>> iterator = entries().entrySet().iterator();
while (iterator.hasNext()) {
MapEntryValue value = iterator.next().getValue();
if (value.type() == MapEntryValue.Type.TOMBSTONE) {
iterator.remove();
}
}
} else {
long lowWaterMark = activeTransactions.values().stream()
.mapToLong(TransactionScope::version)
.min().getAsLong();
Iterator<Map.Entry<K, MapEntryValue>> iterator = entries().entrySet().iterator();
while (iterator.hasNext()) {
MapEntryValue value = iterator.next().getValue();
if (value.type() == MapEntryValue.Type.TOMBSTONE && value.version < lowWaterMark) {
iterator.remove();
}
}
}
} | [
"private",
"void",
"discardTombstones",
"(",
")",
"{",
"if",
"(",
"activeTransactions",
".",
"isEmpty",
"(",
")",
")",
"{",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"MapEntryValue",
">",
">",
"iterator",
"=",
"entries",
"(",
")",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"MapEntryValue",
"value",
"=",
"iterator",
".",
"next",
"(",
")",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
".",
"type",
"(",
")",
"==",
"MapEntryValue",
".",
"Type",
".",
"TOMBSTONE",
")",
"{",
"iterator",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}",
"else",
"{",
"long",
"lowWaterMark",
"=",
"activeTransactions",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"mapToLong",
"(",
"TransactionScope",
"::",
"version",
")",
".",
"min",
"(",
")",
".",
"getAsLong",
"(",
")",
";",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"MapEntryValue",
">",
">",
"iterator",
"=",
"entries",
"(",
")",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"MapEntryValue",
"value",
"=",
"iterator",
".",
"next",
"(",
")",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
".",
"type",
"(",
")",
"==",
"MapEntryValue",
".",
"Type",
".",
"TOMBSTONE",
"&&",
"value",
".",
"version",
"<",
"lowWaterMark",
")",
"{",
"iterator",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Discards tombstones no longer needed by active transactions. | [
"Discards",
"tombstones",
"no",
"longer",
"needed",
"by",
"active",
"transactions",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L849-L870 |
27,331 | atomix/atomix | core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java | AbstractAtomicMapService.publish | private void publish(List<AtomicMapEvent<K, byte[]>> events) {
listeners.forEach(listener -> events.forEach(event -> getSession(listener).accept(client -> client.change(event))));
} | java | private void publish(List<AtomicMapEvent<K, byte[]>> events) {
listeners.forEach(listener -> events.forEach(event -> getSession(listener).accept(client -> client.change(event))));
} | [
"private",
"void",
"publish",
"(",
"List",
"<",
"AtomicMapEvent",
"<",
"K",
",",
"byte",
"[",
"]",
">",
">",
"events",
")",
"{",
"listeners",
".",
"forEach",
"(",
"listener",
"->",
"events",
".",
"forEach",
"(",
"event",
"->",
"getSession",
"(",
"listener",
")",
".",
"accept",
"(",
"client",
"->",
"client",
".",
"change",
"(",
"event",
")",
")",
")",
")",
";",
"}"
] | Publishes events to listeners.
@param events list of map event to publish | [
"Publishes",
"events",
"to",
"listeners",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/map/impl/AbstractAtomicMapService.java#L897-L899 |
27,332 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/PrimitiveBuilder.java | PrimitiveBuilder.protocol | protected PrimitiveProtocol protocol() {
PrimitiveProtocol protocol = this.protocol;
if (protocol == null) {
PrimitiveProtocolConfig<?> protocolConfig = config.getProtocolConfig();
if (protocolConfig == null) {
Collection<PartitionGroup> partitionGroups = managementService.getPartitionService().getPartitionGroups();
if (partitionGroups.size() == 1) {
protocol = partitionGroups.iterator().next().newProtocol();
} else {
String groups = Joiner.on(", ").join(partitionGroups.stream()
.map(group -> group.name())
.collect(Collectors.toList()));
throw new ConfigurationException(String.format("Primitive protocol is ambiguous: %d partition groups found (%s)", partitionGroups.size(), groups));
}
} else {
protocol = protocolConfig.getType().newProtocol(protocolConfig);
}
}
return protocol;
} | java | protected PrimitiveProtocol protocol() {
PrimitiveProtocol protocol = this.protocol;
if (protocol == null) {
PrimitiveProtocolConfig<?> protocolConfig = config.getProtocolConfig();
if (protocolConfig == null) {
Collection<PartitionGroup> partitionGroups = managementService.getPartitionService().getPartitionGroups();
if (partitionGroups.size() == 1) {
protocol = partitionGroups.iterator().next().newProtocol();
} else {
String groups = Joiner.on(", ").join(partitionGroups.stream()
.map(group -> group.name())
.collect(Collectors.toList()));
throw new ConfigurationException(String.format("Primitive protocol is ambiguous: %d partition groups found (%s)", partitionGroups.size(), groups));
}
} else {
protocol = protocolConfig.getType().newProtocol(protocolConfig);
}
}
return protocol;
} | [
"protected",
"PrimitiveProtocol",
"protocol",
"(",
")",
"{",
"PrimitiveProtocol",
"protocol",
"=",
"this",
".",
"protocol",
";",
"if",
"(",
"protocol",
"==",
"null",
")",
"{",
"PrimitiveProtocolConfig",
"<",
"?",
">",
"protocolConfig",
"=",
"config",
".",
"getProtocolConfig",
"(",
")",
";",
"if",
"(",
"protocolConfig",
"==",
"null",
")",
"{",
"Collection",
"<",
"PartitionGroup",
">",
"partitionGroups",
"=",
"managementService",
".",
"getPartitionService",
"(",
")",
".",
"getPartitionGroups",
"(",
")",
";",
"if",
"(",
"partitionGroups",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"protocol",
"=",
"partitionGroups",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"newProtocol",
"(",
")",
";",
"}",
"else",
"{",
"String",
"groups",
"=",
"Joiner",
".",
"on",
"(",
"\", \"",
")",
".",
"join",
"(",
"partitionGroups",
".",
"stream",
"(",
")",
".",
"map",
"(",
"group",
"->",
"group",
".",
"name",
"(",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
")",
";",
"throw",
"new",
"ConfigurationException",
"(",
"String",
".",
"format",
"(",
"\"Primitive protocol is ambiguous: %d partition groups found (%s)\"",
",",
"partitionGroups",
".",
"size",
"(",
")",
",",
"groups",
")",
")",
";",
"}",
"}",
"else",
"{",
"protocol",
"=",
"protocolConfig",
".",
"getType",
"(",
")",
".",
"newProtocol",
"(",
"protocolConfig",
")",
";",
"}",
"}",
"return",
"protocol",
";",
"}"
] | Returns the primitive protocol.
@return the primitive protocol | [
"Returns",
"the",
"primitive",
"protocol",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/PrimitiveBuilder.java#L114-L133 |
27,333 | atomix/atomix | core/src/main/java/io/atomix/core/tree/impl/DocumentTreeResult.java | DocumentTreeResult.ok | public static <V> DocumentTreeResult<V> ok(V result) {
return new DocumentTreeResult<V>(Status.OK, result);
} | java | public static <V> DocumentTreeResult<V> ok(V result) {
return new DocumentTreeResult<V>(Status.OK, result);
} | [
"public",
"static",
"<",
"V",
">",
"DocumentTreeResult",
"<",
"V",
">",
"ok",
"(",
"V",
"result",
")",
"{",
"return",
"new",
"DocumentTreeResult",
"<",
"V",
">",
"(",
"Status",
".",
"OK",
",",
"result",
")",
";",
"}"
] | Returns a successful result.
@param result the operation result
@param <V> the result value type
@return successful result | [
"Returns",
"a",
"successful",
"result",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/tree/impl/DocumentTreeResult.java#L78-L80 |
27,334 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/event/PrimitiveEvent.java | PrimitiveEvent.event | public static PrimitiveEvent event(EventType eventType, byte[] value) {
return new PrimitiveEvent(EventType.canonical(eventType), value);
} | java | public static PrimitiveEvent event(EventType eventType, byte[] value) {
return new PrimitiveEvent(EventType.canonical(eventType), value);
} | [
"public",
"static",
"PrimitiveEvent",
"event",
"(",
"EventType",
"eventType",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"return",
"new",
"PrimitiveEvent",
"(",
"EventType",
".",
"canonical",
"(",
"eventType",
")",
",",
"value",
")",
";",
"}"
] | Creates a new primitive event.
@param eventType the event type
@param value the event value
@return the primitive event | [
"Creates",
"a",
"new",
"primitive",
"event",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/event/PrimitiveEvent.java#L47-L49 |
27,335 | atomix/atomix | core/src/main/java/io/atomix/core/collection/impl/CollectionUpdateResult.java | CollectionUpdateResult.ok | public static <T> CollectionUpdateResult<T> ok(T result) {
return new CollectionUpdateResult<>(Status.OK, result);
} | java | public static <T> CollectionUpdateResult<T> ok(T result) {
return new CollectionUpdateResult<>(Status.OK, result);
} | [
"public",
"static",
"<",
"T",
">",
"CollectionUpdateResult",
"<",
"T",
">",
"ok",
"(",
"T",
"result",
")",
"{",
"return",
"new",
"CollectionUpdateResult",
"<>",
"(",
"Status",
".",
"OK",
",",
"result",
")",
";",
"}"
] | Returns a successful update result.
@param result the update result
@param <T> the result type
@return the successful result | [
"Returns",
"a",
"successful",
"update",
"result",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/collection/impl/CollectionUpdateResult.java#L41-L43 |
27,336 | atomix/atomix | core/src/main/java/io/atomix/core/collection/impl/CollectionUpdateResult.java | CollectionUpdateResult.noop | public static <T> CollectionUpdateResult<T> noop(T result) {
return new CollectionUpdateResult<>(Status.NOOP, result);
} | java | public static <T> CollectionUpdateResult<T> noop(T result) {
return new CollectionUpdateResult<>(Status.NOOP, result);
} | [
"public",
"static",
"<",
"T",
">",
"CollectionUpdateResult",
"<",
"T",
">",
"noop",
"(",
"T",
"result",
")",
"{",
"return",
"new",
"CollectionUpdateResult",
"<>",
"(",
"Status",
".",
"NOOP",
",",
"result",
")",
";",
"}"
] | Returns a no-op result.
@param result the update result
@param <T> the result type
@return the result | [
"Returns",
"a",
"no",
"-",
"op",
"result",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/collection/impl/CollectionUpdateResult.java#L62-L64 |
27,337 | atomix/atomix | primitive/src/main/java/io/atomix/primitive/operation/PrimitiveOperation.java | PrimitiveOperation.operation | public static PrimitiveOperation operation(OperationId id, byte[] value) {
return new PrimitiveOperation(OperationId.simplify(id), value);
} | java | public static PrimitiveOperation operation(OperationId id, byte[] value) {
return new PrimitiveOperation(OperationId.simplify(id), value);
} | [
"public",
"static",
"PrimitiveOperation",
"operation",
"(",
"OperationId",
"id",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"return",
"new",
"PrimitiveOperation",
"(",
"OperationId",
".",
"simplify",
"(",
"id",
")",
",",
"value",
")",
";",
"}"
] | Creates a new primitive operation with a simplified identifier.
@param id the operation identifier
@param value the operation value
@return the primitive operation | [
"Creates",
"a",
"new",
"primitive",
"operation",
"with",
"a",
"simplified",
"identifier",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/operation/PrimitiveOperation.java#L47-L49 |
27,338 | atomix/atomix | utils/src/main/java/io/atomix/utils/Version.java | Version.from | public static Version from(String version) {
String[] fields = version.split("[.-]", 4);
checkArgument(fields.length >= 3, "version number is invalid");
return new Version(
parseInt(fields[0]),
parseInt(fields[1]),
parseInt(fields[2]),
fields.length == 4 ? fields[3] : null);
} | java | public static Version from(String version) {
String[] fields = version.split("[.-]", 4);
checkArgument(fields.length >= 3, "version number is invalid");
return new Version(
parseInt(fields[0]),
parseInt(fields[1]),
parseInt(fields[2]),
fields.length == 4 ? fields[3] : null);
} | [
"public",
"static",
"Version",
"from",
"(",
"String",
"version",
")",
"{",
"String",
"[",
"]",
"fields",
"=",
"version",
".",
"split",
"(",
"\"[.-]\"",
",",
"4",
")",
";",
"checkArgument",
"(",
"fields",
".",
"length",
">=",
"3",
",",
"\"version number is invalid\"",
")",
";",
"return",
"new",
"Version",
"(",
"parseInt",
"(",
"fields",
"[",
"0",
"]",
")",
",",
"parseInt",
"(",
"fields",
"[",
"1",
"]",
")",
",",
"parseInt",
"(",
"fields",
"[",
"2",
"]",
")",
",",
"fields",
".",
"length",
"==",
"4",
"?",
"fields",
"[",
"3",
"]",
":",
"null",
")",
";",
"}"
] | Returns a new version from the given version string.
@param version the version string
@return the version object
@throws IllegalArgumentException if the version string is invalid | [
"Returns",
"a",
"new",
"version",
"from",
"the",
"given",
"version",
"string",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/Version.java#L37-L45 |
27,339 | atomix/atomix | utils/src/main/java/io/atomix/utils/Version.java | Version.from | public static Version from(int major, int minor, int patch, String build) {
return new Version(major, minor, patch, build);
} | java | public static Version from(int major, int minor, int patch, String build) {
return new Version(major, minor, patch, build);
} | [
"public",
"static",
"Version",
"from",
"(",
"int",
"major",
",",
"int",
"minor",
",",
"int",
"patch",
",",
"String",
"build",
")",
"{",
"return",
"new",
"Version",
"(",
"major",
",",
"minor",
",",
"patch",
",",
"build",
")",
";",
"}"
] | Returns a new version from the given parts.
@param major the major version number
@param minor the minor version number
@param patch the patch version number
@param build the build version number
@return the version object | [
"Returns",
"a",
"new",
"version",
"from",
"the",
"given",
"parts",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/Version.java#L56-L58 |
27,340 | atomix/atomix | utils/src/main/java/io/atomix/utils/config/ConfigMapper.java | ConfigMapper.loadFiles | public <T> T loadFiles(Class<T> type, List<File> files, List<String> resources) {
if (files == null) {
return loadResources(type, resources);
}
Config config = ConfigFactory.systemProperties();
for (File file : files) {
config = config.withFallback(ConfigFactory.parseFile(file, ConfigParseOptions.defaults().setAllowMissing(false)));
}
for (String resource : resources) {
config = config.withFallback(ConfigFactory.load(classLoader, resource));
}
return map(checkNotNull(config, "config cannot be null").resolve(), type);
} | java | public <T> T loadFiles(Class<T> type, List<File> files, List<String> resources) {
if (files == null) {
return loadResources(type, resources);
}
Config config = ConfigFactory.systemProperties();
for (File file : files) {
config = config.withFallback(ConfigFactory.parseFile(file, ConfigParseOptions.defaults().setAllowMissing(false)));
}
for (String resource : resources) {
config = config.withFallback(ConfigFactory.load(classLoader, resource));
}
return map(checkNotNull(config, "config cannot be null").resolve(), type);
} | [
"public",
"<",
"T",
">",
"T",
"loadFiles",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"List",
"<",
"File",
">",
"files",
",",
"List",
"<",
"String",
">",
"resources",
")",
"{",
"if",
"(",
"files",
"==",
"null",
")",
"{",
"return",
"loadResources",
"(",
"type",
",",
"resources",
")",
";",
"}",
"Config",
"config",
"=",
"ConfigFactory",
".",
"systemProperties",
"(",
")",
";",
"for",
"(",
"File",
"file",
":",
"files",
")",
"{",
"config",
"=",
"config",
".",
"withFallback",
"(",
"ConfigFactory",
".",
"parseFile",
"(",
"file",
",",
"ConfigParseOptions",
".",
"defaults",
"(",
")",
".",
"setAllowMissing",
"(",
"false",
")",
")",
")",
";",
"}",
"for",
"(",
"String",
"resource",
":",
"resources",
")",
"{",
"config",
"=",
"config",
".",
"withFallback",
"(",
"ConfigFactory",
".",
"load",
"(",
"classLoader",
",",
"resource",
")",
")",
";",
"}",
"return",
"map",
"(",
"checkNotNull",
"(",
"config",
",",
"\"config cannot be null\"",
")",
".",
"resolve",
"(",
")",
",",
"type",
")",
";",
"}"
] | Loads the given configuration file using the mapper, falling back to the given resources.
@param type the type to load
@param files the files to load
@param resources the resources to which to fall back
@param <T> the resulting type
@return the loaded configuration | [
"Loads",
"the",
"given",
"configuration",
"file",
"using",
"the",
"mapper",
"falling",
"back",
"to",
"the",
"given",
"resources",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/config/ConfigMapper.java#L76-L90 |
27,341 | atomix/atomix | core/src/main/java/io/atomix/core/registry/ClasspathScanningRegistry.java | ClasspathScanningRegistry.newInstance | @SuppressWarnings("unchecked")
private static <T> T newInstance(Class<?> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ServiceException("Cannot instantiate service class " + type, e);
}
} | java | @SuppressWarnings("unchecked")
private static <T> T newInstance(Class<?> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ServiceException("Cannot instantiate service class " + type, e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"<",
"T",
">",
"T",
"newInstance",
"(",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"try",
"{",
"return",
"(",
"T",
")",
"type",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"InstantiationException",
"|",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"ServiceException",
"(",
"\"Cannot instantiate service class \"",
"+",
"type",
",",
"e",
")",
";",
"}",
"}"
] | Instantiates the given type using a no-argument constructor.
@param type the type to instantiate
@param <T> the generic type
@return the instantiated object
@throws ServiceException if the type cannot be instantiated | [
"Instantiates",
"the",
"given",
"type",
"using",
"a",
"no",
"-",
"argument",
"constructor",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/registry/ClasspathScanningRegistry.java#L128-L135 |
27,342 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.main | public static void main(String[] args) throws Exception {
// Parse the command line arguments.
final List<String> unknown = new ArrayList<>();
final Namespace namespace = parseArgs(args, unknown);
final Namespace extraArgs = parseUnknown(unknown);
extraArgs.getAttrs().forEach((key, value) -> System.setProperty(key, value.toString()));
final Logger logger = createLogger(namespace);
final Atomix atomix = buildAtomix(namespace);
atomix.start().join();
logger.info("Atomix listening at {}", atomix.getMembershipService().getLocalMember().address());
final ManagedRestService rest = buildRestService(atomix, namespace);
rest.start().join();
logger.warn("The Atomix HTTP API is BETA and is intended for development and debugging purposes only!");
logger.info("HTTP server listening at {}", rest.address());
synchronized (Atomix.class) {
while (atomix.isRunning()) {
Atomix.class.wait();
}
}
} | java | public static void main(String[] args) throws Exception {
// Parse the command line arguments.
final List<String> unknown = new ArrayList<>();
final Namespace namespace = parseArgs(args, unknown);
final Namespace extraArgs = parseUnknown(unknown);
extraArgs.getAttrs().forEach((key, value) -> System.setProperty(key, value.toString()));
final Logger logger = createLogger(namespace);
final Atomix atomix = buildAtomix(namespace);
atomix.start().join();
logger.info("Atomix listening at {}", atomix.getMembershipService().getLocalMember().address());
final ManagedRestService rest = buildRestService(atomix, namespace);
rest.start().join();
logger.warn("The Atomix HTTP API is BETA and is intended for development and debugging purposes only!");
logger.info("HTTP server listening at {}", rest.address());
synchronized (Atomix.class) {
while (atomix.isRunning()) {
Atomix.class.wait();
}
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"// Parse the command line arguments.",
"final",
"List",
"<",
"String",
">",
"unknown",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"Namespace",
"namespace",
"=",
"parseArgs",
"(",
"args",
",",
"unknown",
")",
";",
"final",
"Namespace",
"extraArgs",
"=",
"parseUnknown",
"(",
"unknown",
")",
";",
"extraArgs",
".",
"getAttrs",
"(",
")",
".",
"forEach",
"(",
"(",
"key",
",",
"value",
")",
"->",
"System",
".",
"setProperty",
"(",
"key",
",",
"value",
".",
"toString",
"(",
")",
")",
")",
";",
"final",
"Logger",
"logger",
"=",
"createLogger",
"(",
"namespace",
")",
";",
"final",
"Atomix",
"atomix",
"=",
"buildAtomix",
"(",
"namespace",
")",
";",
"atomix",
".",
"start",
"(",
")",
".",
"join",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"Atomix listening at {}\"",
",",
"atomix",
".",
"getMembershipService",
"(",
")",
".",
"getLocalMember",
"(",
")",
".",
"address",
"(",
")",
")",
";",
"final",
"ManagedRestService",
"rest",
"=",
"buildRestService",
"(",
"atomix",
",",
"namespace",
")",
";",
"rest",
".",
"start",
"(",
")",
".",
"join",
"(",
")",
";",
"logger",
".",
"warn",
"(",
"\"The Atomix HTTP API is BETA and is intended for development and debugging purposes only!\"",
")",
";",
"logger",
".",
"info",
"(",
"\"HTTP server listening at {}\"",
",",
"rest",
".",
"address",
"(",
")",
")",
";",
"synchronized",
"(",
"Atomix",
".",
"class",
")",
"{",
"while",
"(",
"atomix",
".",
"isRunning",
"(",
")",
")",
"{",
"Atomix",
".",
"class",
".",
"wait",
"(",
")",
";",
"}",
"}",
"}"
] | Runs a standalone Atomix agent from the given command line arguments.
@param args the program arguments
@throws Exception if the supplied arguments are invalid | [
"Runs",
"a",
"standalone",
"Atomix",
"agent",
"from",
"the",
"given",
"command",
"line",
"arguments",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L58-L81 |
27,343 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.parseArgs | static Namespace parseArgs(String[] args, List<String> unknown) {
ArgumentParser parser = createParser();
Namespace namespace = null;
try {
namespace = parser.parseKnownArgs(args, unknown);
} catch (ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
}
return namespace;
} | java | static Namespace parseArgs(String[] args, List<String> unknown) {
ArgumentParser parser = createParser();
Namespace namespace = null;
try {
namespace = parser.parseKnownArgs(args, unknown);
} catch (ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
}
return namespace;
} | [
"static",
"Namespace",
"parseArgs",
"(",
"String",
"[",
"]",
"args",
",",
"List",
"<",
"String",
">",
"unknown",
")",
"{",
"ArgumentParser",
"parser",
"=",
"createParser",
"(",
")",
";",
"Namespace",
"namespace",
"=",
"null",
";",
"try",
"{",
"namespace",
"=",
"parser",
".",
"parseKnownArgs",
"(",
"args",
",",
"unknown",
")",
";",
"}",
"catch",
"(",
"ArgumentParserException",
"e",
")",
"{",
"parser",
".",
"handleError",
"(",
"e",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"return",
"namespace",
";",
"}"
] | Parses the command line arguments, returning an argparse4j namespace.
@param args the arguments to parse
@return the namespace | [
"Parses",
"the",
"command",
"line",
"arguments",
"returning",
"an",
"argparse4j",
"namespace",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L89-L99 |
27,344 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.parseUnknown | static Namespace parseUnknown(List<String> unknown) {
Map<String, Object> attrs = new HashMap<>();
String attr = null;
for (String arg : unknown) {
if (arg.startsWith("--")) {
int splitIndex = arg.indexOf('=');
if (splitIndex == -1) {
attr = arg.substring(2);
} else {
attrs.put(arg.substring(2, splitIndex), arg.substring(splitIndex + 1));
attr = null;
}
} else if (attr != null) {
attrs.put(attr, arg);
attr = null;
}
}
return new Namespace(attrs);
} | java | static Namespace parseUnknown(List<String> unknown) {
Map<String, Object> attrs = new HashMap<>();
String attr = null;
for (String arg : unknown) {
if (arg.startsWith("--")) {
int splitIndex = arg.indexOf('=');
if (splitIndex == -1) {
attr = arg.substring(2);
} else {
attrs.put(arg.substring(2, splitIndex), arg.substring(splitIndex + 1));
attr = null;
}
} else if (attr != null) {
attrs.put(attr, arg);
attr = null;
}
}
return new Namespace(attrs);
} | [
"static",
"Namespace",
"parseUnknown",
"(",
"List",
"<",
"String",
">",
"unknown",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"attrs",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"String",
"attr",
"=",
"null",
";",
"for",
"(",
"String",
"arg",
":",
"unknown",
")",
"{",
"if",
"(",
"arg",
".",
"startsWith",
"(",
"\"--\"",
")",
")",
"{",
"int",
"splitIndex",
"=",
"arg",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"splitIndex",
"==",
"-",
"1",
")",
"{",
"attr",
"=",
"arg",
".",
"substring",
"(",
"2",
")",
";",
"}",
"else",
"{",
"attrs",
".",
"put",
"(",
"arg",
".",
"substring",
"(",
"2",
",",
"splitIndex",
")",
",",
"arg",
".",
"substring",
"(",
"splitIndex",
"+",
"1",
")",
")",
";",
"attr",
"=",
"null",
";",
"}",
"}",
"else",
"if",
"(",
"attr",
"!=",
"null",
")",
"{",
"attrs",
".",
"put",
"(",
"attr",
",",
"arg",
")",
";",
"attr",
"=",
"null",
";",
"}",
"}",
"return",
"new",
"Namespace",
"(",
"attrs",
")",
";",
"}"
] | Parses unknown arguments, returning an argparse4j namespace.
@param unknown the unknown arguments to parse
@return the namespace
--foo.bar baz --bar.baz foo bar --foo.bar.baz bang | [
"Parses",
"unknown",
"arguments",
"returning",
"an",
"argparse4j",
"namespace",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L108-L126 |
27,345 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.createLogger | static Logger createLogger(Namespace namespace) {
String logConfig = namespace.getString("log_config");
if (logConfig != null) {
System.setProperty("logback.configurationFile", logConfig);
}
System.setProperty("atomix.log.directory", namespace.getString("log_dir"));
System.setProperty("atomix.log.level", namespace.getString("log_level"));
System.setProperty("atomix.log.console.level", namespace.getString("console_log_level"));
System.setProperty("atomix.log.file.level", namespace.getString("file_log_level"));
return LoggerFactory.getLogger(AtomixAgent.class);
} | java | static Logger createLogger(Namespace namespace) {
String logConfig = namespace.getString("log_config");
if (logConfig != null) {
System.setProperty("logback.configurationFile", logConfig);
}
System.setProperty("atomix.log.directory", namespace.getString("log_dir"));
System.setProperty("atomix.log.level", namespace.getString("log_level"));
System.setProperty("atomix.log.console.level", namespace.getString("console_log_level"));
System.setProperty("atomix.log.file.level", namespace.getString("file_log_level"));
return LoggerFactory.getLogger(AtomixAgent.class);
} | [
"static",
"Logger",
"createLogger",
"(",
"Namespace",
"namespace",
")",
"{",
"String",
"logConfig",
"=",
"namespace",
".",
"getString",
"(",
"\"log_config\"",
")",
";",
"if",
"(",
"logConfig",
"!=",
"null",
")",
"{",
"System",
".",
"setProperty",
"(",
"\"logback.configurationFile\"",
",",
"logConfig",
")",
";",
"}",
"System",
".",
"setProperty",
"(",
"\"atomix.log.directory\"",
",",
"namespace",
".",
"getString",
"(",
"\"log_dir\"",
")",
")",
";",
"System",
".",
"setProperty",
"(",
"\"atomix.log.level\"",
",",
"namespace",
".",
"getString",
"(",
"\"log_level\"",
")",
")",
";",
"System",
".",
"setProperty",
"(",
"\"atomix.log.console.level\"",
",",
"namespace",
".",
"getString",
"(",
"\"console_log_level\"",
")",
")",
";",
"System",
".",
"setProperty",
"(",
"\"atomix.log.file.level\"",
",",
"namespace",
".",
"getString",
"(",
"\"file_log_level\"",
")",
")",
";",
"return",
"LoggerFactory",
".",
"getLogger",
"(",
"AtomixAgent",
".",
"class",
")",
";",
"}"
] | Configures and creates a new logger for the given namespace.
@param namespace the namespace from which to create the logger configuration
@return a new agent logger | [
"Configures",
"and",
"creates",
"a",
"new",
"logger",
"for",
"the",
"given",
"namespace",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L275-L285 |
27,346 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.createConfig | static AtomixConfig createConfig(Namespace namespace) {
final List<File> configFiles = namespace.getList("config");
final String memberId = namespace.getString("member");
final Address address = namespace.get("address");
final String host = namespace.getString("host");
final String rack = namespace.getString("rack");
final String zone = namespace.getString("zone");
final List<NodeConfig> bootstrap = namespace.getList("bootstrap");
final boolean multicastEnabled = namespace.getBoolean("multicast");
final String multicastGroup = namespace.get("multicast_group");
final Integer multicastPort = namespace.get("multicast_port");
System.setProperty("atomix.data", namespace.getString("data_dir"));
// If a configuration was provided, merge the configuration's member information with the provided command line arguments.
AtomixConfig config;
if (configFiles != null && !configFiles.isEmpty()) {
System.setProperty("atomix.config.resources", "");
config = Atomix.config(configFiles);
} else {
config = Atomix.config();
}
if (memberId != null) {
config.getClusterConfig().getNodeConfig().setId(memberId);
}
if (address != null) {
config.getClusterConfig().getNodeConfig().setAddress(address);
}
if (host != null) {
config.getClusterConfig().getNodeConfig().setHostId(host);
}
if (rack != null) {
config.getClusterConfig().getNodeConfig().setRackId(rack);
}
if (zone != null) {
config.getClusterConfig().getNodeConfig().setZoneId(zone);
}
if (bootstrap != null && !bootstrap.isEmpty()) {
config.getClusterConfig().setDiscoveryConfig(new BootstrapDiscoveryConfig().setNodes(bootstrap));
}
if (multicastEnabled) {
config.getClusterConfig().getMulticastConfig().setEnabled(true);
if (multicastGroup != null) {
config.getClusterConfig().getMulticastConfig().setGroup(multicastGroup);
}
if (multicastPort != null) {
config.getClusterConfig().getMulticastConfig().setPort(multicastPort);
}
if (bootstrap == null || bootstrap.isEmpty()) {
config.getClusterConfig().setDiscoveryConfig(new MulticastDiscoveryConfig());
}
}
return config;
} | java | static AtomixConfig createConfig(Namespace namespace) {
final List<File> configFiles = namespace.getList("config");
final String memberId = namespace.getString("member");
final Address address = namespace.get("address");
final String host = namespace.getString("host");
final String rack = namespace.getString("rack");
final String zone = namespace.getString("zone");
final List<NodeConfig> bootstrap = namespace.getList("bootstrap");
final boolean multicastEnabled = namespace.getBoolean("multicast");
final String multicastGroup = namespace.get("multicast_group");
final Integer multicastPort = namespace.get("multicast_port");
System.setProperty("atomix.data", namespace.getString("data_dir"));
// If a configuration was provided, merge the configuration's member information with the provided command line arguments.
AtomixConfig config;
if (configFiles != null && !configFiles.isEmpty()) {
System.setProperty("atomix.config.resources", "");
config = Atomix.config(configFiles);
} else {
config = Atomix.config();
}
if (memberId != null) {
config.getClusterConfig().getNodeConfig().setId(memberId);
}
if (address != null) {
config.getClusterConfig().getNodeConfig().setAddress(address);
}
if (host != null) {
config.getClusterConfig().getNodeConfig().setHostId(host);
}
if (rack != null) {
config.getClusterConfig().getNodeConfig().setRackId(rack);
}
if (zone != null) {
config.getClusterConfig().getNodeConfig().setZoneId(zone);
}
if (bootstrap != null && !bootstrap.isEmpty()) {
config.getClusterConfig().setDiscoveryConfig(new BootstrapDiscoveryConfig().setNodes(bootstrap));
}
if (multicastEnabled) {
config.getClusterConfig().getMulticastConfig().setEnabled(true);
if (multicastGroup != null) {
config.getClusterConfig().getMulticastConfig().setGroup(multicastGroup);
}
if (multicastPort != null) {
config.getClusterConfig().getMulticastConfig().setPort(multicastPort);
}
if (bootstrap == null || bootstrap.isEmpty()) {
config.getClusterConfig().setDiscoveryConfig(new MulticastDiscoveryConfig());
}
}
return config;
} | [
"static",
"AtomixConfig",
"createConfig",
"(",
"Namespace",
"namespace",
")",
"{",
"final",
"List",
"<",
"File",
">",
"configFiles",
"=",
"namespace",
".",
"getList",
"(",
"\"config\"",
")",
";",
"final",
"String",
"memberId",
"=",
"namespace",
".",
"getString",
"(",
"\"member\"",
")",
";",
"final",
"Address",
"address",
"=",
"namespace",
".",
"get",
"(",
"\"address\"",
")",
";",
"final",
"String",
"host",
"=",
"namespace",
".",
"getString",
"(",
"\"host\"",
")",
";",
"final",
"String",
"rack",
"=",
"namespace",
".",
"getString",
"(",
"\"rack\"",
")",
";",
"final",
"String",
"zone",
"=",
"namespace",
".",
"getString",
"(",
"\"zone\"",
")",
";",
"final",
"List",
"<",
"NodeConfig",
">",
"bootstrap",
"=",
"namespace",
".",
"getList",
"(",
"\"bootstrap\"",
")",
";",
"final",
"boolean",
"multicastEnabled",
"=",
"namespace",
".",
"getBoolean",
"(",
"\"multicast\"",
")",
";",
"final",
"String",
"multicastGroup",
"=",
"namespace",
".",
"get",
"(",
"\"multicast_group\"",
")",
";",
"final",
"Integer",
"multicastPort",
"=",
"namespace",
".",
"get",
"(",
"\"multicast_port\"",
")",
";",
"System",
".",
"setProperty",
"(",
"\"atomix.data\"",
",",
"namespace",
".",
"getString",
"(",
"\"data_dir\"",
")",
")",
";",
"// If a configuration was provided, merge the configuration's member information with the provided command line arguments.",
"AtomixConfig",
"config",
";",
"if",
"(",
"configFiles",
"!=",
"null",
"&&",
"!",
"configFiles",
".",
"isEmpty",
"(",
")",
")",
"{",
"System",
".",
"setProperty",
"(",
"\"atomix.config.resources\"",
",",
"\"\"",
")",
";",
"config",
"=",
"Atomix",
".",
"config",
"(",
"configFiles",
")",
";",
"}",
"else",
"{",
"config",
"=",
"Atomix",
".",
"config",
"(",
")",
";",
"}",
"if",
"(",
"memberId",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getNodeConfig",
"(",
")",
".",
"setId",
"(",
"memberId",
")",
";",
"}",
"if",
"(",
"address",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getNodeConfig",
"(",
")",
".",
"setAddress",
"(",
"address",
")",
";",
"}",
"if",
"(",
"host",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getNodeConfig",
"(",
")",
".",
"setHostId",
"(",
"host",
")",
";",
"}",
"if",
"(",
"rack",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getNodeConfig",
"(",
")",
".",
"setRackId",
"(",
"rack",
")",
";",
"}",
"if",
"(",
"zone",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getNodeConfig",
"(",
")",
".",
"setZoneId",
"(",
"zone",
")",
";",
"}",
"if",
"(",
"bootstrap",
"!=",
"null",
"&&",
"!",
"bootstrap",
".",
"isEmpty",
"(",
")",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"setDiscoveryConfig",
"(",
"new",
"BootstrapDiscoveryConfig",
"(",
")",
".",
"setNodes",
"(",
"bootstrap",
")",
")",
";",
"}",
"if",
"(",
"multicastEnabled",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getMulticastConfig",
"(",
")",
".",
"setEnabled",
"(",
"true",
")",
";",
"if",
"(",
"multicastGroup",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getMulticastConfig",
"(",
")",
".",
"setGroup",
"(",
"multicastGroup",
")",
";",
"}",
"if",
"(",
"multicastPort",
"!=",
"null",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"getMulticastConfig",
"(",
")",
".",
"setPort",
"(",
"multicastPort",
")",
";",
"}",
"if",
"(",
"bootstrap",
"==",
"null",
"||",
"bootstrap",
".",
"isEmpty",
"(",
")",
")",
"{",
"config",
".",
"getClusterConfig",
"(",
")",
".",
"setDiscoveryConfig",
"(",
"new",
"MulticastDiscoveryConfig",
"(",
")",
")",
";",
"}",
"}",
"return",
"config",
";",
"}"
] | Creates an Atomix configuration from the given namespace.
@param namespace the namespace from which to create the configuration
@return the Atomix configuration for the given namespace | [
"Creates",
"an",
"Atomix",
"configuration",
"from",
"the",
"given",
"namespace",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L293-L351 |
27,347 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.buildAtomix | private static Atomix buildAtomix(Namespace namespace) {
return Atomix.builder(createConfig(namespace)).withShutdownHookEnabled().build();
} | java | private static Atomix buildAtomix(Namespace namespace) {
return Atomix.builder(createConfig(namespace)).withShutdownHookEnabled().build();
} | [
"private",
"static",
"Atomix",
"buildAtomix",
"(",
"Namespace",
"namespace",
")",
"{",
"return",
"Atomix",
".",
"builder",
"(",
"createConfig",
"(",
"namespace",
")",
")",
".",
"withShutdownHookEnabled",
"(",
")",
".",
"build",
"(",
")",
";",
"}"
] | Builds a new Atomix instance from the given namespace.
@param namespace the namespace from which to build the instance
@return the Atomix instance | [
"Builds",
"a",
"new",
"Atomix",
"instance",
"from",
"the",
"given",
"namespace",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L359-L361 |
27,348 | atomix/atomix | agent/src/main/java/io/atomix/agent/AtomixAgent.java | AtomixAgent.buildRestService | private static ManagedRestService buildRestService(Atomix atomix, Namespace namespace) {
final String httpHost = namespace.getString("http_host");
final Integer httpPort = namespace.getInt("http_port");
return RestService.builder()
.withAtomix(atomix)
.withAddress(Address.from(httpHost, httpPort))
.build();
} | java | private static ManagedRestService buildRestService(Atomix atomix, Namespace namespace) {
final String httpHost = namespace.getString("http_host");
final Integer httpPort = namespace.getInt("http_port");
return RestService.builder()
.withAtomix(atomix)
.withAddress(Address.from(httpHost, httpPort))
.build();
} | [
"private",
"static",
"ManagedRestService",
"buildRestService",
"(",
"Atomix",
"atomix",
",",
"Namespace",
"namespace",
")",
"{",
"final",
"String",
"httpHost",
"=",
"namespace",
".",
"getString",
"(",
"\"http_host\"",
")",
";",
"final",
"Integer",
"httpPort",
"=",
"namespace",
".",
"getInt",
"(",
"\"http_port\"",
")",
";",
"return",
"RestService",
".",
"builder",
"(",
")",
".",
"withAtomix",
"(",
"atomix",
")",
".",
"withAddress",
"(",
"Address",
".",
"from",
"(",
"httpHost",
",",
"httpPort",
")",
")",
".",
"build",
"(",
")",
";",
"}"
] | Builds a REST service for the given Atomix instance from the given namespace.
@param atomix the Atomix instance
@param namespace the namespace from which to build the service
@return the managed REST service | [
"Builds",
"a",
"REST",
"service",
"for",
"the",
"given",
"Atomix",
"instance",
"from",
"the",
"given",
"namespace",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/agent/src/main/java/io/atomix/agent/AtomixAgent.java#L370-L377 |
27,349 | atomix/atomix | utils/src/main/java/io/atomix/utils/net/Address.java | Address.from | public static Address from(int port) {
try {
InetAddress address = getLocalAddress();
return new Address(address.getHostName(), port);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to locate host", e);
}
} | java | public static Address from(int port) {
try {
InetAddress address = getLocalAddress();
return new Address(address.getHostName(), port);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to locate host", e);
}
} | [
"public",
"static",
"Address",
"from",
"(",
"int",
"port",
")",
"{",
"try",
"{",
"InetAddress",
"address",
"=",
"getLocalAddress",
"(",
")",
";",
"return",
"new",
"Address",
"(",
"address",
".",
"getHostName",
"(",
")",
",",
"port",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Failed to locate host\"",
",",
"e",
")",
";",
"}",
"}"
] | Returns an address for the local host and the given port.
@param port the port
@return a new address | [
"Returns",
"an",
"address",
"for",
"the",
"local",
"host",
"and",
"the",
"given",
"port",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/net/Address.java#L96-L103 |
27,350 | atomix/atomix | utils/src/main/java/io/atomix/utils/net/Address.java | Address.getLocalAddress | private static InetAddress getLocalAddress() throws UnknownHostException {
try {
return InetAddress.getLocalHost(); // first NIC
} catch (Exception ignore) {
return InetAddress.getByName(null);
}
} | java | private static InetAddress getLocalAddress() throws UnknownHostException {
try {
return InetAddress.getLocalHost(); // first NIC
} catch (Exception ignore) {
return InetAddress.getByName(null);
}
} | [
"private",
"static",
"InetAddress",
"getLocalAddress",
"(",
")",
"throws",
"UnknownHostException",
"{",
"try",
"{",
"return",
"InetAddress",
".",
"getLocalHost",
"(",
")",
";",
"// first NIC",
"}",
"catch",
"(",
"Exception",
"ignore",
")",
"{",
"return",
"InetAddress",
".",
"getByName",
"(",
"null",
")",
";",
"}",
"}"
] | Returns the local host. | [
"Returns",
"the",
"local",
"host",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/net/Address.java#L108-L114 |
27,351 | atomix/atomix | utils/src/main/java/io/atomix/utils/net/Address.java | Address.address | public InetAddress address(boolean resolve) {
if (resolve) {
address = resolveAddress();
return address;
}
if (address == null) {
synchronized (this) {
if (address == null) {
address = resolveAddress();
}
}
}
return address;
} | java | public InetAddress address(boolean resolve) {
if (resolve) {
address = resolveAddress();
return address;
}
if (address == null) {
synchronized (this) {
if (address == null) {
address = resolveAddress();
}
}
}
return address;
} | [
"public",
"InetAddress",
"address",
"(",
"boolean",
"resolve",
")",
"{",
"if",
"(",
"resolve",
")",
"{",
"address",
"=",
"resolveAddress",
"(",
")",
";",
"return",
"address",
";",
"}",
"if",
"(",
"address",
"==",
"null",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"address",
"==",
"null",
")",
"{",
"address",
"=",
"resolveAddress",
"(",
")",
";",
"}",
"}",
"}",
"return",
"address",
";",
"}"
] | Returns the IP address.
@param resolve whether to force resolve the hostname
@return the IP address | [
"Returns",
"the",
"IP",
"address",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/net/Address.java#L167-L181 |
27,352 | atomix/atomix | utils/src/main/java/io/atomix/utils/net/Address.java | Address.type | public Type type() {
if (type == null) {
synchronized (this) {
if (type == null) {
type = address() instanceof Inet6Address ? Type.IPV6 : Type.IPV4;
}
}
}
return type;
} | java | public Type type() {
if (type == null) {
synchronized (this) {
if (type == null) {
type = address() instanceof Inet6Address ? Type.IPV6 : Type.IPV4;
}
}
}
return type;
} | [
"public",
"Type",
"type",
"(",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"type",
"=",
"address",
"(",
")",
"instanceof",
"Inet6Address",
"?",
"Type",
".",
"IPV6",
":",
"Type",
".",
"IPV4",
";",
"}",
"}",
"}",
"return",
"type",
";",
"}"
] | Returns the address type.
@return the address type | [
"Returns",
"the",
"address",
"type",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/net/Address.java#L201-L210 |
27,353 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.installSnapshot | public void installSnapshot(SnapshotReader reader) {
log.debug("Installing snapshot {}", reader.snapshot().index());
reader.skip(Bytes.LONG); // Skip the service ID
PrimitiveType primitiveType;
try {
primitiveType = raft.getPrimitiveTypes().getPrimitiveType(reader.readString());
} catch (ConfigurationException e) {
log.error(e.getMessage(), e);
return;
}
String serviceName = reader.readString();
currentIndex = reader.readLong();
currentTimestamp = reader.readLong();
timestampDelta = reader.readLong();
int sessionCount = reader.readInt();
for (int i = 0; i < sessionCount; i++) {
SessionId sessionId = SessionId.from(reader.readLong());
MemberId node = MemberId.from(reader.readString());
ReadConsistency readConsistency = ReadConsistency.valueOf(reader.readString());
long minTimeout = reader.readLong();
long maxTimeout = reader.readLong();
long sessionTimestamp = reader.readLong();
// Only create a new session if one does not already exist. This is necessary to ensure only a single session
// is ever opened and exposed to the state machine.
RaftSession session = raft.getSessions().addSession(new RaftSession(
sessionId,
node,
serviceName,
primitiveType,
readConsistency,
minTimeout,
maxTimeout,
sessionTimestamp,
service.serializer(),
this,
raft,
threadContextFactory));
session.setRequestSequence(reader.readLong());
session.setCommandSequence(reader.readLong());
session.setEventIndex(reader.readLong());
session.setLastCompleted(reader.readLong());
session.setLastApplied(reader.snapshot().index());
session.setLastUpdated(sessionTimestamp);
session.open();
service.register(sessions.addSession(session));
}
service.restore(new DefaultBackupInput(reader, service.serializer()));
} | java | public void installSnapshot(SnapshotReader reader) {
log.debug("Installing snapshot {}", reader.snapshot().index());
reader.skip(Bytes.LONG); // Skip the service ID
PrimitiveType primitiveType;
try {
primitiveType = raft.getPrimitiveTypes().getPrimitiveType(reader.readString());
} catch (ConfigurationException e) {
log.error(e.getMessage(), e);
return;
}
String serviceName = reader.readString();
currentIndex = reader.readLong();
currentTimestamp = reader.readLong();
timestampDelta = reader.readLong();
int sessionCount = reader.readInt();
for (int i = 0; i < sessionCount; i++) {
SessionId sessionId = SessionId.from(reader.readLong());
MemberId node = MemberId.from(reader.readString());
ReadConsistency readConsistency = ReadConsistency.valueOf(reader.readString());
long minTimeout = reader.readLong();
long maxTimeout = reader.readLong();
long sessionTimestamp = reader.readLong();
// Only create a new session if one does not already exist. This is necessary to ensure only a single session
// is ever opened and exposed to the state machine.
RaftSession session = raft.getSessions().addSession(new RaftSession(
sessionId,
node,
serviceName,
primitiveType,
readConsistency,
minTimeout,
maxTimeout,
sessionTimestamp,
service.serializer(),
this,
raft,
threadContextFactory));
session.setRequestSequence(reader.readLong());
session.setCommandSequence(reader.readLong());
session.setEventIndex(reader.readLong());
session.setLastCompleted(reader.readLong());
session.setLastApplied(reader.snapshot().index());
session.setLastUpdated(sessionTimestamp);
session.open();
service.register(sessions.addSession(session));
}
service.restore(new DefaultBackupInput(reader, service.serializer()));
} | [
"public",
"void",
"installSnapshot",
"(",
"SnapshotReader",
"reader",
")",
"{",
"log",
".",
"debug",
"(",
"\"Installing snapshot {}\"",
",",
"reader",
".",
"snapshot",
"(",
")",
".",
"index",
"(",
")",
")",
";",
"reader",
".",
"skip",
"(",
"Bytes",
".",
"LONG",
")",
";",
"// Skip the service ID",
"PrimitiveType",
"primitiveType",
";",
"try",
"{",
"primitiveType",
"=",
"raft",
".",
"getPrimitiveTypes",
"(",
")",
".",
"getPrimitiveType",
"(",
"reader",
".",
"readString",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ConfigurationException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"return",
";",
"}",
"String",
"serviceName",
"=",
"reader",
".",
"readString",
"(",
")",
";",
"currentIndex",
"=",
"reader",
".",
"readLong",
"(",
")",
";",
"currentTimestamp",
"=",
"reader",
".",
"readLong",
"(",
")",
";",
"timestampDelta",
"=",
"reader",
".",
"readLong",
"(",
")",
";",
"int",
"sessionCount",
"=",
"reader",
".",
"readInt",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"sessionCount",
";",
"i",
"++",
")",
"{",
"SessionId",
"sessionId",
"=",
"SessionId",
".",
"from",
"(",
"reader",
".",
"readLong",
"(",
")",
")",
";",
"MemberId",
"node",
"=",
"MemberId",
".",
"from",
"(",
"reader",
".",
"readString",
"(",
")",
")",
";",
"ReadConsistency",
"readConsistency",
"=",
"ReadConsistency",
".",
"valueOf",
"(",
"reader",
".",
"readString",
"(",
")",
")",
";",
"long",
"minTimeout",
"=",
"reader",
".",
"readLong",
"(",
")",
";",
"long",
"maxTimeout",
"=",
"reader",
".",
"readLong",
"(",
")",
";",
"long",
"sessionTimestamp",
"=",
"reader",
".",
"readLong",
"(",
")",
";",
"// Only create a new session if one does not already exist. This is necessary to ensure only a single session",
"// is ever opened and exposed to the state machine.",
"RaftSession",
"session",
"=",
"raft",
".",
"getSessions",
"(",
")",
".",
"addSession",
"(",
"new",
"RaftSession",
"(",
"sessionId",
",",
"node",
",",
"serviceName",
",",
"primitiveType",
",",
"readConsistency",
",",
"minTimeout",
",",
"maxTimeout",
",",
"sessionTimestamp",
",",
"service",
".",
"serializer",
"(",
")",
",",
"this",
",",
"raft",
",",
"threadContextFactory",
")",
")",
";",
"session",
".",
"setRequestSequence",
"(",
"reader",
".",
"readLong",
"(",
")",
")",
";",
"session",
".",
"setCommandSequence",
"(",
"reader",
".",
"readLong",
"(",
")",
")",
";",
"session",
".",
"setEventIndex",
"(",
"reader",
".",
"readLong",
"(",
")",
")",
";",
"session",
".",
"setLastCompleted",
"(",
"reader",
".",
"readLong",
"(",
")",
")",
";",
"session",
".",
"setLastApplied",
"(",
"reader",
".",
"snapshot",
"(",
")",
".",
"index",
"(",
")",
")",
";",
"session",
".",
"setLastUpdated",
"(",
"sessionTimestamp",
")",
";",
"session",
".",
"open",
"(",
")",
";",
"service",
".",
"register",
"(",
"sessions",
".",
"addSession",
"(",
"session",
")",
")",
";",
"}",
"service",
".",
"restore",
"(",
"new",
"DefaultBackupInput",
"(",
"reader",
",",
"service",
".",
"serializer",
"(",
")",
")",
")",
";",
"}"
] | Installs a snapshot. | [
"Installs",
"a",
"snapshot",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L236-L287 |
27,354 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.takeSnapshot | public void takeSnapshot(SnapshotWriter writer) {
log.debug("Taking snapshot {}", writer.snapshot().index());
// Serialize sessions to the in-memory snapshot and request a snapshot from the state machine.
writer.writeLong(primitiveId.id());
writer.writeString(primitiveType.name());
writer.writeString(serviceName);
writer.writeLong(currentIndex);
writer.writeLong(currentTimestamp);
writer.writeLong(timestampDelta);
writer.writeInt(sessions.getSessions().size());
for (RaftSession session : sessions.getSessions()) {
writer.writeLong(session.sessionId().id());
writer.writeString(session.memberId().id());
writer.writeString(session.readConsistency().name());
writer.writeLong(session.minTimeout());
writer.writeLong(session.maxTimeout());
writer.writeLong(session.getLastUpdated());
writer.writeLong(session.getRequestSequence());
writer.writeLong(session.getCommandSequence());
writer.writeLong(session.getEventIndex());
writer.writeLong(session.getLastCompleted());
}
service.backup(new DefaultBackupOutput(writer, service.serializer()));
} | java | public void takeSnapshot(SnapshotWriter writer) {
log.debug("Taking snapshot {}", writer.snapshot().index());
// Serialize sessions to the in-memory snapshot and request a snapshot from the state machine.
writer.writeLong(primitiveId.id());
writer.writeString(primitiveType.name());
writer.writeString(serviceName);
writer.writeLong(currentIndex);
writer.writeLong(currentTimestamp);
writer.writeLong(timestampDelta);
writer.writeInt(sessions.getSessions().size());
for (RaftSession session : sessions.getSessions()) {
writer.writeLong(session.sessionId().id());
writer.writeString(session.memberId().id());
writer.writeString(session.readConsistency().name());
writer.writeLong(session.minTimeout());
writer.writeLong(session.maxTimeout());
writer.writeLong(session.getLastUpdated());
writer.writeLong(session.getRequestSequence());
writer.writeLong(session.getCommandSequence());
writer.writeLong(session.getEventIndex());
writer.writeLong(session.getLastCompleted());
}
service.backup(new DefaultBackupOutput(writer, service.serializer()));
} | [
"public",
"void",
"takeSnapshot",
"(",
"SnapshotWriter",
"writer",
")",
"{",
"log",
".",
"debug",
"(",
"\"Taking snapshot {}\"",
",",
"writer",
".",
"snapshot",
"(",
")",
".",
"index",
"(",
")",
")",
";",
"// Serialize sessions to the in-memory snapshot and request a snapshot from the state machine.",
"writer",
".",
"writeLong",
"(",
"primitiveId",
".",
"id",
"(",
")",
")",
";",
"writer",
".",
"writeString",
"(",
"primitiveType",
".",
"name",
"(",
")",
")",
";",
"writer",
".",
"writeString",
"(",
"serviceName",
")",
";",
"writer",
".",
"writeLong",
"(",
"currentIndex",
")",
";",
"writer",
".",
"writeLong",
"(",
"currentTimestamp",
")",
";",
"writer",
".",
"writeLong",
"(",
"timestampDelta",
")",
";",
"writer",
".",
"writeInt",
"(",
"sessions",
".",
"getSessions",
"(",
")",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"RaftSession",
"session",
":",
"sessions",
".",
"getSessions",
"(",
")",
")",
"{",
"writer",
".",
"writeLong",
"(",
"session",
".",
"sessionId",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"writer",
".",
"writeString",
"(",
"session",
".",
"memberId",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"writer",
".",
"writeString",
"(",
"session",
".",
"readConsistency",
"(",
")",
".",
"name",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"minTimeout",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"maxTimeout",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"getLastUpdated",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"getRequestSequence",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"getCommandSequence",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"getEventIndex",
"(",
")",
")",
";",
"writer",
".",
"writeLong",
"(",
"session",
".",
"getLastCompleted",
"(",
")",
")",
";",
"}",
"service",
".",
"backup",
"(",
"new",
"DefaultBackupOutput",
"(",
"writer",
",",
"service",
".",
"serializer",
"(",
")",
")",
")",
";",
"}"
] | Takes a snapshot of the service state. | [
"Takes",
"a",
"snapshot",
"of",
"the",
"service",
"state",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L292-L317 |
27,355 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.openSession | public long openSession(long index, long timestamp, RaftSession session) {
log.debug("Opening session {}", session.sessionId());
// Update the state machine index/timestamp.
tick(index, timestamp);
// Set the session timestamp to the current service timestamp.
session.setLastUpdated(currentTimestamp);
// Expire sessions that have timed out.
expireSessions(currentTimestamp);
// Add the session to the sessions list.
session.open();
service.register(sessions.addSession(session));
// Commit the index, causing events to be sent to clients if necessary.
commit();
// Complete the future.
return session.sessionId().id();
} | java | public long openSession(long index, long timestamp, RaftSession session) {
log.debug("Opening session {}", session.sessionId());
// Update the state machine index/timestamp.
tick(index, timestamp);
// Set the session timestamp to the current service timestamp.
session.setLastUpdated(currentTimestamp);
// Expire sessions that have timed out.
expireSessions(currentTimestamp);
// Add the session to the sessions list.
session.open();
service.register(sessions.addSession(session));
// Commit the index, causing events to be sent to clients if necessary.
commit();
// Complete the future.
return session.sessionId().id();
} | [
"public",
"long",
"openSession",
"(",
"long",
"index",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
")",
"{",
"log",
".",
"debug",
"(",
"\"Opening session {}\"",
",",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"// Update the state machine index/timestamp.",
"tick",
"(",
"index",
",",
"timestamp",
")",
";",
"// Set the session timestamp to the current service timestamp.",
"session",
".",
"setLastUpdated",
"(",
"currentTimestamp",
")",
";",
"// Expire sessions that have timed out.",
"expireSessions",
"(",
"currentTimestamp",
")",
";",
"// Add the session to the sessions list.",
"session",
".",
"open",
"(",
")",
";",
"service",
".",
"register",
"(",
"sessions",
".",
"addSession",
"(",
"session",
")",
")",
";",
"// Commit the index, causing events to be sent to clients if necessary.",
"commit",
"(",
")",
";",
"// Complete the future.",
"return",
"session",
".",
"sessionId",
"(",
")",
".",
"id",
"(",
")",
";",
"}"
] | Registers the given session.
@param index The index of the registration.
@param timestamp The timestamp of the registration.
@param session The session to register. | [
"Registers",
"the",
"given",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L326-L347 |
27,356 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.keepAlive | public boolean keepAlive(long index, long timestamp, RaftSession session, long commandSequence, long eventIndex) {
// If the service has been deleted, just return false to ignore the keep-alive.
if (deleted) {
return false;
}
// Update the state machine index/timestamp.
tick(index, timestamp);
// The session may have been closed by the time this update was executed on the service thread.
if (session.getState() != Session.State.CLOSED) {
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Clear results cached in the session.
session.clearResults(commandSequence);
// Resend missing events starting from the last received event index.
session.resendEvents(eventIndex);
// Update the session's request sequence number. The command sequence number will be applied
// iff the existing request sequence number is less than the command sequence number. This must
// be applied to ensure that request sequence numbers are reset after a leader change since leaders
// track request sequence numbers in local memory.
session.resetRequestSequence(commandSequence);
// Update the sessions' command sequence number. The command sequence number will be applied
// iff the existing sequence number is less than the keep-alive command sequence number. This should
// not be the case under normal operation since the command sequence number in keep-alive requests
// represents the highest sequence for which a client has received a response (the command has already
// been completed), but since the log compaction algorithm can exclude individual entries from replication,
// the command sequence number must be applied for keep-alive requests to reset the sequence number in
// the event the last command for the session was cleaned/compacted from the log.
session.setCommandSequence(commandSequence);
// Complete the future.
return true;
} else {
return false;
}
} | java | public boolean keepAlive(long index, long timestamp, RaftSession session, long commandSequence, long eventIndex) {
// If the service has been deleted, just return false to ignore the keep-alive.
if (deleted) {
return false;
}
// Update the state machine index/timestamp.
tick(index, timestamp);
// The session may have been closed by the time this update was executed on the service thread.
if (session.getState() != Session.State.CLOSED) {
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Clear results cached in the session.
session.clearResults(commandSequence);
// Resend missing events starting from the last received event index.
session.resendEvents(eventIndex);
// Update the session's request sequence number. The command sequence number will be applied
// iff the existing request sequence number is less than the command sequence number. This must
// be applied to ensure that request sequence numbers are reset after a leader change since leaders
// track request sequence numbers in local memory.
session.resetRequestSequence(commandSequence);
// Update the sessions' command sequence number. The command sequence number will be applied
// iff the existing sequence number is less than the keep-alive command sequence number. This should
// not be the case under normal operation since the command sequence number in keep-alive requests
// represents the highest sequence for which a client has received a response (the command has already
// been completed), but since the log compaction algorithm can exclude individual entries from replication,
// the command sequence number must be applied for keep-alive requests to reset the sequence number in
// the event the last command for the session was cleaned/compacted from the log.
session.setCommandSequence(commandSequence);
// Complete the future.
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"keepAlive",
"(",
"long",
"index",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
",",
"long",
"commandSequence",
",",
"long",
"eventIndex",
")",
"{",
"// If the service has been deleted, just return false to ignore the keep-alive.",
"if",
"(",
"deleted",
")",
"{",
"return",
"false",
";",
"}",
"// Update the state machine index/timestamp.",
"tick",
"(",
"index",
",",
"timestamp",
")",
";",
"// The session may have been closed by the time this update was executed on the service thread.",
"if",
"(",
"session",
".",
"getState",
"(",
")",
"!=",
"Session",
".",
"State",
".",
"CLOSED",
")",
"{",
"// Update the session's timestamp to prevent it from being expired.",
"session",
".",
"setLastUpdated",
"(",
"timestamp",
")",
";",
"// Clear results cached in the session.",
"session",
".",
"clearResults",
"(",
"commandSequence",
")",
";",
"// Resend missing events starting from the last received event index.",
"session",
".",
"resendEvents",
"(",
"eventIndex",
")",
";",
"// Update the session's request sequence number. The command sequence number will be applied",
"// iff the existing request sequence number is less than the command sequence number. This must",
"// be applied to ensure that request sequence numbers are reset after a leader change since leaders",
"// track request sequence numbers in local memory.",
"session",
".",
"resetRequestSequence",
"(",
"commandSequence",
")",
";",
"// Update the sessions' command sequence number. The command sequence number will be applied",
"// iff the existing sequence number is less than the keep-alive command sequence number. This should",
"// not be the case under normal operation since the command sequence number in keep-alive requests",
"// represents the highest sequence for which a client has received a response (the command has already",
"// been completed), but since the log compaction algorithm can exclude individual entries from replication,",
"// the command sequence number must be applied for keep-alive requests to reset the sequence number in",
"// the event the last command for the session was cleaned/compacted from the log.",
"session",
".",
"setCommandSequence",
"(",
"commandSequence",
")",
";",
"// Complete the future.",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Keeps the given session alive.
@param index The index of the keep-alive.
@param timestamp The timestamp of the keep-alive.
@param session The session to keep-alive.
@param commandSequence The session command sequence number.
@param eventIndex The session event index. | [
"Keeps",
"the",
"given",
"session",
"alive",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L358-L398 |
27,357 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.keepAliveSessions | public void keepAliveSessions(long index, long timestamp) {
log.debug("Resetting session timeouts");
this.currentIndex = index;
this.currentTimestamp = Math.max(currentTimestamp, timestamp);
for (RaftSession session : sessions.getSessions(primitiveId)) {
session.setLastUpdated(timestamp);
}
} | java | public void keepAliveSessions(long index, long timestamp) {
log.debug("Resetting session timeouts");
this.currentIndex = index;
this.currentTimestamp = Math.max(currentTimestamp, timestamp);
for (RaftSession session : sessions.getSessions(primitiveId)) {
session.setLastUpdated(timestamp);
}
} | [
"public",
"void",
"keepAliveSessions",
"(",
"long",
"index",
",",
"long",
"timestamp",
")",
"{",
"log",
".",
"debug",
"(",
"\"Resetting session timeouts\"",
")",
";",
"this",
".",
"currentIndex",
"=",
"index",
";",
"this",
".",
"currentTimestamp",
"=",
"Math",
".",
"max",
"(",
"currentTimestamp",
",",
"timestamp",
")",
";",
"for",
"(",
"RaftSession",
"session",
":",
"sessions",
".",
"getSessions",
"(",
"primitiveId",
")",
")",
"{",
"session",
".",
"setLastUpdated",
"(",
"timestamp",
")",
";",
"}",
"}"
] | Keeps all sessions alive using the given timestamp.
@param index the index of the timestamp
@param timestamp the timestamp with which to reset session timeouts | [
"Keeps",
"all",
"sessions",
"alive",
"using",
"the",
"given",
"timestamp",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L423-L432 |
27,358 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.closeSession | public void closeSession(long index, long timestamp, RaftSession session, boolean expired) {
log.debug("Closing session {}", session.sessionId());
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Update the state machine index/timestamp.
tick(index, timestamp);
// Expire sessions that have timed out.
expireSessions(currentTimestamp);
// Remove the session from the sessions list.
if (expired) {
session = sessions.removeSession(session.sessionId());
if (session != null) {
session.expire();
service.expire(session.sessionId());
}
} else {
session = sessions.removeSession(session.sessionId());
if (session != null) {
session.close();
service.close(session.sessionId());
}
}
// Commit the index, causing events to be sent to clients if necessary.
commit();
} | java | public void closeSession(long index, long timestamp, RaftSession session, boolean expired) {
log.debug("Closing session {}", session.sessionId());
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Update the state machine index/timestamp.
tick(index, timestamp);
// Expire sessions that have timed out.
expireSessions(currentTimestamp);
// Remove the session from the sessions list.
if (expired) {
session = sessions.removeSession(session.sessionId());
if (session != null) {
session.expire();
service.expire(session.sessionId());
}
} else {
session = sessions.removeSession(session.sessionId());
if (session != null) {
session.close();
service.close(session.sessionId());
}
}
// Commit the index, causing events to be sent to clients if necessary.
commit();
} | [
"public",
"void",
"closeSession",
"(",
"long",
"index",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
",",
"boolean",
"expired",
")",
"{",
"log",
".",
"debug",
"(",
"\"Closing session {}\"",
",",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"// Update the session's timestamp to prevent it from being expired.",
"session",
".",
"setLastUpdated",
"(",
"timestamp",
")",
";",
"// Update the state machine index/timestamp.",
"tick",
"(",
"index",
",",
"timestamp",
")",
";",
"// Expire sessions that have timed out.",
"expireSessions",
"(",
"currentTimestamp",
")",
";",
"// Remove the session from the sessions list.",
"if",
"(",
"expired",
")",
"{",
"session",
"=",
"sessions",
".",
"removeSession",
"(",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"if",
"(",
"session",
"!=",
"null",
")",
"{",
"session",
".",
"expire",
"(",
")",
";",
"service",
".",
"expire",
"(",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"session",
"=",
"sessions",
".",
"removeSession",
"(",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"if",
"(",
"session",
"!=",
"null",
")",
"{",
"session",
".",
"close",
"(",
")",
";",
"service",
".",
"close",
"(",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"}",
"}",
"// Commit the index, causing events to be sent to clients if necessary.",
"commit",
"(",
")",
";",
"}"
] | Unregister the given session.
@param index The index of the unregister.
@param timestamp The timestamp of the unregister.
@param session The session to unregister.
@param expired Whether the session was expired by the leader. | [
"Unregister",
"the",
"given",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L442-L471 |
27,359 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.executeCommand | public OperationResult executeCommand(long index, long sequence, long timestamp, RaftSession session, PrimitiveOperation operation) {
// If the service has been deleted then throw an unknown service exception.
if (deleted) {
log.warn("Service {} has been deleted by another process", serviceName);
throw new RaftException.UnknownService("Service " + serviceName + " has been deleted");
}
// If the session is not open, fail the request.
if (!session.getState().active()) {
log.warn("Session not open: {}", session);
throw new RaftException.UnknownSession("Unknown session: " + session.sessionId());
}
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Update the state machine index/timestamp.
tick(index, timestamp);
// If the command's sequence number is less than the next session sequence number then that indicates that
// we've received a command that was previously applied to the state machine. Ensure linearizability by
// returning the cached response instead of applying it to the user defined state machine.
if (sequence > 0 && sequence < session.nextCommandSequence()) {
log.trace("Returning cached result for command with sequence number {} < {}", sequence, session.nextCommandSequence());
return sequenceCommand(index, sequence, session);
}
// If we've made it this far, the command must have been applied in the proper order as sequenced by the
// session. This should be the case for most commands applied to the state machine.
else {
// Execute the command in the state machine thread. Once complete, the CompletableFuture callback will be completed
// in the state machine thread. Register the result in that thread and then complete the future in the caller's thread.
return applyCommand(index, sequence, timestamp, operation, session);
}
} | java | public OperationResult executeCommand(long index, long sequence, long timestamp, RaftSession session, PrimitiveOperation operation) {
// If the service has been deleted then throw an unknown service exception.
if (deleted) {
log.warn("Service {} has been deleted by another process", serviceName);
throw new RaftException.UnknownService("Service " + serviceName + " has been deleted");
}
// If the session is not open, fail the request.
if (!session.getState().active()) {
log.warn("Session not open: {}", session);
throw new RaftException.UnknownSession("Unknown session: " + session.sessionId());
}
// Update the session's timestamp to prevent it from being expired.
session.setLastUpdated(timestamp);
// Update the state machine index/timestamp.
tick(index, timestamp);
// If the command's sequence number is less than the next session sequence number then that indicates that
// we've received a command that was previously applied to the state machine. Ensure linearizability by
// returning the cached response instead of applying it to the user defined state machine.
if (sequence > 0 && sequence < session.nextCommandSequence()) {
log.trace("Returning cached result for command with sequence number {} < {}", sequence, session.nextCommandSequence());
return sequenceCommand(index, sequence, session);
}
// If we've made it this far, the command must have been applied in the proper order as sequenced by the
// session. This should be the case for most commands applied to the state machine.
else {
// Execute the command in the state machine thread. Once complete, the CompletableFuture callback will be completed
// in the state machine thread. Register the result in that thread and then complete the future in the caller's thread.
return applyCommand(index, sequence, timestamp, operation, session);
}
} | [
"public",
"OperationResult",
"executeCommand",
"(",
"long",
"index",
",",
"long",
"sequence",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
",",
"PrimitiveOperation",
"operation",
")",
"{",
"// If the service has been deleted then throw an unknown service exception.",
"if",
"(",
"deleted",
")",
"{",
"log",
".",
"warn",
"(",
"\"Service {} has been deleted by another process\"",
",",
"serviceName",
")",
";",
"throw",
"new",
"RaftException",
".",
"UnknownService",
"(",
"\"Service \"",
"+",
"serviceName",
"+",
"\" has been deleted\"",
")",
";",
"}",
"// If the session is not open, fail the request.",
"if",
"(",
"!",
"session",
".",
"getState",
"(",
")",
".",
"active",
"(",
")",
")",
"{",
"log",
".",
"warn",
"(",
"\"Session not open: {}\"",
",",
"session",
")",
";",
"throw",
"new",
"RaftException",
".",
"UnknownSession",
"(",
"\"Unknown session: \"",
"+",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"}",
"// Update the session's timestamp to prevent it from being expired.",
"session",
".",
"setLastUpdated",
"(",
"timestamp",
")",
";",
"// Update the state machine index/timestamp.",
"tick",
"(",
"index",
",",
"timestamp",
")",
";",
"// If the command's sequence number is less than the next session sequence number then that indicates that",
"// we've received a command that was previously applied to the state machine. Ensure linearizability by",
"// returning the cached response instead of applying it to the user defined state machine.",
"if",
"(",
"sequence",
">",
"0",
"&&",
"sequence",
"<",
"session",
".",
"nextCommandSequence",
"(",
")",
")",
"{",
"log",
".",
"trace",
"(",
"\"Returning cached result for command with sequence number {} < {}\"",
",",
"sequence",
",",
"session",
".",
"nextCommandSequence",
"(",
")",
")",
";",
"return",
"sequenceCommand",
"(",
"index",
",",
"sequence",
",",
"session",
")",
";",
"}",
"// If we've made it this far, the command must have been applied in the proper order as sequenced by the",
"// session. This should be the case for most commands applied to the state machine.",
"else",
"{",
"// Execute the command in the state machine thread. Once complete, the CompletableFuture callback will be completed",
"// in the state machine thread. Register the result in that thread and then complete the future in the caller's thread.",
"return",
"applyCommand",
"(",
"index",
",",
"sequence",
",",
"timestamp",
",",
"operation",
",",
"session",
")",
";",
"}",
"}"
] | Executes the given command on the state machine.
@param index The index of the command.
@param timestamp The timestamp of the command.
@param sequence The command sequence number.
@param session The session that submitted the command.
@param operation The command to execute.
@return A future to be completed with the command result. | [
"Executes",
"the",
"given",
"command",
"on",
"the",
"state",
"machine",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L483-L516 |
27,360 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.sequenceCommand | private OperationResult sequenceCommand(long index, long sequence, RaftSession session) {
OperationResult result = session.getResult(sequence);
if (result == null) {
log.debug("Missing command result at index {}", index);
}
return result;
} | java | private OperationResult sequenceCommand(long index, long sequence, RaftSession session) {
OperationResult result = session.getResult(sequence);
if (result == null) {
log.debug("Missing command result at index {}", index);
}
return result;
} | [
"private",
"OperationResult",
"sequenceCommand",
"(",
"long",
"index",
",",
"long",
"sequence",
",",
"RaftSession",
"session",
")",
"{",
"OperationResult",
"result",
"=",
"session",
".",
"getResult",
"(",
"sequence",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"log",
".",
"debug",
"(",
"\"Missing command result at index {}\"",
",",
"index",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Loads and returns a cached command result according to the sequence number. | [
"Loads",
"and",
"returns",
"a",
"cached",
"command",
"result",
"according",
"to",
"the",
"sequence",
"number",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L521-L527 |
27,361 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.applyCommand | private OperationResult applyCommand(long index, long sequence, long timestamp, PrimitiveOperation operation, RaftSession session) {
long eventIndex = session.getEventIndex();
Commit<byte[]> commit = new DefaultCommit<>(index, operation.id(), operation.value(), session, timestamp);
OperationResult result;
try {
currentSession = session;
// Execute the state machine operation and get the result.
byte[] output = service.apply(commit);
// Store the result for linearizability and complete the command.
result = OperationResult.succeeded(index, eventIndex, output);
} catch (Exception e) {
// If an exception occurs during execution of the command, store the exception.
result = OperationResult.failed(index, eventIndex, e);
} finally {
currentSession = null;
}
// Once the operation has been applied to the state machine, commit events published by the command.
// The state machine context will build a composite future for events published to all sessions.
commit();
// Register the result in the session to ensure retries receive the same output for the command.
session.registerResult(sequence, result);
// Update the session timestamp and command sequence number.
session.setCommandSequence(sequence);
// Complete the command.
return result;
} | java | private OperationResult applyCommand(long index, long sequence, long timestamp, PrimitiveOperation operation, RaftSession session) {
long eventIndex = session.getEventIndex();
Commit<byte[]> commit = new DefaultCommit<>(index, operation.id(), operation.value(), session, timestamp);
OperationResult result;
try {
currentSession = session;
// Execute the state machine operation and get the result.
byte[] output = service.apply(commit);
// Store the result for linearizability and complete the command.
result = OperationResult.succeeded(index, eventIndex, output);
} catch (Exception e) {
// If an exception occurs during execution of the command, store the exception.
result = OperationResult.failed(index, eventIndex, e);
} finally {
currentSession = null;
}
// Once the operation has been applied to the state machine, commit events published by the command.
// The state machine context will build a composite future for events published to all sessions.
commit();
// Register the result in the session to ensure retries receive the same output for the command.
session.registerResult(sequence, result);
// Update the session timestamp and command sequence number.
session.setCommandSequence(sequence);
// Complete the command.
return result;
} | [
"private",
"OperationResult",
"applyCommand",
"(",
"long",
"index",
",",
"long",
"sequence",
",",
"long",
"timestamp",
",",
"PrimitiveOperation",
"operation",
",",
"RaftSession",
"session",
")",
"{",
"long",
"eventIndex",
"=",
"session",
".",
"getEventIndex",
"(",
")",
";",
"Commit",
"<",
"byte",
"[",
"]",
">",
"commit",
"=",
"new",
"DefaultCommit",
"<>",
"(",
"index",
",",
"operation",
".",
"id",
"(",
")",
",",
"operation",
".",
"value",
"(",
")",
",",
"session",
",",
"timestamp",
")",
";",
"OperationResult",
"result",
";",
"try",
"{",
"currentSession",
"=",
"session",
";",
"// Execute the state machine operation and get the result.",
"byte",
"[",
"]",
"output",
"=",
"service",
".",
"apply",
"(",
"commit",
")",
";",
"// Store the result for linearizability and complete the command.",
"result",
"=",
"OperationResult",
".",
"succeeded",
"(",
"index",
",",
"eventIndex",
",",
"output",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// If an exception occurs during execution of the command, store the exception.",
"result",
"=",
"OperationResult",
".",
"failed",
"(",
"index",
",",
"eventIndex",
",",
"e",
")",
";",
"}",
"finally",
"{",
"currentSession",
"=",
"null",
";",
"}",
"// Once the operation has been applied to the state machine, commit events published by the command.",
"// The state machine context will build a composite future for events published to all sessions.",
"commit",
"(",
")",
";",
"// Register the result in the session to ensure retries receive the same output for the command.",
"session",
".",
"registerResult",
"(",
"sequence",
",",
"result",
")",
";",
"// Update the session timestamp and command sequence number.",
"session",
".",
"setCommandSequence",
"(",
"sequence",
")",
";",
"// Complete the command.",
"return",
"result",
";",
"}"
] | Applies the given commit to the state machine. | [
"Applies",
"the",
"given",
"commit",
"to",
"the",
"state",
"machine",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L532-L565 |
27,362 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.executeQuery | public CompletableFuture<OperationResult> executeQuery(
long index,
long sequence,
long timestamp,
RaftSession session,
PrimitiveOperation operation) {
CompletableFuture<OperationResult> future = new CompletableFuture<>();
executeQuery(index, sequence, timestamp, session, operation, future);
return future;
} | java | public CompletableFuture<OperationResult> executeQuery(
long index,
long sequence,
long timestamp,
RaftSession session,
PrimitiveOperation operation) {
CompletableFuture<OperationResult> future = new CompletableFuture<>();
executeQuery(index, sequence, timestamp, session, operation, future);
return future;
} | [
"public",
"CompletableFuture",
"<",
"OperationResult",
">",
"executeQuery",
"(",
"long",
"index",
",",
"long",
"sequence",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
",",
"PrimitiveOperation",
"operation",
")",
"{",
"CompletableFuture",
"<",
"OperationResult",
">",
"future",
"=",
"new",
"CompletableFuture",
"<>",
"(",
")",
";",
"executeQuery",
"(",
"index",
",",
"sequence",
",",
"timestamp",
",",
"session",
",",
"operation",
",",
"future",
")",
";",
"return",
"future",
";",
"}"
] | Executes the given query on the state machine.
@param index The index of the query.
@param sequence The query sequence number.
@param timestamp The timestamp of the query.
@param session The session that submitted the query.
@param operation The query to execute.
@return A future to be completed with the query result. | [
"Executes",
"the",
"given",
"query",
"on",
"the",
"state",
"machine",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L577-L586 |
27,363 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.executeQuery | private void executeQuery(
long index,
long sequence,
long timestamp,
RaftSession session,
PrimitiveOperation operation,
CompletableFuture<OperationResult> future) {
// If the service has been deleted then throw an unknown service exception.
if (deleted) {
log.warn("Service {} has been deleted by another process", serviceName);
future.completeExceptionally(new RaftException.UnknownService("Service " + serviceName + " has been deleted"));
return;
}
// If the session is not open, fail the request.
if (!session.getState().active()) {
log.warn("Inactive session: " + session.sessionId());
future.completeExceptionally(new RaftException.UnknownSession("Unknown session: " + session.sessionId()));
return;
}
// Otherwise, sequence the query.
sequenceQuery(index, sequence, timestamp, session, operation, future);
} | java | private void executeQuery(
long index,
long sequence,
long timestamp,
RaftSession session,
PrimitiveOperation operation,
CompletableFuture<OperationResult> future) {
// If the service has been deleted then throw an unknown service exception.
if (deleted) {
log.warn("Service {} has been deleted by another process", serviceName);
future.completeExceptionally(new RaftException.UnknownService("Service " + serviceName + " has been deleted"));
return;
}
// If the session is not open, fail the request.
if (!session.getState().active()) {
log.warn("Inactive session: " + session.sessionId());
future.completeExceptionally(new RaftException.UnknownSession("Unknown session: " + session.sessionId()));
return;
}
// Otherwise, sequence the query.
sequenceQuery(index, sequence, timestamp, session, operation, future);
} | [
"private",
"void",
"executeQuery",
"(",
"long",
"index",
",",
"long",
"sequence",
",",
"long",
"timestamp",
",",
"RaftSession",
"session",
",",
"PrimitiveOperation",
"operation",
",",
"CompletableFuture",
"<",
"OperationResult",
">",
"future",
")",
"{",
"// If the service has been deleted then throw an unknown service exception.",
"if",
"(",
"deleted",
")",
"{",
"log",
".",
"warn",
"(",
"\"Service {} has been deleted by another process\"",
",",
"serviceName",
")",
";",
"future",
".",
"completeExceptionally",
"(",
"new",
"RaftException",
".",
"UnknownService",
"(",
"\"Service \"",
"+",
"serviceName",
"+",
"\" has been deleted\"",
")",
")",
";",
"return",
";",
"}",
"// If the session is not open, fail the request.",
"if",
"(",
"!",
"session",
".",
"getState",
"(",
")",
".",
"active",
"(",
")",
")",
"{",
"log",
".",
"warn",
"(",
"\"Inactive session: \"",
"+",
"session",
".",
"sessionId",
"(",
")",
")",
";",
"future",
".",
"completeExceptionally",
"(",
"new",
"RaftException",
".",
"UnknownSession",
"(",
"\"Unknown session: \"",
"+",
"session",
".",
"sessionId",
"(",
")",
")",
")",
";",
"return",
";",
"}",
"// Otherwise, sequence the query.",
"sequenceQuery",
"(",
"index",
",",
"sequence",
",",
"timestamp",
",",
"session",
",",
"operation",
",",
"future",
")",
";",
"}"
] | Executes a query on the state machine thread. | [
"Executes",
"a",
"query",
"on",
"the",
"state",
"machine",
"thread",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L591-L614 |
27,364 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java | RaftServiceContext.close | public void close() {
for (RaftSession serviceSession : sessions.getSessions(serviceId())) {
serviceSession.close();
service.close(serviceSession.sessionId());
}
service.close();
deleted = true;
} | java | public void close() {
for (RaftSession serviceSession : sessions.getSessions(serviceId())) {
serviceSession.close();
service.close(serviceSession.sessionId());
}
service.close();
deleted = true;
} | [
"public",
"void",
"close",
"(",
")",
"{",
"for",
"(",
"RaftSession",
"serviceSession",
":",
"sessions",
".",
"getSessions",
"(",
"serviceId",
"(",
")",
")",
")",
"{",
"serviceSession",
".",
"close",
"(",
")",
";",
"service",
".",
"close",
"(",
"serviceSession",
".",
"sessionId",
"(",
")",
")",
";",
"}",
"service",
".",
"close",
"(",
")",
";",
"deleted",
"=",
"true",
";",
"}"
] | Closes the service context. | [
"Closes",
"the",
"service",
"context",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L707-L714 |
27,365 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/impl/DefaultRaftServer.java | DefaultRaftServer.shutdown | public CompletableFuture<Void> shutdown() {
if (!started) {
return Futures.exceptionalFuture(new IllegalStateException("Server not running"));
}
CompletableFuture<Void> future = new AtomixFuture<>();
context.getThreadContext().execute(() -> {
started = false;
context.transition(Role.INACTIVE);
future.complete(null);
});
return future.whenCompleteAsync((result, error) -> {
context.close();
started = false;
});
} | java | public CompletableFuture<Void> shutdown() {
if (!started) {
return Futures.exceptionalFuture(new IllegalStateException("Server not running"));
}
CompletableFuture<Void> future = new AtomixFuture<>();
context.getThreadContext().execute(() -> {
started = false;
context.transition(Role.INACTIVE);
future.complete(null);
});
return future.whenCompleteAsync((result, error) -> {
context.close();
started = false;
});
} | [
"public",
"CompletableFuture",
"<",
"Void",
">",
"shutdown",
"(",
")",
"{",
"if",
"(",
"!",
"started",
")",
"{",
"return",
"Futures",
".",
"exceptionalFuture",
"(",
"new",
"IllegalStateException",
"(",
"\"Server not running\"",
")",
")",
";",
"}",
"CompletableFuture",
"<",
"Void",
">",
"future",
"=",
"new",
"AtomixFuture",
"<>",
"(",
")",
";",
"context",
".",
"getThreadContext",
"(",
")",
".",
"execute",
"(",
"(",
")",
"->",
"{",
"started",
"=",
"false",
";",
"context",
".",
"transition",
"(",
"Role",
".",
"INACTIVE",
")",
";",
"future",
".",
"complete",
"(",
"null",
")",
";",
"}",
")",
";",
"return",
"future",
".",
"whenCompleteAsync",
"(",
"(",
"result",
",",
"error",
")",
"->",
"{",
"context",
".",
"close",
"(",
")",
";",
"started",
"=",
"false",
";",
"}",
")",
";",
"}"
] | Shuts down the server without leaving the Raft cluster.
@return A completable future to be completed once the server has been shutdown. | [
"Shuts",
"down",
"the",
"server",
"without",
"leaving",
"the",
"Raft",
"cluster",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/impl/DefaultRaftServer.java#L159-L175 |
27,366 | atomix/atomix | utils/src/main/java/io/atomix/utils/Generics.java | Generics.getGenericClassType | public static Type getGenericClassType(Object instance, Class<?> clazz, int position) {
Class<?> type = instance.getClass();
while (type != Object.class) {
if (type.getGenericSuperclass() instanceof ParameterizedType) {
ParameterizedType genericSuperclass = (ParameterizedType) type.getGenericSuperclass();
if (genericSuperclass.getRawType() == clazz) {
return genericSuperclass.getActualTypeArguments()[position];
} else {
type = type.getSuperclass();
}
} else {
type = type.getSuperclass();
}
}
return null;
} | java | public static Type getGenericClassType(Object instance, Class<?> clazz, int position) {
Class<?> type = instance.getClass();
while (type != Object.class) {
if (type.getGenericSuperclass() instanceof ParameterizedType) {
ParameterizedType genericSuperclass = (ParameterizedType) type.getGenericSuperclass();
if (genericSuperclass.getRawType() == clazz) {
return genericSuperclass.getActualTypeArguments()[position];
} else {
type = type.getSuperclass();
}
} else {
type = type.getSuperclass();
}
}
return null;
} | [
"public",
"static",
"Type",
"getGenericClassType",
"(",
"Object",
"instance",
",",
"Class",
"<",
"?",
">",
"clazz",
",",
"int",
"position",
")",
"{",
"Class",
"<",
"?",
">",
"type",
"=",
"instance",
".",
"getClass",
"(",
")",
";",
"while",
"(",
"type",
"!=",
"Object",
".",
"class",
")",
"{",
"if",
"(",
"type",
".",
"getGenericSuperclass",
"(",
")",
"instanceof",
"ParameterizedType",
")",
"{",
"ParameterizedType",
"genericSuperclass",
"=",
"(",
"ParameterizedType",
")",
"type",
".",
"getGenericSuperclass",
"(",
")",
";",
"if",
"(",
"genericSuperclass",
".",
"getRawType",
"(",
")",
"==",
"clazz",
")",
"{",
"return",
"genericSuperclass",
".",
"getActualTypeArguments",
"(",
")",
"[",
"position",
"]",
";",
"}",
"else",
"{",
"type",
"=",
"type",
".",
"getSuperclass",
"(",
")",
";",
"}",
"}",
"else",
"{",
"type",
"=",
"type",
".",
"getSuperclass",
"(",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns the generic type at the given position for the given class.
@param instance the implementing instance
@param clazz the generic class
@param position the generic position
@return the generic type at the given position | [
"Returns",
"the",
"generic",
"type",
"at",
"the",
"given",
"position",
"for",
"the",
"given",
"class",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/Generics.java#L34-L49 |
27,367 | atomix/atomix | utils/src/main/java/io/atomix/utils/Generics.java | Generics.getGenericInterfaceType | public static Type getGenericInterfaceType(Object instance, Class<?> iface, int position) {
Class<?> type = instance.getClass();
while (type != Object.class) {
for (Type genericType : type.getGenericInterfaces()) {
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
if (parameterizedType.getRawType() == iface) {
return parameterizedType.getActualTypeArguments()[position];
}
}
}
type = type.getSuperclass();
}
return null;
} | java | public static Type getGenericInterfaceType(Object instance, Class<?> iface, int position) {
Class<?> type = instance.getClass();
while (type != Object.class) {
for (Type genericType : type.getGenericInterfaces()) {
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
if (parameterizedType.getRawType() == iface) {
return parameterizedType.getActualTypeArguments()[position];
}
}
}
type = type.getSuperclass();
}
return null;
} | [
"public",
"static",
"Type",
"getGenericInterfaceType",
"(",
"Object",
"instance",
",",
"Class",
"<",
"?",
">",
"iface",
",",
"int",
"position",
")",
"{",
"Class",
"<",
"?",
">",
"type",
"=",
"instance",
".",
"getClass",
"(",
")",
";",
"while",
"(",
"type",
"!=",
"Object",
".",
"class",
")",
"{",
"for",
"(",
"Type",
"genericType",
":",
"type",
".",
"getGenericInterfaces",
"(",
")",
")",
"{",
"if",
"(",
"genericType",
"instanceof",
"ParameterizedType",
")",
"{",
"ParameterizedType",
"parameterizedType",
"=",
"(",
"ParameterizedType",
")",
"genericType",
";",
"if",
"(",
"parameterizedType",
".",
"getRawType",
"(",
")",
"==",
"iface",
")",
"{",
"return",
"parameterizedType",
".",
"getActualTypeArguments",
"(",
")",
"[",
"position",
"]",
";",
"}",
"}",
"}",
"type",
"=",
"type",
".",
"getSuperclass",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Returns the generic type at the given position for the given interface.
@param instance the implementing instance
@param iface the generic interface
@param position the generic position
@return the generic type at the given position | [
"Returns",
"the",
"generic",
"type",
"at",
"the",
"given",
"position",
"for",
"the",
"given",
"interface",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/Generics.java#L59-L73 |
27,368 | atomix/atomix | protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/PrimaryRole.java | PrimaryRole.heartbeat | private void heartbeat() {
long index = context.nextIndex();
long timestamp = System.currentTimeMillis();
replicator.replicate(new HeartbeatOperation(index, timestamp))
.thenRun(() -> context.setTimestamp(timestamp));
} | java | private void heartbeat() {
long index = context.nextIndex();
long timestamp = System.currentTimeMillis();
replicator.replicate(new HeartbeatOperation(index, timestamp))
.thenRun(() -> context.setTimestamp(timestamp));
} | [
"private",
"void",
"heartbeat",
"(",
")",
"{",
"long",
"index",
"=",
"context",
".",
"nextIndex",
"(",
")",
";",
"long",
"timestamp",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"replicator",
".",
"replicate",
"(",
"new",
"HeartbeatOperation",
"(",
"index",
",",
"timestamp",
")",
")",
".",
"thenRun",
"(",
"(",
")",
"->",
"context",
".",
"setTimestamp",
"(",
"timestamp",
")",
")",
";",
"}"
] | Applies a heartbeat to the service to ensure timers can be triggered. | [
"Applies",
"a",
"heartbeat",
"to",
"the",
"service",
"to",
"ensure",
"timers",
"can",
"be",
"triggered",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/roles/PrimaryRole.java#L71-L76 |
27,369 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSessionRegistry.java | RaftSessionRegistry.addSession | public RaftSession addSession(RaftSession session) {
RaftSession existingSession = sessions.putIfAbsent(session.sessionId().id(), session);
return existingSession != null ? existingSession : session;
} | java | public RaftSession addSession(RaftSession session) {
RaftSession existingSession = sessions.putIfAbsent(session.sessionId().id(), session);
return existingSession != null ? existingSession : session;
} | [
"public",
"RaftSession",
"addSession",
"(",
"RaftSession",
"session",
")",
"{",
"RaftSession",
"existingSession",
"=",
"sessions",
".",
"putIfAbsent",
"(",
"session",
".",
"sessionId",
"(",
")",
".",
"id",
"(",
")",
",",
"session",
")",
";",
"return",
"existingSession",
"!=",
"null",
"?",
"existingSession",
":",
"session",
";",
"}"
] | Adds a session. | [
"Adds",
"a",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSessionRegistry.java#L35-L38 |
27,370 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSessionRegistry.java | RaftSessionRegistry.getSessions | public Collection<RaftSession> getSessions(PrimitiveId primitiveId) {
return sessions.values().stream()
.filter(session -> session.getService().serviceId().equals(primitiveId))
.filter(session -> session.getState().active())
.collect(Collectors.toSet());
} | java | public Collection<RaftSession> getSessions(PrimitiveId primitiveId) {
return sessions.values().stream()
.filter(session -> session.getService().serviceId().equals(primitiveId))
.filter(session -> session.getState().active())
.collect(Collectors.toSet());
} | [
"public",
"Collection",
"<",
"RaftSession",
">",
"getSessions",
"(",
"PrimitiveId",
"primitiveId",
")",
"{",
"return",
"sessions",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"session",
"->",
"session",
".",
"getService",
"(",
")",
".",
"serviceId",
"(",
")",
".",
"equals",
"(",
"primitiveId",
")",
")",
".",
"filter",
"(",
"session",
"->",
"session",
".",
"getState",
"(",
")",
".",
"active",
"(",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"}"
] | Returns a set of sessions associated with the given service.
@param primitiveId the service identifier
@return a collection of sessions associated with the given service | [
"Returns",
"a",
"set",
"of",
"sessions",
"associated",
"with",
"the",
"given",
"service",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSessionRegistry.java#L82-L87 |
27,371 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSessionRegistry.java | RaftSessionRegistry.removeSessions | public void removeSessions(PrimitiveId primitiveId) {
sessions.entrySet().removeIf(e -> e.getValue().getService().serviceId().equals(primitiveId));
} | java | public void removeSessions(PrimitiveId primitiveId) {
sessions.entrySet().removeIf(e -> e.getValue().getService().serviceId().equals(primitiveId));
} | [
"public",
"void",
"removeSessions",
"(",
"PrimitiveId",
"primitiveId",
")",
"{",
"sessions",
".",
"entrySet",
"(",
")",
".",
"removeIf",
"(",
"e",
"->",
"e",
".",
"getValue",
"(",
")",
".",
"getService",
"(",
")",
".",
"serviceId",
"(",
")",
".",
"equals",
"(",
"primitiveId",
")",
")",
";",
"}"
] | Removes all sessions registered for the given service.
@param primitiveId the service identifier | [
"Removes",
"all",
"sessions",
"registered",
"for",
"the",
"given",
"service",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSessionRegistry.java#L94-L96 |
27,372 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotDescriptor.java | SnapshotDescriptor.copyTo | SnapshotDescriptor copyTo(Buffer buffer) {
this.buffer = buffer
.writeLong(index)
.writeLong(timestamp)
.writeInt(version)
.writeBoolean(locked)
.skip(BYTES - buffer.position())
.flush();
return this;
} | java | SnapshotDescriptor copyTo(Buffer buffer) {
this.buffer = buffer
.writeLong(index)
.writeLong(timestamp)
.writeInt(version)
.writeBoolean(locked)
.skip(BYTES - buffer.position())
.flush();
return this;
} | [
"SnapshotDescriptor",
"copyTo",
"(",
"Buffer",
"buffer",
")",
"{",
"this",
".",
"buffer",
"=",
"buffer",
".",
"writeLong",
"(",
"index",
")",
".",
"writeLong",
"(",
"timestamp",
")",
".",
"writeInt",
"(",
"version",
")",
".",
"writeBoolean",
"(",
"locked",
")",
".",
"skip",
"(",
"BYTES",
"-",
"buffer",
".",
"position",
"(",
")",
")",
".",
"flush",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Copies the snapshot to a new buffer. | [
"Copies",
"the",
"snapshot",
"to",
"a",
"new",
"buffer",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotDescriptor.java#L126-L135 |
27,373 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java | RaftSessionManager.resetConnections | public void resetConnections(MemberId leader, Collection<MemberId> servers) {
selectorManager.resetAll(leader, servers);
} | java | public void resetConnections(MemberId leader, Collection<MemberId> servers) {
selectorManager.resetAll(leader, servers);
} | [
"public",
"void",
"resetConnections",
"(",
"MemberId",
"leader",
",",
"Collection",
"<",
"MemberId",
">",
"servers",
")",
"{",
"selectorManager",
".",
"resetAll",
"(",
"leader",
",",
"servers",
")",
";",
"}"
] | Resets the session manager's cluster information.
@param leader The leader address.
@param servers The collection of servers. | [
"Resets",
"the",
"session",
"manager",
"s",
"cluster",
"information",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java#L131-L133 |
27,374 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java | RaftSessionManager.openSession | public CompletableFuture<RaftSessionState> openSession(
String serviceName,
PrimitiveType primitiveType,
ServiceConfig config,
ReadConsistency readConsistency,
CommunicationStrategy communicationStrategy,
Duration minTimeout,
Duration maxTimeout) {
checkNotNull(serviceName, "serviceName cannot be null");
checkNotNull(primitiveType, "serviceType cannot be null");
checkNotNull(communicationStrategy, "communicationStrategy cannot be null");
checkNotNull(maxTimeout, "timeout cannot be null");
log.debug("Opening session; name: {}, type: {}", serviceName, primitiveType);
OpenSessionRequest request = OpenSessionRequest.builder()
.withMemberId(memberId)
.withServiceName(serviceName)
.withServiceType(primitiveType)
.withServiceConfig(Serializer.using(primitiveType.namespace()).encode(config))
.withReadConsistency(readConsistency)
.withMinTimeout(minTimeout.toMillis())
.withMaxTimeout(maxTimeout.toMillis())
.build();
CompletableFuture<RaftSessionState> future = new CompletableFuture<>();
ThreadContext proxyContext = threadContextFactory.createContext();
connection.openSession(request).whenCompleteAsync((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
// Create and store the proxy state.
RaftSessionState state = new RaftSessionState(
clientId,
SessionId.from(response.session()),
serviceName,
primitiveType,
response.timeout());
sessions.put(state.getSessionId().id(), state);
state.addStateChangeListener(s -> {
if (s == PrimitiveState.EXPIRED || s == PrimitiveState.CLOSED) {
sessions.remove(state.getSessionId().id());
}
});
// Ensure the proxy session info is reset and the session is kept alive.
keepAliveSessions(System.currentTimeMillis(), state.getSessionTimeout());
future.complete(state);
} else {
future.completeExceptionally(new RaftException.Unavailable(response.error().message()));
}
} else {
future.completeExceptionally(new RaftException.Unavailable(error.getMessage()));
}
}, proxyContext);
return future;
} | java | public CompletableFuture<RaftSessionState> openSession(
String serviceName,
PrimitiveType primitiveType,
ServiceConfig config,
ReadConsistency readConsistency,
CommunicationStrategy communicationStrategy,
Duration minTimeout,
Duration maxTimeout) {
checkNotNull(serviceName, "serviceName cannot be null");
checkNotNull(primitiveType, "serviceType cannot be null");
checkNotNull(communicationStrategy, "communicationStrategy cannot be null");
checkNotNull(maxTimeout, "timeout cannot be null");
log.debug("Opening session; name: {}, type: {}", serviceName, primitiveType);
OpenSessionRequest request = OpenSessionRequest.builder()
.withMemberId(memberId)
.withServiceName(serviceName)
.withServiceType(primitiveType)
.withServiceConfig(Serializer.using(primitiveType.namespace()).encode(config))
.withReadConsistency(readConsistency)
.withMinTimeout(minTimeout.toMillis())
.withMaxTimeout(maxTimeout.toMillis())
.build();
CompletableFuture<RaftSessionState> future = new CompletableFuture<>();
ThreadContext proxyContext = threadContextFactory.createContext();
connection.openSession(request).whenCompleteAsync((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
// Create and store the proxy state.
RaftSessionState state = new RaftSessionState(
clientId,
SessionId.from(response.session()),
serviceName,
primitiveType,
response.timeout());
sessions.put(state.getSessionId().id(), state);
state.addStateChangeListener(s -> {
if (s == PrimitiveState.EXPIRED || s == PrimitiveState.CLOSED) {
sessions.remove(state.getSessionId().id());
}
});
// Ensure the proxy session info is reset and the session is kept alive.
keepAliveSessions(System.currentTimeMillis(), state.getSessionTimeout());
future.complete(state);
} else {
future.completeExceptionally(new RaftException.Unavailable(response.error().message()));
}
} else {
future.completeExceptionally(new RaftException.Unavailable(error.getMessage()));
}
}, proxyContext);
return future;
} | [
"public",
"CompletableFuture",
"<",
"RaftSessionState",
">",
"openSession",
"(",
"String",
"serviceName",
",",
"PrimitiveType",
"primitiveType",
",",
"ServiceConfig",
"config",
",",
"ReadConsistency",
"readConsistency",
",",
"CommunicationStrategy",
"communicationStrategy",
",",
"Duration",
"minTimeout",
",",
"Duration",
"maxTimeout",
")",
"{",
"checkNotNull",
"(",
"serviceName",
",",
"\"serviceName cannot be null\"",
")",
";",
"checkNotNull",
"(",
"primitiveType",
",",
"\"serviceType cannot be null\"",
")",
";",
"checkNotNull",
"(",
"communicationStrategy",
",",
"\"communicationStrategy cannot be null\"",
")",
";",
"checkNotNull",
"(",
"maxTimeout",
",",
"\"timeout cannot be null\"",
")",
";",
"log",
".",
"debug",
"(",
"\"Opening session; name: {}, type: {}\"",
",",
"serviceName",
",",
"primitiveType",
")",
";",
"OpenSessionRequest",
"request",
"=",
"OpenSessionRequest",
".",
"builder",
"(",
")",
".",
"withMemberId",
"(",
"memberId",
")",
".",
"withServiceName",
"(",
"serviceName",
")",
".",
"withServiceType",
"(",
"primitiveType",
")",
".",
"withServiceConfig",
"(",
"Serializer",
".",
"using",
"(",
"primitiveType",
".",
"namespace",
"(",
")",
")",
".",
"encode",
"(",
"config",
")",
")",
".",
"withReadConsistency",
"(",
"readConsistency",
")",
".",
"withMinTimeout",
"(",
"minTimeout",
".",
"toMillis",
"(",
")",
")",
".",
"withMaxTimeout",
"(",
"maxTimeout",
".",
"toMillis",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"CompletableFuture",
"<",
"RaftSessionState",
">",
"future",
"=",
"new",
"CompletableFuture",
"<>",
"(",
")",
";",
"ThreadContext",
"proxyContext",
"=",
"threadContextFactory",
".",
"createContext",
"(",
")",
";",
"connection",
".",
"openSession",
"(",
"request",
")",
".",
"whenCompleteAsync",
"(",
"(",
"response",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"if",
"(",
"response",
".",
"status",
"(",
")",
"==",
"RaftResponse",
".",
"Status",
".",
"OK",
")",
"{",
"// Create and store the proxy state.",
"RaftSessionState",
"state",
"=",
"new",
"RaftSessionState",
"(",
"clientId",
",",
"SessionId",
".",
"from",
"(",
"response",
".",
"session",
"(",
")",
")",
",",
"serviceName",
",",
"primitiveType",
",",
"response",
".",
"timeout",
"(",
")",
")",
";",
"sessions",
".",
"put",
"(",
"state",
".",
"getSessionId",
"(",
")",
".",
"id",
"(",
")",
",",
"state",
")",
";",
"state",
".",
"addStateChangeListener",
"(",
"s",
"->",
"{",
"if",
"(",
"s",
"==",
"PrimitiveState",
".",
"EXPIRED",
"||",
"s",
"==",
"PrimitiveState",
".",
"CLOSED",
")",
"{",
"sessions",
".",
"remove",
"(",
"state",
".",
"getSessionId",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"// Ensure the proxy session info is reset and the session is kept alive.",
"keepAliveSessions",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"state",
".",
"getSessionTimeout",
"(",
")",
")",
";",
"future",
".",
"complete",
"(",
"state",
")",
";",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"new",
"RaftException",
".",
"Unavailable",
"(",
"response",
".",
"error",
"(",
")",
".",
"message",
"(",
")",
")",
")",
";",
"}",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"new",
"RaftException",
".",
"Unavailable",
"(",
"error",
".",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"}",
",",
"proxyContext",
")",
";",
"return",
"future",
";",
"}"
] | Opens a new session.
@param serviceName The session name.
@param primitiveType The session type.
@param communicationStrategy The strategy with which to communicate with servers.
@param minTimeout The minimum session timeout.
@param maxTimeout The maximum session timeout.
@return A completable future to be completed once the session has been opened. | [
"Opens",
"a",
"new",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java#L155-L211 |
27,375 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java | RaftSessionManager.closeSession | public CompletableFuture<Void> closeSession(SessionId sessionId, boolean delete) {
RaftSessionState state = sessions.get(sessionId.id());
if (state == null) {
return Futures.exceptionalFuture(new RaftException.UnknownSession("Unknown session: " + sessionId));
}
log.debug("Closing session {}", sessionId);
CloseSessionRequest request = CloseSessionRequest.builder()
.withSession(sessionId.id())
.withDelete(delete)
.build();
CompletableFuture<Void> future = new CompletableFuture<>();
connection.closeSession(request).whenComplete((response, error) -> {
sessions.remove(sessionId.id());
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
future.complete(null);
} else {
future.completeExceptionally(response.error().createException());
}
} else {
future.completeExceptionally(error);
}
});
return future;
} | java | public CompletableFuture<Void> closeSession(SessionId sessionId, boolean delete) {
RaftSessionState state = sessions.get(sessionId.id());
if (state == null) {
return Futures.exceptionalFuture(new RaftException.UnknownSession("Unknown session: " + sessionId));
}
log.debug("Closing session {}", sessionId);
CloseSessionRequest request = CloseSessionRequest.builder()
.withSession(sessionId.id())
.withDelete(delete)
.build();
CompletableFuture<Void> future = new CompletableFuture<>();
connection.closeSession(request).whenComplete((response, error) -> {
sessions.remove(sessionId.id());
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
future.complete(null);
} else {
future.completeExceptionally(response.error().createException());
}
} else {
future.completeExceptionally(error);
}
});
return future;
} | [
"public",
"CompletableFuture",
"<",
"Void",
">",
"closeSession",
"(",
"SessionId",
"sessionId",
",",
"boolean",
"delete",
")",
"{",
"RaftSessionState",
"state",
"=",
"sessions",
".",
"get",
"(",
"sessionId",
".",
"id",
"(",
")",
")",
";",
"if",
"(",
"state",
"==",
"null",
")",
"{",
"return",
"Futures",
".",
"exceptionalFuture",
"(",
"new",
"RaftException",
".",
"UnknownSession",
"(",
"\"Unknown session: \"",
"+",
"sessionId",
")",
")",
";",
"}",
"log",
".",
"debug",
"(",
"\"Closing session {}\"",
",",
"sessionId",
")",
";",
"CloseSessionRequest",
"request",
"=",
"CloseSessionRequest",
".",
"builder",
"(",
")",
".",
"withSession",
"(",
"sessionId",
".",
"id",
"(",
")",
")",
".",
"withDelete",
"(",
"delete",
")",
".",
"build",
"(",
")",
";",
"CompletableFuture",
"<",
"Void",
">",
"future",
"=",
"new",
"CompletableFuture",
"<>",
"(",
")",
";",
"connection",
".",
"closeSession",
"(",
"request",
")",
".",
"whenComplete",
"(",
"(",
"response",
",",
"error",
")",
"->",
"{",
"sessions",
".",
"remove",
"(",
"sessionId",
".",
"id",
"(",
")",
")",
";",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"if",
"(",
"response",
".",
"status",
"(",
")",
"==",
"RaftResponse",
".",
"Status",
".",
"OK",
")",
"{",
"future",
".",
"complete",
"(",
"null",
")",
";",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"response",
".",
"error",
"(",
")",
".",
"createException",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"return",
"future",
";",
"}"
] | Closes a session.
@param sessionId the session identifier.
@param delete whether to delete the service
@return A completable future to be completed once the session is closed. | [
"Closes",
"a",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java#L220-L246 |
27,376 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java | RaftSessionManager.resetAllIndexes | private synchronized void resetAllIndexes() {
Collection<RaftSessionState> sessions = Lists.newArrayList(this.sessions.values());
// If no sessions are open, skip the keep-alive.
if (sessions.isEmpty()) {
return;
}
// Allocate session IDs, command response sequence numbers, and event index arrays.
long[] sessionIds = new long[sessions.size()];
long[] commandResponses = new long[sessions.size()];
long[] eventIndexes = new long[sessions.size()];
// For each session that needs to be kept alive, populate batch request arrays.
int i = 0;
for (RaftSessionState sessionState : sessions) {
sessionIds[i] = sessionState.getSessionId().id();
commandResponses[i] = sessionState.getCommandResponse();
eventIndexes[i] = sessionState.getEventIndex();
i++;
}
log.trace("Resetting {} sessions", sessionIds.length);
KeepAliveRequest request = KeepAliveRequest.builder()
.withSessionIds(sessionIds)
.withCommandSequences(commandResponses)
.withEventIndexes(eventIndexes)
.build();
connection.keepAlive(request);
} | java | private synchronized void resetAllIndexes() {
Collection<RaftSessionState> sessions = Lists.newArrayList(this.sessions.values());
// If no sessions are open, skip the keep-alive.
if (sessions.isEmpty()) {
return;
}
// Allocate session IDs, command response sequence numbers, and event index arrays.
long[] sessionIds = new long[sessions.size()];
long[] commandResponses = new long[sessions.size()];
long[] eventIndexes = new long[sessions.size()];
// For each session that needs to be kept alive, populate batch request arrays.
int i = 0;
for (RaftSessionState sessionState : sessions) {
sessionIds[i] = sessionState.getSessionId().id();
commandResponses[i] = sessionState.getCommandResponse();
eventIndexes[i] = sessionState.getEventIndex();
i++;
}
log.trace("Resetting {} sessions", sessionIds.length);
KeepAliveRequest request = KeepAliveRequest.builder()
.withSessionIds(sessionIds)
.withCommandSequences(commandResponses)
.withEventIndexes(eventIndexes)
.build();
connection.keepAlive(request);
} | [
"private",
"synchronized",
"void",
"resetAllIndexes",
"(",
")",
"{",
"Collection",
"<",
"RaftSessionState",
">",
"sessions",
"=",
"Lists",
".",
"newArrayList",
"(",
"this",
".",
"sessions",
".",
"values",
"(",
")",
")",
";",
"// If no sessions are open, skip the keep-alive.",
"if",
"(",
"sessions",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Allocate session IDs, command response sequence numbers, and event index arrays.",
"long",
"[",
"]",
"sessionIds",
"=",
"new",
"long",
"[",
"sessions",
".",
"size",
"(",
")",
"]",
";",
"long",
"[",
"]",
"commandResponses",
"=",
"new",
"long",
"[",
"sessions",
".",
"size",
"(",
")",
"]",
";",
"long",
"[",
"]",
"eventIndexes",
"=",
"new",
"long",
"[",
"sessions",
".",
"size",
"(",
")",
"]",
";",
"// For each session that needs to be kept alive, populate batch request arrays.",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"RaftSessionState",
"sessionState",
":",
"sessions",
")",
"{",
"sessionIds",
"[",
"i",
"]",
"=",
"sessionState",
".",
"getSessionId",
"(",
")",
".",
"id",
"(",
")",
";",
"commandResponses",
"[",
"i",
"]",
"=",
"sessionState",
".",
"getCommandResponse",
"(",
")",
";",
"eventIndexes",
"[",
"i",
"]",
"=",
"sessionState",
".",
"getEventIndex",
"(",
")",
";",
"i",
"++",
";",
"}",
"log",
".",
"trace",
"(",
"\"Resetting {} sessions\"",
",",
"sessionIds",
".",
"length",
")",
";",
"KeepAliveRequest",
"request",
"=",
"KeepAliveRequest",
".",
"builder",
"(",
")",
".",
"withSessionIds",
"(",
"sessionIds",
")",
".",
"withCommandSequences",
"(",
"commandResponses",
")",
".",
"withEventIndexes",
"(",
"eventIndexes",
")",
".",
"build",
"(",
")",
";",
"connection",
".",
"keepAlive",
"(",
"request",
")",
";",
"}"
] | Resets indexes for all sessions. | [
"Resets",
"indexes",
"for",
"all",
"sessions",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java#L251-L281 |
27,377 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java | RaftSessionManager.resetIndexes | CompletableFuture<Void> resetIndexes(SessionId sessionId) {
RaftSessionState sessionState = sessions.get(sessionId.id());
if (sessionState == null) {
return Futures.exceptionalFuture(new IllegalArgumentException("Unknown session: " + sessionId));
}
CompletableFuture<Void> future = new CompletableFuture<>();
KeepAliveRequest request = KeepAliveRequest.builder()
.withSessionIds(new long[]{sessionId.id()})
.withCommandSequences(new long[]{sessionState.getCommandResponse()})
.withEventIndexes(new long[]{sessionState.getEventIndex()})
.build();
connection.keepAlive(request).whenComplete((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
future.complete(null);
} else {
future.completeExceptionally(response.error().createException());
}
} else {
future.completeExceptionally(error);
}
});
return future;
} | java | CompletableFuture<Void> resetIndexes(SessionId sessionId) {
RaftSessionState sessionState = sessions.get(sessionId.id());
if (sessionState == null) {
return Futures.exceptionalFuture(new IllegalArgumentException("Unknown session: " + sessionId));
}
CompletableFuture<Void> future = new CompletableFuture<>();
KeepAliveRequest request = KeepAliveRequest.builder()
.withSessionIds(new long[]{sessionId.id()})
.withCommandSequences(new long[]{sessionState.getCommandResponse()})
.withEventIndexes(new long[]{sessionState.getEventIndex()})
.build();
connection.keepAlive(request).whenComplete((response, error) -> {
if (error == null) {
if (response.status() == RaftResponse.Status.OK) {
future.complete(null);
} else {
future.completeExceptionally(response.error().createException());
}
} else {
future.completeExceptionally(error);
}
});
return future;
} | [
"CompletableFuture",
"<",
"Void",
">",
"resetIndexes",
"(",
"SessionId",
"sessionId",
")",
"{",
"RaftSessionState",
"sessionState",
"=",
"sessions",
".",
"get",
"(",
"sessionId",
".",
"id",
"(",
")",
")",
";",
"if",
"(",
"sessionState",
"==",
"null",
")",
"{",
"return",
"Futures",
".",
"exceptionalFuture",
"(",
"new",
"IllegalArgumentException",
"(",
"\"Unknown session: \"",
"+",
"sessionId",
")",
")",
";",
"}",
"CompletableFuture",
"<",
"Void",
">",
"future",
"=",
"new",
"CompletableFuture",
"<>",
"(",
")",
";",
"KeepAliveRequest",
"request",
"=",
"KeepAliveRequest",
".",
"builder",
"(",
")",
".",
"withSessionIds",
"(",
"new",
"long",
"[",
"]",
"{",
"sessionId",
".",
"id",
"(",
")",
"}",
")",
".",
"withCommandSequences",
"(",
"new",
"long",
"[",
"]",
"{",
"sessionState",
".",
"getCommandResponse",
"(",
")",
"}",
")",
".",
"withEventIndexes",
"(",
"new",
"long",
"[",
"]",
"{",
"sessionState",
".",
"getEventIndex",
"(",
")",
"}",
")",
".",
"build",
"(",
")",
";",
"connection",
".",
"keepAlive",
"(",
"request",
")",
".",
"whenComplete",
"(",
"(",
"response",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"if",
"(",
"response",
".",
"status",
"(",
")",
"==",
"RaftResponse",
".",
"Status",
".",
"OK",
")",
"{",
"future",
".",
"complete",
"(",
"null",
")",
";",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"response",
".",
"error",
"(",
")",
".",
"createException",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"future",
".",
"completeExceptionally",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"return",
"future",
";",
"}"
] | Resets indexes for the given session.
@param sessionId The session for which to reset indexes.
@return A completable future to be completed once the session's indexes have been reset. | [
"Resets",
"indexes",
"for",
"the",
"given",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java#L289-L315 |
27,378 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java | RaftSessionManager.handleHeartbeat | private CompletableFuture<HeartbeatResponse> handleHeartbeat(HeartbeatRequest request) {
log.trace("Received {}", request);
boolean newLeader = !Objects.equals(selectorManager.leader(), request.leader());
selectorManager.resetAll(request.leader(), request.members());
HeartbeatResponse response = HeartbeatResponse.builder()
.withStatus(RaftResponse.Status.OK)
.build();
if (newLeader) {
resetAllIndexes();
}
log.trace("Sending {}", response);
return CompletableFuture.completedFuture(response);
} | java | private CompletableFuture<HeartbeatResponse> handleHeartbeat(HeartbeatRequest request) {
log.trace("Received {}", request);
boolean newLeader = !Objects.equals(selectorManager.leader(), request.leader());
selectorManager.resetAll(request.leader(), request.members());
HeartbeatResponse response = HeartbeatResponse.builder()
.withStatus(RaftResponse.Status.OK)
.build();
if (newLeader) {
resetAllIndexes();
}
log.trace("Sending {}", response);
return CompletableFuture.completedFuture(response);
} | [
"private",
"CompletableFuture",
"<",
"HeartbeatResponse",
">",
"handleHeartbeat",
"(",
"HeartbeatRequest",
"request",
")",
"{",
"log",
".",
"trace",
"(",
"\"Received {}\"",
",",
"request",
")",
";",
"boolean",
"newLeader",
"=",
"!",
"Objects",
".",
"equals",
"(",
"selectorManager",
".",
"leader",
"(",
")",
",",
"request",
".",
"leader",
"(",
")",
")",
";",
"selectorManager",
".",
"resetAll",
"(",
"request",
".",
"leader",
"(",
")",
",",
"request",
".",
"members",
"(",
")",
")",
";",
"HeartbeatResponse",
"response",
"=",
"HeartbeatResponse",
".",
"builder",
"(",
")",
".",
"withStatus",
"(",
"RaftResponse",
".",
"Status",
".",
"OK",
")",
".",
"build",
"(",
")",
";",
"if",
"(",
"newLeader",
")",
"{",
"resetAllIndexes",
"(",
")",
";",
"}",
"log",
".",
"trace",
"(",
"\"Sending {}\"",
",",
"response",
")",
";",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"response",
")",
";",
"}"
] | Handles a heartbeat request. | [
"Handles",
"a",
"heartbeat",
"request",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionManager.java#L423-L435 |
27,379 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftStorageConfig.java | RaftStorageConfig.getDirectory | public String getDirectory(String groupName) {
return directory != null ? directory : System.getProperty("atomix.data", DATA_PREFIX) + "/" + groupName;
} | java | public String getDirectory(String groupName) {
return directory != null ? directory : System.getProperty("atomix.data", DATA_PREFIX) + "/" + groupName;
} | [
"public",
"String",
"getDirectory",
"(",
"String",
"groupName",
")",
"{",
"return",
"directory",
"!=",
"null",
"?",
"directory",
":",
"System",
".",
"getProperty",
"(",
"\"atomix.data\"",
",",
"DATA_PREFIX",
")",
"+",
"\"/\"",
"+",
"groupName",
";",
"}"
] | Returns the partition data directory.
@param groupName the partition group name
@return the partition data directory | [
"Returns",
"the",
"partition",
"data",
"directory",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftStorageConfig.java#L125-L127 |
27,380 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionSequencer.java | RaftSessionSequencer.completeResponses | private void completeResponses() {
// Iterate through queued responses and complete as many as possible.
ResponseCallback response = responseCallbacks.get(responseSequence + 1);
while (response != null) {
// If the response was completed, remove the response callback from the response queue,
// increment the response sequence number, and check the next response.
if (completeResponse(response.response, response.callback)) {
responseCallbacks.remove(++responseSequence);
response = responseCallbacks.get(responseSequence + 1);
} else {
break;
}
}
// Once we've completed as many responses as possible, if no more operations are outstanding
// and events remain in the event queue, complete the events.
if (requestSequence == responseSequence) {
EventCallback eventCallback = eventCallbacks.poll();
while (eventCallback != null) {
log.trace("Completing {}", eventCallback.request);
eventCallback.run();
eventIndex = eventCallback.request.eventIndex();
eventCallback = eventCallbacks.poll();
}
}
} | java | private void completeResponses() {
// Iterate through queued responses and complete as many as possible.
ResponseCallback response = responseCallbacks.get(responseSequence + 1);
while (response != null) {
// If the response was completed, remove the response callback from the response queue,
// increment the response sequence number, and check the next response.
if (completeResponse(response.response, response.callback)) {
responseCallbacks.remove(++responseSequence);
response = responseCallbacks.get(responseSequence + 1);
} else {
break;
}
}
// Once we've completed as many responses as possible, if no more operations are outstanding
// and events remain in the event queue, complete the events.
if (requestSequence == responseSequence) {
EventCallback eventCallback = eventCallbacks.poll();
while (eventCallback != null) {
log.trace("Completing {}", eventCallback.request);
eventCallback.run();
eventIndex = eventCallback.request.eventIndex();
eventCallback = eventCallbacks.poll();
}
}
} | [
"private",
"void",
"completeResponses",
"(",
")",
"{",
"// Iterate through queued responses and complete as many as possible.",
"ResponseCallback",
"response",
"=",
"responseCallbacks",
".",
"get",
"(",
"responseSequence",
"+",
"1",
")",
";",
"while",
"(",
"response",
"!=",
"null",
")",
"{",
"// If the response was completed, remove the response callback from the response queue,",
"// increment the response sequence number, and check the next response.",
"if",
"(",
"completeResponse",
"(",
"response",
".",
"response",
",",
"response",
".",
"callback",
")",
")",
"{",
"responseCallbacks",
".",
"remove",
"(",
"++",
"responseSequence",
")",
";",
"response",
"=",
"responseCallbacks",
".",
"get",
"(",
"responseSequence",
"+",
"1",
")",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"// Once we've completed as many responses as possible, if no more operations are outstanding",
"// and events remain in the event queue, complete the events.",
"if",
"(",
"requestSequence",
"==",
"responseSequence",
")",
"{",
"EventCallback",
"eventCallback",
"=",
"eventCallbacks",
".",
"poll",
"(",
")",
";",
"while",
"(",
"eventCallback",
"!=",
"null",
")",
"{",
"log",
".",
"trace",
"(",
"\"Completing {}\"",
",",
"eventCallback",
".",
"request",
")",
";",
"eventCallback",
".",
"run",
"(",
")",
";",
"eventIndex",
"=",
"eventCallback",
".",
"request",
".",
"eventIndex",
"(",
")",
";",
"eventCallback",
"=",
"eventCallbacks",
".",
"poll",
"(",
")",
";",
"}",
"}",
"}"
] | Completes all sequenced responses. | [
"Completes",
"all",
"sequenced",
"responses",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionSequencer.java#L147-L172 |
27,381 | atomix/atomix | utils/src/main/java/io/atomix/utils/time/VectorClock.java | VectorClock.update | public void update(VectorTimestamp<T> timestamp) {
VectorTimestamp<T> currentTimestamp = vector.get(timestamp.identifier());
if (currentTimestamp == null || currentTimestamp.value() < timestamp.value()) {
vector.put(timestamp.identifier(), timestamp);
}
} | java | public void update(VectorTimestamp<T> timestamp) {
VectorTimestamp<T> currentTimestamp = vector.get(timestamp.identifier());
if (currentTimestamp == null || currentTimestamp.value() < timestamp.value()) {
vector.put(timestamp.identifier(), timestamp);
}
} | [
"public",
"void",
"update",
"(",
"VectorTimestamp",
"<",
"T",
">",
"timestamp",
")",
"{",
"VectorTimestamp",
"<",
"T",
">",
"currentTimestamp",
"=",
"vector",
".",
"get",
"(",
"timestamp",
".",
"identifier",
"(",
")",
")",
";",
"if",
"(",
"currentTimestamp",
"==",
"null",
"||",
"currentTimestamp",
".",
"value",
"(",
")",
"<",
"timestamp",
".",
"value",
"(",
")",
")",
"{",
"vector",
".",
"put",
"(",
"timestamp",
".",
"identifier",
"(",
")",
",",
"timestamp",
")",
";",
"}",
"}"
] | Updates the given timestamp.
@param timestamp the timestamp to update | [
"Updates",
"the",
"given",
"timestamp",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/time/VectorClock.java#L90-L95 |
27,382 | atomix/atomix | utils/src/main/java/io/atomix/utils/time/VectorClock.java | VectorClock.update | public void update(VectorClock<T> clock) {
for (VectorTimestamp<T> timestamp : clock.vector.values()) {
update(timestamp);
}
} | java | public void update(VectorClock<T> clock) {
for (VectorTimestamp<T> timestamp : clock.vector.values()) {
update(timestamp);
}
} | [
"public",
"void",
"update",
"(",
"VectorClock",
"<",
"T",
">",
"clock",
")",
"{",
"for",
"(",
"VectorTimestamp",
"<",
"T",
">",
"timestamp",
":",
"clock",
".",
"vector",
".",
"values",
"(",
")",
")",
"{",
"update",
"(",
"timestamp",
")",
";",
"}",
"}"
] | Updates the vector clock.
@param clock the vector clock with which to update this clock | [
"Updates",
"the",
"vector",
"clock",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/time/VectorClock.java#L102-L106 |
27,383 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/messaging/impl/AbstractClientConnection.java | AbstractClientConnection.addReplyTime | private void addReplyTime(String type, long replyTime) {
DescriptiveStatistics samples = replySamples.get(type);
if (samples == null) {
samples = replySamples.computeIfAbsent(type, t -> new SynchronizedDescriptiveStatistics(WINDOW_SIZE));
}
samples.addValue(replyTime);
} | java | private void addReplyTime(String type, long replyTime) {
DescriptiveStatistics samples = replySamples.get(type);
if (samples == null) {
samples = replySamples.computeIfAbsent(type, t -> new SynchronizedDescriptiveStatistics(WINDOW_SIZE));
}
samples.addValue(replyTime);
} | [
"private",
"void",
"addReplyTime",
"(",
"String",
"type",
",",
"long",
"replyTime",
")",
"{",
"DescriptiveStatistics",
"samples",
"=",
"replySamples",
".",
"get",
"(",
"type",
")",
";",
"if",
"(",
"samples",
"==",
"null",
")",
"{",
"samples",
"=",
"replySamples",
".",
"computeIfAbsent",
"(",
"type",
",",
"t",
"->",
"new",
"SynchronizedDescriptiveStatistics",
"(",
"WINDOW_SIZE",
")",
")",
";",
"}",
"samples",
".",
"addValue",
"(",
"replyTime",
")",
";",
"}"
] | Adds a reply time to the history.
@param type the message type
@param replyTime the reply time to add to the history | [
"Adds",
"a",
"reply",
"time",
"to",
"the",
"history",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/messaging/impl/AbstractClientConnection.java#L83-L89 |
27,384 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/messaging/impl/AbstractClientConnection.java | AbstractClientConnection.getTimeoutMillis | private long getTimeoutMillis(String type, Duration timeout) {
return timeout != null ? timeout.toMillis() : computeTimeoutMillis(type);
} | java | private long getTimeoutMillis(String type, Duration timeout) {
return timeout != null ? timeout.toMillis() : computeTimeoutMillis(type);
} | [
"private",
"long",
"getTimeoutMillis",
"(",
"String",
"type",
",",
"Duration",
"timeout",
")",
"{",
"return",
"timeout",
"!=",
"null",
"?",
"timeout",
".",
"toMillis",
"(",
")",
":",
"computeTimeoutMillis",
"(",
"type",
")",
";",
"}"
] | Returns the timeout in milliseconds for the given timeout duration
@param type the message type
@param timeout the timeout duration or {@code null} if the timeout is dynamic
@return the timeout in milliseconds | [
"Returns",
"the",
"timeout",
"in",
"milliseconds",
"for",
"the",
"given",
"timeout",
"duration"
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/messaging/impl/AbstractClientConnection.java#L98-L100 |
27,385 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/messaging/impl/AbstractClientConnection.java | AbstractClientConnection.computeTimeoutMillis | private long computeTimeoutMillis(String type) {
DescriptiveStatistics samples = replySamples.get(type);
if (samples == null || samples.getN() < MIN_SAMPLES) {
return MAX_TIMEOUT_MILLIS;
}
return Math.min(Math.max((int) samples.getMax() * TIMEOUT_FACTOR, MIN_TIMEOUT_MILLIS), MAX_TIMEOUT_MILLIS);
} | java | private long computeTimeoutMillis(String type) {
DescriptiveStatistics samples = replySamples.get(type);
if (samples == null || samples.getN() < MIN_SAMPLES) {
return MAX_TIMEOUT_MILLIS;
}
return Math.min(Math.max((int) samples.getMax() * TIMEOUT_FACTOR, MIN_TIMEOUT_MILLIS), MAX_TIMEOUT_MILLIS);
} | [
"private",
"long",
"computeTimeoutMillis",
"(",
"String",
"type",
")",
"{",
"DescriptiveStatistics",
"samples",
"=",
"replySamples",
".",
"get",
"(",
"type",
")",
";",
"if",
"(",
"samples",
"==",
"null",
"||",
"samples",
".",
"getN",
"(",
")",
"<",
"MIN_SAMPLES",
")",
"{",
"return",
"MAX_TIMEOUT_MILLIS",
";",
"}",
"return",
"Math",
".",
"min",
"(",
"Math",
".",
"max",
"(",
"(",
"int",
")",
"samples",
".",
"getMax",
"(",
")",
"*",
"TIMEOUT_FACTOR",
",",
"MIN_TIMEOUT_MILLIS",
")",
",",
"MAX_TIMEOUT_MILLIS",
")",
";",
"}"
] | Computes the timeout for the next request.
@param type the message type
@return the computed timeout for the next request | [
"Computes",
"the",
"timeout",
"for",
"the",
"next",
"request",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/messaging/impl/AbstractClientConnection.java#L108-L114 |
27,386 | atomix/atomix | utils/src/main/java/io/atomix/utils/concurrent/ComposableFuture.java | ComposableFuture.except | public CompletableFuture<T> except(Consumer<Throwable> consumer) {
return whenComplete((result, error) -> {
if (error != null) {
consumer.accept(error);
}
});
} | java | public CompletableFuture<T> except(Consumer<Throwable> consumer) {
return whenComplete((result, error) -> {
if (error != null) {
consumer.accept(error);
}
});
} | [
"public",
"CompletableFuture",
"<",
"T",
">",
"except",
"(",
"Consumer",
"<",
"Throwable",
">",
"consumer",
")",
"{",
"return",
"whenComplete",
"(",
"(",
"result",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"!=",
"null",
")",
"{",
"consumer",
".",
"accept",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sets a consumer to be called when the future is failed.
@param consumer The consumer to call.
@return A new future. | [
"Sets",
"a",
"consumer",
"to",
"be",
"called",
"when",
"the",
"future",
"is",
"failed",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/ComposableFuture.java#L45-L51 |
27,387 | atomix/atomix | utils/src/main/java/io/atomix/utils/concurrent/ComposableFuture.java | ComposableFuture.exceptAsync | public CompletableFuture<T> exceptAsync(Consumer<Throwable> consumer) {
return whenCompleteAsync((result, error) -> {
if (error != null) {
consumer.accept(error);
}
});
} | java | public CompletableFuture<T> exceptAsync(Consumer<Throwable> consumer) {
return whenCompleteAsync((result, error) -> {
if (error != null) {
consumer.accept(error);
}
});
} | [
"public",
"CompletableFuture",
"<",
"T",
">",
"exceptAsync",
"(",
"Consumer",
"<",
"Throwable",
">",
"consumer",
")",
"{",
"return",
"whenCompleteAsync",
"(",
"(",
"result",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"!=",
"null",
")",
"{",
"consumer",
".",
"accept",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sets a consumer to be called asynchronously when the future is failed.
@param consumer The consumer to call.
@return A new future. | [
"Sets",
"a",
"consumer",
"to",
"be",
"called",
"asynchronously",
"when",
"the",
"future",
"is",
"failed",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/ComposableFuture.java#L59-L65 |
27,388 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java | SnapshotFile.isSnapshotFile | public static boolean isSnapshotFile(File file) {
checkNotNull(file, "file cannot be null");
String fileName = file.getName();
// The file name should contain an extension separator.
if (fileName.lastIndexOf(EXTENSION_SEPARATOR) == -1) {
return false;
}
// The file name should end with the snapshot extension.
if (!fileName.endsWith("." + EXTENSION)) {
return false;
}
// Parse the file name parts.
String[] parts = fileName.substring(0, fileName.lastIndexOf(EXTENSION_SEPARATOR)).split(String.valueOf(PART_SEPARATOR));
// The total number of file name parts should be at least 2.
if (parts.length < 2) {
return false;
}
// The second part of the file name should be numeric.
// Subtract from the number of parts to ensure PART_SEPARATOR can be used in snapshot names.
if (!isNumeric(parts[parts.length - 1])) {
return false;
}
// Otherwise, assume this is a snapshot file.
return true;
} | java | public static boolean isSnapshotFile(File file) {
checkNotNull(file, "file cannot be null");
String fileName = file.getName();
// The file name should contain an extension separator.
if (fileName.lastIndexOf(EXTENSION_SEPARATOR) == -1) {
return false;
}
// The file name should end with the snapshot extension.
if (!fileName.endsWith("." + EXTENSION)) {
return false;
}
// Parse the file name parts.
String[] parts = fileName.substring(0, fileName.lastIndexOf(EXTENSION_SEPARATOR)).split(String.valueOf(PART_SEPARATOR));
// The total number of file name parts should be at least 2.
if (parts.length < 2) {
return false;
}
// The second part of the file name should be numeric.
// Subtract from the number of parts to ensure PART_SEPARATOR can be used in snapshot names.
if (!isNumeric(parts[parts.length - 1])) {
return false;
}
// Otherwise, assume this is a snapshot file.
return true;
} | [
"public",
"static",
"boolean",
"isSnapshotFile",
"(",
"File",
"file",
")",
"{",
"checkNotNull",
"(",
"file",
",",
"\"file cannot be null\"",
")",
";",
"String",
"fileName",
"=",
"file",
".",
"getName",
"(",
")",
";",
"// The file name should contain an extension separator.",
"if",
"(",
"fileName",
".",
"lastIndexOf",
"(",
"EXTENSION_SEPARATOR",
")",
"==",
"-",
"1",
")",
"{",
"return",
"false",
";",
"}",
"// The file name should end with the snapshot extension.",
"if",
"(",
"!",
"fileName",
".",
"endsWith",
"(",
"\".\"",
"+",
"EXTENSION",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Parse the file name parts.",
"String",
"[",
"]",
"parts",
"=",
"fileName",
".",
"substring",
"(",
"0",
",",
"fileName",
".",
"lastIndexOf",
"(",
"EXTENSION_SEPARATOR",
")",
")",
".",
"split",
"(",
"String",
".",
"valueOf",
"(",
"PART_SEPARATOR",
")",
")",
";",
"// The total number of file name parts should be at least 2.",
"if",
"(",
"parts",
".",
"length",
"<",
"2",
")",
"{",
"return",
"false",
";",
"}",
"// The second part of the file name should be numeric.",
"// Subtract from the number of parts to ensure PART_SEPARATOR can be used in snapshot names.",
"if",
"(",
"!",
"isNumeric",
"(",
"parts",
"[",
"parts",
".",
"length",
"-",
"1",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Otherwise, assume this is a snapshot file.",
"return",
"true",
";",
"}"
] | Returns a boolean value indicating whether the given file appears to be a parsable snapshot file.
@throws NullPointerException if {@code file} is null | [
"Returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"the",
"given",
"file",
"appears",
"to",
"be",
"a",
"parsable",
"snapshot",
"file",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java#L38-L68 |
27,389 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java | SnapshotFile.isNumeric | private static boolean isNumeric(String value) {
for (char c : value.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
} | java | private static boolean isNumeric(String value) {
for (char c : value.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
} | [
"private",
"static",
"boolean",
"isNumeric",
"(",
"String",
"value",
")",
"{",
"for",
"(",
"char",
"c",
":",
"value",
".",
"toCharArray",
"(",
")",
")",
"{",
"if",
"(",
"!",
"Character",
".",
"isDigit",
"(",
"c",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Returns a boolean indicating whether the given string value is numeric.
@param value The value to check.
@return Indicates whether the given string value is numeric. | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"given",
"string",
"value",
"is",
"numeric",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java#L76-L83 |
27,390 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java | SnapshotFile.createSnapshotFileName | @VisibleForTesting
static String createSnapshotFileName(String serverName, long index) {
return String.format("%s-%d.%s",
serverName,
index,
EXTENSION);
} | java | @VisibleForTesting
static String createSnapshotFileName(String serverName, long index) {
return String.format("%s-%d.%s",
serverName,
index,
EXTENSION);
} | [
"@",
"VisibleForTesting",
"static",
"String",
"createSnapshotFileName",
"(",
"String",
"serverName",
",",
"long",
"index",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"%s-%d.%s\"",
",",
"serverName",
",",
"index",
",",
"EXTENSION",
")",
";",
"}"
] | Creates a snapshot file name from the given parameters. | [
"Creates",
"a",
"snapshot",
"file",
"name",
"from",
"the",
"given",
"parameters",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java#L96-L102 |
27,391 | atomix/atomix | storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentWriter.java | MappableJournalSegmentWriter.map | MappedByteBuffer map() {
if (writer instanceof MappedJournalSegmentWriter) {
return ((MappedJournalSegmentWriter<E>) writer).buffer();
}
try {
JournalWriter<E> writer = this.writer;
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, segment.descriptor().maxSegmentSize());
this.writer = new MappedJournalSegmentWriter<>(buffer, segment, maxEntrySize, index, namespace);
writer.close();
return buffer;
} catch (IOException e) {
throw new StorageException(e);
}
} | java | MappedByteBuffer map() {
if (writer instanceof MappedJournalSegmentWriter) {
return ((MappedJournalSegmentWriter<E>) writer).buffer();
}
try {
JournalWriter<E> writer = this.writer;
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, segment.descriptor().maxSegmentSize());
this.writer = new MappedJournalSegmentWriter<>(buffer, segment, maxEntrySize, index, namespace);
writer.close();
return buffer;
} catch (IOException e) {
throw new StorageException(e);
}
} | [
"MappedByteBuffer",
"map",
"(",
")",
"{",
"if",
"(",
"writer",
"instanceof",
"MappedJournalSegmentWriter",
")",
"{",
"return",
"(",
"(",
"MappedJournalSegmentWriter",
"<",
"E",
">",
")",
"writer",
")",
".",
"buffer",
"(",
")",
";",
"}",
"try",
"{",
"JournalWriter",
"<",
"E",
">",
"writer",
"=",
"this",
".",
"writer",
";",
"MappedByteBuffer",
"buffer",
"=",
"channel",
".",
"map",
"(",
"FileChannel",
".",
"MapMode",
".",
"READ_WRITE",
",",
"0",
",",
"segment",
".",
"descriptor",
"(",
")",
".",
"maxSegmentSize",
"(",
")",
")",
";",
"this",
".",
"writer",
"=",
"new",
"MappedJournalSegmentWriter",
"<>",
"(",
"buffer",
",",
"segment",
",",
"maxEntrySize",
",",
"index",
",",
"namespace",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"return",
"buffer",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"StorageException",
"(",
"e",
")",
";",
"}",
"}"
] | Maps the segment writer into memory, returning the mapped buffer.
@return the buffer that was mapped into memory | [
"Maps",
"the",
"segment",
"writer",
"into",
"memory",
"returning",
"the",
"mapped",
"buffer",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentWriter.java#L56-L70 |
27,392 | atomix/atomix | storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentWriter.java | MappableJournalSegmentWriter.unmap | void unmap() {
if (writer instanceof MappedJournalSegmentWriter) {
JournalWriter<E> writer = this.writer;
this.writer = new FileChannelJournalSegmentWriter<>(channel, segment, maxEntrySize, index, namespace);
writer.close();
}
} | java | void unmap() {
if (writer instanceof MappedJournalSegmentWriter) {
JournalWriter<E> writer = this.writer;
this.writer = new FileChannelJournalSegmentWriter<>(channel, segment, maxEntrySize, index, namespace);
writer.close();
}
} | [
"void",
"unmap",
"(",
")",
"{",
"if",
"(",
"writer",
"instanceof",
"MappedJournalSegmentWriter",
")",
"{",
"JournalWriter",
"<",
"E",
">",
"writer",
"=",
"this",
".",
"writer",
";",
"this",
".",
"writer",
"=",
"new",
"FileChannelJournalSegmentWriter",
"<>",
"(",
"channel",
",",
"segment",
",",
"maxEntrySize",
",",
"index",
",",
"namespace",
")",
";",
"writer",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Unmaps the mapped buffer. | [
"Unmaps",
"the",
"mapped",
"buffer",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/MappableJournalSegmentWriter.java#L75-L81 |
27,393 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocolConfig.java | SwimMembershipProtocolConfig.setProbeInterval | public SwimMembershipProtocolConfig setProbeInterval(Duration probeInterval) {
checkNotNull(probeInterval, "probeInterval cannot be null");
checkArgument(!probeInterval.isNegative() && !probeInterval.isZero(), "probeInterval must be positive");
this.probeInterval = probeInterval;
return this;
} | java | public SwimMembershipProtocolConfig setProbeInterval(Duration probeInterval) {
checkNotNull(probeInterval, "probeInterval cannot be null");
checkArgument(!probeInterval.isNegative() && !probeInterval.isZero(), "probeInterval must be positive");
this.probeInterval = probeInterval;
return this;
} | [
"public",
"SwimMembershipProtocolConfig",
"setProbeInterval",
"(",
"Duration",
"probeInterval",
")",
"{",
"checkNotNull",
"(",
"probeInterval",
",",
"\"probeInterval cannot be null\"",
")",
";",
"checkArgument",
"(",
"!",
"probeInterval",
".",
"isNegative",
"(",
")",
"&&",
"!",
"probeInterval",
".",
"isZero",
"(",
")",
",",
"\"probeInterval must be positive\"",
")",
";",
"this",
".",
"probeInterval",
"=",
"probeInterval",
";",
"return",
"this",
";",
"}"
] | Sets the probe interval.
@param probeInterval the probe interval
@return the membership configuration | [
"Sets",
"the",
"probe",
"interval",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocolConfig.java#L163-L168 |
27,394 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocolConfig.java | SwimMembershipProtocolConfig.setProbeTimeout | public SwimMembershipProtocolConfig setProbeTimeout(Duration probeTimeout) {
checkNotNull(probeTimeout, "probeTimeout cannot be null");
checkArgument(!probeTimeout.isNegative() && !probeTimeout.isZero(), "probeTimeout must be positive");
this.probeTimeout = probeTimeout;
return this;
} | java | public SwimMembershipProtocolConfig setProbeTimeout(Duration probeTimeout) {
checkNotNull(probeTimeout, "probeTimeout cannot be null");
checkArgument(!probeTimeout.isNegative() && !probeTimeout.isZero(), "probeTimeout must be positive");
this.probeTimeout = probeTimeout;
return this;
} | [
"public",
"SwimMembershipProtocolConfig",
"setProbeTimeout",
"(",
"Duration",
"probeTimeout",
")",
"{",
"checkNotNull",
"(",
"probeTimeout",
",",
"\"probeTimeout cannot be null\"",
")",
";",
"checkArgument",
"(",
"!",
"probeTimeout",
".",
"isNegative",
"(",
")",
"&&",
"!",
"probeTimeout",
".",
"isZero",
"(",
")",
",",
"\"probeTimeout must be positive\"",
")",
";",
"this",
".",
"probeTimeout",
"=",
"probeTimeout",
";",
"return",
"this",
";",
"}"
] | Sets the probe timeout.
@param probeTimeout the probe timeout
@return the membership protocol configuration | [
"Sets",
"the",
"probe",
"timeout",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocolConfig.java#L185-L190 |
27,395 | atomix/atomix | cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocolConfig.java | SwimMembershipProtocolConfig.setFailureTimeout | public SwimMembershipProtocolConfig setFailureTimeout(Duration failureTimeout) {
checkNotNull(failureTimeout, "failureTimeout cannot be null");
checkArgument(!failureTimeout.isNegative() && !failureTimeout.isZero(), "failureTimeout must be positive");
this.failureTimeout = checkNotNull(failureTimeout);
return this;
} | java | public SwimMembershipProtocolConfig setFailureTimeout(Duration failureTimeout) {
checkNotNull(failureTimeout, "failureTimeout cannot be null");
checkArgument(!failureTimeout.isNegative() && !failureTimeout.isZero(), "failureTimeout must be positive");
this.failureTimeout = checkNotNull(failureTimeout);
return this;
} | [
"public",
"SwimMembershipProtocolConfig",
"setFailureTimeout",
"(",
"Duration",
"failureTimeout",
")",
"{",
"checkNotNull",
"(",
"failureTimeout",
",",
"\"failureTimeout cannot be null\"",
")",
";",
"checkArgument",
"(",
"!",
"failureTimeout",
".",
"isNegative",
"(",
")",
"&&",
"!",
"failureTimeout",
".",
"isZero",
"(",
")",
",",
"\"failureTimeout must be positive\"",
")",
";",
"this",
".",
"failureTimeout",
"=",
"checkNotNull",
"(",
"failureTimeout",
")",
";",
"return",
"this",
";",
"}"
] | Sets the base failure timeout.
@param failureTimeout the base failure timeout
@return the group membership configuration | [
"Sets",
"the",
"base",
"failure",
"timeout",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocolConfig.java#L228-L233 |
27,396 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/partition/impl/RaftMessageContext.java | RaftMessageContext.publishSubject | String publishSubject(long sessionId) {
if (prefix == null) {
return String.format("publish-%d", sessionId);
} else {
return String.format("%s-publish-%d", prefix, sessionId);
}
} | java | String publishSubject(long sessionId) {
if (prefix == null) {
return String.format("publish-%d", sessionId);
} else {
return String.format("%s-publish-%d", prefix, sessionId);
}
} | [
"String",
"publishSubject",
"(",
"long",
"sessionId",
")",
"{",
"if",
"(",
"prefix",
"==",
"null",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"publish-%d\"",
",",
"sessionId",
")",
";",
"}",
"else",
"{",
"return",
"String",
".",
"format",
"(",
"\"%s-publish-%d\"",
",",
"prefix",
",",
"sessionId",
")",
";",
"}",
"}"
] | Returns the publish subject for the given session.
@param sessionId the session for which to return the publish subject
@return the publish subject for the given session | [
"Returns",
"the",
"publish",
"subject",
"for",
"the",
"given",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/impl/RaftMessageContext.java#L74-L80 |
27,397 | atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/partition/impl/RaftMessageContext.java | RaftMessageContext.resetSubject | String resetSubject(long sessionId) {
if (prefix == null) {
return String.format("reset-%d", sessionId);
} else {
return String.format("%s-reset-%d", prefix, sessionId);
}
} | java | String resetSubject(long sessionId) {
if (prefix == null) {
return String.format("reset-%d", sessionId);
} else {
return String.format("%s-reset-%d", prefix, sessionId);
}
} | [
"String",
"resetSubject",
"(",
"long",
"sessionId",
")",
"{",
"if",
"(",
"prefix",
"==",
"null",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"reset-%d\"",
",",
"sessionId",
")",
";",
"}",
"else",
"{",
"return",
"String",
".",
"format",
"(",
"\"%s-reset-%d\"",
",",
"prefix",
",",
"sessionId",
")",
";",
"}",
"}"
] | Returns the reset subject for the given session.
@param sessionId the session for which to return the reset subject
@return the reset subject for the given session | [
"Returns",
"the",
"reset",
"subject",
"for",
"the",
"given",
"session",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/impl/RaftMessageContext.java#L88-L94 |
27,398 | atomix/atomix | storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java | SegmentedJournal.openReader | public SegmentedJournalReader<E> openReader(long index, SegmentedJournalReader.Mode mode) {
SegmentedJournalReader<E> reader = new SegmentedJournalReader<>(this, index, mode);
readers.add(reader);
return reader;
} | java | public SegmentedJournalReader<E> openReader(long index, SegmentedJournalReader.Mode mode) {
SegmentedJournalReader<E> reader = new SegmentedJournalReader<>(this, index, mode);
readers.add(reader);
return reader;
} | [
"public",
"SegmentedJournalReader",
"<",
"E",
">",
"openReader",
"(",
"long",
"index",
",",
"SegmentedJournalReader",
".",
"Mode",
"mode",
")",
"{",
"SegmentedJournalReader",
"<",
"E",
">",
"reader",
"=",
"new",
"SegmentedJournalReader",
"<>",
"(",
"this",
",",
"index",
",",
"mode",
")",
";",
"readers",
".",
"add",
"(",
"reader",
")",
";",
"return",
"reader",
";",
"}"
] | Opens a new Raft log reader with the given reader mode.
@param index The index from which to begin reading entries.
@param mode The mode in which to read entries.
@return The Raft log reader. | [
"Opens",
"a",
"new",
"Raft",
"log",
"reader",
"with",
"the",
"given",
"reader",
"mode",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L217-L221 |
27,399 | atomix/atomix | storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java | SegmentedJournal.resetSegments | JournalSegment<E> resetSegments(long index) {
assertOpen();
// If the index already equals the first segment index, skip the reset.
JournalSegment<E> firstSegment = getFirstSegment();
if (index == firstSegment.index()) {
return firstSegment;
}
for (JournalSegment<E> segment : segments.values()) {
segment.close();
segment.delete();
}
segments.clear();
JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
.withId(1)
.withIndex(index)
.withMaxSegmentSize(maxSegmentSize)
.withMaxEntries(maxEntriesPerSegment)
.build();
currentSegment = createSegment(descriptor);
segments.put(index, currentSegment);
return currentSegment;
} | java | JournalSegment<E> resetSegments(long index) {
assertOpen();
// If the index already equals the first segment index, skip the reset.
JournalSegment<E> firstSegment = getFirstSegment();
if (index == firstSegment.index()) {
return firstSegment;
}
for (JournalSegment<E> segment : segments.values()) {
segment.close();
segment.delete();
}
segments.clear();
JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
.withId(1)
.withIndex(index)
.withMaxSegmentSize(maxSegmentSize)
.withMaxEntries(maxEntriesPerSegment)
.build();
currentSegment = createSegment(descriptor);
segments.put(index, currentSegment);
return currentSegment;
} | [
"JournalSegment",
"<",
"E",
">",
"resetSegments",
"(",
"long",
"index",
")",
"{",
"assertOpen",
"(",
")",
";",
"// If the index already equals the first segment index, skip the reset.",
"JournalSegment",
"<",
"E",
">",
"firstSegment",
"=",
"getFirstSegment",
"(",
")",
";",
"if",
"(",
"index",
"==",
"firstSegment",
".",
"index",
"(",
")",
")",
"{",
"return",
"firstSegment",
";",
"}",
"for",
"(",
"JournalSegment",
"<",
"E",
">",
"segment",
":",
"segments",
".",
"values",
"(",
")",
")",
"{",
"segment",
".",
"close",
"(",
")",
";",
"segment",
".",
"delete",
"(",
")",
";",
"}",
"segments",
".",
"clear",
"(",
")",
";",
"JournalSegmentDescriptor",
"descriptor",
"=",
"JournalSegmentDescriptor",
".",
"builder",
"(",
")",
".",
"withId",
"(",
"1",
")",
".",
"withIndex",
"(",
"index",
")",
".",
"withMaxSegmentSize",
"(",
"maxSegmentSize",
")",
".",
"withMaxEntries",
"(",
"maxEntriesPerSegment",
")",
".",
"build",
"(",
")",
";",
"currentSegment",
"=",
"createSegment",
"(",
"descriptor",
")",
";",
"segments",
".",
"put",
"(",
"index",
",",
"currentSegment",
")",
";",
"return",
"currentSegment",
";",
"}"
] | Resets and returns the first segment in the journal.
@param index the starting index of the journal
@return the first segment | [
"Resets",
"and",
"returns",
"the",
"first",
"segment",
"in",
"the",
"journal",
"."
] | 3a94b7c80576d762dd0d396d4645df07a0b37c31 | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L304-L328 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.