akka.actor.Address Java Examples

The following examples show how to use akka.actor.Address. 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: AkkaRpcService.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public AkkaRpcService(final ActorSystem actorSystem, final AkkaRpcServiceConfiguration configuration) {
	this.actorSystem = checkNotNull(actorSystem, "actor system");
	this.configuration = checkNotNull(configuration, "akka rpc service configuration");

	Address actorSystemAddress = AkkaUtils.getAddress(actorSystem);

	if (actorSystemAddress.host().isDefined()) {
		address = actorSystemAddress.host().get();
	} else {
		address = "";
	}

	if (actorSystemAddress.port().isDefined()) {
		port = (Integer) actorSystemAddress.port().get();
	} else {
		port = -1;
	}

	internalScheduledExecutor = new ActorSystemScheduledExecutorAdapter(actorSystem);

	terminationFuture = new CompletableFuture<>();

	stopped = false;
}
 
Example #2
Source File: LeaderConnectionInfo.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public LeaderConnectionInfo(String address, UUID leaderSessionID) throws FlinkException {
	this.address = address;
	this.leaderSessionID = leaderSessionID;

	final Address akkaAddress;
	// this only works as long as the address is Akka based
	try {
		akkaAddress = AkkaUtils.getAddressFromAkkaURL(address);
	} catch (MalformedURLException e) {
		throw new FlinkException("Could not extract the hostname from the given address \'" +
			address + "\'.", e);
	}

	if (akkaAddress.host().isDefined()) {
		hostname = akkaAddress.host().get();
	} else {
		hostname = "localhost";
	}

	if (akkaAddress.port().isDefined()) {
		port = (int) akkaAddress.port().get();
	} else {
		port = -1;
	}
}
 
Example #3
Source File: AkkaRpcService.java    From flink with Apache License 2.0 6 votes vote down vote up
public AkkaRpcService(final ActorSystem actorSystem, final AkkaRpcServiceConfiguration configuration) {
	this.actorSystem = checkNotNull(actorSystem, "actor system");
	this.configuration = checkNotNull(configuration, "akka rpc service configuration");

	Address actorSystemAddress = AkkaUtils.getAddress(actorSystem);

	if (actorSystemAddress.host().isDefined()) {
		address = actorSystemAddress.host().get();
	} else {
		address = "";
	}

	if (actorSystemAddress.port().isDefined()) {
		port = (Integer) actorSystemAddress.port().get();
	} else {
		port = -1;
	}

	internalScheduledExecutor = new ActorSystemScheduledExecutorAdapter(actorSystem);

	terminationFuture = new CompletableFuture<>();

	stopped = false;
}
 
Example #4
Source File: LeaderConnectionInfo.java    From flink with Apache License 2.0 6 votes vote down vote up
public LeaderConnectionInfo(String address, UUID leaderSessionID) throws FlinkException {
	this.address = address;
	this.leaderSessionID = leaderSessionID;

	final Address akkaAddress;
	// this only works as long as the address is Akka based
	try {
		akkaAddress = AkkaUtils.getAddressFromAkkaURL(address);
	} catch (MalformedURLException e) {
		throw new FlinkException("Could not extract the hostname from the given address \'" +
			address + "\'.", e);
	}

	if (akkaAddress.host().isDefined()) {
		hostname = akkaAddress.host().get();
	} else {
		hostname = "localhost";
	}

	if (akkaAddress.port().isDefined()) {
		port = (int) akkaAddress.port().get();
	} else {
		port = -1;
	}
}
 
Example #5
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 #6
Source File: Shepherd.java    From akka-tutorial with Apache License 2.0 6 votes vote down vote up
private void handle(SubscriptionMessage message) {
	
	// Find the sender of this message
	ActorRef slave = this.getSender();

	// Keep track of all subscribed slaves but avoid double subscription.
	if (!this.slaves.add(slave)) 
		return;
	this.log().info("New subscription: " + slave);

	// Acknowledge the subscription.
	slave.tell(new Slave.AcknowledgementMessage(), this.getSelf());

	// Set the subscriber on the watch list to get its Terminated messages
	this.getContext().watch(slave);

	// Extract the remote system's address from the sender.
	Address remoteAddress = this.getSender().path().address();

	// Inform the master about the new remote system.
	this.master.tell(new Master.RemoteSystemMessage(remoteAddress), this.getSelf());
}
 
Example #7
Source File: Calculator.java    From akka-tutorial with Apache License 2.0 6 votes vote down vote up
public static void runSlave(String host, int port, String masterHost, int masterPort) {

		// Create the local ActorSystem
		final Config config = AkkaUtils.createRemoteAkkaConfig(host, port);
		final ActorSystem actorSystem = ActorSystem.create(DEFAULT_SLAVE_SYSTEM_NAME, config);
		
		// Create the reaper.
		actorSystem.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);

		// Create a Slave
		final ActorRef slave = actorSystem.actorOf(Slave.props(), Slave.DEFAULT_NAME);

		// Tell the Slave to register the local ActorSystem
		slave.tell(new Slave.AddressMessage(new Address("akka.tcp", DEFAULT_MASTER_SYSTEM_NAME, masterHost, masterPort)), ActorRef.noSender());
		
		// Await termination: The termination should be issued by the reaper
		Calculator.awaitTermination(actorSystem);
	}
 
Example #8
Source File: DefaultQuarantineHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void wasQuarantinedBy(String remoteSystem, ActorSystem actorSystem) {
	Address actorSystemAddress = AkkaUtils.getAddress(actorSystem);
	log.error("The actor system {} has been quarantined by {}. Shutting the actor system " +
		"down to be able to reestablish a connection!", actorSystemAddress, remoteSystem);

	shutdownActorSystem(actorSystem);
}
 
Example #9
Source File: AkkaRpcService.java    From flink with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public AkkaRpcService(final ActorSystem actorSystem, final AkkaRpcServiceConfiguration configuration) {
	this.actorSystem = checkNotNull(actorSystem, "actor system");
	this.configuration = checkNotNull(configuration, "akka rpc service configuration");

	Address actorSystemAddress = AkkaUtils.getAddress(actorSystem);

	if (actorSystemAddress.host().isDefined()) {
		address = actorSystemAddress.host().get();
	} else {
		address = "";
	}

	if (actorSystemAddress.port().isDefined()) {
		port = (Integer) actorSystemAddress.port().get();
	} else {
		port = -1;
	}

	captureAskCallstacks = configuration.captureAskCallStack();

	internalScheduledExecutor = new ActorSystemScheduledExecutorAdapter(actorSystem);

	terminationFuture = new CompletableFuture<>();

	stopped = false;

	supervisor = startSupervisorActor();
}
 
Example #10
Source File: CompressedDDataHandler.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Void> removeAddress(final Address address,
        final Replicator.WriteConsistency writeConsistency) {
    return update(writeConsistency, mmap -> {
        ORMultiMap<ActorRef, ByteString> result = mmap;
        for (final ActorRef subscriber : mmap.getEntries().keySet()) {
            if (subscriber.path().address().equals(address)) {
                result = result.remove(selfUniqueAddress, subscriber);
            }
        }
        return result;
    });
}
 
Example #11
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 #12
Source File: DefaultQuarantineHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void hasQuarantined(String remoteSystem, ActorSystem actorSystem) {
	Address actorSystemAddress = AkkaUtils.getAddress(actorSystem);
	log.error("The actor system {} has quarantined the remote actor system {}. Shutting " +
		"the actor system down to be able to reestablish a connection!", actorSystemAddress, remoteSystem);

	shutdownActorSystem(actorSystem);
}
 
Example #13
Source File: PubUpdater.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void removeMember(final ClusterEvent.MemberRemoved memberRemoved) {
    // publisher detected unreachable remote. remove it from local ORMap.
    final Address address = memberRemoved.member().address();
    log.info("Removing subscribers on removed member <{}>", address);
    ddataWriter.removeAddress(address, Replicator.writeLocal());
}
 
Example #14
Source File: Slave.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public AddressMessage(final Address address) {
	this.address = address;
}
 
Example #15
Source File: ClusterStatusSupplier.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public ClusterStatus get() {
    final Function<Member, String> mapMemberToString = member -> member.address().toString();

    final Set<String> allRoles = cluster.state().getAllRoles()
            .stream()
            .filter(role -> !clusterConfig.getClusterStatusRolesBlacklist().contains(role))
            .collect(Collectors.toSet());
    final Set<Member> unreachable = cluster.state().getUnreachable();
    final Set<Member> all =
            StreamSupport.stream(cluster.state().getMembers().spliterator(), false).collect(Collectors.toSet());
    final Set<Member> reachable = all.stream().filter(m -> !unreachable.contains(m)).collect(Collectors.toSet());

    final Set<ClusterRoleStatus> roles = new HashSet<>(allRoles.size());
    allRoles.forEach(role -> {
        final Predicate<Member> filterRole = member -> member.getRoles().contains(role);

        // only add role if member has reachable or unreachable entries
        if (all.stream().anyMatch(filterRole)) {
            roles.add(ClusterRoleStatus.of(
                    role,
                    reachable.stream()
                            .filter(filterRole)
                            .map(mapMemberToString)
                            .collect(Collectors.toSet()),
                    unreachable.stream()
                            .filter(filterRole)
                            .map(mapMemberToString)
                            .collect(Collectors.toSet()),
                    Optional.ofNullable(cluster.state().getRoleLeader(role))
                            .map(Address::toString)
                            .orElse(null)
            ));
        }
    });

    return ClusterStatus.of(
            reachable.stream().map(mapMemberToString).collect(Collectors.toSet()),
            unreachable.stream().map(mapMemberToString).collect(Collectors.toSet()),
            cluster.state().getSeenBy().stream().map(Address::toString).collect(Collectors.toSet()),
            Optional.ofNullable(cluster.state().getLeader()).map(Address::toString).orElse(null),
            cluster.getSelfRoles(),
            roles
    );
}
 
Example #16
Source File: StatisticsActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void becomeStatisticsAwaiting() {

        final Map<String, ShardStatisticsWrapper> shardStatisticsMap = new HashMap<>();

        final AskTimeoutException askTimeoutException = new AskTimeoutException("Timed out");
        getTimers().startSingleTimer(askTimeoutException, askTimeoutException, statisticsConfig.getAskTimeout());

        getContext().become(ReceiveBuilder.create()
                        .match(RetrieveStatistics.class, this::respondWithCachedStatistics)
                        .match(ShardRegion.ClusterShardingStats.class, clusterShardingStats -> {
                            final Optional<ShardStatisticsWrapper> shardStatistics =
                                    getShardStatistics(shardStatisticsMap, getSender());

                            if (shardStatistics.isPresent()) {
                                final Map<Address, ShardRegion.ShardRegionStats> regions = clusterShardingStats.getRegions();
                                shardStatistics.get().count = regions.isEmpty() ? 0 : regions.values().stream()
                                        .mapToInt(shardRegionStats -> shardRegionStats.getStats().isEmpty() ? 0 :
                                                shardRegionStats.getStats().values().stream()
                                                        .mapToInt(o -> (Integer) o)
                                                        .sum())
                                        .sum();
                            } else {
                                log.warning("Got stats from unknown shard <{}>: <{}>", getSender(), clusterShardingStats);
                            }

                            // all shard statistics are present; no need to wait more.
                            if (shardStatisticsMap.size() >= statisticsConfig.getShards().size()) {
                                getTimers().cancel(askTimeoutException);
                                getSelf().tell(askTimeoutException, getSelf());
                            }
                        })
                        .matchEquals(askTimeoutException, unit -> {
                            updateGauges(shardStatisticsMap);
                            currentStatistics = Statistics.fromGauges(gauges);
                            unbecome();
                        })
                        .matchEquals(InternalResetStatisticsDetails.INSTANCE, this::resetStatisticsDetails)
                        .match(DistributedPubSubMediator.SubscribeAck.class, this::logSubscribeAck)
                        .matchAny(m -> {
                            log.info("Stashing message during 'statisticsAwaiting': {}", m);
                            stash();
                        })
                        .build(),
                false);
    }
 
Example #17
Source File: Master.java    From akka-tutorial with Apache License 2.0 4 votes vote down vote up
public RemoteSystemMessage(final Address remoteAddress) {
	this.remoteAddress = remoteAddress;
}
 
Example #18
Source File: ClientActor.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Object message) {

    int startSize = nodes.size();

    String routerPath = routersByMessageType.get( message.getClass() );

    if ( routerPath != null && ready ) {

        // just pick any node, the ClusterSingletonRouter will do the consistent hash routing
        List<Address> nodesList = new ArrayList<>( nodes );
        Address address = nodesList.get( ThreadLocalRandom.current().nextInt( nodesList.size() ) );
        ActorSelection service = getContext().actorSelection( address + routerPath );
        service.tell( message, getSender() );

    } else if ( routerPath != null ) {

        logger.debug("{} responding with status unknown", name);
        getSender().tell( new ErrorResponse("ClientActor not ready"), getSender() );

    } else if ( message instanceof StatusRequest ) {
        if ( ready ) {
            getSender().tell( new StatusMessage( name, StatusMessage.Status.READY ), getSender() );
        } else {
            getSender().tell( new StatusMessage( name, StatusMessage.Status.INITIALIZING), getSender() );
        }
        return;

    } else {
        processAsClusterEvent( message );
    }

    if ( logger.isDebugEnabled() && startSize != nodes.size() ) {
        logger.debug( "{} now knows {} nodes", name, nodes.size() );
    }

    if (!nodes.isEmpty() && !ready) {
        logger.debug( name + " is ready" );
        ready = true;

    } else if (nodes.isEmpty() && ready) {
        ready = false;
    }
}
 
Example #19
Source File: DDataWriter.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Remove all subscribers at an address from the ddata with write consistency local.
 *
 * @param address the address of the cluster member to be removed.
 * @param writeConsistency write consistency for the operation.
 * @return future that completes or fails according to the result of the operation.
 */
CompletionStage<Void> removeAddress(Address address, Replicator.WriteConsistency writeConsistency);
 
Example #20
Source File: ClusterListener.java    From flux with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor
 * @param memberAddresses mutating list of current cluster member addresses
 */
public ClusterListener(List<Address> memberAddresses) {
	this.memberAddresses = memberAddresses;
}