PerfectHadoop: YARN Resource Manager

April 10, 2017 · View on GitHub

This project provides a Swift wrapper of YARN Resource Manager REST API:

  • YARNResourceManager(): access to cluster information of YARN, including cluster and its metrics, scheduler, application submit, etc.

Connect to YARN Resource Manager

To connect to your Hadoop YARN Resource Manager by Perfect, initialize a YARNResourceManager() object with sufficient parameters:

// this connection could possibly do some basic operations
let yarn = YARNResourceManager(host: "yarn.somehadoopdomain.com", port: 8088)

or connect to Hadoop YARN Node Manager with a valid user name:

// add user name if need
let yarn = YARNResourceManager(host: "yarn.somehadoopdomain.com", port: 8088, user: "your user name")

Authentication

If using Kerberos to authenticate, please try codes below:

// set auth to kerberos
let yarn = YARNResourceManager(host: "yarn.somehadoopdomain.com", port: 8088, user: "username", auth: .krb5)

Parameters of YARNResourceManager Object

ItemData TypeDescription
serviceStringthe service protocol of web request - http / https
hostStringthe hostname or ip address of the Hadoop YARN Resource Manager
portIntthe port of yarn host, default is 8088
authAuthorization.off or .krb5. Default value is .off
proxyUserStringproxy user, if applicable
apibaseStringuse this parameter ONLY the target server has a different api routine other than /ws/v1/cluster
timeoutInttimeout in seconds, zero means never timeout during transfer

Get General Information

Call checkClusterInfo() to get the general information of a YARN Resource Manager in form of a ClusterInfo structure:

guard let i = try yarn.checkClusterInfo() else {
	print("unable to check cluster info")
	return
}//end guard
print(i.startedOn)
print(i.state)
print(i.hadoopVersion)
print(i.resourceManagerVersion)

Once called, checkClusterInfo() would return a ClusterInfo object, as described below:

ClusterInfo Object

ItemData TypeDescription
idIntThe cluster id
startedOnIntThe time the cluster started (in ms since epoch)
stateStringThe ResourceManager state - valid values are: NOTINITED, INITED, STARTED, STOPPED
haStateStringThe ResourceManager HA state - valid values are: INITIALIZING, ACTIVE, STANDBY, STOPPED
resourceManagerVersionStringVersion of the ResourceManager
resourceManagerBuildVersionStringResourceManager build string with build version, user, and checksum
resourceManagerVersionBuiltOnStringTimestamp when ResourceManager was built (in ms since epoch)
hadoopVersionStringVersion of hadoop common
hadoopBuildVersionStringHadoop common build string with build version, user, and checksum
hadoopVersionBuiltOnStringTimestamp when hadoop common was built(in ms since epoch)

Cluster Metrics

Method checkClusterMetrics() returns a detailed info structure of cluster.

guard let m = try yarn.checkClusterMetrics() else {
	// something wrong
}
print(m.availableMB)
print(m.availableVirtualCores)
print(m.allocatedVirtualCores)
print(m.totalMB)

Once called, checkClusterMetrics() would return a ClusterMetrics object as listed below:

ClusterMetrics Object

ItemData TypeDescription
appsSubmittedIntThe number of applications submitted
appsCompletedIntThe number of applications completed
appsPendingIntThe number of applications pending
appsRunningIntThe number of applications running
appsFailedIntThe number of applications failed
appsKilledIntThe number of applications killed
reservedMBIntThe amount of memory reserved in MB
availableMBIntThe amount of memory available in MB
allocatedMBIntThe amount of memory allocated in MB
totalMBIntThe amount of total memory in MB
reservedVirtualCoresIntThe number of reserved virtual cores
availableVirtualCoresIntThe number of available virtual cores
allocatedVirtualCoresIntThe number of allocated virtual cores
totalVirtualCoresIntThe total number of virtual cores
containersAllocatedIntThe number of containers allocated
containersReservedIntThe number of containers reserved
containersPendingIntThe number of containers pending
totalNodesIntThe total number of nodes
activeNodesIntThe number of active nodes
lostNodesIntThe number of lost nodes
unhealthyNodesIntThe number of unhealthy nodes
decommissionedNodesIntThe number of nodes decommissioned
rebootedNodesIntThe number of nodes rebooted

Cluster Scheduler

Method checkSchedulerInfo() returns a detailed info structure of scheduler.

guard let sch = try yarn.checkSchedulerInfo() else {
	// something wrong, must return
}
print(sch.capacity)
print(sch.maxCapacity)
print(sch.queueName)
print(sch.queues.count)

Once done, checkSchedulerInfo() would return a SchedulerInfo structure as listed below:

SchedulerInfo Object

ItemData TypeDescription
availNodeCapacityIntThe available node capacity
capacityDoubleConfigured queue capacity in percentage relative to its parent queue
maxCapacityDoubleMax capacity of the queue
maxQueueMemoryCapacityIntConfigured maximum queue capacity in percentage relative to its parent queue
minQueueMemoryCapacityIntMinimum queue memory capacity
numContainersIntThe number of containers
numNodesIntThe total number of nodes
qstateQStateState of the queue - valid values are: STOPPED, RUNNING
queueNameStringName of the queue
queues[Queue]A collection of queue resources
rootQueueFairQueueA collection of root queue resources
totalNodeCapacityIntThe total node capacity
typeStringScheduler type - capacityScheduler
usedCapacityDoubleUsed queue capacity in percentage
usedNodeCapacityIntThe used node capacity

FairQueue Object

ItemData TypeDescription
maxAppsIntThe maximum number of applications the queue can have
minResourcesResourcesUsedThe configured minimum resources that are guaranteed to the queue
maxResourcesResourcesUsedThe configured maximum resources that are allowed to the queue
usedResourcesResourcesUsedThe sum of resources allocated to containers within the queue
fairResourcesResourcesUsedThe queue’s fair share of resources
clusterResourcesResourcesUsedThe capacity of the cluster
queueNameStringThe name of the queue
schedulingPolicyStringThe name of the scheduling policy used by the queue
childQueuesFairQueueA collection of sub-queue information. Omitted if the queue has no childQueues.
typeStringtype of the queue - fairSchedulerLeafQueueInfo
numActiveAppsIntThe number of active applications in this queue
numPendingAppsIntThe number of pending applications in this queue

Queue Object

ItemData TypeDescription
absoluteCapacityDoubleAbsolute capacity percentage this queue can use of entire cluster
absoluteMaxCapacityDoubleAbsolute maximum capacity percentage this queue can use of the entire cluster
absoluteUsedCapacityDoubleAbsolute used capacity percentage this queue is using of the entire cluster
capacityDoubleConfigured queue capacity in percentage relative to its parent queue
maxActiveApplicationsIntThe maximum number of active applications this queue can have
maxActiveApplicationsPerUserIntThe maximum number of active applications per user this queue can have
maxApplicationsIntThe maximum number of applications this queue can have
maxApplicationsPerUserIntThe maximum number of applications per user this queue can have
maxCapacityDoubleConfigured maximum queue capacity in percentage relative to its parent queue
numActiveApplicationsIntThe number of active applications in this queue
numApplicationsIntThe number of applications currently in the queue
numContainersIntThe number of containers being used
numPendingApplicationsIntThe number of pending applications in this queue
queueNameStringThe name of the queue
queues[Queue]A collection of sub-queue information. Omitted if the queue has no sub-queues.
resourcesUsedResourcesUsedThe total amount of resources used by this queue
stateStringThe state of the queue
typeStringtype of the queue - capacitySchedulerLeafQueueInfo
usedCapacityDoubleUsed queue capacity in percentage
usedResourcesStringA string describing the current resources used by the queue
userLimitIntThe minimum user limit percent set in the configuration
userLimitFactorDoubleThe user limit factor set in the configuration
users[User]A collection of user objects containing resources used, see below:

User Object

ItemData TypeDescription
usernameStringThe username of the user using the resources
resourcesUsedResourcesUsedThe amount of resources used by the user in this queue, see definition below
numActiveApplicationsIntThe number of active applications for this user in this queue
numPendingApplicationsIntThe number of pending applications for this user in this queue

ResourcesUsed Object

ItemData TypeDescription
memoryintMemory required for each container
vCoresintVirtual cores required for each container

Cluster Nodes

Check All Nodes

Method checkClusterNodes() returns an array of node info of cluster.

let nodes = try yarn.checkClusterNodes()
nodes.forEach { node in
	print(node.rack)
	print(node.availableVirtualCores)
	print(node.availMemoryMB)
	print(node.healthReport)
	print(node.healthStatus)
	print(node.id)
	print(node.lastHealthUpdate)
	print(node.nodeHostName)
	print(node.nodeHTTPAddress)

Once done, the checkClusterNodes() would return an array of Node object, as described below:

Node Object

ItemData TypeDescription
rackStringThe rack location of this node
stateStringState of the node - valid values are: NEW, RUNNING, UNHEALTHY, DECOMMISSIONED, LOST, REBOOTED
idStringThe node id
nodeHostNameStringThe host name of the node
nodeHTTPAddressStringThe nodes HTTP address
healthStatusStringThe health status of the node - Healthy or Unhealthy
healthReportStringA detailed health report
lastHealthUpdateIntThe last time the node reported its health (in ms since epoch)
usedMemoryMBIntThe total amount of memory currently used on the node (in MB)
availMemoryMBIntThe total amount of memory currently available on the node (in MB)
usedVirtualCoresIntThe total number of vCores currently used on the node
availableVirtualCoresIntThe total number of vCores available on the node
numContainersintThe total number of containers currently running on the node

Check A Node

Method checkClusterNode() returns a detailed info structure of a node.

guard let n = try yarn.checkClusterNode(id: "host.domain.com:8041") else {
	// something wrong, must return
}

Applications on Cluster

Check All Applications

Method checkApps() returns an array of APP structure.

let apps = try yarn.checkApps()
// or alternatively, you can filter out those APPs you want by setting query parameters:
/// let apps = try yarn.checkApps(states: [APP.State.FINISHED, APP.State.RUNNING], finalStatus: APP.FinalStatus.SUCCEEDED)

apps.forEach{ a in
	print(a.allocatedMB)
	print(a.allocatedVCores)
	print(a.amContainerLogs)
	print(a.amHostHttpAddress)
	print(a.amNodeLabelExpression)
	print(a.amRPCAddress)
	print(a.applicationPriority)
	print(a.applicationTags)
}

Once done, the checkApps() would return an array of APP objects, as described below:

APP Object

ItemData TypeDescription
idStringThe application id
userStringThe user who started the application
nameStringThe application name
applicationTypeStringThe application type
queueStringThe queue the application was submitted to
stateStringThe application state according to the ResourceManager - valid values are members of the YarnApplicationState enum: NEW, NEW_SAVING, SUBMITTED, ACCEPTED, RUNNING, FINISHED, FAILED, KILLED
finalStatusStringThe final status of the application if finished - reported by the application itself - valid values are: UNDEFINED, SUCCEEDED, FAILED, KILLED
progressDoubleThe progress of the application as a percent
trackingUIStringWhere the tracking url is currently pointing - History (for history server) or ApplicationMaster
trackingUrlStringThe web URL that can be used to track the application
diagnosticsStringDetailed diagnostics information
clusterIdIntThe cluster id
startedTimeIntThe time in which application started (in ms since epoch)
finishedTimeIntThe time in which the application finished (in ms since epoch)
elapsedTimeIntThe elapsed time since the application started (in ms)
amContainerLogsStringThe URL of the application master container logs
amHostHttpAddressStringThe nodes http address of the application master
amRPCAddressStringThe RPC address of the application master
allocatedMBIntThe sum of memory in MB allocated to the application’s running containers
allocatedVCoresIntThe sum of virtual cores allocated to the application’s running containers
runningContainersIntThe number of containers currently running for the application
memorySecondsIntThe amount of memory the application has allocated (megabyte-seconds)
vcoreSecondsIntThe amount of CPU resources the application has allocated (virtual core-seconds)
unmanagedApplicationBoolIs the application unmanaged.
applicationPriorityIntpriority of the submitted application
appNodeLabelExpressionStringNode Label expression which is used to identify the nodes on which application’s containers are expected to run by default.
amNodeLabelExpressionStringNode Label expression which is used to identify the node on which application’s AM container is expected to run.

Check A Specific Application

Method checkApp() returns a specific APP Object.

let a = try yarn.checkApp(id: "application_1484231633049_0025")
print(a.allocatedMB)
print(a.allocatedVCores)
print(a.amContainerLogs)
print(a.amHostHttpAddress)
print(a.amNodeLabelExpression)
print(a.amRPCAddress)
print(a.applicationPriority)
print(a.applicationTags)

The return value is an APP structure, please check the above APP object for detail.

Apply A New Application

Method newApplication() returns a new application handler.

guard let a = try yarn.newApplication() else {
	// cannot create a new application, must return
}

Once completed, the newApplication() method will return a NewApplication object, as described below:

NewApplication Object

ItemData TypeDescription
idStringThe newly created application id
maximumResourceCapabilityResourcesUsedThe maximum resource capabilities available on this cluster

ResourcesUsed Object

The NewApplication object will contain a special object called ResourceUsed, as described below:

ItemData TypeDescription
memoryIntThe maximum memory available for a container
vCoresIntThe maximum number of cores available for a container

Submit Modification to An Application

Method submit() can submit modifications to a specific application.

⚠️Note⚠️ Detail configuration of Yarn MapReduce Application is out of the range of this document, please get more information at Hadoop MapReduce Next Generation - Writing YARN Applications https://wiki.apache.org/hadoop/WritingYarnApps

// create an empty application to fill in the blanks
let sum = SubmitApplication()

// *MUST* set the application id
sum.id =  "application_1484231633049_0025"
// set the application name
sum.name = "test"

// allocate a blank local resource
let local = LocalResource(resource: "hdfs://localhost:9000/user/rockywei/DistributedShell/demo-app/AppMaster.jar", type: .FILE, visibility: .APPLICATION, size: 43004, timestamp: 1405452071209)

// assign the resource into an array
let localResources = Entries([Entry(key:"AppMaster.jar", value: local)])

// *MUST* fill in the field of map reduce command
let commands = Commands("/hdp/bin/hadoop jar /hdp/share/hadoop/mapreduce/hadoop-mapreduce-examples-3.0.0-alpha1.jar grep input output 'dfs[a-z.]+'")

// setup environment as need
let environments = Entries([Entry(key:"DISTRIBUTEDSHELLSCRIPTTIMESTAMP", value: "1405459400754"), Entry(key:"CLASSPATH", value:"{{CLASSPATH}}<CPS>./*<CPS>{{HADOOP_CONF_DIR}}<CPS>{{HADOOP_COMMON_HOME}}/share/hadoop/common/*<CPS>{{HADOOP_COMMON_HOME}}/share/hadoop/common/lib/*<CPS>{{HADOOP_HDFS_HOME}}/share/hadoop/hdfs/*<CPS>{{HADOOP_HDFS_HOME}}/share/hadoop/hdfs/lib/*<CPS>{{HADOOP_YARN_HOME}}/share/hadoop/yarn/*<CPS>{{HADOOP_YARN_HOME}}/share/hadoop/yarn/lib/*<CPS>./log4j.properties"), Entry(key:"DISTRIBUTEDSHELLSCRIPTLEN", value:6), Entry(key:"DISTRIBUTEDSHELLSCRIPTLOCATION", value: "hdfs://localhost:9000/user/rockywei/demo-app/shellCommands")])

// specify the container info
sum.amContainerSpec = AmContainerSpec(localResources: localResources, environment: environments, commands: commands)

// set other information as need
sum.unmanagedAM = false
sum.maxAppAttempts = 2
sum.resource = ResourceRequest(memory: 1024, vCores: 1)
sum.type = "MapReduce"
sum.keepContainersAcrossApplicationAttempts = false

// set the log context
sum.logAggregationContext = LogAggregationContext(logIncludePattern: "file1", logExcludePattern: "file2", rolledLogIncludePattern: "file3", rolledLogExcludePattern: "file4", logAggregationPolicyClassName: "org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation.AllContainerLogAggregationPolicy", logAggregationPolicyParameters: "")

// set the failures validity interval
sum.attemptFailuresValidityInterval = 3600000

// set the reservationId, if possible
sum.reservationId = "reservation_1454114874_1"
sum.amBlackListingRequests = AmBlackListingRequests(amBlackListingEnabled: true, disableFailureThreshold: 0.01)

try yarn.submit(application: sum)

SubmitApplication Object

SubmitApplication class contains quite a few sub types, as described below:

ItemData TypeDescription
idStringThe application id
nameStringThe application name
queueStringThe name of the queue to which the application should be submitted
priorityIntThe priority of the application
amContainerSpecAmContainerSpecThe application master container launch context, described below
unmanagedAMBoolIs the application using an unmanaged application master
maxAppAttemptsintThe max number of attempts for this application
resourceResourceRequestThe resources the application master requires, described below
typeStringThe application type(MapReduce, Pig, Hive, etc)
keepContainersAcrossApplicationAttemptsBoolShould YARN keep the containers used by this application instead of destroying them
tags[String]List of application tags, please see the request examples on how to specify the tags
logAggregationContextLogAggregationContextRepresents all of the information needed by the NodeManager to handle the logs for this application
attemptFailuresValidityIntervalIntThe failure number will no take attempt failures which happen out of the validityInterval into failure count
reservationIdstringRepresent the unique id of the corresponding reserved resource allocation in the scheduler
amBlackListingRequestsAmBlackListingRequestsContains blacklisting information such as “enable/disable AM blacklisting” and “disable failure threshold”

AmContainerSpec Object

ItemData TypeDescription
localResourcesEntriesObject describing the resources that need to be localized, described below
environmentEntriesEnvironment variables for your containers, specified as key value pairs
commandsCommandsThe commands for launching your container, in the order in which they should be executed
serviceDataEntriesApplication specific service data; key is the name of the auxiliary service, value is base-64 encoding of the data you wish to pass
credentialsCredentialsThe credentials required for your application to run, described below
applicationAclsEntriesACLs for your application; the key can be “VIEW_APP” or “MODIFY_APP”, the value is the list of users with the permissions

LocalResource Object

ItemData TypeDescription
resourceStringLocation of the resource to be localized
typeResourceTypeType of the resource; options are “ARCHIVE”, “FILE”, and “PATTERN”
visibilityVisibilityVisibility the resource to be localized; options are “PUBLIC”, “PRIVATE”, and “APPLICATION”
sizeIntSize of the resource to be localized
timestampIntTimestamp of the resource to be localized

Commands Object

Currently Commands object only one string field named command. ⚠️NOTE⚠️ According to Hadoop 3.0 alpha document, commands should be an array of command strings with a sequential meaning, however, the example given in Hadoop 3.0 alpha indicates only one command. This feature is experimental and subject to change in future.

Credentials Object

ItemData TypeDescription
tokens[String:String]Tokens that you wish to pass to your application, specified as key-value pairs. The key is an identifier for the token and the value is the token(which should be obtained using the respective web-services)
secrets[String:String]Secrets that you wish to use in your application, specified as key-value pairs. They key is an identifier and the value is the base-64 encoding of the secret

ResourceRequest Object

ItemData TypeDescription
memoryintMemory required for each container
vCoresintVirtual cores required for each container

Entries Object

The Entries Object has only one field of element: entry, which is an array of Entry object or EncryptedEntry object. Each Entry has two elements: a string key and a Any type value.

The difference between Entry and EncryptedEntry is that the value of EncryptedEntry will be encoded in base64 format before submission, providing the type of value is either String or [UInt8].

AmBlackListingRequests Object

ItemData TypeDescription
amBlackListingEnabledBoolWhether AM Blacklisting is enabled
disableFailureThresholdFloatAM Blacklisting disable failure threshold

LogAggregationContext Object

ItemData TypeDescription
logIncludePatternStringThe log files which match the defined include pattern will be uploaded when the application finishes
logExcludePatternStringThe log files which match the defined exclude pattern will not be uploaded when the application finishes
rolledLogIncludePatternStringThe log files which match the defined include pattern will be aggregated in a rolling fashion
rolledLogExcludePatternStringThe log files which match the defined exclude pattern will not be aggregated in a rolling fashion
logAggregationPolicyClassNameStringThe policy which will be used by NodeManager to aggregate the logs
logAggregationPolicyParametersStringThe parameters passed to the policy class

Application State Control

Method getApplicationStatus() returns the current state of application.

guard let state = try yarn.getApplicationStatus(id:  "application_1484231633049_0025") else {
	// something wrong, must return
}
print(state)

Method setApplicationStatus() can set the current state of application to a designated one.

try yarn.setApplicationStatus(id:  "application_1484231633049_0025", state: .KILLED)

Valid States includes:

NEW, NEW_SAVING, SUBMITTED, ACCEPTED, RUNNING, FINISHED, FAILED, KILLED

Application Queue Control

Method getApplicationQueue() returns the current queue name of application.

guard let queue = try yarn.getApplicationQueue(id:  "application_1484231633049_0025") else {
	// something wrong, must return
}
print(queue)

Method setApplicationQueue() can set the current queue name of application to a designated one.

try yarn.setApplicationQueue(id:  "application_1484231633049_0025", queue:"a1a")

Application Priority Control

Method getApplicationPriority() returns the current priority of application.

guard let priority = try yarn.getApplicationPriority(id:  "application_1484231633049_0025") else {
	// something wrong, must return
}
print(priority)

Currently the returned priority is an integer such as 0.

Method setApplicationPriority() can set the current priority of application to a designated one.

try yarn.setApplicationPriority(id:  "application_1484231633049_0025", priority: 1)

Application Attempts

Method checkAppAttempts() returns an array of Attempt object of application.

guard let attempts = try yarn.checkAppAttempts(id:  "application_1484231633049_0025") else {
	// something wrong, must return
}
attempts.forEach { attempt in
	print(attempt.containerId)
	print(attempt.id)
	print(attempt.nodeHttpAddress)
	print(attempt.nodeId)
	print(attempt.startTime)
}//next

Once done, checkAppAttempts() would return an array of AppAttempt object, as described below:

AppAttempt Object

ItemData TypeDescription
idStringThe app attempt id
nodeIdStringThe node id of the node the attempt ran on
nodeHttpAddressStringThe node http address of the node the attempt ran on
logsLinkStringThe http link to the app attempt logs
containerIdStringThe id of the container for the app attempt
startTimeIntThe start time of the attempt (in ms since epoch)

Application Statistics

Method checkAppStatistics() returns an array of statistic variables of application.

let sta = try yarn.checkAppStatistics(states: [APP.State.FINISHED, APP.State.RUNNING])
sta.forEach{ s in
	print(s.count)
	print(s.state)
	print(s.type)
}//next s

checkAppStatistics() allows user to perform a query with two additional parameters:

ParameterData TypeDescription
states[APP.State]states of the applications. If states is not provided, the API will enumerate all application states and return the counts of them.
applicationTypes[String]types of the applications. If applicationTypes is not provided, the API will count the applications of any application type. In this case, the response shows * to indicate any application type. Note that we only support at most one applicationType temporarily, such as applicationTypes: ["MapReduce"]