Preface
In the previous two weeks mainly learned some of the module knowledge in HDFs, many of which are more or less we learn from the place, now turn to another block, known as MRV2, yarn, in yarn, solve the problem of Mr Jobtracker single point, Splitting this up into structures like ResourceManager and NodeManager, on each node, there is also a applicationmaster to manage the entire lifecycle of the application, and indeed there are many good designs in yarn, and today, My main share is this applicationmaster-related set of services, which is part of Resouremanager's internal service. Knowing the startup mechanism of AM, you will learn more about Yarn's task initiation process.
applicationmaster management involves classes
Applicationmaster management involves 4 major categories, Applicationmasterlauncher,amlivelinessmonitor,applicationmasterservice, and applicationmaster itself class. Here's what these classes are for, and in yarn, each class has its own distinct function module.
1.applicationmasterlauncher--called AM to start the Shutdown event handler, he is both a service and a processor, and in this class, only 2 types of events, launch and cleanup events are processed. Corresponding to the case where the app was launched and closed.
2.amlivelinessmonitor--This class from the name can be seen that he is the monitoring class, monitoring the object is AM survival of the monitoring class, the detection method and the previous HDFs, are in the way of heartbeat, if a node expires, will trigger an expiration event.
3.applicationmasterservice--am request Service processing class. AMS exists in ResourceManager, where the service object is applicationmaster on each node and is responsible for receiving the registration requests of each AM. Update the heartbeat package information, and more.
4.applicationmaster--node Application management class, simply put, Applicationmaster is responsible for managing the entire application lifecycle.
A brief description of the I management of the relevant classes, the following from the source level analysis of several processes.
am Start
To allow am to start, the background of course is when a user submits a new application, then Applicationmasterlauncher generates launch events, communicates with the corresponding NodeManager, Make it ready to start the container of the new AM. Here, the Applicationmasterlauncher class is used, as mentioned earlier in this category, which deals with 2 types of events, launch start and cleanup cleaning events, Let's take a look at the basic variable settings for this class
//application Application event Processor public class Applicationmasterlauncher extends Abstractservice Implements eventhandler<amlauncherevent> {private static final log log = Logfactory.getlog (applicationmas Terlauncher.class); Private final Threadpoolexecutor Launcherpool; Private Launcherthread Launcherhandlingthread; Event Queue Private Final blockingqueue<runnable> masterevents = new linkedblockingqueue<runnable> (); Explorer Context protected final Rmcontext context; Public Applicationmasterlauncher (Rmcontext context) {super (ApplicationMasterLauncher.class.getName ()); This.context = context; Initialize thread pool This.launcherpool = new Threadpoolexecutor (1, timeunit.hours, new Linkedblockingqueue<runna Ble> ()); New processing Thread this.launcherhandlingthread = new Launcherthread (); }
It is relatively simple, there is a Masterevents event queue, and there is an execution thread as well as the required thread pool execution environment. In RM-related services, basic is inherited from Abstractservice, the abstract service class. Applicationmasterlauncher mainly deal with 2 types of events, which are shown below
@Override public synchronized void handle (amlauncherevent appevent) { Amlaunchereventtype event = Appevent.gettype (); Rmappattempt application = Appevent.getappattempt (); Processing requests from Applicationmaster, divided into boot events and cleaning Events 2 switch (event) {case LAUNCH: LAUNCH (application); break; Case CLEANUP: CLEANUP (application); Default: Break ; } }
Then call the concrete implementation method to start the event launch event as an example
Add App launch event private void Launch (Rmappattempt application) { Runnable launcher = Createrunnablelauncher ( Application, amlaunchereventtype.launch); Add the Start event to the event queue Masterevents.add (launcher); }
How are these events processed after they are added to the event queue and executed in a separate thread, in the form of a message queue?
The execution thread implements the private class Launcherthread extends thread {public launcherthread () { super ("Applicationmaster Launcher "); } @Override public Void Run () { while (!this.isinterrupted ()) { Runnable tolaunch; try { //Execute method to remove events from the event queue Tolaunch = Masterevents.take (); Put into the thread pool for execution Launcherpool.execute (tolaunch); } catch (Interruptedexception e) { Log.warn ( This.getclass (). GetName () + "interrupted. Returning. "); return;}}}
If the concrete implementation of the event, it depends on how the specific amlauch is executed, Amlauch itself is a runnable instance.
/** * The launch of the AM itself. * Application Event Actuator */public class Amlauncher implements Runnable { private static final log log = Logfactory.getlog (AM Launcher.class); Private Containermanagementprotocol Containermgrproxy; Private final rmappattempt application; Private final Configuration conf; Private final Amlaunchereventtype EventType; Private final Rmcontext Rmcontext; Private final Container Mastercontainer;
The main run method is as follows: Differentiate by event type
@SuppressWarnings ("unchecked") public Void Run () { //amlauncher 2 events handle switch (eventtype) {case LAUNCH: try { log.info ("Launching Master" + Application.getappattemptid ()); Call Start Method launch (); Handler.handle (New Rmappattemptevent (Application.getappattemptid (), rmappattempteventtype.launched)); ... break; Case CLEANUP: try { log.info ("Cleaning master" + application.getappattemptid ()); Call Job Cleaning method Cleanup (); ... break; Default: Log.warn ("Received unknown Event-type" + EventType + ". Ignoring. "); break; } }
The subsequent launch operation invokes the RPC function to initiate container with the remote NodeManager communication. Then to the Applicationmaster run () Start method, in the startup method, the application registration method,
@SuppressWarnings ({"Unchecked"}) public Boolean run () throws Yarnexception, IOException {log.info ("starting Applica Tionmaster "); Credentials Credentials = Usergroupinformation.getcurrentuser (). Getcredentials (); Dataoutputbuffer dob = new Dataoutputbuffer (); Credentials.writetokenstoragetostream (DOB); Now remove the AM->RM tokens so that containers cannot access it. Iterator<token<?>> iter = Credentials.getalltokens (). Iterator (); while (Iter.hasnext ()) {token<?> Token = Iter.next (); if (Token.getkind (). Equals (Amrmtokenidentifier.kind_name)) {iter.remove (); }} alltokens = Bytebuffer.wrap (Dob.getdata (), 0, Dob.getlength ()); Communication with ResourceManager, periodically sends heartbeat information, contains the latest information of the application Amrmclientasync.callbackhandler Alloclistener = new Rmcallbackhandler (); Amrmclient = Amrmclientasync.createamrmclientasync (+, Alloclistener); Amrmclient.init (conf); Amrmclient.start (); ...//Register self with ResouRcemanager//This'll start heartbeating to the RM//start after the AM registration Appmasterhostname = Netutils.gethostname (); Registerapplicationmasterresponse response = amrmclient. Registerapplicationmaster (Appmasterhostname, appMasterRp Cport, Appmastertrackingurl); Dump out information on cluster capability as seen by the//resource Manager int maxMem = Response.getmaximum Resourcecapability (). GetMemory (); Log.info ("Max mem capabililty of resources in this cluster" + maxMem); A resource ask cannot exceed the max. if (Containermemory > MaxMem) {log.info ("Container memory specified above Max threshold of cluster." + "Using max value." + ", specified=" + Containermemory + ", max=" + maxMem); Containermemory = MaxMem; }In this operation, you will register yourself in the Amlivelinessmonitor and start the heartbeat monitoring now.
amlivelinessmonitor Monitoring
In this case, shift the center of gravity from Applicationmaster to Amlivelinessmonitor, first this is an active monitoring thread, and such threads all have a common parent class
Apply a live state monitoring thread public class Amlivelinessmonitor extends Abstractlivelinessmonitor<applicationattemptid> {
A class of characteristics and methods for defining monitoring class threads in Abstractlinessmonitor
Process survival status Monitoring class public abstract class Abstractlivelinessmonitor<o> extends Abstractservice { private static final Log log = Logfactory.getlog (Abstractlivelinessmonitor.class); Thread which runs periodically to see the last time since a heartbeat is //received. Check threads private thread checkerthread; Private volatile Boolean stopped; Default time-out 5 minutes public static final int default_expire = 5*60*1000;//5 mins //timeout time private int expireinterval = D Efault_expire; Monitor interval detection time, 1/3 private int monitorinterval = EXPIREINTERVAL/3 for timeout period; private final clock clock; The results of the heartbeat test were recorded private Map<o, long> running = new Hashmap<o, long> ();
Heartbeat detection itself is very simple, do a communication record check, and then update, record time, when a new node to join monitoring or de-monitoring operation
New node registered heartbeat monitor public synchronized void Register (O ob) { running.put (ob, Clock.gettime ()); } Node remove heartbeat monitor public synchronized void unregister (O ob) { running.remove (OB); }
Each time you do a heartbeat cycle detection, call the following method
Update heartbeat monitoring detection latest time public synchronized void receivedping (O ob) { //only put for the registered objects if (runnin G.containskey (ob)) { running.put (ob, Clock.gettime ()); } }
A very simple Update method, O OB object here varies by scene, in am monitoring, for ApplicationID app ID. It will be seen in the subsequent interactions between AMS and am. After the new application is added to the Amlivelinessmonitor monitoring, the main operation behind it is the interaction between AMS and am.
am vs. AMS
After the Applicationmaster is running, the heartbeat information is periodically sent to the Applicationmasterservice, and the heartbeat information contains a lot of resource description information.
Applicationmaster Heartbeat Information Update @Override public allocateresponse Allocate (allocaterequest request) throws Yarnexception, IOException { Applicationattemptid Appattemptid = AuthorizeRequest (); The time of Heartbeat information update this.amLivelinessMonitor.receivedPing (appattemptid); ....
The latest monitoring time is updated with each heartbeat message. There are also methods for registering applications in AMS
Applicationmaster Application Registration @Override public on Applicationmasterservice service Registerapplicationmasterresponse Registerapplicationmaster ( registerapplicationmasterrequest request) throws Yarnexception, ioexception { Applicationattemptid Applicationattemptid = AuthorizeRequest (); ApplicationID AppID = Applicationattemptid.getapplicationid (); ..... Heartbeat recording on the live monitoring thread, update detection time, key for app ID this.amLivelinessMonitor.receivedPing (applicationattemptid); Rmapp app = This.rmContext.getRMApps (). get (AppID); Setting the response ID to 0 to identify if the //Application master are register for the respective ATTEMPTID
lastresponse.setresponseid (0); Responsemap.put (Applicationattemptid, lastresponse); Log.info ("AM registration" + applicationattemptid); This.rmcontext
If an expiration occurs in the heartbeat monitor, a expire event is triggered, and in Amlivelinessmonitor, this part of the work is given to Checkthread.
Process survival status Monitoring class public abstract class Abstractlivelinessmonitor<o> extends Abstractservice {...//thread which runs PE Riodically to see the last time since a heartbeat is//received. Check threads private thread checkerthread; ....//default timeout 5 minutes public static final int default_expire = 5*60*1000;//5 mins//timeout time private int expireinterval = Defau Lt_expire; Monitor interval detection time, 1/3 private int monitorinterval = EXPIREINTERVAL/3 for timeout period; ....//Saved a heartbeat test results recorded by private map<o, long> running = new Hashmap<o, long> (); Private class Pingchecker implements Runnable {@Override public void run () {while (!stopped &&!) Thread.CurrentThread (). isinterrupted ()) {synchronized (abstractlivelinessmonitor.this) {Iterator<map. Entry<o, long>> iterator = Running.entryset (). iterator (); Avoid calculating current time everytime in loop long currenttime = Clock.gettime (); while (Iterator.hasnext ()) {Map.entry<o, long> Entry = Iterator.next (); Perform timeout detection if (CurrentTime > Entry.getvalue () + expireinterval) {iterator.remove (); Call the time-out processing method, the processing event is referred to the scheduler processing expire (Entry.getkey ()); Log.info ("Expired:" + Entry.getkey (). toString () + "Timed out after" + expireinterval/1000 + "secs "); } } }The main event of a check thread is to traverse the latest heartbeat update time for each node, to determine whether the difference is expired, and to call the expire method. This method is implemented by its subclasses
Apply a live state monitoring thread public class Amlivelinessmonitor extends abstractlivelinessmonitor<applicationattemptid> { // Central Dispatch processor private EventHandler dispatcher; ... @Override protected void expire (Applicationattemptid ID) { //Once the application expires, the processor processes the expired event processing dispatcher.handle ( new Rmappattemptevent (ID, Rmappattempteventtype.expire));} }
Generates an application overdue event, which is then sent to the central scheduler for processing. The reason for this is that in RM, all modules are designed to operate in an event-driven manner, maximizing decoupling between the various modules. Different modules are transformed into different states through different events, which can be understood as state machine changes. Finally, a simple display of the AM module related to the calling process is presented in a single book.
All Code Analysis Please click on the link Https://github.com/linyiqun/hadoop-yarn, follow up will continue to update yarn other aspects of code analysis.
Reference Documents
"Internal –HDFS structure design and implementation principles of Hadoop technology". Cai Bin, etc.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Yarn Source Analysis (a)-----applicationmaster