repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/metrics/ApplicationFinishedEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.metrics; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppMetrics; public class ApplicationFinishedEvent extends SystemMetricsEvent { private ApplicationId appId;; private String diagnosticsInfo; private FinalApplicationStatus appStatus; private YarnApplicationState state; private ApplicationAttemptId latestAppAttemptId; private RMAppMetrics appMetrics; public ApplicationFinishedEvent( ApplicationId appId, String diagnosticsInfo, FinalApplicationStatus appStatus, YarnApplicationState state, ApplicationAttemptId latestAppAttemptId, long finishedTime, RMAppMetrics appMetrics) { super(SystemMetricsEventType.APP_FINISHED, finishedTime); this.appId = appId; this.diagnosticsInfo = diagnosticsInfo; this.appStatus = appStatus; this.latestAppAttemptId = latestAppAttemptId; this.state = state; this.appMetrics=appMetrics; } @Override public int hashCode() { return appId.hashCode(); } public ApplicationId getApplicationId() { return appId; } public String getDiagnosticsInfo() { return diagnosticsInfo; } public FinalApplicationStatus getFinalApplicationStatus() { return appStatus; } public YarnApplicationState getYarnApplicationState() { return state; } public ApplicationAttemptId getLatestApplicationAttemptId() { return latestAppAttemptId; } public RMAppMetrics getAppMetrics() { return appMetrics; } }
2,598
30.313253
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.nodelabels; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.service.Service; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.nodelabels.RMNodeLabel; import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeLabelsUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.collect.ImmutableSet; public class RMNodeLabelsManager extends CommonNodeLabelsManager { protected static class Queue { protected Set<String> accessibleNodeLabels; protected Resource resource; protected Queue() { accessibleNodeLabels = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); resource = Resource.newInstance(0, 0); } } ConcurrentMap<String, Queue> queueCollections = new ConcurrentHashMap<String, Queue>(); private YarnAuthorizationProvider authorizer; private RMContext rmContext = null; @Override protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); authorizer = YarnAuthorizationProvider.getInstance(conf); } @Override public void addLabelsToNode(Map<NodeId, Set<String>> addedLabelsToNode) throws IOException { try { writeLock.lock(); // get nodesCollection before edition Map<String, Host> before = cloneNodeMap(addedLabelsToNode.keySet()); super.addLabelsToNode(addedLabelsToNode); // get nodesCollection after edition Map<String, Host> after = cloneNodeMap(addedLabelsToNode.keySet()); // update running nodes resources updateResourceMappings(before, after); } finally { writeLock.unlock(); } } protected void checkRemoveFromClusterNodeLabelsOfQueue( Collection<String> labelsToRemove) throws IOException { // Check if label to remove doesn't existed or null/empty, will throw // exception if any of labels to remove doesn't meet requirement for (String label : labelsToRemove) { label = normalizeLabel(label); // check if any queue contains this label for (Entry<String, Queue> entry : queueCollections.entrySet()) { String queueName = entry.getKey(); Set<String> queueLabels = entry.getValue().accessibleNodeLabels; if (queueLabels.contains(label)) { throw new IOException("Cannot remove label=" + label + ", because queue=" + queueName + " is using this label. " + "Please remove label on queue before remove the label"); } } } } @Override public void removeFromClusterNodeLabels(Collection<String> labelsToRemove) throws IOException { try { writeLock.lock(); if (getServiceState() == Service.STATE.STARTED) { // We cannot remove node labels from collection when some queue(s) are // using any of them. // We will only do this check when service starting finished. Before // service starting, we will replay edit logs and recover state. It is // possible that a history operation removed some labels which were being // used by some queues in the past but not used by current queues. checkRemoveFromClusterNodeLabelsOfQueue(labelsToRemove); } // copy before NMs Map<String, Host> before = cloneNodeMap(); super.removeFromClusterNodeLabels(labelsToRemove); updateResourceMappings(before, nodeCollections); } finally { writeLock.unlock(); } } @Override public void removeLabelsFromNode(Map<NodeId, Set<String>> removeLabelsFromNode) throws IOException { try { writeLock.lock(); // get nodesCollection before edition Map<String, Host> before = cloneNodeMap(removeLabelsFromNode.keySet()); super.removeLabelsFromNode(removeLabelsFromNode); // get nodesCollection before edition Map<String, Host> after = cloneNodeMap(removeLabelsFromNode.keySet()); // update running nodes resources updateResourceMappings(before, after); } finally { writeLock.unlock(); } } @Override public void replaceLabelsOnNode(Map<NodeId, Set<String>> replaceLabelsToNode) throws IOException { try { writeLock.lock(); // get nodesCollection before edition Map<String, Host> before = cloneNodeMap(replaceLabelsToNode.keySet()); super.replaceLabelsOnNode(replaceLabelsToNode); // get nodesCollection after edition Map<String, Host> after = cloneNodeMap(replaceLabelsToNode.keySet()); // update running nodes resources updateResourceMappings(before, after); } finally { writeLock.unlock(); } } /* * Following methods are used for setting if a node is up and running, and it * will update running nodes resource */ public void activateNode(NodeId nodeId, Resource resource) { try { writeLock.lock(); // save if we have a node before Map<String, Host> before = cloneNodeMap(ImmutableSet.of(nodeId)); createHostIfNonExisted(nodeId.getHost()); try { createNodeIfNonExisted(nodeId); } catch (IOException e) { LOG.error("This shouldn't happen, cannot get host in nodeCollection" + " associated to the node being activated"); return; } Node nm = getNMInNodeSet(nodeId); nm.resource = resource; nm.running = true; // Add node in labelsCollection Set<String> labelsForNode = getLabelsByNode(nodeId); if (labelsForNode != null) { for (String label : labelsForNode) { RMNodeLabel labelInfo = labelCollections.get(label); if(labelInfo != null) { labelInfo.addNodeId(nodeId); } } } // get the node after edition Map<String, Host> after = cloneNodeMap(ImmutableSet.of(nodeId)); updateResourceMappings(before, after); } finally { writeLock.unlock(); } } /* * Following methods are used for setting if a node unregistered to RM */ public void deactivateNode(NodeId nodeId) { try { writeLock.lock(); // save if we have a node before Map<String, Host> before = cloneNodeMap(ImmutableSet.of(nodeId)); Node nm = getNMInNodeSet(nodeId); if (null != nm) { if (null == nm.labels) { // When node deactivated, remove the nm from node collection if no // labels explicitly set for this particular nm // Save labels first, we need to remove label->nodes relation later Set<String> savedNodeLabels = getLabelsOnNode(nodeId); // Remove this node in nodes collection nodeCollections.get(nodeId.getHost()).nms.remove(nodeId); // Remove this node in labels->node removeNodeFromLabels(nodeId, savedNodeLabels); } else { // set nm is not running, and its resource = 0 nm.running = false; nm.resource = Resource.newInstance(0, 0); } } // get the node after edition Map<String, Host> after = cloneNodeMap(ImmutableSet.of(nodeId)); updateResourceMappings(before, after); } finally { writeLock.unlock(); } } public void updateNodeResource(NodeId node, Resource newResource) { deactivateNode(node); activateNode(node, newResource); } public void reinitializeQueueLabels(Map<String, Set<String>> queueToLabels) { try { writeLock.lock(); // clear before set this.queueCollections.clear(); for (Entry<String, Set<String>> entry : queueToLabels.entrySet()) { String queue = entry.getKey(); Queue q = new Queue(); this.queueCollections.put(queue, q); Set<String> labels = entry.getValue(); if (labels.contains(ANY)) { continue; } q.accessibleNodeLabels.addAll(labels); for (Host host : nodeCollections.values()) { for (Entry<NodeId, Node> nentry : host.nms.entrySet()) { NodeId nodeId = nentry.getKey(); Node nm = nentry.getValue(); if (nm.running && isNodeUsableByQueue(getLabelsByNode(nodeId), q)) { Resources.addTo(q.resource, nm.resource); } } } } } finally { writeLock.unlock(); } } public Resource getQueueResource(String queueName, Set<String> queueLabels, Resource clusterResource) { try { readLock.lock(); if (queueLabels.contains(ANY)) { return clusterResource; } Queue q = queueCollections.get(queueName); if (null == q) { return Resources.none(); } return q.resource; } finally { readLock.unlock(); } } public Set<String> getLabelsOnNode(NodeId nodeId) { try { readLock.lock(); Set<String> nodeLabels = getLabelsByNode(nodeId); return Collections.unmodifiableSet(nodeLabels); } finally { readLock.unlock(); } } public boolean containsNodeLabel(String label) { try { readLock.lock(); return label != null && (label.isEmpty() || labelCollections.containsKey(label)); } finally { readLock.unlock(); } } private Map<String, Host> cloneNodeMap(Set<NodeId> nodesToCopy) { Map<String, Host> map = new HashMap<String, Host>(); for (NodeId nodeId : nodesToCopy) { if (!map.containsKey(nodeId.getHost())) { Host originalN = nodeCollections.get(nodeId.getHost()); if (null == originalN) { continue; } Host n = originalN.copy(); n.nms.clear(); map.put(nodeId.getHost(), n); } Host n = map.get(nodeId.getHost()); if (WILDCARD_PORT == nodeId.getPort()) { for (Entry<NodeId, Node> entry : nodeCollections .get(nodeId.getHost()).nms.entrySet()) { n.nms.put(entry.getKey(), entry.getValue().copy()); } } else { Node nm = getNMInNodeSet(nodeId); if (null != nm) { n.nms.put(nodeId, nm.copy()); } } } return map; } @SuppressWarnings("unchecked") private void updateResourceMappings(Map<String, Host> before, Map<String, Host> after) { // Get NMs in before only Set<NodeId> allNMs = new HashSet<NodeId>(); for (Entry<String, Host> entry : before.entrySet()) { allNMs.addAll(entry.getValue().nms.keySet()); } for (Entry<String, Host> entry : after.entrySet()) { allNMs.addAll(entry.getValue().nms.keySet()); } // Map used to notify RM Map<NodeId, Set<String>> newNodeToLabelsMap = new HashMap<NodeId, Set<String>>(); // traverse all nms for (NodeId nodeId : allNMs) { Node oldNM; if ((oldNM = getNMInNodeSet(nodeId, before, true)) != null) { Set<String> oldLabels = getLabelsByNode(nodeId, before); // no label in the past if (oldLabels.isEmpty()) { // update labels RMNodeLabel label = labelCollections.get(NO_LABEL); label.removeNode(oldNM.resource); // update queues, all queue can access this node for (Queue q : queueCollections.values()) { Resources.subtractFrom(q.resource, oldNM.resource); } } else { // update labels for (String labelName : oldLabels) { RMNodeLabel label = labelCollections.get(labelName); if (null == label) { continue; } label.removeNode(oldNM.resource); } // update queues, only queue can access this node will be subtract for (Queue q : queueCollections.values()) { if (isNodeUsableByQueue(oldLabels, q)) { Resources.subtractFrom(q.resource, oldNM.resource); } } } } Node newNM; if ((newNM = getNMInNodeSet(nodeId, after, true)) != null) { Set<String> newLabels = getLabelsByNode(nodeId, after); newNodeToLabelsMap.put(nodeId, ImmutableSet.copyOf(newLabels)); // no label in the past if (newLabels.isEmpty()) { // update labels RMNodeLabel label = labelCollections.get(NO_LABEL); label.addNode(newNM.resource); // update queues, all queue can access this node for (Queue q : queueCollections.values()) { Resources.addTo(q.resource, newNM.resource); } } else { // update labels for (String labelName : newLabels) { RMNodeLabel label = labelCollections.get(labelName); label.addNode(newNM.resource); } // update queues, only queue can access this node will be subtract for (Queue q : queueCollections.values()) { if (isNodeUsableByQueue(newLabels, q)) { Resources.addTo(q.resource, newNM.resource); } } } } } // Notify RM if (rmContext != null && rmContext.getDispatcher() != null) { rmContext.getDispatcher().getEventHandler().handle( new NodeLabelsUpdateSchedulerEvent(newNodeToLabelsMap)); } } public Resource getResourceByLabel(String label, Resource clusterResource) { label = normalizeLabel(label); try { readLock.lock(); if (null == labelCollections.get(label)) { return Resources.none(); } return labelCollections.get(label).getResource(); } finally { readLock.unlock(); } } private boolean isNodeUsableByQueue(Set<String> nodeLabels, Queue q) { // node without any labels can be accessed by any queue if (nodeLabels == null || nodeLabels.isEmpty() || (nodeLabels.size() == 1 && nodeLabels.contains(NO_LABEL))) { return true; } for (String label : nodeLabels) { if (q.accessibleNodeLabels.contains(label)) { return true; } } return false; } private Map<String, Host> cloneNodeMap() { Set<NodeId> nodesToCopy = new HashSet<NodeId>(); for (String nodeName : nodeCollections.keySet()) { nodesToCopy.add(NodeId.newInstance(nodeName, WILDCARD_PORT)); } return cloneNodeMap(nodesToCopy); } public boolean checkAccess(UserGroupInformation user) { // make sure only admin can invoke // this method if (authorizer.isAdmin(user)) { return true; } return false; } public void setRMContext(RMContext rmContext) { this.rmContext = rmContext; } public List<RMNodeLabel> pullRMNodeLabelsInfo() { try { readLock.lock(); List<RMNodeLabel> infos = new ArrayList<RMNodeLabel>(); for (Entry<String, RMNodeLabel> entry : labelCollections.entrySet()) { RMNodeLabel label = entry.getValue(); infos.add(label.getCopy()); } Collections.sort(infos); return infos; } finally { readLock.unlock(); } } }
16,592
30.666031
100
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppState.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; public enum RMAppState { NEW, NEW_SAVING, SUBMITTED, ACCEPTED, RUNNING, FINAL_SAVING, FINISHING, FINISHED, FAILED, KILLING, KILLED }
1,025
29.176471
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.event.AbstractEvent; public class RMAppEvent extends AbstractEvent<RMAppEventType>{ private final ApplicationId appId; public RMAppEvent(ApplicationId appId, RMAppEventType type) { super(type); this.appId = appId; } public ApplicationId getApplicationId() { return this.appId; } }
1,264
33.189189
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppRejectedEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; public class RMAppRejectedEvent extends RMAppEvent { private final String message; public RMAppRejectedEvent(ApplicationId appId, String message) { super(appId, RMAppEventType.APP_REJECTED); this.message = message; } public String getMessage() { return this.message; } }
1,224
33.027778
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppRecoverEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; public class RMAppRecoverEvent extends RMAppEvent { private final RMState state; public RMAppRecoverEvent(ApplicationId appId, RMState state) { super(appId, RMAppEventType.RECOVER); this.state = state; } public RMState getRMState() { return state; } }
1,289
33.864865
83
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppRunningOnNodeEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.NodeId; public class RMAppRunningOnNodeEvent extends RMAppEvent { private final NodeId node; public RMAppRunningOnNodeEvent(ApplicationId appId, NodeId node) { super(appId, RMAppEventType.APP_RUNNING_ON_NODE); this.node = node; } public NodeId getNodeId() { return node; } }
1,271
34.333333
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppMetrics.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.Resource; public class RMAppMetrics { final Resource resourcePreempted; final int numNonAMContainersPreempted; final int numAMContainersPreempted; final long memorySeconds; final long vcoreSeconds; public RMAppMetrics(Resource resourcePreempted, int numNonAMContainersPreempted, int numAMContainersPreempted, long memorySeconds, long vcoreSeconds) { this.resourcePreempted = resourcePreempted; this.numNonAMContainersPreempted = numNonAMContainersPreempted; this.numAMContainersPreempted = numAMContainersPreempted; this.memorySeconds = memorySeconds; this.vcoreSeconds = vcoreSeconds; } public Resource getResourcePreempted() { return resourcePreempted; } public int getNumNonAMContainersPreempted() { return numNonAMContainersPreempted; } public int getNumAMContainersPreempted() { return numAMContainersPreempted; } public long getMemorySeconds() { return memorySeconds; } public long getVcoreSeconds() { return vcoreSeconds; } }
1,938
31.316667
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppMoveEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; import com.google.common.util.concurrent.SettableFuture; public class RMAppMoveEvent extends RMAppEvent { private String targetQueue; private SettableFuture<Object> result; public RMAppMoveEvent(ApplicationId id, String newQueue, SettableFuture<Object> resultFuture) { super(id, RMAppEventType.MOVE); this.targetQueue = newQueue; this.result = resultFuture; } public String getTargetQueue() { return targetQueue; } public SettableFuture<Object> getResult() { return result; } }
1,459
31.444444
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMApp.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LogAggregationStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.server.api.protocolrecords.LogAggregationReport; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; /** * The interface to an Application in the ResourceManager. Take a * look at {@link RMAppImpl} for its implementation. This interface * exposes methods to access various updates in application status/report. */ public interface RMApp extends EventHandler<RMAppEvent> { /** * The application id for this {@link RMApp}. * @return the {@link ApplicationId} for this {@link RMApp}. */ ApplicationId getApplicationId(); /** * The application submission context for this {@link RMApp} * @return the {@link ApplicationSubmissionContext} for this {@link RMApp} */ ApplicationSubmissionContext getApplicationSubmissionContext(); /** * The current state of the {@link RMApp}. * @return the current state {@link RMAppState} for this application. */ RMAppState getState(); /** * The user who submitted this application. * @return the user who submitted the application. */ String getUser(); /** * Progress of application. * @return the progress of the {@link RMApp}. */ float getProgress(); /** * {@link RMApp} can have multiple application attempts {@link RMAppAttempt}. * This method returns the {@link RMAppAttempt} corresponding to * {@link ApplicationAttemptId}. * @param appAttemptId the application attempt id * @return the {@link RMAppAttempt} corresponding to the {@link ApplicationAttemptId}. */ RMAppAttempt getRMAppAttempt(ApplicationAttemptId appAttemptId); /** * Each Application is submitted to a queue decided by {@link * ApplicationSubmissionContext#setQueue(String)}. * This method returns the queue to which an application was submitted. * @return the queue to which the application was submitted to. */ String getQueue(); /** * Reflects a change in the application's queue from the one specified in the * {@link ApplicationSubmissionContext}. * @param name the new queue name */ void setQueue(String name); /** * The name of the application as set in {@link * ApplicationSubmissionContext#setApplicationName(String)}. * @return the name of the application. */ String getName(); /** * {@link RMApp} can have multiple application attempts {@link RMAppAttempt}. * This method returns the current {@link RMAppAttempt}. * @return the current {@link RMAppAttempt} */ RMAppAttempt getCurrentAppAttempt(); /** * {@link RMApp} can have multiple application attempts {@link RMAppAttempt}. * This method returns the all {@link RMAppAttempt}s for the RMApp. * @return all {@link RMAppAttempt}s for the RMApp. */ Map<ApplicationAttemptId, RMAppAttempt> getAppAttempts(); /** * To get the status of an application in the RM, this method can be used. * If full access is not allowed then the following fields in the report * will be stubbed: * <ul> * <li>host - set to "N/A"</li> * <li>RPC port - set to -1</li> * <li>client token - set to "N/A"</li> * <li>diagnostics - set to "N/A"</li> * <li>tracking URL - set to "N/A"</li> * <li>original tracking URL - set to "N/A"</li> * <li>resource usage report - all values are -1</li> * </ul> * * @param clientUserName the user name of the client requesting the report * @param allowAccess whether to allow full access to the report * @return the {@link ApplicationReport} detailing the status of the application. */ ApplicationReport createAndGetApplicationReport(String clientUserName, boolean allowAccess); /** * To receive the collection of all {@link RMNode}s whose updates have been * received by the RMApp. Updates can be node becoming lost or becoming * healthy etc. The method clears the information from the {@link RMApp}. So * each call to this method gives the delta from the previous call. * @param updatedNodes Collection into which the updates are transferred * @return the number of nodes added to the {@link Collection} */ int pullRMNodeUpdates(Collection<RMNode> updatedNodes); /** * The finish time of the {@link RMApp} * @return the finish time of the application., */ long getFinishTime(); /** * the start time of the application. * @return the start time of the application. */ long getStartTime(); /** * the submit time of the application. * @return the submit time of the application. */ long getSubmitTime(); /** * The tracking url for the application master. * @return the tracking url for the application master. */ String getTrackingUrl(); /** * The original tracking url for the application master. * @return the original tracking url for the application master. */ String getOriginalTrackingUrl(); /** * the diagnostics information for the application master. * @return the diagnostics information for the application master. */ StringBuilder getDiagnostics(); /** * The final finish state of the AM when unregistering as in * {@link FinishApplicationMasterRequest#setFinalApplicationStatus(FinalApplicationStatus)}. * @return the final finish state of the AM as set in * {@link FinishApplicationMasterRequest#setFinalApplicationStatus(FinalApplicationStatus)}. */ FinalApplicationStatus getFinalApplicationStatus(); /** * The number of max attempts of the application. * @return the number of max attempts of the application. */ int getMaxAppAttempts(); /** * Returns the application type * @return the application type. */ String getApplicationType(); /** * Get tags for the application * @return tags corresponding to the application */ Set<String> getApplicationTags(); /** * Check whether this application's state has been saved to the state store. * @return the flag indicating whether the applications's state is stored. */ boolean isAppFinalStateStored(); /** * Nodes on which the containers for this {@link RMApp} ran. * @return the set of nodes that ran any containers from this {@link RMApp} * Add more node on which containers for this {@link RMApp} ran */ Set<NodeId> getRanNodes(); /** * Create the external user-facing state of ApplicationMaster from the * current state of the {@link RMApp}. * @return the external user-facing state of ApplicationMaster. */ YarnApplicationState createApplicationState(); /** * Get RMAppMetrics of the {@link RMApp}. * * @return metrics */ RMAppMetrics getRMAppMetrics(); ReservationId getReservationId(); ResourceRequest getAMResourceRequest(); Map<NodeId, LogAggregationReport> getLogAggregationReportsForApp(); LogAggregationStatus getLogAggregationStatusForAppReport(); }
8,645
33.309524
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppNodeUpdateEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; public class RMAppNodeUpdateEvent extends RMAppEvent { public enum RMAppNodeUpdateType { NODE_USABLE, NODE_UNUSABLE } private final RMNode node; private final RMAppNodeUpdateType updateType; public RMAppNodeUpdateEvent(ApplicationId appId, RMNode node, RMAppNodeUpdateType updateType) { super(appId, RMAppEventType.NODE_UPDATE); this.node = node; this.updateType = updateType; } public RMNode getNode() { return node; } public RMAppNodeUpdateType getUpdateType() { return updateType; } }
1,545
29.92
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppEventType.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; public enum RMAppEventType { // Source: ClientRMService START, RECOVER, KILL, MOVE, // Move app to a new queue // Source: Scheduler and RMAppManager APP_REJECTED, // Source: Scheduler APP_ACCEPTED, // Source: RMAppAttempt ATTEMPT_REGISTERED, ATTEMPT_UNREGISTERED, ATTEMPT_FINISHED, // Will send the final state ATTEMPT_FAILED, ATTEMPT_KILLED, NODE_UPDATE, // Source: Container and ResourceTracker APP_RUNNING_ON_NODE, // Source: RMStateStore APP_NEW_SAVED, APP_UPDATE_SAVED, }
1,396
27.510204
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppFailedAttemptEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; public class RMAppFailedAttemptEvent extends RMAppEvent { private final String diagnostics; private final boolean transferStateFromPreviousAttempt; public RMAppFailedAttemptEvent(ApplicationId appId, RMAppEventType event, String diagnostics, boolean transferStateFromPreviousAttempt) { super(appId, event); this.diagnostics = diagnostics; this.transferStateFromPreviousAttempt = transferStateFromPreviousAttempt; } public String getDiagnostics() { return this.diagnostics; } public boolean getTransferStateFromPreviousAttempt() { return transferStateFromPreviousAttempt; } }
1,550
35.069767
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DataInputByteBuffer; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LogAggregationStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.security.client.ClientToAMTokenIdentifier; import org.apache.hadoop.yarn.server.api.protocolrecords.LogAggregationReport; import org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService; import org.apache.hadoop.yarn.server.resourcemanager.RMAppManagerEvent; import org.apache.hadoop.yarn.server.resourcemanager.RMAppManagerEventType; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMServerUtils; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.Recoverable; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppNodeUpdateEvent.RMAppNodeUpdateType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AggregateAppResourceUsage; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptMetrics; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppStartAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeCleanAppEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.server.webproxy.ProxyUriUtils; import org.apache.hadoop.yarn.state.InvalidStateTransitionException; import org.apache.hadoop.yarn.state.MultipleArcTransition; import org.apache.hadoop.yarn.state.SingleArcTransition; import org.apache.hadoop.yarn.state.StateMachine; import org.apache.hadoop.yarn.state.StateMachineFactory; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import com.google.common.annotations.VisibleForTesting; @SuppressWarnings({ "rawtypes", "unchecked" }) public class RMAppImpl implements RMApp, Recoverable { private static final Log LOG = LogFactory.getLog(RMAppImpl.class); private static final String UNAVAILABLE = "N/A"; // Immutable fields private final ApplicationId applicationId; private final RMContext rmContext; private final Configuration conf; private final String user; private final String name; private final ApplicationSubmissionContext submissionContext; private final Dispatcher dispatcher; private final YarnScheduler scheduler; private final ApplicationMasterService masterService; private final StringBuilder diagnostics = new StringBuilder(); private final int maxAppAttempts; private final ReadLock readLock; private final WriteLock writeLock; private final Map<ApplicationAttemptId, RMAppAttempt> attempts = new LinkedHashMap<ApplicationAttemptId, RMAppAttempt>(); private final long submitTime; private final Set<RMNode> updatedNodes = new HashSet<RMNode>(); private final String applicationType; private final Set<String> applicationTags; private final long attemptFailuresValidityInterval; private Clock systemClock; private boolean isNumAttemptsBeyondThreshold = false; // Mutable fields private long startTime; private long finishTime = 0; private long storedFinishTime = 0; // This field isn't protected by readlock now. private volatile RMAppAttempt currentAttempt; private String queue; private EventHandler handler; private static final AppFinishedTransition FINISHED_TRANSITION = new AppFinishedTransition(); private Set<NodeId> ranNodes = new ConcurrentSkipListSet<NodeId>(); private final boolean logAggregationEnabled; private long logAggregationStartTime = 0; private final long logAggregationStatusTimeout; private final Map<NodeId, LogAggregationReport> logAggregationStatus = new HashMap<NodeId, LogAggregationReport>(); private LogAggregationStatus logAggregationStatusForAppReport; private int logAggregationSucceed = 0; private int logAggregationFailed = 0; private Map<NodeId, List<String>> logAggregationDiagnosticsForNMs = new HashMap<NodeId, List<String>>(); private Map<NodeId, List<String>> logAggregationFailureMessagesForNMs = new HashMap<NodeId, List<String>>(); private final int maxLogAggregationDiagnosticsInMemory; // These states stored are only valid when app is at killing or final_saving. private RMAppState stateBeforeKilling; private RMAppState stateBeforeFinalSaving; private RMAppEvent eventCausingFinalSaving; private RMAppState targetedFinalState; private RMAppState recoveredFinalState; private ResourceRequest amReq; Object transitionTodo; private static final StateMachineFactory<RMAppImpl, RMAppState, RMAppEventType, RMAppEvent> stateMachineFactory = new StateMachineFactory<RMAppImpl, RMAppState, RMAppEventType, RMAppEvent>(RMAppState.NEW) // Transitions from NEW state .addTransition(RMAppState.NEW, RMAppState.NEW, RMAppEventType.NODE_UPDATE, new RMAppNodeUpdateTransition()) .addTransition(RMAppState.NEW, RMAppState.NEW_SAVING, RMAppEventType.START, new RMAppNewlySavingTransition()) .addTransition(RMAppState.NEW, EnumSet.of(RMAppState.SUBMITTED, RMAppState.ACCEPTED, RMAppState.FINISHED, RMAppState.FAILED, RMAppState.KILLED, RMAppState.FINAL_SAVING), RMAppEventType.RECOVER, new RMAppRecoveredTransition()) .addTransition(RMAppState.NEW, RMAppState.KILLED, RMAppEventType.KILL, new AppKilledTransition()) .addTransition(RMAppState.NEW, RMAppState.FINAL_SAVING, RMAppEventType.APP_REJECTED, new FinalSavingTransition(new AppRejectedTransition(), RMAppState.FAILED)) // Transitions from NEW_SAVING state .addTransition(RMAppState.NEW_SAVING, RMAppState.NEW_SAVING, RMAppEventType.NODE_UPDATE, new RMAppNodeUpdateTransition()) .addTransition(RMAppState.NEW_SAVING, RMAppState.SUBMITTED, RMAppEventType.APP_NEW_SAVED, new AddApplicationToSchedulerTransition()) .addTransition(RMAppState.NEW_SAVING, RMAppState.FINAL_SAVING, RMAppEventType.KILL, new FinalSavingTransition( new AppKilledTransition(), RMAppState.KILLED)) .addTransition(RMAppState.NEW_SAVING, RMAppState.FINAL_SAVING, RMAppEventType.APP_REJECTED, new FinalSavingTransition(new AppRejectedTransition(), RMAppState.FAILED)) .addTransition(RMAppState.NEW_SAVING, RMAppState.NEW_SAVING, RMAppEventType.MOVE, new RMAppMoveTransition()) // Transitions from SUBMITTED state .addTransition(RMAppState.SUBMITTED, RMAppState.SUBMITTED, RMAppEventType.NODE_UPDATE, new RMAppNodeUpdateTransition()) .addTransition(RMAppState.SUBMITTED, RMAppState.SUBMITTED, RMAppEventType.MOVE, new RMAppMoveTransition()) .addTransition(RMAppState.SUBMITTED, RMAppState.FINAL_SAVING, RMAppEventType.APP_REJECTED, new FinalSavingTransition( new AppRejectedTransition(), RMAppState.FAILED)) .addTransition(RMAppState.SUBMITTED, RMAppState.ACCEPTED, RMAppEventType.APP_ACCEPTED, new StartAppAttemptTransition()) .addTransition(RMAppState.SUBMITTED, RMAppState.FINAL_SAVING, RMAppEventType.KILL, new FinalSavingTransition( new AppKilledTransition(), RMAppState.KILLED)) // Transitions from ACCEPTED state .addTransition(RMAppState.ACCEPTED, RMAppState.ACCEPTED, RMAppEventType.NODE_UPDATE, new RMAppNodeUpdateTransition()) .addTransition(RMAppState.ACCEPTED, RMAppState.ACCEPTED, RMAppEventType.MOVE, new RMAppMoveTransition()) .addTransition(RMAppState.ACCEPTED, RMAppState.RUNNING, RMAppEventType.ATTEMPT_REGISTERED) .addTransition(RMAppState.ACCEPTED, EnumSet.of(RMAppState.ACCEPTED, RMAppState.FINAL_SAVING), // ACCEPTED state is possible to receive ATTEMPT_FAILED/ATTEMPT_FINISHED // event because RMAppRecoveredTransition is returning ACCEPTED state // directly and waiting for the previous AM to exit. RMAppEventType.ATTEMPT_FAILED, new AttemptFailedTransition(RMAppState.ACCEPTED)) .addTransition(RMAppState.ACCEPTED, RMAppState.FINAL_SAVING, RMAppEventType.ATTEMPT_FINISHED, new FinalSavingTransition(FINISHED_TRANSITION, RMAppState.FINISHED)) .addTransition(RMAppState.ACCEPTED, RMAppState.KILLING, RMAppEventType.KILL, new KillAttemptTransition()) .addTransition(RMAppState.ACCEPTED, RMAppState.FINAL_SAVING, RMAppEventType.ATTEMPT_KILLED, new FinalSavingTransition(new AppKilledTransition(), RMAppState.KILLED)) .addTransition(RMAppState.ACCEPTED, RMAppState.ACCEPTED, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) // Transitions from RUNNING state .addTransition(RMAppState.RUNNING, RMAppState.RUNNING, RMAppEventType.NODE_UPDATE, new RMAppNodeUpdateTransition()) .addTransition(RMAppState.RUNNING, RMAppState.RUNNING, RMAppEventType.MOVE, new RMAppMoveTransition()) .addTransition(RMAppState.RUNNING, RMAppState.FINAL_SAVING, RMAppEventType.ATTEMPT_UNREGISTERED, new FinalSavingTransition( new AttemptUnregisteredTransition(), RMAppState.FINISHING, RMAppState.FINISHED)) .addTransition(RMAppState.RUNNING, RMAppState.FINISHED, // UnManagedAM directly jumps to finished RMAppEventType.ATTEMPT_FINISHED, FINISHED_TRANSITION) .addTransition(RMAppState.RUNNING, RMAppState.RUNNING, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) .addTransition(RMAppState.RUNNING, EnumSet.of(RMAppState.ACCEPTED, RMAppState.FINAL_SAVING), RMAppEventType.ATTEMPT_FAILED, new AttemptFailedTransition(RMAppState.ACCEPTED)) .addTransition(RMAppState.RUNNING, RMAppState.KILLING, RMAppEventType.KILL, new KillAttemptTransition()) // Transitions from FINAL_SAVING state .addTransition(RMAppState.FINAL_SAVING, EnumSet.of(RMAppState.FINISHING, RMAppState.FAILED, RMAppState.KILLED, RMAppState.FINISHED), RMAppEventType.APP_UPDATE_SAVED, new FinalStateSavedTransition()) .addTransition(RMAppState.FINAL_SAVING, RMAppState.FINAL_SAVING, RMAppEventType.ATTEMPT_FINISHED, new AttemptFinishedAtFinalSavingTransition()) .addTransition(RMAppState.FINAL_SAVING, RMAppState.FINAL_SAVING, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) // ignorable transitions .addTransition(RMAppState.FINAL_SAVING, RMAppState.FINAL_SAVING, EnumSet.of(RMAppEventType.NODE_UPDATE, RMAppEventType.KILL, RMAppEventType.APP_NEW_SAVED, RMAppEventType.MOVE)) // Transitions from FINISHING state .addTransition(RMAppState.FINISHING, RMAppState.FINISHED, RMAppEventType.ATTEMPT_FINISHED, FINISHED_TRANSITION) .addTransition(RMAppState.FINISHING, RMAppState.FINISHING, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) // ignorable transitions .addTransition(RMAppState.FINISHING, RMAppState.FINISHING, EnumSet.of(RMAppEventType.NODE_UPDATE, // ignore Kill/Move as we have already saved the final Finished state // in state store. RMAppEventType.KILL, RMAppEventType.MOVE)) // Transitions from KILLING state .addTransition(RMAppState.KILLING, RMAppState.KILLING, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) .addTransition(RMAppState.KILLING, RMAppState.FINAL_SAVING, RMAppEventType.ATTEMPT_KILLED, new FinalSavingTransition( new AppKilledTransition(), RMAppState.KILLED)) .addTransition(RMAppState.KILLING, RMAppState.FINAL_SAVING, RMAppEventType.ATTEMPT_UNREGISTERED, new FinalSavingTransition( new AttemptUnregisteredTransition(), RMAppState.FINISHING, RMAppState.FINISHED)) .addTransition(RMAppState.KILLING, RMAppState.FINISHED, // UnManagedAM directly jumps to finished RMAppEventType.ATTEMPT_FINISHED, FINISHED_TRANSITION) .addTransition(RMAppState.KILLING, EnumSet.of(RMAppState.FINAL_SAVING), RMAppEventType.ATTEMPT_FAILED, new AttemptFailedTransition(RMAppState.KILLING)) .addTransition(RMAppState.KILLING, RMAppState.KILLING, EnumSet.of( RMAppEventType.NODE_UPDATE, RMAppEventType.ATTEMPT_REGISTERED, RMAppEventType.APP_UPDATE_SAVED, RMAppEventType.KILL, RMAppEventType.MOVE)) // Transitions from FINISHED state // ignorable transitions .addTransition(RMAppState.FINISHED, RMAppState.FINISHED, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) .addTransition(RMAppState.FINISHED, RMAppState.FINISHED, EnumSet.of( RMAppEventType.NODE_UPDATE, RMAppEventType.ATTEMPT_UNREGISTERED, RMAppEventType.ATTEMPT_FINISHED, RMAppEventType.KILL, RMAppEventType.MOVE)) // Transitions from FAILED state // ignorable transitions .addTransition(RMAppState.FAILED, RMAppState.FAILED, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) .addTransition(RMAppState.FAILED, RMAppState.FAILED, EnumSet.of(RMAppEventType.KILL, RMAppEventType.NODE_UPDATE, RMAppEventType.MOVE)) // Transitions from KILLED state // ignorable transitions .addTransition(RMAppState.KILLED, RMAppState.KILLED, RMAppEventType.APP_RUNNING_ON_NODE, new AppRunningOnNodeTransition()) .addTransition( RMAppState.KILLED, RMAppState.KILLED, EnumSet.of(RMAppEventType.APP_ACCEPTED, RMAppEventType.APP_REJECTED, RMAppEventType.KILL, RMAppEventType.ATTEMPT_FINISHED, RMAppEventType.ATTEMPT_FAILED, RMAppEventType.NODE_UPDATE, RMAppEventType.MOVE)) .installTopology(); private final StateMachine<RMAppState, RMAppEventType, RMAppEvent> stateMachine; private static final int DUMMY_APPLICATION_ATTEMPT_NUMBER = -1; public RMAppImpl(ApplicationId applicationId, RMContext rmContext, Configuration config, String name, String user, String queue, ApplicationSubmissionContext submissionContext, YarnScheduler scheduler, ApplicationMasterService masterService, long submitTime, String applicationType, Set<String> applicationTags, ResourceRequest amReq) { this.systemClock = new SystemClock(); this.applicationId = applicationId; this.name = name; this.rmContext = rmContext; this.dispatcher = rmContext.getDispatcher(); this.handler = dispatcher.getEventHandler(); this.conf = config; this.user = user; this.queue = queue; this.submissionContext = submissionContext; this.scheduler = scheduler; this.masterService = masterService; this.submitTime = submitTime; this.startTime = this.systemClock.getTime(); this.applicationType = applicationType; this.applicationTags = applicationTags; this.amReq = amReq; int globalMaxAppAttempts = conf.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); int individualMaxAppAttempts = submissionContext.getMaxAppAttempts(); if (individualMaxAppAttempts <= 0 || individualMaxAppAttempts > globalMaxAppAttempts) { this.maxAppAttempts = globalMaxAppAttempts; LOG.warn("The specific max attempts: " + individualMaxAppAttempts + " for application: " + applicationId.getId() + " is invalid, because it is out of the range [1, " + globalMaxAppAttempts + "]. Use the global max attempts instead."); } else { this.maxAppAttempts = individualMaxAppAttempts; } this.attemptFailuresValidityInterval = submissionContext.getAttemptFailuresValidityInterval(); if (this.attemptFailuresValidityInterval > 0) { LOG.info("The attemptFailuresValidityInterval for the application: " + this.applicationId + " is " + this.attemptFailuresValidityInterval + "."); } ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); this.stateMachine = stateMachineFactory.make(this); rmContext.getRMApplicationHistoryWriter().applicationStarted(this); rmContext.getSystemMetricsPublisher().appCreated(this, startTime); long localLogAggregationStatusTimeout = conf.getLong(YarnConfiguration.LOG_AGGREGATION_STATUS_TIME_OUT_MS, YarnConfiguration.DEFAULT_LOG_AGGREGATION_STATUS_TIME_OUT_MS); if (localLogAggregationStatusTimeout <= 0) { this.logAggregationStatusTimeout = YarnConfiguration.DEFAULT_LOG_AGGREGATION_STATUS_TIME_OUT_MS; } else { this.logAggregationStatusTimeout = localLogAggregationStatusTimeout; } this.logAggregationEnabled = conf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, YarnConfiguration.DEFAULT_LOG_AGGREGATION_ENABLED); if (this.logAggregationEnabled) { this.logAggregationStatusForAppReport = LogAggregationStatus.NOT_START; } else { this.logAggregationStatusForAppReport = LogAggregationStatus.DISABLED; } maxLogAggregationDiagnosticsInMemory = conf.getInt( YarnConfiguration.RM_MAX_LOG_AGGREGATION_DIAGNOSTICS_IN_MEMORY, YarnConfiguration.DEFAULT_RM_MAX_LOG_AGGREGATION_DIAGNOSTICS_IN_MEMORY); } @Override public ApplicationId getApplicationId() { return this.applicationId; } @Override public ApplicationSubmissionContext getApplicationSubmissionContext() { return this.submissionContext; } @Override public FinalApplicationStatus getFinalApplicationStatus() { this.readLock.lock(); try { // finish state is obtained based on the state machine's current state // as a fall-back in case the application has not been unregistered // ( or if the app never unregistered itself ) // when the report is requested if (currentAttempt != null && currentAttempt.getFinalApplicationStatus() != null) { return currentAttempt.getFinalApplicationStatus(); } return createFinalApplicationStatus(this.stateMachine.getCurrentState()); } finally { this.readLock.unlock(); } } @Override public RMAppState getState() { this.readLock.lock(); try { return this.stateMachine.getCurrentState(); } finally { this.readLock.unlock(); } } @Override public String getUser() { return this.user; } @Override public float getProgress() { RMAppAttempt attempt = this.currentAttempt; if (attempt != null) { return attempt.getProgress(); } return 0; } @Override public RMAppAttempt getRMAppAttempt(ApplicationAttemptId appAttemptId) { this.readLock.lock(); try { return this.attempts.get(appAttemptId); } finally { this.readLock.unlock(); } } @Override public String getQueue() { return this.queue; } @Override public void setQueue(String queue) { this.queue = queue; } @Override public String getName() { return this.name; } @Override public RMAppAttempt getCurrentAppAttempt() { return this.currentAttempt; } @Override public Map<ApplicationAttemptId, RMAppAttempt> getAppAttempts() { this.readLock.lock(); try { return Collections.unmodifiableMap(this.attempts); } finally { this.readLock.unlock(); } } private FinalApplicationStatus createFinalApplicationStatus(RMAppState state) { switch(state) { case NEW: case NEW_SAVING: case SUBMITTED: case ACCEPTED: case RUNNING: case FINAL_SAVING: case KILLING: return FinalApplicationStatus.UNDEFINED; // finished without a proper final state is the same as failed case FINISHING: case FINISHED: case FAILED: return FinalApplicationStatus.FAILED; case KILLED: return FinalApplicationStatus.KILLED; } throw new YarnRuntimeException("Unknown state passed!"); } @Override public int pullRMNodeUpdates(Collection<RMNode> updatedNodes) { this.writeLock.lock(); try { int updatedNodeCount = this.updatedNodes.size(); updatedNodes.addAll(this.updatedNodes); this.updatedNodes.clear(); return updatedNodeCount; } finally { this.writeLock.unlock(); } } @Override public ApplicationReport createAndGetApplicationReport(String clientUserName, boolean allowAccess) { this.readLock.lock(); try { ApplicationAttemptId currentApplicationAttemptId = null; org.apache.hadoop.yarn.api.records.Token clientToAMToken = null; String trackingUrl = UNAVAILABLE; String host = UNAVAILABLE; String origTrackingUrl = UNAVAILABLE; LogAggregationStatus logAggregationStatus = null; int rpcPort = -1; ApplicationResourceUsageReport appUsageReport = RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT; FinalApplicationStatus finishState = getFinalApplicationStatus(); String diags = UNAVAILABLE; float progress = 0.0f; org.apache.hadoop.yarn.api.records.Token amrmToken = null; if (allowAccess) { trackingUrl = getDefaultProxyTrackingUrl(); if (this.currentAttempt != null) { currentApplicationAttemptId = this.currentAttempt.getAppAttemptId(); trackingUrl = this.currentAttempt.getTrackingUrl(); origTrackingUrl = this.currentAttempt.getOriginalTrackingUrl(); if (UserGroupInformation.isSecurityEnabled()) { // get a token so the client can communicate with the app attempt // NOTE: token may be unavailable if the attempt is not running Token<ClientToAMTokenIdentifier> attemptClientToAMToken = this.currentAttempt.createClientToken(clientUserName); if (attemptClientToAMToken != null) { clientToAMToken = BuilderUtils.newClientToAMToken( attemptClientToAMToken.getIdentifier(), attemptClientToAMToken.getKind().toString(), attemptClientToAMToken.getPassword(), attemptClientToAMToken.getService().toString()); } } host = this.currentAttempt.getHost(); rpcPort = this.currentAttempt.getRpcPort(); appUsageReport = currentAttempt.getApplicationResourceUsageReport(); progress = currentAttempt.getProgress(); logAggregationStatus = this.getLogAggregationStatusForAppReport(); } diags = this.diagnostics.toString(); if (currentAttempt != null && currentAttempt.getAppAttemptState() == RMAppAttemptState.LAUNCHED) { if (getApplicationSubmissionContext().getUnmanagedAM() && clientUserName != null && getUser().equals(clientUserName)) { Token<AMRMTokenIdentifier> token = currentAttempt.getAMRMToken(); if (token != null) { amrmToken = BuilderUtils.newAMRMToken(token.getIdentifier(), token.getKind().toString(), token.getPassword(), token.getService().toString()); } } } RMAppMetrics rmAppMetrics = getRMAppMetrics(); appUsageReport.setMemorySeconds(rmAppMetrics.getMemorySeconds()); appUsageReport.setVcoreSeconds(rmAppMetrics.getVcoreSeconds()); } if (currentApplicationAttemptId == null) { currentApplicationAttemptId = BuilderUtils.newApplicationAttemptId(this.applicationId, DUMMY_APPLICATION_ATTEMPT_NUMBER); } ApplicationReport report = BuilderUtils.newApplicationReport( this.applicationId, currentApplicationAttemptId, this.user, this.queue, this.name, host, rpcPort, clientToAMToken, createApplicationState(), diags, trackingUrl, this.startTime, this.finishTime, finishState, appUsageReport, origTrackingUrl, progress, this.applicationType, amrmToken, applicationTags, this.submissionContext.getPriority()); report.setLogAggregationStatus(logAggregationStatus); report.setUnmanagedApp(submissionContext.getUnmanagedAM()); return report; } finally { this.readLock.unlock(); } } private String getDefaultProxyTrackingUrl() { try { final String scheme = WebAppUtils.getHttpSchemePrefix(conf); String proxy = WebAppUtils.getProxyHostAndPort(conf); URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy); URI result = ProxyUriUtils.getProxyUri(null, proxyUri, applicationId); return result.toASCIIString(); } catch (URISyntaxException e) { LOG.warn("Could not generate default proxy tracking URL for " + applicationId); return UNAVAILABLE; } } @Override public long getFinishTime() { this.readLock.lock(); try { return this.finishTime; } finally { this.readLock.unlock(); } } @Override public long getStartTime() { this.readLock.lock(); try { return this.startTime; } finally { this.readLock.unlock(); } } @Override public long getSubmitTime() { return this.submitTime; } @Override public String getTrackingUrl() { RMAppAttempt attempt = this.currentAttempt; if (attempt != null) { return attempt.getTrackingUrl(); } return null; } @Override public String getOriginalTrackingUrl() { RMAppAttempt attempt = this.currentAttempt; if (attempt != null) { return attempt.getOriginalTrackingUrl(); } return null; } @Override public StringBuilder getDiagnostics() { this.readLock.lock(); try { return this.diagnostics; } finally { this.readLock.unlock(); } } @Override public int getMaxAppAttempts() { return this.maxAppAttempts; } @Override public void handle(RMAppEvent event) { this.writeLock.lock(); try { ApplicationId appID = event.getApplicationId(); LOG.debug("Processing event for " + appID + " of type " + event.getType()); final RMAppState oldState = getState(); try { /* keep the master in sync with the state machine */ this.stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitionException e) { LOG.error("Can't handle this event at current state", e); /* TODO fail the application on the failed transition */ } if (oldState != getState()) { LOG.info(appID + " State change from " + oldState + " to " + getState()); } } finally { this.writeLock.unlock(); } } @Override public void recover(RMState state) { ApplicationStateData appState = state.getApplicationState().get(getApplicationId()); this.recoveredFinalState = appState.getState(); LOG.info("Recovering app: " + getApplicationId() + " with " + + appState.getAttemptCount() + " attempts and final state = " + this.recoveredFinalState ); this.diagnostics.append(appState.getDiagnostics()); this.storedFinishTime = appState.getFinishTime(); this.startTime = appState.getStartTime(); for(int i=0; i<appState.getAttemptCount(); ++i) { // create attempt createNewAttempt(); ((RMAppAttemptImpl)this.currentAttempt).recover(state); } } private void createNewAttempt() { ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(applicationId, attempts.size() + 1); RMAppAttempt attempt = new RMAppAttemptImpl(appAttemptId, rmContext, scheduler, masterService, submissionContext, conf, // The newly created attempt maybe last attempt if (number of // previously failed attempts(which should not include Preempted, // hardware error and NM resync) + 1) equal to the max-attempt // limit. maxAppAttempts == (getNumFailedAppAttempts() + 1), amReq); attempts.put(appAttemptId, attempt); currentAttempt = attempt; } private void createAndStartNewAttempt(boolean transferStateFromPreviousAttempt) { createNewAttempt(); handler.handle(new RMAppStartAttemptEvent(currentAttempt.getAppAttemptId(), transferStateFromPreviousAttempt)); } private void processNodeUpdate(RMAppNodeUpdateType type, RMNode node) { NodeState nodeState = node.getState(); updatedNodes.add(node); LOG.debug("Received node update event:" + type + " for node:" + node + " with state:" + nodeState); } private static class RMAppTransition implements SingleArcTransition<RMAppImpl, RMAppEvent> { public void transition(RMAppImpl app, RMAppEvent event) { }; } private static final class RMAppNodeUpdateTransition extends RMAppTransition { public void transition(RMAppImpl app, RMAppEvent event) { RMAppNodeUpdateEvent nodeUpdateEvent = (RMAppNodeUpdateEvent) event; app.processNodeUpdate(nodeUpdateEvent.getUpdateType(), nodeUpdateEvent.getNode()); }; } private static final class AppRunningOnNodeTransition extends RMAppTransition { public void transition(RMAppImpl app, RMAppEvent event) { RMAppRunningOnNodeEvent nodeAddedEvent = (RMAppRunningOnNodeEvent) event; // if final state already stored, notify RMNode if (isAppInFinalState(app)) { app.handler.handle( new RMNodeCleanAppEvent(nodeAddedEvent.getNodeId(), nodeAddedEvent .getApplicationId())); return; } // otherwise, add it to ranNodes for further process app.ranNodes.add(nodeAddedEvent.getNodeId()); if (!app.logAggregationStatus.containsKey(nodeAddedEvent.getNodeId())) { app.logAggregationStatus.put(nodeAddedEvent.getNodeId(), LogAggregationReport.newInstance(app.applicationId, app.logAggregationEnabled ? LogAggregationStatus.NOT_START : LogAggregationStatus.DISABLED, "")); } }; } /** * Move an app to a new queue. * This transition must set the result on the Future in the RMAppMoveEvent, * either as an exception for failure or null for success, or the client will * be left waiting forever. */ private static final class RMAppMoveTransition extends RMAppTransition { public void transition(RMAppImpl app, RMAppEvent event) { RMAppMoveEvent moveEvent = (RMAppMoveEvent) event; try { app.queue = app.scheduler.moveApplication(app.applicationId, moveEvent.getTargetQueue()); } catch (YarnException ex) { moveEvent.getResult().setException(ex); return; } // TODO: Write out change to state store (YARN-1558) // Also take care of RM failover moveEvent.getResult().set(null); } } // synchronously recover attempt to ensure any incoming external events // to be processed after the attempt processes the recover event. private void recoverAppAttempts() { for (RMAppAttempt attempt : getAppAttempts().values()) { attempt.handle(new RMAppAttemptEvent(attempt.getAppAttemptId(), RMAppAttemptEventType.RECOVER)); } } private static final class RMAppRecoveredTransition implements MultipleArcTransition<RMAppImpl, RMAppEvent, RMAppState> { @Override public RMAppState transition(RMAppImpl app, RMAppEvent event) { RMAppRecoverEvent recoverEvent = (RMAppRecoverEvent) event; app.recover(recoverEvent.getRMState()); // The app has completed. if (app.recoveredFinalState != null) { app.recoverAppAttempts(); new FinalTransition(app.recoveredFinalState).transition(app, event); return app.recoveredFinalState; } if (UserGroupInformation.isSecurityEnabled()) { // synchronously renew delegation token on recovery. try { app.rmContext.getDelegationTokenRenewer().addApplicationSync( app.getApplicationId(), app.parseCredentials(), app.submissionContext.getCancelTokensWhenComplete(), app.getUser()); } catch (Exception e) { String msg = "Failed to renew token for " + app.applicationId + " on recovery : " + e.getMessage(); app.diagnostics.append(msg); LOG.error(msg, e); } } // No existent attempts means the attempt associated with this app was not // started or started but not yet saved. if (app.attempts.isEmpty()) { app.scheduler.handle(new AppAddedSchedulerEvent(app.user, app.submissionContext, false)); return RMAppState.SUBMITTED; } // Add application to scheduler synchronously to guarantee scheduler // knows applications before AM or NM re-registers. app.scheduler.handle(new AppAddedSchedulerEvent(app.user, app.submissionContext, true)); // recover attempts app.recoverAppAttempts(); // Last attempt is in final state, return ACCEPTED waiting for last // RMAppAttempt to send finished or failed event back. if (app.currentAttempt != null && (app.currentAttempt.getState() == RMAppAttemptState.KILLED || app.currentAttempt.getState() == RMAppAttemptState.FINISHED || (app.currentAttempt.getState() == RMAppAttemptState.FAILED && app.getNumFailedAppAttempts() == app.maxAppAttempts))) { return RMAppState.ACCEPTED; } // YARN-1507 is saving the application state after the application is // accepted. So after YARN-1507, an app is saved meaning it is accepted. // Thus we return ACCECPTED state on recovery. return RMAppState.ACCEPTED; } } private static final class AddApplicationToSchedulerTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { app.handler.handle(new AppAddedSchedulerEvent(app.user, app.submissionContext, false)); } } private static final class StartAppAttemptTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { app.createAndStartNewAttempt(false); }; } private static final class FinalStateSavedTransition implements MultipleArcTransition<RMAppImpl, RMAppEvent, RMAppState> { @Override public RMAppState transition(RMAppImpl app, RMAppEvent event) { if (app.transitionTodo instanceof SingleArcTransition) { ((SingleArcTransition) app.transitionTodo).transition(app, app.eventCausingFinalSaving); } else if (app.transitionTodo instanceof MultipleArcTransition) { ((MultipleArcTransition) app.transitionTodo).transition(app, app.eventCausingFinalSaving); } return app.targetedFinalState; } } private static class AttemptFailedFinalStateSavedTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { String msg = null; if (event instanceof RMAppFailedAttemptEvent) { msg = app.getAppAttemptFailedDiagnostics(event); } LOG.info(msg); app.diagnostics.append(msg); // Inform the node for app-finish new FinalTransition(RMAppState.FAILED).transition(app, event); } } private String getAppAttemptFailedDiagnostics(RMAppEvent event) { String msg = null; RMAppFailedAttemptEvent failedEvent = (RMAppFailedAttemptEvent) event; if (this.submissionContext.getUnmanagedAM()) { // RM does not manage the AM. Do not retry msg = "Unmanaged application " + this.getApplicationId() + " failed due to " + failedEvent.getDiagnostics() + ". Failing the application."; } else if (this.isNumAttemptsBeyondThreshold) { int globalLimit = conf.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); msg = String.format( "Application %s failed %d times%s%s due to %s. Failing the application.", getApplicationId(), maxAppAttempts, (attemptFailuresValidityInterval <= 0 ? "" : (" in previous " + attemptFailuresValidityInterval + " milliseconds")), (globalLimit == maxAppAttempts) ? "" : (" (global limit =" + globalLimit + "; local limit is =" + maxAppAttempts + ")"), failedEvent.getDiagnostics()); } return msg; } private static final class RMAppNewlySavingTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { // If recovery is enabled then store the application information in a // non-blocking call so make sure that RM has stored the information // needed to restart the AM after RM restart without further client // communication LOG.info("Storing application with id " + app.applicationId); app.rmContext.getStateStore().storeNewApplication(app); } } private void rememberTargetTransitions(RMAppEvent event, Object transitionToDo, RMAppState targetFinalState) { transitionTodo = transitionToDo; targetedFinalState = targetFinalState; eventCausingFinalSaving = event; } private void rememberTargetTransitionsAndStoreState(RMAppEvent event, Object transitionToDo, RMAppState targetFinalState, RMAppState stateToBeStored) { rememberTargetTransitions(event, transitionToDo, targetFinalState); this.stateBeforeFinalSaving = getState(); this.storedFinishTime = this.systemClock.getTime(); LOG.info("Updating application " + this.applicationId + " with final state: " + this.targetedFinalState); // we lost attempt_finished diagnostics in app, because attempt_finished // diagnostics is sent after app final state is saved. Later on, we will // create GetApplicationAttemptReport specifically for getting per attempt // info. String diags = null; switch (event.getType()) { case APP_REJECTED: RMAppRejectedEvent rejectedEvent = (RMAppRejectedEvent) event; diags = rejectedEvent.getMessage(); break; case ATTEMPT_FINISHED: RMAppFinishedAttemptEvent finishedEvent = (RMAppFinishedAttemptEvent) event; diags = finishedEvent.getDiagnostics(); break; case ATTEMPT_FAILED: RMAppFailedAttemptEvent failedEvent = (RMAppFailedAttemptEvent) event; diags = getAppAttemptFailedDiagnostics(failedEvent); break; case ATTEMPT_KILLED: diags = getAppKilledDiagnostics(); break; default: break; } ApplicationStateData appState = ApplicationStateData.newInstance(this.submitTime, this.startTime, this.user, this.submissionContext, stateToBeStored, diags, this.storedFinishTime); this.rmContext.getStateStore().updateApplicationState(appState); } private static final class FinalSavingTransition extends RMAppTransition { Object transitionToDo; RMAppState targetedFinalState; RMAppState stateToBeStored; public FinalSavingTransition(Object transitionToDo, RMAppState targetedFinalState) { this(transitionToDo, targetedFinalState, targetedFinalState); } public FinalSavingTransition(Object transitionToDo, RMAppState targetedFinalState, RMAppState stateToBeStored) { this.transitionToDo = transitionToDo; this.targetedFinalState = targetedFinalState; this.stateToBeStored = stateToBeStored; } @Override public void transition(RMAppImpl app, RMAppEvent event) { app.rememberTargetTransitionsAndStoreState(event, transitionToDo, targetedFinalState, stateToBeStored); } } private static class AttemptUnregisteredTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { app.finishTime = app.storedFinishTime; } } private static class AppFinishedTransition extends FinalTransition { public AppFinishedTransition() { super(RMAppState.FINISHED); } public void transition(RMAppImpl app, RMAppEvent event) { RMAppFinishedAttemptEvent finishedEvent = (RMAppFinishedAttemptEvent)event; app.diagnostics.append(finishedEvent.getDiagnostics()); super.transition(app, event); }; } private static class AttemptFinishedAtFinalSavingTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { if (app.targetedFinalState.equals(RMAppState.FAILED) || app.targetedFinalState.equals(RMAppState.KILLED)) { // Ignore Attempt_Finished event if we were supposed to reach FAILED // FINISHED state return; } // pass in the earlier attempt_unregistered event, as it is needed in // AppFinishedFinalStateSavedTransition later on app.rememberTargetTransitions(event, new AppFinishedFinalStateSavedTransition(app.eventCausingFinalSaving), RMAppState.FINISHED); }; } private static class AppFinishedFinalStateSavedTransition extends RMAppTransition { RMAppEvent attemptUnregistered; public AppFinishedFinalStateSavedTransition(RMAppEvent attemptUnregistered) { this.attemptUnregistered = attemptUnregistered; } @Override public void transition(RMAppImpl app, RMAppEvent event) { new AttemptUnregisteredTransition().transition(app, attemptUnregistered); FINISHED_TRANSITION.transition(app, event); }; } private static class AppKilledTransition extends FinalTransition { public AppKilledTransition() { super(RMAppState.KILLED); } @Override public void transition(RMAppImpl app, RMAppEvent event) { app.diagnostics.append(getAppKilledDiagnostics()); super.transition(app, event); }; } private static String getAppKilledDiagnostics() { return "Application killed by user."; } private static class KillAttemptTransition extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { app.stateBeforeKilling = app.getState(); app.handler.handle(new RMAppAttemptEvent(app.currentAttempt .getAppAttemptId(), RMAppAttemptEventType.KILL)); } } private static final class AppRejectedTransition extends FinalTransition{ public AppRejectedTransition() { super(RMAppState.FAILED); } public void transition(RMAppImpl app, RMAppEvent event) { RMAppRejectedEvent rejectedEvent = (RMAppRejectedEvent)event; app.diagnostics.append(rejectedEvent.getMessage()); super.transition(app, event); }; } private static class FinalTransition extends RMAppTransition { private final RMAppState finalState; public FinalTransition(RMAppState finalState) { this.finalState = finalState; } public void transition(RMAppImpl app, RMAppEvent event) { app.logAggregationStartTime = System.currentTimeMillis(); for (NodeId nodeId : app.getRanNodes()) { app.handler.handle( new RMNodeCleanAppEvent(nodeId, app.applicationId)); } app.finishTime = app.storedFinishTime; if (app.finishTime == 0 ) { app.finishTime = app.systemClock.getTime(); } // Recovered apps that are completed were not added to scheduler, so no // need to remove them from scheduler. if (app.recoveredFinalState == null) { app.handler.handle(new AppRemovedSchedulerEvent(app.applicationId, finalState)); } app.handler.handle( new RMAppManagerEvent(app.applicationId, RMAppManagerEventType.APP_COMPLETED)); app.rmContext.getRMApplicationHistoryWriter() .applicationFinished(app, finalState); app.rmContext.getSystemMetricsPublisher() .appFinished(app, finalState, app.finishTime); }; } private int getNumFailedAppAttempts() { int completedAttempts = 0; long endTime = this.systemClock.getTime(); // Do not count AM preemption, hardware failures or NM resync // as attempt failure. for (RMAppAttempt attempt : attempts.values()) { if (attempt.shouldCountTowardsMaxAttemptRetry()) { if (this.attemptFailuresValidityInterval <= 0 || (attempt.getFinishTime() > endTime - this.attemptFailuresValidityInterval)) { completedAttempts++; } } } return completedAttempts; } private static final class AttemptFailedTransition implements MultipleArcTransition<RMAppImpl, RMAppEvent, RMAppState> { private final RMAppState initialState; public AttemptFailedTransition(RMAppState initialState) { this.initialState = initialState; } @Override public RMAppState transition(RMAppImpl app, RMAppEvent event) { int numberOfFailure = app.getNumFailedAppAttempts(); LOG.info("The number of failed attempts" + (app.attemptFailuresValidityInterval > 0 ? " in previous " + app.attemptFailuresValidityInterval + " milliseconds " : " ") + "is " + numberOfFailure + ". The max attempts is " + app.maxAppAttempts); if (!app.submissionContext.getUnmanagedAM() && numberOfFailure < app.maxAppAttempts) { if (initialState.equals(RMAppState.KILLING)) { // If this is not last attempt, app should be killed instead of // launching a new attempt app.rememberTargetTransitionsAndStoreState(event, new AppKilledTransition(), RMAppState.KILLED, RMAppState.KILLED); return RMAppState.FINAL_SAVING; } boolean transferStateFromPreviousAttempt; RMAppFailedAttemptEvent failedEvent = (RMAppFailedAttemptEvent) event; transferStateFromPreviousAttempt = failedEvent.getTransferStateFromPreviousAttempt(); RMAppAttempt oldAttempt = app.currentAttempt; app.createAndStartNewAttempt(transferStateFromPreviousAttempt); // Transfer the state from the previous attempt to the current attempt. // Note that the previous failed attempt may still be collecting the // container events from the scheduler and update its data structures // before the new attempt is created. We always transferState for // finished containers so that they can be acked to NM, // but when pulling finished container we will check this flag again. ((RMAppAttemptImpl) app.currentAttempt) .transferStateFromAttempt(oldAttempt); return initialState; } else { if (numberOfFailure >= app.maxAppAttempts) { app.isNumAttemptsBeyondThreshold = true; } app.rememberTargetTransitionsAndStoreState(event, new AttemptFailedFinalStateSavedTransition(), RMAppState.FAILED, RMAppState.FAILED); return RMAppState.FINAL_SAVING; } } } @Override public String getApplicationType() { return this.applicationType; } @Override public Set<String> getApplicationTags() { return this.applicationTags; } @Override public boolean isAppFinalStateStored() { RMAppState state = getState(); return state.equals(RMAppState.FINISHING) || state.equals(RMAppState.FINISHED) || state.equals(RMAppState.FAILED) || state.equals(RMAppState.KILLED); } @Override public YarnApplicationState createApplicationState() { RMAppState rmAppState = getState(); // If App is in FINAL_SAVING state, return its previous state. if (rmAppState.equals(RMAppState.FINAL_SAVING)) { rmAppState = stateBeforeFinalSaving; } if (rmAppState.equals(RMAppState.KILLING)) { rmAppState = stateBeforeKilling; } return RMServerUtils.createApplicationState(rmAppState); } public static boolean isAppInFinalState(RMApp rmApp) { RMAppState appState = ((RMAppImpl) rmApp).getRecoveredFinalState(); if (appState == null) { appState = rmApp.getState(); } return appState == RMAppState.FAILED || appState == RMAppState.FINISHED || appState == RMAppState.KILLED; } private RMAppState getRecoveredFinalState() { return this.recoveredFinalState; } @Override public Set<NodeId> getRanNodes() { return ranNodes; } @Override public RMAppMetrics getRMAppMetrics() { Resource resourcePreempted = Resource.newInstance(0, 0); int numAMContainerPreempted = 0; int numNonAMContainerPreempted = 0; long memorySeconds = 0; long vcoreSeconds = 0; for (RMAppAttempt attempt : attempts.values()) { if (null != attempt) { RMAppAttemptMetrics attemptMetrics = attempt.getRMAppAttemptMetrics(); Resources.addTo(resourcePreempted, attemptMetrics.getResourcePreempted()); numAMContainerPreempted += attemptMetrics.getIsPreempted() ? 1 : 0; numNonAMContainerPreempted += attemptMetrics.getNumNonAMContainersPreempted(); // getAggregateAppResourceUsage() will calculate resource usage stats // for both running and finished containers. AggregateAppResourceUsage resUsage = attempt.getRMAppAttemptMetrics().getAggregateAppResourceUsage(); memorySeconds += resUsage.getMemorySeconds(); vcoreSeconds += resUsage.getVcoreSeconds(); } } return new RMAppMetrics(resourcePreempted, numNonAMContainerPreempted, numAMContainerPreempted, memorySeconds, vcoreSeconds); } @Private @VisibleForTesting public void setSystemClock(Clock clock) { this.systemClock = clock; } @Override public ReservationId getReservationId() { return submissionContext.getReservationID(); } @Override public ResourceRequest getAMResourceRequest() { return this.amReq; } protected Credentials parseCredentials() throws IOException { Credentials credentials = new Credentials(); DataInputByteBuffer dibb = new DataInputByteBuffer(); ByteBuffer tokens = submissionContext.getAMContainerSpec().getTokens(); if (tokens != null) { dibb.reset(tokens); credentials.readTokenStorageStream(dibb); tokens.rewind(); } return credentials; } @Override public Map<NodeId, LogAggregationReport> getLogAggregationReportsForApp() { try { this.readLock.lock(); Map<NodeId, LogAggregationReport> outputs = new HashMap<NodeId, LogAggregationReport>(); outputs.putAll(logAggregationStatus); if (!isLogAggregationFinished()) { for (Entry<NodeId, LogAggregationReport> output : outputs.entrySet()) { if (!output.getValue().getLogAggregationStatus() .equals(LogAggregationStatus.TIME_OUT) && !output.getValue().getLogAggregationStatus() .equals(LogAggregationStatus.SUCCEEDED) && !output.getValue().getLogAggregationStatus() .equals(LogAggregationStatus.FAILED) && isAppInFinalState(this) && System.currentTimeMillis() > this.logAggregationStartTime + this.logAggregationStatusTimeout) { output.getValue().setLogAggregationStatus( LogAggregationStatus.TIME_OUT); } } } return outputs; } finally { this.readLock.unlock(); } } public void aggregateLogReport(NodeId nodeId, LogAggregationReport report) { try { this.writeLock.lock(); if (this.logAggregationEnabled && !isLogAggregationFinished()) { LogAggregationReport curReport = this.logAggregationStatus.get(nodeId); boolean stateChangedToFinal = false; if (curReport == null) { this.logAggregationStatus.put(nodeId, report); if (isLogAggregationFinishedForNM(report)) { stateChangedToFinal = true; } } else { if (isLogAggregationFinishedForNM(report)) { if (!isLogAggregationFinishedForNM(curReport)) { stateChangedToFinal = true; } } if (report.getLogAggregationStatus() != LogAggregationStatus.RUNNING || curReport.getLogAggregationStatus() != LogAggregationStatus.RUNNING_WITH_FAILURE) { if (curReport.getLogAggregationStatus() == LogAggregationStatus.TIME_OUT && report.getLogAggregationStatus() == LogAggregationStatus.RUNNING) { // If the log aggregation status got from latest nm heartbeat // is Running, and current log aggregation status is TimeOut, // based on whether there are any failure messages for this NM, // we will reset the log aggregation status as RUNNING or // RUNNING_WITH_FAILURE if (logAggregationFailureMessagesForNMs.get(nodeId) != null && !logAggregationFailureMessagesForNMs.get(nodeId).isEmpty()) { report.setLogAggregationStatus( LogAggregationStatus.RUNNING_WITH_FAILURE); } } curReport.setLogAggregationStatus(report .getLogAggregationStatus()); } } updateLogAggregationDiagnosticMessages(nodeId, report); if (isAppInFinalState(this) && stateChangedToFinal) { updateLogAggregationStatus(nodeId); } } } finally { this.writeLock.unlock(); } } @Override public LogAggregationStatus getLogAggregationStatusForAppReport() { try { this.readLock.lock(); if (! logAggregationEnabled) { return LogAggregationStatus.DISABLED; } if (isLogAggregationFinished()) { return this.logAggregationStatusForAppReport; } Map<NodeId, LogAggregationReport> reports = getLogAggregationReportsForApp(); if (reports.size() == 0) { return this.logAggregationStatusForAppReport; } int logNotStartCount = 0; int logCompletedCount = 0; int logTimeOutCount = 0; int logFailedCount = 0; int logRunningWithFailure = 0; for (Entry<NodeId, LogAggregationReport> report : reports.entrySet()) { switch (report.getValue().getLogAggregationStatus()) { case NOT_START: logNotStartCount++; break; case RUNNING_WITH_FAILURE: logRunningWithFailure ++; break; case SUCCEEDED: logCompletedCount++; break; case FAILED: logFailedCount++; logCompletedCount++; break; case TIME_OUT: logTimeOutCount++; logCompletedCount++; break; default: break; } } if (logNotStartCount == reports.size()) { return LogAggregationStatus.NOT_START; } else if (logCompletedCount == reports.size()) { // We should satisfy two condition in order to return SUCCEEDED or FAILED // 1) make sure the application is in final state // 2) logs status from all NMs are SUCCEEDED/FAILED/TIMEOUT // The SUCCEEDED/FAILED status is the final status which means // the log aggregation is finished. And the log aggregation status will // not be updated anymore. if (logFailedCount > 0 && isAppInFinalState(this)) { return LogAggregationStatus.FAILED; } else if (logTimeOutCount > 0) { return LogAggregationStatus.TIME_OUT; } if (isAppInFinalState(this)) { return LogAggregationStatus.SUCCEEDED; } } else if (logRunningWithFailure > 0) { return LogAggregationStatus.RUNNING_WITH_FAILURE; } return LogAggregationStatus.RUNNING; } finally { this.readLock.unlock(); } } private boolean isLogAggregationFinished() { return this.logAggregationStatusForAppReport .equals(LogAggregationStatus.SUCCEEDED) || this.logAggregationStatusForAppReport .equals(LogAggregationStatus.FAILED); } private boolean isLogAggregationFinishedForNM(LogAggregationReport report) { return report.getLogAggregationStatus() == LogAggregationStatus.SUCCEEDED || report.getLogAggregationStatus() == LogAggregationStatus.FAILED; } private void updateLogAggregationDiagnosticMessages(NodeId nodeId, LogAggregationReport report) { if (report.getDiagnosticMessage() != null && !report.getDiagnosticMessage().isEmpty()) { if (report.getLogAggregationStatus() == LogAggregationStatus.RUNNING ) { List<String> diagnostics = logAggregationDiagnosticsForNMs.get(nodeId); if (diagnostics == null) { diagnostics = new ArrayList<String>(); logAggregationDiagnosticsForNMs.put(nodeId, diagnostics); } else { if (diagnostics.size() == maxLogAggregationDiagnosticsInMemory) { diagnostics.remove(0); } } diagnostics.add(report.getDiagnosticMessage()); this.logAggregationStatus.get(nodeId).setDiagnosticMessage( StringUtils.join(diagnostics, "\n")); } else if (report.getLogAggregationStatus() == LogAggregationStatus.RUNNING_WITH_FAILURE) { List<String> failureMessages = logAggregationFailureMessagesForNMs.get(nodeId); if (failureMessages == null) { failureMessages = new ArrayList<String>(); logAggregationFailureMessagesForNMs.put(nodeId, failureMessages); } else { if (failureMessages.size() == maxLogAggregationDiagnosticsInMemory) { failureMessages.remove(0); } } failureMessages.add(report.getDiagnosticMessage()); } } } private void updateLogAggregationStatus(NodeId nodeId) { LogAggregationStatus status = this.logAggregationStatus.get(nodeId).getLogAggregationStatus(); if (status.equals(LogAggregationStatus.SUCCEEDED)) { this.logAggregationSucceed++; } else if (status.equals(LogAggregationStatus.FAILED)) { this.logAggregationFailed++; } if (this.logAggregationSucceed == this.logAggregationStatus.size()) { this.logAggregationStatusForAppReport = LogAggregationStatus.SUCCEEDED; // Since the log aggregation status for this application for all NMs // is SUCCEEDED, it means all logs are aggregated successfully. // We could remove all the cached log aggregation reports this.logAggregationStatus.clear(); this.logAggregationDiagnosticsForNMs.clear(); this.logAggregationFailureMessagesForNMs.clear(); } else if (this.logAggregationSucceed + this.logAggregationFailed == this.logAggregationStatus.size()) { this.logAggregationStatusForAppReport = LogAggregationStatus.FAILED; // We have collected the log aggregation status for all NMs. // The log aggregation status is FAILED which means the log // aggregation fails in some NMs. We are only interested in the // nodes where the log aggregation is failed. So we could remove // the log aggregation details for those succeeded NMs for (Iterator<Map.Entry<NodeId, LogAggregationReport>> it = this.logAggregationStatus.entrySet().iterator(); it.hasNext();) { Map.Entry<NodeId, LogAggregationReport> entry = it.next(); if (entry.getValue().getLogAggregationStatus() .equals(LogAggregationStatus.SUCCEEDED)) { it.remove(); } } // the log aggregation has finished/failed. // and the status will not be updated anymore. this.logAggregationDiagnosticsForNMs.clear(); } } public String getLogAggregationFailureMessagesForNM(NodeId nodeId) { try { this.readLock.lock(); List<String> failureMessages = this.logAggregationFailureMessagesForNMs.get(nodeId); if (failureMessages == null || failureMessages.isEmpty()) { return StringUtils.EMPTY; } return StringUtils.join(failureMessages, "\n"); } finally { this.readLock.unlock(); } } }
64,882
37.782427
100
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppFinishedAttemptEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp; import org.apache.hadoop.yarn.api.records.ApplicationId; public class RMAppFinishedAttemptEvent extends RMAppEvent { private final String diagnostics; public RMAppFinishedAttemptEvent(ApplicationId appId, String diagnostics) { super(appId, RMAppEventType.ATTEMPT_FINISHED); this.diagnostics = diagnostics; } public String getDiagnostics() { return this.diagnostics; } }
1,266
34.194444
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import static org.apache.hadoop.yarn.util.StringHelper.pjoin; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import javax.crypto.SecretKey; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationAttemptReport; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.YarnApplicationAttemptState; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.security.client.ClientToAMTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService; import org.apache.hadoop.yarn.server.resourcemanager.ClusterMetrics; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMServerUtils; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncherEvent; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncherEventType; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.Recoverable; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppFailedAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppFinishedAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptContainerAllocatedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptContainerFinishedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptLaunchFailedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptRegistrationEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptStatusupdateEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptUnregistrationEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeFinishedContainersPulledByAMEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.webproxy.ProxyUriUtils; import org.apache.hadoop.yarn.state.InvalidStateTransitionException; import org.apache.hadoop.yarn.state.MultipleArcTransition; import org.apache.hadoop.yarn.state.SingleArcTransition; import org.apache.hadoop.yarn.state.StateMachine; import org.apache.hadoop.yarn.state.StateMachineFactory; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import com.google.common.annotations.VisibleForTesting; @SuppressWarnings({"unchecked", "rawtypes"}) public class RMAppAttemptImpl implements RMAppAttempt, Recoverable { private static final Log LOG = LogFactory.getLog(RMAppAttemptImpl.class); private static final RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); public final static Priority AM_CONTAINER_PRIORITY = recordFactory .newRecordInstance(Priority.class); static { AM_CONTAINER_PRIORITY.setPriority(0); } private final StateMachine<RMAppAttemptState, RMAppAttemptEventType, RMAppAttemptEvent> stateMachine; private final RMContext rmContext; private final EventHandler eventHandler; private final YarnScheduler scheduler; private final ApplicationMasterService masterService; private final ReadLock readLock; private final WriteLock writeLock; private final ApplicationAttemptId applicationAttemptId; private final ApplicationSubmissionContext submissionContext; private Token<AMRMTokenIdentifier> amrmToken = null; private volatile Integer amrmTokenKeyId = null; private SecretKey clientTokenMasterKey = null; private ConcurrentMap<NodeId, List<ContainerStatus>> justFinishedContainers = new ConcurrentHashMap<NodeId, List<ContainerStatus>>(); // Tracks the previous finished containers that are waiting to be // verified as received by the AM. If the AM sends the next allocate // request it implicitly acks this list. private ConcurrentMap<NodeId, List<ContainerStatus>> finishedContainersSentToAM = new ConcurrentHashMap<NodeId, List<ContainerStatus>>(); private volatile Container masterContainer; private float progress = 0; private String host = "N/A"; private int rpcPort = -1; private String originalTrackingUrl = "N/A"; private String proxiedTrackingUrl = "N/A"; private long startTime = 0; private long finishTime = 0; private long launchAMStartTime = 0; private long launchAMEndTime = 0; // Set to null initially. Will eventually get set // if an RMAppAttemptUnregistrationEvent occurs private FinalApplicationStatus finalStatus = null; private final StringBuilder diagnostics = new StringBuilder(); private int amContainerExitStatus = ContainerExitStatus.INVALID; private Configuration conf; // Since AM preemption, hardware error and NM resync are not counted towards // AM failure count, even if this flag is true, a new attempt can still be // re-created if this attempt is eventually failed because of preemption, // hardware error or NM resync. So this flag indicates that this may be // last attempt. private final boolean maybeLastAttempt; private static final ExpiredTransition EXPIRED_TRANSITION = new ExpiredTransition(); private RMAppAttemptEvent eventCausingFinalSaving; private RMAppAttemptState targetedFinalState; private RMAppAttemptState recoveredFinalState; private RMAppAttemptState stateBeforeFinalSaving; private Object transitionTodo; private RMAppAttemptMetrics attemptMetrics = null; private ResourceRequest amReq = null; private static final StateMachineFactory<RMAppAttemptImpl, RMAppAttemptState, RMAppAttemptEventType, RMAppAttemptEvent> stateMachineFactory = new StateMachineFactory<RMAppAttemptImpl, RMAppAttemptState, RMAppAttemptEventType, RMAppAttemptEvent>(RMAppAttemptState.NEW) // Transitions from NEW State .addTransition(RMAppAttemptState.NEW, RMAppAttemptState.SUBMITTED, RMAppAttemptEventType.START, new AttemptStartedTransition()) .addTransition(RMAppAttemptState.NEW, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new BaseFinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) .addTransition(RMAppAttemptState.NEW, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.REGISTERED, new FinalSavingTransition( new UnexpectedAMRegisteredTransition(), RMAppAttemptState.FAILED)) .addTransition( RMAppAttemptState.NEW, EnumSet.of(RMAppAttemptState.FINISHED, RMAppAttemptState.KILLED, RMAppAttemptState.FAILED, RMAppAttemptState.LAUNCHED), RMAppAttemptEventType.RECOVER, new AttemptRecoveredTransition()) // Transitions from SUBMITTED state .addTransition(RMAppAttemptState.SUBMITTED, EnumSet.of(RMAppAttemptState.LAUNCHED_UNMANAGED_SAVING, RMAppAttemptState.SCHEDULED), RMAppAttemptEventType.ATTEMPT_ADDED, new ScheduleTransition()) .addTransition(RMAppAttemptState.SUBMITTED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new BaseFinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) .addTransition(RMAppAttemptState.SUBMITTED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.REGISTERED, new FinalSavingTransition( new UnexpectedAMRegisteredTransition(), RMAppAttemptState.FAILED)) // Transitions from SCHEDULED State .addTransition(RMAppAttemptState.SCHEDULED, EnumSet.of(RMAppAttemptState.ALLOCATED_SAVING, RMAppAttemptState.SCHEDULED), RMAppAttemptEventType.CONTAINER_ALLOCATED, new AMContainerAllocatedTransition()) .addTransition(RMAppAttemptState.SCHEDULED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new BaseFinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) .addTransition(RMAppAttemptState.SCHEDULED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.CONTAINER_FINISHED, new FinalSavingTransition( new AMContainerCrashedBeforeRunningTransition(), RMAppAttemptState.FAILED)) // Transitions from ALLOCATED_SAVING State .addTransition(RMAppAttemptState.ALLOCATED_SAVING, RMAppAttemptState.ALLOCATED, RMAppAttemptEventType.ATTEMPT_NEW_SAVED, new AttemptStoredTransition()) // App could be killed by the client. So need to handle this. .addTransition(RMAppAttemptState.ALLOCATED_SAVING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new BaseFinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) .addTransition(RMAppAttemptState.ALLOCATED_SAVING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.CONTAINER_FINISHED, new FinalSavingTransition( new AMContainerCrashedBeforeRunningTransition(), RMAppAttemptState.FAILED)) // Transitions from LAUNCHED_UNMANAGED_SAVING State .addTransition(RMAppAttemptState.LAUNCHED_UNMANAGED_SAVING, RMAppAttemptState.LAUNCHED, RMAppAttemptEventType.ATTEMPT_NEW_SAVED, new UnmanagedAMAttemptSavedTransition()) // attempt should not try to register in this state .addTransition(RMAppAttemptState.LAUNCHED_UNMANAGED_SAVING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.REGISTERED, new FinalSavingTransition( new UnexpectedAMRegisteredTransition(), RMAppAttemptState.FAILED)) // App could be killed by the client. So need to handle this. .addTransition(RMAppAttemptState.LAUNCHED_UNMANAGED_SAVING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new BaseFinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) // Transitions from ALLOCATED State .addTransition(RMAppAttemptState.ALLOCATED, RMAppAttemptState.LAUNCHED, RMAppAttemptEventType.LAUNCHED, new AMLaunchedTransition()) .addTransition(RMAppAttemptState.ALLOCATED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.LAUNCH_FAILED, new FinalSavingTransition(new LaunchFailedTransition(), RMAppAttemptState.FAILED)) .addTransition(RMAppAttemptState.ALLOCATED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition( new KillAllocatedAMTransition(), RMAppAttemptState.KILLED)) .addTransition(RMAppAttemptState.ALLOCATED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.CONTAINER_FINISHED, new FinalSavingTransition( new AMContainerCrashedBeforeRunningTransition(), RMAppAttemptState.FAILED)) // Transitions from LAUNCHED State .addTransition(RMAppAttemptState.LAUNCHED, RMAppAttemptState.RUNNING, RMAppAttemptEventType.REGISTERED, new AMRegisteredTransition()) .addTransition(RMAppAttemptState.LAUNCHED, EnumSet.of(RMAppAttemptState.LAUNCHED, RMAppAttemptState.FINAL_SAVING), RMAppAttemptEventType.CONTAINER_FINISHED, new ContainerFinishedTransition( new AMContainerCrashedBeforeRunningTransition(), RMAppAttemptState.LAUNCHED)) .addTransition( RMAppAttemptState.LAUNCHED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.EXPIRE, new FinalSavingTransition(EXPIRED_TRANSITION, RMAppAttemptState.FAILED)) .addTransition(RMAppAttemptState.LAUNCHED, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new FinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) // Transitions from RUNNING State .addTransition(RMAppAttemptState.RUNNING, EnumSet.of(RMAppAttemptState.FINAL_SAVING, RMAppAttemptState.FINISHED), RMAppAttemptEventType.UNREGISTERED, new AMUnregisteredTransition()) .addTransition(RMAppAttemptState.RUNNING, RMAppAttemptState.RUNNING, RMAppAttemptEventType.STATUS_UPDATE, new StatusUpdateTransition()) .addTransition(RMAppAttemptState.RUNNING, RMAppAttemptState.RUNNING, RMAppAttemptEventType.CONTAINER_ALLOCATED) .addTransition( RMAppAttemptState.RUNNING, EnumSet.of(RMAppAttemptState.RUNNING, RMAppAttemptState.FINAL_SAVING), RMAppAttemptEventType.CONTAINER_FINISHED, new ContainerFinishedTransition( new AMContainerCrashedAtRunningTransition(), RMAppAttemptState.RUNNING)) .addTransition( RMAppAttemptState.RUNNING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.EXPIRE, new FinalSavingTransition(EXPIRED_TRANSITION, RMAppAttemptState.FAILED)) .addTransition( RMAppAttemptState.RUNNING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.KILL, new FinalSavingTransition(new FinalTransition( RMAppAttemptState.KILLED), RMAppAttemptState.KILLED)) // Transitions from FINAL_SAVING State .addTransition(RMAppAttemptState.FINAL_SAVING, EnumSet.of(RMAppAttemptState.FINISHING, RMAppAttemptState.FAILED, RMAppAttemptState.KILLED, RMAppAttemptState.FINISHED), RMAppAttemptEventType.ATTEMPT_UPDATE_SAVED, new FinalStateSavedTransition()) .addTransition(RMAppAttemptState.FINAL_SAVING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.CONTAINER_FINISHED, new ContainerFinishedAtFinalSavingTransition()) .addTransition(RMAppAttemptState.FINAL_SAVING, RMAppAttemptState.FINAL_SAVING, RMAppAttemptEventType.EXPIRE, new AMExpiredAtFinalSavingTransition()) .addTransition(RMAppAttemptState.FINAL_SAVING, RMAppAttemptState.FINAL_SAVING, EnumSet.of( RMAppAttemptEventType.UNREGISTERED, RMAppAttemptEventType.STATUS_UPDATE, RMAppAttemptEventType.LAUNCHED, RMAppAttemptEventType.LAUNCH_FAILED, // should be fixed to reject container allocate request at Final // Saving in scheduler RMAppAttemptEventType.CONTAINER_ALLOCATED, RMAppAttemptEventType.ATTEMPT_NEW_SAVED, RMAppAttemptEventType.KILL)) // Transitions from FAILED State // For work-preserving AM restart, failed attempt are still capturing // CONTAINER_FINISHED event and record the finished containers for the // use by the next new attempt. .addTransition(RMAppAttemptState.FAILED, RMAppAttemptState.FAILED, RMAppAttemptEventType.CONTAINER_FINISHED, new ContainerFinishedAtFinalStateTransition()) .addTransition( RMAppAttemptState.FAILED, RMAppAttemptState.FAILED, EnumSet.of( RMAppAttemptEventType.EXPIRE, RMAppAttemptEventType.KILL, RMAppAttemptEventType.UNREGISTERED, RMAppAttemptEventType.STATUS_UPDATE, RMAppAttemptEventType.CONTAINER_ALLOCATED)) // Transitions from FINISHING State .addTransition(RMAppAttemptState.FINISHING, EnumSet.of(RMAppAttemptState.FINISHING, RMAppAttemptState.FINISHED), RMAppAttemptEventType.CONTAINER_FINISHED, new AMFinishingContainerFinishedTransition()) .addTransition(RMAppAttemptState.FINISHING, RMAppAttemptState.FINISHED, RMAppAttemptEventType.EXPIRE, new FinalTransition(RMAppAttemptState.FINISHED)) .addTransition(RMAppAttemptState.FINISHING, RMAppAttemptState.FINISHING, EnumSet.of( RMAppAttemptEventType.UNREGISTERED, RMAppAttemptEventType.STATUS_UPDATE, RMAppAttemptEventType.CONTAINER_ALLOCATED, // ignore Kill as we have already saved the final Finished state in // state store. RMAppAttemptEventType.KILL)) // Transitions from FINISHED State .addTransition( RMAppAttemptState.FINISHED, RMAppAttemptState.FINISHED, EnumSet.of( RMAppAttemptEventType.EXPIRE, RMAppAttemptEventType.UNREGISTERED, RMAppAttemptEventType.CONTAINER_ALLOCATED, RMAppAttemptEventType.KILL)) .addTransition(RMAppAttemptState.FINISHED, RMAppAttemptState.FINISHED, RMAppAttemptEventType.CONTAINER_FINISHED, new ContainerFinishedAtFinalStateTransition()) // Transitions from KILLED State .addTransition( RMAppAttemptState.KILLED, RMAppAttemptState.KILLED, EnumSet.of(RMAppAttemptEventType.ATTEMPT_ADDED, RMAppAttemptEventType.LAUNCHED, RMAppAttemptEventType.LAUNCH_FAILED, RMAppAttemptEventType.EXPIRE, RMAppAttemptEventType.REGISTERED, RMAppAttemptEventType.CONTAINER_ALLOCATED, RMAppAttemptEventType.UNREGISTERED, RMAppAttemptEventType.KILL, RMAppAttemptEventType.STATUS_UPDATE)) .addTransition(RMAppAttemptState.KILLED, RMAppAttemptState.KILLED, RMAppAttemptEventType.CONTAINER_FINISHED, new ContainerFinishedAtFinalStateTransition()) .installTopology(); public RMAppAttemptImpl(ApplicationAttemptId appAttemptId, RMContext rmContext, YarnScheduler scheduler, ApplicationMasterService masterService, ApplicationSubmissionContext submissionContext, Configuration conf, boolean maybeLastAttempt, ResourceRequest amReq) { this.conf = conf; this.applicationAttemptId = appAttemptId; this.rmContext = rmContext; this.eventHandler = rmContext.getDispatcher().getEventHandler(); this.submissionContext = submissionContext; this.scheduler = scheduler; this.masterService = masterService; ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); this.proxiedTrackingUrl = generateProxyUriWithScheme(); this.maybeLastAttempt = maybeLastAttempt; this.stateMachine = stateMachineFactory.make(this); this.attemptMetrics = new RMAppAttemptMetrics(applicationAttemptId, rmContext); this.amReq = amReq; } @Override public ApplicationAttemptId getAppAttemptId() { return this.applicationAttemptId; } @Override public ApplicationSubmissionContext getSubmissionContext() { return this.submissionContext; } @Override public FinalApplicationStatus getFinalApplicationStatus() { this.readLock.lock(); try { return this.finalStatus; } finally { this.readLock.unlock(); } } @Override public RMAppAttemptState getAppAttemptState() { this.readLock.lock(); try { return this.stateMachine.getCurrentState(); } finally { this.readLock.unlock(); } } @Override public String getHost() { this.readLock.lock(); try { return this.host; } finally { this.readLock.unlock(); } } @Override public int getRpcPort() { this.readLock.lock(); try { return this.rpcPort; } finally { this.readLock.unlock(); } } @Override public String getTrackingUrl() { this.readLock.lock(); try { return (getSubmissionContext().getUnmanagedAM()) ? this.originalTrackingUrl : this.proxiedTrackingUrl; } finally { this.readLock.unlock(); } } @Override public String getOriginalTrackingUrl() { this.readLock.lock(); try { return this.originalTrackingUrl; } finally { this.readLock.unlock(); } } @Override public String getWebProxyBase() { this.readLock.lock(); try { return ProxyUriUtils.getPath(applicationAttemptId.getApplicationId()); } finally { this.readLock.unlock(); } } private String generateProxyUriWithScheme() { this.readLock.lock(); try { final String scheme = WebAppUtils.getHttpSchemePrefix(conf); String proxy = WebAppUtils.getProxyHostAndPort(conf); URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy); URI result = ProxyUriUtils.getProxyUri(null, proxyUri, applicationAttemptId.getApplicationId()); return result.toASCIIString(); } catch (URISyntaxException e) { LOG.warn("Could not proxify the uri for " + applicationAttemptId.getApplicationId(), e); return null; } finally { this.readLock.unlock(); } } private void setTrackingUrlToRMAppPage(RMAppAttemptState stateToBeStored) { originalTrackingUrl = pjoin( WebAppUtils.getResolvedRMWebAppURLWithScheme(conf), "cluster", "app", getAppAttemptId().getApplicationId()); switch (stateToBeStored) { case KILLED: case FAILED: proxiedTrackingUrl = originalTrackingUrl; break; default: break; } } private void invalidateAMHostAndPort() { this.host = "N/A"; this.rpcPort = -1; } // This is only used for RMStateStore. Normal operation must invoke the secret // manager to get the key and not use the local key directly. @Override public SecretKey getClientTokenMasterKey() { return this.clientTokenMasterKey; } @Override public Token<AMRMTokenIdentifier> getAMRMToken() { this.readLock.lock(); try { return this.amrmToken; } finally { this.readLock.unlock(); } } @Private public void setAMRMToken(Token<AMRMTokenIdentifier> lastToken) { this.writeLock.lock(); try { this.amrmToken = lastToken; this.amrmTokenKeyId = null; } finally { this.writeLock.unlock(); } } @Private public int getAMRMTokenKeyId() { Integer keyId = this.amrmTokenKeyId; if (keyId == null) { this.readLock.lock(); try { if (this.amrmToken == null) { throw new YarnRuntimeException("Missing AMRM token for " + this.applicationAttemptId); } keyId = this.amrmToken.decodeIdentifier().getKeyId(); this.amrmTokenKeyId = keyId; } catch (IOException e) { throw new YarnRuntimeException("AMRM token decode error for " + this.applicationAttemptId, e); } finally { this.readLock.unlock(); } } return keyId; } @Override public Token<ClientToAMTokenIdentifier> createClientToken(String client) { this.readLock.lock(); try { Token<ClientToAMTokenIdentifier> token = null; ClientToAMTokenSecretManagerInRM secretMgr = this.rmContext.getClientToAMTokenSecretManager(); if (client != null && secretMgr.getMasterKey(this.applicationAttemptId) != null) { token = new Token<ClientToAMTokenIdentifier>( new ClientToAMTokenIdentifier(this.applicationAttemptId, client), secretMgr); } return token; } finally { this.readLock.unlock(); } } @Override public String getDiagnostics() { this.readLock.lock(); try { return this.diagnostics.toString(); } finally { this.readLock.unlock(); } } public int getAMContainerExitStatus() { this.readLock.lock(); try { return this.amContainerExitStatus; } finally { this.readLock.unlock(); } } @Override public float getProgress() { this.readLock.lock(); try { return this.progress; } finally { this.readLock.unlock(); } } @VisibleForTesting @Override public List<ContainerStatus> getJustFinishedContainers() { this.readLock.lock(); try { List<ContainerStatus> returnList = new ArrayList<ContainerStatus>(); for (Collection<ContainerStatus> containerStatusList : justFinishedContainers.values()) { returnList.addAll(containerStatusList); } return returnList; } finally { this.readLock.unlock(); } } @Override public ConcurrentMap<NodeId, List<ContainerStatus>> getJustFinishedContainersReference () { this.readLock.lock(); try { return this.justFinishedContainers; } finally { this.readLock.unlock(); } } @Override public ConcurrentMap<NodeId, List<ContainerStatus>> getFinishedContainersSentToAMReference() { this.readLock.lock(); try { return this.finishedContainersSentToAM; } finally { this.readLock.unlock(); } } @Override public List<ContainerStatus> pullJustFinishedContainers() { this.writeLock.lock(); try { List<ContainerStatus> returnList = new ArrayList<ContainerStatus>(); // A new allocate means the AM received the previously sent // finishedContainers. We can ack this to NM now sendFinishedContainersToNM(); // Mark every containerStatus as being sent to AM though we may return // only the ones that belong to the current attempt boolean keepContainersAcressAttempts = this.submissionContext .getKeepContainersAcrossApplicationAttempts(); for (NodeId nodeId:justFinishedContainers.keySet()) { // Clear and get current values List<ContainerStatus> finishedContainers = justFinishedContainers.put (nodeId, new ArrayList<ContainerStatus>()); if (keepContainersAcressAttempts) { returnList.addAll(finishedContainers); } else { // Filter out containers from previous attempt for (ContainerStatus containerStatus: finishedContainers) { if (containerStatus.getContainerId().getApplicationAttemptId() .equals(this.getAppAttemptId())) { returnList.add(containerStatus); } } } finishedContainersSentToAM.putIfAbsent(nodeId, new ArrayList <ContainerStatus>()); finishedContainersSentToAM.get(nodeId).addAll(finishedContainers); } return returnList; } finally { this.writeLock.unlock(); } } @Override public Container getMasterContainer() { return this.masterContainer; } @InterfaceAudience.Private @VisibleForTesting public void setMasterContainer(Container container) { masterContainer = container; } @Override public void handle(RMAppAttemptEvent event) { this.writeLock.lock(); try { ApplicationAttemptId appAttemptID = event.getApplicationAttemptId(); LOG.debug("Processing event for " + appAttemptID + " of type " + event.getType()); final RMAppAttemptState oldState = getAppAttemptState(); try { /* keep the master in sync with the state machine */ this.stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitionException e) { LOG.error("Can't handle this event at current state", e); /* TODO fail the application on the failed transition */ } if (oldState != getAppAttemptState()) { LOG.info(appAttemptID + " State change from " + oldState + " to " + getAppAttemptState()); } } finally { this.writeLock.unlock(); } } @Override public ApplicationResourceUsageReport getApplicationResourceUsageReport() { this.readLock.lock(); try { ApplicationResourceUsageReport report = scheduler.getAppResourceUsageReport(this.getAppAttemptId()); if (report == null) { report = RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT; } AggregateAppResourceUsage resUsage = this.attemptMetrics.getAggregateAppResourceUsage(); report.setMemorySeconds(resUsage.getMemorySeconds()); report.setVcoreSeconds(resUsage.getVcoreSeconds()); return report; } finally { this.readLock.unlock(); } } @Override public void recover(RMState state) { ApplicationStateData appState = state.getApplicationState().get(getAppAttemptId().getApplicationId()); ApplicationAttemptStateData attemptState = appState.getAttempt(getAppAttemptId()); assert attemptState != null; LOG.info("Recovering attempt: " + getAppAttemptId() + " with final state: " + attemptState.getState()); diagnostics.append("Attempt recovered after RM restart"); diagnostics.append(attemptState.getDiagnostics()); this.amContainerExitStatus = attemptState.getAMContainerExitStatus(); if (amContainerExitStatus == ContainerExitStatus.PREEMPTED) { this.attemptMetrics.setIsPreempted(); } Credentials credentials = attemptState.getAppAttemptTokens(); setMasterContainer(attemptState.getMasterContainer()); recoverAppAttemptCredentials(credentials, attemptState.getState()); this.recoveredFinalState = attemptState.getState(); this.originalTrackingUrl = attemptState.getFinalTrackingUrl(); this.finalStatus = attemptState.getFinalApplicationStatus(); this.startTime = attemptState.getStartTime(); this.finishTime = attemptState.getFinishTime(); this.attemptMetrics.updateAggregateAppResourceUsage( attemptState.getMemorySeconds(),attemptState.getVcoreSeconds()); } public void transferStateFromAttempt(RMAppAttempt attempt) { this.justFinishedContainers = attempt.getJustFinishedContainersReference(); this.finishedContainersSentToAM = attempt.getFinishedContainersSentToAMReference(); } private void recoverAppAttemptCredentials(Credentials appAttemptTokens, RMAppAttemptState state) { if (appAttemptTokens == null || state == RMAppAttemptState.FAILED || state == RMAppAttemptState.FINISHED || state == RMAppAttemptState.KILLED) { return; } if (UserGroupInformation.isSecurityEnabled()) { byte[] clientTokenMasterKeyBytes = appAttemptTokens.getSecretKey( RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME); if (clientTokenMasterKeyBytes != null) { clientTokenMasterKey = rmContext.getClientToAMTokenSecretManager() .registerMasterKey(applicationAttemptId, clientTokenMasterKeyBytes); } } setAMRMToken(rmContext.getAMRMTokenSecretManager().createAndGetAMRMToken( applicationAttemptId)); } private static class BaseTransition implements SingleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent> { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { } } private static final class AttemptStartedTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { boolean transferStateFromPreviousAttempt = false; if (event instanceof RMAppStartAttemptEvent) { transferStateFromPreviousAttempt = ((RMAppStartAttemptEvent) event) .getTransferStateFromPreviousAttempt(); } appAttempt.startTime = System.currentTimeMillis(); // Register with the ApplicationMasterService appAttempt.masterService .registerAppAttempt(appAttempt.applicationAttemptId); if (UserGroupInformation.isSecurityEnabled()) { appAttempt.clientTokenMasterKey = appAttempt.rmContext.getClientToAMTokenSecretManager() .createMasterKey(appAttempt.applicationAttemptId); } // Add the applicationAttempt to the scheduler and inform the scheduler // whether to transfer the state from previous attempt. appAttempt.eventHandler.handle(new AppAttemptAddedSchedulerEvent( appAttempt.applicationAttemptId, transferStateFromPreviousAttempt)); } } private static final List<ContainerId> EMPTY_CONTAINER_RELEASE_LIST = new ArrayList<ContainerId>(); private static final List<ResourceRequest> EMPTY_CONTAINER_REQUEST_LIST = new ArrayList<ResourceRequest>(); @VisibleForTesting public static final class ScheduleTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { ApplicationSubmissionContext subCtx = appAttempt.submissionContext; if (!subCtx.getUnmanagedAM()) { // Need reset #containers before create new attempt, because this request // will be passed to scheduler, and scheduler will deduct the number after // AM container allocated // Currently, following fields are all hard code, // TODO: change these fields when we want to support // priority/resource-name/relax-locality specification for AM containers // allocation. appAttempt.amReq.setNumContainers(1); appAttempt.amReq.setPriority(AM_CONTAINER_PRIORITY); appAttempt.amReq.setResourceName(ResourceRequest.ANY); appAttempt.amReq.setRelaxLocality(true); // AM resource has been checked when submission Allocation amContainerAllocation = appAttempt.scheduler.allocate(appAttempt.applicationAttemptId, Collections.singletonList(appAttempt.amReq), EMPTY_CONTAINER_RELEASE_LIST, null, null); if (amContainerAllocation != null && amContainerAllocation.getContainers() != null) { assert (amContainerAllocation.getContainers().size() == 0); } return RMAppAttemptState.SCHEDULED; } else { // save state and then go to LAUNCHED state appAttempt.storeAttempt(); return RMAppAttemptState.LAUNCHED_UNMANAGED_SAVING; } } } private static final class AMContainerAllocatedTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // Acquire the AM container from the scheduler. Allocation amContainerAllocation = appAttempt.scheduler.allocate(appAttempt.applicationAttemptId, EMPTY_CONTAINER_REQUEST_LIST, EMPTY_CONTAINER_RELEASE_LIST, null, null); // There must be at least one container allocated, because a // CONTAINER_ALLOCATED is emitted after an RMContainer is constructed, // and is put in SchedulerApplication#newlyAllocatedContainers. // Note that YarnScheduler#allocate is not guaranteed to be able to // fetch it since container may not be fetchable for some reason like // DNS unavailable causing container token not generated. As such, we // return to the previous state and keep retry until am container is // fetched. if (amContainerAllocation.getContainers().size() == 0) { appAttempt.retryFetchingAMContainer(appAttempt); return RMAppAttemptState.SCHEDULED; } // Set the masterContainer appAttempt.setMasterContainer(amContainerAllocation.getContainers() .get(0)); RMContainerImpl rmMasterContainer = (RMContainerImpl)appAttempt.scheduler .getRMContainer(appAttempt.getMasterContainer().getId()); rmMasterContainer.setAMContainer(true); // The node set in NMTokenSecrentManager is used for marking whether the // NMToken has been issued for this node to the AM. // When AM container was allocated to RM itself, the node which allocates // this AM container was marked as the NMToken already sent. Thus, // clear this node set so that the following allocate requests from AM are // able to retrieve the corresponding NMToken. appAttempt.rmContext.getNMTokenSecretManager() .clearNodeSetForAttempt(appAttempt.applicationAttemptId); appAttempt.getSubmissionContext().setResource( appAttempt.getMasterContainer().getResource()); appAttempt.storeAttempt(); return RMAppAttemptState.ALLOCATED_SAVING; } } private void retryFetchingAMContainer(final RMAppAttemptImpl appAttempt) { // start a new thread so that we are not blocking main dispatcher thread. new Thread() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { LOG.warn("Interrupted while waiting to resend the" + " ContainerAllocated Event."); } appAttempt.eventHandler.handle(new RMAppAttemptContainerAllocatedEvent( appAttempt.applicationAttemptId)); } }.start(); } private static final class AttemptStoredTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { appAttempt.launchAttempt(); } } private static class AttemptRecoveredTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { /* * If last attempt recovered final state is null .. it means attempt was * started but AM container may or may not have started / finished. * Therefore we should wait for it to finish. */ if (appAttempt.recoveredFinalState != null) { appAttempt.progress = 1.0f; RMApp rmApp =appAttempt.rmContext.getRMApps().get( appAttempt.getAppAttemptId().getApplicationId()); if (appAttempt.submissionContext .getKeepContainersAcrossApplicationAttempts() && !appAttempt.submissionContext.getUnmanagedAM() && rmApp.getCurrentAppAttempt() != appAttempt) { appAttempt.transferStateFromAttempt(rmApp.getCurrentAppAttempt()); } // We will replay the final attempt only if last attempt is in final // state but application is not in final state. if (rmApp.getCurrentAppAttempt() == appAttempt && !RMAppImpl.isAppInFinalState(rmApp)) { // Add the previous finished attempt to scheduler synchronously so // that scheduler knows the previous attempt. appAttempt.scheduler.handle(new AppAttemptAddedSchedulerEvent( appAttempt.getAppAttemptId(), false, true)); (new BaseFinalTransition(appAttempt.recoveredFinalState)).transition( appAttempt, event); } return appAttempt.recoveredFinalState; } else { // Add the current attempt to the scheduler. if (appAttempt.rmContext.isWorkPreservingRecoveryEnabled()) { // Need to register an app attempt before AM can register appAttempt.masterService .registerAppAttempt(appAttempt.applicationAttemptId); // Add attempt to scheduler synchronously to guarantee scheduler // knows attempts before AM or NM re-registers. appAttempt.scheduler.handle(new AppAttemptAddedSchedulerEvent( appAttempt.getAppAttemptId(), false, true)); } /* * Since the application attempt's final state is not saved that means * for AM container (previous attempt) state must be one of these. * 1) AM container may not have been launched (RM failed right before * this). * 2) AM container was successfully launched but may or may not have * registered / unregistered. * In whichever case we will wait (by moving attempt into LAUNCHED * state) and mark this attempt failed (assuming non work preserving * restart) only after * 1) Node manager during re-registration heart beats back saying * am container finished. * 2) OR AMLivelinessMonitor expires this attempt (when am doesn't * heart beat back). */ (new AMLaunchedTransition()).transition(appAttempt, event); return RMAppAttemptState.LAUNCHED; } } } private void rememberTargetTransitions(RMAppAttemptEvent event, Object transitionToDo, RMAppAttemptState targetFinalState) { transitionTodo = transitionToDo; targetedFinalState = targetFinalState; eventCausingFinalSaving = event; } private void rememberTargetTransitionsAndStoreState(RMAppAttemptEvent event, Object transitionToDo, RMAppAttemptState targetFinalState, RMAppAttemptState stateToBeStored) { rememberTargetTransitions(event, transitionToDo, targetFinalState); stateBeforeFinalSaving = getState(); // As of today, finalState, diagnostics, final-tracking-url and // finalAppStatus are the only things that we store into the StateStore // AFTER the initial saving on app-attempt-start // These fields can be visible from outside only after they are saved in // StateStore String diags = null; // don't leave the tracking URL pointing to a non-existent AM setTrackingUrlToRMAppPage(stateToBeStored); String finalTrackingUrl = getOriginalTrackingUrl(); FinalApplicationStatus finalStatus = null; int exitStatus = ContainerExitStatus.INVALID; switch (event.getType()) { case LAUNCH_FAILED: RMAppAttemptLaunchFailedEvent launchFaileEvent = (RMAppAttemptLaunchFailedEvent) event; diags = launchFaileEvent.getMessage(); break; case REGISTERED: diags = getUnexpectedAMRegisteredDiagnostics(); break; case UNREGISTERED: RMAppAttemptUnregistrationEvent unregisterEvent = (RMAppAttemptUnregistrationEvent) event; diags = unregisterEvent.getDiagnostics(); // reset finalTrackingUrl to url sent by am finalTrackingUrl = sanitizeTrackingUrl(unregisterEvent.getFinalTrackingUrl()); finalStatus = unregisterEvent.getFinalApplicationStatus(); break; case CONTAINER_FINISHED: RMAppAttemptContainerFinishedEvent finishEvent = (RMAppAttemptContainerFinishedEvent) event; diags = getAMContainerCrashedDiagnostics(finishEvent); exitStatus = finishEvent.getContainerStatus().getExitStatus(); break; case KILL: break; case EXPIRE: diags = getAMExpiredDiagnostics(event); break; default: break; } AggregateAppResourceUsage resUsage = this.attemptMetrics.getAggregateAppResourceUsage(); RMStateStore rmStore = rmContext.getStateStore(); setFinishTime(System.currentTimeMillis()); ApplicationAttemptStateData attemptState = ApplicationAttemptStateData.newInstance( applicationAttemptId, getMasterContainer(), rmStore.getCredentialsFromAppAttempt(this), startTime, stateToBeStored, finalTrackingUrl, diags, finalStatus, exitStatus, getFinishTime(), resUsage.getMemorySeconds(), resUsage.getVcoreSeconds()); LOG.info("Updating application attempt " + applicationAttemptId + " with final state: " + targetedFinalState + ", and exit status: " + exitStatus); rmStore.updateApplicationAttemptState(attemptState); } private static class FinalSavingTransition extends BaseTransition { Object transitionToDo; RMAppAttemptState targetedFinalState; public FinalSavingTransition(Object transitionToDo, RMAppAttemptState targetedFinalState) { this.transitionToDo = transitionToDo; this.targetedFinalState = targetedFinalState; } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // For cases Killed/Failed, targetedFinalState is the same as the state to // be stored appAttempt.rememberTargetTransitionsAndStoreState(event, transitionToDo, targetedFinalState, targetedFinalState); } } private static class FinalStateSavedTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptEvent causeEvent = appAttempt.eventCausingFinalSaving; if (appAttempt.transitionTodo instanceof SingleArcTransition) { ((SingleArcTransition) appAttempt.transitionTodo).transition( appAttempt, causeEvent); } else if (appAttempt.transitionTodo instanceof MultipleArcTransition) { ((MultipleArcTransition) appAttempt.transitionTodo).transition( appAttempt, causeEvent); } return appAttempt.targetedFinalState; } } private static class BaseFinalTransition extends BaseTransition { private final RMAppAttemptState finalAttemptState; public BaseFinalTransition(RMAppAttemptState finalAttemptState) { this.finalAttemptState = finalAttemptState; } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { ApplicationAttemptId appAttemptId = appAttempt.getAppAttemptId(); // Tell the AMS. Unregister from the ApplicationMasterService appAttempt.masterService.unregisterAttempt(appAttemptId); // Tell the application and the scheduler ApplicationId applicationId = appAttemptId.getApplicationId(); RMAppEvent appEvent = null; boolean keepContainersAcrossAppAttempts = false; switch (finalAttemptState) { case FINISHED: { appEvent = new RMAppFinishedAttemptEvent(applicationId, appAttempt.getDiagnostics()); } break; case KILLED: { appAttempt.invalidateAMHostAndPort(); appEvent = new RMAppFailedAttemptEvent(applicationId, RMAppEventType.ATTEMPT_KILLED, "Application killed by user.", false); } break; case FAILED: { appAttempt.invalidateAMHostAndPort(); if (appAttempt.submissionContext .getKeepContainersAcrossApplicationAttempts() && !appAttempt.submissionContext.getUnmanagedAM()) { // See if we should retain containers for non-unmanaged applications if (!appAttempt.shouldCountTowardsMaxAttemptRetry()) { // Premption, hardware failures, NM resync doesn't count towards // app-failures and so we should retain containers. keepContainersAcrossAppAttempts = true; } else if (!appAttempt.maybeLastAttempt) { // Not preemption, hardware failures or NM resync. // Not last-attempt too - keep containers. keepContainersAcrossAppAttempts = true; } } appEvent = new RMAppFailedAttemptEvent(applicationId, RMAppEventType.ATTEMPT_FAILED, appAttempt.getDiagnostics(), keepContainersAcrossAppAttempts); } break; default: { LOG.error("Cannot get this state!! Error!!"); } break; } appAttempt.eventHandler.handle(appEvent); appAttempt.eventHandler.handle(new AppAttemptRemovedSchedulerEvent( appAttemptId, finalAttemptState, keepContainersAcrossAppAttempts)); appAttempt.removeCredentials(appAttempt); appAttempt.rmContext.getRMApplicationHistoryWriter() .applicationAttemptFinished(appAttempt, finalAttemptState); appAttempt.rmContext.getSystemMetricsPublisher() .appAttemptFinished(appAttempt, finalAttemptState, appAttempt.rmContext.getRMApps().get( appAttempt.applicationAttemptId.getApplicationId()), System.currentTimeMillis()); } } private static class AMLaunchedTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { if (event.getType() == RMAppAttemptEventType.LAUNCHED) { appAttempt.launchAMEndTime = System.currentTimeMillis(); long delay = appAttempt.launchAMEndTime - appAttempt.launchAMStartTime; ClusterMetrics.getMetrics().addAMLaunchDelay(delay); } // Register with AMLivelinessMonitor appAttempt.attemptLaunched(); // register the ClientTokenMasterKey after it is saved in the store, // otherwise client may hold an invalid ClientToken after RM restarts. appAttempt.rmContext.getClientToAMTokenSecretManager() .registerApplication(appAttempt.getAppAttemptId(), appAttempt.getClientTokenMasterKey()); } } @Override public boolean shouldCountTowardsMaxAttemptRetry() { try { this.readLock.lock(); int exitStatus = getAMContainerExitStatus(); return !(exitStatus == ContainerExitStatus.PREEMPTED || exitStatus == ContainerExitStatus.ABORTED || exitStatus == ContainerExitStatus.DISKS_FAILED || exitStatus == ContainerExitStatus.KILLED_BY_RESOURCEMANAGER); } finally { this.readLock.unlock(); } } private static final class UnmanagedAMAttemptSavedTransition extends AMLaunchedTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // create AMRMToken appAttempt.amrmToken = appAttempt.rmContext.getAMRMTokenSecretManager().createAndGetAMRMToken( appAttempt.applicationAttemptId); super.transition(appAttempt, event); } } private static final class LaunchFailedTransition extends BaseFinalTransition { public LaunchFailedTransition() { super(RMAppAttemptState.FAILED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // Use diagnostic from launcher RMAppAttemptLaunchFailedEvent launchFaileEvent = (RMAppAttemptLaunchFailedEvent) event; appAttempt.diagnostics.append(launchFaileEvent.getMessage()); // Tell the app, scheduler super.transition(appAttempt, event); } } private static final class KillAllocatedAMTransition extends BaseFinalTransition { public KillAllocatedAMTransition() { super(RMAppAttemptState.KILLED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // Tell the application and scheduler super.transition(appAttempt, event); // Tell the launcher to cleanup. appAttempt.eventHandler.handle(new AMLauncherEvent( AMLauncherEventType.CLEANUP, appAttempt)); } } private static final class AMRegisteredTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { long delay = System.currentTimeMillis() - appAttempt.launchAMEndTime; ClusterMetrics.getMetrics().addAMRegisterDelay(delay); RMAppAttemptRegistrationEvent registrationEvent = (RMAppAttemptRegistrationEvent) event; appAttempt.host = registrationEvent.getHost(); appAttempt.rpcPort = registrationEvent.getRpcport(); appAttempt.originalTrackingUrl = sanitizeTrackingUrl(registrationEvent.getTrackingurl()); // Let the app know appAttempt.eventHandler.handle(new RMAppEvent(appAttempt .getAppAttemptId().getApplicationId(), RMAppEventType.ATTEMPT_REGISTERED)); // TODO:FIXME: Note for future. Unfortunately we only do a state-store // write at AM launch time, so we don't save the AM's tracking URL anywhere // as that would mean an extra state-store write. For now, we hope that in // work-preserving restart, AMs are forced to reregister. appAttempt.rmContext.getRMApplicationHistoryWriter() .applicationAttemptStarted(appAttempt); appAttempt.rmContext.getSystemMetricsPublisher() .appAttemptRegistered(appAttempt, System.currentTimeMillis()); } } private static final class AMContainerCrashedBeforeRunningTransition extends BaseFinalTransition { public AMContainerCrashedBeforeRunningTransition() { super(RMAppAttemptState.FAILED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent finishEvent = ((RMAppAttemptContainerFinishedEvent)event); // UnRegister from AMLivelinessMonitor appAttempt.rmContext.getAMLivelinessMonitor().unregister( appAttempt.getAppAttemptId()); // Setup diagnostic message and exit status appAttempt.setAMContainerCrashedDiagnosticsAndExitStatus(finishEvent); // Tell the app, scheduler super.transition(appAttempt, finishEvent); } } private void setAMContainerCrashedDiagnosticsAndExitStatus( RMAppAttemptContainerFinishedEvent finishEvent) { ContainerStatus status = finishEvent.getContainerStatus(); String diagnostics = getAMContainerCrashedDiagnostics(finishEvent); this.diagnostics.append(diagnostics); this.amContainerExitStatus = status.getExitStatus(); } private String getAMContainerCrashedDiagnostics( RMAppAttemptContainerFinishedEvent finishEvent) { ContainerStatus status = finishEvent.getContainerStatus(); StringBuilder diagnosticsBuilder = new StringBuilder(); diagnosticsBuilder.append("AM Container for ").append( finishEvent.getApplicationAttemptId()).append( " exited with ").append(" exitCode: ").append(status.getExitStatus()). append("\n"); diagnosticsBuilder.append("Failing this attempt.").append("Diagnostics: ") .append(status.getDiagnostics()); if (this.getTrackingUrl() != null) { diagnosticsBuilder.append("For more detailed output,").append( " check the application tracking page: ").append( this.getTrackingUrl()).append( " Then click on links to logs of each attempt.\n"); } return diagnosticsBuilder.toString(); } private static class FinalTransition extends BaseFinalTransition { public FinalTransition(RMAppAttemptState finalAttemptState) { super(finalAttemptState); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { appAttempt.progress = 1.0f; // Tell the app and the scheduler super.transition(appAttempt, event); // UnRegister from AMLivelinessMonitor. Perhaps for // FAILING/KILLED/UnManaged AMs appAttempt.rmContext.getAMLivelinessMonitor().unregister( appAttempt.getAppAttemptId()); appAttempt.rmContext.getAMFinishingMonitor().unregister( appAttempt.getAppAttemptId()); if(!appAttempt.submissionContext.getUnmanagedAM()) { // Tell the launcher to cleanup. appAttempt.eventHandler.handle(new AMLauncherEvent( AMLauncherEventType.CLEANUP, appAttempt)); } } } private static class ExpiredTransition extends FinalTransition { public ExpiredTransition() { super(RMAppAttemptState.FAILED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { appAttempt.diagnostics.append(getAMExpiredDiagnostics(event)); super.transition(appAttempt, event); } } private static String getAMExpiredDiagnostics(RMAppAttemptEvent event) { String diag = "ApplicationMaster for attempt " + event.getApplicationAttemptId() + " timed out"; return diag; } private static class UnexpectedAMRegisteredTransition extends BaseFinalTransition { public UnexpectedAMRegisteredTransition() { super(RMAppAttemptState.FAILED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { assert appAttempt.submissionContext.getUnmanagedAM(); appAttempt.diagnostics.append(getUnexpectedAMRegisteredDiagnostics()); super.transition(appAttempt, event); } } private static String getUnexpectedAMRegisteredDiagnostics() { return "Unmanaged AM must register after AM attempt reaches LAUNCHED state."; } private static final class StatusUpdateTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptStatusupdateEvent statusUpdateEvent = (RMAppAttemptStatusupdateEvent) event; // Update progress appAttempt.progress = statusUpdateEvent.getProgress(); // Ping to AMLivelinessMonitor appAttempt.rmContext.getAMLivelinessMonitor().receivedPing( statusUpdateEvent.getApplicationAttemptId()); } } private static final class AMUnregisteredTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // Tell the app if (appAttempt.getSubmissionContext().getUnmanagedAM()) { // Unmanaged AMs have no container to wait for, so they skip // the FINISHING state and go straight to FINISHED. appAttempt.updateInfoOnAMUnregister(event); new FinalTransition(RMAppAttemptState.FINISHED).transition( appAttempt, event); return RMAppAttemptState.FINISHED; } // Saving the attempt final state appAttempt.rememberTargetTransitionsAndStoreState(event, new FinalStateSavedAfterAMUnregisterTransition(), RMAppAttemptState.FINISHING, RMAppAttemptState.FINISHED); ApplicationId applicationId = appAttempt.getAppAttemptId().getApplicationId(); // Tell the app immediately that AM is unregistering so that app itself // can save its state as soon as possible. Whether we do it like this, or // we wait till AppAttempt is saved, it doesn't make any difference on the // app side w.r.t failure conditions. The only event going out of // AppAttempt to App after this point of time is AM/AppAttempt Finished. appAttempt.eventHandler.handle(new RMAppEvent(applicationId, RMAppEventType.ATTEMPT_UNREGISTERED)); return RMAppAttemptState.FINAL_SAVING; } } private static class FinalStateSavedAfterAMUnregisterTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // Unregister from the AMlivenessMonitor and register with AMFinishingMonitor appAttempt.rmContext.getAMLivelinessMonitor().unregister( appAttempt.applicationAttemptId); appAttempt.rmContext.getAMFinishingMonitor().register( appAttempt.applicationAttemptId); // Do not make any more changes to this transition code. Make all changes // to the following method. Unless you are absolutely sure that you have // stuff to do that shouldn't be used by the callers of the following // method. appAttempt.updateInfoOnAMUnregister(event); } } private void updateInfoOnAMUnregister(RMAppAttemptEvent event) { progress = 1.0f; RMAppAttemptUnregistrationEvent unregisterEvent = (RMAppAttemptUnregistrationEvent) event; diagnostics.append(unregisterEvent.getDiagnostics()); originalTrackingUrl = sanitizeTrackingUrl(unregisterEvent.getFinalTrackingUrl()); finalStatus = unregisterEvent.getFinalApplicationStatus(); } private static final class ContainerFinishedTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { // The transition To Do after attempt final state is saved. private BaseTransition transitionToDo; private RMAppAttemptState currentState; public ContainerFinishedTransition(BaseTransition transitionToDo, RMAppAttemptState currentState) { this.transitionToDo = transitionToDo; this.currentState = currentState; } @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent containerFinishedEvent = (RMAppAttemptContainerFinishedEvent) event; ContainerStatus containerStatus = containerFinishedEvent.getContainerStatus(); // Is this container the AmContainer? If the finished container is same as // the AMContainer, AppAttempt fails if (appAttempt.masterContainer != null && appAttempt.masterContainer.getId().equals( containerStatus.getContainerId())) { appAttempt.sendAMContainerToNM(appAttempt, containerFinishedEvent); // Remember the follow up transition and save the final attempt state. appAttempt.rememberTargetTransitionsAndStoreState(event, transitionToDo, RMAppAttemptState.FAILED, RMAppAttemptState.FAILED); return RMAppAttemptState.FINAL_SAVING; } // Add all finished containers so that they can be acked to NM addJustFinishedContainer(appAttempt, containerFinishedEvent); return this.currentState; } } // Ack NM to remove finished containers from context. private void sendFinishedContainersToNM() { for (NodeId nodeId : finishedContainersSentToAM.keySet()) { // Clear and get current values List<ContainerStatus> currentSentContainers = finishedContainersSentToAM.put(nodeId, new ArrayList<ContainerStatus>()); List<ContainerId> containerIdList = new ArrayList<ContainerId>(currentSentContainers.size()); for (ContainerStatus containerStatus : currentSentContainers) { containerIdList.add(containerStatus.getContainerId()); } eventHandler.handle(new RMNodeFinishedContainersPulledByAMEvent(nodeId, containerIdList)); } } // Add am container to the list so that am container instance will be // removed from NMContext. private void sendAMContainerToNM(RMAppAttemptImpl appAttempt, RMAppAttemptContainerFinishedEvent containerFinishedEvent) { NodeId nodeId = containerFinishedEvent.getNodeId(); finishedContainersSentToAM.putIfAbsent(nodeId, new ArrayList<ContainerStatus>()); appAttempt.finishedContainersSentToAM.get(nodeId).add( containerFinishedEvent.getContainerStatus()); if (!appAttempt.getSubmissionContext() .getKeepContainersAcrossApplicationAttempts()) { appAttempt.sendFinishedContainersToNM(); } } private static void addJustFinishedContainer(RMAppAttemptImpl appAttempt, RMAppAttemptContainerFinishedEvent containerFinishedEvent) { appAttempt.justFinishedContainers.putIfAbsent(containerFinishedEvent .getNodeId(), new ArrayList<ContainerStatus>()); appAttempt.justFinishedContainers.get(containerFinishedEvent .getNodeId()).add(containerFinishedEvent.getContainerStatus()); } private static final class ContainerFinishedAtFinalStateTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent containerFinishedEvent = (RMAppAttemptContainerFinishedEvent) event; // Normal container. Add it in completed containers list addJustFinishedContainer(appAttempt, containerFinishedEvent); } } private static class AMContainerCrashedAtRunningTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent finishEvent = (RMAppAttemptContainerFinishedEvent) event; // container associated with AM. must not be unmanaged assert appAttempt.submissionContext.getUnmanagedAM() == false; // Setup diagnostic message and exit status appAttempt.setAMContainerCrashedDiagnosticsAndExitStatus(finishEvent); new FinalTransition(RMAppAttemptState.FAILED).transition(appAttempt, event); } } private static final class AMFinishingContainerFinishedTransition implements MultipleArcTransition<RMAppAttemptImpl, RMAppAttemptEvent, RMAppAttemptState> { @Override public RMAppAttemptState transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent containerFinishedEvent = (RMAppAttemptContainerFinishedEvent) event; ContainerStatus containerStatus = containerFinishedEvent.getContainerStatus(); // Is this container the ApplicationMaster container? if (appAttempt.masterContainer.getId().equals( containerStatus.getContainerId())) { new FinalTransition(RMAppAttemptState.FINISHED).transition( appAttempt, containerFinishedEvent); appAttempt.sendAMContainerToNM(appAttempt, containerFinishedEvent); return RMAppAttemptState.FINISHED; } // Add all finished containers so that they can be acked to NM. addJustFinishedContainer(appAttempt, containerFinishedEvent); return RMAppAttemptState.FINISHING; } } private static class ContainerFinishedAtFinalSavingTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent containerFinishedEvent = (RMAppAttemptContainerFinishedEvent) event; ContainerStatus containerStatus = containerFinishedEvent.getContainerStatus(); // If this is the AM container, it means the AM container is finished, // but we are not yet acknowledged that the final state has been saved. // Thus, we still return FINAL_SAVING state here. if (appAttempt.masterContainer.getId().equals( containerStatus.getContainerId())) { appAttempt.sendAMContainerToNM(appAttempt, containerFinishedEvent); if (appAttempt.targetedFinalState.equals(RMAppAttemptState.FAILED) || appAttempt.targetedFinalState.equals(RMAppAttemptState.KILLED)) { // ignore Container_Finished Event if we were supposed to reach // FAILED/KILLED state. return; } // pass in the earlier AMUnregistered Event also, as this is needed for // AMFinishedAfterFinalSavingTransition later on appAttempt.rememberTargetTransitions(event, new AMFinishedAfterFinalSavingTransition( appAttempt.eventCausingFinalSaving), RMAppAttemptState.FINISHED); return; } // Add all finished containers so that they can be acked to NM. addJustFinishedContainer(appAttempt, containerFinishedEvent); } } private static class AMFinishedAfterFinalSavingTransition extends BaseTransition { RMAppAttemptEvent amUnregisteredEvent; public AMFinishedAfterFinalSavingTransition( RMAppAttemptEvent amUnregisteredEvent) { this.amUnregisteredEvent = amUnregisteredEvent; } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { appAttempt.updateInfoOnAMUnregister(amUnregisteredEvent); new FinalTransition(RMAppAttemptState.FINISHED).transition(appAttempt, event); } } private static class AMExpiredAtFinalSavingTransition extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { if (appAttempt.targetedFinalState.equals(RMAppAttemptState.FAILED) || appAttempt.targetedFinalState.equals(RMAppAttemptState.KILLED)) { // ignore Container_Finished Event if we were supposed to reach // FAILED/KILLED state. return; } // pass in the earlier AMUnregistered Event also, as this is needed for // AMFinishedAfterFinalSavingTransition later on appAttempt.rememberTargetTransitions(event, new AMFinishedAfterFinalSavingTransition( appAttempt.eventCausingFinalSaving), RMAppAttemptState.FINISHED); } } @Override public long getStartTime() { this.readLock.lock(); try { return this.startTime; } finally { this.readLock.unlock(); } } @Override public RMAppAttemptState getState() { this.readLock.lock(); try { return this.stateMachine.getCurrentState(); } finally { this.readLock.unlock(); } } @Override public YarnApplicationAttemptState createApplicationAttemptState() { RMAppAttemptState state = getState(); // If AppAttempt is in FINAL_SAVING state, return its previous state. if (state.equals(RMAppAttemptState.FINAL_SAVING)) { state = stateBeforeFinalSaving; } return RMServerUtils.createApplicationAttemptState(state); } private void launchAttempt(){ launchAMStartTime = System.currentTimeMillis(); // Send event to launch the AM Container eventHandler.handle(new AMLauncherEvent(AMLauncherEventType.LAUNCH, this)); } private void attemptLaunched() { // Register with AMLivelinessMonitor rmContext.getAMLivelinessMonitor().register(getAppAttemptId()); } private void storeAttempt() { // store attempt data in a non-blocking manner to prevent dispatcher // thread starvation and wait for state to be saved LOG.info("Storing attempt: AppId: " + getAppAttemptId().getApplicationId() + " AttemptId: " + getAppAttemptId() + " MasterContainer: " + masterContainer); rmContext.getStateStore().storeNewApplicationAttempt(this); } private void removeCredentials(RMAppAttemptImpl appAttempt) { // Unregister from the ClientToAMTokenSecretManager if (UserGroupInformation.isSecurityEnabled()) { appAttempt.rmContext.getClientToAMTokenSecretManager() .unRegisterApplication(appAttempt.getAppAttemptId()); } // Remove the AppAttempt from the AMRMTokenSecretManager appAttempt.rmContext.getAMRMTokenSecretManager() .applicationMasterFinished(appAttempt.getAppAttemptId()); } private static String sanitizeTrackingUrl(String url) { return (url == null || url.trim().isEmpty()) ? "N/A" : url; } @Override public ApplicationAttemptReport createApplicationAttemptReport() { this.readLock.lock(); ApplicationAttemptReport attemptReport = null; try { // AM container maybe not yet allocated. and also unmangedAM doesn't have // am container. ContainerId amId = masterContainer == null ? null : masterContainer.getId(); attemptReport = ApplicationAttemptReport.newInstance(this .getAppAttemptId(), this.getHost(), this.getRpcPort(), this .getTrackingUrl(), this.getOriginalTrackingUrl(), this.getDiagnostics(), YarnApplicationAttemptState.valueOf(this.getState().toString()), amId, this.startTime, this.finishTime); } finally { this.readLock.unlock(); } return attemptReport; } // for testing public boolean mayBeLastAttempt() { return maybeLastAttempt; } @Override public RMAppAttemptMetrics getRMAppAttemptMetrics() { // didn't use read/write lock here because RMAppAttemptMetrics has its own // lock return attemptMetrics; } @Override public long getFinishTime() { try { this.readLock.lock(); return this.finishTime; } finally { this.readLock.unlock(); } } private void setFinishTime(long finishTime) { try { this.writeLock.lock(); this.finishTime = finishTime; } finally { this.writeLock.unlock(); } } }
76,216
38.005629
109
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptState.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; public enum RMAppAttemptState { NEW, SUBMITTED, SCHEDULED, ALLOCATED, LAUNCHED, FAILED, RUNNING, FINISHING, FINISHED, KILLED, ALLOCATED_SAVING, LAUNCHED_UNMANAGED_SAVING, FINAL_SAVING }
1,069
41.8
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/AggregateAppResourceUsage.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import org.apache.hadoop.classification.InterfaceAudience.Private; @Private public class AggregateAppResourceUsage { long memorySeconds; long vcoreSeconds; public AggregateAppResourceUsage(long memorySeconds, long vcoreSeconds) { this.memorySeconds = memorySeconds; this.vcoreSeconds = vcoreSeconds; } /** * @return the memorySeconds */ public long getMemorySeconds() { return memorySeconds; } /** * @param memorySeconds the memorySeconds to set */ public void setMemorySeconds(long memorySeconds) { this.memorySeconds = memorySeconds; } /** * @return the vcoreSeconds */ public long getVcoreSeconds() { return vcoreSeconds; } /** * @param vcoreSeconds the vcoreSeconds to set */ public void setVcoreSeconds(long vcoreSeconds) { this.vcoreSeconds = vcoreSeconds; } }
1,731
27.393443
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptEventType.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; public enum RMAppAttemptEventType { // Source: RMApp START, KILL, // Source: AMLauncher LAUNCHED, LAUNCH_FAILED, // Source: AMLivelinessMonitor EXPIRE, // Source: ApplicationMasterService REGISTERED, STATUS_UPDATE, UNREGISTERED, // Source: Containers CONTAINER_ALLOCATED, CONTAINER_FINISHED, // Source: RMStateStore ATTEMPT_NEW_SAVED, ATTEMPT_UPDATE_SAVED, // Source: Scheduler ATTEMPT_ADDED, // Source: RMAttemptImpl.recover RECOVER }
1,372
24.90566
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.event.AbstractEvent; public class RMAppAttemptEvent extends AbstractEvent<RMAppAttemptEventType> { private final ApplicationAttemptId appAttemptId; public RMAppAttemptEvent(ApplicationAttemptId appAttemptId, RMAppAttemptEventType type) { super(type); this.appAttemptId = appAttemptId; } public ApplicationAttemptId getApplicationAttemptId() { return this.appAttemptId; } }
1,377
35.263158
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppStartAttemptEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; public class RMAppStartAttemptEvent extends RMAppAttemptEvent { private final boolean transferStateFromPreviousAttempt; public RMAppStartAttemptEvent(ApplicationAttemptId appAttemptId, boolean transferStateFromPreviousAttempt) { super(appAttemptId, RMAppAttemptEventType.START); this.transferStateFromPreviousAttempt = transferStateFromPreviousAttempt; } public boolean getTransferStateFromPreviousAttempt() { return transferStateFromPreviousAttempt; } }
1,429
37.648649
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttempt.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import java.util.List; import java.util.concurrent.ConcurrentMap; import javax.crypto.SecretKey; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationAttemptReport; import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.YarnApplicationAttemptState; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.security.client.ClientToAMTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; /** * Interface to an Application Attempt in the Resource Manager. * A {@link RMApp} can have multiple app attempts based on * {@link YarnConfiguration#RM_AM_MAX_ATTEMPTS}. For specific * implementation take a look at {@link RMAppAttemptImpl}. */ public interface RMAppAttempt extends EventHandler<RMAppAttemptEvent> { /** * Get the application attempt id for this {@link RMAppAttempt}. * @return the {@link ApplicationAttemptId} for this RM attempt. */ ApplicationAttemptId getAppAttemptId(); /** * The state of the {@link RMAppAttempt}. * @return the state {@link RMAppAttemptState} of this {@link RMAppAttempt} */ RMAppAttemptState getAppAttemptState(); /** * The host on which the {@link RMAppAttempt} is running/ran on. * @return the host on which the {@link RMAppAttempt} ran/is running on. */ String getHost(); /** * The rpc port of the {@link RMAppAttempt}. * @return the rpc port of the {@link RMAppAttempt} to which the clients can connect * to. */ int getRpcPort(); /** * The url at which the status of the application attempt can be accessed. * @return the url at which the status of the attempt can be accessed. */ String getTrackingUrl(); /** * The original url at which the status of the application attempt can be * accessed. This url is not fronted by a proxy. This is only intended to be * used by the proxy. * @return the url at which the status of the attempt can be accessed and is * not fronted by a proxy. */ String getOriginalTrackingUrl(); /** * The base to be prepended to web URLs that are not relative, and the user * has been checked. * @return the base URL to be prepended to web URLs that are not relative. */ String getWebProxyBase(); /** * Diagnostics information for the application attempt. * @return diagnostics information for the application attempt. */ String getDiagnostics(); /** * Progress for the application attempt. * @return the progress for this {@link RMAppAttempt} */ float getProgress(); /** * The final status set by the AM. * @return the final status that is set by the AM when unregistering itself. Can return a null * if the AM has not unregistered itself. */ FinalApplicationStatus getFinalApplicationStatus(); /** * Return a list of the last set of finished containers, resetting the * finished containers to empty. * @return the list of just finished containers, re setting the finished containers. */ List<ContainerStatus> pullJustFinishedContainers(); /** * Returns a reference to the map of last set of finished containers to the * corresponding node. This does not reset the finished containers. * @return the list of just finished containers, this does not reset the * finished containers. */ ConcurrentMap<NodeId, List<ContainerStatus>> getJustFinishedContainersReference(); /** * Return the list of last set of finished containers. This does not reset * the finished containers. * @return the list of just finished containers */ List<ContainerStatus> getJustFinishedContainers(); /** * The map of conatiners per Node that are already sent to the AM. * @return map of per node list of finished container status sent to AM */ ConcurrentMap<NodeId, List<ContainerStatus>> getFinishedContainersSentToAMReference(); /** * The container on which the Application Master is running. * @return the {@link Container} on which the application master is running. */ Container getMasterContainer(); /** * The application submission context for this {@link RMAppAttempt}. * @return the application submission context for this Application. */ ApplicationSubmissionContext getSubmissionContext(); /** * The AMRMToken belonging to this app attempt * @return The AMRMToken belonging to this app attempt */ Token<AMRMTokenIdentifier> getAMRMToken(); /** * The master key for client-to-AM tokens for this app attempt. This is only * used for RMStateStore. Normal operation must invoke the secret manager to * get the key and not use the local key directly. * @return The master key for client-to-AM tokens for this app attempt */ @LimitedPrivate("RMStateStore") SecretKey getClientTokenMasterKey(); /** * Create a token for authenticating a client connection to the app attempt * @param clientName the name of the client requesting the token * @return the token or null if the attempt is not running */ Token<ClientToAMTokenIdentifier> createClientToken(String clientName); /** * Get application container and resource usage information. * @return an ApplicationResourceUsageReport object. */ ApplicationResourceUsageReport getApplicationResourceUsageReport(); /** * the start time of the application. * @return the start time of the application. */ long getStartTime(); /** * The current state of the {@link RMAppAttempt}. * * @return the current state {@link RMAppAttemptState} for this application * attempt. */ RMAppAttemptState getState(); /** * Create the external user-facing state of the attempt of ApplicationMaster * from the current state of the {@link RMAppAttempt}. * * @return the external user-facing state of the attempt ApplicationMaster. */ YarnApplicationAttemptState createApplicationAttemptState(); /** * Create the Application attempt report from the {@link RMAppAttempt} * * @return {@link ApplicationAttemptReport} */ ApplicationAttemptReport createApplicationAttemptReport(); /** * Return the flag which indicates whether the attempt failure should be * counted to attempt retry count. * <p> * There failure types should not be counted to attempt retry count: * <ul> * <li>preempted by the scheduler.</li> * <li> * hardware failures, such as NM failing, lost NM and NM disk errors. * </li> * <li>killed by RM because of RM restart or failover.</li> * </ul> */ boolean shouldCountTowardsMaxAttemptRetry(); /** * Get metrics from the {@link RMAppAttempt} * @return metrics */ RMAppAttemptMetrics getRMAppAttemptMetrics(); /** * the finish time of the application attempt. * @return the finish time of the application attempt. */ long getFinishTime(); }
8,407
33.600823
97
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/AMLivelinessMonitor.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.util.AbstractLivelinessMonitor; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.SystemClock; public class AMLivelinessMonitor extends AbstractLivelinessMonitor<ApplicationAttemptId> { private EventHandler dispatcher; public AMLivelinessMonitor(Dispatcher d) { super("AMLivelinessMonitor", new SystemClock()); this.dispatcher = d.getEventHandler(); } public AMLivelinessMonitor(Dispatcher d, Clock clock) { super("AMLivelinessMonitor", clock); this.dispatcher = d.getEventHandler(); } public void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); int expireIntvl = conf.getInt(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, YarnConfiguration.DEFAULT_RM_AM_EXPIRY_INTERVAL_MS); setExpireInterval(expireIntvl); setMonitorInterval(expireIntvl/3); } @Override protected void expire(ApplicationAttemptId id) { dispatcher.handle( new RMAppAttemptEvent(id, RMAppAttemptEventType.EXPIRE)); } }
2,189
37.421053
90
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptMetrics.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.util.resource.Resources; public class RMAppAttemptMetrics { private static final Log LOG = LogFactory.getLog(RMAppAttemptMetrics.class); private ApplicationAttemptId attemptId = null; // preemption info private Resource resourcePreempted = Resource.newInstance(0, 0); // application headroom private volatile Resource applicationHeadroom = Resource.newInstance(0, 0); private AtomicInteger numNonAMContainersPreempted = new AtomicInteger(0); private AtomicBoolean isPreempted = new AtomicBoolean(false); private ReadLock readLock; private WriteLock writeLock; private AtomicLong finishedMemorySeconds = new AtomicLong(0); private AtomicLong finishedVcoreSeconds = new AtomicLong(0); private RMContext rmContext; private int[][] localityStatistics = new int[NodeType.values().length][NodeType.values().length]; private volatile int totalAllocatedContainers; public RMAppAttemptMetrics(ApplicationAttemptId attemptId, RMContext rmContext) { this.attemptId = attemptId; ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); this.rmContext = rmContext; } public void updatePreemptionInfo(Resource resource, RMContainer container) { try { writeLock.lock(); resourcePreempted = Resources.addTo(resourcePreempted, resource); } finally { writeLock.unlock(); } if (!container.isAMContainer()) { // container got preempted is not a master container LOG.info(String.format( "Non-AM container preempted, current appAttemptId=%s, " + "containerId=%s, resource=%s", attemptId, container.getContainerId(), resource)); numNonAMContainersPreempted.incrementAndGet(); } else { // container got preempted is a master container LOG.info(String.format("AM container preempted, " + "current appAttemptId=%s, containerId=%s, resource=%s", attemptId, container.getContainerId(), resource)); isPreempted.set(true); } } public Resource getResourcePreempted() { try { readLock.lock(); return resourcePreempted; } finally { readLock.unlock(); } } public int getNumNonAMContainersPreempted() { return numNonAMContainersPreempted.get(); } public void setIsPreempted() { this.isPreempted.set(true); } public boolean getIsPreempted() { return this.isPreempted.get(); } public AggregateAppResourceUsage getAggregateAppResourceUsage() { long memorySeconds = finishedMemorySeconds.get(); long vcoreSeconds = finishedVcoreSeconds.get(); // Only add in the running containers if this is the active attempt. RMAppAttempt currentAttempt = rmContext.getRMApps() .get(attemptId.getApplicationId()).getCurrentAppAttempt(); if (currentAttempt.getAppAttemptId().equals(attemptId)) { ApplicationResourceUsageReport appResUsageReport = rmContext .getScheduler().getAppResourceUsageReport(attemptId); if (appResUsageReport != null) { memorySeconds += appResUsageReport.getMemorySeconds(); vcoreSeconds += appResUsageReport.getVcoreSeconds(); } } return new AggregateAppResourceUsage(memorySeconds, vcoreSeconds); } public void updateAggregateAppResourceUsage(long finishedMemorySeconds, long finishedVcoreSeconds) { this.finishedMemorySeconds.addAndGet(finishedMemorySeconds); this.finishedVcoreSeconds.addAndGet(finishedVcoreSeconds); } public void incNumAllocatedContainers(NodeType containerType, NodeType requestType) { localityStatistics[containerType.index][requestType.index]++; totalAllocatedContainers++; } public int[][] getLocalityStatistics() { return this.localityStatistics; } public int getTotalAllocatedContainers() { return this.totalAllocatedContainers; } public Resource getApplicationAttemptHeadroom() { return applicationHeadroom; } public void setApplicationAttemptHeadRoom(Resource headRoom) { this.applicationHeadroom = headRoom; } }
5,902
36.125786
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptUnregistrationEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; public class RMAppAttemptUnregistrationEvent extends RMAppAttemptEvent { private final String finalTrackingUrl; private final FinalApplicationStatus finalStatus; private final String diagnostics; public RMAppAttemptUnregistrationEvent(ApplicationAttemptId appAttemptId, String trackingUrl, FinalApplicationStatus finalStatus, String diagnostics) { super(appAttemptId, RMAppAttemptEventType.UNREGISTERED); this.finalTrackingUrl = trackingUrl; this.finalStatus = finalStatus; this.diagnostics = diagnostics; } public String getFinalTrackingUrl() { return this.finalTrackingUrl; } public FinalApplicationStatus getFinalApplicationStatus() { return this.finalStatus; } public String getDiagnostics() { return this.diagnostics; } }
1,980
36.377358
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptContainerFinishedEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; public class RMAppAttemptContainerFinishedEvent extends RMAppAttemptEvent { private final ContainerStatus containerStatus; private final NodeId nodeId; public RMAppAttemptContainerFinishedEvent(ApplicationAttemptId appAttemptId, ContainerStatus containerStatus, NodeId nodeId) { super(appAttemptId, RMAppAttemptEventType.CONTAINER_FINISHED); this.containerStatus = containerStatus; this.nodeId = nodeId; } public ContainerStatus getContainerStatus() { return this.containerStatus; } public NodeId getNodeId() { return this.nodeId; } }
1,816
37.659574
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptStatusupdateEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; public class RMAppAttemptStatusupdateEvent extends RMAppAttemptEvent { private final float progress; public RMAppAttemptStatusupdateEvent(ApplicationAttemptId appAttemptId, float progress) { super(appAttemptId, RMAppAttemptEventType.STATUS_UPDATE); this.progress = progress; } public float getProgress() { return this.progress; } }
1,489
36.25
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptRegistrationEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; public class RMAppAttemptRegistrationEvent extends RMAppAttemptEvent { private final ApplicationAttemptId appAttemptId; private final String host; private int rpcport; private String trackingurl; public RMAppAttemptRegistrationEvent(ApplicationAttemptId appAttemptId, String host, int rpcPort, String trackingUrl) { super(appAttemptId, RMAppAttemptEventType.REGISTERED); this.appAttemptId = appAttemptId; this.host = host; this.rpcport = rpcPort; this.trackingurl = trackingUrl; } public String getHost() { return this.host; } public int getRpcport() { return this.rpcport; } public String getTrackingurl() { return this.trackingurl; } }
1,830
33.54717
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptContainerAllocatedEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; public class RMAppAttemptContainerAllocatedEvent extends RMAppAttemptEvent { public RMAppAttemptContainerAllocatedEvent(ApplicationAttemptId appAttemptId) { super(appAttemptId, RMAppAttemptEventType.CONTAINER_ALLOCATED); } }
1,412
43.15625
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptLaunchFailedEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; public class RMAppAttemptLaunchFailedEvent extends RMAppAttemptEvent { private final String message; public RMAppAttemptLaunchFailedEvent(ApplicationAttemptId appAttemptId, String message) { super(appAttemptId, RMAppAttemptEventType.LAUNCH_FAILED); this.message = message; } public String getMessage() { return this.message; } }
1,485
37.102564
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/InMemoryReservationAllocation.java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.Collections; import java.util.Map; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; /** * An in memory implementation of a reservation allocation using the * {@link RLESparseResourceAllocation} * */ public class InMemoryReservationAllocation implements ReservationAllocation { private final String planName; private final ReservationId reservationID; private final String user; private final ReservationDefinition contract; private final long startTime; private final long endTime; private final Map<ReservationInterval, Resource> allocationRequests; private boolean hasGang = false; private long acceptedAt = -1; private RLESparseResourceAllocation resourcesOverTime; public InMemoryReservationAllocation(ReservationId reservationID, ReservationDefinition contract, String user, String planName, long startTime, long endTime, Map<ReservationInterval, Resource> allocations, ResourceCalculator calculator, Resource minAlloc) { this(reservationID, contract, user, planName, startTime, endTime, allocations, calculator, minAlloc, false); } public InMemoryReservationAllocation(ReservationId reservationID, ReservationDefinition contract, String user, String planName, long startTime, long endTime, Map<ReservationInterval, Resource> allocations, ResourceCalculator calculator, Resource minAlloc, boolean hasGang) { this.contract = contract; this.startTime = startTime; this.endTime = endTime; this.reservationID = reservationID; this.user = user; this.allocationRequests = allocations; this.planName = planName; this.hasGang = hasGang; resourcesOverTime = new RLESparseResourceAllocation(calculator, minAlloc); for (Map.Entry<ReservationInterval, Resource> r : allocations .entrySet()) { resourcesOverTime.addInterval(r.getKey(), r.getValue()); } } @Override public ReservationId getReservationId() { return reservationID; } @Override public ReservationDefinition getReservationDefinition() { return contract; } @Override public long getStartTime() { return startTime; } @Override public long getEndTime() { return endTime; } @Override public Map<ReservationInterval, Resource> getAllocationRequests() { return Collections.unmodifiableMap(allocationRequests); } @Override public String getPlanName() { return planName; } @Override public String getUser() { return user; } @Override public boolean containsGangs() { return hasGang; } @Override public void setAcceptanceTimestamp(long acceptedAt) { this.acceptedAt = acceptedAt; } @Override public long getAcceptanceTime() { return acceptedAt; } @Override public Resource getResourcesAtTime(long tick) { if (tick < startTime || tick >= endTime) { return Resource.newInstance(0, 0); } return Resources.clone(resourcesOverTime.getCapacityAtTime(tick)); } @Override public String toString() { StringBuilder sBuf = new StringBuilder(); sBuf.append(getReservationId()).append(" user:").append(getUser()) .append(" startTime: ").append(getStartTime()).append(" endTime: ") .append(getEndTime()).append(" alloc:[") .append(resourcesOverTime.toString()).append("] "); return sBuf.toString(); } @Override public int compareTo(ReservationAllocation other) { // reverse order of acceptance if (this.getAcceptanceTime() > other.getAcceptanceTime()) { return -1; } if (this.getAcceptanceTime() < other.getAcceptanceTime()) { return 1; } return 0; } @Override public int hashCode() { return reservationID.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InMemoryReservationAllocation other = (InMemoryReservationAllocation) obj; return this.reservationID.equals(other.getReservationId()); } }
5,396
29.84
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/NoOverCommitPolicy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.MismatchedUserException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.ResourceOverCommitException; import org.apache.hadoop.yarn.util.resource.Resources; /** * This policy enforce a simple physical cluster capacity constraints, by * validating that the allocation proposed fits in the current plan. This * validation is compatible with "updates" and in verifying the capacity * constraints it conceptually remove the prior version of the reservation. */ @LimitedPrivate("yarn") @Unstable public class NoOverCommitPolicy implements SharingPolicy { @Override public void validate(Plan plan, ReservationAllocation reservation) throws PlanningException { ReservationAllocation oldReservation = plan.getReservationById(reservation.getReservationId()); // check updates are using same name if (oldReservation != null && !oldReservation.getUser().equals(reservation.getUser())) { throw new MismatchedUserException( "Updating an existing reservation with mismatching user:" + oldReservation.getUser() + " != " + reservation.getUser()); } long startTime = reservation.getStartTime(); long endTime = reservation.getEndTime(); long step = plan.getStep(); // for every instant in time, check we are respecting cluster capacity for (long t = startTime; t < endTime; t += step) { Resource currExistingAllocTot = plan.getTotalCommittedResources(t); Resource currNewAlloc = reservation.getResourcesAtTime(t); Resource currOldAlloc = Resource.newInstance(0, 0); if (oldReservation != null) { oldReservation.getResourcesAtTime(t); } // check the cluster is never over committed // currExistingAllocTot + currNewAlloc - currOldAlloc > // capPlan.getTotalCapacity() if (Resources.greaterThan(plan.getResourceCalculator(), plan .getTotalCapacity(), Resources.subtract( Resources.add(currExistingAllocTot, currNewAlloc), currOldAlloc), plan.getTotalCapacity())) { throw new ResourceOverCommitException("Resources at time " + t + " would be overcommitted by " + "accepting reservation: " + reservation.getReservationId()); } } } @Override public long getValidWindow() { // this policy has no "memory" so the valid window is set to zero return 0; } @Override public void init(String planQueuePath, ReservationSchedulerConfiguration conf) { // nothing to do for this policy } }
3,798
39.849462
104
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; public interface ReservationConstants { /** * The suffix used for a queue under a reservable queue that will be used * as a default queue whenever no reservation is used */ String DEFAULT_QUEUE_SUFFIX = "-default"; }
1,106
37.172414
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/FairSchedulerPlanFollower.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.Collection; import java.util.List; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSLeafQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSParentQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.resource.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FairSchedulerPlanFollower extends AbstractSchedulerPlanFollower { private static final Logger LOG = LoggerFactory .getLogger(FairSchedulerPlanFollower.class); private FairScheduler fs; @Override public void init(Clock clock, ResourceScheduler sched, Collection<Plan> plans) { super.init(clock, sched, plans); fs = (FairScheduler)sched; LOG.info("Initializing Plan Follower Policy:" + this.getClass().getCanonicalName()); } @Override protected Queue getPlanQueue(String planQueueName) { Queue planQueue = fs.getQueueManager().getParentQueue(planQueueName, false); if (planQueue == null) { LOG.error("The queue " + planQueueName + " cannot be found or is not a " + "ParentQueue"); } return planQueue; } @Override protected float calculateReservationToPlanRatio(Resource clusterResources, Resource planResources, Resource capToAssign) { return Resources.divide(fs.getResourceCalculator(), clusterResources, capToAssign, planResources); } @Override protected boolean arePlanResourcesLessThanReservations(Resource clusterResources, Resource planResources, Resource reservedResources) { return Resources.greaterThan(fs.getResourceCalculator(), clusterResources, reservedResources, planResources); } @Override protected List<? extends Queue> getChildReservationQueues(Queue queue) { FSQueue planQueue = (FSQueue)queue; List<FSQueue> childQueues = planQueue.getChildQueues(); return childQueues; } @Override protected void addReservationQueue(String planQueueName, Queue queue, String currResId) { String leafQueueName = getReservationQueueName(planQueueName, currResId); fs.getQueueManager().getLeafQueue(leafQueueName, true); } @Override protected void createDefaultReservationQueue(String planQueueName, Queue queue, String defReservationId) { String defReservationQueueName = getReservationQueueName(planQueueName, defReservationId); if (!fs.getQueueManager().exists(defReservationQueueName)) { fs.getQueueManager().getLeafQueue(defReservationQueueName, true); } } @Override protected Resource getPlanResources(Plan plan, Queue queue, Resource clusterResources) { FSParentQueue planQueue = (FSParentQueue)queue; Resource planResources = planQueue.getSteadyFairShare(); return planResources; } @Override protected Resource getReservationQueueResourceIfExists(Plan plan, ReservationId reservationId) { String reservationQueueName = getReservationQueueName(plan.getQueueName(), reservationId.toString()); FSLeafQueue reservationQueue = fs.getQueueManager().getLeafQueue(reservationQueueName, false); Resource reservationResource = null; if (reservationQueue != null) { reservationResource = reservationQueue.getSteadyFairShare(); } return reservationResource; } @Override protected String getReservationQueueName(String planQueueName, String reservationQueueName) { String planQueueNameFullPath = fs.getQueueManager().getQueue (planQueueName).getName(); if (!reservationQueueName.startsWith(planQueueNameFullPath)) { // If name is not a path we need full path for FairScheduler. See // YARN-2773 for the root cause return planQueueNameFullPath + "." + reservationQueueName; } return reservationQueueName; } @Override protected String getReservationIdFromQueueName(String resQueueName) { return resQueueName.substring(resQueueName.lastIndexOf(".") + 1); } }
5,296
36.302817
82
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/RLESparseResourceAllocation.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.io.IOException; import java.io.StringWriter; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.gson.stream.JsonWriter; /** * This is a run length encoded sparse data structure that maintains resource * allocations over time. */ public class RLESparseResourceAllocation { private static final int THRESHOLD = 100; private static final Resource ZERO_RESOURCE = Resource.newInstance(0, 0); private TreeMap<Long, Resource> cumulativeCapacity = new TreeMap<Long, Resource>(); private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock readLock = readWriteLock.readLock(); private final Lock writeLock = readWriteLock.writeLock(); private final ResourceCalculator resourceCalculator; private final Resource minAlloc; public RLESparseResourceAllocation(ResourceCalculator resourceCalculator, Resource minAlloc) { this.resourceCalculator = resourceCalculator; this.minAlloc = minAlloc; } private boolean isSameAsPrevious(Long key, Resource capacity) { Entry<Long, Resource> previous = cumulativeCapacity.lowerEntry(key); return (previous != null && previous.getValue().equals(capacity)); } private boolean isSameAsNext(Long key, Resource capacity) { Entry<Long, Resource> next = cumulativeCapacity.higherEntry(key); return (next != null && next.getValue().equals(capacity)); } /** * Add a resource for the specified interval * * @param reservationInterval the interval for which the resource is to be * added * @param totCap the resource to be added * @return true if addition is successful, false otherwise */ public boolean addInterval(ReservationInterval reservationInterval, Resource totCap) { if (totCap.equals(ZERO_RESOURCE)) { return true; } writeLock.lock(); try { long startKey = reservationInterval.getStartTime(); long endKey = reservationInterval.getEndTime(); NavigableMap<Long, Resource> ticks = cumulativeCapacity.headMap(endKey, false); if (ticks != null && !ticks.isEmpty()) { Resource updatedCapacity = Resource.newInstance(0, 0); Entry<Long, Resource> lowEntry = ticks.floorEntry(startKey); if (lowEntry == null) { // This is the earliest starting interval cumulativeCapacity.put(startKey, totCap); } else { updatedCapacity = Resources.add(lowEntry.getValue(), totCap); // Add a new tick only if the updated value is different // from the previous tick if ((startKey == lowEntry.getKey()) && (isSameAsPrevious(lowEntry.getKey(), updatedCapacity))) { cumulativeCapacity.remove(lowEntry.getKey()); } else { cumulativeCapacity.put(startKey, updatedCapacity); } } // Increase all the capacities of overlapping intervals Set<Entry<Long, Resource>> overlapSet = ticks.tailMap(startKey, false).entrySet(); for (Entry<Long, Resource> entry : overlapSet) { updatedCapacity = Resources.add(entry.getValue(), totCap); entry.setValue(updatedCapacity); } } else { // This is the first interval to be added cumulativeCapacity.put(startKey, totCap); } Resource nextTick = cumulativeCapacity.get(endKey); if (nextTick != null) { // If there is overlap, remove the duplicate entry if (isSameAsPrevious(endKey, nextTick)) { cumulativeCapacity.remove(endKey); } } else { // Decrease capacity as this is end of the interval cumulativeCapacity.put(endKey, Resources.subtract(cumulativeCapacity .floorEntry(endKey).getValue(), totCap)); } return true; } finally { writeLock.unlock(); } } /** * Removes a resource for the specified interval * * @param reservationInterval the interval for which the resource is to be * removed * @param totCap the resource to be removed * @return true if removal is successful, false otherwise */ public boolean removeInterval(ReservationInterval reservationInterval, Resource totCap) { if (totCap.equals(ZERO_RESOURCE)) { return true; } writeLock.lock(); try { long startKey = reservationInterval.getStartTime(); long endKey = reservationInterval.getEndTime(); // update the start key NavigableMap<Long, Resource> ticks = cumulativeCapacity.headMap(endKey, false); // Decrease all the capacities of overlapping intervals SortedMap<Long, Resource> overlapSet = ticks.tailMap(startKey); if (overlapSet != null && !overlapSet.isEmpty()) { Resource updatedCapacity = Resource.newInstance(0, 0); long currentKey = -1; for (Iterator<Entry<Long, Resource>> overlapEntries = overlapSet.entrySet().iterator(); overlapEntries.hasNext();) { Entry<Long, Resource> entry = overlapEntries.next(); currentKey = entry.getKey(); updatedCapacity = Resources.subtract(entry.getValue(), totCap); // update each entry between start and end key cumulativeCapacity.put(currentKey, updatedCapacity); } // Remove the first overlap entry if it is same as previous after // updation Long firstKey = overlapSet.firstKey(); if (isSameAsPrevious(firstKey, overlapSet.get(firstKey))) { cumulativeCapacity.remove(firstKey); } // Remove the next entry if it is same as end entry after updation if ((currentKey != -1) && (isSameAsNext(currentKey, updatedCapacity))) { cumulativeCapacity.remove(cumulativeCapacity.higherKey(currentKey)); } } return true; } finally { writeLock.unlock(); } } /** * Returns the capacity, i.e. total resources allocated at the specified point * of time * * @param tick the time (UTC in ms) at which the capacity is requested * @return the resources allocated at the specified time */ public Resource getCapacityAtTime(long tick) { readLock.lock(); try { Entry<Long, Resource> closestStep = cumulativeCapacity.floorEntry(tick); if (closestStep != null) { return Resources.clone(closestStep.getValue()); } return Resources.clone(ZERO_RESOURCE); } finally { readLock.unlock(); } } /** * Get the timestamp of the earliest resource allocation * * @return the timestamp of the first resource allocation */ public long getEarliestStartTime() { readLock.lock(); try { if (cumulativeCapacity.isEmpty()) { return -1; } else { return cumulativeCapacity.firstKey(); } } finally { readLock.unlock(); } } /** * Get the timestamp of the latest resource allocation * * @return the timestamp of the last resource allocation */ public long getLatestEndTime() { readLock.lock(); try { if (cumulativeCapacity.isEmpty()) { return -1; } else { return cumulativeCapacity.lastKey(); } } finally { readLock.unlock(); } } /** * Returns true if there are no non-zero entries * * @return true if there are no allocations or false otherwise */ public boolean isEmpty() { readLock.lock(); try { if (cumulativeCapacity.isEmpty()) { return true; } // Deletion leaves a single zero entry so check for that if (cumulativeCapacity.size() == 1) { return cumulativeCapacity.firstEntry().getValue().equals(ZERO_RESOURCE); } return false; } finally { readLock.unlock(); } } @Override public String toString() { StringBuilder ret = new StringBuilder(); readLock.lock(); try { if (cumulativeCapacity.size() > THRESHOLD) { ret.append("Number of steps: ").append(cumulativeCapacity.size()) .append(" earliest entry: ").append(cumulativeCapacity.firstKey()) .append(" latest entry: ").append(cumulativeCapacity.lastKey()); } else { for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) { ret.append(r.getKey()).append(": ").append(r.getValue()) .append("\n "); } } return ret.toString(); } finally { readLock.unlock(); } } /** * Returns the JSON string representation of the current resources allocated * over time * * @return the JSON string representation of the current resources allocated * over time */ public String toMemJSONString() { StringWriter json = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(json); readLock.lock(); try { jsonWriter.beginObject(); // jsonWriter.name("timestamp").value("resource"); for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) { jsonWriter.name(r.getKey().toString()).value(r.getValue().toString()); } jsonWriter.endObject(); jsonWriter.close(); return json.toString(); } catch (IOException e) { // This should not happen return ""; } finally { readLock.unlock(); } } /** * Returns the representation of the current resources allocated over time as * an interval map. * * @return the representation of the current resources allocated over time as * an interval map. */ public Map<ReservationInterval, Resource> toIntervalMap() { readLock.lock(); try { Map<ReservationInterval, Resource> allocations = new TreeMap<ReservationInterval, Resource>(); // Empty if (isEmpty()) { return allocations; } Map.Entry<Long, Resource> lastEntry = null; for (Map.Entry<Long, Resource> entry : cumulativeCapacity.entrySet()) { if (lastEntry != null) { ReservationInterval interval = new ReservationInterval(lastEntry.getKey(), entry.getKey()); Resource resource = lastEntry.getValue(); allocations.put(interval, resource); } lastEntry = entry; } return allocations; } finally { readLock.unlock(); } } }
11,627
31.75493
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/AbstractReservationSystem.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.Planner; import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.ReservationAgent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.UTCClock; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is the implementation of {@link ReservationSystem} based on the * {@link ResourceScheduler} */ @LimitedPrivate("yarn") @Unstable public abstract class AbstractReservationSystem extends AbstractService implements ReservationSystem { private static final Logger LOG = LoggerFactory .getLogger(AbstractReservationSystem.class); // private static final String DEFAULT_CAPACITY_SCHEDULER_PLAN private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); private final Lock readLock = readWriteLock.readLock(); private final Lock writeLock = readWriteLock.writeLock(); private boolean initialized = false; private final Clock clock = new UTCClock(); private AtomicLong resCounter = new AtomicLong(); private Map<String, Plan> plans = new HashMap<String, Plan>(); private Map<ReservationId, String> resQMap = new HashMap<ReservationId, String>(); private RMContext rmContext; private ResourceScheduler scheduler; private ScheduledExecutorService scheduledExecutorService; protected Configuration conf; protected long planStepSize; private PlanFollower planFollower; /** * Construct the service. * * @param name service name */ public AbstractReservationSystem(String name) { super(name); } @Override public void setRMContext(RMContext rmContext) { writeLock.lock(); try { this.rmContext = rmContext; } finally { writeLock.unlock(); } } @Override public void reinitialize(Configuration conf, RMContext rmContext) throws YarnException { writeLock.lock(); try { if (!initialized) { initialize(conf); initialized = true; } else { initializeNewPlans(conf); } } finally { writeLock.unlock(); } } private void initialize(Configuration conf) throws YarnException { LOG.info("Initializing Reservation system"); this.conf = conf; scheduler = rmContext.getScheduler(); // Get the plan step size planStepSize = conf.getTimeDuration( YarnConfiguration.RM_RESERVATION_SYSTEM_PLAN_FOLLOWER_TIME_STEP, YarnConfiguration.DEFAULT_RM_RESERVATION_SYSTEM_PLAN_FOLLOWER_TIME_STEP, TimeUnit.MILLISECONDS); if (planStepSize < 0) { planStepSize = YarnConfiguration.DEFAULT_RM_RESERVATION_SYSTEM_PLAN_FOLLOWER_TIME_STEP; } // Create a plan corresponding to every reservable queue Set<String> planQueueNames = scheduler.getPlanQueues(); for (String planQueueName : planQueueNames) { Plan plan = initializePlan(planQueueName); plans.put(planQueueName, plan); } } private void initializeNewPlans(Configuration conf) { LOG.info("Refreshing Reservation system"); writeLock.lock(); try { // Create a plan corresponding to every new reservable queue Set<String> planQueueNames = scheduler.getPlanQueues(); for (String planQueueName : planQueueNames) { if (!plans.containsKey(planQueueName)) { Plan plan = initializePlan(planQueueName); plans.put(planQueueName, plan); } else { LOG.warn("Plan based on reservation queue {0} already exists.", planQueueName); } } // Update the plan follower with the active plans if (planFollower != null) { planFollower.setPlans(plans.values()); } } catch (YarnException e) { LOG.warn("Exception while trying to refresh reservable queues", e); } finally { writeLock.unlock(); } } private PlanFollower createPlanFollower() { String planFollowerPolicyClassName = conf.get(YarnConfiguration.RM_RESERVATION_SYSTEM_PLAN_FOLLOWER, getDefaultPlanFollower()); if (planFollowerPolicyClassName == null) { return null; } LOG.info("Using PlanFollowerPolicy: " + planFollowerPolicyClassName); try { Class<?> planFollowerPolicyClazz = conf.getClassByName(planFollowerPolicyClassName); if (PlanFollower.class.isAssignableFrom(planFollowerPolicyClazz)) { return (PlanFollower) ReflectionUtils.newInstance( planFollowerPolicyClazz, conf); } else { throw new YarnRuntimeException("Class: " + planFollowerPolicyClassName + " not instance of " + PlanFollower.class.getCanonicalName()); } } catch (ClassNotFoundException e) { throw new YarnRuntimeException( "Could not instantiate PlanFollowerPolicy: " + planFollowerPolicyClassName, e); } } private String getDefaultPlanFollower() { // currently only capacity scheduler is supported if (scheduler instanceof CapacityScheduler) { return CapacitySchedulerPlanFollower.class.getName(); } else if (scheduler instanceof FairScheduler) { return FairSchedulerPlanFollower.class.getName(); } return null; } @Override public Plan getPlan(String planName) { readLock.lock(); try { return plans.get(planName); } finally { readLock.unlock(); } } /** * @return the planStepSize */ @Override public long getPlanFollowerTimeStep() { readLock.lock(); try { return planStepSize; } finally { readLock.unlock(); } } @Override public void synchronizePlan(String planName) { writeLock.lock(); try { Plan plan = plans.get(planName); if (plan != null) { planFollower.synchronizePlan(plan); } } finally { writeLock.unlock(); } } @Override public void serviceInit(Configuration conf) throws Exception { Configuration configuration = new Configuration(conf); reinitialize(configuration, rmContext); // Create the plan follower with the active plans planFollower = createPlanFollower(); if (planFollower != null) { planFollower.init(clock, scheduler, plans.values()); } super.serviceInit(conf); } @Override public void serviceStart() throws Exception { if (planFollower != null) { scheduledExecutorService = new ScheduledThreadPoolExecutor(1); scheduledExecutorService.scheduleWithFixedDelay(planFollower, 0L, planStepSize, TimeUnit.MILLISECONDS); } super.serviceStart(); } @Override public void serviceStop() { // Stop the plan follower if (scheduledExecutorService != null && !scheduledExecutorService.isShutdown()) { scheduledExecutorService.shutdown(); } // Clear the plans plans.clear(); } @Override public String getQueueForReservation(ReservationId reservationId) { readLock.lock(); try { return resQMap.get(reservationId); } finally { readLock.unlock(); } } @Override public void setQueueForReservation(ReservationId reservationId, String queueName) { writeLock.lock(); try { resQMap.put(reservationId, queueName); } finally { writeLock.unlock(); } } @Override public ReservationId getNewReservationId() { writeLock.lock(); try { ReservationId resId = ReservationId.newInstance(ResourceManager.getClusterTimeStamp(), resCounter.incrementAndGet()); LOG.info("Allocated new reservationId: " + resId); return resId; } finally { writeLock.unlock(); } } @Override public Map<String, Plan> getAllPlans() { return plans; } /** * Get the default reservation system corresponding to the scheduler * * @param scheduler the scheduler for which the reservation system is required */ public static String getDefaultReservationSystem(ResourceScheduler scheduler) { if (scheduler instanceof CapacityScheduler) { return CapacityReservationSystem.class.getName(); } else if (scheduler instanceof FairScheduler) { return FairReservationSystem.class.getName(); } return null; } protected Plan initializePlan(String planQueueName) throws YarnException { String planQueuePath = getPlanQueuePath(planQueueName); SharingPolicy adPolicy = getAdmissionPolicy(planQueuePath); adPolicy.init(planQueuePath, getReservationSchedulerConfiguration()); // Calculate the max plan capacity Resource minAllocation = getMinAllocation(); Resource maxAllocation = getMaxAllocation(); ResourceCalculator rescCalc = getResourceCalculator(); Resource totCap = getPlanQueueCapacity(planQueueName); Plan plan = new InMemoryPlan(getRootQueueMetrics(), adPolicy, getAgent(planQueuePath), totCap, planStepSize, rescCalc, minAllocation, maxAllocation, planQueueName, getReplanner(planQueuePath), getReservationSchedulerConfiguration() .getMoveOnExpiry(planQueuePath)); LOG.info("Intialized plan {0} based on reservable queue {1}", plan.toString(), planQueueName); return plan; } protected Planner getReplanner(String planQueueName) { ReservationSchedulerConfiguration reservationConfig = getReservationSchedulerConfiguration(); String plannerClassName = reservationConfig.getReplanner(planQueueName); LOG.info("Using Replanner: " + plannerClassName + " for queue: " + planQueueName); try { Class<?> plannerClazz = conf.getClassByName(plannerClassName); if (Planner.class.isAssignableFrom(plannerClazz)) { Planner planner = (Planner) ReflectionUtils.newInstance(plannerClazz, conf); planner.init(planQueueName, reservationConfig); return planner; } else { throw new YarnRuntimeException("Class: " + plannerClazz + " not instance of " + Planner.class.getCanonicalName()); } } catch (ClassNotFoundException e) { throw new YarnRuntimeException("Could not instantiate Planner: " + plannerClassName + " for queue: " + planQueueName, e); } } protected ReservationAgent getAgent(String queueName) { ReservationSchedulerConfiguration reservationConfig = getReservationSchedulerConfiguration(); String agentClassName = reservationConfig.getReservationAgent(queueName); LOG.info("Using Agent: " + agentClassName + " for queue: " + queueName); try { Class<?> agentClazz = conf.getClassByName(agentClassName); if (ReservationAgent.class.isAssignableFrom(agentClazz)) { return (ReservationAgent) ReflectionUtils.newInstance(agentClazz, conf); } else { throw new YarnRuntimeException("Class: " + agentClassName + " not instance of " + ReservationAgent.class.getCanonicalName()); } } catch (ClassNotFoundException e) { throw new YarnRuntimeException("Could not instantiate Agent: " + agentClassName + " for queue: " + queueName, e); } } protected SharingPolicy getAdmissionPolicy(String queueName) { ReservationSchedulerConfiguration reservationConfig = getReservationSchedulerConfiguration(); String admissionPolicyClassName = reservationConfig.getReservationAdmissionPolicy(queueName); LOG.info("Using AdmissionPolicy: " + admissionPolicyClassName + " for queue: " + queueName); try { Class<?> admissionPolicyClazz = conf.getClassByName(admissionPolicyClassName); if (SharingPolicy.class.isAssignableFrom(admissionPolicyClazz)) { return (SharingPolicy) ReflectionUtils.newInstance( admissionPolicyClazz, conf); } else { throw new YarnRuntimeException("Class: " + admissionPolicyClassName + " not instance of " + SharingPolicy.class.getCanonicalName()); } } catch (ClassNotFoundException e) { throw new YarnRuntimeException("Could not instantiate AdmissionPolicy: " + admissionPolicyClassName + " for queue: " + queueName, e); } } protected abstract ReservationSchedulerConfiguration getReservationSchedulerConfiguration(); protected abstract String getPlanQueuePath(String planQueueName); protected abstract Resource getPlanQueueCapacity(String planQueueName); protected abstract Resource getMinAllocation(); protected abstract Resource getMaxAllocation(); protected abstract ResourceCalculator getResourceCalculator(); protected abstract QueueMetrics getRootQueueMetrics(); }
14,992
33.230594
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationSystemUtil.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.impl.pb.ReservationDefinitionPBImpl; import org.apache.hadoop.yarn.api.records.impl.pb.ReservationIdPBImpl; import org.apache.hadoop.yarn.api.records.impl.pb.ResourcePBImpl; import org.apache.hadoop.yarn.proto.YarnProtos; import org.apache.hadoop.yarn.proto.YarnProtos.ReservationDefinitionProto; import org.apache.hadoop.yarn.proto.YarnProtos.ReservationIdProto; import org.apache.hadoop.yarn.proto.YarnProtos.ResourceProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ResourceAllocationRequestProto; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Simple helper class for static methods used to transform across * common formats in tests */ public final class ReservationSystemUtil { private ReservationSystemUtil() { // not called } public static Resource toResource(ReservationRequest request) { Resource resource = Resources.multiply(request.getCapability(), (float) request.getNumContainers()); return resource; } public static Map<ReservationInterval, Resource> toResources( Map<ReservationInterval, ReservationRequest> allocations) { Map<ReservationInterval, Resource> resources = new HashMap<ReservationInterval, Resource>(); for (Map.Entry<ReservationInterval, ReservationRequest> entry : allocations.entrySet()) { resources.put(entry.getKey(), toResource(entry.getValue())); } return resources; } public static ReservationAllocationStateProto buildStateProto( ReservationAllocation allocation) { ReservationAllocationStateProto.Builder builder = ReservationAllocationStateProto.newBuilder(); builder.setAcceptanceTimestamp(allocation.getAcceptanceTime()); builder.setContainsGangs(allocation.containsGangs()); builder.setStartTime(allocation.getStartTime()); builder.setEndTime(allocation.getEndTime()); builder.setUser(allocation.getUser()); ReservationDefinitionProto definitionProto = convertToProtoFormat( allocation.getReservationDefinition()); builder.setReservationDefinition(definitionProto); for (Map.Entry<ReservationInterval, Resource> entry : allocation.getAllocationRequests().entrySet()) { ResourceAllocationRequestProto p = ResourceAllocationRequestProto.newBuilder() .setStartTime(entry.getKey().getStartTime()) .setEndTime(entry.getKey().getEndTime()) .setResource(convertToProtoFormat(entry.getValue())) .build(); builder.addAllocationRequests(p); } ReservationAllocationStateProto allocationProto = builder.build(); return allocationProto; } private static ReservationDefinitionProto convertToProtoFormat( ReservationDefinition reservationDefinition) { return ((ReservationDefinitionPBImpl)reservationDefinition).getProto(); } public static ResourceProto convertToProtoFormat(Resource e) { return YarnProtos.ResourceProto.newBuilder() .setMemory(e.getMemory()) .setVirtualCores(e.getVirtualCores()) .build(); } public static Map<ReservationInterval, Resource> toAllocations( List<ResourceAllocationRequestProto> allocationRequestsList) { Map<ReservationInterval, Resource> allocations = new HashMap<>(); for (ResourceAllocationRequestProto proto : allocationRequestsList) { allocations.put( new ReservationInterval(proto.getStartTime(), proto.getEndTime()), convertFromProtoFormat(proto.getResource())); } return allocations; } private static ResourcePBImpl convertFromProtoFormat(ResourceProto resource) { return new ResourcePBImpl(resource); } public static ReservationDefinitionPBImpl convertFromProtoFormat( ReservationDefinitionProto r) { return new ReservationDefinitionPBImpl(r); } public static ReservationIdPBImpl convertFromProtoFormat( ReservationIdProto r) { return new ReservationIdPBImpl(r); } public static ReservationId toReservationId( ReservationIdProto reservationId) { return new ReservationIdPBImpl(reservationId); } public static InMemoryReservationAllocation toInMemoryAllocation( String planName, ReservationId reservationId, ReservationAllocationStateProto allocationState, Resource minAlloc, ResourceCalculator planResourceCalculator) { ReservationDefinition definition = convertFromProtoFormat( allocationState.getReservationDefinition()); Map<ReservationInterval, Resource> allocations = toAllocations( allocationState.getAllocationRequestsList()); InMemoryReservationAllocation allocation = new InMemoryReservationAllocation(reservationId, definition, allocationState.getUser(), planName, allocationState.getStartTime(), allocationState.getEndTime(), allocations, planResourceCalculator, minAlloc, allocationState.getContainsGangs()); return allocation; } }
6,359
39.769231
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/CapacitySchedulerPlanFollower.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.io.IOException; import java.util.Collection; import java.util.List; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerDynamicEditException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.PlanQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.ReservationQueue; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.resource.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class implements a {@link PlanFollower}. This is invoked on a timer, and * it is in charge to publish the state of the {@link Plan}s to the underlying * {@link CapacityScheduler}. This implementation does so, by * adding/removing/resizing leaf queues in the scheduler, thus affecting the * dynamic behavior of the scheduler in a way that is consistent with the * content of the plan. It also updates the plan's view on how much resources * are available in the cluster. * * This implementation of PlanFollower is relatively stateless, and it can * synchronize schedulers and Plans that have arbitrary changes (performing set * differences among existing queues). This makes it resilient to frequency of * synchronization, and RM restart issues (no "catch up" is necessary). */ public class CapacitySchedulerPlanFollower extends AbstractSchedulerPlanFollower { private static final Logger LOG = LoggerFactory .getLogger(CapacitySchedulerPlanFollower.class); private CapacityScheduler cs; @Override public void init(Clock clock, ResourceScheduler sched, Collection<Plan> plans) { super.init(clock, sched, plans); LOG.info("Initializing Plan Follower Policy:" + this.getClass().getCanonicalName()); if (!(sched instanceof CapacityScheduler)) { throw new YarnRuntimeException( "CapacitySchedulerPlanFollower can only work with CapacityScheduler"); } this.cs = (CapacityScheduler) sched; } @Override protected Queue getPlanQueue(String planQueueName) { CSQueue queue = cs.getQueue(planQueueName); if (!(queue instanceof PlanQueue)) { LOG.error("The Plan is not an PlanQueue!"); return null; } return queue; } @Override protected float calculateReservationToPlanRatio( Resource clusterResources, Resource planResources, Resource reservationResources) { return Resources.divide(cs.getResourceCalculator(), clusterResources, reservationResources, planResources); } @Override protected boolean arePlanResourcesLessThanReservations( Resource clusterResources, Resource planResources, Resource reservedResources) { return Resources.greaterThan(cs.getResourceCalculator(), clusterResources, reservedResources, planResources); } @Override protected List<? extends Queue> getChildReservationQueues(Queue queue) { PlanQueue planQueue = (PlanQueue)queue; List<CSQueue> childQueues = planQueue.getChildQueues(); return childQueues; } @Override protected void addReservationQueue( String planQueueName, Queue queue, String currResId) { PlanQueue planQueue = (PlanQueue)queue; try { ReservationQueue resQueue = new ReservationQueue(cs, currResId, planQueue); cs.addQueue(resQueue); } catch (SchedulerDynamicEditException e) { LOG.warn( "Exception while trying to activate reservation: {} for plan: {}", currResId, planQueueName, e); } catch (IOException e) { LOG.warn( "Exception while trying to activate reservation: {} for plan: {}", currResId, planQueueName, e); } } @Override protected void createDefaultReservationQueue( String planQueueName, Queue queue, String defReservationId) { PlanQueue planQueue = (PlanQueue)queue; if (cs.getQueue(defReservationId) == null) { try { ReservationQueue defQueue = new ReservationQueue(cs, defReservationId, planQueue); cs.addQueue(defQueue); } catch (SchedulerDynamicEditException e) { LOG.warn( "Exception while trying to create default reservation queue for plan: {}", planQueueName, e); } catch (IOException e) { LOG.warn( "Exception while trying to create default reservation queue for " + "plan: {}", planQueueName, e); } } } @Override protected Resource getPlanResources( Plan plan, Queue queue, Resource clusterResources) { PlanQueue planQueue = (PlanQueue)queue; float planAbsCap = planQueue.getAbsoluteCapacity(); Resource planResources = Resources.multiply(clusterResources, planAbsCap); plan.setTotalCapacity(planResources); return planResources; } @Override protected Resource getReservationQueueResourceIfExists(Plan plan, ReservationId reservationId) { CSQueue resQueue = cs.getQueue(reservationId.toString()); Resource reservationResource = null; if (resQueue != null) { reservationResource = Resources.multiply(cs.getClusterResource(), resQueue.getAbsoluteCapacity()); } return reservationResource; } }
6,569
37.647059
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/PlanContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.Planner; import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.ReservationAgent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; /** * This interface provides read-only access to configuration-type parameter for * a plan. * */ public interface PlanContext { /** * Returns the configured "step" or granularity of time of the plan in millis. * * @return plan step in millis */ public long getStep(); /** * Return the {@link ReservationAgent} configured for this plan that is * responsible for optimally placing various reservation requests * * @return the {@link ReservationAgent} configured for this plan */ public ReservationAgent getReservationAgent(); /** * Return an instance of a {@link Planner}, which will be invoked in response * to unexpected reduction in the resources of this plan * * @return an instance of a {@link Planner}, which will be invoked in response * to unexpected reduction in the resources of this plan */ public Planner getReplanner(); /** * Return the configured {@link SharingPolicy} that governs the sharing of the * resources of the plan between its various users * * @return the configured {@link SharingPolicy} that governs the sharing of * the resources of the plan between its various users */ public SharingPolicy getSharingPolicy(); /** * Returns the system {@link ResourceCalculator} * * @return the system {@link ResourceCalculator} */ public ResourceCalculator getResourceCalculator(); /** * Returns the single smallest {@link Resource} allocation that can be * reserved in this plan * * @return the single smallest {@link Resource} allocation that can be * reserved in this plan */ public Resource getMinimumAllocation(); /** * Returns the single largest {@link Resource} allocation that can be reserved * in this plan * * @return the single largest {@link Resource} allocation that can be reserved * in this plan */ public Resource getMaximumAllocation(); /** * Return the name of the queue in the {@link ResourceScheduler} corresponding * to this plan * * @return the name of the queue in the {@link ResourceScheduler} * corresponding to this plan */ public String getQueueName(); /** * Return the {@link QueueMetrics} for the queue in the * {@link ResourceScheduler} corresponding to this plan * * @return the {@link QueueMetrics} for the queue in the * {@link ResourceScheduler} corresponding to this plan */ public QueueMetrics getQueueMetrics(); /** * Instructs the {@link PlanFollower} on what to do for applications * which are still running when the reservation is expiring (move-to-default * vs kill) * * @return true if remaining applications have to be killed, false if they * have to migrated */ public boolean getMoveOnExpiry(); }
4,172
33.204918
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationSystem.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import java.util.Map; /** * This interface is the one implemented by any system that wants to support * Reservations i.e. make {@code Resource} allocations in future. Implementors * need to bootstrap all configured {@link Plan}s in the active * {@link ResourceScheduler} along with their corresponding * {@code ReservationAgent} and {@link SharingPolicy}. It is also responsible * for managing the {@link PlanFollower} to ensure the {@link Plan}s are in sync * with the {@link ResourceScheduler}. */ @LimitedPrivate("yarn") @Unstable public interface ReservationSystem { /** * Set RMContext for {@link ReservationSystem}. This method should be called * immediately after instantiating a reservation system once. * * @param rmContext created by {@code ResourceManager} */ void setRMContext(RMContext rmContext); /** * Re-initialize the {@link ReservationSystem}. * * @param conf configuration * @param rmContext current context of the {@code ResourceManager} * @throws YarnException */ void reinitialize(Configuration conf, RMContext rmContext) throws YarnException; /** * Get an existing {@link Plan} that has been initialized. * * @param planName the name of the {@link Plan} * @return the {@link Plan} identified by name * */ Plan getPlan(String planName); /** * Return a map containing all the plans known to this ReservationSystem * (useful for UI) * * @return a Map of Plan names and Plan objects */ Map<String, Plan> getAllPlans(); /** * Invokes {@link PlanFollower} to synchronize the specified {@link Plan} with * the {@link ResourceScheduler} * * @param planName the name of the {@link Plan} to be synchronized */ void synchronizePlan(String planName); /** * Return the time step (ms) at which the {@link PlanFollower} is invoked * * @return the time step (ms) at which the {@link PlanFollower} is invoked */ long getPlanFollowerTimeStep(); /** * Get a new unique {@link ReservationId}. * * @return a new unique {@link ReservationId} * */ ReservationId getNewReservationId(); /** * Get the {@link Queue} that an existing {@link ReservationId} is associated * with. * * @param reservationId the unique id of the reservation * @return the name of the associated Queue * */ String getQueueForReservation(ReservationId reservationId); /** * Set the {@link Queue} that an existing {@link ReservationId} should be * associated with. * * @param reservationId the unique id of the reservation * @param queueName the name of Queue to associate the reservation with * */ void setQueueForReservation(ReservationId reservationId, String queueName); }
4,166
32.604839
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/CapacityOverTimePolicy.java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.Date; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.MismatchedUserException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningQuotaException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.ResourceOverCommitException; import org.apache.hadoop.yarn.util.resource.Resources; /** * This policy enforces a time-extended notion of Capacity. In particular it * guarantees that the allocation received in input when combined with all * previous allocation for the user does not violate an instantaneous max limit * on the resources received, and that for every window of time of length * validWindow, the integral of the allocations for a user (sum of the currently * submitted allocation and all prior allocations for the user) does not exceed * validWindow * maxAvg. * * This allows flexibility, in the sense that an allocation can instantaneously * use large portions of the available capacity, but prevents abuses by bounding * the average use over time. * * By controlling maxInst, maxAvg, validWindow the administrator configuring * this policy can obtain a behavior ranging from instantaneously enforced * capacity (akin to existing queues), or fully flexible allocations (likely * reserved to super-users, or trusted systems). */ @LimitedPrivate("yarn") @Unstable public class CapacityOverTimePolicy implements SharingPolicy { private ReservationSchedulerConfiguration conf; private long validWindow; private float maxInst; private float maxAvg; // For now this is CapacityScheduler specific, but given a hierarchy in the // configuration structure of the schedulers (e.g., SchedulerConfiguration) // it should be easy to remove this limitation @Override public void init(String reservationQueuePath, ReservationSchedulerConfiguration conf) { this.conf = conf; validWindow = this.conf.getReservationWindow(reservationQueuePath); maxInst = this.conf.getInstantaneousMaxCapacity(reservationQueuePath) / 100; maxAvg = this.conf.getAverageCapacity(reservationQueuePath) / 100; }; @Override public void validate(Plan plan, ReservationAllocation reservation) throws PlanningException { // this is entire method invoked under a write-lock on the plan, no need // to synchronize accesses to the plan further // Try to verify whether there is already a reservation with this ID in // the system (remove its contribution during validation to simulate a // try-n-swap // update). ReservationAllocation oldReservation = plan.getReservationById(reservation.getReservationId()); // sanity check that the update of a reservation is not changing username if (oldReservation != null && !oldReservation.getUser().equals(reservation.getUser())) { throw new MismatchedUserException( "Updating an existing reservation with mismatched user:" + oldReservation.getUser() + " != " + reservation.getUser()); } long startTime = reservation.getStartTime(); long endTime = reservation.getEndTime(); long step = plan.getStep(); Resource planTotalCapacity = plan.getTotalCapacity(); Resource maxAvgRes = Resources.multiply(planTotalCapacity, maxAvg); Resource maxInsRes = Resources.multiply(planTotalCapacity, maxInst); // define variable that will store integral of resources (need diff class to // avoid overflow issues for long/large allocations) IntegralResource runningTot = new IntegralResource(0L, 0L); IntegralResource maxAllowed = new IntegralResource(maxAvgRes); maxAllowed.multiplyBy(validWindow / step); // check that the resources offered to the user during any window of length // "validWindow" overlapping this allocation are within maxAllowed // also enforce instantaneous and physical constraints during this pass for (long t = startTime - validWindow; t < endTime + validWindow; t += step) { Resource currExistingAllocTot = plan.getTotalCommittedResources(t); Resource currExistingAllocForUser = plan.getConsumptionForUser(reservation.getUser(), t); Resource currNewAlloc = reservation.getResourcesAtTime(t); Resource currOldAlloc = Resources.none(); if (oldReservation != null) { currOldAlloc = oldReservation.getResourcesAtTime(t); } // throw exception if the cluster is overcommitted // tot_allocated - old + new > capacity Resource inst = Resources.subtract(Resources.add(currExistingAllocTot, currNewAlloc), currOldAlloc); if (Resources.greaterThan(plan.getResourceCalculator(), planTotalCapacity, inst, planTotalCapacity)) { throw new ResourceOverCommitException(" Resources at time " + t + " would be overcommitted (" + inst + " over " + plan.getTotalCapacity() + ") by accepting reservation: " + reservation.getReservationId()); } // throw exception if instantaneous limits are violated // tot_alloc_to_this_user - old + new > inst_limit if (Resources.greaterThan(plan.getResourceCalculator(), planTotalCapacity, Resources.subtract( Resources.add(currExistingAllocForUser, currNewAlloc), currOldAlloc), maxInsRes)) { throw new PlanningQuotaException("Instantaneous quota capacity " + maxInst + " would be passed at time " + t + " by accepting reservation: " + reservation.getReservationId()); } // throw exception if the running integral of utilization over validWindow // is violated. We perform a delta check, adding/removing instants at the // boundary of the window from runningTot. // runningTot = previous_runningTot + currExistingAllocForUser + // currNewAlloc - currOldAlloc - pastNewAlloc - pastOldAlloc; // Where: // 1) currNewAlloc, currExistingAllocForUser represent the contribution of // the instant in time added in this pass. // 2) pastNewAlloc, pastOldAlloc are the contributions relative to time // instants that are being retired from the the window // 3) currOldAlloc is the contribution (if any) of the previous version of // this reservation (the one we are updating) runningTot.add(currExistingAllocForUser); runningTot.add(currNewAlloc); runningTot.subtract(currOldAlloc); // expire contributions from instant in time before (t - validWindow) if (t > startTime) { Resource pastOldAlloc = plan.getConsumptionForUser(reservation.getUser(), t - validWindow); Resource pastNewAlloc = reservation.getResourcesAtTime(t - validWindow); // runningTot = runningTot - pastExistingAlloc - pastNewAlloc; runningTot.subtract(pastOldAlloc); runningTot.subtract(pastNewAlloc); } // check integral // runningTot > maxAvg * validWindow // NOTE: we need to use comparator of IntegralResource directly, as // Resource and ResourceCalculator assume "int" amount of resources, // which is not sufficient when comparing integrals (out-of-bound) if (maxAllowed.compareTo(runningTot) < 0) { throw new PlanningQuotaException( "Integral (avg over time) quota capacity " + maxAvg + " over a window of " + validWindow / 1000 + " seconds, " + " would be passed at time " + t + "(" + new Date(t) + ") by accepting reservation: " + reservation.getReservationId()); } } } @Override public long getValidWindow() { return validWindow; } /** * This class provides support for Resource-like book-keeping, based on * long(s), as using Resource to store the "integral" of the allocation over * time leads to integer overflows for large allocations/clusters. (Evolving * Resource to use long is too disruptive at this point.) * * The comparison/multiplication behaviors of IntegralResource are consistent * with the DefaultResourceCalculator. */ private static class IntegralResource { long memory; long vcores; public IntegralResource(Resource resource) { this.memory = resource.getMemory(); this.vcores = resource.getVirtualCores(); } public IntegralResource(long mem, long vcores) { this.memory = mem; this.vcores = vcores; } public void add(Resource r) { memory += r.getMemory(); vcores += r.getVirtualCores(); } public void subtract(Resource r) { memory -= r.getMemory(); vcores -= r.getVirtualCores(); } public void multiplyBy(long window) { memory = memory * window; vcores = vcores * window; } public long compareTo(IntegralResource other) { long diff = memory - other.memory; if (diff == 0) { diff = vcores - other.vcores; } return diff; } @Override public String toString() { return "<memory:" + memory + ", vCores:" + vcores + ">"; } } }
10,491
41.306452
104
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/AbstractSchedulerPlanFollower.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.QueueEntitlement; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.resource.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; public abstract class AbstractSchedulerPlanFollower implements PlanFollower { private static final Logger LOG = LoggerFactory .getLogger(CapacitySchedulerPlanFollower.class); protected Collection<Plan> plans = new ArrayList<Plan>(); protected YarnScheduler scheduler; protected Clock clock; @Override public void init(Clock clock, ResourceScheduler sched, Collection<Plan> plans) { this.clock = clock; this.scheduler = sched; this.plans.addAll(plans); } @Override public synchronized void run() { for (Plan plan : plans) { synchronizePlan(plan); } } @Override public synchronized void setPlans(Collection<Plan> plans) { this.plans.clear(); this.plans.addAll(plans); } @Override public synchronized void synchronizePlan(Plan plan) { String planQueueName = plan.getQueueName(); if (LOG.isDebugEnabled()) { LOG.debug("Running plan follower edit policy for plan: " + planQueueName); } // align with plan step long step = plan.getStep(); long now = clock.getTime(); if (now % step != 0) { now += step - (now % step); } Queue planQueue = getPlanQueue(planQueueName); if (planQueue == null) return; // first we publish to the plan the current availability of resources Resource clusterResources = scheduler.getClusterResource(); Resource planResources = getPlanResources(plan, planQueue, clusterResources); Set<ReservationAllocation> currentReservations = plan.getReservationsAtTime(now); Set<String> curReservationNames = new HashSet<String>(); Resource reservedResources = Resource.newInstance(0, 0); int numRes = getReservedResources(now, currentReservations, curReservationNames, reservedResources); // create the default reservation queue if it doesnt exist String defReservationId = getReservationIdFromQueueName(planQueueName) + ReservationConstants.DEFAULT_QUEUE_SUFFIX; String defReservationQueue = getReservationQueueName(planQueueName, defReservationId); createDefaultReservationQueue(planQueueName, planQueue, defReservationId); curReservationNames.add(defReservationId); // if the resources dedicated to this plan has shrunk invoke replanner if (arePlanResourcesLessThanReservations(clusterResources, planResources, reservedResources)) { try { plan.getReplanner().plan(plan, null); } catch (PlanningException e) { LOG.warn("Exception while trying to replan: {}", planQueueName, e); } } // identify the reservations that have expired and new reservations that // have to be activated List<? extends Queue> resQueues = getChildReservationQueues(planQueue); Set<String> expired = new HashSet<String>(); for (Queue resQueue : resQueues) { String resQueueName = resQueue.getQueueName(); String reservationId = getReservationIdFromQueueName(resQueueName); if (curReservationNames.contains(reservationId)) { // it is already existing reservation, so needed not create new // reservation queue curReservationNames.remove(reservationId); } else { // the reservation has termination, mark for cleanup expired.add(reservationId); } } // garbage collect expired reservations cleanupExpiredQueues(planQueueName, plan.getMoveOnExpiry(), expired, defReservationQueue); // Add new reservations and update existing ones float totalAssignedCapacity = 0f; if (currentReservations != null) { // first release all excess capacity in default queue try { setQueueEntitlement(planQueueName, defReservationQueue, 0f, 1.0f); } catch (YarnException e) { LOG.warn( "Exception while trying to release default queue capacity for plan: {}", planQueueName, e); } // sort allocations from the one giving up the most resources, to the // one asking for the most // avoid order-of-operation errors that temporarily violate 100% // capacity bound List<ReservationAllocation> sortedAllocations = sortByDelta( new ArrayList<ReservationAllocation>(currentReservations), now, plan); for (ReservationAllocation res : sortedAllocations) { String currResId = res.getReservationId().toString(); if (curReservationNames.contains(currResId)) { addReservationQueue(planQueueName, planQueue, currResId); } Resource capToAssign = res.getResourcesAtTime(now); float targetCapacity = 0f; if (planResources.getMemory() > 0 && planResources.getVirtualCores() > 0) { targetCapacity = calculateReservationToPlanRatio(clusterResources, planResources, capToAssign); } if (LOG.isDebugEnabled()) { LOG.debug( "Assigning capacity of {} to queue {} with target capacity {}", capToAssign, currResId, targetCapacity); } // set maxCapacity to 100% unless the job requires gang, in which // case we stick to capacity (as running early/before is likely a // waste of resources) float maxCapacity = 1.0f; if (res.containsGangs()) { maxCapacity = targetCapacity; } try { setQueueEntitlement(planQueueName, currResId, targetCapacity, maxCapacity); } catch (YarnException e) { LOG.warn("Exception while trying to size reservation for plan: {}", currResId, planQueueName, e); } totalAssignedCapacity += targetCapacity; } } // compute the default queue capacity float defQCap = 1.0f - totalAssignedCapacity; if (LOG.isDebugEnabled()) { LOG.debug("PlanFollowerEditPolicyTask: total Plan Capacity: {} " + "currReservation: {} default-queue capacity: {}", planResources, numRes, defQCap); } // set the default queue to eat-up all remaining capacity try { setQueueEntitlement(planQueueName, defReservationQueue, defQCap, 1.0f); } catch (YarnException e) { LOG.warn( "Exception while trying to reclaim default queue capacity for plan: {}", planQueueName, e); } // garbage collect finished reservations from plan try { plan.archiveCompletedReservations(now); } catch (PlanningException e) { LOG.error("Exception in archiving completed reservations: ", e); } LOG.info("Finished iteration of plan follower edit policy for plan: " + planQueueName); // Extension: update plan with app states, // useful to support smart replanning } protected String getReservationIdFromQueueName(String resQueueName) { return resQueueName; } protected void setQueueEntitlement(String planQueueName, String currResId, float targetCapacity, float maxCapacity) throws YarnException { String reservationQueueName = getReservationQueueName(planQueueName, currResId); scheduler.setEntitlement(reservationQueueName, new QueueEntitlement( targetCapacity, maxCapacity)); } // Schedulers have different ways of naming queues. See YARN-2773 protected String getReservationQueueName(String planQueueName, String reservationId) { return reservationId; } /** * First sets entitlement of queues to zero to prevent new app submission. * Then move all apps in the set of queues to the parent plan queue's default * reservation queue if move is enabled. Finally cleanups the queue by killing * any apps (if move is disabled or move failed) and removing the queue */ protected void cleanupExpiredQueues(String planQueueName, boolean shouldMove, Set<String> toRemove, String defReservationQueue) { for (String expiredReservationId : toRemove) { try { // reduce entitlement to 0 String expiredReservation = getReservationQueueName(planQueueName, expiredReservationId); setQueueEntitlement(planQueueName, expiredReservation, 0.0f, 0.0f); if (shouldMove) { moveAppsInQueueSync(expiredReservation, defReservationQueue); } if (scheduler.getAppsInQueue(expiredReservation).size() > 0) { scheduler.killAllAppsInQueue(expiredReservation); LOG.info("Killing applications in queue: {}", expiredReservation); } else { scheduler.removeQueue(expiredReservation); LOG.info("Queue: " + expiredReservation + " removed"); } } catch (YarnException e) { LOG.warn("Exception while trying to expire reservation: {}", expiredReservationId, e); } } } /** * Move all apps in the set of queues to the parent plan queue's default * reservation queue in a synchronous fashion */ private void moveAppsInQueueSync(String expiredReservation, String defReservationQueue) { List<ApplicationAttemptId> activeApps = scheduler.getAppsInQueue(expiredReservation); if (activeApps.isEmpty()) { return; } for (ApplicationAttemptId app : activeApps) { // fallback to parent's default queue try { scheduler.moveApplication(app.getApplicationId(), defReservationQueue); } catch (YarnException e) { LOG.warn( "Encountered unexpected error during migration of application: {}" + " from reservation: {}", app, expiredReservation, e); } } } protected int getReservedResources(long now, Set<ReservationAllocation> currentReservations, Set<String> curReservationNames, Resource reservedResources) { int numRes = 0; if (currentReservations != null) { numRes = currentReservations.size(); for (ReservationAllocation reservation : currentReservations) { curReservationNames.add(reservation.getReservationId().toString()); Resources.addTo(reservedResources, reservation.getResourcesAtTime(now)); } } return numRes; } /** * Sort in the order from the least new amount of resources asked (likely * negative) to the highest. This prevents "order-of-operation" errors related * to exceeding 100% capacity temporarily. */ protected List<ReservationAllocation> sortByDelta( List<ReservationAllocation> currentReservations, long now, Plan plan) { Collections.sort(currentReservations, new ReservationAllocationComparator( now, this, plan)); return currentReservations; } /** * Get queue associated with reservable queue named * @param planQueueName Name of the reservable queue * @return queue associated with the reservable queue */ protected abstract Queue getPlanQueue(String planQueueName); /** * Calculates ratio of reservationResources to planResources */ protected abstract float calculateReservationToPlanRatio( Resource clusterResources, Resource planResources, Resource reservationResources); /** * Check if plan resources are less than expected reservation resources */ protected abstract boolean arePlanResourcesLessThanReservations( Resource clusterResources, Resource planResources, Resource reservedResources); /** * Get a list of reservation queues for this planQueue */ protected abstract List<? extends Queue> getChildReservationQueues( Queue planQueue); /** * Add a new reservation queue for reservation currResId for this planQueue */ protected abstract void addReservationQueue( String planQueueName, Queue queue, String currResId); /** * Creates the default reservation queue for use when no reservation is * used for applications submitted to this planQueue */ protected abstract void createDefaultReservationQueue( String planQueueName, Queue queue, String defReservationQueue); /** * Get plan resources for this planQueue */ protected abstract Resource getPlanResources( Plan plan, Queue queue, Resource clusterResources); /** * Get reservation queue resources if it exists otherwise return null */ protected abstract Resource getReservationQueueResourceIfExists(Plan plan, ReservationId reservationId); private static class ReservationAllocationComparator implements Comparator<ReservationAllocation> { AbstractSchedulerPlanFollower planFollower; long now; Plan plan; ReservationAllocationComparator(long now, AbstractSchedulerPlanFollower planFollower, Plan plan) { this.now = now; this.planFollower = planFollower; this.plan = plan; } private Resource getUnallocatedReservedResources( ReservationAllocation reservation) { Resource resResource; Resource reservationResource = planFollower .getReservationQueueResourceIfExists (plan, reservation.getReservationId()); if (reservationResource != null) { resResource = Resources.subtract( reservation.getResourcesAtTime(now), reservationResource); } else { resResource = reservation.getResourcesAtTime(now); } return resResource; } @Override public int compare(ReservationAllocation lhs, ReservationAllocation rhs) { // compute delta between current and previous reservation, and compare // based on that Resource lhsRes = getUnallocatedReservedResources(lhs); Resource rhsRes = getUnallocatedReservedResources(rhs); return lhsRes.compareTo(rhsRes); } } }
15,591
36.84466
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationInputValidator.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.List; import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateRequest; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter; import org.apache.hadoop.yarn.api.records.ReservationRequests; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger.AuditConstants; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.resource.Resources; public class ReservationInputValidator { private final Clock clock; /** * Utility class to validate reservation requests. */ public ReservationInputValidator(Clock clock) { this.clock = clock; } private Plan validateReservation(ReservationSystem reservationSystem, ReservationId reservationId, String auditConstant) throws YarnException { String message = ""; // check if the reservation id is valid if (reservationId == null) { message = "Missing reservation id." + " Please try again by specifying a reservation id."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } String queueName = reservationSystem.getQueueForReservation(reservationId); if (queueName == null) { message = "The specified reservation with ID: " + reservationId + " is unknown. Please try again with a valid reservation."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // check if the associated plan is valid Plan plan = reservationSystem.getPlan(queueName); if (plan == null) { message = "The specified reservation: " + reservationId + " is not associated with any valid plan." + " Please try again with a valid reservation."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } return plan; } private void validateReservationDefinition(ReservationId reservationId, ReservationDefinition contract, Plan plan, String auditConstant) throws YarnException { String message = ""; // check if deadline is in the past if (contract == null) { message = "Missing reservation definition." + " Please try again by specifying a reservation definition."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } if (contract.getDeadline() <= clock.getTime()) { message = "The specified deadline: " + contract.getDeadline() + " is the past. Please try again with deadline in the future."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // Check if at least one RR has been specified ReservationRequests resReqs = contract.getReservationRequests(); if (resReqs == null) { message = "No resources have been specified to reserve." + "Please try again by specifying the resources to reserve."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } List<ReservationRequest> resReq = resReqs.getReservationResources(); if (resReq == null || resReq.isEmpty()) { message = "No resources have been specified to reserve." + " Please try again by specifying the resources to reserve."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // compute minimum duration and max gang size long minDuration = 0; Resource maxGangSize = Resource.newInstance(0, 0); ReservationRequestInterpreter type = contract.getReservationRequests().getInterpreter(); for (ReservationRequest rr : resReq) { if (type == ReservationRequestInterpreter.R_ALL || type == ReservationRequestInterpreter.R_ANY) { minDuration = Math.max(minDuration, rr.getDuration()); } else { minDuration += rr.getDuration(); } maxGangSize = Resources.max(plan.getResourceCalculator(), plan.getTotalCapacity(), maxGangSize, Resources.multiply(rr.getCapability(), rr.getConcurrency())); } // verify the allocation is possible (skip for ANY) if (contract.getDeadline() - contract.getArrival() < minDuration && type != ReservationRequestInterpreter.R_ANY) { message = "The time difference (" + (contract.getDeadline() - contract.getArrival()) + ") between arrival (" + contract.getArrival() + ") " + "and deadline (" + contract.getDeadline() + ") must " + " be greater or equal to the minimum resource duration (" + minDuration + ")"; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // check that the largest gang does not exceed the inventory available // capacity (skip for ANY) if (Resources.greaterThan(plan.getResourceCalculator(), plan.getTotalCapacity(), maxGangSize, plan.getTotalCapacity()) && type != ReservationRequestInterpreter.R_ANY) { message = "The size of the largest gang in the reservation refinition (" + maxGangSize + ") exceed the capacity available (" + plan.getTotalCapacity() + " )"; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } } /** * Quick validation on the input to check some obvious fail conditions (fail * fast) the input and returns the appropriate {@link Plan} associated with * the specified {@link Queue} or throws an exception message illustrating the * details of any validation check failures * * @param reservationSystem the {@link ReservationSystem} to validate against * @param request the {@link ReservationSubmissionRequest} defining the * resources required over time for the request * @param reservationId the {@link ReservationId} associated with the current * request * @return the {@link Plan} to submit the request to * @throws YarnException */ public Plan validateReservationSubmissionRequest( ReservationSystem reservationSystem, ReservationSubmissionRequest request, ReservationId reservationId) throws YarnException { // Check if it is a managed queue String queueName = request.getQueue(); if (queueName == null || queueName.isEmpty()) { String errMsg = "The queue to submit is not specified." + " Please try again with a valid reservable queue."; RMAuditLogger.logFailure("UNKNOWN", AuditConstants.SUBMIT_RESERVATION_REQUEST, "validate reservation input", "ClientRMService", errMsg); throw RPCUtil.getRemoteException(errMsg); } Plan plan = reservationSystem.getPlan(queueName); if (plan == null) { String errMsg = "The specified queue: " + queueName + " is not managed by reservation system." + " Please try again with a valid reservable queue."; RMAuditLogger.logFailure("UNKNOWN", AuditConstants.SUBMIT_RESERVATION_REQUEST, "validate reservation input", "ClientRMService", errMsg); throw RPCUtil.getRemoteException(errMsg); } validateReservationDefinition(reservationId, request.getReservationDefinition(), plan, AuditConstants.SUBMIT_RESERVATION_REQUEST); return plan; } /** * Quick validation on the input to check some obvious fail conditions (fail * fast) the input and returns the appropriate {@link Plan} associated with * the specified {@link Queue} or throws an exception message illustrating the * details of any validation check failures * * @param reservationSystem the {@link ReservationSystem} to validate against * @param request the {@link ReservationUpdateRequest} defining the resources * required over time for the request * @return the {@link Plan} to submit the request to * @throws YarnException */ public Plan validateReservationUpdateRequest( ReservationSystem reservationSystem, ReservationUpdateRequest request) throws YarnException { ReservationId reservationId = request.getReservationId(); Plan plan = validateReservation(reservationSystem, reservationId, AuditConstants.UPDATE_RESERVATION_REQUEST); validateReservationDefinition(reservationId, request.getReservationDefinition(), plan, AuditConstants.UPDATE_RESERVATION_REQUEST); return plan; } /** * Quick validation on the input to check some obvious fail conditions (fail * fast) the input and returns the appropriate {@link Plan} associated with * the specified {@link Queue} or throws an exception message illustrating the * details of any validation check failures * * @param reservationSystem the {@link ReservationSystem} to validate against * @param request the {@link ReservationDeleteRequest} defining the resources * required over time for the request * @return the {@link Plan} to submit the request to * @throws YarnException */ public Plan validateReservationDeleteRequest( ReservationSystem reservationSystem, ReservationDeleteRequest request) throws YarnException { return validateReservation(reservationSystem, request.getReservationId(), AuditConstants.DELETE_RESERVATION_REQUEST); } }
11,809
43.904943
82
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/InMemoryPlan.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.Planner; import org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.ReservationAgent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.UTCClock; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represents an in memory representation of the state of our * reservation system, and provides accelerated access to both individual * reservations and aggregate utilization of resources over time. */ public class InMemoryPlan implements Plan { private static final Logger LOG = LoggerFactory.getLogger(InMemoryPlan.class); private static final Resource ZERO_RESOURCE = Resource.newInstance(0, 0); private TreeMap<ReservationInterval, Set<InMemoryReservationAllocation>> currentReservations = new TreeMap<ReservationInterval, Set<InMemoryReservationAllocation>>(); private RLESparseResourceAllocation rleSparseVector; private Map<String, RLESparseResourceAllocation> userResourceAlloc = new HashMap<String, RLESparseResourceAllocation>(); private Map<ReservationId, InMemoryReservationAllocation> reservationTable = new HashMap<ReservationId, InMemoryReservationAllocation>(); private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock readLock = readWriteLock.readLock(); private final Lock writeLock = readWriteLock.writeLock(); private final SharingPolicy policy; private final ReservationAgent agent; private final long step; private final ResourceCalculator resCalc; private final Resource minAlloc, maxAlloc; private final String queueName; private final QueueMetrics queueMetrics; private final Planner replanner; private final boolean getMoveOnExpiry; private final Clock clock; private Resource totalCapacity; public InMemoryPlan(QueueMetrics queueMetrics, SharingPolicy policy, ReservationAgent agent, Resource totalCapacity, long step, ResourceCalculator resCalc, Resource minAlloc, Resource maxAlloc, String queueName, Planner replanner, boolean getMoveOnExpiry) { this(queueMetrics, policy, agent, totalCapacity, step, resCalc, minAlloc, maxAlloc, queueName, replanner, getMoveOnExpiry, new UTCClock()); } public InMemoryPlan(QueueMetrics queueMetrics, SharingPolicy policy, ReservationAgent agent, Resource totalCapacity, long step, ResourceCalculator resCalc, Resource minAlloc, Resource maxAlloc, String queueName, Planner replanner, boolean getMoveOnExpiry, Clock clock) { this.queueMetrics = queueMetrics; this.policy = policy; this.agent = agent; this.step = step; this.totalCapacity = totalCapacity; this.resCalc = resCalc; this.minAlloc = minAlloc; this.maxAlloc = maxAlloc; this.rleSparseVector = new RLESparseResourceAllocation(resCalc, minAlloc); this.queueName = queueName; this.replanner = replanner; this.getMoveOnExpiry = getMoveOnExpiry; this.clock = clock; } @Override public QueueMetrics getQueueMetrics() { return queueMetrics; } private void incrementAllocation(ReservationAllocation reservation) { assert (readWriteLock.isWriteLockedByCurrentThread()); Map<ReservationInterval, Resource> allocationRequests = reservation.getAllocationRequests(); // check if we have encountered the user earlier and if not add an entry String user = reservation.getUser(); RLESparseResourceAllocation resAlloc = userResourceAlloc.get(user); if (resAlloc == null) { resAlloc = new RLESparseResourceAllocation(resCalc, minAlloc); userResourceAlloc.put(user, resAlloc); } for (Map.Entry<ReservationInterval, Resource> r : allocationRequests .entrySet()) { resAlloc.addInterval(r.getKey(), r.getValue()); rleSparseVector.addInterval(r.getKey(), r.getValue()); } } private void decrementAllocation(ReservationAllocation reservation) { assert (readWriteLock.isWriteLockedByCurrentThread()); Map<ReservationInterval, Resource> allocationRequests = reservation.getAllocationRequests(); String user = reservation.getUser(); RLESparseResourceAllocation resAlloc = userResourceAlloc.get(user); for (Map.Entry<ReservationInterval, Resource> r : allocationRequests .entrySet()) { resAlloc.removeInterval(r.getKey(), r.getValue()); rleSparseVector.removeInterval(r.getKey(), r.getValue()); } if (resAlloc.isEmpty()) { userResourceAlloc.remove(user); } } public Set<ReservationAllocation> getAllReservations() { readLock.lock(); try { if (currentReservations != null) { Set<ReservationAllocation> flattenedReservations = new HashSet<ReservationAllocation>(); for (Set<InMemoryReservationAllocation> reservationEntries : currentReservations .values()) { flattenedReservations.addAll(reservationEntries); } return flattenedReservations; } else { return null; } } finally { readLock.unlock(); } } @Override public boolean addReservation(ReservationAllocation reservation) throws PlanningException { // Verify the allocation is memory based otherwise it is not supported InMemoryReservationAllocation inMemReservation = (InMemoryReservationAllocation) reservation; if (inMemReservation.getUser() == null) { String errMsg = "The specified Reservation with ID " + inMemReservation.getReservationId() + " is not mapped to any user"; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } writeLock.lock(); try { if (reservationTable.containsKey(inMemReservation.getReservationId())) { String errMsg = "The specified Reservation with ID " + inMemReservation.getReservationId() + " already exists"; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } // Validate if we can accept this reservation, throws exception if // validation fails policy.validate(this, inMemReservation); // we record here the time in which the allocation has been accepted reservation.setAcceptanceTimestamp(clock.getTime()); ReservationInterval searchInterval = new ReservationInterval(inMemReservation.getStartTime(), inMemReservation.getEndTime()); Set<InMemoryReservationAllocation> reservations = currentReservations.get(searchInterval); if (reservations == null) { reservations = new HashSet<InMemoryReservationAllocation>(); } if (!reservations.add(inMemReservation)) { LOG.error("Unable to add reservation: {} to plan.", inMemReservation.getReservationId()); return false; } currentReservations.put(searchInterval, reservations); reservationTable.put(inMemReservation.getReservationId(), inMemReservation); incrementAllocation(inMemReservation); LOG.info("Sucessfully added reservation: {} to plan.", inMemReservation.getReservationId()); return true; } finally { writeLock.unlock(); } } @Override public boolean updateReservation(ReservationAllocation reservation) throws PlanningException { writeLock.lock(); boolean result = false; try { ReservationId resId = reservation.getReservationId(); ReservationAllocation currReservation = getReservationById(resId); if (currReservation == null) { String errMsg = "The specified Reservation with ID " + resId + " does not exist in the plan"; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } // validate if we can accept this reservation, throws exception if // validation fails policy.validate(this, reservation); if (!removeReservation(currReservation)) { LOG.error("Unable to replace reservation: {} from plan.", reservation.getReservationId()); return result; } try { result = addReservation(reservation); } catch (PlanningException e) { LOG.error("Unable to update reservation: {} from plan due to {}.", reservation.getReservationId(), e.getMessage()); } if (result) { LOG.info("Sucessfully updated reservation: {} in plan.", reservation.getReservationId()); return result; } else { // rollback delete addReservation(currReservation); LOG.info("Rollbacked update reservation: {} from plan.", reservation.getReservationId()); return result; } } finally { writeLock.unlock(); } } private boolean removeReservation(ReservationAllocation reservation) { assert (readWriteLock.isWriteLockedByCurrentThread()); ReservationInterval searchInterval = new ReservationInterval(reservation.getStartTime(), reservation.getEndTime()); Set<InMemoryReservationAllocation> reservations = currentReservations.get(searchInterval); if (reservations != null) { if (!reservations.remove(reservation)) { LOG.error("Unable to remove reservation: {} from plan.", reservation.getReservationId()); return false; } if (reservations.isEmpty()) { currentReservations.remove(searchInterval); } } else { String errMsg = "The specified Reservation with ID " + reservation.getReservationId() + " does not exist in the plan"; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } reservationTable.remove(reservation.getReservationId()); decrementAllocation(reservation); LOG.info("Sucessfully deleted reservation: {} in plan.", reservation.getReservationId()); return true; } @Override public boolean deleteReservation(ReservationId reservationID) { writeLock.lock(); try { ReservationAllocation reservation = getReservationById(reservationID); if (reservation == null) { String errMsg = "The specified Reservation with ID " + reservationID + " does not exist in the plan"; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } return removeReservation(reservation); } finally { writeLock.unlock(); } } @Override public void archiveCompletedReservations(long tick) { // Since we are looking for old reservations, read lock is optimal LOG.debug("Running archival at time: {}", tick); List<InMemoryReservationAllocation> expiredReservations = new ArrayList<InMemoryReservationAllocation>(); readLock.lock(); // archive reservations and delete the ones which are beyond // the reservation policy "window" try { long archivalTime = tick - policy.getValidWindow(); ReservationInterval searchInterval = new ReservationInterval(archivalTime, archivalTime); SortedMap<ReservationInterval, Set<InMemoryReservationAllocation>> reservations = currentReservations.headMap(searchInterval, true); if (!reservations.isEmpty()) { for (Set<InMemoryReservationAllocation> reservationEntries : reservations .values()) { for (InMemoryReservationAllocation reservation : reservationEntries) { if (reservation.getEndTime() <= archivalTime) { expiredReservations.add(reservation); } } } } } finally { readLock.unlock(); } if (expiredReservations.isEmpty()) { return; } // Need write lock only if there are any reservations to be deleted writeLock.lock(); try { for (InMemoryReservationAllocation expiredReservation : expiredReservations) { removeReservation(expiredReservation); } } finally { writeLock.unlock(); } } @Override public Set<ReservationAllocation> getReservationsAtTime(long tick) { ReservationInterval searchInterval = new ReservationInterval(tick, Long.MAX_VALUE); readLock.lock(); try { SortedMap<ReservationInterval, Set<InMemoryReservationAllocation>> reservations = currentReservations.headMap(searchInterval, true); if (!reservations.isEmpty()) { Set<ReservationAllocation> flattenedReservations = new HashSet<ReservationAllocation>(); for (Set<InMemoryReservationAllocation> reservationEntries : reservations .values()) { for (InMemoryReservationAllocation reservation : reservationEntries) { if (reservation.getEndTime() > tick) { flattenedReservations.add(reservation); } } } return Collections.unmodifiableSet(flattenedReservations); } else { return Collections.emptySet(); } } finally { readLock.unlock(); } } @Override public long getStep() { return step; } @Override public SharingPolicy getSharingPolicy() { return policy; } @Override public ReservationAgent getReservationAgent() { return agent; } @Override public Resource getConsumptionForUser(String user, long t) { readLock.lock(); try { RLESparseResourceAllocation userResAlloc = userResourceAlloc.get(user); if (userResAlloc != null) { return userResAlloc.getCapacityAtTime(t); } else { return Resources.clone(ZERO_RESOURCE); } } finally { readLock.unlock(); } } @Override public Resource getTotalCommittedResources(long t) { readLock.lock(); try { return rleSparseVector.getCapacityAtTime(t); } finally { readLock.unlock(); } } @Override public ReservationAllocation getReservationById(ReservationId reservationID) { if (reservationID == null) { return null; } readLock.lock(); try { return reservationTable.get(reservationID); } finally { readLock.unlock(); } } @Override public Resource getTotalCapacity() { readLock.lock(); try { return Resources.clone(totalCapacity); } finally { readLock.unlock(); } } @Override public Resource getMinimumAllocation() { return Resources.clone(minAlloc); } @Override public void setTotalCapacity(Resource cap) { writeLock.lock(); try { totalCapacity = Resources.clone(cap); } finally { writeLock.unlock(); } } public long getEarliestStartTime() { readLock.lock(); try { return rleSparseVector.getEarliestStartTime(); } finally { readLock.unlock(); } } @Override public long getLastEndTime() { readLock.lock(); try { return rleSparseVector.getLatestEndTime(); } finally { readLock.unlock(); } } @Override public ResourceCalculator getResourceCalculator() { return resCalc; } @Override public String getQueueName() { return queueName; } @Override public Resource getMaximumAllocation() { return Resources.clone(maxAlloc); } public String toCumulativeString() { readLock.lock(); try { return rleSparseVector.toString(); } finally { readLock.unlock(); } } @Override public Planner getReplanner() { return replanner; } @Override public boolean getMoveOnExpiry() { return getMoveOnExpiry; } @Override public String toString() { readLock.lock(); try { StringBuffer planStr = new StringBuffer("In-memory Plan: "); planStr.append("Parent Queue: ").append(queueName) .append("Total Capacity: ").append(totalCapacity).append("Step: ") .append(step); for (ReservationAllocation reservation : getAllReservations()) { planStr.append(reservation); } return planStr.toString(); } finally { readLock.unlock(); } } }
17,725
32.13271
96
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationInterval.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; /** * This represents the time duration of the reservation * */ public class ReservationInterval implements Comparable<ReservationInterval> { private final long startTime; private final long endTime; public ReservationInterval(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; } /** * Get the start time of the reservation interval * * @return the startTime */ public long getStartTime() { return startTime; } /** * Get the end time of the reservation interval * * @return the endTime */ public long getEndTime() { return endTime; } /** * Returns whether the interval is active at the specified instant of time * * @param tick the instance of the time to check * @return true if active, false otherwise */ public boolean isOverlap(long tick) { return (startTime <= tick && tick <= endTime); } @Override public int compareTo(ReservationInterval anotherInterval) { long diff = 0; if (startTime == anotherInterval.getStartTime()) { diff = endTime - anotherInterval.getEndTime(); } else { diff = startTime - anotherInterval.getStartTime(); } if (diff < 0) { return -1; } else if (diff > 0) { return 1; } else { return 0; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (endTime ^ (endTime >>> 32)); result = prime * result + (int) (startTime ^ (startTime >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ReservationInterval)) { return false; } ReservationInterval other = (ReservationInterval) obj; if (endTime != other.endTime) { return false; } if (startTime != other.startTime) { return false; } return true; } public String toString() { return "[" + startTime + ", " + endTime + "]"; } }
2,961
24.534483
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/PlanFollower.java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.Collection; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.util.Clock; /** * A PlanFollower is a component that runs on a timer, and synchronizes the * underlying {@link ResourceScheduler} with the {@link Plan}(s) and viceversa. * * While different implementations might operate differently, the key idea is to * map the current allocation of resources for each active reservation in the * plan(s), to a corresponding notion in the underlying scheduler (e.g., tuning * capacity of queues, set pool weights, or tweak application priorities). The * goal is to affect the dynamic allocation of resources done by the scheduler * so that the jobs obtain access to resources in a way that is consistent with * the reservations in the plan. A key conceptual step here is to convert the * absolute-valued promises made in the reservations to appropriate relative * priorities/queue sizes etc. * * Symmetrically the PlanFollower exposes changes in cluster conditions (as * tracked by the scheduler) to the plan, e.g., the overall amount of physical * resources available. The Plan in turn can react by replanning its allocations * if appropriate. * * The implementation can assume that is run frequently enough to be able to * observe and react to normal operational changes in cluster conditions on the * fly (e.g., if cluster resources drop, we can update the relative weights of a * queue so that the absolute promises made to the job at reservation time are * respected). * * However, due to RM restarts and the related downtime, it is advisable for * implementations to operate in a stateless way, and be able to synchronize the * state of plans/scheduler regardless of how big is the time gap between * executions. */ public interface PlanFollower extends Runnable { /** * Init function that configures the PlanFollower, by providing: * * @param clock a reference to the system clock. * @param sched a reference to the underlying scheduler * @param plans references to the plans we should keep synchronized at every * time tick. */ public void init(Clock clock, ResourceScheduler sched, Collection<Plan> plans); /** * The function performing the actual synchronization operation for a given * Plan. This is normally invoked by the run method, but it can be invoked * synchronously to avoid race conditions when a user's reservation request * start time is imminent. * * @param plan the Plan to synchronize */ public void synchronizePlan(Plan plan); /** * Setter for the list of plans. * * @param plans the collection of Plans we operate on at every time tick. */ public void setPlans(Collection<Plan> plans); }
3,863
44.458824
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/FairReservationSystem.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; public class FairReservationSystem extends AbstractReservationSystem { private FairScheduler fairScheduler; public FairReservationSystem() { super(FairReservationSystem.class.getName()); } @Override public void reinitialize(Configuration conf, RMContext rmContext) throws YarnException { // Validate if the scheduler is fair scheduler ResourceScheduler scheduler = rmContext.getScheduler(); if (!(scheduler instanceof FairScheduler)) { throw new YarnRuntimeException("Class " + scheduler.getClass().getCanonicalName() + " not instance of " + FairScheduler.class.getCanonicalName()); } fairScheduler = (FairScheduler) scheduler; this.conf = conf; super.reinitialize(conf, rmContext); } @Override protected ReservationSchedulerConfiguration getReservationSchedulerConfiguration() { return fairScheduler.getAllocationConfiguration(); } @Override protected ResourceCalculator getResourceCalculator() { return fairScheduler.getResourceCalculator(); } @Override protected QueueMetrics getRootQueueMetrics() { return fairScheduler.getRootQueueMetrics(); } @Override protected Resource getMinAllocation() { return fairScheduler.getMinimumResourceCapability(); } @Override protected Resource getMaxAllocation() { return fairScheduler.getMaximumResourceCapability(); } @Override protected String getPlanQueuePath(String planQueueName) { return planQueueName; } @Override protected Resource getPlanQueueCapacity(String planQueueName) { return fairScheduler.getQueueManager().getParentQueue(planQueueName, false) .getSteadyFairShare(); } }
3,162
33.758242
82
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/CapacityReservationSystem.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is the implementation of {@link ReservationSystem} based on the * {@link CapacityScheduler} */ @LimitedPrivate("yarn") @Unstable public class CapacityReservationSystem extends AbstractReservationSystem { private static final Logger LOG = LoggerFactory .getLogger(CapacityReservationSystem.class); private CapacityScheduler capScheduler; public CapacityReservationSystem() { super(CapacityReservationSystem.class.getName()); } @Override public void reinitialize(Configuration conf, RMContext rmContext) throws YarnException { // Validate if the scheduler is capacity based ResourceScheduler scheduler = rmContext.getScheduler(); if (!(scheduler instanceof CapacityScheduler)) { throw new YarnRuntimeException("Class " + scheduler.getClass().getCanonicalName() + " not instance of " + CapacityScheduler.class.getCanonicalName()); } capScheduler = (CapacityScheduler) scheduler; this.conf = conf; super.reinitialize(conf, rmContext); } @Override protected Resource getMinAllocation() { return capScheduler.getMinimumResourceCapability(); } @Override protected Resource getMaxAllocation() { return capScheduler.getMaximumResourceCapability(); } @Override protected ResourceCalculator getResourceCalculator() { return capScheduler.getResourceCalculator(); } @Override protected QueueMetrics getRootQueueMetrics() { return capScheduler.getRootQueueMetrics(); } @Override protected String getPlanQueuePath(String planQueueName) { return capScheduler.getQueue(planQueueName).getQueuePath(); } @Override protected Resource getPlanQueueCapacity(String planQueueName) { Resource minAllocation = getMinAllocation(); ResourceCalculator rescCalc = getResourceCalculator(); CSQueue planQueue = capScheduler.getQueue(planQueueName); return rescCalc.multiplyAndNormalizeDown(capScheduler.getClusterResource(), planQueue.getAbsoluteCapacity(), minAllocation); } @Override protected ReservationSchedulerConfiguration getReservationSchedulerConfiguration() { return capScheduler.getConfiguration(); } }
3,943
34.531532
90
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationSchedulerConfiguration.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ReservationDefinition; public abstract class ReservationSchedulerConfiguration extends Configuration { @InterfaceAudience.Private public static final long DEFAULT_RESERVATION_WINDOW = 24*60*60*1000; // 1 day in msec @InterfaceAudience.Private public static final String DEFAULT_RESERVATION_ADMISSION_POLICY = "org.apache.hadoop.yarn.server.resourcemanager.reservation.CapacityOverTimePolicy"; @InterfaceAudience.Private public static final String DEFAULT_RESERVATION_AGENT_NAME = "org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.AlignedPlannerWithGreedy"; @InterfaceAudience.Private public static final String DEFAULT_RESERVATION_PLANNER_NAME = "org.apache.hadoop.yarn.server.resourcemanager.reservation.planning.SimpleCapacityReplanner"; @InterfaceAudience.Private public static final boolean DEFAULT_RESERVATION_MOVE_ON_EXPIRY = true; // default to 1h lookahead enforcement @InterfaceAudience.Private public static final long DEFAULT_RESERVATION_ENFORCEMENT_WINDOW = 60*60*1000; // 1 hour @InterfaceAudience.Private public static final boolean DEFAULT_SHOW_RESERVATIONS_AS_QUEUES = false; @InterfaceAudience.Private public static final float DEFAULT_CAPACITY_OVER_TIME_MULTIPLIER = 1; public ReservationSchedulerConfiguration() { super(); } public ReservationSchedulerConfiguration( Configuration configuration) { super(configuration); } /** * Checks if the queue participates in reservation based scheduling * @param queue name of the queue * @return true if the queue participates in reservation based scheduling */ public abstract boolean isReservable(String queue); /** * Gets the length of time in milliseconds for which the {@link SharingPolicy} * checks for validity * @param queue name of the queue * @return length in time in milliseconds for which to check the * {@link SharingPolicy} */ public long getReservationWindow(String queue) { return DEFAULT_RESERVATION_WINDOW; } /** * Gets the average allowed capacity which will aggregated over the * {@link ReservationSchedulerConfiguration#getReservationWindow} by the * the {@link SharingPolicy} to check aggregate used capacity * @param queue name of the queue * @return average capacity allowed by the {@link SharingPolicy} */ public float getAverageCapacity(String queue) { return DEFAULT_CAPACITY_OVER_TIME_MULTIPLIER; } /** * Gets the maximum capacity at any time that the {@link SharingPolicy} allows * @param queue name of the queue * @return maximum allowed capacity at any time */ public float getInstantaneousMaxCapacity(String queue) { return DEFAULT_CAPACITY_OVER_TIME_MULTIPLIER; } /** * Gets the name of the {@link SharingPolicy} class associated with the queue * @param queue name of the queue * @return the class name of the {@link SharingPolicy} */ public String getReservationAdmissionPolicy(String queue) { return DEFAULT_RESERVATION_ADMISSION_POLICY; } /** * Gets the name of the {@code ReservationAgent} class associated with the * queue * @param queue name of the queue * @return the class name of the {@code ReservationAgent} */ public String getReservationAgent(String queue) { return DEFAULT_RESERVATION_AGENT_NAME; } /** * Checks whether the reservation queues be hidden or visible * @param queuePath name of the queue * @return true if reservation queues should be visible */ public boolean getShowReservationAsQueues(String queuePath) { return DEFAULT_SHOW_RESERVATIONS_AS_QUEUES; } /** * Gets the name of the {@code Planner} class associated with the * queue * @param queue name of the queue * @return the class name of the {@code Planner} */ public String getReplanner(String queue) { return DEFAULT_RESERVATION_PLANNER_NAME; } /** * Gets whether the applications should be killed or moved to the parent queue * when the {@link ReservationDefinition} expires * @param queue name of the queue * @return true if application should be moved, false if they need to be * killed */ public boolean getMoveOnExpiry(String queue) { return DEFAULT_RESERVATION_MOVE_ON_EXPIRY; } /** * Gets the time in milliseconds for which the {@code Planner} will verify * the {@link Plan}s satisfy the constraints * @param queue name of the queue * @return the time in milliseconds for which to check constraints */ public long getEnforcementWindow(String queue) { return DEFAULT_RESERVATION_ENFORCEMENT_WINDOW; } }
5,656
34.35625
100
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/PlanEdit.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; /** * This interface groups the methods used to modify the state of a Plan. */ public interface PlanEdit extends PlanContext, PlanView { /** * Add a new {@link ReservationAllocation} to the plan * * @param reservation the {@link ReservationAllocation} to be added to the * plan * @return true if addition is successful, false otherwise */ public boolean addReservation(ReservationAllocation reservation) throws PlanningException; /** * Updates an existing {@link ReservationAllocation} in the plan. This is * required for re-negotiation * * @param reservation the {@link ReservationAllocation} to be updated the plan * @return true if update is successful, false otherwise */ public boolean updateReservation(ReservationAllocation reservation) throws PlanningException; /** * Delete an existing {@link ReservationAllocation} from the plan identified * uniquely by its {@link ReservationId}. This will generally be used for * garbage collection * * @param reservationID the {@link ReservationAllocation} to be deleted from * the plan identified uniquely by its {@link ReservationId} * @return true if delete is successful, false otherwise */ public boolean deleteReservation(ReservationId reservationID) throws PlanningException; /** * Method invoked to garbage collect old reservations. It cleans up expired * reservations that have fallen out of the sliding archival window * * @param tick the current time from which the archival window is computed */ public void archiveCompletedReservations(long tick) throws PlanningException; /** * Sets the overall capacity in terms of {@link Resource} assigned to this * plan * * @param capacity the overall capacity in terms of {@link Resource} assigned * to this plan */ public void setTotalCapacity(Resource capacity); }
3,017
36.725
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/SharingPolicy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; /** * This is the interface for policy that validate new * {@link ReservationAllocation}s for allocations being added to a {@link Plan}. * Individual policies will be enforcing different invariants. */ @LimitedPrivate("yarn") @Unstable public interface SharingPolicy { /** * Initialize this policy * * @param planQueuePath the name of the queue for this plan * @param conf the system configuration */ public void init(String planQueuePath, ReservationSchedulerConfiguration conf); /** * This method runs the policy validation logic, and return true/false on * whether the {@link ReservationAllocation} is acceptable according to this * sharing policy. * * @param plan the {@link Plan} we validate against * @param newAllocation the allocation proposed to be added to the * {@link Plan} * @throws PlanningException if the policy is respected if we add this * {@link ReservationAllocation} to the {@link Plan} */ public void validate(Plan plan, ReservationAllocation newAllocation) throws PlanningException; /** * Returns the time range before and after the current reservation considered * by this policy. In particular, this informs the archival process for the * {@link Plan}, i.e., reservations regarding times before (now - validWindow) * can be deleted. * * @return validWindow the window of validity considered by the policy. */ public long getValidWindow(); }
2,595
37.746269
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationAllocation.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import java.util.Map; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; /** * A ReservationAllocation represents a concrete allocation of resources over * time that satisfy a certain {@link ReservationDefinition}. This is used * internally by a {@link Plan} to store information about how each of the * accepted {@link ReservationDefinition} have been allocated. */ public interface ReservationAllocation extends Comparable<ReservationAllocation> { /** * Returns the unique identifier {@link ReservationId} that represents the * reservation * * @return reservationId the unique identifier {@link ReservationId} that * represents the reservation */ public ReservationId getReservationId(); /** * Returns the original {@link ReservationDefinition} submitted by the client * * @return the {@link ReservationDefinition} submitted by the client */ public ReservationDefinition getReservationDefinition(); /** * Returns the time at which the reservation is activated * * @return the time at which the reservation is activated */ public long getStartTime(); /** * Returns the time at which the reservation terminates * * @return the time at which the reservation terminates */ public long getEndTime(); /** * Returns the map of resources requested against the time interval for which * they were * * @return the allocationRequests the map of resources requested against the * time interval for which they were */ public Map<ReservationInterval, Resource> getAllocationRequests(); /** * Return a string identifying the plan to which the reservation belongs * * @return the plan to which the reservation belongs */ public String getPlanName(); /** * Returns the user who requested the reservation * * @return the user who requested the reservation */ public String getUser(); /** * Returns whether the reservation has gang semantics or not * * @return true if there is a gang request, false otherwise */ public boolean containsGangs(); /** * Sets the time at which the reservation was accepted by the system * * @param acceptedAt the time at which the reservation was accepted by the * system */ public void setAcceptanceTimestamp(long acceptedAt); /** * Returns the time at which the reservation was accepted by the system * * @return the time at which the reservation was accepted by the system */ public long getAcceptanceTime(); /** * Returns the capacity represented by cumulative resources reserved by the * reservation at the specified point of time * * @param tick the time (UTC in ms) for which the reserved resources are * requested * @return the resources reserved at the specified time */ public Resource getResourcesAtTime(long tick); }
3,909
31.04918
79
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/Plan.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.yarn.api.records.ReservationDefinition; /** * A Plan represents the central data structure of a reservation system that * maintains the "agenda" for the cluster. In particular, it maintains * information on how a set of {@link ReservationDefinition} that have been * previously accepted will be honored. * * {@link ReservationDefinition} submitted by the users through the RM public * APIs are passed to appropriate {@code ReservationAgent}s, which in turn will * consult the Plan (via the {@link PlanView} interface) and try to determine * whether there are sufficient resources available in this Plan to satisfy the * temporal and resource constraints of a {@link ReservationDefinition}. If a * valid allocation is found the agent will try to store it in the plan (via the * {@link PlanEdit} interface). Upon success the system return to the user a * positive acknowledgment, and a reservation identifier to be later used to * access the reserved resources. * * A {@link PlanFollower} will continuously read from the Plan and will * affect the instantaneous allocation of resources among jobs running by * publishing the "current" slice of the Plan to the underlying scheduler. I.e., * the configuration of queues/weights of the scheduler are modified to reflect * the allocations in the Plan. * * As this interface have several methods we decompose them into three groups: * {@link PlanContext}: containing configuration type information, * {@link PlanView} read-only access to the plan state, and {@link PlanEdit} * write access to the plan state. */ public interface Plan extends PlanContext, PlanView, PlanEdit { }
2,553
47.188679
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/PlanView.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import java.util.Set; /** * This interface provides a read-only view on the allocations made in this * plan. This methods are used for example by {@code ReservationAgent}s to * determine the free resources in a certain point in time, and by * PlanFollowerPolicy to publish this plan to the scheduler. */ public interface PlanView extends PlanContext { /** * Return a {@link ReservationAllocation} identified by its * {@link ReservationId} * * @param reservationID the unique id to identify the * {@link ReservationAllocation} * @return {@link ReservationAllocation} identified by the specified id */ public ReservationAllocation getReservationById(ReservationId reservationID); /** * Gets all the active reservations at the specified point of time * * @param tick the time (UTC in ms) for which the active reservations are * requested * @return set of active reservations at the specified time */ public Set<ReservationAllocation> getReservationsAtTime(long tick); /** * Gets all the reservations in the plan * * @return set of all reservations handled by this Plan */ public Set<ReservationAllocation> getAllReservations(); /** * Returns the total {@link Resource} reserved for all users at the specified * time * * @param tick the time (UTC in ms) for which the reserved resources are * requested * @return the total {@link Resource} reserved for all users at the specified * time */ Resource getTotalCommittedResources(long tick); /** * Returns the total {@link Resource} reserved for a given user at the * specified time * * @param user the user who made the reservation(s) * @param tick the time (UTC in ms) for which the reserved resources are * requested * @return the total {@link Resource} reserved for a given user at the * specified time */ public Resource getConsumptionForUser(String user, long tick); /** * Returns the overall capacity in terms of {@link Resource} assigned to this * plan (typically will correspond to the absolute capacity of the * corresponding queue). * * @return the overall capacity in terms of {@link Resource} assigned to this * plan */ Resource getTotalCapacity(); /** * Gets the time (UTC in ms) at which the first reservation starts * * @return the time (UTC in ms) at which the first reservation starts */ public long getEarliestStartTime(); /** * Returns the time (UTC in ms) at which the last reservation terminates * * @return the time (UTC in ms) at which the last reservation terminates */ public long getLastEndTime(); }
3,716
33.738318
79
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/exceptions/MismatchedUserException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; /** * Exception thrown when an update to an existing reservation is performed * by a user that is not the reservation owner. */ @Public @Unstable public class MismatchedUserException extends PlanningException { private static final long serialVersionUID = 8313222590561668413L; public MismatchedUserException(String message) { super(message); } public MismatchedUserException(Throwable cause) { super(cause); } public MismatchedUserException(String message, Throwable cause) { super(message, cause); } }
1,561
32.956522
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/exceptions/PlanningException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionRequest; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; /** * Exception thrown by the admission control subsystem when there is a problem * in trying to find an allocation for a user * {@link ReservationSubmissionRequest}. */ @Public @Unstable public class PlanningException extends Exception { private static final long serialVersionUID = -684069387367879218L; public PlanningException(String message) { super(message); } public PlanningException(Throwable cause) { super(cause); } public PlanningException(String message, Throwable cause) { super(message, cause); } }
1,654
31.45098
79
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/exceptions/PlanningQuotaException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; /** * This exception is thrown if the user quota is exceed while accepting or * updating a reservation. */ @Public @Unstable public class PlanningQuotaException extends PlanningException { private static final long serialVersionUID = 8206629288380246166L; public PlanningQuotaException(String message) { super(message); } public PlanningQuotaException(Throwable cause) { super(cause); } public PlanningQuotaException(String message, Throwable cause) { super(message, cause); } }
1,536
31.702128
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/exceptions/ContractValidationException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; /** * This exception is thrown if the request made is not syntactically valid. */ @Public @Unstable public class ContractValidationException extends PlanningException { private static final long serialVersionUID = 1L; public ContractValidationException(String message) { super(message); } }
1,329
34
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/exceptions/ResourceOverCommitException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; /** * This exception indicate that the reservation that has been attempted, would * exceed the physical resources available in the {@link Plan} at the moment. */ @Public @Unstable public class ResourceOverCommitException extends PlanningException { private static final long serialVersionUID = 7070699407526521032L; public ResourceOverCommitException(String message) { super(message); } public ResourceOverCommitException(Throwable cause) { super(cause); } public ResourceOverCommitException(String message, Throwable cause) { super(message, cause); } }
1,682
34.0625
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageEarliestStart.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; /** * Interface for setting the earliest start time of a stage in IterativePlanner. */ public interface StageEarliestStart { /** * Computes the earliest allowed starting time for a given stage. * * @param plan the Plan to which the reservation must be fitted * @param reservation the job contract * @param index the index of the stage in the job contract * @param currentReservationStage the stage * @param stageDeadline the deadline of the stage set by the two phase * planning algorithm * * @return the earliest allowed starting time for the stage. */ long setEarliestStartTime(Plan plan, ReservationDefinition reservation, int index, ReservationRequest currentReservationStage, long stageDeadline); }
1,858
38.553191
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/IterativePlanner.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.HashMap; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.RLESparseResourceAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationInterval; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.ContractValidationException; import org.apache.hadoop.yarn.util.resource.Resources; /** * A planning algorithm consisting of two main phases. The algorithm iterates * over the job stages in descending order. For each stage, the algorithm: 1. * Determines an interval [stageArrivalTime, stageDeadline) in which the stage * is allocated. 2. Computes an allocation for the stage inside the interval. * * For ANY and ALL jobs, phase 1 sets the allocation window of each stage to be * [jobArrival, jobDeadline]. For ORDER and ORDER_NO_GAP jobs, the deadline of * each stage is set as succcessorStartTime - the starting time of its * succeeding stage (or jobDeadline if it is the last stage). * * The phases are set using the two functions: 1. setAlgEarliestStartTime 2. * setAlgComputeStageAllocation */ public class IterativePlanner extends PlanningAlgorithm { // Modifications performed by the algorithm that are not been reflected in the // actual plan while a request is still pending. private RLESparseResourceAllocation planModifications; // Data extracted from plan private Map<Long, Resource> planLoads; private Resource capacity; private long step; // Job parameters private ReservationRequestInterpreter jobType; private long jobArrival; private long jobDeadline; // Phase algorithms private StageEarliestStart algStageEarliestStart = null; private StageAllocator algStageAllocator = null; // Constructor public IterativePlanner(StageEarliestStart algEarliestStartTime, StageAllocator algStageAllocator) { setAlgStageEarliestStart(algEarliestStartTime); setAlgStageAllocator(algStageAllocator); } @Override public RLESparseResourceAllocation computeJobAllocation(Plan plan, ReservationId reservationId, ReservationDefinition reservation) throws ContractValidationException { // Initialize initialize(plan, reservation); // If the job has been previously reserved, logically remove its allocation ReservationAllocation oldReservation = plan.getReservationById(reservationId); if (oldReservation != null) { ignoreOldAllocation(oldReservation); } // Create the allocations data structure RLESparseResourceAllocation allocations = new RLESparseResourceAllocation(plan.getResourceCalculator(), plan.getMinimumAllocation()); // Get a reverse iterator for the set of stages ListIterator<ReservationRequest> li = reservation .getReservationRequests() .getReservationResources() .listIterator( reservation.getReservationRequests().getReservationResources() .size()); // Current stage ReservationRequest currentReservationStage; // Index, points on the current node int index = reservation.getReservationRequests().getReservationResources().size(); // Stage deadlines long stageDeadline = stepRoundDown(reservation.getDeadline(), step); long successorStartingTime = -1; // Iterate the stages in reverse order while (li.hasPrevious()) { // Get current stage currentReservationStage = li.previous(); index -= 1; // Validate that the ReservationRequest respects basic constraints validateInputStage(plan, currentReservationStage); // Compute an adjusted earliestStart for this resource // (we need this to provision some space for the ORDER contracts) long stageArrivalTime = reservation.getArrival(); if (jobType == ReservationRequestInterpreter.R_ORDER || jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP) { stageArrivalTime = computeEarliestStartingTime(plan, reservation, index, currentReservationStage, stageDeadline); } stageArrivalTime = stepRoundUp(stageArrivalTime, step); stageArrivalTime = Math.max(stageArrivalTime, reservation.getArrival()); // Compute the allocation of a single stage Map<ReservationInterval, Resource> curAlloc = computeStageAllocation(plan, currentReservationStage, stageArrivalTime, stageDeadline); // If we did not find an allocation, return NULL // (unless it's an ANY job, then we simply continue). if (curAlloc == null) { // If it's an ANY job, we can move to the next possible request if (jobType == ReservationRequestInterpreter.R_ANY) { continue; } // Otherwise, the job cannot be allocated return null; } // Get the start & end time of the current allocation Long stageStartTime = findEarliestTime(curAlloc.keySet()); Long stageEndTime = findLatestTime(curAlloc.keySet()); // If we did find an allocation for the stage, add it for (Entry<ReservationInterval, Resource> entry : curAlloc.entrySet()) { allocations.addInterval(entry.getKey(), entry.getValue()); } // If this is an ANY clause, we have finished if (jobType == ReservationRequestInterpreter.R_ANY) { break; } // If ORDER job, set the stageDeadline of the next stage to be processed if (jobType == ReservationRequestInterpreter.R_ORDER || jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP) { // Verify that there is no gap, in case the job is ORDER_NO_GAP if (jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP && successorStartingTime != -1 && successorStartingTime > stageEndTime) { return null; } // Store the stageStartTime and set the new stageDeadline successorStartingTime = stageStartTime; stageDeadline = stageStartTime; } } // If the allocation is empty, return an error if (allocations.isEmpty()) { return null; } return allocations; } protected void initialize(Plan plan, ReservationDefinition reservation) { // Get plan step & capacity capacity = plan.getTotalCapacity(); step = plan.getStep(); // Get job parameters (type, arrival time & deadline) jobType = reservation.getReservationRequests().getInterpreter(); jobArrival = stepRoundUp(reservation.getArrival(), step); jobDeadline = stepRoundDown(reservation.getDeadline(), step); // Dirty read of plan load planLoads = getAllLoadsInInterval(plan, jobArrival, jobDeadline); // Initialize the plan modifications planModifications = new RLESparseResourceAllocation(plan.getResourceCalculator(), plan.getMinimumAllocation()); } private Map<Long, Resource> getAllLoadsInInterval(Plan plan, long startTime, long endTime) { // Create map Map<Long, Resource> loads = new HashMap<Long, Resource>(); // Calculate the load for every time slot between [start,end) for (long t = startTime; t < endTime; t += step) { Resource load = plan.getTotalCommittedResources(t); loads.put(t, load); } // Return map return loads; } private void ignoreOldAllocation(ReservationAllocation oldReservation) { // If there is no old reservation, return if (oldReservation == null) { return; } // Subtract each allocation interval from the planModifications for (Entry<ReservationInterval, Resource> entry : oldReservation .getAllocationRequests().entrySet()) { // Read the entry ReservationInterval interval = entry.getKey(); Resource resource = entry.getValue(); // Find the actual request Resource negativeResource = Resources.multiply(resource, -1); // Insert it into planModifications as a 'negative' request, to // represent available resources planModifications.addInterval(interval, negativeResource); } } private void validateInputStage(Plan plan, ReservationRequest rr) throws ContractValidationException { // Validate concurrency if (rr.getConcurrency() < 1) { throw new ContractValidationException("Gang Size should be >= 1"); } // Validate number of containers if (rr.getNumContainers() <= 0) { throw new ContractValidationException("Num containers should be > 0"); } // Check that gangSize and numContainers are compatible if (rr.getNumContainers() % rr.getConcurrency() != 0) { throw new ContractValidationException( "Parallelism must be an exact multiple of gang size"); } // Check that the largest container request does not exceed the cluster-wide // limit for container sizes if (Resources.greaterThan(plan.getResourceCalculator(), capacity, rr.getCapability(), plan.getMaximumAllocation())) { throw new ContractValidationException( "Individual capability requests should not exceed cluster's " + "maxAlloc"); } } // Call algEarliestStartTime() protected long computeEarliestStartingTime(Plan plan, ReservationDefinition reservation, int index, ReservationRequest currentReservationStage, long stageDeadline) { return algStageEarliestStart.setEarliestStartTime(plan, reservation, index, currentReservationStage, stageDeadline); } // Call algStageAllocator protected Map<ReservationInterval, Resource> computeStageAllocation( Plan plan, ReservationRequest rr, long stageArrivalTime, long stageDeadline) { return algStageAllocator.computeStageAllocation(plan, planLoads, planModifications, rr, stageArrivalTime, stageDeadline); } // Set the algorithm: algStageEarliestStart public IterativePlanner setAlgStageEarliestStart(StageEarliestStart alg) { this.algStageEarliestStart = alg; return this; // To allow concatenation of setAlg() functions } // Set the algorithm: algStageAllocator public IterativePlanner setAlgStageAllocator(StageAllocator alg) { this.algStageAllocator = alg; return this; // To allow concatenation of setAlg() functions } }
11,738
33.628319
104
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageEarliestStartByDemand.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.ListIterator; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; /** * Sets the earliest start time of a stage proportional to the job weight. The * interval [jobArrival, stageDeadline) is divided as follows. First, each stage * is guaranteed at least its requested duration. Then, the stage receives a * fraction of the remaining time. The fraction is calculated as the ratio * between the weight (total requested resources) of the stage and the total * weight of all proceeding stages. */ public class StageEarliestStartByDemand implements StageEarliestStart { private long step; @Override public long setEarliestStartTime(Plan plan, ReservationDefinition reservation, int index, ReservationRequest current, long stageDeadline) { step = plan.getStep(); // If this is the first stage, don't bother with the computation. if (index < 1) { return reservation.getArrival(); } // Get iterator ListIterator<ReservationRequest> li = reservation.getReservationRequests().getReservationResources() .listIterator(index); ReservationRequest rr; // Calculate the total weight & total duration double totalWeight = calcWeight(current); long totalDuration = getRoundedDuration(current, plan); while (li.hasPrevious()) { rr = li.previous(); totalWeight += calcWeight(rr); totalDuration += getRoundedDuration(rr, plan); } // Compute the weight of the current stage as compared to remaining ones double ratio = calcWeight(current) / totalWeight; // Estimate an early start time, such that: // 1. Every stage is guaranteed to receive at least its duration // 2. The remainder of the window is divided between stages // proportionally to its workload (total memory consumption) long window = stageDeadline - reservation.getArrival(); long windowRemainder = window - totalDuration; long earlyStart = (long) (stageDeadline - getRoundedDuration(current, plan) - (windowRemainder * ratio)); // Realign if necessary (since we did some arithmetic) earlyStart = stepRoundUp(earlyStart, step); // Return return earlyStart; } // Weight = total memory consumption of stage protected double calcWeight(ReservationRequest stage) { return (stage.getDuration() * stage.getCapability().getMemory()) * (stage.getNumContainers()); } protected long getRoundedDuration(ReservationRequest stage, Plan plan) { return stepRoundUp(stage.getDuration(), step); } protected static long stepRoundDown(long t, long step) { return (t / step) * step; } protected static long stepRoundUp(long t, long step) { return ((t + step - 1) / step) * step; } }
3,804
34.560748
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/AlignedPlannerWithGreedy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.LinkedList; import java.util.List; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A planning algorithm that first runs LowCostAligned, and if it fails runs * Greedy. */ public class AlignedPlannerWithGreedy implements ReservationAgent { // Default smoothness factor private static final int DEFAULT_SMOOTHNESS_FACTOR = 10; // Log private static final Logger LOG = LoggerFactory .getLogger(AlignedPlannerWithGreedy.class); // Smoothness factor private final ReservationAgent planner; // Constructor public AlignedPlannerWithGreedy() { this(DEFAULT_SMOOTHNESS_FACTOR); } // Constructor public AlignedPlannerWithGreedy(int smoothnessFactor) { // List of algorithms List<ReservationAgent> listAlg = new LinkedList<ReservationAgent>(); // LowCostAligned planning algorithm ReservationAgent algAligned = new IterativePlanner(new StageEarliestStartByDemand(), new StageAllocatorLowCostAligned(smoothnessFactor)); listAlg.add(algAligned); // Greedy planning algorithm ReservationAgent algGreedy = new IterativePlanner(new StageEarliestStartByJobArrival(), new StageAllocatorGreedy()); listAlg.add(algGreedy); // Set planner: // 1. Attempt to execute algAligned // 2. If failed, fall back to algGreedy planner = new TryManyReservationAgents(listAlg); } @Override public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { LOG.info("placing the following ReservationRequest: " + contract); try { boolean res = planner.createReservation(reservationId, user, plan, contract); if (res) { LOG.info("OUTCOME: SUCCESS, Reservation ID: " + reservationId.toString() + ", Contract: " + contract.toString()); } else { LOG.info("OUTCOME: FAILURE, Reservation ID: " + reservationId.toString() + ", Contract: " + contract.toString()); } return res; } catch (PlanningException e) { LOG.info("OUTCOME: FAILURE, Reservation ID: " + reservationId.toString() + ", Contract: " + contract.toString()); throw e; } } @Override public boolean updateReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { LOG.info("updating the following ReservationRequest: " + contract); return planner.updateReservation(reservationId, user, plan, contract); } @Override public boolean deleteReservation(ReservationId reservationId, String user, Plan plan) throws PlanningException { LOG.info("removing the following ReservationId: " + reservationId); return planner.deleteReservation(reservationId, user, plan); } }
4,050
31.669355
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/SimpleCapacityReplanner.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.UTCClock; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.annotations.VisibleForTesting; /** * This (re)planner scan a period of time from now to a maximum time window (or * the end of the last session, whichever comes first) checking the overall * capacity is not violated. * * It greedily removes sessions in reversed order of acceptance (latest accepted * is the first removed). */ public class SimpleCapacityReplanner implements Planner { private static final Log LOG = LogFactory .getLog(SimpleCapacityReplanner.class); private static final Resource ZERO_RESOURCE = Resource.newInstance(0, 0); private final Clock clock; // this allows to control to time-span of this replanning // far into the future time instants might be worth replanning for // later on private long lengthOfCheckZone; public SimpleCapacityReplanner() { this(new UTCClock()); } @VisibleForTesting SimpleCapacityReplanner(Clock clock) { this.clock = clock; } @Override public void init(String planQueueName, ReservationSchedulerConfiguration conf) { this.lengthOfCheckZone = conf.getEnforcementWindow(planQueueName); } @Override public void plan(Plan plan, List<ReservationDefinition> contracts) throws PlanningException { if (contracts != null) { throw new RuntimeException( "SimpleCapacityReplanner cannot handle new reservation contracts"); } ResourceCalculator resCalc = plan.getResourceCalculator(); Resource totCap = plan.getTotalCapacity(); long now = clock.getTime(); // loop on all moment in time from now to the end of the check Zone // or the end of the planned sessions whichever comes first for (long t = now; (t < plan.getLastEndTime() && t < (now + lengthOfCheckZone)); t += plan.getStep()) { Resource excessCap = Resources.subtract(plan.getTotalCommittedResources(t), totCap); // if we are violating if (Resources.greaterThan(resCalc, totCap, excessCap, ZERO_RESOURCE)) { // sorted on reverse order of acceptance, so newest reservations first Set<ReservationAllocation> curReservations = new TreeSet<ReservationAllocation>(plan.getReservationsAtTime(t)); for (Iterator<ReservationAllocation> resIter = curReservations.iterator(); resIter.hasNext() && Resources.greaterThan(resCalc, totCap, excessCap, ZERO_RESOURCE);) { ReservationAllocation reservation = resIter.next(); plan.deleteReservation(reservation.getReservationId()); excessCap = Resources.subtract(excessCap, reservation.getResourcesAtTime(t)); LOG.info("Removing reservation " + reservation.getReservationId() + " to repair physical-resource constraints in the plan: " + plan.getQueueName()); } } } } }
4,629
37.907563
99
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageEarliestStartByJobArrival.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; /** * Sets the earliest start time of a stage as the job arrival time. */ public class StageEarliestStartByJobArrival implements StageEarliestStart { @Override public long setEarliestStartTime(Plan plan, ReservationDefinition reservation, int index, ReservationRequest current, long stageDeadline) { return reservation.getArrival(); } }
1,449
35.25
79
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/PlanningAlgorithm.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.Map; import java.util.Set; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.InMemoryReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.RLESparseResourceAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationInterval; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.ContractValidationException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; /** * An abstract class that follows the general behavior of planning algorithms. */ public abstract class PlanningAlgorithm implements ReservationAgent { /** * Performs the actual allocation for a ReservationDefinition within a Plan. * * @param reservationId the identifier of the reservation * @param user the user who owns the reservation * @param plan the Plan to which the reservation must be fitted * @param contract encapsulates the resources required by the user for his * session * @param oldReservation the existing reservation (null if none) * @return whether the allocateUser function was successful or not * * @throws PlanningException if the session cannot be fitted into the plan * @throws ContractValidationException */ protected boolean allocateUser(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract, ReservationAllocation oldReservation) throws PlanningException, ContractValidationException { // Adjust the ResourceDefinition to account for system "imperfections" // (e.g., scheduling delays for large containers). ReservationDefinition adjustedContract = adjustContract(plan, contract); // Compute the job allocation RLESparseResourceAllocation allocation = computeJobAllocation(plan, reservationId, adjustedContract); // If no job allocation was found, fail if (allocation == null) { throw new PlanningException( "The planning algorithm could not find a valid allocation" + " for your request"); } // Translate the allocation to a map (with zero paddings) long step = plan.getStep(); long jobArrival = stepRoundUp(adjustedContract.getArrival(), step); long jobDeadline = stepRoundUp(adjustedContract.getDeadline(), step); Map<ReservationInterval, Resource> mapAllocations = allocationsToPaddedMap(allocation, jobArrival, jobDeadline); // Create the reservation ReservationAllocation capReservation = new InMemoryReservationAllocation(reservationId, // ID adjustedContract, // Contract user, // User name plan.getQueueName(), // Queue name findEarliestTime(mapAllocations.keySet()), // Earliest start time findLatestTime(mapAllocations.keySet()), // Latest end time mapAllocations, // Allocations plan.getResourceCalculator(), // Resource calculator plan.getMinimumAllocation()); // Minimum allocation // Add (or update) the reservation allocation if (oldReservation != null) { return plan.updateReservation(capReservation); } else { return plan.addReservation(capReservation); } } private Map<ReservationInterval, Resource> allocationsToPaddedMap(RLESparseResourceAllocation allocation, long jobArrival, long jobDeadline) { // Allocate Map<ReservationInterval, Resource> mapAllocations = allocation.toIntervalMap(); // Zero allocation Resource zeroResource = Resource.newInstance(0, 0); // Pad at the beginning long earliestStart = findEarliestTime(mapAllocations.keySet()); if (jobArrival < earliestStart) { mapAllocations.put(new ReservationInterval(jobArrival, earliestStart), zeroResource); } // Pad at the beginning long latestEnd = findLatestTime(mapAllocations.keySet()); if (latestEnd < jobDeadline) { mapAllocations.put(new ReservationInterval(latestEnd, jobDeadline), zeroResource); } return mapAllocations; } public abstract RLESparseResourceAllocation computeJobAllocation(Plan plan, ReservationId reservationId, ReservationDefinition reservation) throws PlanningException, ContractValidationException; @Override public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { // Allocate return allocateUser(reservationId, user, plan, contract, null); } @Override public boolean updateReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { // Get the old allocation ReservationAllocation oldAlloc = plan.getReservationById(reservationId); // Allocate (ignores the old allocation) return allocateUser(reservationId, user, plan, contract, oldAlloc); } @Override public boolean deleteReservation(ReservationId reservationId, String user, Plan plan) throws PlanningException { // Delete the existing reservation return plan.deleteReservation(reservationId); } protected static long findEarliestTime(Set<ReservationInterval> sesInt) { long ret = Long.MAX_VALUE; for (ReservationInterval s : sesInt) { if (s.getStartTime() < ret) { ret = s.getStartTime(); } } return ret; } protected static long findLatestTime(Set<ReservationInterval> sesInt) { long ret = Long.MIN_VALUE; for (ReservationInterval s : sesInt) { if (s.getEndTime() > ret) { ret = s.getEndTime(); } } return ret; } protected static long stepRoundDown(long t, long step) { return (t / step) * step; } protected static long stepRoundUp(long t, long step) { return ((t + step - 1) / step) * step; } private ReservationDefinition adjustContract(Plan plan, ReservationDefinition originalContract) { // Place here adjustment. For example using QueueMetrics we can track // large container delays per YARN-YARN-1990 return originalContract; } }
7,418
34.668269
104
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/ReservationAgent.java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; /** * An entity that seeks to acquire resources to satisfy an user's contract */ public interface ReservationAgent { /** * Create a reservation for the user that abides by the specified contract * * @param reservationId the identifier of the reservation to be created. * @param user the user who wants to create the reservation * @param plan the Plan to which the reservation must be fitted * @param contract encapsulates the resources the user requires for his * session * * @return whether the create operation was successful or not * @throws PlanningException if the session cannot be fitted into the plan */ public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException; /** * Update a reservation for the user that abides by the specified contract * * @param reservationId the identifier of the reservation to be updated * @param user the user who wants to create the session * @param plan the Plan to which the reservation must be fitted * @param contract encapsulates the resources the user requires for his * reservation * * @return whether the update operation was successful or not * @throws PlanningException if the reservation cannot be fitted into the plan */ public boolean updateReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException; /** * Delete an user reservation * * @param reservationId the identifier of the reservation to be deleted * @param user the user who wants to create the reservation * @param plan the Plan to which the session must be fitted * * @return whether the delete operation was successful or not * @throws PlanningException if the reservation cannot be fitted into the plan */ public boolean deleteReservation(ReservationId reservationId, String user, Plan plan) throws PlanningException; }
3,387
44.783784
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/Planner.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.List; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; public interface Planner { /** * Update the existing {@link Plan}, by adding/removing/updating existing * reservations, and adding a subset of the reservation requests in the * contracts parameter. * * @param plan the {@link Plan} to replan * @param contracts the list of reservation requests * @throws PlanningException */ public void plan(Plan plan, List<ReservationDefinition> contracts) throws PlanningException; /** * Initialize the replanner * * @param planQueueName the name of the queue for this plan * @param conf the scheduler configuration */ void init(String planQueueName, ReservationSchedulerConfiguration conf); }
1,925
37.52
99
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/GreedyReservationAgent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This Agent employs a simple greedy placement strategy, placing the various * stages of a {@link ReservationDefinition} from the deadline moving backward * towards the arrival. This allows jobs with earlier deadline to be scheduled * greedily as well. Combined with an opportunistic anticipation of work if the * cluster is not fully utilized also seems to provide good latency for * best-effort jobs (i.e., jobs running without a reservation). * * This agent does not account for locality and only consider container * granularity for validation purposes (i.e., you can't exceed max-container * size). */ public class GreedyReservationAgent implements ReservationAgent { // Log private static final Logger LOG = LoggerFactory .getLogger(GreedyReservationAgent.class); // Greedy planner private final ReservationAgent planner = new IterativePlanner( new StageEarliestStartByJobArrival(), new StageAllocatorGreedy()); @Override public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { LOG.info("placing the following ReservationRequest: " + contract); try { boolean res = planner.createReservation(reservationId, user, plan, contract); if (res) { LOG.info("OUTCOME: SUCCESS, Reservation ID: " + reservationId.toString() + ", Contract: " + contract.toString()); } else { LOG.info("OUTCOME: FAILURE, Reservation ID: " + reservationId.toString() + ", Contract: " + contract.toString()); } return res; } catch (PlanningException e) { LOG.info("OUTCOME: FAILURE, Reservation ID: " + reservationId.toString() + ", Contract: " + contract.toString()); throw e; } } @Override public boolean updateReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { LOG.info("updating the following ReservationRequest: " + contract); return planner.updateReservation(reservationId, user, plan, contract); } @Override public boolean deleteReservation(ReservationId reservationId, String user, Plan plan) throws PlanningException { LOG.info("removing the following ReservationId: " + reservationId); return planner.deleteReservation(reservationId, user, plan); } }
3,649
36.628866
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageAllocatorGreedy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.RLESparseResourceAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationInterval; import org.apache.hadoop.yarn.util.resource.Resources; /** * Computes the stage allocation according to the greedy allocation rule. The * greedy rule repeatedly allocates requested containers at the rightmost * (latest) free interval. */ public class StageAllocatorGreedy implements StageAllocator { @Override public Map<ReservationInterval, Resource> computeStageAllocation(Plan plan, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications, ReservationRequest rr, long stageEarliestStart, long stageDeadline) { Resource totalCapacity = plan.getTotalCapacity(); Map<ReservationInterval, Resource> allocationRequests = new HashMap<ReservationInterval, Resource>(); // compute the gang as a resource and get the duration Resource gang = Resources.multiply(rr.getCapability(), rr.getConcurrency()); long dur = rr.getDuration(); long step = plan.getStep(); // ceil the duration to the next multiple of the plan step if (dur % step != 0) { dur += (step - (dur % step)); } // we know for sure that this division has no remainder (part of contract // with user, validate before int gangsToPlace = rr.getNumContainers() / rr.getConcurrency(); int maxGang = 0; // loop trying to place until we are done, or we are considering // an invalid range of times while (gangsToPlace > 0 && stageDeadline - dur >= stageEarliestStart) { // as we run along we remember how many gangs we can fit, and what // was the most constraining moment in time (we will restart just // after that to place the next batch) maxGang = gangsToPlace; long minPoint = stageDeadline; int curMaxGang = maxGang; // start placing at deadline (excluded due to [,) interval semantics and // move backward for (long t = stageDeadline - plan.getStep(); t >= stageDeadline - dur && maxGang > 0; t = t - plan.getStep()) { // compute net available resources Resource netAvailableRes = Resources.clone(totalCapacity); // Resources.addTo(netAvailableRes, oldResCap); Resources.subtractFrom(netAvailableRes, plan.getTotalCommittedResources(t)); Resources.subtractFrom(netAvailableRes, planModifications.getCapacityAtTime(t)); // compute maximum number of gangs we could fit curMaxGang = (int) Math.floor(Resources.divide(plan.getResourceCalculator(), totalCapacity, netAvailableRes, gang)); // pick the minimum between available resources in this instant, and how // many gangs we have to place curMaxGang = Math.min(gangsToPlace, curMaxGang); // compare with previous max, and set it. also remember *where* we found // the minimum (useful for next attempts) if (curMaxGang <= maxGang) { maxGang = curMaxGang; minPoint = t; } } // if we were able to place any gang, record this, and decrement // gangsToPlace if (maxGang > 0) { gangsToPlace -= maxGang; ReservationInterval reservationInt = new ReservationInterval(stageDeadline - dur, stageDeadline); Resource reservationRes = Resources.multiply(rr.getCapability(), rr.getConcurrency() * maxGang); // remember occupied space (plan is read-only till we find a plausible // allocation for the entire request). This is needed since we might be // placing other ReservationRequest within the same // ReservationDefinition, // and we must avoid double-counting the available resources planModifications.addInterval(reservationInt, reservationRes); allocationRequests.put(reservationInt, reservationRes); } // reset our new starting point (curDeadline) to the most constraining // point so far, we will look "left" of that to find more places where // to schedule gangs (for sure nothing on the "right" of this point can // fit a full gang. stageDeadline = minPoint; } // if no gangs are left to place we succeed and return the allocation if (gangsToPlace == 0) { return allocationRequests; } else { // If we are here is becasue we did not manage to satisfy this request. // So we need to remove unwanted side-effect from tempAssigned (needed // for ANY). for (Map.Entry<ReservationInterval, Resource> tempAllocation : allocationRequests.entrySet()) { planModifications.removeInterval(tempAllocation.getKey(), tempAllocation.getValue()); } // and return null to signal failure in this allocation return null; } } }
6,083
38.764706
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageAllocator.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.Map; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.RLESparseResourceAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationInterval; /** * Interface for allocating a single stage in IterativePlanner. */ public interface StageAllocator { /** * Computes the allocation of a stage inside a defined time interval. * * @param plan the Plan to which the reservation must be fitted * @param planLoads a 'dirty' read of the plan loads at each time * @param planModifications the allocations performed by the planning * algorithm which are not yet reflected by plan * @param rr the stage * @param stageEarliestStart the arrival time (earliest starting time) set for * the stage by the two phase planning algorithm * @param stageDeadline the deadline of the stage set by the two phase * planning algorithm * * @return The computed allocation (or null if the stage could not be * allocated) */ Map<ReservationInterval, Resource> computeStageAllocation(Plan plan, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications, ReservationRequest rr, long stageEarliestStart, long stageDeadline); }
2,347
41.690909
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageAllocatorLowCostAligned.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.Comparator; import java.util.Map; import java.util.TreeSet; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.RLESparseResourceAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationInterval; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; /** * A stage allocator that iteratively allocates containers in the * {@link DurationInterval} with lowest overall cost. The algorithm only * considers intervals of the form: [stageDeadline - (n+1)*duration, * stageDeadline - n*duration) for an integer n. This guarantees that the * allocations are aligned (as opposed to overlapping duration intervals). * * The smoothnessFactor parameter controls the number of containers that are * simultaneously allocated in each iteration of the algorithm. */ public class StageAllocatorLowCostAligned implements StageAllocator { // Smoothness factor private int smoothnessFactor = 10; // Constructor public StageAllocatorLowCostAligned() { } // Constructor public StageAllocatorLowCostAligned(int smoothnessFactor) { this.smoothnessFactor = smoothnessFactor; } // computeJobAllocation() @Override public Map<ReservationInterval, Resource> computeStageAllocation( Plan plan, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications, ReservationRequest rr, long stageEarliestStart, long stageDeadline) { // Initialize ResourceCalculator resCalc = plan.getResourceCalculator(); Resource capacity = plan.getTotalCapacity(); long step = plan.getStep(); // Create allocationRequestsearlies RLESparseResourceAllocation allocationRequests = new RLESparseResourceAllocation(plan.getResourceCalculator(), plan.getMinimumAllocation()); // Initialize parameters long duration = stepRoundUp(rr.getDuration(), step); int windowSizeInDurations = (int) ((stageDeadline - stageEarliestStart) / duration); int totalGangs = rr.getNumContainers() / rr.getConcurrency(); int numContainersPerGang = rr.getConcurrency(); Resource gang = Resources.multiply(rr.getCapability(), numContainersPerGang); // Set maxGangsPerUnit int maxGangsPerUnit = (int) Math.max( Math.floor(((double) totalGangs) / windowSizeInDurations), 1); maxGangsPerUnit = Math.max(maxGangsPerUnit / smoothnessFactor, 1); // If window size is too small, return null if (windowSizeInDurations <= 0) { return null; } // Initialize tree sorted by costs TreeSet<DurationInterval> durationIntervalsSortedByCost = new TreeSet<DurationInterval>(new Comparator<DurationInterval>() { @Override public int compare(DurationInterval val1, DurationInterval val2) { int cmp = Double.compare(val1.getTotalCost(), val2.getTotalCost()); if (cmp != 0) { return cmp; } return (-1) * Long.compare(val1.getEndTime(), val2.getEndTime()); } }); // Add durationIntervals that end at (endTime - n*duration) for some n. for (long intervalEnd = stageDeadline; intervalEnd >= stageEarliestStart + duration; intervalEnd -= duration) { long intervalStart = intervalEnd - duration; // Get duration interval [intervalStart,intervalEnd) DurationInterval durationInterval = getDurationInterval(intervalStart, intervalEnd, planLoads, planModifications, capacity, resCalc, step); // If the interval can fit a gang, add it to the tree if (durationInterval.canAllocate(gang, capacity, resCalc)) { durationIntervalsSortedByCost.add(durationInterval); } } // Allocate int remainingGangs = totalGangs; while (remainingGangs > 0) { // If no durationInterval can fit a gang, break and return null if (durationIntervalsSortedByCost.isEmpty()) { break; } // Get best duration interval DurationInterval bestDurationInterval = durationIntervalsSortedByCost.first(); int numGangsToAllocate = Math.min(maxGangsPerUnit, remainingGangs); // Add it remainingGangs -= numGangsToAllocate; ReservationInterval reservationInt = new ReservationInterval(bestDurationInterval.getStartTime(), bestDurationInterval.getEndTime()); Resource reservationRes = Resources.multiply(rr.getCapability(), rr.getConcurrency() * numGangsToAllocate); planModifications.addInterval(reservationInt, reservationRes); allocationRequests.addInterval(reservationInt, reservationRes); // Remove from tree durationIntervalsSortedByCost.remove(bestDurationInterval); // Get updated interval DurationInterval updatedDurationInterval = getDurationInterval(bestDurationInterval.getStartTime(), bestDurationInterval.getStartTime() + duration, planLoads, planModifications, capacity, resCalc, step); // Add to tree, if possible if (updatedDurationInterval.canAllocate(gang, capacity, resCalc)) { durationIntervalsSortedByCost.add(updatedDurationInterval); } } // Get the final allocation Map<ReservationInterval, Resource> allocations = allocationRequests.toIntervalMap(); // If no gangs are left to place we succeed and return the allocation if (remainingGangs <= 0) { return allocations; } else { // If we are here is because we did not manage to satisfy this request. // We remove unwanted side-effect from planModifications (needed for ANY). for (Map.Entry<ReservationInterval, Resource> tempAllocation : allocations.entrySet()) { planModifications.removeInterval(tempAllocation.getKey(), tempAllocation.getValue()); } // Return null to signal failure in this allocation return null; } } protected DurationInterval getDurationInterval(long startTime, long endTime, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications, Resource capacity, ResourceCalculator resCalc, long step) { // Initialize the dominant loads structure Resource dominantResources = Resource.newInstance(0, 0); // Calculate totalCost and maxLoad double totalCost = 0.0; for (long t = startTime; t < endTime; t += step) { // Get the load Resource load = getLoadAtTime(t, planLoads, planModifications); // Increase the total cost totalCost += calcCostOfLoad(load, capacity, resCalc); // Update the dominant resources dominantResources = Resources.componentwiseMax(dominantResources, load); } // Return the corresponding durationInterval return new DurationInterval(startTime, endTime, totalCost, dominantResources); } protected double calcCostOfInterval(long startTime, long endTime, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications, Resource capacity, ResourceCalculator resCalc, long step) { // Sum costs in the interval [startTime,endTime) double totalCost = 0.0; for (long t = startTime; t < endTime; t += step) { totalCost += calcCostOfTimeSlot(t, planLoads, planModifications, capacity, resCalc); } // Return sum return totalCost; } protected double calcCostOfTimeSlot(long t, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications, Resource capacity, ResourceCalculator resCalc) { // Get the current load at time t Resource load = getLoadAtTime(t, planLoads, planModifications); // Return cost return calcCostOfLoad(load, capacity, resCalc); } protected Resource getLoadAtTime(long t, Map<Long, Resource> planLoads, RLESparseResourceAllocation planModifications) { Resource planLoad = planLoads.get(t); planLoad = (planLoad == null) ? Resource.newInstance(0, 0) : planLoad; return Resources.add(planLoad, planModifications.getCapacityAtTime(t)); } protected double calcCostOfLoad(Resource load, Resource capacity, ResourceCalculator resCalc) { return resCalc.ratio(load, capacity); } protected static long stepRoundDown(long t, long step) { return (t / step) * step; } protected static long stepRoundUp(long t, long step) { return ((t + step - 1) / step) * step; } /** * An inner class that represents an interval, typically of length duration. * The class holds the total cost of the interval and the maximal load inside * the interval in each dimension (both calculated externally). */ protected static class DurationInterval { private long startTime; private long endTime; private double cost; private Resource maxLoad; // Constructor public DurationInterval(long startTime, long endTime, double cost, Resource maxLoad) { this.startTime = startTime; this.endTime = endTime; this.cost = cost; this.maxLoad = maxLoad; } // canAllocate() - boolean function, returns whether requestedResources // can be allocated during the durationInterval without // violating capacity constraints public boolean canAllocate(Resource requestedResources, Resource capacity, ResourceCalculator resCalc) { Resource updatedMaxLoad = Resources.add(maxLoad, requestedResources); return (resCalc.compare(capacity, updatedMaxLoad, capacity) <= 0); } // numCanFit() - returns the maximal number of requestedResources can be // allocated during the durationInterval without violating // capacity constraints public int numCanFit(Resource requestedResources, Resource capacity, ResourceCalculator resCalc) { // Represents the largest resource demand that can be satisfied throughout // the entire DurationInterval (i.e., during [startTime,endTime)) Resource availableResources = Resources.subtract(capacity, maxLoad); // Maximal number of requestedResources that fit inside the interval return (int) Math.floor(Resources.divide(resCalc, capacity, availableResources, requestedResources)); } public long getStartTime() { return this.startTime; } public void setStartTime(long value) { this.startTime = value; } public long getEndTime() { return this.endTime; } public void setEndTime(long value) { this.endTime = value; } public Resource getMaxLoad() { return this.maxLoad; } public void setMaxLoad(Resource value) { this.maxLoad = value; } public double getTotalCost() { return this.cost; } public void setTotalCost(double value) { this.cost = value; } } }
12,009
32.268698
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/TryManyReservationAgents.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.LinkedList; import java.util.List; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; /** * A planning algorithm that invokes several other planning algorithms according * to a given order. If one of the planners succeeds, the allocation it * generates is returned. */ public class TryManyReservationAgents implements ReservationAgent { // Planning algorithms private final List<ReservationAgent> algs; // Constructor public TryManyReservationAgents(List<ReservationAgent> algs) { this.algs = new LinkedList<ReservationAgent>(algs); } @Override public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { // Save the planning exception PlanningException planningException = null; // Try all of the algorithms, in order for (ReservationAgent alg : algs) { try { if (alg.createReservation(reservationId, user, plan, contract)) { return true; } } catch (PlanningException e) { planningException = e; } } // If all of the algorithms failed and one of the algorithms threw an // exception, throw the last planning exception if (planningException != null) { throw planningException; } // If all of the algorithms failed, return false return false; } @Override public boolean updateReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { // Save the planning exception PlanningException planningException = null; // Try all of the algorithms, in order for (ReservationAgent alg : algs) { try { if (alg.updateReservation(reservationId, user, plan, contract)) { return true; } } catch (PlanningException e) { planningException = e; } } // If all of the algorithms failed and one of the algorithms threw an // exception, throw the last planning exception if (planningException != null) { throw planningException; } // If all of the algorithms failed, return false return false; } @Override public boolean deleteReservation(ReservationId reservationId, String user, Plan plan) throws PlanningException { return plan.deleteReservation(reservationId); } }
3,521
29.626087
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/SchedulingEditPolicy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.monitor; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler; public interface SchedulingEditPolicy { public void init(Configuration config, RMContext context, PreemptableResourceScheduler scheduler); /** * This method is invoked at regular intervals. Internally the policy is * allowed to track containers and affect the scheduler. The "actions" * performed are passed back through an EventHandler. */ public void editSchedule(); public long getMonitoringInterval(); public String getPolicyName(); }
1,546
36.731707
92
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/SchedulingMonitor.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.monitor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler; import com.google.common.annotations.VisibleForTesting; public class SchedulingMonitor extends AbstractService { private final SchedulingEditPolicy scheduleEditPolicy; private static final Log LOG = LogFactory.getLog(SchedulingMonitor.class); //thread which runs periodically to see the last time since a heartbeat is //received. private Thread checkerThread; private volatile boolean stopped; private long monitorInterval; private RMContext rmContext; public SchedulingMonitor(RMContext rmContext, SchedulingEditPolicy scheduleEditPolicy) { super("SchedulingMonitor (" + scheduleEditPolicy.getPolicyName() + ")"); this.scheduleEditPolicy = scheduleEditPolicy; this.rmContext = rmContext; } public long getMonitorInterval() { return monitorInterval; } @VisibleForTesting public synchronized SchedulingEditPolicy getSchedulingEditPolicy() { return scheduleEditPolicy; } public void serviceInit(Configuration conf) throws Exception { scheduleEditPolicy.init(conf, rmContext, (PreemptableResourceScheduler) rmContext.getScheduler()); this.monitorInterval = scheduleEditPolicy.getMonitoringInterval(); super.serviceInit(conf); } @Override public void serviceStart() throws Exception { assert !stopped : "starting when already stopped"; checkerThread = new Thread(new PreemptionChecker()); checkerThread.setName(getName()); checkerThread.start(); super.serviceStart(); } @Override public void serviceStop() throws Exception { stopped = true; if (checkerThread != null) { checkerThread.interrupt(); } super.serviceStop(); } @VisibleForTesting public void invokePolicy(){ scheduleEditPolicy.editSchedule(); } private class PreemptionChecker implements Runnable { @Override public void run() { while (!stopped && !Thread.currentThread().isInterrupted()) { //invoke the preemption policy at a regular pace //the policy will generate preemption or kill events //managed by the dispatcher invokePolicy(); try { Thread.sleep(monitorInterval); } catch (InterruptedException e) { LOG.info(getName() + " thread interrupted"); break; } } } } }
3,508
32.419048
92
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.monitor.SchedulingEditPolicy; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerPreemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.PreemptableResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.QueueCapacities; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; /** * This class implement a {@link SchedulingEditPolicy} that is designed to be * paired with the {@code CapacityScheduler}. At every invocation of {@code * editSchedule()} it computes the ideal amount of resources assigned to each * queue (for each queue in the hierarchy), and determines whether preemption * is needed. Overcapacity is distributed among queues in a weighted fair manner, * where the weight is the amount of guaranteed capacity for the queue. * Based on this ideal assignment it determines whether preemption is required * and select a set of containers from each application that would be killed if * the corresponding amount of resources is not freed up by the application. * * If not in {@code observeOnly} mode, it triggers preemption requests via a * {@link ContainerPreemptEvent} that the {@code ResourceManager} will ensure * to deliver to the application (or to execute). * * If the deficit of resources is persistent over a long enough period of time * this policy will trigger forced termination of containers (again by generating * {@link ContainerPreemptEvent}). */ public class ProportionalCapacityPreemptionPolicy implements SchedulingEditPolicy { private static final Log LOG = LogFactory.getLog(ProportionalCapacityPreemptionPolicy.class); /** If true, run the policy but do not affect the cluster with preemption and * kill events. */ public static final String OBSERVE_ONLY = "yarn.resourcemanager.monitor.capacity.preemption.observe_only"; /** Time in milliseconds between invocations of this policy */ public static final String MONITORING_INTERVAL = "yarn.resourcemanager.monitor.capacity.preemption.monitoring_interval"; /** Time in milliseconds between requesting a preemption from an application * and killing the container. */ public static final String WAIT_TIME_BEFORE_KILL = "yarn.resourcemanager.monitor.capacity.preemption.max_wait_before_kill"; /** Maximum percentage of resources preempted in a single round. By * controlling this value one can throttle the pace at which containers are * reclaimed from the cluster. After computing the total desired preemption, * the policy scales it back within this limit. */ public static final String TOTAL_PREEMPTION_PER_ROUND = "yarn.resourcemanager.monitor.capacity.preemption.total_preemption_per_round"; /** Maximum amount of resources above the target capacity ignored for * preemption. This defines a deadzone around the target capacity that helps * prevent thrashing and oscillations around the computed target balance. * High values would slow the time to capacity and (absent natural * completions) it might prevent convergence to guaranteed capacity. */ public static final String MAX_IGNORED_OVER_CAPACITY = "yarn.resourcemanager.monitor.capacity.preemption.max_ignored_over_capacity"; /** * Given a computed preemption target, account for containers naturally * expiring and preempt only this percentage of the delta. This determines * the rate of geometric convergence into the deadzone ({@link * #MAX_IGNORED_OVER_CAPACITY}). For example, a termination factor of 0.5 * will reclaim almost 95% of resources within 5 * {@link * #WAIT_TIME_BEFORE_KILL}, even absent natural termination. */ public static final String NATURAL_TERMINATION_FACTOR = "yarn.resourcemanager.monitor.capacity.preemption.natural_termination_factor"; private RMContext rmContext; private final Clock clock; private double maxIgnoredOverCapacity; private long maxWaitTime; private CapacityScheduler scheduler; private long monitoringInterval; private final Map<RMContainer,Long> preempted = new HashMap<RMContainer,Long>(); private ResourceCalculator rc; private float percentageClusterPreemptionAllowed; private double naturalTerminationFactor; private boolean observeOnly; private Map<String, Map<String, TempQueuePerPartition>> queueToPartitions = new HashMap<>(); private RMNodeLabelsManager nlm; public ProportionalCapacityPreemptionPolicy() { clock = new SystemClock(); } public ProportionalCapacityPreemptionPolicy(Configuration config, RMContext context, CapacityScheduler scheduler) { this(config, context, scheduler, new SystemClock()); } public ProportionalCapacityPreemptionPolicy(Configuration config, RMContext context, CapacityScheduler scheduler, Clock clock) { init(config, context, scheduler); this.clock = clock; } public void init(Configuration config, RMContext context, PreemptableResourceScheduler sched) { LOG.info("Preemption monitor:" + this.getClass().getCanonicalName()); assert null == scheduler : "Unexpected duplicate call to init"; if (!(sched instanceof CapacityScheduler)) { throw new YarnRuntimeException("Class " + sched.getClass().getCanonicalName() + " not instance of " + CapacityScheduler.class.getCanonicalName()); } rmContext = context; scheduler = (CapacityScheduler) sched; maxIgnoredOverCapacity = config.getDouble(MAX_IGNORED_OVER_CAPACITY, 0.1); naturalTerminationFactor = config.getDouble(NATURAL_TERMINATION_FACTOR, 0.2); maxWaitTime = config.getLong(WAIT_TIME_BEFORE_KILL, 15000); monitoringInterval = config.getLong(MONITORING_INTERVAL, 3000); percentageClusterPreemptionAllowed = config.getFloat(TOTAL_PREEMPTION_PER_ROUND, (float) 0.1); observeOnly = config.getBoolean(OBSERVE_ONLY, false); rc = scheduler.getResourceCalculator(); nlm = scheduler.getRMContext().getNodeLabelManager(); } @VisibleForTesting public ResourceCalculator getResourceCalculator() { return rc; } @Override public void editSchedule() { CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); } /** * This method selects and tracks containers to be preempted. If a container * is in the target list for more than maxWaitTime it is killed. * * @param root the root of the CapacityScheduler queue hierarchy * @param clusterResources the total amount of resources in the cluster */ @SuppressWarnings("unchecked") private void containerBasedPreemptOrKill(CSQueue root, Resource clusterResources) { // All partitions to look at Set<String> allPartitions = new HashSet<>(); allPartitions.addAll(scheduler.getRMContext() .getNodeLabelManager().getClusterNodeLabelNames()); allPartitions.add(RMNodeLabelsManager.NO_LABEL); // extract a summary of the queues from scheduler synchronized (scheduler) { queueToPartitions.clear(); for (String partitionToLookAt : allPartitions) { cloneQueues(root, nlm.getResourceByLabel(partitionToLookAt, clusterResources), partitionToLookAt); } } // compute total preemption allowed Resource totalPreemptionAllowed = Resources.multiply(clusterResources, percentageClusterPreemptionAllowed); Set<String> leafQueueNames = null; for (String partition : allPartitions) { TempQueuePerPartition tRoot = getQueueByPartition(CapacitySchedulerConfiguration.ROOT, partition); // compute the ideal distribution of resources among queues // updates cloned queues state accordingly tRoot.idealAssigned = tRoot.guaranteed; leafQueueNames = recursivelyComputeIdealAssignment(tRoot, totalPreemptionAllowed); } // based on ideal allocation select containers to be preempted from each // queue and each application Map<ApplicationAttemptId,Set<RMContainer>> toPreempt = getContainersToPreempt(leafQueueNames, clusterResources); if (LOG.isDebugEnabled()) { logToCSV(new ArrayList<String>(leafQueueNames)); } // if we are in observeOnly mode return before any action is taken if (observeOnly) { return; } // preempt (or kill) the selected containers for (Map.Entry<ApplicationAttemptId,Set<RMContainer>> e : toPreempt.entrySet()) { ApplicationAttemptId appAttemptId = e.getKey(); if (LOG.isDebugEnabled()) { LOG.debug("Send to scheduler: in app=" + appAttemptId + " #containers-to-be-preempted=" + e.getValue().size()); } for (RMContainer container : e.getValue()) { // if we tried to preempt this for more than maxWaitTime if (preempted.get(container) != null && preempted.get(container) + maxWaitTime < clock.getTime()) { // kill it rmContext.getDispatcher().getEventHandler().handle( new ContainerPreemptEvent(appAttemptId, container, SchedulerEventType.KILL_CONTAINER)); preempted.remove(container); } else { if (preempted.get(container) != null) { // We already updated the information to scheduler earlier, we need // not have to raise another event. continue; } //otherwise just send preemption events rmContext.getDispatcher().getEventHandler().handle( new ContainerPreemptEvent(appAttemptId, container, SchedulerEventType.PREEMPT_CONTAINER)); preempted.put(container, clock.getTime()); } } } // Keep the preempted list clean for (Iterator<RMContainer> i = preempted.keySet().iterator(); i.hasNext();){ RMContainer id = i.next(); // garbage collect containers that are irrelevant for preemption if (preempted.get(id) + 2 * maxWaitTime < clock.getTime()) { i.remove(); } } } /** * This method recursively computes the ideal assignment of resources to each * level of the hierarchy. This ensures that leafs that are over-capacity but * with parents within capacity will not be preempted. Preemptions are allowed * within each subtree according to local over/under capacity. * * @param root the root of the cloned queue hierachy * @param totalPreemptionAllowed maximum amount of preemption allowed * @return a list of leaf queues updated with preemption targets */ private Set<String> recursivelyComputeIdealAssignment( TempQueuePerPartition root, Resource totalPreemptionAllowed) { Set<String> leafQueueNames = new HashSet<>(); if (root.getChildren() != null && root.getChildren().size() > 0) { // compute ideal distribution at this level computeIdealResourceDistribution(rc, root.getChildren(), totalPreemptionAllowed, root.idealAssigned); // compute recursively for lower levels and build list of leafs for(TempQueuePerPartition t : root.getChildren()) { leafQueueNames.addAll(recursivelyComputeIdealAssignment(t, totalPreemptionAllowed)); } } else { // we are in a leaf nothing to do, just return yourself return ImmutableSet.of(root.queueName); } return leafQueueNames; } /** * This method computes (for a single level in the tree, passed as a {@code * List<TempQueue>}) the ideal assignment of resources. This is done * recursively to allocate capacity fairly across all queues with pending * demands. It terminates when no resources are left to assign, or when all * demand is satisfied. * * @param rc resource calculator * @param queues a list of cloned queues to be assigned capacity to (this is * an out param) * @param totalPreemptionAllowed total amount of preemption we allow * @param tot_guarant the amount of capacity assigned to this pool of queues */ private void computeIdealResourceDistribution(ResourceCalculator rc, List<TempQueuePerPartition> queues, Resource totalPreemptionAllowed, Resource tot_guarant) { // qAlloc tracks currently active queues (will decrease progressively as // demand is met) List<TempQueuePerPartition> qAlloc = new ArrayList<TempQueuePerPartition>(queues); // unassigned tracks how much resources are still to assign, initialized // with the total capacity for this set of queues Resource unassigned = Resources.clone(tot_guarant); // group queues based on whether they have non-zero guaranteed capacity Set<TempQueuePerPartition> nonZeroGuarQueues = new HashSet<TempQueuePerPartition>(); Set<TempQueuePerPartition> zeroGuarQueues = new HashSet<TempQueuePerPartition>(); for (TempQueuePerPartition q : qAlloc) { if (Resources .greaterThan(rc, tot_guarant, q.guaranteed, Resources.none())) { nonZeroGuarQueues.add(q); } else { zeroGuarQueues.add(q); } } // first compute the allocation as a fixpoint based on guaranteed capacity computeFixpointAllocation(rc, tot_guarant, nonZeroGuarQueues, unassigned, false); // if any capacity is left unassigned, distributed among zero-guarantee // queues uniformly (i.e., not based on guaranteed capacity, as this is zero) if (!zeroGuarQueues.isEmpty() && Resources.greaterThan(rc, tot_guarant, unassigned, Resources.none())) { computeFixpointAllocation(rc, tot_guarant, zeroGuarQueues, unassigned, true); } // based on ideal assignment computed above and current assignment we derive // how much preemption is required overall Resource totPreemptionNeeded = Resource.newInstance(0, 0); for (TempQueuePerPartition t:queues) { if (Resources.greaterThan(rc, tot_guarant, t.current, t.idealAssigned)) { Resources.addTo(totPreemptionNeeded, Resources.subtract(t.current, t.idealAssigned)); } } // if we need to preempt more than is allowed, compute a factor (0<f<1) // that is used to scale down how much we ask back from each queue float scalingFactor = 1.0F; if (Resources.greaterThan(rc, tot_guarant, totPreemptionNeeded, totalPreemptionAllowed)) { scalingFactor = Resources.divide(rc, tot_guarant, totalPreemptionAllowed, totPreemptionNeeded); } // assign to each queue the amount of actual preemption based on local // information of ideal preemption and scaling factor for (TempQueuePerPartition t : queues) { t.assignPreemption(scalingFactor, rc, tot_guarant); } if (LOG.isDebugEnabled()) { long time = clock.getTime(); for (TempQueuePerPartition t : queues) { LOG.debug(time + ": " + t); } } } /** * Given a set of queues compute the fix-point distribution of unassigned * resources among them. As pending request of a queue are exhausted, the * queue is removed from the set and remaining capacity redistributed among * remaining queues. The distribution is weighted based on guaranteed * capacity, unless asked to ignoreGuarantee, in which case resources are * distributed uniformly. */ private void computeFixpointAllocation(ResourceCalculator rc, Resource tot_guarant, Collection<TempQueuePerPartition> qAlloc, Resource unassigned, boolean ignoreGuarantee) { // Prior to assigning the unused resources, process each queue as follows: // If current > guaranteed, idealAssigned = guaranteed + untouchable extra // Else idealAssigned = current; // Subtract idealAssigned resources from unassigned. // If the queue has all of its needs met (that is, if // idealAssigned >= current + pending), remove it from consideration. // Sort queues from most under-guaranteed to most over-guaranteed. TQComparator tqComparator = new TQComparator(rc, tot_guarant); PriorityQueue<TempQueuePerPartition> orderedByNeed = new PriorityQueue<TempQueuePerPartition>(10, tqComparator); for (Iterator<TempQueuePerPartition> i = qAlloc.iterator(); i.hasNext();) { TempQueuePerPartition q = i.next(); if (Resources.greaterThan(rc, tot_guarant, q.current, q.guaranteed)) { q.idealAssigned = Resources.add(q.guaranteed, q.untouchableExtra); } else { q.idealAssigned = Resources.clone(q.current); } Resources.subtractFrom(unassigned, q.idealAssigned); // If idealAssigned < (current + pending), q needs more resources, so // add it to the list of underserved queues, ordered by need. Resource curPlusPend = Resources.add(q.current, q.pending); if (Resources.lessThan(rc, tot_guarant, q.idealAssigned, curPlusPend)) { orderedByNeed.add(q); } } //assign all cluster resources until no more demand, or no resources are left while (!orderedByNeed.isEmpty() && Resources.greaterThan(rc,tot_guarant, unassigned,Resources.none())) { Resource wQassigned = Resource.newInstance(0, 0); // we compute normalizedGuarantees capacity based on currently active // queues resetCapacity(rc, unassigned, orderedByNeed, ignoreGuarantee); // For each underserved queue (or set of queues if multiple are equally // underserved), offer its share of the unassigned resources based on its // normalized guarantee. After the offer, if the queue is not satisfied, // place it back in the ordered list of queues, recalculating its place // in the order of most under-guaranteed to most over-guaranteed. In this // way, the most underserved queue(s) are always given resources first. Collection<TempQueuePerPartition> underserved = getMostUnderservedQueues(orderedByNeed, tqComparator); for (Iterator<TempQueuePerPartition> i = underserved.iterator(); i .hasNext();) { TempQueuePerPartition sub = i.next(); Resource wQavail = Resources.multiplyAndNormalizeUp(rc, unassigned, sub.normalizedGuarantee, Resource.newInstance(1, 1)); Resource wQidle = sub.offer(wQavail, rc, tot_guarant); Resource wQdone = Resources.subtract(wQavail, wQidle); if (Resources.greaterThan(rc, tot_guarant, wQdone, Resources.none())) { // The queue is still asking for more. Put it back in the priority // queue, recalculating its order based on need. orderedByNeed.add(sub); } Resources.addTo(wQassigned, wQdone); } Resources.subtractFrom(unassigned, wQassigned); } } // Take the most underserved TempQueue (the one on the head). Collect and // return the list of all queues that have the same idealAssigned // percentage of guaranteed. protected Collection<TempQueuePerPartition> getMostUnderservedQueues( PriorityQueue<TempQueuePerPartition> orderedByNeed, TQComparator tqComparator) { ArrayList<TempQueuePerPartition> underserved = new ArrayList<TempQueuePerPartition>(); while (!orderedByNeed.isEmpty()) { TempQueuePerPartition q1 = orderedByNeed.remove(); underserved.add(q1); TempQueuePerPartition q2 = orderedByNeed.peek(); // q1's pct of guaranteed won't be larger than q2's. If it's less, then // return what has already been collected. Otherwise, q1's pct of // guaranteed == that of q2, so add q2 to underserved list during the // next pass. if (q2 == null || tqComparator.compare(q1,q2) < 0) { return underserved; } } return underserved; } /** * Computes a normalizedGuaranteed capacity based on active queues * @param rc resource calculator * @param clusterResource the total amount of resources in the cluster * @param queues the list of queues to consider */ private void resetCapacity(ResourceCalculator rc, Resource clusterResource, Collection<TempQueuePerPartition> queues, boolean ignoreGuar) { Resource activeCap = Resource.newInstance(0, 0); if (ignoreGuar) { for (TempQueuePerPartition q : queues) { q.normalizedGuarantee = (float) 1.0f / ((float) queues.size()); } } else { for (TempQueuePerPartition q : queues) { Resources.addTo(activeCap, q.guaranteed); } for (TempQueuePerPartition q : queues) { q.normalizedGuarantee = Resources.divide(rc, clusterResource, q.guaranteed, activeCap); } } } private String getPartitionByNodeId(NodeId nodeId) { return scheduler.getSchedulerNode(nodeId).getPartition(); } /** * Return should we preempt rmContainer. If we should, deduct from * <code>resourceToObtainByPartition</code> */ private boolean tryPreemptContainerAndDeductResToObtain( Map<String, Resource> resourceToObtainByPartitions, RMContainer rmContainer, Resource clusterResource, Map<ApplicationAttemptId, Set<RMContainer>> preemptMap) { ApplicationAttemptId attemptId = rmContainer.getApplicationAttemptId(); // We will not account resource of a container twice or more if (preemptMapContains(preemptMap, attemptId, rmContainer)) { return false; } String nodePartition = getPartitionByNodeId(rmContainer.getAllocatedNode()); Resource toObtainByPartition = resourceToObtainByPartitions.get(nodePartition); if (null != toObtainByPartition && Resources.greaterThan(rc, clusterResource, toObtainByPartition, Resources.none())) { Resources.subtractFrom(toObtainByPartition, rmContainer.getAllocatedResource()); // When we have no more resource need to obtain, remove from map. if (Resources.lessThanOrEqual(rc, clusterResource, toObtainByPartition, Resources.none())) { resourceToObtainByPartitions.remove(nodePartition); } if (LOG.isDebugEnabled()) { LOG.debug("Marked container=" + rmContainer.getContainerId() + " in partition=" + nodePartition + " will be preempted"); } // Add to preemptMap addToPreemptMap(preemptMap, attemptId, rmContainer); return true; } return false; } private boolean preemptMapContains( Map<ApplicationAttemptId, Set<RMContainer>> preemptMap, ApplicationAttemptId attemptId, RMContainer rmContainer) { Set<RMContainer> rmContainers; if (null == (rmContainers = preemptMap.get(attemptId))) { return false; } return rmContainers.contains(rmContainer); } private void addToPreemptMap( Map<ApplicationAttemptId, Set<RMContainer>> preemptMap, ApplicationAttemptId appAttemptId, RMContainer containerToPreempt) { Set<RMContainer> set; if (null == (set = preemptMap.get(appAttemptId))) { set = new HashSet<RMContainer>(); preemptMap.put(appAttemptId, set); } set.add(containerToPreempt); } /** * Based a resource preemption target drop reservations of containers and * if necessary select containers for preemption from applications in each * over-capacity queue. It uses {@link #NATURAL_TERMINATION_FACTOR} to * account for containers that will naturally complete. * * @param queues set of leaf queues to preempt from * @param clusterResource total amount of cluster resources * @return a map of applciationID to set of containers to preempt */ private Map<ApplicationAttemptId,Set<RMContainer>> getContainersToPreempt( Set<String> leafQueueNames, Resource clusterResource) { Map<ApplicationAttemptId, Set<RMContainer>> preemptMap = new HashMap<ApplicationAttemptId, Set<RMContainer>>(); List<RMContainer> skippedAMContainerlist = new ArrayList<RMContainer>(); // Loop all leaf queues for (String queueName : leafQueueNames) { // check if preemption disabled for the queue if (getQueueByPartition(queueName, RMNodeLabelsManager.NO_LABEL).preemptionDisabled) { if (LOG.isDebugEnabled()) { LOG.debug("skipping from queue=" + queueName + " because it's a non-preemptable queue"); } continue; } // compute resToObtainByPartition considered inter-queue preemption LeafQueue leafQueue = null; Map<String, Resource> resToObtainByPartition = new HashMap<String, Resource>(); for (TempQueuePerPartition qT : getQueuePartitions(queueName)) { leafQueue = qT.leafQueue; // we act only if we are violating balance by more than // maxIgnoredOverCapacity if (Resources.greaterThan(rc, clusterResource, qT.current, Resources.multiply(qT.guaranteed, 1.0 + maxIgnoredOverCapacity))) { // we introduce a dampening factor naturalTerminationFactor that // accounts for natural termination of containers Resource resToObtain = Resources.multiply(qT.toBePreempted, naturalTerminationFactor); // Only add resToObtain when it >= 0 if (Resources.greaterThan(rc, clusterResource, resToObtain, Resources.none())) { resToObtainByPartition.put(qT.partition, resToObtain); if (LOG.isDebugEnabled()) { LOG.debug("Queue=" + queueName + " partition=" + qT.partition + " resource-to-obtain=" + resToObtain); } } qT.actuallyPreempted = Resources.clone(resToObtain); } else { qT.actuallyPreempted = Resources.none(); } } synchronized (leafQueue) { // go through all ignore-partition-exclusivity containers first to make // sure such containers will be preempted first Map<String, TreeSet<RMContainer>> ignorePartitionExclusivityContainers = leafQueue.getIgnoreExclusivityRMContainers(); for (String partition : resToObtainByPartition.keySet()) { if (ignorePartitionExclusivityContainers.containsKey(partition)) { TreeSet<RMContainer> rmContainers = ignorePartitionExclusivityContainers.get(partition); // We will check container from reverse order, so latter submitted // application's containers will be preempted first. for (RMContainer c : rmContainers.descendingSet()) { boolean preempted = tryPreemptContainerAndDeductResToObtain( resToObtainByPartition, c, clusterResource, preemptMap); if (!preempted) { break; } } } } // preempt other containers Resource skippedAMSize = Resource.newInstance(0, 0); Iterator<FiCaSchedulerApp> desc = leafQueue.getOrderingPolicy().getPreemptionIterator(); while (desc.hasNext()) { FiCaSchedulerApp fc = desc.next(); // When we complete preempt from one partition, we will remove from // resToObtainByPartition, so when it becomes empty, we can get no // more preemption is needed if (resToObtainByPartition.isEmpty()) { break; } preemptFrom(fc, clusterResource, resToObtainByPartition, skippedAMContainerlist, skippedAMSize, preemptMap); } // Can try preempting AMContainers (still saving atmost // maxAMCapacityForThisQueue AMResource's) if more resources are // required to be preempted from this Queue. Resource maxAMCapacityForThisQueue = Resources.multiply( Resources.multiply(clusterResource, leafQueue.getAbsoluteCapacity()), leafQueue.getMaxAMResourcePerQueuePercent()); preemptAMContainers(clusterResource, preemptMap, skippedAMContainerlist, resToObtainByPartition, skippedAMSize, maxAMCapacityForThisQueue); } } return preemptMap; } /** * As more resources are needed for preemption, saved AMContainers has to be * rescanned. Such AMContainers can be preempted based on resToObtain, but * maxAMCapacityForThisQueue resources will be still retained. * * @param clusterResource * @param preemptMap * @param skippedAMContainerlist * @param resToObtain * @param skippedAMSize * @param maxAMCapacityForThisQueue */ private void preemptAMContainers(Resource clusterResource, Map<ApplicationAttemptId, Set<RMContainer>> preemptMap, List<RMContainer> skippedAMContainerlist, Map<String, Resource> resToObtainByPartition, Resource skippedAMSize, Resource maxAMCapacityForThisQueue) { for (RMContainer c : skippedAMContainerlist) { // Got required amount of resources for preemption, can stop now if (resToObtainByPartition.isEmpty()) { break; } // Once skippedAMSize reaches down to maxAMCapacityForThisQueue, // container selection iteration for preemption will be stopped. if (Resources.lessThanOrEqual(rc, clusterResource, skippedAMSize, maxAMCapacityForThisQueue)) { break; } boolean preempted = tryPreemptContainerAndDeductResToObtain(resToObtainByPartition, c, clusterResource, preemptMap); if (preempted) { Resources.subtractFrom(skippedAMSize, c.getAllocatedResource()); } } skippedAMContainerlist.clear(); } /** * Given a target preemption for a specific application, select containers * to preempt (after unreserving all reservation for that app). */ @SuppressWarnings("unchecked") private void preemptFrom(FiCaSchedulerApp app, Resource clusterResource, Map<String, Resource> resToObtainByPartition, List<RMContainer> skippedAMContainerlist, Resource skippedAMSize, Map<ApplicationAttemptId, Set<RMContainer>> preemptMap) { ApplicationAttemptId appId = app.getApplicationAttemptId(); if (LOG.isDebugEnabled()) { LOG.debug("Looking at application=" + app.getApplicationAttemptId() + " resourceToObtain=" + resToObtainByPartition); } // first drop reserved containers towards rsrcPreempt List<RMContainer> reservedContainers = new ArrayList<RMContainer>(app.getReservedContainers()); for (RMContainer c : reservedContainers) { if (resToObtainByPartition.isEmpty()) { return; } // Try to preempt this container tryPreemptContainerAndDeductResToObtain(resToObtainByPartition, c, clusterResource, preemptMap); if (!observeOnly) { rmContext.getDispatcher().getEventHandler().handle( new ContainerPreemptEvent( appId, c, SchedulerEventType.DROP_RESERVATION)); } } // if more resources are to be freed go through all live containers in // reverse priority and reverse allocation order and mark them for // preemption List<RMContainer> liveContainers = new ArrayList<RMContainer>(app.getLiveContainers()); sortContainers(liveContainers); for (RMContainer c : liveContainers) { if (resToObtainByPartition.isEmpty()) { return; } // Skip AM Container from preemption for now. if (c.isAMContainer()) { skippedAMContainerlist.add(c); Resources.addTo(skippedAMSize, c.getAllocatedResource()); continue; } // Try to preempt this container tryPreemptContainerAndDeductResToObtain(resToObtainByPartition, c, clusterResource, preemptMap); } } /** * Compare by reversed priority order first, and then reversed containerId * order * @param containers */ @VisibleForTesting static void sortContainers(List<RMContainer> containers){ Collections.sort(containers, new Comparator<RMContainer>() { @Override public int compare(RMContainer a, RMContainer b) { Comparator<Priority> c = new org.apache.hadoop.yarn.server .resourcemanager.resource.Priority.Comparator(); int priorityComp = c.compare(b.getContainer().getPriority(), a.getContainer().getPriority()); if (priorityComp != 0) { return priorityComp; } return b.getContainerId().compareTo(a.getContainerId()); } }); } @Override public long getMonitoringInterval() { return monitoringInterval; } @Override public String getPolicyName() { return "ProportionalCapacityPreemptionPolicy"; } /** * This method walks a tree of CSQueue and clones the portion of the state * relevant for preemption in TempQueue(s). It also maintains a pointer to * the leaves. Finally it aggregates pending resources in each queue and rolls * it up to higher levels. * * @param curQueue current queue which I'm looking at now * @param partitionResource the total amount of resources in the cluster * @return the root of the cloned queue hierarchy */ private TempQueuePerPartition cloneQueues(CSQueue curQueue, Resource partitionResource, String partitionToLookAt) { TempQueuePerPartition ret; synchronized (curQueue) { String queueName = curQueue.getQueueName(); QueueCapacities qc = curQueue.getQueueCapacities(); float absCap = qc.getAbsoluteCapacity(partitionToLookAt); float absMaxCap = qc.getAbsoluteMaximumCapacity(partitionToLookAt); boolean preemptionDisabled = curQueue.getPreemptionDisabled(); Resource current = curQueue.getQueueResourceUsage().getUsed( partitionToLookAt); Resource guaranteed = Resources.multiply(partitionResource, absCap); Resource maxCapacity = Resources.multiply(partitionResource, absMaxCap); // when partition is a non-exclusive partition, the actual maxCapacity // could more than specified maxCapacity try { if (!scheduler.getRMContext().getNodeLabelManager() .isExclusiveNodeLabel(partitionToLookAt)) { maxCapacity = Resources.max(rc, partitionResource, maxCapacity, current); } } catch (IOException e) { // This may cause by partition removed when running capacity monitor, // just ignore the error, this will be corrected when doing next check. } Resource extra = Resource.newInstance(0, 0); if (Resources.greaterThan(rc, partitionResource, current, guaranteed)) { extra = Resources.subtract(current, guaranteed); } if (curQueue instanceof LeafQueue) { LeafQueue l = (LeafQueue) curQueue; Resource pending = l.getQueueResourceUsage().getPending(partitionToLookAt); ret = new TempQueuePerPartition(queueName, current, pending, guaranteed, maxCapacity, preemptionDisabled, partitionToLookAt); if (preemptionDisabled) { ret.untouchableExtra = extra; } else { ret.preemptableExtra = extra; } ret.setLeafQueue(l); } else { Resource pending = Resource.newInstance(0, 0); ret = new TempQueuePerPartition(curQueue.getQueueName(), current, pending, guaranteed, maxCapacity, false, partitionToLookAt); Resource childrensPreemptable = Resource.newInstance(0, 0); for (CSQueue c : curQueue.getChildQueues()) { TempQueuePerPartition subq = cloneQueues(c, partitionResource, partitionToLookAt); Resources.addTo(childrensPreemptable, subq.preemptableExtra); ret.addChild(subq); } // untouchableExtra = max(extra - childrenPreemptable, 0) if (Resources.greaterThanOrEqual( rc, partitionResource, childrensPreemptable, extra)) { ret.untouchableExtra = Resource.newInstance(0, 0); } else { ret.untouchableExtra = Resources.subtract(extra, childrensPreemptable); } ret.preemptableExtra = Resources.min( rc, partitionResource, childrensPreemptable, extra); } } addTempQueuePartition(ret); return ret; } // simple printout function that reports internal queue state (useful for // plotting) private void logToCSV(List<String> leafQueueNames){ Collections.sort(leafQueueNames); String queueState = " QUEUESTATE: " + clock.getTime(); StringBuilder sb = new StringBuilder(); sb.append(queueState); for (String queueName : leafQueueNames) { TempQueuePerPartition tq = getQueueByPartition(queueName, RMNodeLabelsManager.NO_LABEL); sb.append(", "); tq.appendLogString(sb); } LOG.debug(sb.toString()); } private void addTempQueuePartition(TempQueuePerPartition queuePartition) { String queueName = queuePartition.queueName; Map<String, TempQueuePerPartition> queuePartitions; if (null == (queuePartitions = queueToPartitions.get(queueName))) { queuePartitions = new HashMap<String, TempQueuePerPartition>(); queueToPartitions.put(queueName, queuePartitions); } queuePartitions.put(queuePartition.partition, queuePartition); } /** * Get queue partition by given queueName and partitionName */ private TempQueuePerPartition getQueueByPartition(String queueName, String partition) { Map<String, TempQueuePerPartition> partitionToQueues = null; if (null == (partitionToQueues = queueToPartitions.get(queueName))) { return null; } return partitionToQueues.get(partition); } /** * Get all queue partitions by given queueName */ private Collection<TempQueuePerPartition> getQueuePartitions(String queueName) { if (!queueToPartitions.containsKey(queueName)) { return null; } return queueToPartitions.get(queueName).values(); } /** * Temporary data-structure tracking resource availability, pending resource * need, current utilization. This is per-queue-per-partition data structure */ static class TempQueuePerPartition { final String queueName; final Resource current; final Resource pending; final Resource guaranteed; final Resource maxCapacity; final String partition; Resource idealAssigned; Resource toBePreempted; // For logging purpose Resource actuallyPreempted; Resource untouchableExtra; Resource preemptableExtra; double normalizedGuarantee; final ArrayList<TempQueuePerPartition> children; LeafQueue leafQueue; boolean preemptionDisabled; TempQueuePerPartition(String queueName, Resource current, Resource pending, Resource guaranteed, Resource maxCapacity, boolean preemptionDisabled, String partition) { this.queueName = queueName; this.current = current; this.pending = pending; this.guaranteed = guaranteed; this.maxCapacity = maxCapacity; this.idealAssigned = Resource.newInstance(0, 0); this.actuallyPreempted = Resource.newInstance(0, 0); this.toBePreempted = Resource.newInstance(0, 0); this.normalizedGuarantee = Float.NaN; this.children = new ArrayList<TempQueuePerPartition>(); this.untouchableExtra = Resource.newInstance(0, 0); this.preemptableExtra = Resource.newInstance(0, 0); this.preemptionDisabled = preemptionDisabled; this.partition = partition; } public void setLeafQueue(LeafQueue l){ assert children.size() == 0; this.leafQueue = l; } /** * When adding a child we also aggregate its pending resource needs. * @param q the child queue to add to this queue */ public void addChild(TempQueuePerPartition q) { assert leafQueue == null; children.add(q); Resources.addTo(pending, q.pending); } public void addChildren(ArrayList<TempQueuePerPartition> queues) { assert leafQueue == null; children.addAll(queues); } public ArrayList<TempQueuePerPartition> getChildren(){ return children; } // This function "accepts" all the resources it can (pending) and return // the unused ones Resource offer(Resource avail, ResourceCalculator rc, Resource clusterResource) { Resource absMaxCapIdealAssignedDelta = Resources.componentwiseMax( Resources.subtract(maxCapacity, idealAssigned), Resource.newInstance(0, 0)); // remain = avail - min(avail, (max - assigned), (current + pending - assigned)) Resource accepted = Resources.min(rc, clusterResource, absMaxCapIdealAssignedDelta, Resources.min(rc, clusterResource, avail, Resources.subtract( Resources.add(current, pending), idealAssigned))); Resource remain = Resources.subtract(avail, accepted); Resources.addTo(idealAssigned, accepted); return remain; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" NAME: " + queueName) .append(" CUR: ").append(current) .append(" PEN: ").append(pending) .append(" GAR: ").append(guaranteed) .append(" NORM: ").append(normalizedGuarantee) .append(" IDEAL_ASSIGNED: ").append(idealAssigned) .append(" IDEAL_PREEMPT: ").append(toBePreempted) .append(" ACTUAL_PREEMPT: ").append(actuallyPreempted) .append(" UNTOUCHABLE: ").append(untouchableExtra) .append(" PREEMPTABLE: ").append(preemptableExtra) .append("\n"); return sb.toString(); } public void printAll() { LOG.info(this.toString()); for (TempQueuePerPartition sub : this.getChildren()) { sub.printAll(); } } public void assignPreemption(float scalingFactor, ResourceCalculator rc, Resource clusterResource) { if (Resources.greaterThan(rc, clusterResource, current, idealAssigned)) { toBePreempted = Resources.multiply( Resources.subtract(current, idealAssigned), scalingFactor); } else { toBePreempted = Resource.newInstance(0, 0); } } void appendLogString(StringBuilder sb) { sb.append(queueName).append(", ") .append(current.getMemory()).append(", ") .append(current.getVirtualCores()).append(", ") .append(pending.getMemory()).append(", ") .append(pending.getVirtualCores()).append(", ") .append(guaranteed.getMemory()).append(", ") .append(guaranteed.getVirtualCores()).append(", ") .append(idealAssigned.getMemory()).append(", ") .append(idealAssigned.getVirtualCores()).append(", ") .append(toBePreempted.getMemory()).append(", ") .append(toBePreempted.getVirtualCores() ).append(", ") .append(actuallyPreempted.getMemory()).append(", ") .append(actuallyPreempted.getVirtualCores()); } } static class TQComparator implements Comparator<TempQueuePerPartition> { private ResourceCalculator rc; private Resource clusterRes; TQComparator(ResourceCalculator rc, Resource clusterRes) { this.rc = rc; this.clusterRes = clusterRes; } @Override public int compare(TempQueuePerPartition tq1, TempQueuePerPartition tq2) { if (getIdealPctOfGuaranteed(tq1) < getIdealPctOfGuaranteed(tq2)) { return -1; } if (getIdealPctOfGuaranteed(tq1) > getIdealPctOfGuaranteed(tq2)) { return 1; } return 0; } // Calculates idealAssigned / guaranteed // TempQueues with 0 guarantees are always considered the most over // capacity and therefore considered last for resources. private double getIdealPctOfGuaranteed(TempQueuePerPartition q) { double pctOver = Integer.MAX_VALUE; if (q != null && Resources.greaterThan( rc, clusterRes, q.guaranteed, Resources.none())) { pctOver = Resources.divide(rc, clusterRes, q.idealAssigned, q.guaranteed); } return (pctOver); } } @VisibleForTesting public Map<String, Map<String, TempQueuePerPartition>> getQueuePartitions() { return queueToPartitions; } }
46,862
40.107895
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/StoreFencedException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.exceptions.YarnException; public class StoreFencedException extends YarnException { private static final long serialVersionUID = 1L; public StoreFencedException() { super("RMStateStore has been fenced"); } }
1,122
37.724138
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreFactory.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.yarn.conf.YarnConfiguration; public class RMStateStoreFactory { private static final Log LOG = LogFactory.getLog(RMStateStoreFactory.class); public static RMStateStore getStore(Configuration conf) { Class<? extends RMStateStore> storeClass = conf.getClass(YarnConfiguration.RM_STORE, MemoryRMStateStore.class, RMStateStore.class); LOG.info("Using RMStateStore implementation - " + storeClass); return ReflectionUtils.newInstance(storeClass, conf); } }
1,551
42.111111
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/Recoverable.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; public interface Recoverable { public void recover(RMState state) throws Exception; }
1,028
41.875
83
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @InterfaceAudience.Private @InterfaceStability.Unstable package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability;
1,047
40.92
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreAMRMTokenEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; public class RMStateStoreAMRMTokenEvent extends RMStateStoreEvent { private AMRMTokenSecretManagerState amrmTokenSecretManagerState; private boolean isUpdate; public RMStateStoreAMRMTokenEvent(RMStateStoreEventType type) { super(type); } public RMStateStoreAMRMTokenEvent( AMRMTokenSecretManagerState amrmTokenSecretManagerState, boolean isUpdate, RMStateStoreEventType type) { this(type); this.amrmTokenSecretManagerState = amrmTokenSecretManagerState; this.isUpdate = isUpdate; } public AMRMTokenSecretManagerState getAmrmTokenSecretManagerState() { return amrmTokenSecretManagerState; } public boolean isUpdate() { return isUpdate; } }
1,672
34.595745
98
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.google.common.base.Preconditions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.AuthInfo; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.framework.api.transaction.CuratorTransactionFinal; import org.apache.curator.retry.RetryNTimes; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.util.ZKUtil; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.conf.HAUtil; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.proto.YarnServerCommonProtos.VersionProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.AMRMTokenSecretManagerStateProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationAttemptStateDataProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationStateDataProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.EpochProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.records.impl.pb.VersionPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.RMZKUtils; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.Epoch; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMDelegationTokenIdentifierData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.AMRMTokenSecretManagerStatePBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.EpochPBImpl; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Id; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.server.auth.DigestAuthenticationProvider; import com.google.common.annotations.VisibleForTesting; /** * {@link RMStateStore} implementation backed by ZooKeeper. * * The znode structure is as follows: * ROOT_DIR_PATH * |--- VERSION_INFO * |--- EPOCH_NODE * |--- RM_ZK_FENCING_LOCK * |--- RM_APP_ROOT * | |----- (#ApplicationId1) * | | |----- (#ApplicationAttemptIds) * | | * | |----- (#ApplicationId2) * | | |----- (#ApplicationAttemptIds) * | .... * | * |--- RM_DT_SECRET_MANAGER_ROOT * |----- RM_DT_SEQUENTIAL_NUMBER_ZNODE_NAME * |----- RM_DELEGATION_TOKENS_ROOT_ZNODE_NAME * | |----- Token_1 * | |----- Token_2 * | .... * | * |----- RM_DT_MASTER_KEYS_ROOT_ZNODE_NAME * | |----- Key_1 * | |----- Key_2 * .... * |--- AMRMTOKEN_SECRET_MANAGER_ROOT * |----- currentMasterKey * |----- nextMasterKey * * |-- RESERVATION_SYSTEM_ROOT * |------PLAN_1 * | |------ RESERVATION_1 * | |------ RESERVATION_2 * | .... * |------PLAN_2 * .... * Note: Changes from 1.1 to 1.2 - AMRMTokenSecretManager state has been saved * separately. The currentMasterkey and nextMasterkey have been stored. * Also, AMRMToken has been removed from ApplicationAttemptState. * * Changes from 1.2 to 1.3, Addition of ReservationSystem state. */ @Private @Unstable public class ZKRMStateStore extends RMStateStore { public static final Log LOG = LogFactory.getLog(ZKRMStateStore.class); private final SecureRandom random = new SecureRandom(); protected static final String ROOT_ZNODE_NAME = "ZKRMStateRoot"; protected static final Version CURRENT_VERSION_INFO = Version .newInstance(1, 3); private static final String RM_DELEGATION_TOKENS_ROOT_ZNODE_NAME = "RMDelegationTokensRoot"; private static final String RM_DT_SEQUENTIAL_NUMBER_ZNODE_NAME = "RMDTSequentialNumber"; private static final String RM_DT_MASTER_KEYS_ROOT_ZNODE_NAME = "RMDTMasterKeysRoot"; private String zkHostPort = null; private int numRetries; private int zkSessionTimeout; @VisibleForTesting int zkRetryInterval; /** Znode paths */ private String zkRootNodePath; private String rmAppRoot; private String rmDTSecretManagerRoot; private String dtMasterKeysRootPath; private String delegationTokensRootPath; private String dtSequenceNumberPath; private String amrmTokenSecretManagerRoot; private String reservationRoot; @VisibleForTesting protected String znodeWorkingPath; /** Fencing related variables */ private static final String FENCING_LOCK = "RM_ZK_FENCING_LOCK"; private boolean useDefaultFencingScheme = false; private String fencingNodePath; private Thread verifyActiveStatusThread; /** ACL and auth info */ private List<ACL> zkAcl; private List<ZKUtil.ZKAuthInfo> zkAuths; @VisibleForTesting List<ACL> zkRootNodeAcl; private String zkRootNodeUsername; private final String zkRootNodePassword = Long.toString(random.nextLong()); public static final int CREATE_DELETE_PERMS = ZooDefs.Perms.CREATE | ZooDefs.Perms.DELETE; private final String zkRootNodeAuthScheme = new DigestAuthenticationProvider().getScheme(); @VisibleForTesting protected CuratorFramework curatorFramework; /** * Given the {@link Configuration} and {@link ACL}s used (zkAcl) for * ZooKeeper access, construct the {@link ACL}s for the store's root node. * In the constructed {@link ACL}, all the users allowed by zkAcl are given * rwa access, while the current RM has exclude create-delete access. * * To be called only when HA is enabled and the configuration doesn't set ACL * for the root node. */ @VisibleForTesting @Private @Unstable protected List<ACL> constructZkRootNodeACL( Configuration conf, List<ACL> sourceACLs) throws NoSuchAlgorithmException { List<ACL> zkRootNodeAcl = new ArrayList<>(); for (ACL acl : sourceACLs) { zkRootNodeAcl.add(new ACL( ZKUtil.removeSpecificPerms(acl.getPerms(), CREATE_DELETE_PERMS), acl.getId())); } zkRootNodeUsername = HAUtil.getConfValueForRMInstance( YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS, conf); Id rmId = new Id(zkRootNodeAuthScheme, DigestAuthenticationProvider.generateDigest( zkRootNodeUsername + ":" + zkRootNodePassword)); zkRootNodeAcl.add(new ACL(CREATE_DELETE_PERMS, rmId)); return zkRootNodeAcl; } @Override public synchronized void initInternal(Configuration conf) throws Exception { zkHostPort = conf.get(YarnConfiguration.RM_ZK_ADDRESS); if (zkHostPort == null) { throw new YarnRuntimeException("No server address specified for " + "zookeeper state store for Resource Manager recovery. " + YarnConfiguration.RM_ZK_ADDRESS + " is not configured."); } numRetries = conf.getInt(YarnConfiguration.RM_ZK_NUM_RETRIES, YarnConfiguration.DEFAULT_ZK_RM_NUM_RETRIES); znodeWorkingPath = conf.get(YarnConfiguration.ZK_RM_STATE_STORE_PARENT_PATH, YarnConfiguration.DEFAULT_ZK_RM_STATE_STORE_PARENT_PATH); zkSessionTimeout = conf.getInt(YarnConfiguration.RM_ZK_TIMEOUT_MS, YarnConfiguration.DEFAULT_RM_ZK_TIMEOUT_MS); if (HAUtil.isHAEnabled(conf)) { zkRetryInterval = zkSessionTimeout / numRetries; } else { zkRetryInterval = conf.getInt(YarnConfiguration.RM_ZK_RETRY_INTERVAL_MS, YarnConfiguration.DEFAULT_RM_ZK_RETRY_INTERVAL_MS); } zkAcl = RMZKUtils.getZKAcls(conf); zkAuths = RMZKUtils.getZKAuths(conf); zkRootNodePath = getNodePath(znodeWorkingPath, ROOT_ZNODE_NAME); rmAppRoot = getNodePath(zkRootNodePath, RM_APP_ROOT); /* Initialize fencing related paths, acls, and ops */ fencingNodePath = getNodePath(zkRootNodePath, FENCING_LOCK); if (HAUtil.isHAEnabled(conf)) { String zkRootNodeAclConf = HAUtil.getConfValueForRMInstance (YarnConfiguration.ZK_RM_STATE_STORE_ROOT_NODE_ACL, conf); if (zkRootNodeAclConf != null) { zkRootNodeAclConf = ZKUtil.resolveConfIndirection(zkRootNodeAclConf); try { zkRootNodeAcl = ZKUtil.parseACLs(zkRootNodeAclConf); } catch (ZKUtil.BadAclFormatException bafe) { LOG.error("Invalid format for " + YarnConfiguration.ZK_RM_STATE_STORE_ROOT_NODE_ACL); throw bafe; } } else { useDefaultFencingScheme = true; zkRootNodeAcl = constructZkRootNodeACL(conf, zkAcl); } } rmDTSecretManagerRoot = getNodePath(zkRootNodePath, RM_DT_SECRET_MANAGER_ROOT); dtMasterKeysRootPath = getNodePath(rmDTSecretManagerRoot, RM_DT_MASTER_KEYS_ROOT_ZNODE_NAME); delegationTokensRootPath = getNodePath(rmDTSecretManagerRoot, RM_DELEGATION_TOKENS_ROOT_ZNODE_NAME); dtSequenceNumberPath = getNodePath(rmDTSecretManagerRoot, RM_DT_SEQUENTIAL_NUMBER_ZNODE_NAME); amrmTokenSecretManagerRoot = getNodePath(zkRootNodePath, AMRMTOKEN_SECRET_MANAGER_ROOT); reservationRoot = getNodePath(zkRootNodePath, RESERVATION_SYSTEM_ROOT); } @Override public synchronized void startInternal() throws Exception { // createConnection for future API calls createConnection(); // ensure root dirs exist createRootDirRecursively(znodeWorkingPath); create(zkRootNodePath); if (HAUtil.isHAEnabled(getConfig())){ fence(); verifyActiveStatusThread = new VerifyActiveStatusThread(); verifyActiveStatusThread.start(); } create(rmAppRoot); create(rmDTSecretManagerRoot); create(dtMasterKeysRootPath); create(delegationTokensRootPath); create(dtSequenceNumberPath); create(amrmTokenSecretManagerRoot); create(reservationRoot); } private void logRootNodeAcls(String prefix) throws Exception { Stat getStat = new Stat(); List<ACL> getAcls = getACL(zkRootNodePath); StringBuilder builder = new StringBuilder(); builder.append(prefix); for (ACL acl : getAcls) { builder.append(acl.toString()); } builder.append(getStat.toString()); LOG.debug(builder.toString()); } private synchronized void fence() throws Exception { if (LOG.isTraceEnabled()) { logRootNodeAcls("Before fencing\n"); } curatorFramework.setACL().withACL(zkRootNodeAcl).forPath(zkRootNodePath); delete(fencingNodePath); if (LOG.isTraceEnabled()) { logRootNodeAcls("After fencing\n"); } } @Override protected synchronized void closeInternal() throws Exception { if (verifyActiveStatusThread != null) { verifyActiveStatusThread.interrupt(); verifyActiveStatusThread.join(1000); } IOUtils.closeStream(curatorFramework); } @Override protected Version getCurrentVersion() { return CURRENT_VERSION_INFO; } @Override protected synchronized void storeVersion() throws Exception { String versionNodePath = getNodePath(zkRootNodePath, VERSION_NODE); byte[] data = ((VersionPBImpl) CURRENT_VERSION_INFO).getProto().toByteArray(); if (exists(versionNodePath)) { safeSetData(versionNodePath, data, -1); } else { safeCreate(versionNodePath, data, zkAcl, CreateMode.PERSISTENT); } } @Override protected synchronized Version loadVersion() throws Exception { String versionNodePath = getNodePath(zkRootNodePath, VERSION_NODE); if (exists(versionNodePath)) { byte[] data = getData(versionNodePath); return new VersionPBImpl(VersionProto.parseFrom(data)); } return null; } @Override public synchronized long getAndIncrementEpoch() throws Exception { String epochNodePath = getNodePath(zkRootNodePath, EPOCH_NODE); long currentEpoch = 0; if (exists(epochNodePath)) { // load current epoch byte[] data = getData(epochNodePath); Epoch epoch = new EpochPBImpl(EpochProto.parseFrom(data)); currentEpoch = epoch.getEpoch(); // increment epoch and store it byte[] storeData = Epoch.newInstance(currentEpoch + 1).getProto() .toByteArray(); safeSetData(epochNodePath, storeData, -1); } else { // initialize epoch node with 1 for the next time. byte[] storeData = Epoch.newInstance(currentEpoch + 1).getProto() .toByteArray(); safeCreate(epochNodePath, storeData, zkAcl, CreateMode.PERSISTENT); } return currentEpoch; } @Override public synchronized RMState loadState() throws Exception { RMState rmState = new RMState(); // recover DelegationTokenSecretManager loadRMDTSecretManagerState(rmState); // recover RM applications loadRMAppState(rmState); // recover AMRMTokenSecretManager loadAMRMTokenSecretManagerState(rmState); // recover reservation state loadReservationSystemState(rmState); return rmState; } private void loadReservationSystemState(RMState rmState) throws Exception { List<String> planNodes = getChildren(reservationRoot); for (String planName : planNodes) { if (LOG.isDebugEnabled()) { LOG.debug("Loading plan from znode: " + planName); } String planNodePath = getNodePath(reservationRoot, planName); List<String> reservationNodes = getChildren(planNodePath); for (String reservationNodeName : reservationNodes) { String reservationNodePath = getNodePath(planNodePath, reservationNodeName); if (LOG.isDebugEnabled()) { LOG.debug("Loading reservation from znode: " + reservationNodePath); } byte[] reservationData = getData(reservationNodePath); ReservationAllocationStateProto allocationState = ReservationAllocationStateProto.parseFrom(reservationData); if (!rmState.getReservationState().containsKey(planName)) { rmState.getReservationState().put(planName, new HashMap<ReservationId, ReservationAllocationStateProto>()); } ReservationId reservationId = ReservationId.parseReservationId(reservationNodeName); rmState.getReservationState().get(planName).put(reservationId, allocationState); } } } private void loadAMRMTokenSecretManagerState(RMState rmState) throws Exception { byte[] data = getData(amrmTokenSecretManagerRoot); if (data == null) { LOG.warn("There is no data saved"); return; } AMRMTokenSecretManagerStatePBImpl stateData = new AMRMTokenSecretManagerStatePBImpl( AMRMTokenSecretManagerStateProto.parseFrom(data)); rmState.amrmTokenSecretManagerState = AMRMTokenSecretManagerState.newInstance( stateData.getCurrentMasterKey(), stateData.getNextMasterKey()); } private synchronized void loadRMDTSecretManagerState(RMState rmState) throws Exception { loadRMDelegationKeyState(rmState); loadRMSequentialNumberState(rmState); loadRMDelegationTokenState(rmState); } private void loadRMDelegationKeyState(RMState rmState) throws Exception { List<String> childNodes = getChildren(dtMasterKeysRootPath); for (String childNodeName : childNodes) { String childNodePath = getNodePath(dtMasterKeysRootPath, childNodeName); byte[] childData = getData(childNodePath); if (childData == null) { LOG.warn("Content of " + childNodePath + " is broken."); continue; } ByteArrayInputStream is = new ByteArrayInputStream(childData); DataInputStream fsIn = new DataInputStream(is); try { if (childNodeName.startsWith(DELEGATION_KEY_PREFIX)) { DelegationKey key = new DelegationKey(); key.readFields(fsIn); rmState.rmSecretManagerState.masterKeyState.add(key); if (LOG.isDebugEnabled()) { LOG.debug("Loaded delegation key: keyId=" + key.getKeyId() + ", expirationDate=" + key.getExpiryDate()); } } } finally { is.close(); } } } private void loadRMSequentialNumberState(RMState rmState) throws Exception { byte[] seqData = getData(dtSequenceNumberPath); if (seqData != null) { ByteArrayInputStream seqIs = new ByteArrayInputStream(seqData); DataInputStream seqIn = new DataInputStream(seqIs); try { rmState.rmSecretManagerState.dtSequenceNumber = seqIn.readInt(); } finally { seqIn.close(); } } } private void loadRMDelegationTokenState(RMState rmState) throws Exception { List<String> childNodes = getChildren(delegationTokensRootPath); for (String childNodeName : childNodes) { String childNodePath = getNodePath(delegationTokensRootPath, childNodeName); byte[] childData = getData(childNodePath); if (childData == null) { LOG.warn("Content of " + childNodePath + " is broken."); continue; } ByteArrayInputStream is = new ByteArrayInputStream(childData); DataInputStream fsIn = new DataInputStream(is); try { if (childNodeName.startsWith(DELEGATION_TOKEN_PREFIX)) { RMDelegationTokenIdentifierData identifierData = new RMDelegationTokenIdentifierData(); identifierData.readFields(fsIn); RMDelegationTokenIdentifier identifier = identifierData.getTokenIdentifier(); long renewDate = identifierData.getRenewDate(); rmState.rmSecretManagerState.delegationTokenState.put(identifier, renewDate); if (LOG.isDebugEnabled()) { LOG.debug("Loaded RMDelegationTokenIdentifier: " + identifier + " renewDate=" + renewDate); } } } finally { is.close(); } } } private synchronized void loadRMAppState(RMState rmState) throws Exception { List<String> childNodes = getChildren(rmAppRoot); for (String childNodeName : childNodes) { String childNodePath = getNodePath(rmAppRoot, childNodeName); byte[] childData = getData(childNodePath); if (childNodeName.startsWith(ApplicationId.appIdStrPrefix)) { // application if (LOG.isDebugEnabled()) { LOG.debug("Loading application from znode: " + childNodeName); } ApplicationId appId = ConverterUtils.toApplicationId(childNodeName); ApplicationStateDataPBImpl appState = new ApplicationStateDataPBImpl( ApplicationStateDataProto.parseFrom(childData)); if (!appId.equals( appState.getApplicationSubmissionContext().getApplicationId())) { throw new YarnRuntimeException("The child node name is different " + "from the application id"); } rmState.appState.put(appId, appState); loadApplicationAttemptState(appState, appId); } else { LOG.info("Unknown child node with name: " + childNodeName); } } } private void loadApplicationAttemptState(ApplicationStateData appState, ApplicationId appId) throws Exception { String appPath = getNodePath(rmAppRoot, appId.toString()); List<String> attempts = getChildren(appPath); for (String attemptIDStr : attempts) { if (attemptIDStr.startsWith(ApplicationAttemptId.appAttemptIdStrPrefix)) { String attemptPath = getNodePath(appPath, attemptIDStr); byte[] attemptData = getData(attemptPath); ApplicationAttemptStateDataPBImpl attemptState = new ApplicationAttemptStateDataPBImpl( ApplicationAttemptStateDataProto.parseFrom(attemptData)); appState.attempts.put(attemptState.getAttemptId(), attemptState); } } LOG.debug("Done loading applications from ZK state store"); } @Override public synchronized void storeApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateDataPB) throws Exception { String nodeCreatePath = getNodePath(rmAppRoot, appId.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Storing info for app: " + appId + " at: " + nodeCreatePath); } byte[] appStateData = appStateDataPB.getProto().toByteArray(); safeCreate(nodeCreatePath, appStateData, zkAcl, CreateMode.PERSISTENT); } @Override public synchronized void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateDataPB) throws Exception { String nodeUpdatePath = getNodePath(rmAppRoot, appId.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Storing final state info for app: " + appId + " at: " + nodeUpdatePath); } byte[] appStateData = appStateDataPB.getProto().toByteArray(); if (exists(nodeUpdatePath)) { safeSetData(nodeUpdatePath, appStateData, -1); } else { safeCreate(nodeUpdatePath, appStateData, zkAcl, CreateMode.PERSISTENT); LOG.debug(appId + " znode didn't exist. Created a new znode to" + " update the application state."); } } @Override public synchronized void storeApplicationAttemptStateInternal( ApplicationAttemptId appAttemptId, ApplicationAttemptStateData attemptStateDataPB) throws Exception { String appDirPath = getNodePath(rmAppRoot, appAttemptId.getApplicationId().toString()); String nodeCreatePath = getNodePath(appDirPath, appAttemptId.toString()); if (LOG.isDebugEnabled()) { LOG.debug("Storing info for attempt: " + appAttemptId + " at: " + nodeCreatePath); } byte[] attemptStateData = attemptStateDataPB.getProto().toByteArray(); safeCreate(nodeCreatePath, attemptStateData, zkAcl, CreateMode.PERSISTENT); } @Override public synchronized void updateApplicationAttemptStateInternal( ApplicationAttemptId appAttemptId, ApplicationAttemptStateData attemptStateDataPB) throws Exception { String appIdStr = appAttemptId.getApplicationId().toString(); String appAttemptIdStr = appAttemptId.toString(); String appDirPath = getNodePath(rmAppRoot, appIdStr); String nodeUpdatePath = getNodePath(appDirPath, appAttemptIdStr); if (LOG.isDebugEnabled()) { LOG.debug("Storing final state info for attempt: " + appAttemptIdStr + " at: " + nodeUpdatePath); } byte[] attemptStateData = attemptStateDataPB.getProto().toByteArray(); if (exists(nodeUpdatePath)) { safeSetData(nodeUpdatePath, attemptStateData, -1); } else { safeCreate(nodeUpdatePath, attemptStateData, zkAcl, CreateMode.PERSISTENT); LOG.debug(appAttemptId + " znode didn't exist. Created a new znode to" + " update the application attempt state."); } } @Override public synchronized void removeApplicationStateInternal( ApplicationStateData appState) throws Exception { String appId = appState.getApplicationSubmissionContext().getApplicationId() .toString(); String appIdRemovePath = getNodePath(rmAppRoot, appId); if (LOG.isDebugEnabled()) { LOG.debug("Removing info for app: " + appId + " at: " + appIdRemovePath + " and its attempts."); } for (ApplicationAttemptId attemptId : appState.attempts.keySet()) { String attemptRemovePath = getNodePath(appIdRemovePath, attemptId.toString()); safeDelete(attemptRemovePath); } safeDelete(appIdRemovePath); } @Override protected synchronized void storeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { SafeTransaction trx = new SafeTransaction(); addStoreOrUpdateOps(trx, rmDTIdentifier, renewDate, false); trx.commit(); } @Override protected synchronized void removeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier) throws Exception { String nodeRemovePath = getNodePath(delegationTokensRootPath, DELEGATION_TOKEN_PREFIX + rmDTIdentifier.getSequenceNumber()); if (LOG.isDebugEnabled()) { LOG.debug("Removing RMDelegationToken_" + rmDTIdentifier.getSequenceNumber()); } safeDelete(nodeRemovePath); } @Override protected synchronized void updateRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { SafeTransaction trx = new SafeTransaction(); String nodeRemovePath = getNodePath(delegationTokensRootPath, DELEGATION_TOKEN_PREFIX + rmDTIdentifier.getSequenceNumber()); if (exists(nodeRemovePath)) { // in case znode exists addStoreOrUpdateOps(trx, rmDTIdentifier, renewDate, true); } else { // in case znode doesn't exist addStoreOrUpdateOps(trx, rmDTIdentifier, renewDate, false); LOG.debug("Attempted to update a non-existing znode " + nodeRemovePath); } trx.commit(); } private void addStoreOrUpdateOps(SafeTransaction trx, RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, boolean isUpdate) throws Exception { // store RM delegation token String nodeCreatePath = getNodePath(delegationTokensRootPath, DELEGATION_TOKEN_PREFIX + rmDTIdentifier.getSequenceNumber()); ByteArrayOutputStream seqOs = new ByteArrayOutputStream(); DataOutputStream seqOut = new DataOutputStream(seqOs); RMDelegationTokenIdentifierData identifierData = new RMDelegationTokenIdentifierData(rmDTIdentifier, renewDate); try { if (LOG.isDebugEnabled()) { LOG.debug((isUpdate ? "Storing " : "Updating ") + "RMDelegationToken_" + rmDTIdentifier.getSequenceNumber()); } if (isUpdate) { trx.setData(nodeCreatePath, identifierData.toByteArray(), -1); } else { trx.create(nodeCreatePath, identifierData.toByteArray(), zkAcl, CreateMode.PERSISTENT); // Update Sequence number only while storing DT seqOut.writeInt(rmDTIdentifier.getSequenceNumber()); if (LOG.isDebugEnabled()) { LOG.debug((isUpdate ? "Storing " : "Updating ") + dtSequenceNumberPath + ". SequenceNumber: " + rmDTIdentifier.getSequenceNumber()); } trx.setData(dtSequenceNumberPath, seqOs.toByteArray(), -1); } } finally { seqOs.close(); } } @Override protected synchronized void storeRMDTMasterKeyState( DelegationKey delegationKey) throws Exception { String nodeCreatePath = getNodePath(dtMasterKeysRootPath, DELEGATION_KEY_PREFIX + delegationKey.getKeyId()); ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream fsOut = new DataOutputStream(os); if (LOG.isDebugEnabled()) { LOG.debug("Storing RMDelegationKey_" + delegationKey.getKeyId()); } delegationKey.write(fsOut); try { safeCreate(nodeCreatePath, os.toByteArray(), zkAcl, CreateMode.PERSISTENT); } finally { os.close(); } } @Override protected synchronized void removeRMDTMasterKeyState( DelegationKey delegationKey) throws Exception { String nodeRemovePath = getNodePath(dtMasterKeysRootPath, DELEGATION_KEY_PREFIX + delegationKey.getKeyId()); if (LOG.isDebugEnabled()) { LOG.debug("Removing RMDelegationKey_" + delegationKey.getKeyId()); } safeDelete(nodeRemovePath); } @Override public synchronized void deleteStore() throws Exception { delete(zkRootNodePath); } @Override public synchronized void removeApplication(ApplicationId removeAppId) throws Exception { String appIdRemovePath = getNodePath(rmAppRoot, removeAppId.toString()); delete(appIdRemovePath); } @VisibleForTesting String getNodePath(String root, String nodeName) { return (root + "/" + nodeName); } @Override public synchronized void storeOrUpdateAMRMTokenSecretManagerState( AMRMTokenSecretManagerState amrmTokenSecretManagerState, boolean isUpdate) throws Exception { AMRMTokenSecretManagerState data = AMRMTokenSecretManagerState.newInstance(amrmTokenSecretManagerState); byte[] stateData = data.getProto().toByteArray(); safeSetData(amrmTokenSecretManagerRoot, stateData, -1); } @Override protected synchronized void removeReservationState(String planName, String reservationIdName) throws Exception { String planNodePath = getNodePath(reservationRoot, planName); String reservationPath = getNodePath(planNodePath, reservationIdName); if (LOG.isDebugEnabled()) { LOG.debug("Removing reservationallocation " + reservationIdName + " for" + " plan " + planName); } safeDelete(reservationPath); List<String> reservationNodes = getChildren(planNodePath); if (reservationNodes.isEmpty()) { safeDelete(planNodePath); } } @Override protected synchronized void storeReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { SafeTransaction trx = new SafeTransaction(); addOrUpdateReservationState( reservationAllocation, planName, reservationIdName, trx, false); trx.commit(); } @Override protected synchronized void updateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { SafeTransaction trx = new SafeTransaction(); addOrUpdateReservationState( reservationAllocation, planName, reservationIdName, trx, true); trx.commit(); } private void addOrUpdateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName, SafeTransaction trx, boolean isUpdate) throws Exception { String planCreatePath = getNodePath(reservationRoot, planName); String reservationPath = getNodePath(planCreatePath, reservationIdName); byte[] reservationData = reservationAllocation.toByteArray(); if (!exists(planCreatePath)) { if (LOG.isDebugEnabled()) { LOG.debug("Creating plan node: " + planName + " at: " + planCreatePath); } trx.create(planCreatePath, null, zkAcl, CreateMode.PERSISTENT); } if (isUpdate) { if (LOG.isDebugEnabled()) { LOG.debug("Updating reservation: " + reservationIdName + " in plan:" + planName + " at: " + reservationPath); } trx.setData(reservationPath, reservationData, -1); } else { if (LOG.isDebugEnabled()) { LOG.debug("Storing reservation: " + reservationIdName + " in plan:" + planName + " at: " + reservationPath); } trx.create(reservationPath, reservationData, zkAcl, CreateMode.PERSISTENT); } } /** * Utility function to ensure that the configured base znode exists. * This recursively creates the znode as well as all of its parents. */ private void createRootDirRecursively(String path) throws Exception { String pathParts[] = path.split("/"); Preconditions.checkArgument(pathParts.length >= 1 && pathParts[0].isEmpty(), "Invalid path: %s", path); StringBuilder sb = new StringBuilder(); for (int i = 1; i < pathParts.length; i++) { sb.append("/").append(pathParts[i]); create(sb.toString()); } } /* * ZK operations using curator */ private void createConnection() throws Exception { // Curator connection CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); builder = builder.connectString(zkHostPort) .connectionTimeoutMs(zkSessionTimeout) .retryPolicy(new RetryNTimes(numRetries, zkRetryInterval)); // Set up authorization based on fencing scheme List<AuthInfo> authInfos = new ArrayList<>(); for (ZKUtil.ZKAuthInfo zkAuth : zkAuths) { authInfos.add(new AuthInfo(zkAuth.getScheme(), zkAuth.getAuth())); } if (useDefaultFencingScheme) { byte[] defaultFencingAuth = (zkRootNodeUsername + ":" + zkRootNodePassword).getBytes( Charset.forName("UTF-8")); authInfos.add(new AuthInfo(zkRootNodeAuthScheme, defaultFencingAuth)); } builder = builder.authorization(authInfos); // Connect to ZK curatorFramework = builder.build(); curatorFramework.start(); } @VisibleForTesting byte[] getData(final String path) throws Exception { return curatorFramework.getData().forPath(path); } private List<ACL> getACL(final String path) throws Exception { return curatorFramework.getACL().forPath(path); } private List<String> getChildren(final String path) throws Exception { return curatorFramework.getChildren().forPath(path); } private boolean exists(final String path) throws Exception { return curatorFramework.checkExists().forPath(path) != null; } @VisibleForTesting void create(final String path) throws Exception { if (!exists(path)) { curatorFramework.create() .withMode(CreateMode.PERSISTENT).withACL(zkAcl) .forPath(path, null); } } @VisibleForTesting void delete(final String path) throws Exception { if (exists(path)) { curatorFramework.delete().deletingChildrenIfNeeded().forPath(path); } } private void safeCreate(String path, byte[] data, List<ACL> acl, CreateMode mode) throws Exception { if (!exists(path)) { SafeTransaction transaction = new SafeTransaction(); transaction.create(path, data, acl, mode); transaction.commit(); } } private void safeDelete(final String path) throws Exception { if (exists(path)) { SafeTransaction transaction = new SafeTransaction(); transaction.delete(path); transaction.commit(); } } private void safeSetData(String path, byte[] data, int version) throws Exception { SafeTransaction transaction = new SafeTransaction(); transaction.setData(path, data, version); transaction.commit(); } /** * Use curator transactions to ensure zk-operations are performed in an all * or nothing fashion. This is equivalent to using ZooKeeper#multi. * * TODO (YARN-3774): Curator 3.0 introduces CuratorOp similar to Op. We ll * have to rewrite this inner class when we adopt that. */ private class SafeTransaction { private CuratorTransactionFinal transactionFinal; SafeTransaction() throws Exception { CuratorTransaction transaction = curatorFramework.inTransaction(); transactionFinal = transaction.create() .withMode(CreateMode.PERSISTENT).withACL(zkAcl) .forPath(fencingNodePath, new byte[0]).and(); } public void commit() throws Exception { transactionFinal = transactionFinal.delete() .forPath(fencingNodePath).and(); transactionFinal.commit(); } public void create(String path, byte[] data, List<ACL> acl, CreateMode mode) throws Exception { transactionFinal = transactionFinal.create() .withMode(mode).withACL(acl).forPath(path, data).and(); } public void delete(String path) throws Exception { transactionFinal = transactionFinal.delete().forPath(path).and(); } public void setData(String path, byte[] data, int version) throws Exception { transactionFinal = transactionFinal.setData() .withVersion(version).forPath(path, data).and(); } } /** * Helper class that periodically attempts creating a znode to ensure that * this RM continues to be the Active. */ private class VerifyActiveStatusThread extends Thread { VerifyActiveStatusThread() { super(VerifyActiveStatusThread.class.getName()); } public void run() { try { while (true) { if(isFencedState()) { break; } // Create and delete fencing node new SafeTransaction().commit(); Thread.sleep(zkSessionTimeout); } } catch (InterruptedException ie) { LOG.info(VerifyActiveStatusThread.class.getName() + " thread " + "interrupted! Exiting!"); } catch (Exception e) { notifyStoreOperationFailed(new StoreFencedException()); } } } }
38,878
35.782403
112
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreAppAttemptEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; public class RMStateStoreAppAttemptEvent extends RMStateStoreEvent { ApplicationAttemptStateData attemptState; public RMStateStoreAppAttemptEvent(ApplicationAttemptStateData attemptState) { super(RMStateStoreEventType.STORE_APP_ATTEMPT); this.attemptState = attemptState; } public ApplicationAttemptStateData getAppAttemptState() { return attemptState; } }
1,358
37.828571
98
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreEventType.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; public enum RMStateStoreEventType { STORE_APP_ATTEMPT, STORE_APP, UPDATE_APP, UPDATE_APP_ATTEMPT, REMOVE_APP, FENCED, // Below events should be called synchronously STORE_MASTERKEY, REMOVE_MASTERKEY, STORE_DELEGATION_TOKEN, REMOVE_DELEGATION_TOKEN, UPDATE_DELEGATION_TOKEN, UPDATE_AMRM_TOKEN, STORE_RESERVATION, UPDATE_RESERVATION, REMOVE_RESERVATION, }
1,260
30.525
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreAppEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; public class RMStateStoreAppEvent extends RMStateStoreEvent { private final ApplicationStateData appState; public RMStateStoreAppEvent(ApplicationStateData appState) { super(RMStateStoreEventType.STORE_APP); this.appState = appState; } public ApplicationStateData getAppState() { return appState; } }
1,292
34.916667
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.fs.XAttrSetFlag; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.proto.YarnServerCommonProtos.VersionProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.AMRMTokenSecretManagerStateProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationAttemptStateDataProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationStateDataProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.EpochProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.records.impl.pb.VersionPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.Epoch; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMDelegationTokenIdentifierData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.AMRMTokenSecretManagerStatePBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.EpochPBImpl; import com.google.common.annotations.VisibleForTesting; @Private @Unstable /** * A simple class for storing RM state in any storage that implements a basic * FileSystem interface. Does not use directories so that simple key-value * stores can be used. The retry policy for the real filesystem client must be * configured separately to enable retry of filesystem operations when needed. * * Changes from 1.1 to 1.2, AMRMTokenSecretManager state has been saved * separately. The currentMasterkey and nextMasterkey have been stored. * Also, AMRMToken has been removed from ApplicationAttemptState. * * Changes from 1.2 to 1.3, Addition of ReservationSystem state. */ public class FileSystemRMStateStore extends RMStateStore { public static final Log LOG = LogFactory.getLog(FileSystemRMStateStore.class); protected static final String ROOT_DIR_NAME = "FSRMStateRoot"; protected static final Version CURRENT_VERSION_INFO = Version .newInstance(1, 3); protected static final String AMRMTOKEN_SECRET_MANAGER_NODE = "AMRMTokenSecretManagerNode"; private static final String UNREADABLE_BY_SUPERUSER_XATTRIB = "security.hdfs.unreadable.by.superuser"; protected FileSystem fs; @VisibleForTesting protected Configuration fsConf; private Path rootDirPath; @Private @VisibleForTesting Path rmDTSecretManagerRoot; private Path rmAppRoot; private Path dtSequenceNumberPath = null; private int fsNumRetries; private long fsRetryInterval; private boolean intermediateEncryptionEnabled = YarnConfiguration.DEFAULT_YARN_INTERMEDIATE_DATA_ENCRYPTION; @VisibleForTesting Path fsWorkingPath; Path amrmTokenSecretManagerRoot; private Path reservationRoot; @Override public synchronized void initInternal(Configuration conf) throws Exception{ fsWorkingPath = new Path(conf.get(YarnConfiguration.FS_RM_STATE_STORE_URI)); rootDirPath = new Path(fsWorkingPath, ROOT_DIR_NAME); rmDTSecretManagerRoot = new Path(rootDirPath, RM_DT_SECRET_MANAGER_ROOT); rmAppRoot = new Path(rootDirPath, RM_APP_ROOT); amrmTokenSecretManagerRoot = new Path(rootDirPath, AMRMTOKEN_SECRET_MANAGER_ROOT); reservationRoot = new Path(rootDirPath, RESERVATION_SYSTEM_ROOT); fsNumRetries = conf.getInt(YarnConfiguration.FS_RM_STATE_STORE_NUM_RETRIES, YarnConfiguration.DEFAULT_FS_RM_STATE_STORE_NUM_RETRIES); fsRetryInterval = conf.getLong(YarnConfiguration.FS_RM_STATE_STORE_RETRY_INTERVAL_MS, YarnConfiguration.DEFAULT_FS_RM_STATE_STORE_RETRY_INTERVAL_MS); intermediateEncryptionEnabled = conf.getBoolean(YarnConfiguration.YARN_INTERMEDIATE_DATA_ENCRYPTION, YarnConfiguration.DEFAULT_YARN_INTERMEDIATE_DATA_ENCRYPTION); } @Override protected synchronized void startInternal() throws Exception { // create filesystem only now, as part of service-start. By this time, RM is // authenticated with kerberos so we are good to create a file-system // handle. fsConf = new Configuration(getConfig()); fsConf.setBoolean("dfs.client.retry.policy.enabled", true); String retryPolicy = fsConf.get(YarnConfiguration.FS_RM_STATE_STORE_RETRY_POLICY_SPEC, YarnConfiguration.DEFAULT_FS_RM_STATE_STORE_RETRY_POLICY_SPEC); fsConf.set("dfs.client.retry.policy.spec", retryPolicy); String scheme = fsWorkingPath.toUri().getScheme(); if (scheme == null) { scheme = FileSystem.getDefaultUri(fsConf).getScheme(); } if (scheme != null) { String disableCacheName = String.format("fs.%s.impl.disable.cache", scheme); fsConf.setBoolean(disableCacheName, true); } fs = fsWorkingPath.getFileSystem(fsConf); mkdirsWithRetries(rmDTSecretManagerRoot); mkdirsWithRetries(rmAppRoot); mkdirsWithRetries(amrmTokenSecretManagerRoot); mkdirsWithRetries(reservationRoot); } @Override protected synchronized void closeInternal() throws Exception { closeWithRetries(); } @Override protected Version getCurrentVersion() { return CURRENT_VERSION_INFO; } @Override protected synchronized Version loadVersion() throws Exception { Path versionNodePath = getNodePath(rootDirPath, VERSION_NODE); FileStatus status = getFileStatusWithRetries(versionNodePath); if (status != null) { byte[] data = readFileWithRetries(versionNodePath, status.getLen()); Version version = new VersionPBImpl(VersionProto.parseFrom(data)); return version; } return null; } @Override protected synchronized void storeVersion() throws Exception { Path versionNodePath = getNodePath(rootDirPath, VERSION_NODE); byte[] data = ((VersionPBImpl) CURRENT_VERSION_INFO).getProto().toByteArray(); if (existsWithRetries(versionNodePath)) { updateFile(versionNodePath, data, false); } else { writeFileWithRetries(versionNodePath, data, false); } } @Override public synchronized long getAndIncrementEpoch() throws Exception { Path epochNodePath = getNodePath(rootDirPath, EPOCH_NODE); long currentEpoch = 0; FileStatus status = getFileStatusWithRetries(epochNodePath); if (status != null) { // load current epoch byte[] data = readFileWithRetries(epochNodePath, status.getLen()); Epoch epoch = new EpochPBImpl(EpochProto.parseFrom(data)); currentEpoch = epoch.getEpoch(); // increment epoch and store it byte[] storeData = Epoch.newInstance(currentEpoch + 1).getProto() .toByteArray(); updateFile(epochNodePath, storeData, false); } else { // initialize epoch file with 1 for the next time. byte[] storeData = Epoch.newInstance(currentEpoch + 1).getProto() .toByteArray(); writeFileWithRetries(epochNodePath, storeData, false); } return currentEpoch; } @Override public synchronized RMState loadState() throws Exception { RMState rmState = new RMState(); // recover DelegationTokenSecretManager loadRMDTSecretManagerState(rmState); // recover RM applications loadRMAppState(rmState); // recover AMRMTokenSecretManager loadAMRMTokenSecretManagerState(rmState); // recover reservation state loadReservationSystemState(rmState); return rmState; } private void loadReservationSystemState(RMState rmState) throws Exception { try { final ReservationStateFileProcessor fileProcessor = new ReservationStateFileProcessor(rmState); final Path rootDirectory = this.reservationRoot; processDirectoriesOfFiles(fileProcessor, rootDirectory); } catch (Exception e) { LOG.error("Failed to load state.", e); throw e; } } private void loadAMRMTokenSecretManagerState(RMState rmState) throws Exception { checkAndResumeUpdateOperation(amrmTokenSecretManagerRoot); Path amrmTokenSecretManagerStateDataDir = new Path(amrmTokenSecretManagerRoot, AMRMTOKEN_SECRET_MANAGER_NODE); FileStatus status = getFileStatusWithRetries( amrmTokenSecretManagerStateDataDir); if (status == null) { return; } assert status.isFile(); byte[] data = readFileWithRetries(amrmTokenSecretManagerStateDataDir, status.getLen()); AMRMTokenSecretManagerStatePBImpl stateData = new AMRMTokenSecretManagerStatePBImpl( AMRMTokenSecretManagerStateProto.parseFrom(data)); rmState.amrmTokenSecretManagerState = AMRMTokenSecretManagerState.newInstance( stateData.getCurrentMasterKey(), stateData.getNextMasterKey()); } private void loadRMAppState(RMState rmState) throws Exception { try { List<ApplicationAttemptStateData> attempts = new ArrayList<>(); final RMAppStateFileProcessor rmAppStateFileProcessor = new RMAppStateFileProcessor(rmState, attempts); final Path rootDirectory = this.rmAppRoot; processDirectoriesOfFiles(rmAppStateFileProcessor, rootDirectory); // go through all attempts and add them to their apps, Ideally, each // attempt node must have a corresponding app node, because remove // directory operation remove both at the same time for (ApplicationAttemptStateData attemptState : attempts) { ApplicationId appId = attemptState.getAttemptId().getApplicationId(); ApplicationStateData appState = rmState.appState.get(appId); assert appState != null; appState.attempts.put(attemptState.getAttemptId(), attemptState); } LOG.info("Done loading applications from FS state store"); } catch (Exception e) { LOG.error("Failed to load state.", e); throw e; } } private void processDirectoriesOfFiles( RMStateFileProcessor rmAppStateFileProcessor, Path rootDirectory) throws Exception { for (FileStatus dir : listStatusWithRetries(rootDirectory)) { checkAndResumeUpdateOperation(dir.getPath()); String dirName = dir.getPath().getName(); for (FileStatus fileNodeStatus : listStatusWithRetries(dir.getPath())) { assert fileNodeStatus.isFile(); String fileName = fileNodeStatus.getPath().getName(); if (checkAndRemovePartialRecordWithRetries(fileNodeStatus.getPath())) { continue; } byte[] fileData = readFileWithRetries(fileNodeStatus.getPath(), fileNodeStatus.getLen()); // Set attribute if not already set setUnreadableBySuperuserXattrib(fileNodeStatus.getPath()); rmAppStateFileProcessor.processChildNode(dirName, fileName, fileData); } } } private boolean checkAndRemovePartialRecord(Path record) throws IOException { // If the file ends with .tmp then it shows that it failed // during saving state into state store. The file will be deleted as a // part of this call if (record.getName().endsWith(".tmp")) { LOG.error("incomplete rm state store entry found :" + record); fs.delete(record, false); return true; } return false; } private void checkAndResumeUpdateOperation(Path path) throws Exception { // Before loading the state information, check whether .new file exists. // If it does, the prior updateFile is failed on half way. We need to // complete replacing the old file first. FileStatus[] newChildNodes = listStatusWithRetries(path, new PathFilter() { @Override public boolean accept(Path path) { return path.getName().endsWith(".new"); } }); for(FileStatus newChildNodeStatus : newChildNodes) { assert newChildNodeStatus.isFile(); String newChildNodeName = newChildNodeStatus.getPath().getName(); String childNodeName = newChildNodeName.substring( 0, newChildNodeName.length() - ".new".length()); Path childNodePath = new Path(newChildNodeStatus.getPath().getParent(), childNodeName); replaceFile(newChildNodeStatus.getPath(), childNodePath); } } private void loadRMDTSecretManagerState(RMState rmState) throws Exception { checkAndResumeUpdateOperation(rmDTSecretManagerRoot); FileStatus[] childNodes = listStatusWithRetries(rmDTSecretManagerRoot); for(FileStatus childNodeStatus : childNodes) { assert childNodeStatus.isFile(); String childNodeName = childNodeStatus.getPath().getName(); if (checkAndRemovePartialRecordWithRetries(childNodeStatus.getPath())) { continue; } if(childNodeName.startsWith(DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX)) { rmState.rmSecretManagerState.dtSequenceNumber = Integer.parseInt(childNodeName.split("_")[1]); continue; } Path childNodePath = getNodePath(rmDTSecretManagerRoot, childNodeName); byte[] childData = readFileWithRetries(childNodePath, childNodeStatus.getLen()); ByteArrayInputStream is = new ByteArrayInputStream(childData); try (DataInputStream fsIn = new DataInputStream(is)) { if (childNodeName.startsWith(DELEGATION_KEY_PREFIX)) { DelegationKey key = new DelegationKey(); key.readFields(fsIn); rmState.rmSecretManagerState.masterKeyState.add(key); if (LOG.isDebugEnabled()) { LOG.debug("Loaded delegation key: keyId=" + key.getKeyId() + ", expirationDate=" + key.getExpiryDate()); } } else if (childNodeName.startsWith(DELEGATION_TOKEN_PREFIX)) { RMDelegationTokenIdentifierData identifierData = new RMDelegationTokenIdentifierData(); identifierData.readFields(fsIn); RMDelegationTokenIdentifier identifier = identifierData.getTokenIdentifier(); long renewDate = identifierData.getRenewDate(); rmState.rmSecretManagerState.delegationTokenState.put(identifier, renewDate); if (LOG.isDebugEnabled()) { LOG.debug("Loaded RMDelegationTokenIdentifier: " + identifier + " renewDate=" + renewDate); } } else { LOG.warn("Unknown file for recovering RMDelegationTokenSecretManager"); } } } } @Override public synchronized void storeApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateDataPB) throws Exception { Path appDirPath = getAppDir(rmAppRoot, appId); mkdirsWithRetries(appDirPath); Path nodeCreatePath = getNodePath(appDirPath, appId.toString()); LOG.info("Storing info for app: " + appId + " at: " + nodeCreatePath); byte[] appStateData = appStateDataPB.getProto().toByteArray(); try { // currently throw all exceptions. May need to respond differently for HA // based on whether we have lost the right to write to FS writeFileWithRetries(nodeCreatePath, appStateData, true); } catch (Exception e) { LOG.info("Error storing info for app: " + appId, e); throw e; } } @Override public synchronized void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateDataPB) throws Exception { Path appDirPath = getAppDir(rmAppRoot, appId); Path nodeCreatePath = getNodePath(appDirPath, appId.toString()); LOG.info("Updating info for app: " + appId + " at: " + nodeCreatePath); byte[] appStateData = appStateDataPB.getProto().toByteArray(); try { // currently throw all exceptions. May need to respond differently for HA // based on whether we have lost the right to write to FS updateFile(nodeCreatePath, appStateData, true); } catch (Exception e) { LOG.info("Error updating info for app: " + appId, e); throw e; } } @Override public synchronized void storeApplicationAttemptStateInternal( ApplicationAttemptId appAttemptId, ApplicationAttemptStateData attemptStateDataPB) throws Exception { Path appDirPath = getAppDir(rmAppRoot, appAttemptId.getApplicationId()); Path nodeCreatePath = getNodePath(appDirPath, appAttemptId.toString()); LOG.info("Storing info for attempt: " + appAttemptId + " at: " + nodeCreatePath); byte[] attemptStateData = attemptStateDataPB.getProto().toByteArray(); try { // currently throw all exceptions. May need to respond differently for HA // based on whether we have lost the right to write to FS writeFileWithRetries(nodeCreatePath, attemptStateData, true); } catch (Exception e) { LOG.info("Error storing info for attempt: " + appAttemptId, e); throw e; } } @Override public synchronized void updateApplicationAttemptStateInternal( ApplicationAttemptId appAttemptId, ApplicationAttemptStateData attemptStateDataPB) throws Exception { Path appDirPath = getAppDir(rmAppRoot, appAttemptId.getApplicationId()); Path nodeCreatePath = getNodePath(appDirPath, appAttemptId.toString()); LOG.info("Updating info for attempt: " + appAttemptId + " at: " + nodeCreatePath); byte[] attemptStateData = attemptStateDataPB.getProto().toByteArray(); try { // currently throw all exceptions. May need to respond differently for HA // based on whether we have lost the right to write to FS updateFile(nodeCreatePath, attemptStateData, true); } catch (Exception e) { LOG.info("Error updating info for attempt: " + appAttemptId, e); throw e; } } @Override public synchronized void removeApplicationStateInternal( ApplicationStateData appState) throws Exception { ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); Path nodeRemovePath = getAppDir(rmAppRoot, appId); LOG.info("Removing info for app: " + appId + " at: " + nodeRemovePath); deleteFileWithRetries(nodeRemovePath); } @Override public synchronized void storeRMDelegationTokenState( RMDelegationTokenIdentifier identifier, Long renewDate) throws Exception { storeOrUpdateRMDelegationTokenState(identifier, renewDate, false); } @Override public synchronized void removeRMDelegationTokenState( RMDelegationTokenIdentifier identifier) throws Exception { Path nodeCreatePath = getNodePath(rmDTSecretManagerRoot, DELEGATION_TOKEN_PREFIX + identifier.getSequenceNumber()); LOG.info("Removing RMDelegationToken_" + identifier.getSequenceNumber()); deleteFileWithRetries(nodeCreatePath); } @Override protected synchronized void updateRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { storeOrUpdateRMDelegationTokenState(rmDTIdentifier, renewDate, true); } private void storeOrUpdateRMDelegationTokenState( RMDelegationTokenIdentifier identifier, Long renewDate, boolean isUpdate) throws Exception { Path nodeCreatePath = getNodePath(rmDTSecretManagerRoot, DELEGATION_TOKEN_PREFIX + identifier.getSequenceNumber()); RMDelegationTokenIdentifierData identifierData = new RMDelegationTokenIdentifierData(identifier, renewDate); if (isUpdate) { LOG.info("Updating RMDelegationToken_" + identifier.getSequenceNumber()); updateFile(nodeCreatePath, identifierData.toByteArray(), true); } else { LOG.info("Storing RMDelegationToken_" + identifier.getSequenceNumber()); writeFileWithRetries(nodeCreatePath, identifierData.toByteArray(), true); // store sequence number Path latestSequenceNumberPath = getNodePath(rmDTSecretManagerRoot, DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX + identifier.getSequenceNumber()); LOG.info("Storing " + DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX + identifier.getSequenceNumber()); if (dtSequenceNumberPath == null) { if (!createFileWithRetries(latestSequenceNumberPath)) { throw new Exception("Failed to create " + latestSequenceNumberPath); } } else { if (!renameFileWithRetries(dtSequenceNumberPath, latestSequenceNumberPath)) { throw new Exception("Failed to rename " + dtSequenceNumberPath); } } dtSequenceNumberPath = latestSequenceNumberPath; } } @Override public synchronized void storeRMDTMasterKeyState(DelegationKey masterKey) throws Exception { Path nodeCreatePath = getNodePath(rmDTSecretManagerRoot, DELEGATION_KEY_PREFIX + masterKey.getKeyId()); ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream fsOut = new DataOutputStream(os)) { LOG.info("Storing RMDelegationKey_" + masterKey.getKeyId()); masterKey.write(fsOut); writeFileWithRetries(nodeCreatePath, os.toByteArray(), true); } } @Override public synchronized void removeRMDTMasterKeyState(DelegationKey masterKey) throws Exception { Path nodeCreatePath = getNodePath(rmDTSecretManagerRoot, DELEGATION_KEY_PREFIX + masterKey.getKeyId()); LOG.info("Removing RMDelegationKey_"+ masterKey.getKeyId()); deleteFileWithRetries(nodeCreatePath); } @Override public synchronized void deleteStore() throws Exception { if (existsWithRetries(rootDirPath)) { deleteFileWithRetries(rootDirPath); } } @Override public synchronized void removeApplication(ApplicationId removeAppId) throws Exception { Path nodeRemovePath = getAppDir(rmAppRoot, removeAppId); if (existsWithRetries(nodeRemovePath)) { deleteFileWithRetries(nodeRemovePath); } } private Path getAppDir(Path root, ApplicationId appId) { return getNodePath(root, appId.toString()); } @VisibleForTesting protected Path getAppDir(ApplicationId appId) { return getAppDir(rmAppRoot, appId); } @VisibleForTesting protected Path getAppAttemptDir(ApplicationAttemptId appAttId) { return getNodePath(getAppDir(appAttId.getApplicationId()), appAttId .toString()); } // FileSystem related code private boolean checkAndRemovePartialRecordWithRetries(final Path record) throws Exception { return new FSAction<Boolean>() { @Override public Boolean run() throws Exception { return checkAndRemovePartialRecord(record); } }.runWithRetries(); } private void mkdirsWithRetries(final Path appDirPath) throws Exception { new FSAction<Void>() { @Override public Void run() throws Exception { fs.mkdirs(appDirPath); return null; } }.runWithRetries(); } private void writeFileWithRetries(final Path outputPath, final byte[] data, final boolean makeUnreadableByAdmin) throws Exception { new FSAction<Void>() { @Override public Void run() throws Exception { writeFile(outputPath, data, makeUnreadableByAdmin); return null; } }.runWithRetries(); } private void deleteFileWithRetries(final Path deletePath) throws Exception { new FSAction<Void>() { @Override public Void run() throws Exception { deleteFile(deletePath); return null; } }.runWithRetries(); } private boolean renameFileWithRetries(final Path src, final Path dst) throws Exception { return new FSAction<Boolean>() { @Override public Boolean run() throws Exception { return renameFile(src, dst); } }.runWithRetries(); } private boolean createFileWithRetries(final Path newFile) throws Exception { return new FSAction<Boolean>() { @Override public Boolean run() throws Exception { return createFile(newFile); } }.runWithRetries(); } private FileStatus getFileStatusWithRetries(final Path path) throws Exception { return new FSAction<FileStatus>() { @Override public FileStatus run() throws Exception { return getFileStatus(path); } }.runWithRetries(); } private boolean existsWithRetries(final Path path) throws Exception { return new FSAction<Boolean>() { @Override public Boolean run() throws Exception { return fs.exists(path); } }.runWithRetries(); } private byte[] readFileWithRetries(final Path inputPath, final long len) throws Exception { return new FSAction<byte[]>() { @Override public byte[] run() throws Exception { return readFile(inputPath, len); } }.runWithRetries(); } private FileStatus[] listStatusWithRetries(final Path path) throws Exception { return new FSAction<FileStatus[]>() { @Override public FileStatus[] run() throws Exception { return fs.listStatus(path); } }.runWithRetries(); } private FileStatus[] listStatusWithRetries(final Path path, final PathFilter filter) throws Exception { return new FSAction<FileStatus[]>() { @Override public FileStatus[] run() throws Exception { return fs.listStatus(path, filter); } }.runWithRetries(); } private void closeWithRetries() throws Exception { new FSAction<Void>() { @Override public Void run() throws Exception { fs.close(); return null; } }.runWithRetries(); } private abstract class FSAction<T> { abstract T run() throws Exception; T runWithRetries() throws Exception { int retry = 0; while (true) { try { return run(); } catch (IOException e) { LOG.info("Exception while executing a FS operation.", e); if (++retry > fsNumRetries) { LOG.info("Maxed out FS retries. Giving up!"); throw e; } LOG.info("Retrying operation on FS. Retry no. " + retry); Thread.sleep(fsRetryInterval); } } } } private void deleteFile(Path deletePath) throws Exception { if(!fs.delete(deletePath, true)) { throw new Exception("Failed to delete " + deletePath); } } private byte[] readFile(Path inputPath, long len) throws Exception { FSDataInputStream fsIn = null; try { fsIn = fs.open(inputPath); // state data will not be that "long" byte[] data = new byte[(int) len]; fsIn.readFully(data); return data; } finally { IOUtils.cleanup(LOG, fsIn); } } private FileStatus getFileStatus(Path path) throws Exception { try { return fs.getFileStatus(path); } catch (FileNotFoundException e) { return null; } } /* * In order to make this write atomic as a part of write we will first write * data to .tmp file and then rename it. Here we are assuming that rename is * atomic for underlying file system. */ protected void writeFile(Path outputPath, byte[] data, boolean makeUnradableByAdmin) throws Exception { Path tempPath = new Path(outputPath.getParent(), outputPath.getName() + ".tmp"); FSDataOutputStream fsOut = null; // This file will be overwritten when app/attempt finishes for saving the // final status. try { fsOut = fs.create(tempPath, true); if (makeUnradableByAdmin) { setUnreadableBySuperuserXattrib(tempPath); } fsOut.write(data); fsOut.close(); fsOut = null; fs.rename(tempPath, outputPath); } finally { IOUtils.cleanup(LOG, fsOut); } } /* * In order to make this update atomic as a part of write we will first write * data to .new file and then rename it. Here we are assuming that rename is * atomic for underlying file system. */ protected void updateFile(Path outputPath, byte[] data, boolean makeUnradableByAdmin) throws Exception { Path newPath = new Path(outputPath.getParent(), outputPath.getName() + ".new"); // use writeFileWithRetries to make sure .new file is created atomically writeFileWithRetries(newPath, data, makeUnradableByAdmin); replaceFile(newPath, outputPath); } protected void replaceFile(Path srcPath, Path dstPath) throws Exception { if (existsWithRetries(dstPath)) { deleteFileWithRetries(dstPath); } else { LOG.info("File doesn't exist. Skip deleting the file " + dstPath); } renameFileWithRetries(srcPath, dstPath); } @Private @VisibleForTesting boolean renameFile(Path src, Path dst) throws Exception { return fs.rename(src, dst); } private boolean createFile(Path newFile) throws Exception { return fs.createNewFile(newFile); } @Private @VisibleForTesting Path getNodePath(Path root, String nodeName) { return new Path(root, nodeName); } @Override public synchronized void storeOrUpdateAMRMTokenSecretManagerState( AMRMTokenSecretManagerState amrmTokenSecretManagerState, boolean isUpdate) throws Exception { Path nodeCreatePath = getNodePath(amrmTokenSecretManagerRoot, AMRMTOKEN_SECRET_MANAGER_NODE); AMRMTokenSecretManagerState data = AMRMTokenSecretManagerState.newInstance(amrmTokenSecretManagerState); byte[] stateData = data.getProto().toByteArray(); if (isUpdate) { updateFile(nodeCreatePath, stateData, true); } else { writeFileWithRetries(nodeCreatePath, stateData, true); } } @Override protected void storeReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { Path planCreatePath = getNodePath(reservationRoot, planName); mkdirsWithRetries(planCreatePath); Path reservationPath = getNodePath(planCreatePath, reservationIdName); LOG.info("Storing state for reservation " + reservationIdName + " from " + "plan " + planName + " at path " + reservationPath); byte[] reservationData = reservationAllocation.toByteArray(); writeFileWithRetries(reservationPath, reservationData, true); } @Override protected void updateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { Path planCreatePath = getNodePath(reservationRoot, planName); Path reservationPath = getNodePath(planCreatePath, reservationIdName); LOG.info("Updating state for reservation " + reservationIdName + " from " + "plan " + planName + " at path " + reservationPath); byte[] reservationData = reservationAllocation.toByteArray(); updateFile(reservationPath, reservationData, true); } @Override protected void removeReservationState( String planName, String reservationIdName) throws Exception { Path planCreatePath = getNodePath(reservationRoot, planName); Path reservationPath = getNodePath(planCreatePath, reservationIdName); LOG.info("Removing state for reservation " + reservationIdName + " from " + "plan " + planName + " at path " + reservationPath); deleteFileWithRetries(reservationPath); } @VisibleForTesting public int getNumRetries() { return fsNumRetries; } @VisibleForTesting public long getRetryInterval() { return fsRetryInterval; } private void setUnreadableBySuperuserXattrib(Path p) throws IOException { if (fs.getScheme().toLowerCase().contains("hdfs") && intermediateEncryptionEnabled && !fs.getXAttrs(p).containsKey(UNREADABLE_BY_SUPERUSER_XATTRIB)) { fs.setXAttr(p, UNREADABLE_BY_SUPERUSER_XATTRIB, null, EnumSet.of(XAttrSetFlag.CREATE)); } } private static class ReservationStateFileProcessor implements RMStateFileProcessor { private RMState rmState; public ReservationStateFileProcessor(RMState state) { this.rmState = state; } @Override public void processChildNode(String planName, String childNodeName, byte[] childData) throws IOException { ReservationAllocationStateProto allocationState = ReservationAllocationStateProto.parseFrom(childData); if (!rmState.getReservationState().containsKey(planName)) { rmState.getReservationState().put(planName, new HashMap<ReservationId, ReservationAllocationStateProto>()); } ReservationId reservationId = ReservationId.parseReservationId(childNodeName); rmState.getReservationState().get(planName).put(reservationId, allocationState); } } private static class RMAppStateFileProcessor implements RMStateFileProcessor { private RMState rmState; private List<ApplicationAttemptStateData> attempts; public RMAppStateFileProcessor(RMState rmState, List<ApplicationAttemptStateData> attempts) { this.rmState = rmState; this.attempts = attempts; } @Override public void processChildNode(String appDirName, String childNodeName, byte[] childData) throws com.google.protobuf.InvalidProtocolBufferException { if (childNodeName.startsWith(ApplicationId.appIdStrPrefix)) { // application if (LOG.isDebugEnabled()) { LOG.debug("Loading application from node: " + childNodeName); } ApplicationStateDataPBImpl appState = new ApplicationStateDataPBImpl( ApplicationStateDataProto.parseFrom(childData)); ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); rmState.appState.put(appId, appState); } else if (childNodeName.startsWith( ApplicationAttemptId.appAttemptIdStrPrefix)) { // attempt if (LOG.isDebugEnabled()) { LOG.debug("Loading application attempt from node: " + childNodeName); } ApplicationAttemptStateDataPBImpl attemptState = new ApplicationAttemptStateDataPBImpl( ApplicationAttemptStateDataProto.parseFrom(childData)); attempts.add(attemptState); } else { LOG.info("Unknown child node with name: " + childNodeName); } } } // Interface for common state processing of directory of file layout private interface RMStateFileProcessor { void processChildNode(String appDirName, String childNodeName, byte[] childData) throws IOException; } }
37,008
36.72579
112
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRemoveAppEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; public class RMStateStoreRemoveAppEvent extends RMStateStoreEvent { ApplicationStateData appState; RMStateStoreRemoveAppEvent(ApplicationStateData appState) { super(RMStateStoreEventType.REMOVE_APP); this.appState = appState; } public ApplicationStateData getAppState() { return appState; } }
1,287
35.8
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRMDTMasterKeyEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.security.token.delegation.DelegationKey; public class RMStateStoreRMDTMasterKeyEvent extends RMStateStoreEvent { private DelegationKey delegationKey; public RMStateStoreRMDTMasterKeyEvent(RMStateStoreEventType type) { super(type); } public RMStateStoreRMDTMasterKeyEvent(DelegationKey delegationKey, RMStateStoreEventType type) { this(type); this.delegationKey = delegationKey; } public DelegationKey getDelegationKey() { return delegationKey; } }
1,386
33.675
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; @Unstable public class NullRMStateStore extends RMStateStore { @Override protected void initInternal(Configuration conf) throws Exception { // Do nothing } @Override protected void startInternal() throws Exception { // Do nothing } @Override protected void closeInternal() throws Exception { // Do nothing } @Override public synchronized long getAndIncrementEpoch() throws Exception { return 0L; } @Override public RMState loadState() throws Exception { throw new UnsupportedOperationException("Cannot load state from null store"); } @Override protected void storeApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws Exception { // Do nothing } @Override protected void storeApplicationAttemptStateInternal(ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception { // Do nothing } @Override protected void removeApplicationStateInternal(ApplicationStateData appState) throws Exception { // Do nothing } @Override public void storeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { // Do nothing } @Override public void removeRMDelegationTokenState(RMDelegationTokenIdentifier rmDTIdentifier) throws Exception { // Do nothing } @Override protected void updateRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { // Do nothing } @Override public void storeRMDTMasterKeyState(DelegationKey delegationKey) throws Exception { // Do nothing } @Override protected void storeReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { // Do nothing } @Override protected void removeReservationState(String planName, String reservationIdName) throws Exception { // Do nothing } @Override protected void updateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { // Do nothing } @Override public void removeRMDTMasterKeyState(DelegationKey delegationKey) throws Exception { // Do nothing } @Override protected void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws Exception { // Do nothing } @Override protected void updateApplicationAttemptStateInternal(ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception { } @Override public void checkVersion() throws Exception { // Do nothing } @Override protected Version loadVersion() throws Exception { // Do nothing return null; } @Override protected void storeVersion() throws Exception { // Do nothing } @Override protected Version getCurrentVersion() { // Do nothing return null; } @Override public void storeOrUpdateAMRMTokenSecretManagerState( AMRMTokenSecretManagerState state, boolean isUpdate) { //DO Nothing } @Override public void deleteStore() throws Exception { // Do nothing } @Override public void removeApplication(ApplicationId removeAppId) throws Exception { // Do nothing } }
5,133
27.208791
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreStoreReservationEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; /** * Event representing maintaining ReservationSystem state. */ public class RMStateStoreStoreReservationEvent extends RMStateStoreEvent { private ReservationAllocationStateProto reservationAllocation; private String planName; private String reservationIdName; public RMStateStoreStoreReservationEvent(RMStateStoreEventType type) { super(type); } public RMStateStoreStoreReservationEvent( ReservationAllocationStateProto reservationAllocationState, RMStateStoreEventType type, String planName, String reservationIdName) { this(type); this.reservationAllocation = reservationAllocationState; this.planName = planName; this.reservationIdName = reservationIdName; } public ReservationAllocationStateProto getReservationAllocation() { return reservationAllocation; } public String getPlanName() { return planName; } public String getReservationIdName() { return reservationIdName; } }
1,943
33.105263
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateUpdateAppEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; public class RMStateUpdateAppEvent extends RMStateStoreEvent { private final ApplicationStateData appState; public RMStateUpdateAppEvent(ApplicationStateData appState) { super(RMStateStoreEventType.UPDATE_APP); this.appState = appState; } public ApplicationStateData getAppState() { return appState; } }
1,278
35.542857
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateVersionIncompatibleException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.exceptions.YarnException; /** * This exception is thrown by ResourceManager if it's loading an incompatible * version of state from state store on recovery. */ public class RMStateVersionIncompatibleException extends YarnException { private static final long serialVersionUID = 1364408L; public RMStateVersionIncompatibleException(Throwable cause) { super(cause); } public RMStateVersionIncompatibleException(String message) { super(message); } public RMStateVersionIncompatibleException(String message, Throwable cause) { super(message, cause); } }
1,487
33.604651
79
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import static org.fusesource.leveldbjni.JniDBFactory.asString; import static org.fusesource.leveldbjni.JniDBFactory.bytes; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.proto.YarnServerCommonProtos.VersionProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.AMRMTokenSecretManagerStateProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.EpochProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationAttemptStateDataProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationStateDataProto; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.records.impl.pb.VersionPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.Epoch; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMDelegationTokenIdentifierData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.AMRMTokenSecretManagerStatePBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; import org.apache.hadoop.yarn.server.utils.LeveldbIterator; import org.apache.hadoop.yarn.util.ConverterUtils; import org.fusesource.leveldbjni.JniDBFactory; import org.fusesource.leveldbjni.internal.NativeDB; import org.iq80.leveldb.DB; import org.iq80.leveldb.DBException; import org.iq80.leveldb.Logger; import org.iq80.leveldb.Options; import org.iq80.leveldb.WriteBatch; import com.google.common.annotations.VisibleForTesting; /** * Changes from 1.0 to 1.1, Addition of ReservationSystem state. */ public class LeveldbRMStateStore extends RMStateStore { public static final Log LOG = LogFactory.getLog(LeveldbRMStateStore.class); private static final String SEPARATOR = "/"; private static final String DB_NAME = "yarn-rm-state"; private static final String RM_DT_MASTER_KEY_KEY_PREFIX = RM_DT_SECRET_MANAGER_ROOT + SEPARATOR + DELEGATION_KEY_PREFIX; private static final String RM_DT_TOKEN_KEY_PREFIX = RM_DT_SECRET_MANAGER_ROOT + SEPARATOR + DELEGATION_TOKEN_PREFIX; private static final String RM_DT_SEQUENCE_NUMBER_KEY = RM_DT_SECRET_MANAGER_ROOT + SEPARATOR + "RMDTSequentialNumber"; private static final String RM_APP_KEY_PREFIX = RM_APP_ROOT + SEPARATOR + ApplicationId.appIdStrPrefix; private static final String RM_RESERVATION_KEY_PREFIX = RESERVATION_SYSTEM_ROOT + SEPARATOR; private static final Version CURRENT_VERSION_INFO = Version .newInstance(1, 1); private DB db; private String getApplicationNodeKey(ApplicationId appId) { return RM_APP_ROOT + SEPARATOR + appId; } private String getApplicationAttemptNodeKey(ApplicationAttemptId attemptId) { return getApplicationAttemptNodeKey( getApplicationNodeKey(attemptId.getApplicationId()), attemptId); } private String getApplicationAttemptNodeKey(String appNodeKey, ApplicationAttemptId attemptId) { return appNodeKey + SEPARATOR + attemptId; } private String getRMDTMasterKeyNodeKey(DelegationKey masterKey) { return RM_DT_MASTER_KEY_KEY_PREFIX + masterKey.getKeyId(); } private String getRMDTTokenNodeKey(RMDelegationTokenIdentifier tokenId) { return RM_DT_TOKEN_KEY_PREFIX + tokenId.getSequenceNumber(); } private String getReservationNodeKey(String planName, String reservationId) { return RESERVATION_SYSTEM_ROOT + SEPARATOR + planName + SEPARATOR + reservationId; } @Override protected void initInternal(Configuration conf) throws Exception { } private Path getStorageDir() throws IOException { Configuration conf = getConfig(); String storePath = conf.get(YarnConfiguration.RM_LEVELDB_STORE_PATH); if (storePath == null) { throw new IOException("No store location directory configured in " + YarnConfiguration.RM_LEVELDB_STORE_PATH); } return new Path(storePath, DB_NAME); } private Path createStorageDir() throws IOException { Path root = getStorageDir(); FileSystem fs = FileSystem.getLocal(getConfig()); fs.mkdirs(root, new FsPermission((short)0700)); return root; } @Override protected void startInternal() throws Exception { Path storeRoot = createStorageDir(); Options options = new Options(); options.createIfMissing(false); options.logger(new LeveldbLogger()); LOG.info("Using state database at " + storeRoot + " for recovery"); File dbfile = new File(storeRoot.toString()); try { db = JniDBFactory.factory.open(dbfile, options); } catch (NativeDB.DBException e) { if (e.isNotFound() || e.getMessage().contains(" does not exist ")) { LOG.info("Creating state database at " + dbfile); options.createIfMissing(true); try { db = JniDBFactory.factory.open(dbfile, options); // store version storeVersion(); } catch (DBException dbErr) { throw new IOException(dbErr.getMessage(), dbErr); } } else { throw e; } } } @Override protected void closeInternal() throws Exception { if (db != null) { db.close(); db = null; } } @VisibleForTesting boolean isClosed() { return db == null; } @Override protected Version loadVersion() throws Exception { Version version = null; try { byte[] data = db.get(bytes(VERSION_NODE)); if (data != null) { version = new VersionPBImpl(VersionProto.parseFrom(data)); } } catch (DBException e) { throw new IOException(e); } return version; } @Override protected void storeVersion() throws Exception { dbStoreVersion(CURRENT_VERSION_INFO); } void dbStoreVersion(Version state) throws IOException { String key = VERSION_NODE; byte[] data = ((VersionPBImpl) state).getProto().toByteArray(); try { db.put(bytes(key), data); } catch (DBException e) { throw new IOException(e); } } @Override protected Version getCurrentVersion() { return CURRENT_VERSION_INFO; } @Override public synchronized long getAndIncrementEpoch() throws Exception { long currentEpoch = 0; byte[] dbKeyBytes = bytes(EPOCH_NODE); try { byte[] data = db.get(dbKeyBytes); if (data != null) { currentEpoch = EpochProto.parseFrom(data).getEpoch(); } EpochProto proto = Epoch.newInstance(currentEpoch + 1).getProto(); db.put(dbKeyBytes, proto.toByteArray()); } catch (DBException e) { throw new IOException(e); } return currentEpoch; } @Override public RMState loadState() throws Exception { RMState rmState = new RMState(); loadRMDTSecretManagerState(rmState); loadRMApps(rmState); loadAMRMTokenSecretManagerState(rmState); loadReservationState(rmState); return rmState; } private void loadReservationState(RMState rmState) throws IOException { int numReservations = 0; LeveldbIterator iter = null; try { iter = new LeveldbIterator(db); iter.seek(bytes(RM_RESERVATION_KEY_PREFIX)); while (iter.hasNext()) { Entry<byte[],byte[]> entry = iter.next(); String key = asString(entry.getKey()); String planReservationString = key.substring(RM_RESERVATION_KEY_PREFIX.length()); String[] parts = planReservationString.split(SEPARATOR); if (parts.length != 2) { LOG.warn("Incorrect reservation state key " + key); continue; } String planName = parts[0]; String reservationName = parts[1]; ReservationAllocationStateProto allocationState = ReservationAllocationStateProto.parseFrom(entry.getValue()); if (!rmState.getReservationState().containsKey(planName)) { rmState.getReservationState().put(planName, new HashMap<ReservationId, ReservationAllocationStateProto>()); } ReservationId reservationId = ReservationId.parseReservationId(reservationName); rmState.getReservationState().get(planName).put(reservationId, allocationState); numReservations++; } } catch (DBException e) { throw new IOException(e); } finally { if (iter != null) { iter.close(); } } LOG.info("Recovered " + numReservations + " reservations"); } private void loadRMDTSecretManagerState(RMState state) throws IOException { int numKeys = loadRMDTSecretManagerKeys(state); LOG.info("Recovered " + numKeys + " RM delegation token master keys"); int numTokens = loadRMDTSecretManagerTokens(state); LOG.info("Recovered " + numTokens + " RM delegation tokens"); loadRMDTSecretManagerTokenSequenceNumber(state); } private int loadRMDTSecretManagerKeys(RMState state) throws IOException { int numKeys = 0; LeveldbIterator iter = null; try { iter = new LeveldbIterator(db); iter.seek(bytes(RM_DT_MASTER_KEY_KEY_PREFIX)); while (iter.hasNext()) { Entry<byte[],byte[]> entry = iter.next(); String key = asString(entry.getKey()); if (!key.startsWith(RM_DT_MASTER_KEY_KEY_PREFIX)) { break; } DelegationKey masterKey = loadDelegationKey(entry.getValue()); state.rmSecretManagerState.masterKeyState.add(masterKey); ++numKeys; if (LOG.isDebugEnabled()) { LOG.debug("Loaded RM delegation key from " + key + ": keyId=" + masterKey.getKeyId() + ", expirationDate=" + masterKey.getExpiryDate()); } } } catch (DBException e) { throw new IOException(e); } finally { if (iter != null) { iter.close(); } } return numKeys; } private DelegationKey loadDelegationKey(byte[] data) throws IOException { DelegationKey key = new DelegationKey(); DataInputStream in = new DataInputStream(new ByteArrayInputStream(data)); try { key.readFields(in); } finally { IOUtils.cleanup(LOG, in); } return key; } private int loadRMDTSecretManagerTokens(RMState state) throws IOException { int numTokens = 0; LeveldbIterator iter = null; try { iter = new LeveldbIterator(db); iter.seek(bytes(RM_DT_TOKEN_KEY_PREFIX)); while (iter.hasNext()) { Entry<byte[],byte[]> entry = iter.next(); String key = asString(entry.getKey()); if (!key.startsWith(RM_DT_TOKEN_KEY_PREFIX)) { break; } RMDelegationTokenIdentifierData tokenData = loadDelegationToken( entry.getValue()); RMDelegationTokenIdentifier tokenId = tokenData.getTokenIdentifier(); long renewDate = tokenData.getRenewDate(); state.rmSecretManagerState.delegationTokenState.put(tokenId, renewDate); ++numTokens; if (LOG.isDebugEnabled()) { LOG.debug("Loaded RM delegation token from " + key + ": tokenId=" + tokenId + ", renewDate=" + renewDate); } } } catch (DBException e) { throw new IOException(e); } finally { if (iter != null) { iter.close(); } } return numTokens; } private RMDelegationTokenIdentifierData loadDelegationToken(byte[] data) throws IOException { RMDelegationTokenIdentifierData tokenData = new RMDelegationTokenIdentifierData(); DataInputStream in = new DataInputStream(new ByteArrayInputStream(data)); try { tokenData.readFields(in); } finally { IOUtils.cleanup(LOG, in); } return tokenData; } private void loadRMDTSecretManagerTokenSequenceNumber(RMState state) throws IOException { byte[] data = null; try { data = db.get(bytes(RM_DT_SEQUENCE_NUMBER_KEY)); } catch (DBException e) { throw new IOException(e); } if (data != null) { DataInputStream in = new DataInputStream(new ByteArrayInputStream(data)); try { state.rmSecretManagerState.dtSequenceNumber = in.readInt(); } finally { IOUtils.cleanup(LOG, in); } } } private void loadRMApps(RMState state) throws IOException { int numApps = 0; int numAppAttempts = 0; LeveldbIterator iter = null; try { iter = new LeveldbIterator(db); iter.seek(bytes(RM_APP_KEY_PREFIX)); while (iter.hasNext()) { Entry<byte[],byte[]> entry = iter.next(); String key = asString(entry.getKey()); if (!key.startsWith(RM_APP_KEY_PREFIX)) { break; } String appIdStr = key.substring(RM_APP_ROOT.length() + 1); if (appIdStr.contains(SEPARATOR)) { LOG.warn("Skipping extraneous data " + key); continue; } numAppAttempts += loadRMApp(state, iter, appIdStr, entry.getValue()); ++numApps; } } catch (DBException e) { throw new IOException(e); } finally { if (iter != null) { iter.close(); } } LOG.info("Recovered " + numApps + " applications and " + numAppAttempts + " application attempts"); } private int loadRMApp(RMState rmState, LeveldbIterator iter, String appIdStr, byte[] appData) throws IOException { ApplicationStateData appState = createApplicationState(appIdStr, appData); ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); rmState.appState.put(appId, appState); String attemptNodePrefix = getApplicationNodeKey(appId) + SEPARATOR; while (iter.hasNext()) { Entry<byte[],byte[]> entry = iter.peekNext(); String key = asString(entry.getKey()); if (!key.startsWith(attemptNodePrefix)) { break; } String attemptId = key.substring(attemptNodePrefix.length()); if (attemptId.startsWith(ApplicationAttemptId.appAttemptIdStrPrefix)) { ApplicationAttemptStateData attemptState = createAttemptState(attemptId, entry.getValue()); appState.attempts.put(attemptState.getAttemptId(), attemptState); } else { LOG.warn("Ignoring unknown application key: " + key); } iter.next(); } int numAttempts = appState.attempts.size(); if (LOG.isDebugEnabled()) { LOG.debug("Loaded application " + appId + " with " + numAttempts + " attempts"); } return numAttempts; } private ApplicationStateData createApplicationState(String appIdStr, byte[] data) throws IOException { ApplicationId appId = ConverterUtils.toApplicationId(appIdStr); ApplicationStateDataPBImpl appState = new ApplicationStateDataPBImpl( ApplicationStateDataProto.parseFrom(data)); if (!appId.equals( appState.getApplicationSubmissionContext().getApplicationId())) { throw new YarnRuntimeException("The database entry for " + appId + " contains data for " + appState.getApplicationSubmissionContext().getApplicationId()); } return appState; } @VisibleForTesting ApplicationStateData loadRMAppState(ApplicationId appId) throws IOException { String appKey = getApplicationNodeKey(appId); byte[] data = null; try { data = db.get(bytes(appKey)); } catch (DBException e) { throw new IOException(e); } if (data == null) { return null; } return createApplicationState(appId.toString(), data); } private ApplicationAttemptStateData createAttemptState(String itemName, byte[] data) throws IOException { ApplicationAttemptId attemptId = ConverterUtils.toApplicationAttemptId(itemName); ApplicationAttemptStateDataPBImpl attemptState = new ApplicationAttemptStateDataPBImpl( ApplicationAttemptStateDataProto.parseFrom(data)); if (!attemptId.equals(attemptState.getAttemptId())) { throw new YarnRuntimeException("The database entry for " + attemptId + " contains data for " + attemptState.getAttemptId()); } return attemptState; } private void loadAMRMTokenSecretManagerState(RMState rmState) throws IOException { try { byte[] data = db.get(bytes(AMRMTOKEN_SECRET_MANAGER_ROOT)); if (data != null) { AMRMTokenSecretManagerStatePBImpl stateData = new AMRMTokenSecretManagerStatePBImpl( AMRMTokenSecretManagerStateProto.parseFrom(data)); rmState.amrmTokenSecretManagerState = AMRMTokenSecretManagerState.newInstance( stateData.getCurrentMasterKey(), stateData.getNextMasterKey()); } } catch (DBException e) { throw new IOException(e); } } @Override protected void storeApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws IOException { String key = getApplicationNodeKey(appId); if (LOG.isDebugEnabled()) { LOG.debug("Storing state for app " + appId + " at " + key); } try { db.put(bytes(key), appStateData.getProto().toByteArray()); } catch (DBException e) { throw new IOException(e); } } @Override protected void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws IOException { storeApplicationStateInternal(appId, appStateData); } @Override protected void storeApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws IOException { String key = getApplicationAttemptNodeKey(attemptId); if (LOG.isDebugEnabled()) { LOG.debug("Storing state for attempt " + attemptId + " at " + key); } try { db.put(bytes(key), attemptStateData.getProto().toByteArray()); } catch (DBException e) { throw new IOException(e); } } @Override protected void updateApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws IOException { storeApplicationAttemptStateInternal(attemptId, attemptStateData); } @Override protected void removeApplicationStateInternal(ApplicationStateData appState) throws IOException { ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); String appKey = getApplicationNodeKey(appId); try { WriteBatch batch = db.createWriteBatch(); try { batch.delete(bytes(appKey)); for (ApplicationAttemptId attemptId : appState.attempts.keySet()) { String attemptKey = getApplicationAttemptNodeKey(appKey, attemptId); batch.delete(bytes(attemptKey)); } if (LOG.isDebugEnabled()) { LOG.debug("Removing state for app " + appId + " and " + appState.attempts.size() + " attempts" + " at " + appKey); } db.write(batch); } finally { batch.close(); } } catch (DBException e) { throw new IOException(e); } } @Override protected void storeReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { try { WriteBatch batch = db.createWriteBatch(); try { String key = getReservationNodeKey(planName, reservationIdName); if (LOG.isDebugEnabled()) { LOG.debug("Storing state for reservation " + reservationIdName + " plan " + planName + " at " + key); } batch.put(bytes(key), reservationAllocation.toByteArray()); db.write(batch); } finally { batch.close(); } } catch (DBException e) { throw new IOException(e); } } @Override protected void updateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { storeReservationState(reservationAllocation, planName, reservationIdName); } @Override protected void removeReservationState(String planName, String reservationIdName) throws Exception { try { WriteBatch batch = db.createWriteBatch(); try { String reservationKey = getReservationNodeKey(planName, reservationIdName); batch.delete(bytes(reservationKey)); if (LOG.isDebugEnabled()) { LOG.debug("Removing state for reservation " + reservationIdName + " plan " + planName + " at " + reservationKey); } db.write(batch); } finally { batch.close(); } } catch (DBException e) { throw new IOException(e); } } private void storeOrUpdateRMDT(RMDelegationTokenIdentifier tokenId, Long renewDate, boolean isUpdate) throws IOException { String tokenKey = getRMDTTokenNodeKey(tokenId); RMDelegationTokenIdentifierData tokenData = new RMDelegationTokenIdentifierData(tokenId, renewDate); if (LOG.isDebugEnabled()) { LOG.debug("Storing token to " + tokenKey); } try { WriteBatch batch = db.createWriteBatch(); try { batch.put(bytes(tokenKey), tokenData.toByteArray()); if(!isUpdate) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); try (DataOutputStream ds = new DataOutputStream(bs)) { ds.writeInt(tokenId.getSequenceNumber()); } if (LOG.isDebugEnabled()) { LOG.debug("Storing " + tokenId.getSequenceNumber() + " to " + RM_DT_SEQUENCE_NUMBER_KEY); } batch.put(bytes(RM_DT_SEQUENCE_NUMBER_KEY), bs.toByteArray()); } db.write(batch); } finally { batch.close(); } } catch (DBException e) { throw new IOException(e); } } @Override protected void storeRMDelegationTokenState( RMDelegationTokenIdentifier tokenId, Long renewDate) throws IOException { storeOrUpdateRMDT(tokenId, renewDate, false); } @Override protected void updateRMDelegationTokenState( RMDelegationTokenIdentifier tokenId, Long renewDate) throws IOException { storeOrUpdateRMDT(tokenId, renewDate, true); } @Override protected void removeRMDelegationTokenState( RMDelegationTokenIdentifier tokenId) throws IOException { String tokenKey = getRMDTTokenNodeKey(tokenId); if (LOG.isDebugEnabled()) { LOG.debug("Removing token at " + tokenKey); } try { db.delete(bytes(tokenKey)); } catch (DBException e) { throw new IOException(e); } } @Override protected void storeRMDTMasterKeyState(DelegationKey masterKey) throws IOException { String dbKey = getRMDTMasterKeyNodeKey(masterKey); if (LOG.isDebugEnabled()) { LOG.debug("Storing token master key to " + dbKey); } ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(os); try { masterKey.write(out); } finally { out.close(); } try { db.put(bytes(dbKey), os.toByteArray()); } catch (DBException e) { throw new IOException(e); } } @Override protected void removeRMDTMasterKeyState(DelegationKey masterKey) throws IOException { String dbKey = getRMDTMasterKeyNodeKey(masterKey); if (LOG.isDebugEnabled()) { LOG.debug("Removing token master key at " + dbKey); } try { db.delete(bytes(dbKey)); } catch (DBException e) { throw new IOException(e); } } @Override public void storeOrUpdateAMRMTokenSecretManagerState( AMRMTokenSecretManagerState state, boolean isUpdate) { AMRMTokenSecretManagerState data = AMRMTokenSecretManagerState.newInstance(state); byte[] stateData = data.getProto().toByteArray(); db.put(bytes(AMRMTOKEN_SECRET_MANAGER_ROOT), stateData); } @Override public void deleteStore() throws IOException { Path root = getStorageDir(); LOG.info("Deleting state database at " + root); db.close(); db = null; FileSystem fs = FileSystem.getLocal(getConfig()); fs.delete(root, true); } @Override public synchronized void removeApplication(ApplicationId removeAppId) throws IOException { String appKey = getApplicationNodeKey(removeAppId); LOG.info("Removing state for app " + removeAppId); try { db.delete(bytes(appKey)); } catch (DBException e) { throw new IOException(e); } } @VisibleForTesting int getNumEntriesInDatabase() throws IOException { int numEntries = 0; LeveldbIterator iter = null; try { iter = new LeveldbIterator(db); iter.seekToFirst(); while (iter.hasNext()) { Entry<byte[], byte[]> entry = iter.next(); LOG.info("entry: " + asString(entry.getKey())); ++numEntries; } } catch (DBException e) { throw new IOException(e); } finally { if (iter != null) { iter.close(); } } return numEntries; } private static class LeveldbLogger implements Logger { private static final Log LOG = LogFactory.getLog(LeveldbLogger.class); @Override public void log(String message) { LOG.info(message); } } }
27,598
32.947109
112
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import com.google.common.annotations.VisibleForTesting; @Private @Unstable public class MemoryRMStateStore extends RMStateStore { RMState state = new RMState(); private long epoch = 0L; @VisibleForTesting public RMState getState() { return state; } @Override public void checkVersion() throws Exception { } @Override public synchronized long getAndIncrementEpoch() throws Exception { long currentEpoch = epoch; epoch = epoch + 1; return currentEpoch; } @Override public synchronized RMState loadState() throws Exception { // return a copy of the state to allow for modification of the real state RMState returnState = new RMState(); returnState.appState.putAll(state.appState); returnState.rmSecretManagerState.getMasterKeyState() .addAll(state.rmSecretManagerState.getMasterKeyState()); returnState.rmSecretManagerState.getTokenState().putAll( state.rmSecretManagerState.getTokenState()); returnState.rmSecretManagerState.dtSequenceNumber = state.rmSecretManagerState.dtSequenceNumber; returnState.amrmTokenSecretManagerState = state.amrmTokenSecretManagerState == null ? null : AMRMTokenSecretManagerState .newInstance(state.amrmTokenSecretManagerState); return returnState; } @Override public synchronized void initInternal(Configuration conf) { } @Override protected synchronized void startInternal() throws Exception { } @Override protected synchronized void closeInternal() throws Exception { } @Override public synchronized void storeApplicationStateInternal( ApplicationId appId, ApplicationStateData appState) throws Exception { state.appState.put(appId, appState); } @Override public synchronized void updateApplicationStateInternal( ApplicationId appId, ApplicationStateData appState) throws Exception { LOG.info("Updating final state " + appState.getState() + " for app: " + appId); if (state.appState.get(appId) != null) { // add the earlier attempts back appState.attempts.putAll(state.appState.get(appId).attempts); } state.appState.put(appId, appState); } @Override public synchronized void storeApplicationAttemptStateInternal( ApplicationAttemptId appAttemptId, ApplicationAttemptStateData attemptState) throws Exception { ApplicationStateData appState = state.getApplicationState().get( attemptState.getAttemptId().getApplicationId()); if (appState == null) { throw new YarnRuntimeException("Application doesn't exist"); } appState.attempts.put(attemptState.getAttemptId(), attemptState); } @Override public synchronized void updateApplicationAttemptStateInternal( ApplicationAttemptId appAttemptId, ApplicationAttemptStateData attemptState) throws Exception { ApplicationStateData appState = state.getApplicationState().get(appAttemptId.getApplicationId()); if (appState == null) { throw new YarnRuntimeException("Application doesn't exist"); } LOG.info("Updating final state " + attemptState.getState() + " for attempt: " + attemptState.getAttemptId()); appState.attempts.put(attemptState.getAttemptId(), attemptState); } @Override public synchronized void removeApplicationStateInternal( ApplicationStateData appState) throws Exception { ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); ApplicationStateData removed = state.appState.remove(appId); if (removed == null) { throw new YarnRuntimeException("Removing non-exsisting application state"); } } private void storeOrUpdateRMDT(RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, boolean isUpdate) throws Exception { Map<RMDelegationTokenIdentifier, Long> rmDTState = state.rmSecretManagerState.getTokenState(); if (rmDTState.containsKey(rmDTIdentifier)) { IOException e = new IOException("RMDelegationToken: " + rmDTIdentifier + "is already stored."); LOG.info("Error storing info for RMDelegationToken: " + rmDTIdentifier, e); throw e; } rmDTState.put(rmDTIdentifier, renewDate); if(!isUpdate) { state.rmSecretManagerState.dtSequenceNumber = rmDTIdentifier.getSequenceNumber(); } LOG.info("Store RMDT with sequence number " + rmDTIdentifier.getSequenceNumber()); } @Override public synchronized void storeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { storeOrUpdateRMDT(rmDTIdentifier, renewDate, false); } @Override public synchronized void removeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier) throws Exception{ Map<RMDelegationTokenIdentifier, Long> rmDTState = state.rmSecretManagerState.getTokenState(); rmDTState.remove(rmDTIdentifier); LOG.info("Remove RMDT with sequence number " + rmDTIdentifier.getSequenceNumber()); } @Override protected synchronized void updateRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception { removeRMDelegationTokenState(rmDTIdentifier); storeOrUpdateRMDT(rmDTIdentifier, renewDate, true); LOG.info("Update RMDT with sequence number " + rmDTIdentifier.getSequenceNumber()); } @Override public synchronized void storeRMDTMasterKeyState(DelegationKey delegationKey) throws Exception { Set<DelegationKey> rmDTMasterKeyState = state.rmSecretManagerState.getMasterKeyState(); if (rmDTMasterKeyState.contains(delegationKey)) { IOException e = new IOException("RMDTMasterKey with keyID: " + delegationKey.getKeyId() + " is already stored"); LOG.info("Error storing info for RMDTMasterKey with keyID: " + delegationKey.getKeyId(), e); throw e; } state.getRMDTSecretManagerState().getMasterKeyState().add(delegationKey); LOG.info("Store RMDT master key with key id: " + delegationKey.getKeyId() + ". Currently rmDTMasterKeyState size: " + rmDTMasterKeyState.size()); } @Override public synchronized void removeRMDTMasterKeyState(DelegationKey delegationKey) throws Exception { LOG.info("Remove RMDT master key with key id: " + delegationKey.getKeyId()); Set<DelegationKey> rmDTMasterKeyState = state.rmSecretManagerState.getMasterKeyState(); rmDTMasterKeyState.remove(delegationKey); } @Override protected synchronized void storeReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { LOG.info("Storing reservationallocation for " + reservationIdName + " " + "for plan " + planName); Map<ReservationId, ReservationAllocationStateProto> planState = state.getReservationState().get(planName); if (planState == null) { planState = new HashMap<>(); state.getReservationState().put(planName, planState); } ReservationId reservationId = ReservationId.parseReservationId(reservationIdName); planState.put(reservationId, reservationAllocation); } @Override protected synchronized void updateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception { LOG.info("Updating reservationallocation for " + reservationIdName + " " + "for plan " + planName); Map<ReservationId, ReservationAllocationStateProto> planState = state.getReservationState().get(planName); if (planState == null) { throw new YarnRuntimeException("State for plan " + planName + " does " + "not exist"); } ReservationId reservationId = ReservationId.parseReservationId(reservationIdName); planState.put(reservationId, reservationAllocation); } @Override protected synchronized void removeReservationState( String planName, String reservationIdName) throws Exception { LOG.info("Removing reservationallocation " + reservationIdName + " for plan " + planName); Map<ReservationId, ReservationAllocationStateProto> planState = state.getReservationState().get(planName); if (planState == null) { throw new YarnRuntimeException("State for plan " + planName + " does " + "not exist"); } ReservationId reservationId = ReservationId.parseReservationId(reservationIdName); planState.remove(reservationId); if (planState.isEmpty()) { state.getReservationState().remove(planName); } } @Override protected Version loadVersion() throws Exception { return null; } @Override protected void storeVersion() throws Exception { } @Override protected Version getCurrentVersion() { return null; } @Override public synchronized void storeOrUpdateAMRMTokenSecretManagerState( AMRMTokenSecretManagerState amrmTokenSecretManagerState, boolean isUpdate) { if (amrmTokenSecretManagerState != null) { state.amrmTokenSecretManagerState = AMRMTokenSecretManagerState .newInstance(amrmTokenSecretManagerState); } } @Override public void deleteStore() throws Exception { } @Override public void removeApplication(ApplicationId removeAppId) throws Exception { } }
11,499
35.392405
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreRMDTEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; public class RMStateStoreRMDTEvent extends RMStateStoreEvent { private RMDelegationTokenIdentifier rmDTIdentifier; private Long renewDate; public RMStateStoreRMDTEvent(RMStateStoreEventType type) { super(type); } public RMStateStoreRMDTEvent(RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate, RMStateStoreEventType type) { this(type); this.rmDTIdentifier = rmDTIdentifier; this.renewDate = renewDate; } public RMDelegationTokenIdentifier getRmDTIdentifier() { return rmDTIdentifier; } public Long getRenewDate() { return renewDate; } }
1,547
33.4
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.event.AbstractEvent; public class RMStateStoreEvent extends AbstractEvent<RMStateStoreEventType> { public RMStateStoreEvent(RMStateStoreEventType type) { super(type); } }
1,082
39.111111
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateUpdateAppAttemptEvent.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; public class RMStateUpdateAppAttemptEvent extends RMStateStoreEvent { ApplicationAttemptStateData attemptState; public RMStateUpdateAppAttemptEvent( ApplicationAttemptStateData attemptState) { super(RMStateStoreEventType.UPDATE_APP_ATTEMPT); this.attemptState = attemptState; } public ApplicationAttemptStateData getAppAttemptState() { return attemptState; } }
1,350
35.513514
98
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import javax.crypto.SecretKey; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.resourcemanager.RMFatalEvent; import org.apache.hadoop.yarn.server.resourcemanager.RMFatalEventType; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AggregateAppResourceUsage; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType; import org.apache.hadoop.yarn.state.InvalidStateTransitionException; import org.apache.hadoop.yarn.state.SingleArcTransition; import org.apache.hadoop.yarn.state.StateMachine; import org.apache.hadoop.yarn.state.StateMachineFactory; @Private @Unstable /** * Base class to implement storage of ResourceManager state. * Takes care of asynchronous notifications and interfacing with YARN objects. * Real store implementations need to derive from it and implement blocking * store and load methods to actually store and load the state. */ public abstract class RMStateStore extends AbstractService { // constants for RM App state and RMDTSecretManagerState. protected static final String RM_APP_ROOT = "RMAppRoot"; protected static final String RM_DT_SECRET_MANAGER_ROOT = "RMDTSecretManagerRoot"; protected static final String DELEGATION_KEY_PREFIX = "DelegationKey_"; protected static final String DELEGATION_TOKEN_PREFIX = "RMDelegationToken_"; protected static final String DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX = "RMDTSequenceNumber_"; protected static final String AMRMTOKEN_SECRET_MANAGER_ROOT = "AMRMTokenSecretManagerRoot"; protected static final String RESERVATION_SYSTEM_ROOT = "ReservationSystemRoot"; protected static final String VERSION_NODE = "RMVersionNode"; protected static final String EPOCH_NODE = "EpochNode"; private ResourceManager resourceManager; private final ReadLock readLock; private final WriteLock writeLock; public static final Log LOG = LogFactory.getLog(RMStateStore.class); private enum RMStateStoreState { ACTIVE, FENCED }; private static final StateMachineFactory<RMStateStore, RMStateStoreState, RMStateStoreEventType, RMStateStoreEvent> stateMachineFactory = new StateMachineFactory<RMStateStore, RMStateStoreState, RMStateStoreEventType, RMStateStoreEvent>( RMStateStoreState.ACTIVE) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.STORE_APP, new StoreAppTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.UPDATE_APP, new UpdateAppTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.REMOVE_APP, new RemoveAppTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.STORE_APP_ATTEMPT, new StoreAppAttemptTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.UPDATE_APP_ATTEMPT, new UpdateAppAttemptTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.STORE_MASTERKEY, new StoreRMDTMasterKeyTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.REMOVE_MASTERKEY, new RemoveRMDTMasterKeyTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.STORE_DELEGATION_TOKEN, new StoreRMDTTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.REMOVE_DELEGATION_TOKEN, new RemoveRMDTTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.UPDATE_DELEGATION_TOKEN, new UpdateRMDTTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.UPDATE_AMRM_TOKEN, new StoreOrUpdateAMRMTokenTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.STORE_RESERVATION, new StoreReservationAllocationTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.UPDATE_RESERVATION, new UpdateReservationAllocationTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.ACTIVE, RMStateStoreEventType.REMOVE_RESERVATION, new RemoveReservationAllocationTransition()) .addTransition(RMStateStoreState.ACTIVE, RMStateStoreState.FENCED, RMStateStoreEventType.FENCED) .addTransition(RMStateStoreState.FENCED, RMStateStoreState.FENCED, EnumSet.of( RMStateStoreEventType.STORE_APP, RMStateStoreEventType.UPDATE_APP, RMStateStoreEventType.REMOVE_APP, RMStateStoreEventType.STORE_APP_ATTEMPT, RMStateStoreEventType.UPDATE_APP_ATTEMPT, RMStateStoreEventType.FENCED, RMStateStoreEventType.STORE_MASTERKEY, RMStateStoreEventType.REMOVE_MASTERKEY, RMStateStoreEventType.STORE_DELEGATION_TOKEN, RMStateStoreEventType.REMOVE_DELEGATION_TOKEN, RMStateStoreEventType.UPDATE_DELEGATION_TOKEN, RMStateStoreEventType.UPDATE_AMRM_TOKEN, RMStateStoreEventType.STORE_RESERVATION, RMStateStoreEventType.UPDATE_RESERVATION, RMStateStoreEventType.REMOVE_RESERVATION)); private final StateMachine<RMStateStoreState, RMStateStoreEventType, RMStateStoreEvent> stateMachine; private static class StoreAppTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreAppEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } ApplicationStateData appState = ((RMStateStoreAppEvent) event).getAppState(); ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); LOG.info("Storing info for app: " + appId); try { store.storeApplicationStateInternal(appId, appState); store.notifyApplication(new RMAppEvent(appId, RMAppEventType.APP_NEW_SAVED)); } catch (Exception e) { LOG.error("Error storing app: " + appId, e); store.notifyStoreOperationFailed(e); } }; } private static class UpdateAppTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateUpdateAppEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } ApplicationStateData appState = ((RMStateUpdateAppEvent) event).getAppState(); ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); LOG.info("Updating info for app: " + appId); try { store.updateApplicationStateInternal(appId, appState); store.notifyApplication(new RMAppEvent(appId, RMAppEventType.APP_UPDATE_SAVED)); } catch (Exception e) { LOG.error("Error updating app: " + appId, e); store.notifyStoreOperationFailed(e); } }; } private static class RemoveAppTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreRemoveAppEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } ApplicationStateData appState = ((RMStateStoreRemoveAppEvent) event).getAppState(); ApplicationId appId = appState.getApplicationSubmissionContext().getApplicationId(); LOG.info("Removing info for app: " + appId); try { store.removeApplicationStateInternal(appState); } catch (Exception e) { LOG.error("Error removing app: " + appId, e); store.notifyStoreOperationFailed(e); } }; } private static class StoreAppAttemptTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreAppAttemptEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } ApplicationAttemptStateData attemptState = ((RMStateStoreAppAttemptEvent) event).getAppAttemptState(); try { if (LOG.isDebugEnabled()) { LOG.debug("Storing info for attempt: " + attemptState.getAttemptId()); } store.storeApplicationAttemptStateInternal(attemptState.getAttemptId(), attemptState); store.notifyApplicationAttempt(new RMAppAttemptEvent (attemptState.getAttemptId(), RMAppAttemptEventType.ATTEMPT_NEW_SAVED)); } catch (Exception e) { LOG.error("Error storing appAttempt: " + attemptState.getAttemptId(), e); store.notifyStoreOperationFailed(e); } }; } private static class UpdateAppAttemptTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateUpdateAppAttemptEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } ApplicationAttemptStateData attemptState = ((RMStateUpdateAppAttemptEvent) event).getAppAttemptState(); try { if (LOG.isDebugEnabled()) { LOG.debug("Updating info for attempt: " + attemptState.getAttemptId()); } store.updateApplicationAttemptStateInternal(attemptState.getAttemptId(), attemptState); store.notifyApplicationAttempt(new RMAppAttemptEvent (attemptState.getAttemptId(), RMAppAttemptEventType.ATTEMPT_UPDATE_SAVED)); } catch (Exception e) { LOG.error("Error updating appAttempt: " + attemptState.getAttemptId(), e); store.notifyStoreOperationFailed(e); } }; } private static class StoreRMDTTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreRMDTEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event; try { LOG.info("Storing RMDelegationToken and SequenceNumber"); store.storeRMDelegationTokenState( dtEvent.getRmDTIdentifier(), dtEvent.getRenewDate()); } catch (Exception e) { LOG.error("Error While Storing RMDelegationToken and SequenceNumber ", e); store.notifyStoreOperationFailed(e); } } } private static class RemoveRMDTTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreRMDTEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event; try { LOG.info("Removing RMDelegationToken and SequenceNumber"); store.removeRMDelegationTokenState(dtEvent.getRmDTIdentifier()); } catch (Exception e) { LOG.error("Error While Removing RMDelegationToken and SequenceNumber ", e); store.notifyStoreOperationFailed(e); } } } private static class UpdateRMDTTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreRMDTEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreRMDTEvent dtEvent = (RMStateStoreRMDTEvent) event; try { LOG.info("Updating RMDelegationToken and SequenceNumber"); store.updateRMDelegationTokenState( dtEvent.getRmDTIdentifier(), dtEvent.getRenewDate()); } catch (Exception e) { LOG.error("Error While Updating RMDelegationToken and SequenceNumber ", e); store.notifyStoreOperationFailed(e); } } } private static class StoreRMDTMasterKeyTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreRMDTMasterKeyEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreRMDTMasterKeyEvent dtEvent = (RMStateStoreRMDTMasterKeyEvent) event; try { LOG.info("Storing RMDTMasterKey."); store.storeRMDTMasterKeyState(dtEvent.getDelegationKey()); } catch (Exception e) { LOG.error("Error While Storing RMDTMasterKey.", e); store.notifyStoreOperationFailed(e); } } } private static class RemoveRMDTMasterKeyTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreRMDTMasterKeyEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreRMDTMasterKeyEvent dtEvent = (RMStateStoreRMDTMasterKeyEvent) event; try { LOG.info("Removing RMDTMasterKey."); store.removeRMDTMasterKeyState(dtEvent.getDelegationKey()); } catch (Exception e) { LOG.error("Error While Removing RMDTMasterKey.", e); store.notifyStoreOperationFailed(e); } } } private static class StoreOrUpdateAMRMTokenTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreAMRMTokenEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreAMRMTokenEvent amrmEvent = (RMStateStoreAMRMTokenEvent) event; try { LOG.info("Updating AMRMToken"); store.storeOrUpdateAMRMTokenSecretManagerState( amrmEvent.getAmrmTokenSecretManagerState(), amrmEvent.isUpdate()); } catch (Exception e) { LOG.error("Error storing info for AMRMTokenSecretManager", e); store.notifyStoreOperationFailed(e); } } } private static class StoreReservationAllocationTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreStoreReservationEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreStoreReservationEvent reservationEvent = (RMStateStoreStoreReservationEvent) event; try { LOG.info("Storing reservation allocation." + reservationEvent .getReservationIdName()); store.storeReservationState( reservationEvent.getReservationAllocation(), reservationEvent.getPlanName(), reservationEvent.getReservationIdName()); } catch (Exception e) { LOG.error("Error while storing reservation allocation.", e); store.notifyStoreOperationFailed(e); } } } private static class UpdateReservationAllocationTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreStoreReservationEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreStoreReservationEvent reservationEvent = (RMStateStoreStoreReservationEvent) event; try { LOG.info("Updating reservation allocation." + reservationEvent .getReservationIdName()); store.updateReservationState( reservationEvent.getReservationAllocation(), reservationEvent.getPlanName(), reservationEvent.getReservationIdName()); } catch (Exception e) { LOG.error("Error while updating reservation allocation.", e); store.notifyStoreOperationFailed(e); } } } private static class RemoveReservationAllocationTransition implements SingleArcTransition<RMStateStore, RMStateStoreEvent> { @Override public void transition(RMStateStore store, RMStateStoreEvent event) { if (!(event instanceof RMStateStoreStoreReservationEvent)) { // should never happen LOG.error("Illegal event type: " + event.getClass()); return; } RMStateStoreStoreReservationEvent reservationEvent = (RMStateStoreStoreReservationEvent) event; try { LOG.info("Removing reservation allocation." + reservationEvent .getReservationIdName()); store.removeReservationState( reservationEvent.getPlanName(), reservationEvent.getReservationIdName()); } catch (Exception e) { LOG.error("Error while removing reservation allocation.", e); store.notifyStoreOperationFailed(e); } } } public RMStateStore() { super(RMStateStore.class.getName()); ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); stateMachine = stateMachineFactory.make(this); } public static class RMDTSecretManagerState { // DTIdentifier -> renewDate Map<RMDelegationTokenIdentifier, Long> delegationTokenState = new HashMap<RMDelegationTokenIdentifier, Long>(); Set<DelegationKey> masterKeyState = new HashSet<DelegationKey>(); int dtSequenceNumber = 0; public Map<RMDelegationTokenIdentifier, Long> getTokenState() { return delegationTokenState; } public Set<DelegationKey> getMasterKeyState() { return masterKeyState; } public int getDTSequenceNumber() { return dtSequenceNumber; } } /** * State of the ResourceManager */ public static class RMState { Map<ApplicationId, ApplicationStateData> appState = new TreeMap<ApplicationId, ApplicationStateData>(); RMDTSecretManagerState rmSecretManagerState = new RMDTSecretManagerState(); AMRMTokenSecretManagerState amrmTokenSecretManagerState = null; private Map<String, Map<ReservationId, ReservationAllocationStateProto>> reservationState = new TreeMap<>(); public Map<ApplicationId, ApplicationStateData> getApplicationState() { return appState; } public RMDTSecretManagerState getRMDTSecretManagerState() { return rmSecretManagerState; } public AMRMTokenSecretManagerState getAMRMTokenSecretManagerState() { return amrmTokenSecretManagerState; } public Map<String, Map<ReservationId, ReservationAllocationStateProto>> getReservationState() { return reservationState; } } private Dispatcher rmDispatcher; /** * Dispatcher used to send state operation completion events to * ResourceManager services */ public void setRMDispatcher(Dispatcher dispatcher) { this.rmDispatcher = dispatcher; } AsyncDispatcher dispatcher; @Override protected void serviceInit(Configuration conf) throws Exception{ // create async handler dispatcher = new AsyncDispatcher(); dispatcher.init(conf); dispatcher.register(RMStateStoreEventType.class, new ForwardingEventHandler()); dispatcher.setDrainEventsOnStop(); initInternal(conf); } @Override protected void serviceStart() throws Exception { dispatcher.start(); startInternal(); } /** * Derived classes initialize themselves using this method. */ protected abstract void initInternal(Configuration conf) throws Exception; /** * Derived classes start themselves using this method. * The base class is started and the event dispatcher is ready to use at * this point */ protected abstract void startInternal() throws Exception; @Override protected void serviceStop() throws Exception { dispatcher.stop(); closeInternal(); } /** * Derived classes close themselves using this method. * The base class will be closed and the event dispatcher will be shutdown * after this */ protected abstract void closeInternal() throws Exception; /** * 1) Versioning scheme: major.minor. For e.g. 1.0, 1.1, 1.2...1.25, 2.0 etc. * 2) Any incompatible change of state-store is a major upgrade, and any * compatible change of state-store is a minor upgrade. * 3) If theres's no version, treat it as CURRENT_VERSION_INFO. * 4) Within a minor upgrade, say 1.1 to 1.2: * overwrite the version info and proceed as normal. * 5) Within a major upgrade, say 1.2 to 2.0: * throw exception and indicate user to use a separate upgrade tool to * upgrade RM state. */ public void checkVersion() throws Exception { Version loadedVersion = loadVersion(); LOG.info("Loaded RM state version info " + loadedVersion); if (loadedVersion != null && loadedVersion.equals(getCurrentVersion())) { return; } // if there is no version info, treat it as CURRENT_VERSION_INFO; if (loadedVersion == null) { loadedVersion = getCurrentVersion(); } if (loadedVersion.isCompatibleTo(getCurrentVersion())) { LOG.info("Storing RM state version info " + getCurrentVersion()); storeVersion(); } else { throw new RMStateVersionIncompatibleException( "Expecting RM state version " + getCurrentVersion() + ", but loading version " + loadedVersion); } } /** * Derived class use this method to load the version information from state * store. */ protected abstract Version loadVersion() throws Exception; /** * Derived class use this method to store the version information. */ protected abstract void storeVersion() throws Exception; /** * Get the current version of the underlying state store. */ protected abstract Version getCurrentVersion(); /** * Get the current epoch of RM and increment the value. */ public abstract long getAndIncrementEpoch() throws Exception; /** * Blocking API * The derived class must recover state from the store and return a new * RMState object populated with that state * This must not be called on the dispatcher thread */ public abstract RMState loadState() throws Exception; /** * Non-Blocking API * ResourceManager services use this to store the application's state * This does not block the dispatcher threads * RMAppStoredEvent will be sent on completion to notify the RMApp */ @SuppressWarnings("unchecked") public synchronized void storeNewApplication(RMApp app) { ApplicationSubmissionContext context = app .getApplicationSubmissionContext(); assert context instanceof ApplicationSubmissionContextPBImpl; ApplicationStateData appState = ApplicationStateData.newInstance( app.getSubmitTime(), app.getStartTime(), context, app.getUser()); dispatcher.getEventHandler().handle(new RMStateStoreAppEvent(appState)); } @SuppressWarnings("unchecked") public synchronized void updateApplicationState( ApplicationStateData appState) { dispatcher.getEventHandler().handle(new RMStateUpdateAppEvent(appState)); } public void updateFencedState() { handleStoreEvent(new RMStateStoreEvent(RMStateStoreEventType.FENCED)); } /** * Blocking API * Derived classes must implement this method to store the state of an * application. */ protected abstract void storeApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws Exception; protected abstract void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws Exception; @SuppressWarnings("unchecked") /** * Non-blocking API * ResourceManager services call this to store state on an application attempt * This does not block the dispatcher threads * RMAppAttemptStoredEvent will be sent on completion to notify the RMAppAttempt */ public synchronized void storeNewApplicationAttempt(RMAppAttempt appAttempt) { Credentials credentials = getCredentialsFromAppAttempt(appAttempt); AggregateAppResourceUsage resUsage = appAttempt.getRMAppAttemptMetrics().getAggregateAppResourceUsage(); ApplicationAttemptStateData attemptState = ApplicationAttemptStateData.newInstance( appAttempt.getAppAttemptId(), appAttempt.getMasterContainer(), credentials, appAttempt.getStartTime(), resUsage.getMemorySeconds(), resUsage.getVcoreSeconds()); dispatcher.getEventHandler().handle( new RMStateStoreAppAttemptEvent(attemptState)); } @SuppressWarnings("unchecked") public synchronized void updateApplicationAttemptState( ApplicationAttemptStateData attemptState) { dispatcher.getEventHandler().handle( new RMStateUpdateAppAttemptEvent(attemptState)); } /** * Blocking API * Derived classes must implement this method to store the state of an * application attempt */ protected abstract void storeApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception; protected abstract void updateApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception; /** * RMDTSecretManager call this to store the state of a delegation token * and sequence number */ public void storeRMDelegationToken( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) { handleStoreEvent(new RMStateStoreRMDTEvent(rmDTIdentifier, renewDate, RMStateStoreEventType.STORE_DELEGATION_TOKEN)); } /** * Blocking API * Derived classes must implement this method to store the state of * RMDelegationToken and sequence number */ protected abstract void storeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception; /** * RMDTSecretManager call this to remove the state of a delegation token */ public void removeRMDelegationToken( RMDelegationTokenIdentifier rmDTIdentifier) { handleStoreEvent(new RMStateStoreRMDTEvent(rmDTIdentifier, null, RMStateStoreEventType.REMOVE_DELEGATION_TOKEN)); } /** * Blocking API * Derived classes must implement this method to remove the state of RMDelegationToken */ protected abstract void removeRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier) throws Exception; /** * RMDTSecretManager call this to update the state of a delegation token * and sequence number */ public void updateRMDelegationToken( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) { handleStoreEvent(new RMStateStoreRMDTEvent(rmDTIdentifier, renewDate, RMStateStoreEventType.UPDATE_DELEGATION_TOKEN)); } /** * Blocking API * Derived classes must implement this method to update the state of * RMDelegationToken and sequence number */ protected abstract void updateRMDelegationTokenState( RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate) throws Exception; /** * RMDTSecretManager call this to store the state of a master key */ public void storeRMDTMasterKey(DelegationKey delegationKey) { handleStoreEvent(new RMStateStoreRMDTMasterKeyEvent(delegationKey, RMStateStoreEventType.STORE_MASTERKEY)); } /** * Blocking API * Derived classes must implement this method to store the state of * DelegationToken Master Key */ protected abstract void storeRMDTMasterKeyState(DelegationKey delegationKey) throws Exception; /** * RMDTSecretManager call this to remove the state of a master key */ public void removeRMDTMasterKey(DelegationKey delegationKey) { handleStoreEvent(new RMStateStoreRMDTMasterKeyEvent(delegationKey, RMStateStoreEventType.REMOVE_MASTERKEY)); } /** * Blocking Apis to maintain reservation state. */ public void storeNewReservation( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) { handleStoreEvent(new RMStateStoreStoreReservationEvent( reservationAllocation, RMStateStoreEventType.STORE_RESERVATION, planName, reservationIdName)); } public void updateReservation( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) { handleStoreEvent(new RMStateStoreStoreReservationEvent( reservationAllocation, RMStateStoreEventType.UPDATE_RESERVATION, planName, reservationIdName)); } public void removeReservation(String planName, String reservationIdName) { handleStoreEvent(new RMStateStoreStoreReservationEvent( null, RMStateStoreEventType.REMOVE_RESERVATION, planName, reservationIdName)); } /** * Blocking API * Derived classes must implement this method to store the state of * a reservation allocation. */ protected abstract void storeReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception; /** * Blocking API * Derived classes must implement this method to remove the state of * a reservation allocation. */ protected abstract void removeReservationState(String planName, String reservationIdName) throws Exception; /** * Blocking API * Derived classes must implement this method to update the state of * a reservation allocation. */ protected abstract void updateReservationState( ReservationAllocationStateProto reservationAllocation, String planName, String reservationIdName) throws Exception; /** * Blocking API * Derived classes must implement this method to remove the state of * DelegationToken Master Key */ protected abstract void removeRMDTMasterKeyState(DelegationKey delegationKey) throws Exception; /** * Blocking API Derived classes must implement this method to store or update * the state of AMRMToken Master Key */ protected abstract void storeOrUpdateAMRMTokenSecretManagerState( AMRMTokenSecretManagerState amrmTokenSecretManagerState, boolean isUpdate) throws Exception; /** * Store or Update state of AMRMToken Master Key */ public void storeOrUpdateAMRMTokenSecretManager( AMRMTokenSecretManagerState amrmTokenSecretManagerState, boolean isUpdate) { handleStoreEvent(new RMStateStoreAMRMTokenEvent( amrmTokenSecretManagerState, isUpdate, RMStateStoreEventType.UPDATE_AMRM_TOKEN)); } /** * Non-blocking API * ResourceManager services call this to remove an application from the state * store * This does not block the dispatcher threads * There is no notification of completion for this operation. */ @SuppressWarnings("unchecked") public synchronized void removeApplication(RMApp app) { ApplicationStateData appState = ApplicationStateData.newInstance( app.getSubmitTime(), app.getStartTime(), app.getApplicationSubmissionContext(), app.getUser()); for(RMAppAttempt appAttempt : app.getAppAttempts().values()) { appState.attempts.put(appAttempt.getAppAttemptId(), null); } dispatcher.getEventHandler().handle(new RMStateStoreRemoveAppEvent(appState)); } /** * Blocking API * Derived classes must implement this method to remove the state of an * application and its attempts */ protected abstract void removeApplicationStateInternal( ApplicationStateData appState) throws Exception; // TODO: This should eventually become cluster-Id + "AM_RM_TOKEN_SERVICE". See // YARN-1779 public static final Text AM_RM_TOKEN_SERVICE = new Text( "AM_RM_TOKEN_SERVICE"); public static final Text AM_CLIENT_TOKEN_MASTER_KEY_NAME = new Text("YARN_CLIENT_TOKEN_MASTER_KEY"); public Credentials getCredentialsFromAppAttempt(RMAppAttempt appAttempt) { Credentials credentials = new Credentials(); SecretKey clientTokenMasterKey = appAttempt.getClientTokenMasterKey(); if(clientTokenMasterKey != null){ credentials.addSecretKey(AM_CLIENT_TOKEN_MASTER_KEY_NAME, clientTokenMasterKey.getEncoded()); } return credentials; } @VisibleForTesting protected boolean isFencedState() { return (RMStateStoreState.FENCED == getRMStateStoreState()); } // Dispatcher related code protected void handleStoreEvent(RMStateStoreEvent event) { this.writeLock.lock(); try { if (LOG.isDebugEnabled()) { LOG.debug("Processing event of type " + event.getType()); } final RMStateStoreState oldState = getRMStateStoreState(); this.stateMachine.doTransition(event.getType(), event); if (oldState != getRMStateStoreState()) { LOG.info("RMStateStore state change from " + oldState + " to " + getRMStateStoreState()); } } catch (InvalidStateTransitionException e) { LOG.error("Can't handle this event at current state", e); } finally { this.writeLock.unlock(); } } @SuppressWarnings("unchecked") /** * This method is called to notify the ResourceManager that the store * operation has failed. * @param failureCause the exception due to which the operation failed */ protected void notifyStoreOperationFailed(Exception failureCause) { LOG.error("State store operation failed ", failureCause); if (failureCause instanceof StoreFencedException) { updateFencedState(); Thread standByTransitionThread = new Thread(new StandByTransitionThread()); standByTransitionThread.setName("StandByTransitionThread Handler"); standByTransitionThread.start(); } else { if (YarnConfiguration.shouldRMFailFast(getConfig())) { rmDispatcher.getEventHandler().handle( new RMFatalEvent(RMFatalEventType.STATE_STORE_OP_FAILED, failureCause)); } } } @SuppressWarnings("unchecked") /** * This method is called to notify the application that * new application is stored or updated in state store * @param event App event containing the app id and event type */ private void notifyApplication(RMAppEvent event) { rmDispatcher.getEventHandler().handle(event); } @SuppressWarnings("unchecked") /** * This method is called to notify the application attempt * that new attempt is stored or updated in state store * @param event App attempt event containing the app attempt * id and event type */ private void notifyApplicationAttempt(RMAppAttemptEvent event) { rmDispatcher.getEventHandler().handle(event); } /** * EventHandler implementation which forward events to the FSRMStateStore * This hides the EventHandle methods of the store from its public interface */ private final class ForwardingEventHandler implements EventHandler<RMStateStoreEvent> { @Override public void handle(RMStateStoreEvent event) { handleStoreEvent(event); } } /** * Derived classes must implement this method to delete the state store * @throws Exception */ public abstract void deleteStore() throws Exception; /** * Derived classes must implement this method to remove application from the * state store * * @throws Exception */ public abstract void removeApplication(ApplicationId removeAppId) throws Exception; public void setResourceManager(ResourceManager rm) { this.resourceManager = rm; } private class StandByTransitionThread implements Runnable { @Override public void run() { LOG.info("RMStateStore has been fenced"); resourceManager.handleTransitionToStandBy(); } } public RMStateStoreState getRMStateStoreState() { this.readLock.lock(); try { return this.stateMachine.getCurrentState(); } finally { this.readLock.unlock(); } } }
41,192
36.653565
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery.records; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Stable; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationStateDataProto; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.util.Records; /** * Contains all the state data that needs to be stored persistently * for an Application */ @Public @Unstable public abstract class ApplicationStateData { public Map<ApplicationAttemptId, ApplicationAttemptStateData> attempts = new HashMap<ApplicationAttemptId, ApplicationAttemptStateData>(); public static ApplicationStateData newInstance(long submitTime, long startTime, String user, ApplicationSubmissionContext submissionContext, RMAppState state, String diagnostics, long finishTime) { ApplicationStateData appState = Records.newRecord(ApplicationStateData.class); appState.setSubmitTime(submitTime); appState.setStartTime(startTime); appState.setUser(user); appState.setApplicationSubmissionContext(submissionContext); appState.setState(state); appState.setDiagnostics(diagnostics); appState.setFinishTime(finishTime); return appState; } public static ApplicationStateData newInstance(long submitTime, long startTime, ApplicationSubmissionContext context, String user) { return newInstance(submitTime, startTime, user, context, null, "", 0); } public int getAttemptCount() { return attempts.size(); } public ApplicationAttemptStateData getAttempt( ApplicationAttemptId attemptId) { return attempts.get(attemptId); } public abstract ApplicationStateDataProto getProto(); /** * The time at which the application was received by the Resource Manager * @return submitTime */ @Public @Unstable public abstract long getSubmitTime(); @Public @Unstable public abstract void setSubmitTime(long submitTime); /** * Get the <em>start time</em> of the application. * @return <em>start time</em> of the application */ @Public @Stable public abstract long getStartTime(); @Private @Unstable public abstract void setStartTime(long startTime); /** * The application submitter */ @Public @Unstable public abstract void setUser(String user); @Public @Unstable public abstract String getUser(); /** * The {@link ApplicationSubmissionContext} for the application * {@link ApplicationId} can be obtained from the this * @return ApplicationSubmissionContext */ @Public @Unstable public abstract ApplicationSubmissionContext getApplicationSubmissionContext(); @Public @Unstable public abstract void setApplicationSubmissionContext( ApplicationSubmissionContext context); /** * Get the final state of the application. * @return the final state of the application. */ public abstract RMAppState getState(); public abstract void setState(RMAppState state); /** * Get the diagnostics information for the application master. * @return the diagnostics information for the application master. */ public abstract String getDiagnostics(); public abstract void setDiagnostics(String diagnostics); /** * The finish time of the application. * @return the finish time of the application., */ public abstract long getFinishTime(); public abstract void setFinishTime(long finishTime); }
4,751
31.108108
102
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.recovery.records; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos.ApplicationAttemptStateDataProto; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.util.Records; /* * Contains the state data that needs to be persisted for an ApplicationAttempt */ @Public @Unstable public abstract class ApplicationAttemptStateData { public static ApplicationAttemptStateData newInstance( ApplicationAttemptId attemptId, Container container, Credentials attemptTokens, long startTime, RMAppAttemptState finalState, String finalTrackingUrl, String diagnostics, FinalApplicationStatus amUnregisteredFinalStatus, int exitStatus, long finishTime, long memorySeconds, long vcoreSeconds) { ApplicationAttemptStateData attemptStateData = Records.newRecord(ApplicationAttemptStateData.class); attemptStateData.setAttemptId(attemptId); attemptStateData.setMasterContainer(container); attemptStateData.setAppAttemptTokens(attemptTokens); attemptStateData.setState(finalState); attemptStateData.setFinalTrackingUrl(finalTrackingUrl); attemptStateData.setDiagnostics(diagnostics == null ? "" : diagnostics); attemptStateData.setStartTime(startTime); attemptStateData.setFinalApplicationStatus(amUnregisteredFinalStatus); attemptStateData.setAMContainerExitStatus(exitStatus); attemptStateData.setFinishTime(finishTime); attemptStateData.setMemorySeconds(memorySeconds); attemptStateData.setVcoreSeconds(vcoreSeconds); return attemptStateData; } public static ApplicationAttemptStateData newInstance( ApplicationAttemptId attemptId, Container masterContainer, Credentials attemptTokens, long startTime, long memorySeconds, long vcoreSeconds) { return newInstance(attemptId, masterContainer, attemptTokens, startTime, null, "N/A", "", null, ContainerExitStatus.INVALID, 0, memorySeconds, vcoreSeconds); } public abstract ApplicationAttemptStateDataProto getProto(); /** * The ApplicationAttemptId for the application attempt * @return ApplicationAttemptId for the application attempt */ @Public @Unstable public abstract ApplicationAttemptId getAttemptId(); public abstract void setAttemptId(ApplicationAttemptId attemptId); /* * The master container running the application attempt * @return Container that hosts the attempt */ @Public @Unstable public abstract Container getMasterContainer(); public abstract void setMasterContainer(Container container); /** * The application attempt tokens that belong to this attempt * @return The application attempt tokens that belong to this attempt */ @Public @Unstable public abstract Credentials getAppAttemptTokens(); public abstract void setAppAttemptTokens(Credentials attemptTokens); /** * Get the final state of the application attempt. * @return the final state of the application attempt. */ public abstract RMAppAttemptState getState(); public abstract void setState(RMAppAttemptState state); /** * Get the original not-proxied <em>final tracking url</em> for the * application. This is intended to only be used by the proxy itself. * * @return the original not-proxied <em>final tracking url</em> for the * application */ public abstract String getFinalTrackingUrl(); /** * Set the final tracking Url of the AM. * @param url */ public abstract void setFinalTrackingUrl(String url); /** * Get the <em>diagnositic information</em> of the attempt * @return <em>diagnositic information</em> of the attempt */ public abstract String getDiagnostics(); public abstract void setDiagnostics(String diagnostics); /** * Get the <em>start time</em> of the application. * @return <em>start time</em> of the application */ public abstract long getStartTime(); public abstract void setStartTime(long startTime); /** * Get the <em>final finish status</em> of the application. * @return <em>final finish status</em> of the application */ public abstract FinalApplicationStatus getFinalApplicationStatus(); public abstract void setFinalApplicationStatus( FinalApplicationStatus finishState); public abstract int getAMContainerExitStatus(); public abstract void setAMContainerExitStatus(int exitStatus); /** * Get the <em>finish time</em> of the application attempt. * @return <em>finish time</em> of the application attempt */ public abstract long getFinishTime(); public abstract void setFinishTime(long finishTime); /** * Get the <em>memory seconds</em> (in MB seconds) of the application. * @return <em>memory seconds</em> (in MB seconds) of the application */ @Public @Unstable public abstract long getMemorySeconds(); @Public @Unstable public abstract void setMemorySeconds(long memorySeconds); /** * Get the <em>vcore seconds</em> of the application. * @return <em>vcore seconds</em> of the application */ @Public @Unstable public abstract long getVcoreSeconds(); @Public @Unstable public abstract void setVcoreSeconds(long vcoreSeconds); }
6,549
34.215054
109
java