akka.cluster.Cluster Java Examples

The following examples show how to use akka.cluster.Cluster. 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: StatusResource.java    From flux with Apache License 2.0 6 votes vote down vote up
/**
 * Api to make a node leave the cluster.
 * @param host hostname/ip of the node.
 * @param port port
 */
@POST
@Path("/cluster/leave")
public Response leaveCluster(@QueryParam("host") String host, @QueryParam("port") Integer port) {
    if(StringUtils.isEmpty(host) || port == null) {
        return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).entity("empty hostname or port").build();
    }

    if(FluxInitializer.fluxRole.equals(FluxRuntimeRole.ORCHESTRATION)){
        return Response.status(Response.Status.FORBIDDEN.getStatusCode()).entity("Api not valid for Flux's" +
                " orchestraton nodes.").build();
    }

    Address akkAddress = new Address("akka.tcp", actorSystemManager.retrieveActorSystem().name(), host, port);
    Cluster cluster = Cluster.get(actorSystemManager.retrieveActorSystem());
    cluster.leave(akkAddress);

    return Response.status(Response.Status.OK.getStatusCode()).build();
}
 
Example #2
Source File: PubSubFactoryTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUpCluster() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    system1 = ActorSystem.create("actorSystem", getTestConf());
    system2 = ActorSystem.create("actorSystem", getTestConf());
    cluster1 = Cluster.get(system1);
    cluster2 = Cluster.get(system2);
    cluster1.registerOnMemberUp(latch::countDown);
    cluster2.registerOnMemberUp(latch::countDown);
    cluster1.join(cluster1.selfAddress());
    cluster2.join(cluster1.selfAddress());
    factory1 = TestPubSubFactory.of(newContext(system1));
    factory2 = TestPubSubFactory.of(newContext(system2));
    // wait for both members to be UP
    latch.await();
}
 
Example #3
Source File: OctopusSlave.java    From akka-tutorial with Apache License 2.0 6 votes vote down vote up
public static void start(String actorSystemName, int workers, String host, int port, String masterhost, int masterport) {
	
	final Config config = createConfiguration(actorSystemName, SLAVE_ROLE, host, port, masterhost, masterport);
	
	final ActorSystem system = createSystem(actorSystemName, config);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			//system.actorOf(ClusterListener.props(), ClusterListener.DEFAULT_NAME);
			system.actorOf(MetricsListener.props(), MetricsListener.DEFAULT_NAME);

			for (int i = 0; i < workers; i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
		}
	});
}
 
Example #4
Source File: SshSessionActor.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Object message) throws Throwable {
    if (message instanceof SessionDataRequest) {
        SessionDataRequest sessionDataRequest = (SessionDataRequest) message;
        sshSession.sendData(sessionDataRequest.getData());
        String dataOut = sshClientSessionListener.awaitData();
        SessionDataResponse sessionDataResponse = new SessionDataResponse(dataOut);
        sender().tell(sessionDataResponse, self());
    } else if (message instanceof SessionPingMessage) {
        String memberAddress = Cluster.get(context().system()).selfAddress().toString();
        context().sender().tell(new SessionPongMessage(memberAddress, sshSession.getId()), self());
    } else if (message instanceof SessionCloseRequest) {
        SessionCloseRequest sessionCloseRequest = (SessionCloseRequest)message;
        sshSession.close();
        SessionCloseResponse sessionCloseResponse = new SessionCloseResponse(sshSession.getId(),
                sessionCloseRequest.getClientId(), clientActorAddress);
        sender().tell(sessionCloseResponse, null);
        self().tell(PoisonPill.getInstance(), self());
    } else {
        LOG.info("onReceive: {}", message.getClass().getName());
        context().sender().tell(new SessionError(clientId,"unsupported message"), self());
    }
}
 
Example #5
Source File: ActorSystemManagerImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void leaveCluster(){

    Cluster cluster = Cluster.get(clusterSystem);
    logger.info("Downing self: {} from cluster: {}", cluster.selfAddress(), clusterSystem.name());
    cluster.leave(cluster.selfAddress());
}
 
Example #6
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void startSecondActorSystemAndJoinCluster() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    actorSystem2 = ActorSystem.create(getClass().getSimpleName(), TestConstants.CONFIG);
    final Cluster cluster1 = Cluster.get(actorSystem);
    final Cluster cluster2 = Cluster.get(actorSystem2);
    cluster1.registerOnMemberUp(latch::countDown);
    cluster2.registerOnMemberUp(latch::countDown);
    cluster1.join(cluster1.selfAddress());
    cluster2.join(cluster1.selfAddress());
    latch.await();
}
 
Example #7
Source File: StatisticsActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private StatisticsActor(final ActorRef pubSubMediator) {
    statisticsConfig = StatisticsConfig.forActor(getContext());

    this.pubSubMediator = pubSubMediator;
    this.gauges = initializeGaugesForHotEntities(statisticsConfig);

    final ActorSystem actorSystem = getContext().getSystem();
    final int numberOfShards = getNumberOfShards(actorSystem);
    clusterSharding = initClusterSharding(actorSystem, statisticsConfig, numberOfShards);
    clusterStatusSupplier = new ClusterStatusSupplier(Cluster.get(getContext().getSystem()));
    scheduleInternalRetrieveHotEntities();
    subscribeForStatisticsCommands();
}
 
Example #8
Source File: CompressedDDataHandler.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompressedDDataHandler(final DistributedDataConfig config,
        final ActorRefFactory actorRefFactory,
        final ActorSystem actorSystem,
        final Executor ddataExecutor,
        final String topicType,
        final List<Integer> seeds) {
    super(config, actorRefFactory, ddataExecutor);
    this.topicType = topicType;
    this.selfUniqueAddress = SelfUniqueAddress.apply(Cluster.get(actorSystem).selfUniqueAddress());
    this.seeds = seeds;
}
 
Example #9
Source File: ConciergeRootActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Route createRoute(final ActorSystem actorSystem, final ActorRef healthCheckingActor) {
    final StatusRoute statusRoute = new StatusRoute(new ClusterStatusSupplier(Cluster.get(actorSystem)),
            healthCheckingActor, actorSystem);

    return logRequest("http-request", () ->
            logResult("http-response", statusRoute::buildStatusRoute));
}
 
Example #10
Source File: SimpleClusterMain.java    From akka-kubernetes-example with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  ActorSystem actorSystem = ActorSystem.create(CLUSTER_NAME);
  actorSystem.actorOf(SimpleClusterListener.props());
  final ActorMaterializer materializer = ActorMaterializer.create(actorSystem);

  Cluster cluster = Cluster.get(actorSystem);
  List<Address> addresses = Arrays.asList(System.getenv().get("SEED_NODES").split(","))
      .stream()
      .map(ip -> new Address("akka.tcp", CLUSTER_NAME, ip, 2551))
      .collect(Collectors.toList());
  cluster.joinSeedNodes(addresses);
}
 
Example #11
Source File: SlaveSystem.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
public static void start() {
	final Configuration c = ConfigurationSingleton.get();
	
	final Config config = ConfigFactory.parseString(
			"akka.remote.artery.canonical.hostname = \"" + c.getHost() + "\"\n" +
			"akka.remote.artery.canonical.port = " + c.getPort() + "\n" +
			"akka.cluster.roles = [" + SLAVE_ROLE + "]\n" +
			"akka.cluster.seed-nodes = [\"akka://" + c.getActorSystemName() + "@" + c.getMasterHost() + ":" + c.getMasterPort() + "\"]")
		.withFallback(ConfigFactory.load("application"));
	
	final ActorSystem system = ActorSystem.create(c.getActorSystemName(), config);
	
	ActorRef reaper = system.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			for (int i = 0; i < c.getNumWorkers(); i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
		}
	});
	
	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
}
 
Example #12
Source File: OctopusMaster.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
public static void start(String actorSystemName, int workers, String host, int port) {

		final Config config = createConfiguration(actorSystemName, MASTER_ROLE, host, port, host, port);
		
		final ActorSystem system = createSystem(actorSystemName, config);
		
		Cluster.get(system).registerOnMemberUp(new Runnable() {
			@Override
			public void run() {
				system.actorOf(ClusterListener.props(), ClusterListener.DEFAULT_NAME);
			//	system.actorOf(MetricsListener.props(), MetricsListener.DEFAULT_NAME);

				system.actorOf(Profiler.props(), Profiler.DEFAULT_NAME);
				
				for (int i = 0; i < workers; i++)
					system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
				
			//	int maxInstancesPerNode = workers; // TODO: Every node gets the same number of workers, so it cannot be a parameter for the slave nodes
			//	Set<String> useRoles = new HashSet<>(Arrays.asList("master", "slave"));
			//	ActorRef router = system.actorOf(
			//		new ClusterRouterPool(
			//			new AdaptiveLoadBalancingPool(SystemLoadAverageMetricsSelector.getInstance(), 0),
			//			new ClusterRouterPoolSettings(10000, workers, true, new HashSet<>(Arrays.asList("master", "slave"))))
			//		.props(Props.create(Worker.class)), "router");
			}
		});
		
		final Scanner scanner = new Scanner(System.in);
		String line = scanner.nextLine();
		scanner.close();
		
		int attributes = Integer.parseInt(line);
		
		system.actorSelection("/user/" + Profiler.DEFAULT_NAME).tell(new Profiler.TaskMessage(attributes), ActorRef.noSender());
	}
 
Example #13
Source File: OctopusSystem.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
protected static ActorSystem createSystem(String actorSystemName, Config config) {
	
	// Create the ActorSystem
	final ActorSystem system = ActorSystem.create(actorSystemName, config);
	
	// Register a callback that ends the program when the ActorSystem terminates
	system.registerOnTermination(new Runnable() {
		@Override
		public void run() {
			System.exit(0);
		}
	});
	
	// Register a callback that terminates the ActorSystem when it is detached from the cluster
	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
	
	return system;
}
 
Example #14
Source File: MasterSystem.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public static void start() {
	final Configuration c = ConfigurationSingleton.get();
	
	final Config config = ConfigFactory.parseString(
			"akka.remote.artery.canonical.hostname = \"" + c.getHost() + "\"\n" +
			"akka.remote.artery.canonical.port = " + c.getPort() + "\n" +
			"akka.cluster.roles = [" + MASTER_ROLE + "]\n" +
			"akka.cluster.seed-nodes = [\"akka://" + c.getActorSystemName() + "@" + c.getHost() + ":" + c.getPort() + "\"]")
		.withFallback(ConfigFactory.load("application"));
	
	final ActorSystem system = ActorSystem.create(c.getActorSystemName(), config);
	
	ActorRef reaper = system.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);
	
	ActorRef master = system.actorOf(Master.props(), Master.DEFAULT_NAME);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			for (int i = 0; i < c.getNumWorkers(); i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
		}
	});
	
	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
	
	System.out.println("Press <enter> to end the application!");
	try (final Scanner scanner = new Scanner(System.in)) {
		scanner.nextLine();
	}
	
	system.actorSelection("/user/" + Master.DEFAULT_NAME).tell(new Master.EndMessage(), ActorRef.noSender());
}
 
Example #15
Source File: SshLocalManagerActor.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
@Override
public void preStart() {
    String nodeAddress = Cluster.get(context().system()).selfAddress().toString();
    localManager.setNodeAddress(nodeAddress);
}
 
Example #16
Source File: SshClusterManagerActor.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public SshClusterManagerActor(SshClusterManagerImpl sshClusterManager) {
    this.sshClusterManager = sshClusterManager;
    this.cluster = Cluster.get(getContext().system());
    sshClusterManager.setContext(getContext().system(), self(), cluster.selfAddress().toString());
}
 
Example #17
Source File: PoliciesRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static Route createRoute(final ActorSystem actorSystem, final ActorRef healthCheckingActor) {
    final StatusRoute statusRoute = new StatusRoute(new ClusterStatusSupplier(Cluster.get(actorSystem)),
            healthCheckingActor, actorSystem);

    return logRequest("http-request", () -> logResult("http-response", statusRoute::buildStatusRoute));
}
 
Example #18
Source File: ClusterStatusObserverActor.java    From java-11-examples with Apache License 2.0 4 votes vote down vote up
public ClusterStatusObserverActor(ClusterStatusObserver clusterStatusObserver) {
    this.clusterStatusObserver = clusterStatusObserver;
    this.cluster = Cluster.get(getContext().system());
}
 
Example #19
Source File: ConnectivityRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static Route createRoute(final ActorSystem actorSystem, final ActorRef healthCheckingActor) {
    final StatusRoute statusRoute = new StatusRoute(new ClusterStatusSupplier(Cluster.get(actorSystem)),
            healthCheckingActor, actorSystem);

    return logRequest("http-request", () -> logResult("http-response", statusRoute::buildStatusRoute));
}
 
Example #20
Source File: SearchRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static Route createRoute(final ActorSystem actorSystem, final ActorRef healthCheckingActor) {
    final StatusRoute statusRoute = new StatusRoute(new ClusterStatusSupplier(Cluster.get(actorSystem)),
            healthCheckingActor, actorSystem);

    return logRequest("http-request", () -> logResult("http-response", statusRoute::buildStatusRoute));
}
 
Example #21
Source File: ThingsRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static Route createRoute(final ActorSystem actorSystem, final ActorRef healthCheckingActor) {
    final StatusRoute statusRoute = new StatusRoute(new ClusterStatusSupplier(Cluster.get(actorSystem)),
            healthCheckingActor, actorSystem);

    return logRequest("http-request", () -> logResult("http-response", statusRoute::buildStatusRoute));
}
 
Example #22
Source File: GatewayRootActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static Route createRoute(final ActorSystem actorSystem,
        final GatewayConfig gatewayConfig,
        final ActorRef proxyActor,
        final ActorRef streamingActor,
        final ActorRef healthCheckingActor,
        final ActorRef pubSubMediator,
        final HealthCheckConfig healthCheckConfig,
        final JwtAuthenticationFactory jwtAuthenticationFactory,
        final ProtocolAdapterProvider protocolAdapterProvider,
        final HeaderTranslator headerTranslator) {

    final AuthenticationConfig authConfig = gatewayConfig.getAuthenticationConfig();

    final MessageDispatcher authenticationDispatcher =
            actorSystem.dispatchers().lookup(AUTHENTICATION_DISPATCHER_NAME);

    final GatewayAuthenticationDirectiveFactory authenticationDirectiveFactory =
            new DittoGatewayAuthenticationDirectiveFactory(authConfig, jwtAuthenticationFactory,
                    authenticationDispatcher);

    final Supplier<ClusterStatus> clusterStateSupplier = new ClusterStatusSupplier(Cluster.get(actorSystem));
    final StatusAndHealthProvider statusAndHealthProvider =
            DittoStatusAndHealthProviderFactory.of(actorSystem, clusterStateSupplier, healthCheckConfig);

    final LimitsConfig limitsConfig = gatewayConfig.getLimitsConfig();
    final DittoHeadersSizeChecker dittoHeadersSizeChecker =
            DittoHeadersSizeChecker.of(limitsConfig.getHeadersMaxSize(), limitsConfig.getAuthSubjectsMaxCount());

    final HttpConfig httpConfig = gatewayConfig.getHttpConfig();
    final DevOpsConfig devOpsConfig = authConfig.getDevOpsConfig();

    final GatewaySignalEnrichmentConfig signalEnrichmentConfig =
            gatewayConfig.getStreamingConfig().getSignalEnrichmentConfig();
    final GatewaySignalEnrichmentProvider signalEnrichmentProvider =
            signalEnrichmentProvider(signalEnrichmentConfig, actorSystem);

    final StreamingConfig streamingConfig = gatewayConfig.getStreamingConfig();
    final CommandConfig commandConfig = gatewayConfig.getCommandConfig();

    return RootRoute.getBuilder(httpConfig)
            .statsRoute(new StatsRoute(proxyActor, actorSystem, httpConfig, commandConfig, devOpsConfig,
                    headerTranslator))
            .statusRoute(new StatusRoute(clusterStateSupplier, healthCheckingActor, actorSystem))
            .overallStatusRoute(new OverallStatusRoute(clusterStateSupplier, statusAndHealthProvider, devOpsConfig))
            .cachingHealthRoute(
                    new CachingHealthRoute(statusAndHealthProvider, gatewayConfig.getPublicHealthConfig()))
            .devopsRoute(new DevOpsRoute(proxyActor, actorSystem, httpConfig, commandConfig, devOpsConfig,
                    headerTranslator))
            .policiesRoute(new PoliciesRoute(proxyActor, actorSystem, httpConfig, commandConfig, headerTranslator))
            .sseThingsRoute(ThingsSseRouteBuilder.getInstance(streamingActor, streamingConfig, pubSubMediator)
                    .withSignalEnrichmentProvider(signalEnrichmentProvider))
            .thingsRoute(new ThingsRoute(proxyActor, actorSystem, httpConfig, commandConfig,
                    gatewayConfig.getMessageConfig(), gatewayConfig.getClaimMessageConfig(), headerTranslator))
            .thingSearchRoute(
                    new ThingSearchRoute(proxyActor, actorSystem, httpConfig, commandConfig, headerTranslator))
            .whoamiRoute(new WhoamiRoute(proxyActor, actorSystem, httpConfig, commandConfig, headerTranslator))
            .websocketRoute(WebSocketRoute.getInstance(streamingActor, streamingConfig)
                    .withSignalEnrichmentProvider(signalEnrichmentProvider)
                    .withHeaderTranslator(headerTranslator))
            .supportedSchemaVersions(httpConfig.getSupportedSchemaVersions())
            .protocolAdapterProvider(protocolAdapterProvider)
            .headerTranslator(headerTranslator)
            .httpAuthenticationDirective(authenticationDirectiveFactory.buildHttpAuthentication())
            .wsAuthenticationDirective(authenticationDirectiveFactory.buildWsAuthentication())
            .dittoHeadersSizeChecker(dittoHeadersSizeChecker)
            .build();
}
 
Example #23
Source File: BlockedNamespaces.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private BlockedNamespaces(final DistributedDataConfig config, final ActorSystem system) {
    super(config, system, system.dispatchers().lookup(BLOCKED_NAMESPACES_DISPATCHER));
    selfUniqueAddress = SelfUniqueAddress.apply(Cluster.get(system).selfUniqueAddress());
}
 
Example #24
Source File: Worker.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public Worker() {
	this.cluster = Cluster.get(this.context().system());
}
 
Example #25
Source File: PubUpdater.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
private PubUpdater(final DDataWriter<?> ddataWriter) {
    this.ddataWriter = ddataWriter;
    Cluster.get(getContext().getSystem()).subscribe(getSelf(), ClusterEvent.MemberRemoved.class);
}
 
Example #26
Source File: SlaveSystem.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public static void start() {
	final Configuration c = ConfigurationSingleton.get();
	
	final Config config = ConfigFactory.parseString(
			"akka.remote.artery.canonical.hostname = \"" + c.getHost() + "\"\n" +
			"akka.remote.artery.canonical.port = " + c.getPort() + "\n" +
			"akka.cluster.roles = [" + SLAVE_ROLE + "]\n" +
			"akka.cluster.seed-nodes = [\"akka://" + c.getActorSystemName() + "@" + c.getMasterHost() + ":" + c.getMasterPort() + "\"]")
		.withFallback(ConfigFactory.load("application"));
	
	final ActorSystem system = ActorSystem.create(c.getActorSystemName(), config);
	
//	ActorRef clusterListener = system.actorOf(ClusterListener.props(), ClusterListener.DEFAULT_NAME);
//	ActorRef metricsListener = system.actorOf(MetricsListener.props(), MetricsListener.DEFAULT_NAME);
	
	ActorRef reaper = system.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			for (int i = 0; i < c.getNumWorkers(); i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
		}
	});

	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
}
 
Example #27
Source File: DittoService.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Starts the root actor(s) of this service.
 * <p>
 * May be overridden to change the way how the root actor(s) of this service are started. <em>Note: If this method
 * is overridden, the following methods will not be called automatically:</em>
 * </p>
 * <ul>
 * <li>{@link #getMainRootActorProps(org.eclipse.ditto.services.base.config.ServiceSpecificConfig, akka.actor.ActorRef, akka.stream.ActorMaterializer)},</li>
 * <li>{@link #startMainRootActor(akka.actor.ActorSystem, akka.actor.Props)},</li>
 * <li>{@link #getAdditionalRootActorsInformation(org.eclipse.ditto.services.base.config.ServiceSpecificConfig, akka.actor.ActorRef, akka.stream.ActorMaterializer)} and</li>
 * <li>{@link #startAdditionalRootActors(akka.actor.ActorSystem, Iterable)}.</li>
 * </ul>
 *
 * @param actorSystem Akka actor system for starting actors.
 * @param serviceSpecificConfig the configuration settings of this service.
 */
protected void startServiceRootActors(final ActorSystem actorSystem, final C serviceSpecificConfig) {
    logger.info("Waiting for member to be up before proceeding with further initialisation.");
    Cluster.get(actorSystem).registerOnMemberUp(() -> {
        logger.info("Member successfully joined the cluster, instantiating remaining actors.");

        final ActorRef pubSubMediator = getDistributedPubSubMediatorActor(actorSystem);
        final ActorMaterializer materializer = createActorMaterializer(actorSystem);

        injectSystemPropertiesLimits(serviceSpecificConfig);

        startMainRootActor(actorSystem, getMainRootActorProps(serviceSpecificConfig, pubSubMediator, materializer));
        startAdditionalRootActors(actorSystem, getAdditionalRootActorsInformation(serviceSpecificConfig,
                pubSubMediator, materializer));
    });
}
 
Example #28
Source File: MasterSystem.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public static void start() {
	final Configuration c = ConfigurationSingleton.get();
	
	final Config config = ConfigFactory.parseString(
			"akka.remote.artery.canonical.hostname = \"" + c.getHost() + "\"\n" +
			"akka.remote.artery.canonical.port = " + c.getPort() + "\n" +
			"akka.cluster.roles = [" + MASTER_ROLE + "]\n" +
			"akka.cluster.seed-nodes = [\"akka://" + c.getActorSystemName() + "@" + c.getHost() + ":" + c.getPort() + "\"]")
		.withFallback(ConfigFactory.load("application"));
	
	final ActorSystem system = ActorSystem.create(c.getActorSystemName(), config);

//	ActorRef clusterListener = system.actorOf(ClusterListener.props(), ClusterListener.DEFAULT_NAME);
//	ActorRef metricsListener = system.actorOf(MetricsListener.props(), MetricsListener.DEFAULT_NAME);
	
	ActorRef reaper = system.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);
	
	ActorRef reader = system.actorOf(Reader.props(), Reader.DEFAULT_NAME);
	
	ActorRef collector = system.actorOf(Collector.props(), Collector.DEFAULT_NAME);
	
	ActorRef master = system.actorOf(Master.props(reader, collector), Master.DEFAULT_NAME);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			for (int i = 0; i < c.getNumWorkers(); i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
			
			if (!c.isStartPaused())
				system.actorSelection("/user/" + Master.DEFAULT_NAME).tell(new Master.StartMessage(), ActorRef.noSender());
		}
	});

	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
	
	if (c.isStartPaused()) {
		System.out.println("Press <enter> to start!");
		try (final Scanner scanner = new Scanner(System.in)) {
			scanner.nextLine();
		}
		
		system.actorSelection("/user/" + Master.DEFAULT_NAME).tell(new Master.StartMessage(), ActorRef.noSender());
	}
}
 
Example #29
Source File: ClusterStatusSupplier.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates a new {@code ClusterStatusSupplier} instance with the given {@code cluster} to get the state from.
 *
 * @param cluster the given cluster to extract the information from.
 */
public ClusterStatusSupplier(final Cluster cluster) {
    this.cluster = cluster;
    clusterConfig = DefaultClusterConfig.of(DefaultScopedConfig.dittoScoped(cluster.system().settings().config()));
}
 
Example #30
Source File: ClusterStatusStage.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates the cluster status stage - whenever a message (tick) triggers the stage,
 * <ul>
 * <li>the ClusterStatus is determined</li>
 * <li>it is checked that all members are reachable and all {@link #EXPECTED_ROLES} are present</li>
 * <li>when everything is healthy, in outlet 0 the number of instances of the expected roles will be emitted</li>
 * <li>when anything is not health, in outlet 1 a {@link CreditDecision} with rejection is emitted</li>
 * </ul>
 *
 * @param actorSystem the ActorSystem to determine the cluster from
 * @param <T> the type of the tick messages
 * @return the created cluster status stage.
 */
static <T> Graph<FanOutShape2<T, Integer, CreditDecision>, NotUsed> create(
        final ActorSystem actorSystem) {
    return create(new ClusterStatusSupplier(Cluster.get(actorSystem)));
}