Share
Embed
Introduzione a Akka.net
Introduzione ad Actor Model e Akka.net in collaborazione con Alessandro Melchiori
Andrea Ceroni
November 16, 2017
Transcript
59 slides
-
Introduzione a Akka.net Andrea Ceroni [email protected] @andrekiba6 Sponsored by 8
giugno 2017 Relatori Alessandro Melchiori [email protected] @amelchiori -
Argomenti Actor Model Akka.net actor Ref, actor Selection, actor path,
actor lifecycle messaggi switchable behavior supervision hierarchy use cases 1 -
Shared state and concurrency 4 • Synchronizing shared state •
Coordinating work among threads • Use synchronization mechanisms • Debugging...WTF ? • ... -
5 Actor Model The actor model in computer science is
a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received. https://en.wikipedia.org/wiki/Actor_model -
6 Actor Model The actor model in computer science is
a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received. https://en.wikipedia.org/wiki/Actor_model -
8 Alan Key and OOP «... I thought of objects
being like biological cells and/or individual computers on a network, only able to communicate with messages (so messaging came at the very beginning -- it took a while to see how to do messaging in a programming language efficiently enough to be useful).» «... OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.» http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en -
9 Alan Key and OOP «... I thought of objects
being like biological cells and/or individual computers on a network, only able to communicate with messages (so messaging came at the very beginning -- it took a while to see how to do messaging in a programming language efficiently enough to be useful).» «... OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.» http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en -
Implementations 10 • Erlang • Akka (Scala, Java) • Orleans
• Akka.net • Reliable Actors (Azure Service Fabric) -
Reactive Manifesto Responsive Message Driven Resilient Elastic Asynchronous message passing
Loose coupling Location transparency Consistent response times Respond in timely fashion Varying workloads React to workload changes Scalable Failures contained Isolation of components Recovery -
• High level abstractions (actors, messages, FSMs) • Asynchronous Simple
Concurrency • Location transparency • Remote deployment using configuration High Performance • ~50 million messages per second per machine • 1GB heap memory = ~2.5 million actors • Load balancing / routing Resilient • Self-healing • Supervisory hierarchies and fault isolation Simple Distribution Akka.net features -
Actors “Everything is an Actor” esegue un compito solo, ben
definito dividere il lavoro da svolgere in task più piccoli ogni actor ha un indirizzo gli actor comunicano tramite messaggi un actor è lazy, fino a quando non riceve un messaggio rimane dormiente -
Cosa può fare un actor crearealtri actors riceveremessaggi mandare messaggi
cambiarecomportamento per il messaggio successivo Actor 12 -
il comportamento può cambiare in base al messaggio ricevuto i
messaggi vengono accodati per essere processati l’actor ha uno stato interno che non condivide con nessuno un actor può avere dei figli di cui è responsabile strategia per gestire problemi sui figli (eccezioni) Actor Incoming message mailbox Behaviour State 0,1,...n Children Supervisory Strategy 13 -
Actor References Actor1 Child Actor ActorRef Parent Child Actor2 Child
Actor ActorRef ActorRef ActorRef ActorRef Self 14 -
Perchè ActorRef • protegge l’actor dall’esterno, nessuno può modificare lo
stato dell’actor (se non l’actor stesso in seguito all’arrivo di un messaggio) • garantiscono completa trasparenza sul deploy (ad esempio su un host remoto) • svincolano l’istanza vera e propria dell’actor che può essere così sostituita (restart) senza bisogno di dover aggiornare tutte le referenze 15 -
Come si ottiene ActorRef create new actor ActorOf() lookup existing
actor ActorSelection() 16 -
Actor System User Guardian System Guardian Root Guardian top level
root actor User Hierarchy System Hierarchy parent supervisor for system actors parent supervisor for users actors Actor System 17 -
Actor path Root Guardian / /user/PlayerControllerActor /user User Guardian PlayerControllerActor
“Andre6” /user/PlayerControllerActor/Andre6 18 -
Actor path Protocol single process o inter-process transport protocol ActorSystemName
nome dell’actor system Address indirizzo IP remoto e porta dell’actor system HierarchyPath path dell’actor nella gerarchia akka://AkkaGame/user/PlayerControllerActor/Andre6 akka.tcp://[email protected]:9002/user/PlayerControllerActor/Andre6 19 -
Actor selection Actor ActorRef Actor Tell(message) Actor ActorSelection Actor Tell(message)
actorSystem.ActorSelection(“akka://AkkaGame/user/...”) Context.ActorSelection(“/../../TestActor”) 20 -
“A message is an item of data that is sent
to a specific destination… In a message-driven system addressable recipients await the arrival of messagesand react to them, otherwise lying dormant.” The Reactive Manifesto -
Messaggi • Un actor processa un messaggio alla volta! •
POCO class (serializzabili) • immutabili (thread-safe) • Tell, Ask, Forward 21 -
Come invio un messaggio Tell • dico qualcosa ad un
altro actor • “fire & forget” • non mi aspetto risposta • non rimango bloccato in attesa • scala meglio e più facilmente • molto utilizzato Ask • chiedo qualcosa ad un altro actor • mi aspetto una risposta • l’altro actor deve rispondermi • timeout (TaskCancelledException) • scala più difficilmente • utilizzato solo se necessario 22 -
Actor Systems Actor System Instance Another Actor System Instance Actor
Actor Actor Actor Actor Actor Actor Actor Actor Actor Message Message Local Remote 23 -
Location Transparency The ability to send a message to another
actor without needing to know where it is; whether it be in the same actor systeminstance on the same computer, or another actor systeminstance on the other side of the world. -
Props Ricetta per costruire un particolare tipo di attore. Una
Prop contiene le informazioni necessarie all’actor system per creare correttamente l’istanza. Ad esempio gli argomenti da passare al costruttore e dove deve essere deployato l’actor. -
Actor instantiation definire “Props” pensare ad un nome creare l’istanza
usando Props e il nome N.B. • usare sempre i metodi delle factory di Akka.net per creare props e actors • non usare mai la new -
Actor lifecycle Receiving messages Starting Restarting Stopping Terminated riceve e
processa messaggi viene creato nell’actor system morto, non può essere restartato clean up sta per ritornare in starting PreStart() PostStop() PreRestart() PostStop() PostRestart() 24 -
Actor lifecycle methods PreStart() • chiamato prima che l’actor riceva
il suo primo messaggio • si usa per inizializzare l’actor e renderlo pronto al primo messaggio PostStop() • chiamato dopo che l’actor è stato stoppato e la sua coda disabilitata • ogni messaggio mandato all’actor dopo questo evento finirà nella deadLetters dell’actor system • custom cleanup • rilasciare le risorse di sistema -
Actor lifecycle methods PreRestart() • chiamato prima che l’actor venga
restartato sulla vecchia istanza • è possibile fare qualcosa con il messaggio/eccezione corrente (se c’è perchè l’actor potrebbe venire restartato anche a causa di un problema in uno dei fratelli ad esempio...) • ad esempio salvare il messaggio corrente per riprocessarlo dopo • di default stoppa tutti gli eventuali figli e chiama postStop() PostRestart() • chiamato dopo PreRestart() sulla nuova istanza • di default chiama PreStart() quindi è possibile farne l’override per non richiamarlo • è possibile fare qualcosa con l’eventuale eccezione che ha causato il restart • logging -
Lifecycle methods N.B. Il restart di un actor semplicemente sostituisce
la sua istanza con una nuova, ma actorRef (path + UID) non viene cambiata. Il contenuto della mailbox non viene modificato (può continuare a ricevere messaggi durante il restart) e continuerà ad essere processata dopo il restart 25 -
Switchable behavior Actor Behavior A Behavior B Behavior C Message
1 Message 2 Message 3 Current behavior N.B. il nuovo behavior si applica al messaggio successivo! 26 -
Switchable behavior API switcha direttamente al behavior specificato • il
metodo Become() switcha al nuovo behavior • il behavior precedente non viene ricordato utilizza uno stack per ricordare i precedenti • il metodo BecomeStacked() switcha al nuovo behavior e pusha nella stack quello precedente • il metodo UnbecomeStacked() estrate dallo stack il behavior precedente e switcha -
Actor Supervision Hierarchy “Supervision hierarchies allow the system to not
only deal with faults but become self-healing” -
Actor Supervision Hierarchy Actor Actor Actor Actor User Guardia n
actorSystem.ActorOf() Context.ActorOf() 27 -
Actor Supervision Hierarchy Actor System Instance Actor 2 Actor 5
Actor 3 Actor 4 Actor 1 Actor1 decide come rispondere, ad esempio con Restart Actor2 solleva eccezione l’azione viene propagata nella gerarchia Actor2 e figli vengono sospesi 28 -
Resume Resume • l’eccezione viene ignorata • lo stato dell’actor
viene mantenuto • viene fatto il resume anche di eventuali figli dell’actor 30 -
Restart • lo stato dell’actor viene perduto • viene eseguito
il restart anche di tutti i figli • è la strategia di default • i messaggi in mailbox rimangono Restart 31 -
Stop • l’actor viene terminato definitivamente • anche tutti i
figli vengono terminati Stop 32 -
Escalate • l’actor padre non sa come gestire l’eccezione e
scala a sua volta a livello superiore della gerarchia • l’actor padre viene sospeso a sua volta • anche tutti i figli dell’actor padre vengono sospesi Escalate 33 -
Supervision Strategy Supervision Strategy child actor exception Directive (Resume, Restart...)
Max exceptions in time period Stop -
OneForOne Strategy Actor Actor Actor Actor la direttiva (Resume, Restart...)
viene applicata al solo figlio che ha sollevato eccezione 34 -
AllForOne Strategy Actor Actor Actor Actor la direttiva (Resume, Restart...)
viene applicata anche a tutti i fratelli dell’actor che ha sollevato eccezione 35 -
Let it crash Parent Child • Un actor tende a
proteggere il proprio stato delegando il lavoro ai suoi figli • un task rischioso viene spinto sempre più a basso nella gerarchia (Error Kernel) • il figlio svolge il lavoro, nella peggiore delle ipotesi viene restartato dal padre 36 -
Stop Actors • ActorSystem.Terminate() stoppa l’intero actor system a partire
da user guardian (e tutti i figli) e poi system guardian • ActorSystem.Stop(actorRef) stoppa un actor specifico • un figlio può essere stoppato automaticamente dal padre in caso di eccezione • un figlio può essere stoppato manualmente tramite Context.Stop(actorRef) • è possibile mandare il messaggio PoisonPill actorRef.Tell(PoisonPill.Instance) • lo stop avviene in asincrono -
Akka.net Nuget packages Akka Akka.Persistence.* Akka.DI.* Akka.Cluster Akka.Remote Akka.Logger.* Logging
support (NLog, Serilog, etc.) Supports persistent actors DI support (Unity, AutoFac...) Clustering support Remote actors support 37