akka.management.cluster.bootstrap.ClusterBootstrap Scala Examples
The following examples show how to use akka.management.cluster.bootstrap.ClusterBootstrap.
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.
Example 1
Source File: DocSvr.scala From Raphtory with Apache License 2.0 | 5 votes |
package com.raphtory.core.clustersetup import akka.actor.ActorSystem import akka.actor.Address import akka.actor.ExtendedActorSystem import akka.cluster.Cluster import akka.cluster.Member import akka.event.LoggingAdapter import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.javadsl.AkkaManagement import com.raphtory.core.clustersetup.util.ConfigUtils._ import com.raphtory.core.utils.Utils import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import com.typesafe.config.ConfigValueFactory import scala.collection.JavaConversions import scala.collection.JavaConversions._ trait DocSvr { def seedLoc: String implicit val system: ActorSystem val docker = System.getenv().getOrDefault("DOCKER", "false").trim.toBoolean val clusterSystemName: String = Utils.clusterSystemName val ssn: String = java.util.UUID.randomUUID.toString def printConfigInfo(config: Config, system: ActorSystem): Unit = { val log: LoggingAdapter = system.log val systemConfig: SystemConfig = config.parse() val bindAddress: SocketAddress = systemConfig.bindAddress val tcpAddress: SocketAddress = systemConfig.tcpAddress log.info(s"Created ActorSystem with ID: $ssn") log.info(s"Binding ActorSystem internally to address ${bindAddress.host}:${bindAddress.port}") log.info(s"Binding ActorSystem externally to host ${tcpAddress.host}:${tcpAddress.port}") log.info(s"Registering the following seeds to ActorSystem: ${systemConfig.seeds}") log.info(s"Registering the following roles to ActorSystem: ${systemConfig.roles}") // FIXME: This is bit unorthodox ... val akkaSystemUrl: Address = system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress log.info(s"ActorSystem successfully initialised at the following Akka URL: $akkaSystemUrl") } }
Example 2
Source File: Main.scala From streamee with Apache License 2.0 | 5 votes |
package io.moia.streamee.demo import akka.actor.{ ActorSystem => ClassicSystem } import akka.actor.CoordinatedShutdown.Reason import akka.actor.typed.{ Behavior, Scheduler } import akka.actor.typed.scaladsl.{ ActorContext, Behaviors } import akka.actor.typed.scaladsl.adapter.{ ClassicActorSystemOps, TypedActorSystemOps } import akka.cluster.typed.{ Cluster, ClusterSingleton, SelfUp, SingletonActor, Subscribe, Unsubscribe } import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import io.moia.streamee.FrontProcessor import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector import org.slf4j.LoggerFactory import pureconfig.generic.auto.exportReader import pureconfig.ConfigSource import scala.concurrent.ExecutionContext import scala.concurrent.duration.FiniteDuration object Main { final case class Config( api: Api.Config, textShufflerProcessorTimeout: FiniteDuration, textShuffler: TextShuffler.Config ) final object TopLevelActorTerminated extends Reason private val logger = LoggerFactory.getLogger(getClass) def main(args: Array[String]): Unit = { // Always use async logging! sys.props += "log4j2.contextSelector" -> classOf[AsyncLoggerContextSelector].getName // Must happen before creating the actor system! val config = ConfigSource.default.at("streamee-demo").loadOrThrow[Config] // Always start with a classic system! val system = ClassicSystem("streamee-demo") system.spawn(Main(config), "main") // Cluster bootstrap AkkaManagement(system).start() ClusterBootstrap(system).start() } def apply(config: Config): Behavior[SelfUp] = Behaviors.setup { context => if (logger.isInfoEnabled) logger.info(s"${context.system.name} started and ready to join cluster") Cluster(context.system).subscriptions ! Subscribe(context.self, classOf[SelfUp]) Behaviors.receive { (context, _) => if (logger.isInfoEnabled) logger.info(s"${context.system.name} joined cluster and is up") Cluster(context.system).subscriptions ! Unsubscribe(context.self) initialize(config)(context) Behaviors.empty } } private def initialize(config: Config)(implicit context: ActorContext[_]) = { import config._ implicit val classicSystem: ClassicSystem = context.system.toClassic implicit val ec: ExecutionContext = context.executionContext implicit val scheduler: Scheduler = context.system.scheduler val wordShufflerRunner = ClusterSingleton(context.system).init( SingletonActor(WordShufflerRunner(), "word-shuffler") .withStopMessage(WordShufflerRunner.Shutdown) ) val textShufflerProcessor = FrontProcessor( TextShuffler(config.textShuffler, wordShufflerRunner), textShufflerProcessorTimeout, "text-shuffler" ) Api(config.api, textShufflerProcessor) } }
Example 3
Source File: AkkaUdpClusterMain.scala From akka-kubernetes-tests with Apache License 2.0 | 5 votes |
package akka.kubernetes import akka.actor.ActorSystem import akka.cluster.Cluster import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.stream.ActorMaterializer object AkkaUdpClusterMain extends App { implicit val system = ActorSystem("ArteryUdp") implicit val mat = ActorMaterializer() implicit val cluster = Cluster(system) AkkaManagement(system).start() ClusterBootstrap(system).start() Cluster(system).registerOnMemberUp({ system.log.info("Cluster member is up!") }) }
Example 4
Source File: SoakMain.scala From akka-kubernetes-tests with Apache License 2.0 | 5 votes |
package akka.kubernetes.soak import akka.actor.ActorSystem import akka.cluster.Cluster import akka.http.scaladsl.Http import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.remote.RARP import akka.stream.ActorMaterializer import com.sun.management.OperatingSystemMXBean import scala.concurrent.duration._ import akka.util.PrettyDuration._ object SoakMain extends App { implicit val system = ActorSystem() implicit val mat = ActorMaterializer() val log = system.log import java.lang.management.ManagementFactory log.info("Java version: {}", sys.props("java.version")) log.info("Cores: " + Runtime.getRuntime.availableProcessors) log.info("Total Memory: " + Runtime.getRuntime.totalMemory / 1000000 + "Mb") log.info("Max Memory: " + Runtime.getRuntime.maxMemory / 1000000 + "Mb") log.info("Free Memory: " + Runtime.getRuntime.freeMemory / 1000000 + "Mb") val memorySize = ManagementFactory.getOperatingSystemMXBean.asInstanceOf[OperatingSystemMXBean].getTotalPhysicalMemorySize log.info("RAM: " + memorySize / 1000000 + "Mb") log.info("JAVA env vars: {}", sys.env.filterKeys(_.contains("JAVA"))) log.info("JVM env vars: {}", sys.env.filterKeys(_.contains("JVM"))) val management = AkkaManagement(system).start() val bootstrapStart = System.nanoTime() val bootstrap = ClusterBootstrap(system).start() val listeningOn = RARP(system).provider.getDefaultAddress.host.getOrElse("0.0.0.0") log.info("Listening on {}", listeningOn) Cluster(system).registerOnMemberUp({ val joiningTime = (System.nanoTime() - bootstrapStart).nano system.actorOf(PingPong.serverProps(), "server") val client = system.actorOf(PingPong.clientProps(joiningTime), "client") val clusterStats = new StatsEndpoint(system, client) log.info("Cluster member is up! Starting tests and binding http server. Joining time: {}", joiningTime.pretty) Http().bindAndHandle(clusterStats.route, listeningOn, 8080) }) }
Example 5
Source File: ChaosMain.scala From akka-kubernetes-tests with Apache License 2.0 | 5 votes |
package akka.kubernetes.chaos import akka.actor.ActorSystem import akka.cluster.Cluster import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.remote.RARP import akka.stream.ActorMaterializer object ChaosMain extends App { implicit val system = ActorSystem() implicit val mat = ActorMaterializer() val log = system.log val management = AkkaManagement(system).start() val bootstrap = ClusterBootstrap(system).start() val route = path("hello") { get { println("Time to say good bye") Runtime.getRuntime.halt(-1) complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>You won't get this</h1>")) } } val listeningOn = RARP(system).provider.getDefaultAddress.host.getOrElse("0.0.0.0") log.info("Listening on {}", listeningOn) Http().bindAndHandle(route, listeningOn, 8080) Cluster(system).registerOnMemberUp({ log.info("Cluster member is up!") }) }
Example 6
Source File: CqrsApp.scala From akka-kubernetes-tests with Apache License 2.0 | 5 votes |
package akka.kubernetes.couchbase import java.util.UUID import java.util.concurrent.atomic.AtomicInteger import akka.actor.ActorSystem import akka.cluster.Cluster import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.persistence.couchbase.scaladsl.CouchbaseReadJournal import akka.persistence.query.{NoOffset, PersistenceQuery} import akka.stream.ActorMaterializer import scala.concurrent.ExecutionContext import scala.concurrent.duration._ import scala.util.{Random, Try} object CqrsApp { def main(args: Array[String]): Unit = { val system = ActorSystem("CouchbaseSystem") val materializer = ActorMaterializer()(system) val ec: ExecutionContext = system.dispatcher val log = system.log AkkaManagement(system).start() ClusterBootstrap(system).start() Cluster(system).registerOnMemberUp { val selfRoles = Cluster(system).selfRoles log.info("Running with roles {}", selfRoles) val shardedSwitchEntity = ShardedSwitchEntity(system) shardedSwitchEntity.start() EventProcessorWrapper(system).start() if (selfRoles.contains("load-generation")) { log.info("Starting load generation") testIt(system, shardedSwitchEntity) } if (selfRoles.contains("simple-query")) { log.info("Starting simple query") verySimpleRead(system, materializer, ec) } } def verySimpleRead(implicit system: ActorSystem, mat: ActorMaterializer, ec: ExecutionContext): Unit = { val query = PersistenceQuery(system).readJournalFor[CouchbaseReadJournal](CouchbaseReadJournal.Identifier) val startTime = System.currentTimeMillis() query .currentEventsByTag("tag1", NoOffset) .runFold(0)((count, _) => count + 1) .onComplete { t: Try[Int] => system.log.info("Query finished for tag1 in {}. Read {} rows", (System.currentTimeMillis() - startTime).millis.toSeconds, t) } } // Every instance will add 100 persistent actors and second 2 messages to each per 2 seconds def testIt(system: ActorSystem, shardedSwitch: ShardedSwitchEntity): Unit = { val uuid = UUID.randomUUID() val nrSwitches = 100 def switchName(nr: Int) = s"switch-$uuid-$nr" log.info("Creating {} switches with uuid {}", nrSwitches, uuid) (0 until nrSwitches) foreach { s => shardedSwitch.tell(switchName(s), SwitchEntity.CreateSwitch(6)) } import system.dispatcher system.scheduler.schedule(3.seconds, 2.second) { (0 until nrSwitches) foreach { s => val switch = switchName(s) log.debug("Sending messages to switch {}", switch) shardedSwitch.tell(switch, SwitchEntity.SetPortStatus(Random.nextInt(6), portEnabled = true)) shardedSwitch.tell(switch, SwitchEntity.SendPortStatus) } } } } }
Example 7
Source File: AkkaKubernetes.scala From akka-kubernetes-tests with Apache License 2.0 | 5 votes |
package akka.kubernetes.sample import akka.actor.{Actor, ActorLogging, ActorSystem, PoisonPill, Props} import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.sharding.{ClusterSharding, ClusterShardingSettings} import akka.cluster.singleton.{ ClusterSingletonManager, ClusterSingletonManagerSettings, ClusterSingletonProxy, ClusterSingletonProxySettings } import akka.cluster.{Cluster, ClusterEvent} import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives._ import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.stream.ActorMaterializer object DemoApp extends App { implicit val system = ActorSystem("KubernetesTest") import system.{dispatcher, log} implicit val mat = ActorMaterializer() implicit val cluster = Cluster(system) log.info("Running with [{}]", new Resources()) log.info(s"Started [$system], cluster.selfAddress = ${cluster.selfAddress}") AkkaManagement(system).start() ClusterBootstrap(system).start() system.actorOf( ClusterSingletonManager.props(singletonProps = Props(new AkkaBoss("patriknw")), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), "boss" ) val bossProxy = system.actorOf( ClusterSingletonProxy.props(singletonManagerPath = "/user/boss", settings = ClusterSingletonProxySettings(system)), name = "bossProxy" ) val teamMembers = ClusterSharding(system).start( "team-member", Props(new AkkaMember()), ClusterShardingSettings(system), AkkaMember.extractEntityId, AkkaMember.extractShardId ) cluster.subscribe(system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent]) val talkToTheBoss = new TalkToTheBossRouteRoute(bossProxy) val talkToATeamMember = new TalkToATeamMemberRoute(teamMembers) Http().bindAndHandle( concat(talkToTheBoss.route(), talkToATeamMember.route(), ClusterStateRoute.routeGetMembers(cluster), VersionRoute.versionRoute), "0.0.0.0", 8080 ) Cluster(system).registerOnMemberUp({ log.info("Cluster member is up!") }) } class ClusterWatcher extends Actor with ActorLogging { implicit val cluster = Cluster(context.system) override def receive = { case msg ⇒ log.info(s"Cluster ${cluster.selfAddress} >>> " + msg) } }
Example 8
Source File: NSDbActors.scala From NSDb with Apache License 2.0 | 5 votes |
package io.radicalbit.nsdb.cluster import java.util.concurrent.TimeUnit import akka.actor._ import akka.cluster.Cluster import akka.cluster.ddata.DistributedData import akka.cluster.singleton._ import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.util.Timeout import io.radicalbit.nsdb.cluster.actor._ trait NSDbActors { implicit def system: ActorSystem implicit lazy val timeout: Timeout = Timeout(system.settings.config.getDuration("nsdb.global.timeout", TimeUnit.SECONDS), TimeUnit.SECONDS) def initTopLevelActors(): Unit = { AkkaManagement(system).start() ClusterBootstrap(system).start() system.actorOf( ClusterSingletonManager.props(singletonProps = Props(classOf[DatabaseActorsGuardian]), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), name = "databaseActorGuardian" ) system.actorOf( ClusterSingletonProxy.props(singletonManagerPath = "/user/databaseActorGuardian", settings = ClusterSingletonProxySettings(system)), name = "databaseActorGuardianProxy" ) DistributedData(system).replicator system.actorOf(ClusterListener.props(true), name = s"cluster-listener_${createNodeName(Cluster(system).selfMember)}") } }
Example 9
Source File: DemoApp.scala From reactive-lib with Apache License 2.0 | 5 votes |
package foo import akka.actor.{ Actor, ActorLogging, ActorSystem, Props } import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.{ Cluster, ClusterEvent } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.AkkaManagement import akka.management.cluster.bootstrap.ClusterBootstrap import akka.stream.ActorMaterializer object DemoApp extends App { implicit val system = ActorSystem("Appka") import system.log implicit val mat = ActorMaterializer() val cluster = Cluster(system) log.info(s"Started [$system], cluster.selfAddress = ${cluster.selfAddress}") log.info("something2") //#start-akka-management AkkaManagement(system).start() //#start-akka-management ClusterBootstrap(system).start() cluster.subscribe( system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent]) // add real app routes here val routes = path("hello") { get { complete( HttpEntity( ContentTypes.`text/html(UTF-8)`, "<h1>Hello</h1>")) } } Http().bindAndHandle(routes, "0.0.0.0", 8080) Cluster(system).registerOnMemberUp({ log.info("Cluster member is up!") }) } class ClusterWatcher extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive = { case msg ⇒ log.info(s"Cluster ${cluster.selfAddress} >>> " + msg) } }
Example 10
Source File: ClusterApp.scala From reactive-lib with Apache License 2.0 | 5 votes |
package foo import akka.actor.{ Actor, ActorLogging, ActorSystem, PoisonPill, Props } import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.singleton.{ ClusterSingletonManager, ClusterSingletonManagerSettings } import akka.cluster.{ Cluster, ClusterEvent } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.AkkaManagement import akka.management.cluster.bootstrap.ClusterBootstrap import akka.stream.ActorMaterializer object ClusterApp { def main(args: Array[String]): Unit = { implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() implicit val executionContext = system.dispatcher val cluster = Cluster(system) system.log.info("Starting Akka Management") system.log.info("something2") // AkkaManagement(system).start() // ClusterBootstrap(system).start() system.actorOf( ClusterSingletonManager.props( Props[NoisySingleton], PoisonPill, ClusterSingletonManagerSettings(system))) Cluster(system).subscribe( system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent]) // add real app routes here val routes = path("hello") { get { complete( HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Hello</h1>")) } } Http().bindAndHandle(routes, "0.0.0.0", 8080) system.log.info( s"Server online at http://localhost:8080/\nPress RETURN to stop...") cluster.registerOnMemberUp(() => { system.log.info("Cluster member is up!") }) } class ClusterWatcher extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive = { case msg ⇒ log.info(s"Cluster ${cluster.selfAddress} >>> " + msg) } } }
Example 11
Source File: ClusterBootstrapAutostart.scala From reactive-lib with Apache License 2.0 | 5 votes |
package com.lightbend.rp.akkaclusterbootstrap import akka.actor._ import akka.cluster.Cluster import akka.management.cluster.bootstrap.ClusterBootstrap import com.lightbend.rp.common.{ AkkaClusterBootstrapModule, Module, Platform } final class ClusterBootstrapAutostart(system: ExtendedActorSystem) extends Extension { if (Module.enabled(AkkaClusterBootstrapModule)) { val cluster = Cluster(system) if (cluster.settings.SeedNodes.nonEmpty) { system.log.warning("ClusterBootstrapAutostart is enabled but seed nodes are defined, no action will be taken") } else if (Platform.active.isEmpty) { system.log.info("ClusterBootstrapAutostart is enabled but no active platform detected (i.e. running locally), no action will be taken") } else { ClusterBootstrap(system).start() } } } object ClusterBootstrapAutostart extends ExtensionId[ClusterBootstrapAutostart] with ExtensionIdProvider { override def lookup: ClusterBootstrapAutostart.type = ClusterBootstrapAutostart override def get(system: ActorSystem): ClusterBootstrapAutostart = super.get(system) override def createExtension(system: ExtendedActorSystem): ClusterBootstrapAutostart = new ClusterBootstrapAutostart(system) }
Example 12
Source File: Main.scala From akka-persistence-cassandra with Apache License 2.0 | 5 votes |
package akka.persistence.cassandra.example import akka.actor.typed.{ ActorRef, ActorSystem } import akka.actor.typed.scaladsl.Behaviors import akka.cluster.sharding.typed.ShardingEnvelope import akka.cluster.typed.{ Cluster, SelfUp, Subscribe } import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.persistence.cassandra.example.LoadGenerator.Start import akka.actor.typed.scaladsl.LoggerOps import akka.stream.alpakka.cassandra.scaladsl.CassandraSessionRegistry import scala.concurrent.Await import scala.concurrent.duration._ object Main { def main(args: Array[String]): Unit = { ActorSystem(Behaviors.setup[SelfUp] { ctx => val readSettings = ReadSide.Settings(ctx.system.settings.config.getConfig("cassandra.example")) val writeSettings = ConfigurablePersistentActor.Settings(readSettings.nrTags) val loadSettings = LoadGenerator.Settings(ctx.system.settings.config.getConfig("cassandra.example")) AkkaManagement(ctx.system).start() ClusterBootstrap(ctx.system).start() val cluster = Cluster(ctx.system) cluster.subscriptions ! Subscribe(ctx.self, classOf[SelfUp]) val topic = ReadSideTopic.init(ctx) if (cluster.selfMember.hasRole("read")) { val session = CassandraSessionRegistry(ctx.system).sessionFor("akka.persistence.cassandra") val offsetTableStmt = """ CREATE TABLE IF NOT EXISTS akka.offsetStore ( eventProcessorId text, tag text, timeUuidOffset timeuuid, PRIMARY KEY (eventProcessorId, tag) ) """ Await.ready(session.executeDDL(offsetTableStmt), 30.seconds) } Behaviors.receiveMessage { case SelfUp(state) => ctx.log.infoN( "Cluster member joined. Initializing persistent actors. Roles {}. Members {}", cluster.selfMember.roles, state.members) val ref = ConfigurablePersistentActor.init(writeSettings, ctx.system) if (cluster.selfMember.hasRole("read")) { ctx.spawnAnonymous(Reporter(topic)) } ReadSide(ctx.system, topic, readSettings) if (cluster.selfMember.hasRole("load")) { ctx.log.info("Starting load generation") val load = ctx.spawn(LoadGenerator(loadSettings, ref), "load-generator") load ! Start(10.seconds) } Behaviors.empty } }, "apc-example") } }
Example 13
Source File: DemoApp.scala From sbt-reactive-app with Apache License 2.0 | 5 votes |
package foo import akka.actor.{ Actor, ActorLogging, ActorSystem, Props } import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.{ Cluster, ClusterEvent } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.AkkaManagement import akka.management.cluster.bootstrap.ClusterBootstrap import akka.stream.ActorMaterializer object DemoApp extends App { implicit val system = ActorSystem("Appka") import system.log implicit val mat = ActorMaterializer() val cluster = Cluster(system) log.info(s"Started [$system], cluster.selfAddress = ${cluster.selfAddress}") log.info("something2") //#start-akka-management AkkaManagement(system).start() //#start-akka-management ClusterBootstrap(system).start() cluster.subscribe( system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent]) // add real app routes here val routes = path("hello") { get { complete( HttpEntity( ContentTypes.`text/html(UTF-8)`, "<h1>Hello</h1>")) } } Http().bindAndHandle(routes, "0.0.0.0", 8080) Cluster(system).registerOnMemberUp({ log.info("Cluster member is up!") }) } class ClusterWatcher extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive = { case msg ⇒ log.info(s"Cluster ${cluster.selfAddress} >>> " + msg) } }
Example 14
Source File: Main.scala From ForestFlow with Apache License 2.0 | 5 votes |
package ai.forestflow.event.subscribers import java.net.InetAddress import akka.Done import akka.actor.ActorSystem import akka.actor.CoordinatedShutdown.PhaseBeforeActorSystemTerminate import akka.cluster.Cluster import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import com.typesafe.config.Config import com.typesafe.scalalogging.StrictLogging import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success, Try} object Main extends StrictLogging { def main(args: Array[String]): Unit = { import ai.forestflow.startup.ActorSystemStartup._ preStartup(typeSafeConfig) logger.info(s"Started system: [$system], cluster.selfAddress = ${cluster.selfAddress}") shutdown.addTask(PhaseBeforeActorSystemTerminate, "main.cleanup") { () => cleanup(typeSafeConfig) } bootstrapCluster(system, cluster) logger.info(s"Sharding lease owner for this node will be set to: ${cluster.selfAddress.hostPort}") // Start application after self member joined the cluster (Up) cluster.registerOnMemberUp({ logger.info(s"Cluster Member is up: ${cluster.selfMember.toString()}") postStartup }) } private def bootstrapCluster(system: ActorSystem, cluster: Cluster): Unit = { // Akka Management hosts the HTTP routes used by bootstrap AkkaManagement(system).start() // Starting the bootstrap process needs to be done explicitly ClusterBootstrap(system).start() system.log.info(s"Akka Management hostname from InetAddress.getLocalHost.getHostAddress is: ${InetAddress.getLocalHost.getHostAddress}") } private def preStartup(config: Config): Unit = { } private def postStartup(implicit system: ActorSystem, config: Config): Unit = { // Kafka Prediction Logger setup import system.log val basic_topic = Try(config.getString("application.kafka-prediction-logger.basic-topic")).toOption val gp_topic = Try(config.getString("application.kafka-prediction-logger.graphpipe-topic")).toOption if (basic_topic.isDefined || gp_topic.isDefined){ log.info(s"Setting up Kafka prediction logging with basic_topic: $basic_topic graphpipe_topic: $gp_topic") val predictionLogger = system.actorOf(PredictionLogger.props(basic_topic, gp_topic)) } } private def cleanup(config: Config)(implicit executionContext: ExecutionContext) = Future { Done } }
Example 15
Source File: DemoApp.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import akka.actor.{ Actor, ActorLogging, ActorSystem, Props } import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.{ Cluster, ClusterEvent } import akka.http.scaladsl.Http import akka.management.scaladsl.AkkaManagement import akka.management.cluster.bootstrap.ClusterBootstrap import akka.stream.ActorMaterializer import akka.stream.scaladsl.Sink import akka.stream.scaladsl.Source import com.typesafe.config.ConfigFactory object DemoApp extends App { implicit val system = ActorSystem("simple") import system.log import system.dispatcher implicit val mat = ActorMaterializer() val cluster = Cluster(system) log.info("Started [{}], cluster.selfAddress = {}", system, cluster.selfAddress) AkkaManagement(system).start() ClusterBootstrap(system).start() cluster .subscribe(system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent]) import akka.http.scaladsl.server.Directives._ Http().bindAndHandle(complete("Hello world"), "0.0.0.0", 8080) } class ClusterWatcher extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive = { case msg => log.info("Cluster {} >>> {}", msg, cluster.selfAddress) } }
Example 16
Source File: EcsApiDemoApp.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import java.net.InetAddress import akka.actor.ActorSystem import akka.discovery.awsapi.ecs.AsyncEcsDiscovery import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import com.typesafe.config.ConfigFactory object EcsApiDemoApp { def main(args: Array[String]): Unit = { val privateAddress = getPrivateAddressOrExit val config = ConfigFactory .systemProperties() .withFallback( ConfigFactory.parseString(s""" |akka { | actor.provider = "cluster" | management { | cluster.bootstrap.contact-point.fallback-port = 8558 | http.hostname = "${privateAddress.getHostAddress}" | } | discovery.method = aws-api-ecs-async | remote.netty.tcp.hostname = "${privateAddress.getHostAddress}" |} """.stripMargin) ) val system = ActorSystem("ecsBootstrapDemoApp", config) AkkaManagement(system).start() ClusterBootstrap(system).start() } private[this] def getPrivateAddressOrExit: InetAddress = AsyncEcsDiscovery.getContainerAddress match { case Left(error) => System.err.println(s"$error Halting.") sys.exit(1) case Right(value) => value } }
Example 17
Source File: ClusterApp.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import akka.actor.{ Actor, ActorLogging, ActorSystem, PoisonPill, Props } import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.singleton.{ ClusterSingletonManager, ClusterSingletonManagerSettings } import akka.cluster.{ Cluster, ClusterEvent } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.stream.ActorMaterializer object ClusterApp { def main(args: Array[String]): Unit = { implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() implicit val executionContext = system.dispatcher val cluster = Cluster(system) system.log.info("Starting Akka Management") AkkaManagement(system).start() ClusterBootstrap(system).start() system.actorOf( ClusterSingletonManager.props( Props[NoisySingleton], PoisonPill, ClusterSingletonManagerSettings(system) ) ) Cluster(system).subscribe( system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent] ) // add real app routes here val routes = path("hello") { get { complete( HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Hello</h1>") ) } } Http().bindAndHandle(routes, "0.0.0.0", 8080) system.log.info( s"Server online at http://localhost:8080/\nPress RETURN to stop..." ) cluster.registerOnMemberUp(() => { system.log.info("Cluster member is up!") }) } class ClusterWatcher extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive = { case msg => log.info(s"Cluster ${cluster.selfAddress} >>> " + msg) } } }
Example 18
Source File: MarathonApiDockerDemoApp.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import akka.actor.ActorSystem import akka.cluster.{ Cluster, MemberStatus } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import akka.stream.ActorMaterializer object MarathonApiDockerDemoApp extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() val cluster = Cluster(system) def isReady() = { val selfNow = cluster.selfMember selfNow.status == MemberStatus.Up } def isHealthy() = { isReady() } val route = concat( path("ping")(complete("pong!")), path("healthy")(complete(if (isHealthy()) StatusCodes.OK else StatusCodes.ServiceUnavailable)), path("ready")(complete(if (isReady()) StatusCodes.OK else StatusCodes.ServiceUnavailable)) ) AkkaManagement(system).start() ClusterBootstrap(system).start() Http().bindAndHandle( route, sys.env.get("HOST").getOrElse("127.0.0.1"), sys.env.get("PORT_HTTP").map(_.toInt).getOrElse(8080)) }
Example 19
Source File: DemoApp.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import akka.actor.{ Actor, ActorLogging, ActorSystem, Props } import akka.cluster.ClusterEvent.ClusterDomainEvent import akka.cluster.{ Cluster, ClusterEvent } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.cluster.bootstrap.ClusterBootstrap //#start-akka-management import akka.management.scaladsl.AkkaManagement //#start-akka-management import akka.stream.ActorMaterializer object DemoApp extends App { implicit val system = ActorSystem("Appka") import system.log implicit val mat = ActorMaterializer() val cluster = Cluster(system) log.info(s"Started [$system], cluster.selfAddress = ${cluster.selfAddress}") //#start-akka-management AkkaManagement(system).start() //#start-akka-management ClusterBootstrap(system).start() cluster.subscribe( system.actorOf(Props[ClusterWatcher]), ClusterEvent.InitialStateAsEvents, classOf[ClusterDomainEvent] ) // add real app routes here val routes = path("hello") { get { complete( HttpEntity( ContentTypes.`text/html(UTF-8)`, "<h1>Hello</h1>" ) ) } } Http().bindAndHandle(routes, "0.0.0.0", 8080) Cluster(system).registerOnMemberUp({ log.info("Cluster member is up!") }) } class ClusterWatcher extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive = { case msg => log.info(s"Cluster ${cluster.selfAddress} >>> " + msg) } }
Example 20
Source File: DemoApp.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import akka.actor.ActorSystem import akka.cluster.{ Cluster, MemberStatus } import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.management.scaladsl.AkkaManagement import akka.management.cluster.bootstrap.ClusterBootstrap import akka.stream.ActorMaterializer object DemoApp extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() val cluster = Cluster(system) def isReady() = { val selfNow = cluster.selfMember selfNow.status == MemberStatus.Up } def isHealthy() = { isReady() } val route = concat( path("ping")(complete("pong!")), path("healthy")(complete(if (isHealthy()) StatusCodes.OK else StatusCodes.ServiceUnavailable)), path("ready")(complete(if (isReady()) StatusCodes.OK else StatusCodes.ServiceUnavailable))) AkkaManagement(system).start() ClusterBootstrap(system).start() Http().bindAndHandle( route, sys.env.get("HOST").getOrElse("127.0.0.1"), sys.env.get("PORT_HTTP").map(_.toInt).getOrElse(8080)) }
Example 21
Source File: Main.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.cluster.bootstrap import akka.actor.ActorSystem import akka.cluster.Cluster import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement import com.typesafe.config.{ Config, ConfigFactory } //#main object Node1 extends App { new Main(1) } object Node2 extends App { new Main(2) } object Node3 extends App { new Main(3) } class Main(nr: Int) { val config: Config = ConfigFactory.parseString(s""" akka.remote.artery.canonical.hostname = "127.0.0.$nr" akka.management.http.hostname = "127.0.0.$nr" """).withFallback(ConfigFactory.load()) val system = ActorSystem("local-cluster", config) AkkaManagement(system).start() ClusterBootstrap(system).start() Cluster(system).registerOnMemberUp({ system.log.info("Cluster is up!") }) } //#main
Example 22
Source File: ClusterStatusTrackerMain.scala From Pi-Akka-Cluster with Apache License 2.0 | 5 votes |
package akkapi.cluster import akka.NotUsed import akka.actor.typed.scaladsl.adapter.TypedActorSystemOps import akka.actor.typed.scaladsl.{ActorContext, Behaviors} import akka.actor.typed.{ActorSystem, Behavior, Terminated} import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement object Main { def apply(settings: Settings): Behavior[NotUsed] = Behaviors.setup { context => val ledStripDriver = context.spawn(LedStripDriver(settings), "led-strip-driver") val ledStripController = context.spawn(LedStripVisualiser(settings, ledStripDriver), "led-strip-controller") val clusterStatusTracker = context.spawn( ClusterStatusTracker( settings, Some(contextToClusterSingleton(settings)) ), "cluster-status-tracker" ) clusterStatusTracker ! ClusterStatusTracker.SubscribeVisualiser(ledStripController) Behaviors.receiveSignal { case (_, Terminated(_)) => Behaviors.stopped } } private def contextToClusterSingleton(settings: Settings): ActorContextToSingletonBehavior = (context: ActorContext[ClusterStatusTracker.ClusterEvent]) => PiClusterSingleton(settings, context.self) type ActorContextToSingletonBehavior = ActorContext[ClusterStatusTracker.ClusterEvent] => Behavior[PiClusterSingleton.Command] } object ClusterStatusTrackerMain { def main(args: Array[String]): Unit = { System.loadLibrary("rpi_ws281x") val settings = Settings() val config = settings.config val system = ActorSystem[NotUsed](Main(settings), settings.actorSystemName, config) // Start Akka HTTP Management extension AkkaManagement(system.toClassic).start() ClusterBootstrap(system.toClassic).start() } }
Example 23
Source File: ClusterStatusTrackerMain.scala From Pi-Akka-Cluster with Apache License 2.0 | 5 votes |
package akkapi.cluster import akka.NotUsed import akka.actor.typed.scaladsl.adapter.TypedActorSystemOps import akka.actor.typed.scaladsl.{ActorContext, Behaviors} import akka.actor.typed.{ActorSystem, Behavior, Terminated} import akka.management.cluster.bootstrap.ClusterBootstrap import akka.management.scaladsl.AkkaManagement object Main { def apply(settings: Settings): Behavior[NotUsed] = Behaviors.setup { context => val ledStripDriver = context.spawn(LedStripDriver(settings), "led-strip-driver") val ledStripController = context.spawn(LedStripVisualiser(settings, ledStripDriver), "led-strip-controller") val clusterStatusTracker = context.spawn( ClusterStatusTracker( settings, Some(contextToClusterSingleton(settings)) ), "cluster-status-tracker" ) clusterStatusTracker ! ClusterStatusTracker.SubscribeVisualiser(ledStripController) Behaviors.receiveSignal { case (_, Terminated(_)) => Behaviors.stopped } } private def contextToClusterSingleton(settings: Settings): ActorContextToSingletonBehavior = (context: ActorContext[ClusterStatusTracker.ClusterEvent]) => PiClusterSingleton(settings, context.self) type ActorContextToSingletonBehavior = ActorContext[ClusterStatusTracker.ClusterEvent] => Behavior[PiClusterSingleton.Command] } object ClusterStatusTrackerMain { def main(args: Array[String]): Unit = { System.loadLibrary("rpi_ws281x") val settings = Settings() val config = settings.config val system = ActorSystem[NotUsed](Main(settings), settings.actorSystemName, config) // Start Akka HTTP Management extension AkkaManagement(system.toClassic).start() ClusterBootstrap(system.toClassic).start() } }