io.atomix.cluster.ClusterMembershipEvent Java Examples

The following examples show how to use io.atomix.cluster.ClusterMembershipEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClusterResource.java    From atomix with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/nodes/{node}/events")
@Produces(MediaType.APPLICATION_JSON)
public void getNodeEvent(@PathParam("node") String memberId, @Context ClusterMembershipService clusterMembershipService, @Context EventManager events, @Suspended AsyncResponse response) {
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.getOrCreateEventLog(ClusterResource.class, memberId, l -> e -> {
    if (e.subject().id().id().equals(memberId)) {
      l.addEvent(e);
    }
  });
  if (eventLog.open()) {
    clusterMembershipService.addListener(eventLog.listener());
  }

  eventLog.nextEvent().whenComplete((result, error) -> {
    if (error == null) {
      response.resume(Response.ok(new NodeEvent(result.subject().id(), result.type())));
    } else {
      LOGGER.warn("{}", error);
      response.resume(Response.serverError().build());
    }
  });
}
 
Example #2
Source File: AtomixClusterStore.java    From onos with Apache License 2.0 6 votes vote down vote up
private void changeMembership(ClusterMembershipEvent event) {
    ControllerNode node = nodes.get(NodeId.nodeId(event.subject().id().id()));
    switch (event.type()) {
        case MEMBER_ADDED:
        case METADATA_CHANGED:
            if (node == null) {
                node = toControllerNode(event.subject());
                nodes.put(node.id(), node);
                notifyDelegate(new ClusterEvent(ClusterEvent.Type.INSTANCE_ADDED, node));
            }
            updateVersion(node, event.subject());
            updateState(node, event.subject());
            break;
        case MEMBER_REMOVED:
            if (node != null
                && states.put(node.id(), ControllerNode.State.INACTIVE) != ControllerNode.State.INACTIVE) {
                notifyDelegate(new ClusterEvent(ClusterEvent.Type.INSTANCE_DEACTIVATED, node));
                notifyDelegate(new ClusterEvent(ClusterEvent.Type.INSTANCE_REMOVED, node));
            }
            break;
        default:
            break;
    }
}
 
Example #3
Source File: ClusterResource.java    From atomix with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/nodes/{node}/events/{id}")
@Produces(MediaType.APPLICATION_JSON)
public void getNodeEvent(@PathParam("node") String memberId, @PathParam("id") String listenerId, @Context ClusterMembershipService clusterMembershipService, @Context EventManager events, @Suspended AsyncResponse response) {
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.getEventLog(ClusterResource.class, getNodeListener(memberId, listenerId));
  if (eventLog == null) {
    response.resume(Response.status(Status.NOT_FOUND).build());
    return;
  }

  eventLog.nextEvent().whenComplete((result, error) -> {
    if (error == null) {
      response.resume(Response.ok(new NodeEvent(result.subject().id(), result.type())));
    } else {
      LOGGER.warn("{}", error);
      response.resume(Response.serverError().build());
    }
  });
}
 
Example #4
Source File: AtomixClusterManager.java    From atomix-vertx with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a cluster event.
 */
private void handleClusterEvent(ClusterMembershipEvent event) {
  NodeListener nodeListener = this.listener;
  if (nodeListener != null) {
    context.execute(() -> {
      if (active.get()) {
        switch (event.type()) {
          case MEMBER_ADDED:
            nodeListener.nodeAdded(event.subject().id().id());
            break;
          case MEMBER_REMOVED:
            nodeListener.nodeLeft(event.subject().id().id());
            break;
          default:
            break;
        }
      }
    });
  }
}
 
Example #5
Source File: ClusterResource.java    From atomix with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/events/{id}")
@Produces(MediaType.APPLICATION_JSON)
public void getEvent(@PathParam("id") String listenerId, @Context ClusterMembershipService clusterMembershipService, @Context EventManager events, @Suspended AsyncResponse response) {
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.getEventLog(ClusterResource.class, listenerId);
  if (eventLog == null) {
    response.resume(Response.status(Status.NOT_FOUND).build());
    return;
  }

  eventLog.nextEvent().whenComplete((result, error) -> {
    if (error == null) {
      response.resume(Response.ok(new NodeEvent(result.subject().id(), result.type())));
    } else {
      LOGGER.warn("{}", error);
      response.resume(Response.serverError().build());
    }
  });
}
 
Example #6
Source File: ClusterResource.java    From atomix with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/events")
@Produces(MediaType.APPLICATION_JSON)
public void getEvent(@Context ClusterMembershipService clusterMembershipService, @Context EventManager events, @Suspended AsyncResponse response) {
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.getOrCreateEventLog(ClusterResource.class, "", l -> e -> l.addEvent(e));
  if (eventLog.open()) {
    clusterMembershipService.addListener(eventLog.listener());
  }

  eventLog.nextEvent().whenComplete((result, error) -> {
    if (error == null) {
      response.resume(Response.ok(new NodeEvent(result.subject().id(), result.type())));
    } else {
      LOGGER.warn("{}", error);
      response.resume(Response.serverError().build());
    }
  });
}
 
Example #7
Source File: DistributedLogSession.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a cluster event.
 */
private void handleClusterEvent(ClusterMembershipEvent event) {
  PrimaryTerm term = this.term;
  if (term != null
      && event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED
      && event.subject().id().equals(term.primary().memberId())) {
    changeState(PrimitiveState.SUSPENDED);
  }
}
 
Example #8
Source File: FollowerRole.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a cluster event.
 */
private void handleClusterEvent(ClusterMembershipEvent event) {
  raft.getThreadContext().execute(() -> {
    RaftMember leader = raft.getLeader();
    if (leader != null && event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED && event.subject().id().equals(leader.memberId())) {
      raft.setLeader(null);
      sendPollRequests();
    }
  });
}
 
Example #9
Source File: ClusterResource.java    From atomix with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/events")
@Produces(MediaType.APPLICATION_JSON)
public Response addListener(@Context ClusterMembershipService clusterMembershipService, @Context EventManager events) {
  String listenerId = UUID.randomUUID().toString();
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.getOrCreateEventLog(ClusterResource.class, listenerId, l -> e -> l.addEvent(e));
  if (eventLog.open()) {
    clusterMembershipService.addListener(eventLog.listener());
  }
  return Response.ok(listenerId).build();
}
 
Example #10
Source File: LeaderRole.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a cluster event.
 */
private void handleClusterEvent(ClusterMembershipEvent event) {
  raft.getThreadContext().execute(() -> {
    if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
      log.debug("Node {} deactivated", event.subject().id());
      raft.getSessions().getSessions().stream()
          .filter(session -> session.memberId().equals(event.subject().id()))
          .forEach(this::expireSession);
    }
  });
}
 
Example #11
Source File: ClusterResource.java    From atomix with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/events/{id}")
public void removeListener(@PathParam("id") String listenerId, @Context ClusterMembershipService clusterMembershipService, @Context EventManager events) {
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.removeEventLog(ClusterResource.class, listenerId);
  if (eventLog != null && eventLog.close()) {
    clusterMembershipService.removeListener(eventLog.listener());
  }
}
 
Example #12
Source File: PrimaryBackupServiceContext.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a cluster event.
 */
private void handleClusterEvent(ClusterMembershipEvent event) {
  threadContext.execute(() -> {
    if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
      for (Session session : sessions.values()) {
        if (session.memberId().equals(event.subject().id())) {
          role.expire((PrimaryBackupSession) session);
        }
      }
    }
  });
}
 
Example #13
Source File: ClusterResource.java    From atomix with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/nodes/{node}/events")
@Produces(MediaType.APPLICATION_JSON)
public Response addNodeListener(@PathParam("node") String memberId, @Context ClusterMembershipService clusterMembershipService, @Context EventManager events) {
  String id = UUID.randomUUID().toString();
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.getOrCreateEventLog(ClusterResource.class, getNodeListener(memberId, id), l -> e -> {
    if (e.subject().id().id().equals(memberId)) {
      l.addEvent(e);
    }
  });
  if (eventLog.open()) {
    clusterMembershipService.addListener(eventLog.listener());
  }
  return Response.ok(id).build();
}
 
Example #14
Source File: PrimaryBackupSessionClient.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a cluster event.
 */
private void handleClusterEvent(ClusterMembershipEvent event) {
  PrimaryTerm term = this.term;
  if (term != null && event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED && event.subject().id().equals(term.primary().memberId())) {
    threadContext.execute(() -> {
      state = PrimitiveState.SUSPENDED;
      stateChangeListeners.forEach(l -> l.accept(state));
    });
  }
}
 
Example #15
Source File: ClusterResource.java    From atomix with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/nodes/{node}/events/{id}")
public void removeNodeListener(@PathParam("node") String memberId, @PathParam("id") String listenerId, @Context ClusterMembershipService clusterMembershipService, @Context EventManager events) {
  EventLog<ClusterMembershipEventListener, ClusterMembershipEvent> eventLog = events.removeEventLog(ClusterResource.class, getNodeListener(memberId, listenerId));
  if (eventLog != null && eventLog.close()) {
    clusterMembershipService.removeListener(eventLog.listener());
  }
}
 
Example #16
Source File: DefaultClusterMembershipServiceTest.java    From atomix with Apache License 2.0 5 votes vote down vote up
ClusterMembershipEvent nextEvent() {
  try {
    return queue.poll(5, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
    return null;
  }
}
 
Example #17
Source File: AtomixTest.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Tests scaling down a cluster.
 */
@Test
public void testScaleDownPersistent() throws Exception {
  List<CompletableFuture<Atomix>> futures = new ArrayList<>();
  futures.add(startAtomix(1, Arrays.asList(1, 2, 3), Profile.dataGrid()));
  futures.add(startAtomix(2, Arrays.asList(1, 2, 3), Profile.dataGrid()));
  futures.add(startAtomix(3, Arrays.asList(1, 2, 3), Profile.dataGrid()));
  Futures.allOf(futures).get(30, TimeUnit.SECONDS);
  TestClusterMembershipEventListener eventListener1 = new TestClusterMembershipEventListener();
  instances.get(0).getMembershipService().addListener(eventListener1);
  TestClusterMembershipEventListener eventListener2 = new TestClusterMembershipEventListener();
  instances.get(1).getMembershipService().addListener(eventListener2);
  TestClusterMembershipEventListener eventListener3 = new TestClusterMembershipEventListener();
  instances.get(2).getMembershipService().addListener(eventListener3);
  instances.get(0).stop().get(30, TimeUnit.SECONDS);
  assertEquals(ClusterMembershipEvent.Type.REACHABILITY_CHANGED, eventListener2.event().type());
  assertEquals(ClusterMembershipEvent.Type.MEMBER_REMOVED, eventListener2.event().type());
  assertEquals(2, instances.get(1).getMembershipService().getMembers().size());
  assertEquals(ClusterMembershipEvent.Type.REACHABILITY_CHANGED, eventListener3.event().type());
  assertEquals(ClusterMembershipEvent.Type.MEMBER_REMOVED, eventListener3.event().type());
  assertEquals(2, instances.get(2).getMembershipService().getMembers().size());
  instances.get(1).stop().get(30, TimeUnit.SECONDS);
  assertEquals(ClusterMembershipEvent.Type.REACHABILITY_CHANGED, eventListener3.event().type());
  assertEquals(ClusterMembershipEvent.Type.MEMBER_REMOVED, eventListener3.event().type());
  assertEquals(1, instances.get(2).getMembershipService().getMembers().size());
  instances.get(2).stop().get(30, TimeUnit.SECONDS);
}
 
Example #18
Source File: AtomixTest.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a client properties.
 */
@Test
public void testClientProperties() throws Exception {
  List<CompletableFuture<Atomix>> futures = new ArrayList<>();
  futures.add(startAtomix(1, Arrays.asList(1, 2, 3), ConsensusProfile.builder()
      .withMembers("1", "2", "3")
      .withDataPath(new File(new File(DATA_DIR, "client-properties"), "1"))
      .build()));
  futures.add(startAtomix(2, Arrays.asList(1, 2, 3), ConsensusProfile.builder()
      .withMembers("1", "2", "3")
      .withDataPath(new File(new File(DATA_DIR, "client-properties"), "2"))
      .build()));
  futures.add(startAtomix(3, Arrays.asList(1, 2, 3), ConsensusProfile.builder()
      .withMembers("1", "2", "3")
      .withDataPath(new File(new File(DATA_DIR, "client-properties"), "3"))
      .build()));
  Futures.allOf(futures).get(30, TimeUnit.SECONDS);

  TestClusterMembershipEventListener dataListener = new TestClusterMembershipEventListener();
  instances.get(0).getMembershipService().addListener(dataListener);

  Properties properties = new Properties();
  properties.setProperty("a-key", "a-value");
  Atomix client1 = startAtomix(4, Arrays.asList(1, 2, 3), properties, Profile.client()).get(30, TimeUnit.SECONDS);
  assertEquals(1, client1.getPartitionService().getPartitionGroups().size());

  // client1 added to data node
  ClusterMembershipEvent event1 = dataListener.event();
  assertEquals(ClusterMembershipEvent.Type.MEMBER_ADDED, event1.type());

  Member member = event1.subject();

  assertNotNull(member.properties());
  assertEquals(1, member.properties().size());
  assertEquals("a-value", member.properties().get("a-key"));
}
 
Example #19
Source File: DefaultClusterMembershipService.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a group membership event.
 */
private void handleMembershipEvent(GroupMembershipEvent event) {
  post(new ClusterMembershipEvent(ClusterMembershipEvent.Type.valueOf(event.type().name()), event.member()));
}
 
Example #20
Source File: CoreTransactionService.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a cluster membership change event.
 */
private void onMembershipChange(ClusterMembershipEvent event) {
  if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
    recoverTransactions(transactions.entrySet().iterator(), event.subject().id());
  }
}
 
Example #21
Source File: AtomixTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
private void testClientJoinLeave(Profile... profiles) throws Exception {
  List<CompletableFuture<Atomix>> futures = new ArrayList<>();
  futures.add(startAtomix(1, Arrays.asList(1, 2, 3), profiles[0]));
  futures.add(startAtomix(2, Arrays.asList(1, 2, 3), profiles[1]));
  futures.add(startAtomix(3, Arrays.asList(1, 2, 3), profiles[2]));
  Futures.allOf(futures).get(30, TimeUnit.SECONDS);

  TestClusterMembershipEventListener dataListener = new TestClusterMembershipEventListener();
  instances.get(0).getMembershipService().addListener(dataListener);

  Atomix client1 = startAtomix(4, Arrays.asList(1, 2, 3), Profile.client()).get(30, TimeUnit.SECONDS);
  assertEquals(1, client1.getPartitionService().getPartitionGroups().size());

  // client1 added to data node
  ClusterMembershipEvent event1 = dataListener.event();
  assertEquals(ClusterMembershipEvent.Type.MEMBER_ADDED, event1.type());

  Thread.sleep(1000);

  TestClusterMembershipEventListener clientListener = new TestClusterMembershipEventListener();
  client1.getMembershipService().addListener(clientListener);

  Atomix client2 = startAtomix(5, Arrays.asList(1, 2, 3), Profile.client()).get(30, TimeUnit.SECONDS);
  assertEquals(1, client2.getPartitionService().getPartitionGroups().size());

  // client2 added to data node
  assertEquals(ClusterMembershipEvent.Type.MEMBER_ADDED, dataListener.event().type());

  // client2 added to client node
  assertEquals(ClusterMembershipEvent.Type.MEMBER_ADDED, clientListener.event().type());

  client2.stop().get(30, TimeUnit.SECONDS);

  // client2 removed from data node
  assertEquals(ClusterMembershipEvent.Type.REACHABILITY_CHANGED, dataListener.event().type());
  assertEquals(ClusterMembershipEvent.Type.MEMBER_REMOVED, dataListener.event().type());

  // client2 removed from client node
  assertEquals(ClusterMembershipEvent.Type.REACHABILITY_CHANGED, clientListener.event().type());
  assertEquals(ClusterMembershipEvent.Type.MEMBER_REMOVED, clientListener.event().type());
}
 
Example #22
Source File: HashBasedPrimaryElection.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a cluster membership event.
 */
private void handleClusterMembershipEvent(ClusterMembershipEvent event) {
  if (event.type() == ClusterMembershipEvent.Type.MEMBER_ADDED || event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
    recomputeTerm(groupMembershipService.getMembership(partitionId.group()));
  }
}