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-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/AppChecker.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.sharedcachemanager; import java.util.Collection; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.service.CompositeService; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.exceptions.YarnException; /** * An interface for checking whether an app is running so that the cleaner * service may determine if it can safely remove a cached entry. */ @Private @Evolving public abstract class AppChecker extends CompositeService { public AppChecker() { super("AppChecker"); } public AppChecker(String name) { super(name); } /** * Returns whether the app is in an active state. * * @return true if the app is found and is not in one of the completed states; * false otherwise * @throws YarnException if there is an error in determining the app state */ @Private public abstract boolean isApplicationActive(ApplicationId id) throws YarnException; /** * Returns the list of all active apps at the given time. * * @return the list of active apps, or an empty list if there is none * @throws YarnException if there is an error in obtaining the list */ @Private public abstract Collection<ApplicationId> getActiveApplications() throws YarnException; }
2,227
32.757576
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/RemoteAppChecker.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.sharedcachemanager; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; /** * An implementation of AppChecker that queries the resource manager remotely to * determine whether the app is running. */ @Private @Unstable public class RemoteAppChecker extends AppChecker { private static final EnumSet<YarnApplicationState> ACTIVE_STATES = EnumSet .of(YarnApplicationState.NEW, YarnApplicationState.ACCEPTED, YarnApplicationState.NEW_SAVING, YarnApplicationState.SUBMITTED, YarnApplicationState.RUNNING); private final YarnClient client; public RemoteAppChecker() { this(YarnClient.createYarnClient()); } RemoteAppChecker(YarnClient client) { super("RemoteAppChecker"); this.client = client; } @Override protected void serviceInit(Configuration conf) throws Exception { addService(client); super.serviceInit(conf); } @Override @Private public boolean isApplicationActive(ApplicationId id) throws YarnException { ApplicationReport report = null; try { report = client.getApplicationReport(id); } catch (ApplicationNotFoundException e) { // the app does not exist return false; } catch (IOException e) { throw new YarnException(e); } if (report == null) { // the app does not exist return false; } return ACTIVE_STATES.contains(report.getYarnApplicationState()); } @Override @Private public Collection<ApplicationId> getActiveApplications() throws YarnException { try { List<ApplicationId> activeApps = new ArrayList<ApplicationId>(); List<ApplicationReport> apps = client.getApplications(ACTIVE_STATES); for (ApplicationReport app: apps) { activeApps.add(app.getApplicationId()); } return activeApps; } catch (IOException e) { throw new YarnException(e); } } }
3,346
31.495146
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/SCMAdminProtocolService.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.sharedcachemanager; import java.io.IOException; import java.net.InetSocketAddress; 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.ipc.Server; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.api.SCMAdminProtocol; import org.apache.hadoop.yarn.server.api.protocolrecords.RunSharedCacheCleanerTaskRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RunSharedCacheCleanerTaskResponse; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.ipc.YarnRPC; /** * This service handles all SCMAdminProtocol rpc calls from administrators * to the shared cache manager. */ @Private @Unstable public class SCMAdminProtocolService extends AbstractService implements SCMAdminProtocol { private static final Log LOG = LogFactory.getLog(SCMAdminProtocolService.class); private final RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); private Server server; InetSocketAddress clientBindAddress; private final CleanerService cleanerService; private YarnAuthorizationProvider authorizer; public SCMAdminProtocolService(CleanerService cleanerService) { super(SCMAdminProtocolService.class.getName()); this.cleanerService = cleanerService; } @Override protected void serviceInit(Configuration conf) throws Exception { this.clientBindAddress = getBindAddress(conf); authorizer = YarnAuthorizationProvider.getInstance(conf); super.serviceInit(conf); } InetSocketAddress getBindAddress(Configuration conf) { return conf.getSocketAddr(YarnConfiguration.SCM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_SCM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_SCM_ADMIN_PORT); } @Override protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); this.server = rpc.getServer(SCMAdminProtocol.class, this, clientBindAddress, conf, null, // Secret manager null for now (security not supported) conf.getInt(YarnConfiguration.SCM_ADMIN_CLIENT_THREAD_COUNT, YarnConfiguration.DEFAULT_SCM_ADMIN_CLIENT_THREAD_COUNT)); // TODO: Enable service authorization (see YARN-2774) this.server.start(); clientBindAddress = conf.updateConnectAddr(YarnConfiguration.SCM_ADMIN_ADDRESS, server.getListenerAddress()); super.serviceStart(); } @Override protected void serviceStop() throws Exception { if (this.server != null) { this.server.stop(); } super.serviceStop(); } private void checkAcls(String method) throws YarnException { UserGroupInformation user; try { user = UserGroupInformation.getCurrentUser(); } catch (IOException ioe) { LOG.warn("Couldn't get current user", ioe); throw RPCUtil.getRemoteException(ioe); } if (!authorizer.isAdmin(user)) { LOG.warn("User " + user.getShortUserName() + " doesn't have permission" + " to call '" + method + "'"); throw RPCUtil.getRemoteException( new AccessControlException("User " + user.getShortUserName() + " doesn't have permission" + " to call '" + method + "'")); } LOG.info("SCM Admin: " + method + " invoked by user " + user.getShortUserName()); } @Override public RunSharedCacheCleanerTaskResponse runCleanerTask( RunSharedCacheCleanerTaskRequest request) throws YarnException { checkAcls("runCleanerTask"); RunSharedCacheCleanerTaskResponse response = recordFactory.newRecordInstance(RunSharedCacheCleanerTaskResponse.class); this.cleanerService.runCleanerTask(); // if we are here, then we have submitted the request to the cleaner // service, ack the request to the admin client response.setAccepted(true); return response; } }
5,435
36.489655
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/SharedCacheManager.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.sharedcachemanager; 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.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.source.JvmMetrics; import org.apache.hadoop.service.CompositeService; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.ShutdownHookManager; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.YarnUncaughtExceptionHandler; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.sharedcachemanager.store.SCMStore; import org.apache.hadoop.yarn.server.sharedcachemanager.webapp.SCMWebServer; import com.google.common.annotations.VisibleForTesting; /** * This service maintains the shared cache meta data. It handles claiming and * releasing of resources, all rpc calls from the client to the shared cache * manager, and administrative commands. It also persists the shared cache meta * data to a backend store, and cleans up stale entries on a regular basis. */ @Private @Unstable public class SharedCacheManager extends CompositeService { /** * Priority of the SharedCacheManager shutdown hook. */ public static final int SHUTDOWN_HOOK_PRIORITY = 30; private static final Log LOG = LogFactory.getLog(SharedCacheManager.class); private SCMStore store; public SharedCacheManager() { super("SharedCacheManager"); } @Override protected void serviceInit(Configuration conf) throws Exception { this.store = createSCMStoreService(conf); addService(store); CleanerService cs = createCleanerService(store); addService(cs); SharedCacheUploaderService nms = createNMCacheUploaderSCMProtocolService(store); addService(nms); ClientProtocolService cps = createClientProtocolService(store); addService(cps); SCMAdminProtocolService saps = createSCMAdminProtocolService(cs); addService(saps); SCMWebServer webUI = createSCMWebServer(this); addService(webUI); // init metrics DefaultMetricsSystem.initialize("SharedCacheManager"); JvmMetrics.initSingleton("SharedCacheManager", null); super.serviceInit(conf); } @SuppressWarnings("unchecked") private static SCMStore createSCMStoreService(Configuration conf) { Class<? extends SCMStore> defaultStoreClass; try { defaultStoreClass = (Class<? extends SCMStore>) Class .forName(YarnConfiguration.DEFAULT_SCM_STORE_CLASS); } catch (Exception e) { throw new YarnRuntimeException("Invalid default scm store class" + YarnConfiguration.DEFAULT_SCM_STORE_CLASS, e); } SCMStore store = ReflectionUtils.newInstance(conf.getClass( YarnConfiguration.SCM_STORE_CLASS, defaultStoreClass, SCMStore.class), conf); return store; } private CleanerService createCleanerService(SCMStore store) { return new CleanerService(store); } private SharedCacheUploaderService createNMCacheUploaderSCMProtocolService(SCMStore store) { return new SharedCacheUploaderService(store); } private ClientProtocolService createClientProtocolService(SCMStore store) { return new ClientProtocolService(store); } private SCMAdminProtocolService createSCMAdminProtocolService( CleanerService cleanerService) { return new SCMAdminProtocolService(cleanerService); } private SCMWebServer createSCMWebServer(SharedCacheManager scm) { return new SCMWebServer(scm); } @Override protected void serviceStop() throws Exception { DefaultMetricsSystem.shutdown(); super.serviceStop(); } /** * For testing purposes only. */ @VisibleForTesting SCMStore getSCMStore() { return this.store; } public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler()); StringUtils.startupShutdownMessage(SharedCacheManager.class, args, LOG); try { Configuration conf = new YarnConfiguration(); SharedCacheManager sharedCacheManager = new SharedCacheManager(); ShutdownHookManager.get().addShutdownHook( new CompositeServiceShutdownHook(sharedCacheManager), SHUTDOWN_HOOK_PRIORITY); sharedCacheManager.init(conf); sharedCacheManager.start(); } catch (Throwable t) { LOG.fatal("Error starting SharedCacheManager", t); System.exit(-1); } } }
5,538
32.77439
82
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/webapp/SCMController.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.sharedcachemanager.webapp; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.webapp.Controller; /** * The controller class for the shared cache manager web app. */ @Private @Unstable public class SCMController extends Controller { @Override public void index() { setTitle("Shared Cache Manager"); } /** * It is referenced in SCMWebServer.SCMWebApp.setup() */ @SuppressWarnings("unused") public void overview() { render(SCMOverviewPage.class); } }
1,442
31.795455
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/webapp/SCMMetricsInfo.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.sharedcachemanager.webapp; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.CleanerMetrics; import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.ClientSCMMetrics; import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.SharedCacheUploaderMetrics; /** * This class is used to summarize useful shared cache manager metrics for the * webUI display. */ @XmlRootElement(name = "SCMMetrics") @XmlAccessorType(XmlAccessType.FIELD) @Private @Unstable public class SCMMetricsInfo { protected long totalDeletedFiles; protected long totalProcessedFiles; protected long cacheHits; protected long cacheMisses; protected long cacheReleases; protected long acceptedUploads; protected long rejectedUploads; public SCMMetricsInfo() { } public SCMMetricsInfo(CleanerMetrics cleanerMetrics, ClientSCMMetrics clientSCMMetrics, SharedCacheUploaderMetrics scmUploaderMetrics) { totalDeletedFiles = cleanerMetrics.getTotalDeletedFiles(); totalProcessedFiles = cleanerMetrics.getTotalProcessedFiles(); cacheHits = clientSCMMetrics.getCacheHits(); cacheMisses = clientSCMMetrics.getCacheMisses(); cacheReleases = clientSCMMetrics.getCacheReleases(); acceptedUploads = scmUploaderMetrics.getAcceptedUploads(); rejectedUploads = scmUploaderMetrics.getRejectUploads(); } public long getTotalDeletedFiles() { return totalDeletedFiles; } public long getTotalProcessedFiles() { return totalProcessedFiles; } public long getCacheHits() { return cacheHits; } public long getCacheMisses() { return cacheMisses; } public long getCacheReleases() { return cacheReleases; } public long getAcceptedUploads() { return acceptedUploads; } public long getRejectUploads() { return rejectedUploads; } }
2,908
39.971831
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/webapp/SCMOverviewPage.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.sharedcachemanager.webapp; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.ACCORDION; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.ACCORDION_ID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initID; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.server.sharedcachemanager.SharedCacheManager; import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.CleanerMetrics; import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.ClientSCMMetrics; import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.SharedCacheUploaderMetrics; import org.apache.hadoop.yarn.util.Times; import org.apache.hadoop.yarn.webapp.SubView; import org.apache.hadoop.yarn.webapp.view.HtmlBlock; import org.apache.hadoop.yarn.webapp.view.InfoBlock; import org.apache.hadoop.yarn.webapp.view.TwoColumnLayout; import com.google.inject.Inject; /** * This class is to render the shared cache manager web ui overview page. */ @Private @Unstable public class SCMOverviewPage extends TwoColumnLayout { @Override protected void preHead(Page.HTML<_> html) { set(ACCORDION_ID, "nav"); set(initID(ACCORDION, "nav"), "{autoHeight:false, active:0}"); } @Override protected Class<? extends SubView> content() { return SCMOverviewBlock.class; } @Override protected Class<? extends SubView> nav() { return SCMOverviewNavBlock.class; } static private class SCMOverviewNavBlock extends HtmlBlock { @Override protected void render(Block html) { html.div("#nav").h3("Tools").ul().li().a("/conf", "Configuration")._() .li().a("/stacks", "Thread dump")._().li().a("/logs", "Logs")._() .li().a("/metrics", "Metrics")._()._()._(); } } static private class SCMOverviewBlock extends HtmlBlock { final SharedCacheManager scm; @Inject SCMOverviewBlock(SharedCacheManager scm, ViewContext ctx) { super(ctx); this.scm = scm; } @Override protected void render(Block html) { SCMMetricsInfo metricsInfo = new SCMMetricsInfo( CleanerMetrics.getInstance(), ClientSCMMetrics.getInstance(), SharedCacheUploaderMetrics.getInstance()); info("Shared Cache Manager overview"). _("Started on:", Times.format(scm.getStartTime())). _("Cache hits: ", metricsInfo.getCacheHits()). _("Cache misses: ", metricsInfo.getCacheMisses()). _("Cache releases: ", metricsInfo.getCacheReleases()). _("Accepted uploads: ", metricsInfo.getAcceptedUploads()). _("Rejected uploads: ", metricsInfo.getRejectUploads()). _("Deleted files by the cleaner: ", metricsInfo.getTotalDeletedFiles()). _("Processed files by the cleaner: ", metricsInfo.getTotalProcessedFiles()); html._(InfoBlock.class); } } }
3,764
38.21875
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/webapp/SCMWebServer.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.sharedcachemanager.webapp; 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.service.AbstractService; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.sharedcachemanager.SharedCacheManager; import org.apache.hadoop.yarn.webapp.WebApp; import org.apache.hadoop.yarn.webapp.WebApps; /** * A very simple web interface for the metrics reported by * {@link org.apache.hadoop.yarn.server.sharedcachemanager.SharedCacheManager} * TODO: Security for web ui (See YARN-2774) */ @Private @Unstable public class SCMWebServer extends AbstractService { private static final Log LOG = LogFactory.getLog(SCMWebServer.class); private final SharedCacheManager scm; private WebApp webApp; private String bindAddress; public SCMWebServer(SharedCacheManager scm) { super(SCMWebServer.class.getName()); this.scm = scm; } @Override protected void serviceInit(Configuration conf) throws Exception { this.bindAddress = getBindAddress(conf); super.serviceInit(conf); } private String getBindAddress(Configuration conf) { return conf.get(YarnConfiguration.SCM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_SCM_WEBAPP_ADDRESS); } @Override protected void serviceStart() throws Exception { SCMWebApp scmWebApp = new SCMWebApp(scm); this.webApp = WebApps.$for("sharedcache").at(bindAddress).start(scmWebApp); LOG.info("Instantiated " + SCMWebApp.class.getName() + " at " + bindAddress); } @Override protected void serviceStop() throws Exception { if (this.webApp != null) { this.webApp.stop(); } } private class SCMWebApp extends WebApp { private final SharedCacheManager scm; public SCMWebApp(SharedCacheManager scm) { this.scm = scm; } @Override public void setup() { if (scm != null) { bind(SharedCacheManager.class).toInstance(scm); } route("/", SCMController.class, "overview"); } } }
3,047
32.494505
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/metrics/CleanerMetrics.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.sharedcachemanager.metrics; 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.Evolving; import org.apache.hadoop.metrics2.MetricsSource; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.lib.MetricsAnnotations; import org.apache.hadoop.metrics2.lib.MetricsRegistry; import org.apache.hadoop.metrics2.lib.MetricsSourceBuilder; import org.apache.hadoop.metrics2.lib.MutableCounterLong; import org.apache.hadoop.metrics2.lib.MutableGaugeLong; /** * This class is for maintaining the various Cleaner activity statistics and * publishing them through the metrics interfaces. */ @Private @Evolving @Metrics(name = "CleanerActivity", about = "Cleaner service metrics", context = "yarn") public class CleanerMetrics { public static final Log LOG = LogFactory.getLog(CleanerMetrics.class); private final MetricsRegistry registry = new MetricsRegistry("cleaner"); private final static CleanerMetrics INSTANCE = create(); public static CleanerMetrics getInstance() { return INSTANCE; } @Metric("number of deleted files over all runs") private MutableCounterLong totalDeletedFiles; public long getTotalDeletedFiles() { return totalDeletedFiles.value(); } private @Metric("number of deleted files in the last run") MutableGaugeLong deletedFiles; public long getDeletedFiles() { return deletedFiles.value(); } private @Metric("number of processed files over all runs") MutableCounterLong totalProcessedFiles; public long getTotalProcessedFiles() { return totalProcessedFiles.value(); } private @Metric("number of processed files in the last run") MutableGaugeLong processedFiles; public long getProcessedFiles() { return processedFiles.value(); } @Metric("number of file errors over all runs") private MutableCounterLong totalFileErrors; public long getTotalFileErrors() { return totalFileErrors.value(); } private @Metric("number of file errors in the last run") MutableGaugeLong fileErrors; public long getFileErrors() { return fileErrors.value(); } private CleanerMetrics() { } /** * The metric source obtained after parsing the annotations */ MetricsSource metricSource; static CleanerMetrics create() { MetricsSystem ms = DefaultMetricsSystem.instance(); CleanerMetrics metricObject = new CleanerMetrics(); MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(metricObject); final MetricsSource s = sb.build(); ms.register("cleaner", "The cleaner service of truly shared cache", s); metricObject.metricSource = s; return metricObject; } /** * Report a delete operation at the current system time */ public void reportAFileDelete() { totalProcessedFiles.incr(); processedFiles.incr(); totalDeletedFiles.incr(); deletedFiles.incr(); } /** * Report a process operation at the current system time */ public void reportAFileProcess() { totalProcessedFiles.incr(); processedFiles.incr(); } /** * Report a process operation error at the current system time */ public void reportAFileError() { totalProcessedFiles.incr(); processedFiles.incr(); totalFileErrors.incr(); fileErrors.incr(); } /** * Report the start a new run of the cleaner. * */ public void reportCleaningStart() { processedFiles.set(0); deletedFiles.set(0); fileErrors.set(0); } }
4,609
29.529801
87
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/metrics/ClientSCMMetrics.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.sharedcachemanager.metrics; 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.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.lib.MetricsRegistry; import org.apache.hadoop.metrics2.lib.MutableCounterLong; /** * This class is for maintaining client requests metrics * and publishing them through the metrics interfaces. */ @Private @Unstable @Metrics(about="Client SCM metrics", context="yarn") public class ClientSCMMetrics { private static final Log LOG = LogFactory.getLog(ClientSCMMetrics.class); final MetricsRegistry registry; private final static ClientSCMMetrics INSTANCE = create(); private ClientSCMMetrics() { registry = new MetricsRegistry("clientRequests"); LOG.debug("Initialized " + registry); } public static ClientSCMMetrics getInstance() { return INSTANCE; } static ClientSCMMetrics create() { MetricsSystem ms = DefaultMetricsSystem.instance(); ClientSCMMetrics metrics = new ClientSCMMetrics(); ms.register("clientRequests", null, metrics); return metrics; } @Metric("Number of cache hits") MutableCounterLong cacheHits; @Metric("Number of cache misses") MutableCounterLong cacheMisses; @Metric("Number of cache releases") MutableCounterLong cacheReleases; /** * One cache hit event */ public void incCacheHitCount() { cacheHits.incr(); } /** * One cache miss event */ public void incCacheMissCount() { cacheMisses.incr(); } /** * One cache release event */ public void incCacheRelease() { cacheReleases.incr(); } public long getCacheHits() { return cacheHits.value(); } public long getCacheMisses() { return cacheMisses.value(); } public long getCacheReleases() { return cacheReleases.value(); } }
2,961
31.549451
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/metrics/SharedCacheUploaderMetrics.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.sharedcachemanager.metrics; 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.Evolving; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.lib.MetricsRegistry; import org.apache.hadoop.metrics2.lib.MutableCounterLong; /** * This class is for maintaining shared cache uploader requests metrics * and publishing them through the metrics interfaces. */ @Private @Evolving @Metrics(about="shared cache upload metrics", context="yarn") public class SharedCacheUploaderMetrics { static final Log LOG = LogFactory.getLog(SharedCacheUploaderMetrics.class); final MetricsRegistry registry; private final static SharedCacheUploaderMetrics INSTANCE = create(); private SharedCacheUploaderMetrics() { registry = new MetricsRegistry("SharedCacheUploaderRequests"); LOG.debug("Initialized "+ registry); } public static SharedCacheUploaderMetrics getInstance() { return INSTANCE; } static SharedCacheUploaderMetrics create() { MetricsSystem ms = DefaultMetricsSystem.instance(); SharedCacheUploaderMetrics metrics = new SharedCacheUploaderMetrics(); ms.register("SharedCacheUploaderRequests", null, metrics); return metrics; } @Metric("Number of accepted uploads") MutableCounterLong acceptedUploads; @Metric("Number of rejected uploads") MutableCounterLong rejectedUploads; /** * One accepted upload event */ public void incAcceptedUploads() { acceptedUploads.incr(); } /** * One rejected upload event */ public void incRejectedUploads() { rejectedUploads.incr(); } public long getAcceptedUploads() { return acceptedUploads.value(); } public long getRejectUploads() { return rejectedUploads.value(); } }
2,909
34.060241
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/store/SCMStore.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.sharedcachemanager.store; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.service.CompositeService; import org.apache.hadoop.util.ReflectionUtils; 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.sharedcachemanager.AppChecker; import com.google.common.annotations.VisibleForTesting; /** * An abstract class for the data store used by the shared cache manager * service. All implementations of methods in this interface need to be thread * safe and atomic. */ @Private @Evolving public abstract class SCMStore extends CompositeService { protected AppChecker appChecker; protected SCMStore(String name) { super(name); } @VisibleForTesting SCMStore(String name, AppChecker appChecker) { super(name); this.appChecker = appChecker; } @Override protected void serviceInit(Configuration conf) throws Exception { if (this.appChecker == null) { this.appChecker = createAppCheckerService(conf); } addService(appChecker); super.serviceInit(conf); } /** * Add a resource to the shared cache and it's associated filename. The * resource is identified by a unique key. If the key already exists no action * is taken and the filename of the existing resource is returned. If the key * does not exist, the resource is added, it's access time is set, and the * filename of the resource is returned. * * @param key a unique identifier for a resource * @param fileName the filename of the resource * @return the filename of the resource as represented by the cache */ @Private public abstract String addResource(String key, String fileName); /** * Remove a resource from the shared cache. * * @param key a unique identifier for a resource * @return true if the resource was removed or did not exist, false if the * resource existed, contained at least one * <code>SharedCacheResourceReference</code> and was not removed. */ @Private public abstract boolean removeResource(String key); /** * Add a <code>SharedCacheResourceReference</code> to a resource and update * the resource access time. * * @param key a unique identifier for a resource * @param ref the <code>SharedCacheResourceReference</code> to add * @return String the filename of the resource if the * <code>SharedCacheResourceReference</code> was added or already * existed. null if the resource did not exist */ @Private public abstract String addResourceReference(String key, SharedCacheResourceReference ref); /** * Get the <code>SharedCacheResourceReference</code>(s) associated with the * resource. * * @param key a unique identifier for a resource * @return an unmodifiable collection of * <code>SharedCacheResourceReferences</code>. If the resource does * not exist, an empty set is returned. */ @Private public abstract Collection<SharedCacheResourceReference> getResourceReferences( String key); /** * Remove a <code>SharedCacheResourceReference</code> from a resource. * * @param key a unique identifier for a resource * @param ref the <code>SharedCacheResourceReference</code> to remove * @param updateAccessTime true if the call should update the access time for * the resource * @return true if the reference was removed, false otherwise */ @Private public abstract boolean removeResourceReference(String key, SharedCacheResourceReference ref, boolean updateAccessTime); /** * Remove a collection of <code>SharedCacheResourceReferences</code> from a * resource. * * @param key a unique identifier for a resource * @param refs the collection of <code>SharedCacheResourceReference</code>s to * remove * @param updateAccessTime true if the call should update the access time for * the resource */ @Private public abstract void removeResourceReferences(String key, Collection<SharedCacheResourceReference> refs, boolean updateAccessTime); /** * Clean all resource references to a cache resource that contain application * ids pointing to finished applications. If the resource key does not exist, * do nothing. * * @param key a unique identifier for a resource * @throws YarnException */ @Private public void cleanResourceReferences(String key) throws YarnException { Collection<SharedCacheResourceReference> refs = getResourceReferences(key); if (!refs.isEmpty()) { Set<SharedCacheResourceReference> refsToRemove = new HashSet<SharedCacheResourceReference>(); for (SharedCacheResourceReference r : refs) { if (!appChecker.isApplicationActive(r.getAppId())) { // application in resource reference is dead, it is safe to remove the // reference refsToRemove.add(r); } } if (refsToRemove.size() > 0) { removeResourceReferences(key, refsToRemove, false); } } } /** * Check if a specific resource is evictable according to the store's enabled * cache eviction policies. * * @param key a unique identifier for a resource * @param file the <code>FileStatus</code> object for the resource file in the * file system. * @return true if the resource is evicatble, false otherwise */ @Private public abstract boolean isResourceEvictable(String key, FileStatus file); /** * Create an instance of the AppChecker service via reflection based on the * {@link YarnConfiguration#SCM_APP_CHECKER_CLASS} parameter. * * @param conf * @return an instance of the AppChecker class */ @Private @SuppressWarnings("unchecked") public static AppChecker createAppCheckerService(Configuration conf) { Class<? extends AppChecker> defaultCheckerClass; try { defaultCheckerClass = (Class<? extends AppChecker>) Class .forName(YarnConfiguration.DEFAULT_SCM_APP_CHECKER_CLASS); } catch (Exception e) { throw new YarnRuntimeException("Invalid default scm app checker class" + YarnConfiguration.DEFAULT_SCM_APP_CHECKER_CLASS, e); } AppChecker checker = ReflectionUtils.newInstance(conf.getClass( YarnConfiguration.SCM_APP_CHECKER_CLASS, defaultCheckerClass, AppChecker.class), conf); return checker; } }
7,677
34.878505
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/store/InMemorySCMStore.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.sharedcachemanager.store; 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.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.StringInterner; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.sharedcache.SharedCacheUtil; import org.apache.hadoop.yarn.server.sharedcachemanager.AppChecker; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * A thread safe version of an in-memory SCM store. The thread safety is * implemented with two key pieces: (1) at the mapping level a ConcurrentHashMap * is used to allow concurrency to resources and their associated references, * and (2) a key level lock is used to ensure mutual exclusion between any * operation that accesses a resource with the same key. <br> * <br> * To ensure safe key-level locking, we use the original string key and intern * it weakly using hadoop's <code>StringInterner</code>. It avoids the pitfalls * of using built-in String interning. The interned strings are also weakly * referenced, so it can be garbage collected once it is done. And there is * little risk of keys being available for other parts of the code so they can * be used as locks accidentally. <br> * <br> * Resources in the in-memory store are evicted based on a time staleness * criteria. If a resource is not referenced (i.e. used) for a given period, it * is designated as a stale resource and is considered evictable. */ @Private @Evolving public class InMemorySCMStore extends SCMStore { private static final Log LOG = LogFactory.getLog(InMemorySCMStore.class); private final Map<String, SharedCacheResource> cachedResources = new ConcurrentHashMap<String, SharedCacheResource>(); private Collection<ApplicationId> initialApps = new ArrayList<ApplicationId>(); private final Object initialAppsLock = new Object(); private long startTime; private int stalenessMinutes; private ScheduledExecutorService scheduler; private int initialDelayMin; private int checkPeriodMin; public InMemorySCMStore() { super(InMemorySCMStore.class.getName()); } @VisibleForTesting public InMemorySCMStore(AppChecker appChecker) { super(InMemorySCMStore.class.getName(), appChecker); } private String intern(String key) { return StringInterner.weakIntern(key); } /** * The in-memory store bootstraps itself from the shared cache entries that * exist in HDFS. */ @Override protected void serviceInit(Configuration conf) throws Exception { this.startTime = System.currentTimeMillis(); this.initialDelayMin = getInitialDelay(conf); this.checkPeriodMin = getCheckPeriod(conf); this.stalenessMinutes = getStalenessPeriod(conf); bootstrap(conf); ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("InMemorySCMStore") .build(); scheduler = Executors.newSingleThreadScheduledExecutor(tf); super.serviceInit(conf); } @Override protected void serviceStart() throws Exception { // start composed services first super.serviceStart(); // Get initial list of running applications LOG.info("Getting the active app list to initialize the in-memory scm store"); synchronized (initialAppsLock) { initialApps = appChecker.getActiveApplications(); } LOG.info(initialApps.size() + " apps recorded as active at this time"); Runnable task = new AppCheckTask(appChecker); scheduler.scheduleAtFixedRate(task, initialDelayMin, checkPeriodMin, TimeUnit.MINUTES); LOG.info("Scheduled the in-memory scm store app check task to run every " + checkPeriodMin + " minutes."); } @Override protected void serviceStop() throws Exception { LOG.info("Stopping the " + InMemorySCMStore.class.getSimpleName() + " service."); if (scheduler != null) { LOG.info("Shutting down the background thread."); scheduler.shutdownNow(); try { if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("Gave up waiting for the app check task to shutdown."); } } catch (InterruptedException e) { LOG.warn( "The InMemorySCMStore was interrupted while shutting down the " + "app check task.", e); } LOG.info("The background thread stopped."); } super.serviceStop(); } private void bootstrap(Configuration conf) throws IOException { Map<String, String> initialCachedResources = getInitialCachedResources(FileSystem.get(conf), conf); LOG.info("Bootstrapping from " + initialCachedResources.size() + " cache resources located in the file system"); Iterator<Map.Entry<String, String>> it = initialCachedResources.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> e = it.next(); String key = intern(e.getKey()); String fileName = e.getValue(); SharedCacheResource resource = new SharedCacheResource(fileName); // we don't hold the lock for this as it is done as part of serviceInit cachedResources.put(key, resource); // clear out the initial resource to reduce the footprint it.remove(); } LOG.info("Bootstrapping complete"); } @VisibleForTesting Map<String, String> getInitialCachedResources(FileSystem fs, Configuration conf) throws IOException { // get the root directory for the shared cache String location = conf.get(YarnConfiguration.SHARED_CACHE_ROOT, YarnConfiguration.DEFAULT_SHARED_CACHE_ROOT); Path root = new Path(location); if (!fs.exists(root)) { String message = "The shared cache root directory " + location + " was not found"; LOG.error(message); throw new IOException(message); } int nestedLevel = SharedCacheUtil.getCacheDepth(conf); // now traverse individual directories and process them // the directory structure is specified by the nested level parameter // (e.g. 9/c/d/<checksum>/file) String pattern = SharedCacheUtil.getCacheEntryGlobPattern(nestedLevel+1); LOG.info("Querying for all individual cached resource files"); FileStatus[] entries = fs.globStatus(new Path(root, pattern)); int numEntries = entries == null ? 0 : entries.length; LOG.info("Found " + numEntries + " files: processing for one resource per " + "key"); Map<String, String> initialCachedEntries = new HashMap<String, String>(); if (entries != null) { for (FileStatus entry : entries) { Path file = entry.getPath(); String fileName = file.getName(); if (entry.isFile()) { // get the parent to get the checksum Path parent = file.getParent(); if (parent != null) { // the name of the immediate parent directory is the checksum String key = parent.getName(); // make sure we insert only one file per checksum whichever comes // first if (initialCachedEntries.containsKey(key)) { LOG.warn("Key " + key + " is already mapped to file " + initialCachedEntries.get(key) + "; file " + fileName + " will not be added"); } else { initialCachedEntries.put(key, fileName); } } } } } LOG.info("A total of " + initialCachedEntries.size() + " files are now mapped"); return initialCachedEntries; } /** * Adds the given resource to the store under the key and the filename. If the * entry is already found, it returns the existing filename. It represents the * state of the store at the time of this query. The entry may change or even * be removed once this method returns. The caller should be prepared to * handle that situation. * * @return the filename of the newly inserted resource or that of the existing * resource */ @Override public String addResource(String key, String fileName) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource == null) { resource = new SharedCacheResource(fileName); cachedResources.put(interned, resource); } return resource.getFileName(); } } /** * Adds the provided resource reference to the cache resource under the key, * and updates the access time. If it returns a non-null value, the caller may * safely assume that the resource will not be removed at least until the app * in this resource reference has terminated. * * @return the filename of the resource, or null if the resource is not found */ @Override public String addResourceReference(String key, SharedCacheResourceReference ref) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource == null) { // it's not mapped return null; } resource.addReference(ref); resource.updateAccessTime(); return resource.getFileName(); } } /** * Returns the list of resource references currently registered under the * cache entry. If the list is empty, it returns an empty collection. The * returned collection is unmodifiable and a snapshot of the information at * the time of the query. The state may change after this query returns. The * caller should handle the situation that some or all of these resource * references are no longer relevant. * * @return the collection that contains the resource references associated * with the resource; or an empty collection if no resource references * are registered under this resource */ @Override public Collection<SharedCacheResourceReference> getResourceReferences(String key) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource == null) { return Collections.emptySet(); } Set<SharedCacheResourceReference> refs = new HashSet<SharedCacheResourceReference>( resource.getResourceReferences()); return Collections.unmodifiableSet(refs); } } /** * Removes the provided resource reference from the resource. If the resource * does not exist, nothing will be done. */ @Override public boolean removeResourceReference(String key, SharedCacheResourceReference ref, boolean updateAccessTime) { String interned = intern(key); synchronized (interned) { boolean removed = false; SharedCacheResource resource = cachedResources.get(interned); if (resource != null) { Set<SharedCacheResourceReference> resourceRefs = resource.getResourceReferences(); removed = resourceRefs.remove(ref); if (updateAccessTime) { resource.updateAccessTime(); } } return removed; } } /** * Removes the provided collection of resource references from the resource. * If the resource does not exist, nothing will be done. */ @Override public void removeResourceReferences(String key, Collection<SharedCacheResourceReference> refs, boolean updateAccessTime) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource != null) { Set<SharedCacheResourceReference> resourceRefs = resource.getResourceReferences(); resourceRefs.removeAll(refs); if (updateAccessTime) { resource.updateAccessTime(); } } } } /** * Provides atomicity for the method. */ @Override public void cleanResourceReferences(String key) throws YarnException { String interned = intern(key); synchronized (interned) { super.cleanResourceReferences(key); } } /** * Removes the given resource from the store. Returns true if the resource is * found and removed or if the resource is not found. Returns false if it was * unable to remove the resource because the resource reference list was not * empty. */ @Override public boolean removeResource(String key) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource == null) { return true; } if (!resource.getResourceReferences().isEmpty()) { return false; } // no users cachedResources.remove(interned); return true; } } /** * Obtains the access time for a resource. It represents the view of the * resource at the time of the query. The value may have been updated at a * later point. * * @return the access time of the resource if found; -1 if the resource is not * found */ @VisibleForTesting long getAccessTime(String key) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); return resource == null ? -1 : resource.getAccessTime(); } } @Override public boolean isResourceEvictable(String key, FileStatus file) { synchronized (initialAppsLock) { if (initialApps.size() > 0) { return false; } } long staleTime = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(this.stalenessMinutes); long accessTime = getAccessTime(key); if (accessTime == -1) { // check modification time long modTime = file.getModificationTime(); // if modification time is older then the store startup time, we need to // just use the store startup time as the last point of certainty long lastUse = modTime < this.startTime ? this.startTime : modTime; return lastUse < staleTime; } else { // check access time return accessTime < staleTime; } } private static int getStalenessPeriod(Configuration conf) { int stalenessMinutes = conf.getInt(YarnConfiguration.IN_MEMORY_STALENESS_PERIOD_MINS, YarnConfiguration.DEFAULT_IN_MEMORY_STALENESS_PERIOD_MINS); // non-positive value is invalid; use the default if (stalenessMinutes <= 0) { throw new HadoopIllegalArgumentException("Non-positive staleness value: " + stalenessMinutes + ". The staleness value must be greater than zero."); } return stalenessMinutes; } private static int getInitialDelay(Configuration conf) { int initialMinutes = conf.getInt(YarnConfiguration.IN_MEMORY_INITIAL_DELAY_MINS, YarnConfiguration.DEFAULT_IN_MEMORY_INITIAL_DELAY_MINS); // non-positive value is invalid; use the default if (initialMinutes <= 0) { throw new HadoopIllegalArgumentException( "Non-positive initial delay value: " + initialMinutes + ". The initial delay value must be greater than zero."); } return initialMinutes; } private static int getCheckPeriod(Configuration conf) { int checkMinutes = conf.getInt(YarnConfiguration.IN_MEMORY_CHECK_PERIOD_MINS, YarnConfiguration.DEFAULT_IN_MEMORY_CHECK_PERIOD_MINS); // non-positive value is invalid; use the default if (checkMinutes <= 0) { throw new HadoopIllegalArgumentException( "Non-positive check period value: " + checkMinutes + ". The check period value must be greater than zero."); } return checkMinutes; } @Private @Evolving class AppCheckTask implements Runnable { private final AppChecker taskAppChecker; public AppCheckTask(AppChecker appChecker) { this.taskAppChecker = appChecker; } @Override public void run() { try { LOG.info("Checking the initial app list for finished applications."); synchronized (initialAppsLock) { if (initialApps.isEmpty()) { // we're fine, no-op; there are no active apps that were running at // the time of the service start } else { LOG.info("Looking into " + initialApps.size() + " apps to see if they are still active"); Iterator<ApplicationId> it = initialApps.iterator(); while (it.hasNext()) { ApplicationId id = it.next(); try { if (!taskAppChecker.isApplicationActive(id)) { // remove it from the list it.remove(); } } catch (YarnException e) { LOG.warn("Exception while checking the app status;" + " will leave the entry in the list", e); // continue } } } LOG.info("There are now " + initialApps.size() + " entries in the list"); } } catch (Throwable e) { LOG.error( "Unexpected exception thrown during in-memory store app check task." + " Rescheduling task.", e); } } } }
19,019
35.506718
86
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/store/SharedCacheResourceReference.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.sharedcachemanager.store; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Evolving; import org.apache.hadoop.yarn.api.records.ApplicationId; /** * This is an object that represents a reference to a shared cache resource. */ @Private @Evolving public class SharedCacheResourceReference { private final ApplicationId appId; private final String shortUserName; /** * Create a resource reference. * * @param appId <code>ApplicationId</code> that is referencing a resource. * @param shortUserName <code>ShortUserName</code> of the user that created * the reference. */ public SharedCacheResourceReference(ApplicationId appId, String shortUserName) { this.appId = appId; this.shortUserName = shortUserName; } public ApplicationId getAppId() { return this.appId; } public String getShortUserName() { return this.shortUserName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((appId == null) ? 0 : appId.hashCode()); result = prime * result + ((shortUserName == null) ? 0 : shortUserName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SharedCacheResourceReference other = (SharedCacheResourceReference) obj; if (appId == null) { if (other.appId != null) return false; } else if (!appId.equals(other.appId)) return false; if (shortUserName == null) { if (other.shortUserName != null) return false; } else if (!shortUserName.equals(other.shortUserName)) return false; return true; } }
2,706
30.476744
82
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/store/SharedCacheResource.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.sharedcachemanager.store; import java.util.HashSet; import java.util.Set; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Evolving; /** * Class that encapsulates the cache resource. The instances are not thread * safe. Any operation that uses the resource must use thread-safe mechanisms to * ensure safe access with the only exception of the filename. */ @Private @Evolving class SharedCacheResource { private long accessTime; private final Set<SharedCacheResourceReference> refs; private final String fileName; SharedCacheResource(String fileName) { this.accessTime = System.currentTimeMillis(); this.refs = new HashSet<SharedCacheResourceReference>(); this.fileName = fileName; } long getAccessTime() { return accessTime; } void updateAccessTime() { accessTime = System.currentTimeMillis(); } String getFileName() { return this.fileName; } Set<SharedCacheResourceReference> getResourceReferences() { return this.refs; } boolean addReference(SharedCacheResourceReference ref) { return this.refs.add(ref); } }
2,009
30.40625
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/test/YarnTestDriver.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.test; import org.apache.hadoop.util.ProgramDriver; import org.apache.hadoop.yarn.server.resourcemanager.recovery.TestZKRMStateStorePerf; /** * Driver for Yarn tests. * */ public class YarnTestDriver { private ProgramDriver pgd; public YarnTestDriver() { this(new ProgramDriver()); } public YarnTestDriver(ProgramDriver pgd) { this.pgd = pgd; try { pgd.addClass(TestZKRMStateStorePerf.class.getSimpleName(), TestZKRMStateStorePerf.class, "ZKRMStateStore i/o benchmark."); } catch(Throwable e) { e.printStackTrace(); } } public void run(String argv[]) { int exitCode = -1; try { exitCode = pgd.run(argv); } catch(Throwable e) { e.printStackTrace(); } System.exit(exitCode); } public static void main(String argv[]){ new YarnTestDriver().run(argv); } }
1,700
26.885246
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestContainerResourceUsage.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; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import org.apache.commons.lang.time.DateUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppMetrics; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AggregateAppResourceUsage; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestContainerResourceUsage { private YarnConfiguration conf; @Before public void setup() throws UnknownHostException { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); conf = new YarnConfiguration(); UserGroupInformation.setConfiguration(conf); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); } @After public void tearDown() { } @Test (timeout = 120000) public void testUsageWithOneAttemptAndOneContainer() throws Exception { MockRM rm = new MockRM(conf); rm.start(); MockNM nm = new MockNM("127.0.0.1:1234", 15120, rm.getResourceTrackerService()); nm.registerNode(); RMApp app0 = rm.submitApp(200); RMAppMetrics rmAppMetrics = app0.getRMAppMetrics(); Assert.assertTrue( "Before app submittion, memory seconds should have been 0 but was " + rmAppMetrics.getMemorySeconds(), rmAppMetrics.getMemorySeconds() == 0); Assert.assertTrue( "Before app submission, vcore seconds should have been 0 but was " + rmAppMetrics.getVcoreSeconds(), rmAppMetrics.getVcoreSeconds() == 0); RMAppAttempt attempt0 = app0.getCurrentAppAttempt(); nm.nodeHeartbeat(true); MockAM am0 = rm.sendAMLaunched(attempt0.getAppAttemptId()); am0.registerAppAttempt(); RMContainer rmContainer = rm.getResourceScheduler() .getRMContainer(attempt0.getMasterContainer().getId()); // Allow metrics to accumulate. int sleepInterval = 1000; int cumulativeSleepTime = 0; while (rmAppMetrics.getMemorySeconds() <= 0 && cumulativeSleepTime < 5000) { Thread.sleep(sleepInterval); cumulativeSleepTime += sleepInterval; } rmAppMetrics = app0.getRMAppMetrics(); Assert.assertTrue( "While app is running, memory seconds should be >0 but is " + rmAppMetrics.getMemorySeconds(), rmAppMetrics.getMemorySeconds() > 0); Assert.assertTrue( "While app is running, vcore seconds should be >0 but is " + rmAppMetrics.getVcoreSeconds(), rmAppMetrics.getVcoreSeconds() > 0); MockRM.finishAMAndVerifyAppState(app0, rm, nm, am0); AggregateAppResourceUsage ru = calculateContainerResourceMetrics(rmContainer); rmAppMetrics = app0.getRMAppMetrics(); Assert.assertEquals("Unexcpected MemorySeconds value", ru.getMemorySeconds(), rmAppMetrics.getMemorySeconds()); Assert.assertEquals("Unexpected VcoreSeconds value", ru.getVcoreSeconds(), rmAppMetrics.getVcoreSeconds()); rm.stop(); } @Test (timeout = 120000) public void testUsageWithMultipleContainersAndRMRestart() throws Exception { // Set max attempts to 1 so that when the first attempt fails, the app // won't try to start a new one. conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); conf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); conf.setBoolean(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_ENABLED, false); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm0 = new MockRM(conf, memStore); rm0.start(); MockNM nm = new MockNM("127.0.0.1:1234", 65536, rm0.getResourceTrackerService()); nm.registerNode(); RMApp app0 = rm0.submitApp(200); rm0.waitForState(app0.getApplicationId(), RMAppState.ACCEPTED); RMAppAttempt attempt0 = app0.getCurrentAppAttempt(); ApplicationAttemptId attemptId0 = attempt0.getAppAttemptId(); rm0.waitForState(attemptId0, RMAppAttemptState.SCHEDULED); nm.nodeHeartbeat(true); rm0.waitForState(attemptId0, RMAppAttemptState.ALLOCATED); MockAM am0 = rm0.sendAMLaunched(attempt0.getAppAttemptId()); am0.registerAppAttempt(); int NUM_CONTAINERS = 2; am0.allocate("127.0.0.1" , 1000, NUM_CONTAINERS, new ArrayList<ContainerId>()); nm.nodeHeartbeat(true); List<Container> conts = am0.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (conts.size() != NUM_CONTAINERS) { nm.nodeHeartbeat(true); conts.addAll(am0.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } // launch the 2nd and 3rd containers. for (Container c : conts) { nm.nodeHeartbeat(attempt0.getAppAttemptId(), c.getId().getContainerId(), ContainerState.RUNNING); rm0.waitForState(nm, c.getId(), RMContainerState.RUNNING); } // Get the RMContainers for all of the live containers, to be used later // for metrics calculations and comparisons. Collection<RMContainer> rmContainers = rm0.scheduler .getSchedulerAppInfo(attempt0.getAppAttemptId()) .getLiveContainers(); // Allow metrics to accumulate. int sleepInterval = 1000; int cumulativeSleepTime = 0; while (app0.getRMAppMetrics().getMemorySeconds() <= 0 && cumulativeSleepTime < 5000) { Thread.sleep(sleepInterval); cumulativeSleepTime += sleepInterval; } // Stop all non-AM containers for (Container c : conts) { if (c.getId().getContainerId() == 1) continue; nm.nodeHeartbeat(attempt0.getAppAttemptId(), c.getId().getContainerId(), ContainerState.COMPLETE); rm0.waitForState(nm, c.getId(), RMContainerState.COMPLETED); } // After all other containers have completed, manually complete the master // container in order to trigger a save to the state store of the resource // usage metrics. This will cause the attempt to fail, and, since the max // attempt retries is 1, the app will also fail. This is intentional so // that all containers will complete prior to saving. ContainerId cId = ContainerId.newContainerId(attempt0.getAppAttemptId(), 1); nm.nodeHeartbeat(attempt0.getAppAttemptId(), cId.getContainerId(), ContainerState.COMPLETE); rm0.waitForState(nm, cId, RMContainerState.COMPLETED); // Check that the container metrics match those from the app usage report. long memorySeconds = 0; long vcoreSeconds = 0; for (RMContainer c : rmContainers) { AggregateAppResourceUsage ru = calculateContainerResourceMetrics(c); memorySeconds += ru.getMemorySeconds(); vcoreSeconds += ru.getVcoreSeconds(); } RMAppMetrics metricsBefore = app0.getRMAppMetrics(); Assert.assertEquals("Unexcpected MemorySeconds value", memorySeconds, metricsBefore.getMemorySeconds()); Assert.assertEquals("Unexpected VcoreSeconds value", vcoreSeconds, metricsBefore.getVcoreSeconds()); // create new RM to represent RM restart. Load up the state store. MockRM rm1 = new MockRM(conf, memStore); rm1.start(); RMApp app0After = rm1.getRMContext().getRMApps().get(app0.getApplicationId()); // Compare container resource usage metrics from before and after restart. RMAppMetrics metricsAfter = app0After.getRMAppMetrics(); Assert.assertEquals("Vcore seconds were not the same after RM Restart", metricsBefore.getVcoreSeconds(), metricsAfter.getVcoreSeconds()); Assert.assertEquals("Memory seconds were not the same after RM Restart", metricsBefore.getMemorySeconds(), metricsAfter.getMemorySeconds()); rm0.stop(); rm0.close(); rm1.stop(); rm1.close(); } @Test(timeout = 60000) public void testUsageAfterAMRestartWithMultipleContainers() throws Exception { amRestartTests(false); } @Test(timeout = 60000) public void testUsageAfterAMRestartKeepContainers() throws Exception { amRestartTests(true); } private void amRestartTests(boolean keepRunningContainers) throws Exception { MockRM rm = new MockRM(conf); rm.start(); RMApp app = rm.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null, "MAPREDUCE", false, keepRunningContainers); MockNM nm = new MockNM("127.0.0.1:1234", 10240, rm.getResourceTrackerService()); nm.registerNode(); MockAM am0 = MockRM.launchAndRegisterAM(app, rm, nm); int NUM_CONTAINERS = 1; // allocate NUM_CONTAINERS containers am0.allocate("127.0.0.1", 1024, NUM_CONTAINERS, new ArrayList<ContainerId>()); nm.nodeHeartbeat(true); // wait for containers to be allocated. List<Container> containers = am0.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (containers.size() != NUM_CONTAINERS) { nm.nodeHeartbeat(true); containers.addAll(am0.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(200); } // launch the 2nd container. ContainerId containerId2 = ContainerId.newContainerId(am0.getApplicationAttemptId(), 2); nm.nodeHeartbeat(am0.getApplicationAttemptId(), containerId2.getContainerId(), ContainerState.RUNNING); rm.waitForState(nm, containerId2, RMContainerState.RUNNING); // Capture the containers here so the metrics can be calculated after the // app has completed. Collection<RMContainer> rmContainers = rm.scheduler .getSchedulerAppInfo(am0.getApplicationAttemptId()) .getLiveContainers(); // fail the first app attempt by sending CONTAINER_FINISHED event without // registering. ContainerId amContainerId = app.getCurrentAppAttempt().getMasterContainer().getId(); nm.nodeHeartbeat(am0.getApplicationAttemptId(), amContainerId.getContainerId(), ContainerState.COMPLETE); am0.waitForState(RMAppAttemptState.FAILED); long memorySeconds = 0; long vcoreSeconds = 0; // Calculate container usage metrics for first attempt. if (keepRunningContainers) { // Only calculate the usage for the one container that has completed. for (RMContainer c : rmContainers) { if (c.getContainerId().equals(amContainerId)) { AggregateAppResourceUsage ru = calculateContainerResourceMetrics(c); memorySeconds += ru.getMemorySeconds(); vcoreSeconds += ru.getVcoreSeconds(); } else { // The remaining container should be RUNNING. Assert.assertTrue("After first attempt failed, remaining container " + "should still be running. ", c.getContainerState().equals(ContainerState.RUNNING)); } } } else { // If keepRunningContainers is false, all live containers should now // be completed. Calculate the resource usage metrics for all of them. for (RMContainer c : rmContainers) { AggregateAppResourceUsage ru = calculateContainerResourceMetrics(c); memorySeconds += ru.getMemorySeconds(); vcoreSeconds += ru.getVcoreSeconds(); } } // wait for app to start a new attempt. rm.waitForState(app.getApplicationId(), RMAppState.ACCEPTED); // assert this is a new AM. RMAppAttempt attempt2 = app.getCurrentAppAttempt(); Assert.assertFalse(attempt2.getAppAttemptId() .equals(am0.getApplicationAttemptId())); // launch the new AM nm.nodeHeartbeat(true); MockAM am1 = rm.sendAMLaunched(attempt2.getAppAttemptId()); am1.registerAppAttempt(); // allocate NUM_CONTAINERS containers am1.allocate("127.0.0.1", 1024, NUM_CONTAINERS, new ArrayList<ContainerId>()); nm.nodeHeartbeat(true); // wait for containers to be allocated. containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (containers.size() != NUM_CONTAINERS) { nm.nodeHeartbeat(true); containers.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(200); } rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); // Capture running containers for later use by metrics calculations. rmContainers = rm.scheduler.getSchedulerAppInfo(attempt2.getAppAttemptId()) .getLiveContainers(); // complete container by sending the container complete event which has // earlier attempt's attemptId amContainerId = app.getCurrentAppAttempt().getMasterContainer().getId(); nm.nodeHeartbeat(am0.getApplicationAttemptId(), amContainerId.getContainerId(), ContainerState.COMPLETE); MockRM.finishAMAndVerifyAppState(app, rm, nm, am1); // Calculate container usage metrics for second attempt. for (RMContainer c : rmContainers) { AggregateAppResourceUsage ru = calculateContainerResourceMetrics(c); memorySeconds += ru.getMemorySeconds(); vcoreSeconds += ru.getVcoreSeconds(); } RMAppMetrics rmAppMetrics = app.getRMAppMetrics(); Assert.assertEquals("Unexcpected MemorySeconds value", memorySeconds, rmAppMetrics.getMemorySeconds()); Assert.assertEquals("Unexpected VcoreSeconds value", vcoreSeconds, rmAppMetrics.getVcoreSeconds()); rm.stop(); return; } private AggregateAppResourceUsage calculateContainerResourceMetrics( RMContainer rmContainer) { Resource resource = rmContainer.getContainer().getResource(); long usedMillis = rmContainer.getFinishTime() - rmContainer.getCreationTime(); long memorySeconds = resource.getMemory() * usedMillis / DateUtils.MILLIS_PER_SECOND; long vcoreSeconds = resource.getVirtualCores() * usedMillis / DateUtils.MILLIS_PER_SECOND; return new AggregateAppResourceUsage(memorySeconds, vcoreSeconds); } }
16,526
39.016949
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/RMHATestBase.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; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.ClientBaseWithFixes; import org.apache.hadoop.ha.HAServiceProtocol; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.HAUtil; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; public class RMHATestBase extends ClientBaseWithFixes{ private static final int ZK_TIMEOUT_MS = 5000; private static StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); protected Configuration configuration = new YarnConfiguration(); static MockRM rm1 = null; static MockRM rm2 = null; Configuration confForRM1; Configuration confForRM2; @Before public void setup() throws Exception { configuration.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); configuration.set(YarnConfiguration.RM_HA_IDS, "rm1,rm2"); configuration.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); configuration.set(YarnConfiguration.RM_STORE, ZKRMStateStore.class.getName()); configuration.set(YarnConfiguration.RM_ZK_ADDRESS, hostPort); configuration.setInt(YarnConfiguration.RM_ZK_TIMEOUT_MS, ZK_TIMEOUT_MS); configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); configuration.set(YarnConfiguration.RM_CLUSTER_ID, "test-yarn-cluster"); int base = 100; for (String confKey : YarnConfiguration .getServiceAddressConfKeys(configuration)) { configuration.set(HAUtil.addSuffix(confKey, "rm1"), "0.0.0.0:" + (base + 20)); configuration.set(HAUtil.addSuffix(confKey, "rm2"), "0.0.0.0:" + (base + 40)); base = base * 2; } confForRM1 = new Configuration(configuration); confForRM1.set(YarnConfiguration.RM_HA_ID, "rm1"); confForRM2 = new Configuration(configuration); confForRM2.set(YarnConfiguration.RM_HA_ID, "rm2"); } @After public void teardown() { if (rm1 != null) { rm1.stop(); } if (rm2 != null) { rm2.stop(); } } protected MockAM launchAM(RMApp app, MockRM rm, MockNM nm) throws Exception { RMAppAttempt attempt = app.getCurrentAppAttempt(); nm.nodeHeartbeat(true); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); rm.waitForState(app.getCurrentAppAttempt().getAppAttemptId(), RMAppAttemptState.RUNNING); return am; } protected void startRMs() throws IOException { rm1 = new MockRM(confForRM1, null, false); rm2 = new MockRM(confForRM2, null, false); startRMs(rm1, confForRM1, rm2, confForRM2); } protected void startRMsWithCustomizedRMAppManager() throws IOException { final Configuration conf1 = new Configuration(confForRM1); rm1 = new MockRM(conf1) { @Override protected RMAppManager createRMAppManager() { return new MyRMAppManager(this.rmContext, this.scheduler, this.masterService, this.applicationACLsManager, conf1); } }; rm2 = new MockRM(confForRM2); startRMs(rm1, conf1, rm2, confForRM2); } private static class MyRMAppManager extends RMAppManager { private Configuration conf; private RMContext rmContext; public MyRMAppManager(RMContext context, YarnScheduler scheduler, ApplicationMasterService masterService, ApplicationACLsManager applicationACLsManager, Configuration conf) { super(context, scheduler, masterService, applicationACLsManager, conf); this.conf = conf; this.rmContext = context; } @Override protected void submitApplication( ApplicationSubmissionContext submissionContext, long submitTime, String user) throws YarnException { //Do nothing, just add the application to RMContext RMAppImpl application = new RMAppImpl(submissionContext.getApplicationId(), this.rmContext, this.conf, submissionContext.getApplicationName(), user, submissionContext.getQueue(), submissionContext, this.rmContext.getScheduler(), this.rmContext.getApplicationMasterService(), submitTime, submissionContext.getApplicationType(), submissionContext.getApplicationTags(), null); this.rmContext.getRMApps().put(submissionContext.getApplicationId(), application); //Do not send RMAppEventType.START event //so the state of Application will not reach to NEW_SAVING state. } } protected boolean isFinalState(RMAppState state) { return state.equals(RMAppState.FINISHING) || state.equals(RMAppState.FINISHED) || state.equals(RMAppState.FAILED) || state.equals(RMAppState.KILLED); } protected void explicitFailover() throws IOException { rm1.adminService.transitionToStandby(requestInfo); rm2.adminService.transitionToActive(requestInfo); Assert.assertTrue(rm1.getRMContext().getHAServiceState() == HAServiceState.STANDBY); Assert.assertTrue(rm2.getRMContext().getHAServiceState() == HAServiceState.ACTIVE); } protected void startRMs(MockRM rm1, Configuration confForRM1, MockRM rm2, Configuration confForRM2) throws IOException { rm1.init(confForRM1); rm1.start(); Assert.assertTrue(rm1.getRMContext().getHAServiceState() == HAServiceState.STANDBY); rm2.init(confForRM2); rm2.start(); Assert.assertTrue(rm2.getRMContext().getHAServiceState() == HAServiceState.STANDBY); rm1.adminService.transitionToActive(requestInfo); Assert.assertTrue(rm1.getRMContext().getHAServiceState() == HAServiceState.ACTIVE); } }
7,692
38.25
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClientRMTokens.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import org.apache.hadoop.net.NetUtils; import org.junit.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.Text; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.Server; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; import org.apache.hadoop.security.token.SecretManager; import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.CancelDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.RenewDelegationTokenRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.recovery.NullRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.security.QueueACLsManager; import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import org.junit.Before; import org.junit.Test; public class TestClientRMTokens { private static final Log LOG = LogFactory.getLog(TestClientRMTokens.class); @Before public void resetSecretManager() { RMDelegationTokenIdentifier.Renewer.setSecretManager(null, null); } @Test public void testDelegationToken() throws IOException, InterruptedException { final YarnConfiguration conf = new YarnConfiguration(); conf.set(YarnConfiguration.RM_PRINCIPAL, "testuser/[email protected]"); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); ResourceScheduler scheduler = createMockScheduler(conf); long initialInterval = 10000l; long maxLifetime= 20000l; long renewInterval = 10000l; RMDelegationTokenSecretManager rmDtSecretManager = createRMDelegationTokenSecretManager( initialInterval, maxLifetime, renewInterval); rmDtSecretManager.startThreads(); LOG.info("Creating DelegationTokenSecretManager with initialInterval: " + initialInterval + ", maxLifetime: " + maxLifetime + ", renewInterval: " + renewInterval); final ClientRMService clientRMService = new ClientRMServiceForTest(conf, scheduler, rmDtSecretManager); clientRMService.init(conf); clientRMService.start(); ApplicationClientProtocol clientRMWithDT = null; try { // Create a user for the renewr and fake the authentication-method UserGroupInformation loggedInUser = UserGroupInformation .createRemoteUser("[email protected]"); Assert.assertEquals("testrenewer", loggedInUser.getShortUserName()); // Default realm is APACHE.ORG loggedInUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); org.apache.hadoop.yarn.api.records.Token token = getDelegationToken(loggedInUser, clientRMService, loggedInUser.getShortUserName()); long tokenFetchTime = System.currentTimeMillis(); LOG.info("Got delegation token at: " + tokenFetchTime); // Now try talking to RMService using the delegation token clientRMWithDT = getClientRMProtocolWithDT(token, clientRMService.getBindAddress(), "loginuser1", conf); GetNewApplicationRequest request = Records.newRecord(GetNewApplicationRequest.class); try { clientRMWithDT.getNewApplication(request); } catch (IOException e) { fail("Unexpected exception" + e); } catch (YarnException e) { fail("Unexpected exception" + e); } // Renew after 50% of token age. while(System.currentTimeMillis() < tokenFetchTime + initialInterval / 2) { Thread.sleep(500l); } long nextExpTime = renewDelegationToken(loggedInUser, clientRMService, token); long renewalTime = System.currentTimeMillis(); LOG.info("Renewed token at: " + renewalTime + ", NextExpiryTime: " + nextExpTime); // Wait for first expiry, but before renewed expiry. while (System.currentTimeMillis() > tokenFetchTime + initialInterval && System.currentTimeMillis() < nextExpTime) { Thread.sleep(500l); } Thread.sleep(50l); // Valid token because of renewal. try { clientRMWithDT.getNewApplication(request); } catch (IOException e) { fail("Unexpected exception" + e); } catch (YarnException e) { fail("Unexpected exception" + e); } // Wait for expiry. while(System.currentTimeMillis() < renewalTime + renewInterval) { Thread.sleep(500l); } Thread.sleep(50l); LOG.info("At time: " + System.currentTimeMillis() + ", token should be invalid"); // Token should have expired. try { clientRMWithDT.getNewApplication(request); fail("Should not have succeeded with an expired token"); } catch (Exception e) { assertEquals(InvalidToken.class.getName(), e.getClass().getName()); assertTrue(e.getMessage().contains("is expired")); } // Test cancellation // Stop the existing proxy, start another. if (clientRMWithDT != null) { RPC.stopProxy(clientRMWithDT); clientRMWithDT = null; } token = getDelegationToken(loggedInUser, clientRMService, loggedInUser.getShortUserName()); tokenFetchTime = System.currentTimeMillis(); LOG.info("Got delegation token at: " + tokenFetchTime); // Now try talking to RMService using the delegation token clientRMWithDT = getClientRMProtocolWithDT(token, clientRMService.getBindAddress(), "loginuser2", conf); request = Records.newRecord(GetNewApplicationRequest.class); try { clientRMWithDT.getNewApplication(request); } catch (IOException e) { fail("Unexpected exception" + e); } catch (YarnException e) { fail("Unexpected exception" + e); } cancelDelegationToken(loggedInUser, clientRMService, token); if (clientRMWithDT != null) { RPC.stopProxy(clientRMWithDT); clientRMWithDT = null; } // Creating a new connection. clientRMWithDT = getClientRMProtocolWithDT(token, clientRMService.getBindAddress(), "loginuser2", conf); LOG.info("Cancelled delegation token at: " + System.currentTimeMillis()); // Verify cancellation worked. try { clientRMWithDT.getNewApplication(request); fail("Should not have succeeded with a cancelled delegation token"); } catch (IOException e) { } catch (YarnException e) { } // Test new version token // Stop the existing proxy, start another. if (clientRMWithDT != null) { RPC.stopProxy(clientRMWithDT); clientRMWithDT = null; } token = getDelegationToken(loggedInUser, clientRMService, loggedInUser.getShortUserName()); byte[] tokenIdentifierContent = token.getIdentifier().array(); RMDelegationTokenIdentifier tokenIdentifier = new RMDelegationTokenIdentifier(); DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenIdentifierContent, tokenIdentifierContent.length); tokenIdentifier.readFields(dib); // Construct new version RMDelegationTokenIdentifier with additional field RMDelegationTokenIdentifierForTest newVersionTokenIdentifier = new RMDelegationTokenIdentifierForTest(tokenIdentifier, "message"); Token<RMDelegationTokenIdentifier> newRMDTtoken = new Token<RMDelegationTokenIdentifier>(newVersionTokenIdentifier, rmDtSecretManager); org.apache.hadoop.yarn.api.records.Token newToken = BuilderUtils.newDelegationToken( newRMDTtoken.getIdentifier(), newRMDTtoken.getKind().toString(), newRMDTtoken.getPassword(), newRMDTtoken.getService().toString() ); // Now try talking to RMService using the new version delegation token clientRMWithDT = getClientRMProtocolWithDT(newToken, clientRMService.getBindAddress(), "loginuser3", conf); request = Records.newRecord(GetNewApplicationRequest.class); try { clientRMWithDT.getNewApplication(request); } catch (IOException e) { fail("Unexpected exception" + e); } catch (YarnException e) { fail("Unexpected exception" + e); } } finally { rmDtSecretManager.stopThreads(); // TODO PRECOMMIT Close proxies. if (clientRMWithDT != null) { RPC.stopProxy(clientRMWithDT); } } } @Test public void testShortCircuitRenewCancel() throws IOException, InterruptedException { InetSocketAddress addr = NetUtils.createSocketAddr( InetAddress.getLocalHost().getHostName(), 123, null); checkShortCircuitRenewCancel(addr, addr, true); } @Test public void testShortCircuitRenewCancelWildcardAddress() throws IOException, InterruptedException { InetSocketAddress rmAddr = new InetSocketAddress(123); InetSocketAddress serviceAddr = NetUtils.createSocketAddr( InetAddress.getLocalHost().getHostName(), rmAddr.getPort(), null); checkShortCircuitRenewCancel( rmAddr, serviceAddr, true); } @Test public void testShortCircuitRenewCancelSameHostDifferentPort() throws IOException, InterruptedException { InetSocketAddress rmAddr = NetUtils.createSocketAddr( InetAddress.getLocalHost().getHostName(), 123, null); checkShortCircuitRenewCancel( rmAddr, new InetSocketAddress(rmAddr.getAddress(), rmAddr.getPort()+1), false); } @Test public void testShortCircuitRenewCancelDifferentHostSamePort() throws IOException, InterruptedException { InetSocketAddress rmAddr = NetUtils.createSocketAddr( InetAddress.getLocalHost().getHostName(), 123, null); checkShortCircuitRenewCancel( rmAddr, new InetSocketAddress("1.1.1.1", rmAddr.getPort()), false); } @Test public void testShortCircuitRenewCancelDifferentHostDifferentPort() throws IOException, InterruptedException { InetSocketAddress rmAddr = NetUtils.createSocketAddr( InetAddress.getLocalHost().getHostName(), 123, null); checkShortCircuitRenewCancel( rmAddr, new InetSocketAddress("1.1.1.1", rmAddr.getPort()+1), false); } @SuppressWarnings("unchecked") private void checkShortCircuitRenewCancel(InetSocketAddress rmAddr, InetSocketAddress serviceAddr, boolean shouldShortCircuit ) throws IOException, InterruptedException { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.IPC_RPC_IMPL, YarnBadRPC.class, YarnRPC.class); RMDelegationTokenSecretManager secretManager = mock(RMDelegationTokenSecretManager.class); RMDelegationTokenIdentifier.Renewer.setSecretManager(secretManager, rmAddr); RMDelegationTokenIdentifier ident = new RMDelegationTokenIdentifier( new Text("owner"), new Text("renewer"), null); Token<RMDelegationTokenIdentifier> token = new Token<RMDelegationTokenIdentifier>(ident, secretManager); SecurityUtil.setTokenService(token, serviceAddr); if (shouldShortCircuit) { token.renew(conf); verify(secretManager).renewToken(eq(token), eq("renewer")); reset(secretManager); token.cancel(conf); verify(secretManager).cancelToken(eq(token), eq("renewer")); } else { try { token.renew(conf); fail(); } catch (RuntimeException e) { assertEquals("getProxy", e.getMessage()); } verify(secretManager, never()).renewToken(any(Token.class), anyString()); try { token.cancel(conf); fail(); } catch (RuntimeException e) { assertEquals("getProxy", e.getMessage()); } verify(secretManager, never()).cancelToken(any(Token.class), anyString()); } } @SuppressWarnings("rawtypes") public static class YarnBadRPC extends YarnRPC { @Override public Object getProxy(Class protocol, InetSocketAddress addr, Configuration conf) { throw new RuntimeException("getProxy"); } @Override public void stopProxy(Object proxy, Configuration conf) { throw new RuntimeException("stopProxy"); } @Override public Server getServer(Class protocol, Object instance, InetSocketAddress addr, Configuration conf, SecretManager<? extends TokenIdentifier> secretManager, int numHandlers, String portRangeConfig) { throw new RuntimeException("getServer"); } } // Get the delegation token directly as it is a little difficult to setup // the kerberos based rpc. private org.apache.hadoop.yarn.api.records.Token getDelegationToken( final UserGroupInformation loggedInUser, final ApplicationClientProtocol clientRMService, final String renewerString) throws IOException, InterruptedException { org.apache.hadoop.yarn.api.records.Token token = loggedInUser .doAs(new PrivilegedExceptionAction<org.apache.hadoop.yarn.api.records.Token>() { @Override public org.apache.hadoop.yarn.api.records.Token run() throws YarnException, IOException { GetDelegationTokenRequest request = Records .newRecord(GetDelegationTokenRequest.class); request.setRenewer(renewerString); return clientRMService.getDelegationToken(request) .getRMDelegationToken(); } }); return token; } private long renewDelegationToken(final UserGroupInformation loggedInUser, final ApplicationClientProtocol clientRMService, final org.apache.hadoop.yarn.api.records.Token dToken) throws IOException, InterruptedException { long nextExpTime = loggedInUser.doAs(new PrivilegedExceptionAction<Long>() { @Override public Long run() throws YarnException, IOException { RenewDelegationTokenRequest request = Records .newRecord(RenewDelegationTokenRequest.class); request.setDelegationToken(dToken); return clientRMService.renewDelegationToken(request) .getNextExpirationTime(); } }); return nextExpTime; } private void cancelDelegationToken(final UserGroupInformation loggedInUser, final ApplicationClientProtocol clientRMService, final org.apache.hadoop.yarn.api.records.Token dToken) throws IOException, InterruptedException { loggedInUser.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws YarnException, IOException { CancelDelegationTokenRequest request = Records .newRecord(CancelDelegationTokenRequest.class); request.setDelegationToken(dToken); clientRMService.cancelDelegationToken(request); return null; } }); } private ApplicationClientProtocol getClientRMProtocolWithDT( org.apache.hadoop.yarn.api.records.Token token, final InetSocketAddress rmAddress, String user, final Configuration conf) { // Maybe consider converting to Hadoop token, serialize de-serialize etc // before trying to renew the token. UserGroupInformation ugi = UserGroupInformation .createRemoteUser(user); ugi.addToken(ConverterUtils.convertFromYarn(token, rmAddress)); final YarnRPC rpc = YarnRPC.create(conf); ApplicationClientProtocol clientRMWithDT = ugi .doAs(new PrivilegedAction<ApplicationClientProtocol>() { @Override public ApplicationClientProtocol run() { return (ApplicationClientProtocol) rpc.getProxy(ApplicationClientProtocol.class, rmAddress, conf); } }); return clientRMWithDT; } class ClientRMServiceForTest extends ClientRMService { public ClientRMServiceForTest(Configuration conf, ResourceScheduler scheduler, RMDelegationTokenSecretManager rmDTSecretManager) { super(mock(RMContext.class), scheduler, mock(RMAppManager.class), new ApplicationACLsManager(conf), new QueueACLsManager(scheduler, conf), rmDTSecretManager); } // Use a random port unless explicitly specified. @Override InetSocketAddress getBindAddress(Configuration conf) { return conf.getSocketAddr(YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS, 0); } @Override protected void serviceStop() throws Exception { if (rmDTSecretManager != null) { rmDTSecretManager.stopThreads(); } super.serviceStop(); } } private static ResourceScheduler createMockScheduler(Configuration conf) { ResourceScheduler mockSched = mock(ResourceScheduler.class); doReturn(BuilderUtils.newResource(512, 0)).when(mockSched) .getMinimumResourceCapability(); doReturn(BuilderUtils.newResource(5120, 0)).when(mockSched) .getMaximumResourceCapability(); return mockSched; } private static RMDelegationTokenSecretManager createRMDelegationTokenSecretManager(long secretKeyInterval, long tokenMaxLifetime, long tokenRenewInterval) { RMContext rmContext = mock(RMContext.class); when(rmContext.getStateStore()).thenReturn(new NullRMStateStore()); RMDelegationTokenSecretManager rmDtSecretManager = new RMDelegationTokenSecretManager(secretKeyInterval, tokenMaxLifetime, tokenRenewInterval, 3600000, rmContext); return rmDtSecretManager; } }
20,355
37.921606
104
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationACLs.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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.service.Service.STATE; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; 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.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.QueueACL; 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.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreFactory; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.security.QueueACLsManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestApplicationACLs { private static final String APP_OWNER = "owner"; private static final String FRIEND = "friend"; private static final String ENEMY = "enemy"; private static final String QUEUE_ADMIN_USER = "queue-admin-user"; private static final String SUPER_USER = "superUser"; private static final String FRIENDLY_GROUP = "friendly-group"; private static final String SUPER_GROUP = "superGroup"; private static final String UNAVAILABLE = "N/A"; private static final Log LOG = LogFactory.getLog(TestApplicationACLs.class); static MockRM resourceManager; static Configuration conf = new YarnConfiguration(); final static YarnRPC rpc = YarnRPC.create(conf); final static InetSocketAddress rmAddress = conf.getSocketAddr( YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS, YarnConfiguration.DEFAULT_RM_PORT); private static ApplicationClientProtocol rmClient; private static RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(conf); private static boolean isQueueUser = false; @BeforeClass public static void setup() throws InterruptedException, IOException { RMStateStore store = RMStateStoreFactory.getStore(conf); conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); AccessControlList adminACL = new AccessControlList(""); adminACL.addGroup(SUPER_GROUP); conf.set(YarnConfiguration.YARN_ADMIN_ACL, adminACL.getAclString()); resourceManager = new MockRM(conf) { @Override protected QueueACLsManager createQueueACLsManager( ResourceScheduler scheduler, Configuration conf) { QueueACLsManager mockQueueACLsManager = mock(QueueACLsManager.class); when(mockQueueACLsManager.checkAccess(any(UserGroupInformation.class), any(QueueACL.class), anyString())).thenAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { return isQueueUser; } }); return mockQueueACLsManager; } protected ClientRMService createClientRMService() { return new ClientRMService(getRMContext(), this.scheduler, this.rmAppManager, this.applicationACLsManager, this.queueACLsManager, null); }; }; new Thread() { public void run() { UserGroupInformation.createUserForTesting(ENEMY, new String[] {}); UserGroupInformation.createUserForTesting(FRIEND, new String[] { FRIENDLY_GROUP }); UserGroupInformation.createUserForTesting(SUPER_USER, new String[] { SUPER_GROUP }); resourceManager.start(); }; }.start(); int waitCount = 0; while (resourceManager.getServiceState() == STATE.INITED && waitCount++ < 60) { LOG.info("Waiting for RM to start..."); Thread.sleep(1500); } if (resourceManager.getServiceState() != STATE.STARTED) { // RM could have failed. throw new IOException( "ResourceManager failed to start. Final state is " + resourceManager.getServiceState()); } UserGroupInformation owner = UserGroupInformation .createRemoteUser(APP_OWNER); rmClient = owner.doAs(new PrivilegedExceptionAction<ApplicationClientProtocol>() { @Override public ApplicationClientProtocol run() throws Exception { return (ApplicationClientProtocol) rpc.getProxy(ApplicationClientProtocol.class, rmAddress, conf); } }); } @AfterClass public static void tearDown() { if(resourceManager != null) { resourceManager.stop(); } } @Test public void testApplicationACLs() throws Exception { verifyOwnerAccess(); verifySuperUserAccess(); verifyFriendAccess(); verifyEnemyAccess(); verifyAdministerQueueUserAccess(); } @SuppressWarnings("deprecation") private ApplicationId submitAppAndGetAppId(AccessControlList viewACL, AccessControlList modifyACL) throws Exception { SubmitApplicationRequest submitRequest = recordFactory .newRecordInstance(SubmitApplicationRequest.class); ApplicationSubmissionContext context = recordFactory .newRecordInstance(ApplicationSubmissionContext.class); ApplicationId applicationId = rmClient.getNewApplication( recordFactory.newRecordInstance(GetNewApplicationRequest.class)) .getApplicationId(); context.setApplicationId(applicationId); Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(); acls.put(ApplicationAccessType.VIEW_APP, viewACL.getAclString()); acls.put(ApplicationAccessType.MODIFY_APP, modifyACL.getAclString()); ContainerLaunchContext amContainer = recordFactory .newRecordInstance(ContainerLaunchContext.class); Resource resource = BuilderUtils.newResource(1024, 1); context.setResource(resource); amContainer.setApplicationACLs(acls); context.setAMContainerSpec(amContainer); submitRequest.setApplicationSubmissionContext(context); rmClient.submitApplication(submitRequest); resourceManager.waitForState(applicationId, RMAppState.ACCEPTED); return applicationId; } private ApplicationClientProtocol getRMClientForUser(String user) throws IOException, InterruptedException { UserGroupInformation userUGI = UserGroupInformation .createRemoteUser(user); ApplicationClientProtocol userClient = userUGI .doAs(new PrivilegedExceptionAction<ApplicationClientProtocol>() { @Override public ApplicationClientProtocol run() throws Exception { return (ApplicationClientProtocol) rpc.getProxy(ApplicationClientProtocol.class, rmAddress, conf); } }); return userClient; } private void verifyOwnerAccess() throws Exception { AccessControlList viewACL = new AccessControlList(""); viewACL.addGroup(FRIENDLY_GROUP); AccessControlList modifyACL = new AccessControlList(""); modifyACL.addUser(FRIEND); ApplicationId applicationId = submitAppAndGetAppId(viewACL, modifyACL); final GetApplicationReportRequest appReportRequest = recordFactory .newRecordInstance(GetApplicationReportRequest.class); appReportRequest.setApplicationId(applicationId); final KillApplicationRequest finishAppRequest = recordFactory .newRecordInstance(KillApplicationRequest.class); finishAppRequest.setApplicationId(applicationId); // View as owner rmClient.getApplicationReport(appReportRequest); // List apps as owner Assert.assertEquals("App view by owner should list the apps!!", 1, rmClient.getApplications( recordFactory.newRecordInstance(GetApplicationsRequest.class)) .getApplicationList().size()); // Kill app as owner rmClient.forceKillApplication(finishAppRequest); resourceManager.waitForState(applicationId, RMAppState.KILLED); } private void verifySuperUserAccess() throws Exception { AccessControlList viewACL = new AccessControlList(""); viewACL.addGroup(FRIENDLY_GROUP); AccessControlList modifyACL = new AccessControlList(""); modifyACL.addUser(FRIEND); ApplicationId applicationId = submitAppAndGetAppId(viewACL, modifyACL); final GetApplicationReportRequest appReportRequest = recordFactory .newRecordInstance(GetApplicationReportRequest.class); appReportRequest.setApplicationId(applicationId); final KillApplicationRequest finishAppRequest = recordFactory .newRecordInstance(KillApplicationRequest.class); finishAppRequest.setApplicationId(applicationId); ApplicationClientProtocol superUserClient = getRMClientForUser(SUPER_USER); // View as the superUser superUserClient.getApplicationReport(appReportRequest); // List apps as superUser Assert.assertEquals("App view by super-user should list the apps!!", 2, superUserClient.getApplications( recordFactory.newRecordInstance(GetApplicationsRequest.class)) .getApplicationList().size()); // Kill app as the superUser superUserClient.forceKillApplication(finishAppRequest); resourceManager.waitForState(applicationId, RMAppState.KILLED); } private void verifyFriendAccess() throws Exception { AccessControlList viewACL = new AccessControlList(""); viewACL.addGroup(FRIENDLY_GROUP); AccessControlList modifyACL = new AccessControlList(""); modifyACL.addUser(FRIEND); ApplicationId applicationId = submitAppAndGetAppId(viewACL, modifyACL); final GetApplicationReportRequest appReportRequest = recordFactory .newRecordInstance(GetApplicationReportRequest.class); appReportRequest.setApplicationId(applicationId); final KillApplicationRequest finishAppRequest = recordFactory .newRecordInstance(KillApplicationRequest.class); finishAppRequest.setApplicationId(applicationId); ApplicationClientProtocol friendClient = getRMClientForUser(FRIEND); // View as the friend friendClient.getApplicationReport(appReportRequest); // List apps as friend Assert.assertEquals("App view by a friend should list the apps!!", 3, friendClient.getApplications( recordFactory.newRecordInstance(GetApplicationsRequest.class)) .getApplicationList().size()); // Kill app as the friend friendClient.forceKillApplication(finishAppRequest); resourceManager.waitForState(applicationId, RMAppState.KILLED); } private void verifyEnemyAccess() throws Exception { AccessControlList viewACL = new AccessControlList(""); viewACL.addGroup(FRIENDLY_GROUP); AccessControlList modifyACL = new AccessControlList(""); modifyACL.addUser(FRIEND); ApplicationId applicationId = submitAppAndGetAppId(viewACL, modifyACL); final GetApplicationReportRequest appReportRequest = recordFactory .newRecordInstance(GetApplicationReportRequest.class); appReportRequest.setApplicationId(applicationId); final KillApplicationRequest finishAppRequest = recordFactory .newRecordInstance(KillApplicationRequest.class); finishAppRequest.setApplicationId(applicationId); ApplicationClientProtocol enemyRmClient = getRMClientForUser(ENEMY); // View as the enemy ApplicationReport appReport = enemyRmClient.getApplicationReport( appReportRequest).getApplicationReport(); verifyEnemyAppReport(appReport); // List apps as enemy List<ApplicationReport> appReports = enemyRmClient .getApplications(recordFactory .newRecordInstance(GetApplicationsRequest.class)) .getApplicationList(); Assert.assertEquals("App view by enemy should list the apps!!", 4, appReports.size()); for (ApplicationReport report : appReports) { verifyEnemyAppReport(report); } // Kill app as the enemy try { enemyRmClient.forceKillApplication(finishAppRequest); Assert.fail("App killing by the enemy should fail!!"); } catch (YarnException e) { LOG.info("Got exception while killing app as the enemy", e); Assert .assertTrue(e.getMessage().contains( "User enemy cannot perform operation MODIFY_APP on " + applicationId)); } rmClient.forceKillApplication(finishAppRequest); } private void verifyEnemyAppReport(ApplicationReport appReport) { Assert.assertEquals("Enemy should not see app host!", UNAVAILABLE, appReport.getHost()); Assert.assertEquals("Enemy should not see app rpc port!", -1, appReport.getRpcPort()); Assert.assertEquals("Enemy should not see app client token!", null, appReport.getClientToAMToken()); Assert.assertEquals("Enemy should not see app diagnostics!", UNAVAILABLE, appReport.getDiagnostics()); Assert.assertEquals("Enemy should not see app tracking url!", UNAVAILABLE, appReport.getTrackingUrl()); Assert.assertEquals("Enemy should not see app original tracking url!", UNAVAILABLE, appReport.getOriginalTrackingUrl()); ApplicationResourceUsageReport usageReport = appReport.getApplicationResourceUsageReport(); Assert.assertEquals("Enemy should not see app used containers", -1, usageReport.getNumUsedContainers()); Assert.assertEquals("Enemy should not see app reserved containers", -1, usageReport.getNumReservedContainers()); Assert.assertEquals("Enemy should not see app used resources", -1, usageReport.getUsedResources().getMemory()); Assert.assertEquals("Enemy should not see app reserved resources", -1, usageReport.getReservedResources().getMemory()); Assert.assertEquals("Enemy should not see app needed resources", -1, usageReport.getNeededResources().getMemory()); } private void verifyAdministerQueueUserAccess() throws Exception { isQueueUser = true; AccessControlList viewACL = new AccessControlList(""); viewACL.addGroup(FRIENDLY_GROUP); AccessControlList modifyACL = new AccessControlList(""); modifyACL.addUser(FRIEND); ApplicationId applicationId = submitAppAndGetAppId(viewACL, modifyACL); final GetApplicationReportRequest appReportRequest = recordFactory .newRecordInstance(GetApplicationReportRequest.class); appReportRequest.setApplicationId(applicationId); final KillApplicationRequest finishAppRequest = recordFactory .newRecordInstance(KillApplicationRequest.class); finishAppRequest.setApplicationId(applicationId); ApplicationClientProtocol administerQueueUserRmClient = getRMClientForUser(QUEUE_ADMIN_USER); // View as the administerQueueUserRmClient administerQueueUserRmClient.getApplicationReport(appReportRequest); // List apps as administerQueueUserRmClient Assert.assertEquals("App view by queue-admin-user should list the apps!!", 5, administerQueueUserRmClient.getApplications( recordFactory.newRecordInstance(GetApplicationsRequest.class)) .getApplicationList().size()); // Kill app as the administerQueueUserRmClient administerQueueUserRmClient.forceKillApplication(finishAppRequest); resourceManager.waitForState(applicationId, RMAppState.KILLED); } }
17,663
40.562353
92
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMNodeTransitions.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; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.hadoop.util.HostsFileReader; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceOption; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.event.InlineDispatcher; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; 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.rmnode.RMNodeCleanContainerEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeReconnectEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeStartedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeStatusEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType; import org.apache.hadoop.yarn.server.resourcemanager.security.DelegationTokenRenewer; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestRMNodeTransitions { RMNodeImpl node; private RMContext rmContext; private YarnScheduler scheduler; private SchedulerEventType eventType; private List<ContainerStatus> completedContainers = new ArrayList<ContainerStatus>(); private final class TestSchedulerEventDispatcher implements EventHandler<SchedulerEvent> { @Override public void handle(SchedulerEvent event) { scheduler.handle(event); } } private NodesListManagerEvent nodesListManagerEvent = null; private class TestNodeListManagerEventDispatcher implements EventHandler<NodesListManagerEvent> { @Override public void handle(NodesListManagerEvent event) { nodesListManagerEvent = event; } } @Before public void setUp() throws Exception { InlineDispatcher rmDispatcher = new InlineDispatcher(); rmContext = new RMContextImpl(rmDispatcher, mock(ContainerAllocationExpirer.class), null, null, mock(DelegationTokenRenewer.class), null, null, null, null, null); NodesListManager nodesListManager = mock(NodesListManager.class); HostsFileReader reader = mock(HostsFileReader.class); when(nodesListManager.getHostsReader()).thenReturn(reader); ((RMContextImpl) rmContext).setNodesListManager(nodesListManager); scheduler = mock(YarnScheduler.class); doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { final SchedulerEvent event = (SchedulerEvent)(invocation.getArguments()[0]); eventType = event.getType(); if (eventType == SchedulerEventType.NODE_UPDATE) { List<UpdatedContainerInfo> lastestContainersInfoList = ((NodeUpdateSchedulerEvent)event).getRMNode().pullContainerUpdates(); for(UpdatedContainerInfo lastestContainersInfo : lastestContainersInfoList) { completedContainers.addAll(lastestContainersInfo.getCompletedContainers()); } } return null; } } ).when(scheduler).handle(any(SchedulerEvent.class)); rmDispatcher.register(SchedulerEventType.class, new TestSchedulerEventDispatcher()); rmDispatcher.register(NodesListManagerEventType.class, new TestNodeListManagerEventDispatcher()); NodeId nodeId = BuilderUtils.newNodeId("localhost", 0); node = new RMNodeImpl(nodeId, rmContext, null, 0, 0, null, null, null); nodesListManagerEvent = null; } @After public void tearDown() throws Exception { } private RMNodeStatusEvent getMockRMNodeStatusEvent( List<ContainerStatus> containerStatus) { NodeHeartbeatResponse response = mock(NodeHeartbeatResponse.class); NodeHealthStatus healthStatus = mock(NodeHealthStatus.class); Boolean yes = new Boolean(true); doReturn(yes).when(healthStatus).getIsNodeHealthy(); RMNodeStatusEvent event = mock(RMNodeStatusEvent.class); doReturn(healthStatus).when(event).getNodeHealthStatus(); doReturn(response).when(event).getLatestResponse(); doReturn(RMNodeEventType.STATUS_UPDATE).when(event).getType(); if (containerStatus != null) { doReturn(containerStatus).when(event).getContainers(); } return event; } @Test (timeout = 5000) public void testExpiredContainer() { // Start the node node.handle(new RMNodeStartedEvent(null, null, null)); verify(scheduler).handle(any(NodeAddedSchedulerEvent.class)); // Expire a container ContainerId completedContainerId = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(0, 0), 0), 0); node.handle(new RMNodeCleanContainerEvent(null, completedContainerId)); Assert.assertEquals(1, node.getContainersToCleanUp().size()); // Now verify that scheduler isn't notified of an expired container // by checking number of 'completedContainers' it got in the previous event RMNodeStatusEvent statusEvent = getMockRMNodeStatusEvent(null); ContainerStatus containerStatus = mock(ContainerStatus.class); doReturn(completedContainerId).when(containerStatus).getContainerId(); doReturn(Collections.singletonList(containerStatus)). when(statusEvent).getContainers(); node.handle(statusEvent); /* Expect the scheduler call handle function 2 times * 1. RMNode status from new to Running, handle the add_node event * 2. handle the node update event */ verify(scheduler,times(2)).handle(any(NodeUpdateSchedulerEvent.class)); } @Test (timeout = 5000) public void testContainerUpdate() throws InterruptedException{ //Start the node node.handle(new RMNodeStartedEvent(null, null, null)); NodeId nodeId = BuilderUtils.newNodeId("localhost:1", 1); RMNodeImpl node2 = new RMNodeImpl(nodeId, rmContext, null, 0, 0, null, null, null); node2.handle(new RMNodeStartedEvent(null, null, null)); ContainerId completedContainerIdFromNode1 = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(0, 0), 0), 0); ContainerId completedContainerIdFromNode2_1 = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(1, 1), 1), 1); ContainerId completedContainerIdFromNode2_2 = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(1, 1), 1), 2); RMNodeStatusEvent statusEventFromNode1 = getMockRMNodeStatusEvent(null); RMNodeStatusEvent statusEventFromNode2_1 = getMockRMNodeStatusEvent(null); RMNodeStatusEvent statusEventFromNode2_2 = getMockRMNodeStatusEvent(null); ContainerStatus containerStatusFromNode1 = mock(ContainerStatus.class); ContainerStatus containerStatusFromNode2_1 = mock(ContainerStatus.class); ContainerStatus containerStatusFromNode2_2 = mock(ContainerStatus.class); doReturn(completedContainerIdFromNode1).when(containerStatusFromNode1) .getContainerId(); doReturn(Collections.singletonList(containerStatusFromNode1)) .when(statusEventFromNode1).getContainers(); node.handle(statusEventFromNode1); Assert.assertEquals(1, completedContainers.size()); Assert.assertEquals(completedContainerIdFromNode1, completedContainers.get(0).getContainerId()); completedContainers.clear(); doReturn(completedContainerIdFromNode2_1).when(containerStatusFromNode2_1) .getContainerId(); doReturn(Collections.singletonList(containerStatusFromNode2_1)) .when(statusEventFromNode2_1).getContainers(); doReturn(completedContainerIdFromNode2_2).when(containerStatusFromNode2_2) .getContainerId(); doReturn(Collections.singletonList(containerStatusFromNode2_2)) .when(statusEventFromNode2_2).getContainers(); node2.setNextHeartBeat(false); node2.handle(statusEventFromNode2_1); node2.setNextHeartBeat(true); node2.handle(statusEventFromNode2_2); Assert.assertEquals(2, completedContainers.size()); Assert.assertEquals(completedContainerIdFromNode2_1,completedContainers.get(0) .getContainerId()); Assert.assertEquals(completedContainerIdFromNode2_2,completedContainers.get(1) .getContainerId()); } @Test (timeout = 5000) public void testStatusChange(){ //Start the node node.handle(new RMNodeStartedEvent(null, null, null)); //Add info to the queue first node.setNextHeartBeat(false); ContainerId completedContainerId1 = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(0, 0), 0), 0); ContainerId completedContainerId2 = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(1, 1), 1), 1); RMNodeStatusEvent statusEvent1 = getMockRMNodeStatusEvent(null); RMNodeStatusEvent statusEvent2 = getMockRMNodeStatusEvent(null); ContainerStatus containerStatus1 = mock(ContainerStatus.class); ContainerStatus containerStatus2 = mock(ContainerStatus.class); doReturn(completedContainerId1).when(containerStatus1).getContainerId(); doReturn(Collections.singletonList(containerStatus1)) .when(statusEvent1).getContainers(); doReturn(completedContainerId2).when(containerStatus2).getContainerId(); doReturn(Collections.singletonList(containerStatus2)) .when(statusEvent2).getContainers(); verify(scheduler,times(1)).handle(any(NodeUpdateSchedulerEvent.class)); node.handle(statusEvent1); node.handle(statusEvent2); verify(scheduler,times(1)).handle(any(NodeUpdateSchedulerEvent.class)); Assert.assertEquals(2, node.getQueueSize()); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.EXPIRE)); Assert.assertEquals(0, node.getQueueSize()); } @Test public void testRunningExpire() { RMNodeImpl node = getRunningNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.EXPIRE)); Assert.assertEquals("Active Nodes", initialActive - 1, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost + 1, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.LOST, node.getState()); } @Test public void testRunningExpireMultiple() { RMNodeImpl node1 = getRunningNode(null, 10001); RMNodeImpl node2 = getRunningNode(null, 10002); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node1.handle(new RMNodeEvent(node1.getNodeID(), RMNodeEventType.EXPIRE)); Assert.assertEquals("Active Nodes", initialActive - 1, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost + 1, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.LOST, node1.getState()); Assert.assertTrue("Node " + node1.toString() + " should be inactive", rmContext.getInactiveRMNodes().containsKey(node1.getNodeID())); Assert.assertFalse("Node " + node2.toString() + " should not be inactive", rmContext.getInactiveRMNodes().containsKey(node2.getNodeID())); node2.handle(new RMNodeEvent(node1.getNodeID(), RMNodeEventType.EXPIRE)); Assert.assertEquals("Active Nodes", initialActive - 2, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost + 2, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.LOST, node2.getState()); Assert.assertTrue("Node " + node1.toString() + " should be inactive", rmContext.getInactiveRMNodes().containsKey(node1.getNodeID())); Assert.assertTrue("Node " + node2.toString() + " should be inactive", rmContext.getInactiveRMNodes().containsKey(node2.getNodeID())); } @Test public void testUnhealthyExpire() { RMNodeImpl node = getUnhealthyNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.EXPIRE)); Assert.assertEquals("Active Nodes", initialActive, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost + 1, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy - 1, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.LOST, node.getState()); } @Test public void testUnhealthyExpireForSchedulerRemove() { RMNodeImpl node = getUnhealthyNode(); verify(scheduler,times(2)).handle(any(NodeRemovedSchedulerEvent.class)); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.EXPIRE)); verify(scheduler,times(2)).handle(any(NodeRemovedSchedulerEvent.class)); Assert.assertEquals(NodeState.LOST, node.getState()); } @Test public void testRunningDecommission() { RMNodeImpl node = getRunningNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.DECOMMISSION)); Assert.assertEquals("Active Nodes", initialActive - 1, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned + 1, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.DECOMMISSIONED, node.getState()); } @Test public void testUnhealthyDecommission() { RMNodeImpl node = getUnhealthyNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.DECOMMISSION)); Assert.assertEquals("Active Nodes", initialActive, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy - 1, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned + 1, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.DECOMMISSIONED, node.getState()); } @Test public void testRunningRebooting() { RMNodeImpl node = getRunningNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.REBOOTING)); Assert.assertEquals("Active Nodes", initialActive - 1, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted + 1, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.REBOOTED, node.getState()); } @Test public void testUnhealthyRebooting() { RMNodeImpl node = getUnhealthyNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.REBOOTING)); Assert.assertEquals("Active Nodes", initialActive, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy - 1, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted + 1, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.REBOOTED, node.getState()); } @Test public void testNMShutdown() { RMNodeImpl node = getRunningNode(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.SHUTDOWN)); Assert.assertEquals(NodeState.SHUTDOWN, node.getState()); } @Test public void testUnhealthyNMShutdown() { RMNodeImpl node = getUnhealthyNode(); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.SHUTDOWN)); Assert.assertEquals(NodeState.SHUTDOWN, node.getState()); } @Test(timeout=20000) public void testUpdateHeartbeatResponseForCleanup() { RMNodeImpl node = getRunningNode(); NodeId nodeId = node.getNodeID(); // Expire a container ContainerId completedContainerId = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( BuilderUtils.newApplicationId(0, 0), 0), 0); node.handle(new RMNodeCleanContainerEvent(nodeId, completedContainerId)); Assert.assertEquals(1, node.getContainersToCleanUp().size()); // Finish an application ApplicationId finishedAppId = BuilderUtils.newApplicationId(0, 1); node.handle(new RMNodeCleanAppEvent(nodeId, finishedAppId)); Assert.assertEquals(1, node.getAppsToCleanup().size()); // Verify status update does not clear containers/apps to cleanup // but updating heartbeat response for cleanup does RMNodeStatusEvent statusEvent = getMockRMNodeStatusEvent(null); node.handle(statusEvent); Assert.assertEquals(1, node.getContainersToCleanUp().size()); Assert.assertEquals(1, node.getAppsToCleanup().size()); NodeHeartbeatResponse hbrsp = Records.newRecord(NodeHeartbeatResponse.class); node.updateNodeHeartbeatResponseForCleanup(hbrsp); Assert.assertEquals(0, node.getContainersToCleanUp().size()); Assert.assertEquals(0, node.getAppsToCleanup().size()); Assert.assertEquals(1, hbrsp.getContainersToCleanup().size()); Assert.assertEquals(completedContainerId, hbrsp.getContainersToCleanup().get(0)); Assert.assertEquals(1, hbrsp.getApplicationsToCleanup().size()); Assert.assertEquals(finishedAppId, hbrsp.getApplicationsToCleanup().get(0)); } @Test(timeout=20000) public void testUpdateHeartbeatResponseForAppLifeCycle() { RMNodeImpl node = getRunningNode(); NodeId nodeId = node.getNodeID(); ApplicationId runningAppId = BuilderUtils.newApplicationId(0, 1); // Create a running container ContainerId runningContainerId = BuilderUtils.newContainerId( BuilderUtils.newApplicationAttemptId( runningAppId, 0), 0); ContainerStatus status = ContainerStatus.newInstance(runningContainerId, ContainerState.RUNNING, "", 0); List<ContainerStatus> statusList = new ArrayList<ContainerStatus>(); statusList.add(status); NodeHealthStatus nodeHealth = NodeHealthStatus.newInstance(true, "", System.currentTimeMillis()); node.handle(new RMNodeStatusEvent(nodeId, nodeHealth, statusList, null, null)); Assert.assertEquals(1, node.getRunningApps().size()); // Finish an application ApplicationId finishedAppId = runningAppId; node.handle(new RMNodeCleanAppEvent(nodeId, finishedAppId)); Assert.assertEquals(1, node.getAppsToCleanup().size()); Assert.assertEquals(0, node.getRunningApps().size()); } private RMNodeImpl getRunningNode() { return getRunningNode(null, 0); } private RMNodeImpl getRunningNode(String nmVersion) { return getRunningNode(nmVersion, 0); } private RMNodeImpl getRunningNode(String nmVersion, int port) { NodeId nodeId = BuilderUtils.newNodeId("localhost", port); Resource capability = Resource.newInstance(4096, 4); RMNodeImpl node = new RMNodeImpl(nodeId, rmContext, null, 0, 0, null, capability, nmVersion); node.handle(new RMNodeStartedEvent(node.getNodeID(), null, null)); Assert.assertEquals(NodeState.RUNNING, node.getState()); return node; } private RMNodeImpl getUnhealthyNode() { RMNodeImpl node = getRunningNode(); NodeHealthStatus status = NodeHealthStatus.newInstance(false, "sick", System.currentTimeMillis()); node.handle(new RMNodeStatusEvent(node.getNodeID(), status, new ArrayList<ContainerStatus>(), null, null)); Assert.assertEquals(NodeState.UNHEALTHY, node.getState()); return node; } private RMNodeImpl getNewNode() { NodeId nodeId = BuilderUtils.newNodeId("localhost", 0); RMNodeImpl node = new RMNodeImpl(nodeId, rmContext, null, 0, 0, null, null, null); return node; } private RMNodeImpl getNewNode(Resource capability) { NodeId nodeId = BuilderUtils.newNodeId("localhost", 0); RMNodeImpl node = new RMNodeImpl(nodeId, rmContext, null, 0, 0, null, capability, null); return node; } private RMNodeImpl getRebootedNode() { NodeId nodeId = BuilderUtils.newNodeId("localhost", 0); Resource capability = Resource.newInstance(4096, 4); RMNodeImpl node = new RMNodeImpl(nodeId, rmContext,null, 0, 0, null, capability, null); node.handle(new RMNodeStartedEvent(node.getNodeID(), null, null)); Assert.assertEquals(NodeState.RUNNING, node.getState()); node.handle(new RMNodeEvent(node.getNodeID(), RMNodeEventType.REBOOTING)); Assert.assertEquals(NodeState.REBOOTED, node.getState()); return node; } @Test public void testAdd() { RMNodeImpl node = getNewNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeStartedEvent(node.getNodeID(), null, null)); Assert.assertEquals("Active Nodes", initialActive + 1, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.RUNNING, node.getState()); Assert.assertNotNull(nodesListManagerEvent); Assert.assertEquals(NodesListManagerEventType.NODE_USABLE, nodesListManagerEvent.getType()); } @Test public void testReconnect() { RMNodeImpl node = getRunningNode(); ClusterMetrics cm = ClusterMetrics.getMetrics(); int initialActive = cm.getNumActiveNMs(); int initialLost = cm.getNumLostNMs(); int initialUnhealthy = cm.getUnhealthyNMs(); int initialDecommissioned = cm.getNumDecommisionedNMs(); int initialRebooted = cm.getNumRebootedNMs(); node.handle(new RMNodeReconnectEvent(node.getNodeID(), node, null, null)); Assert.assertEquals("Active Nodes", initialActive, cm.getNumActiveNMs()); Assert.assertEquals("Lost Nodes", initialLost, cm.getNumLostNMs()); Assert.assertEquals("Unhealthy Nodes", initialUnhealthy, cm.getUnhealthyNMs()); Assert.assertEquals("Decommissioned Nodes", initialDecommissioned, cm.getNumDecommisionedNMs()); Assert.assertEquals("Rebooted Nodes", initialRebooted, cm.getNumRebootedNMs()); Assert.assertEquals(NodeState.RUNNING, node.getState()); Assert.assertNotNull(nodesListManagerEvent); Assert.assertEquals(NodesListManagerEventType.NODE_USABLE, nodesListManagerEvent.getType()); } @Test public void testResourceUpdateOnRunningNode() { RMNodeImpl node = getRunningNode(); Resource oldCapacity = node.getTotalCapability(); assertEquals("Memory resource is not match.", oldCapacity.getMemory(), 4096); assertEquals("CPU resource is not match.", oldCapacity.getVirtualCores(), 4); node.handle(new RMNodeResourceUpdateEvent(node.getNodeID(), ResourceOption.newInstance(Resource.newInstance(2048, 2), RMNode.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT))); Resource newCapacity = node.getTotalCapability(); assertEquals("Memory resource is not match.", newCapacity.getMemory(), 2048); assertEquals("CPU resource is not match.", newCapacity.getVirtualCores(), 2); Assert.assertEquals(NodeState.RUNNING, node.getState()); Assert.assertNotNull(nodesListManagerEvent); Assert.assertEquals(NodesListManagerEventType.NODE_USABLE, nodesListManagerEvent.getType()); } @Test public void testResourceUpdateOnNewNode() { RMNodeImpl node = getNewNode(Resource.newInstance(4096, 4)); Resource oldCapacity = node.getTotalCapability(); assertEquals("Memory resource is not match.", oldCapacity.getMemory(), 4096); assertEquals("CPU resource is not match.", oldCapacity.getVirtualCores(), 4); node.handle(new RMNodeResourceUpdateEvent(node.getNodeID(), ResourceOption.newInstance(Resource.newInstance(2048, 2), RMNode.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT))); Resource newCapacity = node.getTotalCapability(); assertEquals("Memory resource is not match.", newCapacity.getMemory(), 2048); assertEquals("CPU resource is not match.", newCapacity.getVirtualCores(), 2); Assert.assertEquals(NodeState.NEW, node.getState()); } @Test public void testResourceUpdateOnRebootedNode() { RMNodeImpl node = getRebootedNode(); Resource oldCapacity = node.getTotalCapability(); assertEquals("Memory resource is not match.", oldCapacity.getMemory(), 4096); assertEquals("CPU resource is not match.", oldCapacity.getVirtualCores(), 4); node.handle(new RMNodeResourceUpdateEvent(node.getNodeID(), ResourceOption.newInstance(Resource.newInstance(2048, 2), RMNode.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT))); Resource newCapacity = node.getTotalCapability(); assertEquals("Memory resource is not match.", newCapacity.getMemory(), 2048); assertEquals("CPU resource is not match.", newCapacity.getVirtualCores(), 2); Assert.assertEquals(NodeState.REBOOTED, node.getState()); } @Test public void testReconnnectUpdate() { final String nmVersion1 = "nm version 1"; final String nmVersion2 = "nm version 2"; RMNodeImpl node = getRunningNode(nmVersion1); Assert.assertEquals(nmVersion1, node.getNodeManagerVersion()); RMNodeImpl reconnectingNode = getRunningNode(nmVersion2); node.handle(new RMNodeReconnectEvent(node.getNodeID(), reconnectingNode, null, null)); Assert.assertEquals(nmVersion2, node.getNodeManagerVersion()); } @Test public void testContainerExpire() throws Exception { ContainerAllocationExpirer mockExpirer = mock(ContainerAllocationExpirer.class); ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ContainerId containerId1 = ContainerId.newContainerId(appAttemptId, 1L); ContainerId containerId2 = ContainerId.newContainerId(appAttemptId, 2L); mockExpirer.register(containerId1); mockExpirer.register(containerId2); verify(mockExpirer).register(containerId1); verify(mockExpirer).register(containerId2); ((RMContextImpl) rmContext).setContainerAllocationExpirer(mockExpirer); RMNodeImpl rmNode = getRunningNode(); ContainerStatus status1 = ContainerStatus .newInstance(containerId1, ContainerState.RUNNING, "", 0); ContainerStatus status2 = ContainerStatus.newInstance(containerId2, ContainerState.COMPLETE, "", 0); List<ContainerStatus> statusList = new ArrayList<ContainerStatus>(); statusList.add(status1); statusList.add(status2); RMNodeStatusEvent statusEvent = getMockRMNodeStatusEvent(statusList); rmNode.handle(statusEvent); verify(mockExpirer).unregister(containerId1); verify(mockExpirer).unregister(containerId2); } }
33,528
43.824866
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/HATestUtil.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; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.conf.HAUtil; import org.apache.hadoop.yarn.conf.YarnConfiguration; public class HATestUtil { public static void setRpcAddressForRM(String rmId, int base, Configuration conf) { for (String confKey : YarnConfiguration.getServiceAddressConfKeys(conf)) { setConfForRM(rmId, confKey, "0.0.0.0:" + (base + YarnConfiguration.getRMDefaultPortNumber(confKey, conf)), conf); } } public static void setConfForRM(String rmId, String prefix, String value, Configuration conf) { conf.set(HAUtil.addSuffix(prefix, rmId), value); } }
1,507
37.666667
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMDispatcher.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; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager.SchedulerEventDispatcher; 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.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType; import org.junit.Assert; import org.junit.Test; public class TestRMDispatcher { @SuppressWarnings("unchecked") @Test(timeout=10000) public void testSchedulerEventDispatcherForPreemptionEvents() { AsyncDispatcher rmDispatcher = new AsyncDispatcher(); CapacityScheduler sched = spy(new CapacityScheduler()); YarnConfiguration conf = new YarnConfiguration(); SchedulerEventDispatcher schedulerDispatcher = new SchedulerEventDispatcher(sched); rmDispatcher.register(SchedulerEventType.class, schedulerDispatcher); rmDispatcher.init(conf); rmDispatcher.start(); schedulerDispatcher.init(conf); schedulerDispatcher.start(); try { ApplicationAttemptId appAttemptId = mock(ApplicationAttemptId.class); RMContainer container = mock(RMContainer.class); ContainerPreemptEvent event1 = new ContainerPreemptEvent( appAttemptId, container, SchedulerEventType.DROP_RESERVATION); rmDispatcher.getEventHandler().handle(event1); ContainerPreemptEvent event2 = new ContainerPreemptEvent( appAttemptId, container, SchedulerEventType.KILL_CONTAINER); rmDispatcher.getEventHandler().handle(event2); ContainerPreemptEvent event3 = new ContainerPreemptEvent( appAttemptId, container, SchedulerEventType.PREEMPT_CONTAINER); rmDispatcher.getEventHandler().handle(event3); // Wait for events to be processed by scheduler dispatcher. Thread.sleep(1000); verify(sched, times(3)).handle(any(SchedulerEvent.class)); verify(sched).dropContainerReservation(container); verify(sched).preemptContainer(appAttemptId, container); verify(sched).killContainer(container); } catch (InterruptedException e) { Assert.fail(); } finally { schedulerDispatcher.stop(); rmDispatcher.stop(); } } }
3,613
44.746835
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterLauncher.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; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.ContainerManagementProtocol; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesResponse; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersResponse; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.SerializedException; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.ApplicationAttemptNotFoundException; import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncherEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Test; public class TestApplicationMasterLauncher { private static final Log LOG = LogFactory .getLog(TestApplicationMasterLauncher.class); private static final class MyContainerManagerImpl implements ContainerManagementProtocol { boolean launched = false; boolean cleanedup = false; String attemptIdAtContainerManager = null; String containerIdAtContainerManager = null; String nmHostAtContainerManager = null; long submitTimeAtContainerManager; int maxAppAttempts; @Override public StartContainersResponse startContainers(StartContainersRequest requests) throws YarnException { StartContainerRequest request = requests.getStartContainerRequests().get(0); LOG.info("Container started by MyContainerManager: " + request); launched = true; Map<String, String> env = request.getContainerLaunchContext().getEnvironment(); Token containerToken = request.getContainerToken(); ContainerTokenIdentifier tokenId = null; try { tokenId = BuilderUtils.newContainerTokenIdentifier(containerToken); } catch (IOException e) { throw RPCUtil.getRemoteException(e); } ContainerId containerId = tokenId.getContainerID(); containerIdAtContainerManager = containerId.toString(); attemptIdAtContainerManager = containerId.getApplicationAttemptId().toString(); nmHostAtContainerManager = tokenId.getNmHostAddress(); submitTimeAtContainerManager = Long.parseLong(env.get(ApplicationConstants.APP_SUBMIT_TIME_ENV)); maxAppAttempts = Integer.parseInt(env.get(ApplicationConstants.MAX_APP_ATTEMPTS_ENV)); return StartContainersResponse.newInstance( new HashMap<String, ByteBuffer>(), new ArrayList<ContainerId>(), new HashMap<ContainerId, SerializedException>()); } @Override public StopContainersResponse stopContainers(StopContainersRequest request) throws YarnException { LOG.info("Container cleaned up by MyContainerManager"); cleanedup = true; return null; } @Override public GetContainerStatusesResponse getContainerStatuses( GetContainerStatusesRequest request) throws YarnException { return null; } } @Test public void testAMLaunchAndCleanup() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); MyContainerManagerImpl containerManager = new MyContainerManagerImpl(); MockRMWithCustomAMLauncher rm = new MockRMWithCustomAMLauncher( containerManager); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 5120); RMApp app = rm.submitApp(2000); // kick the scheduling nm1.nodeHeartbeat(true); int waitCount = 0; while (containerManager.launched == false && waitCount++ < 20) { LOG.info("Waiting for AM Launch to happen.."); Thread.sleep(1000); } Assert.assertTrue(containerManager.launched); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId appAttemptId = attempt.getAppAttemptId(); Assert.assertEquals(appAttemptId.toString(), containerManager.attemptIdAtContainerManager); Assert.assertEquals(app.getSubmitTime(), containerManager.submitTimeAtContainerManager); Assert.assertEquals(app.getRMAppAttempt(appAttemptId) .getMasterContainer().getId() .toString(), containerManager.containerIdAtContainerManager); Assert.assertEquals(nm1.getNodeId().toString(), containerManager.nmHostAtContainerManager); Assert.assertEquals(YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS, containerManager.maxAppAttempts); MockAM am = new MockAM(rm.getRMContext(), rm .getApplicationMasterService(), appAttemptId); am.registerAppAttempt(); am.unregisterAppAttempt(); //complete the AM container to finish the app normally nm1.nodeHeartbeat(attempt.getAppAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); waitCount = 0; while (containerManager.cleanedup == false && waitCount++ < 20) { LOG.info("Waiting for AM Cleanup to happen.."); Thread.sleep(1000); } Assert.assertTrue(containerManager.cleanedup); am.waitForState(RMAppAttemptState.FINISHED); rm.stop(); } @SuppressWarnings("unused") @Test(timeout = 100000) public void testallocateBeforeAMRegistration() throws Exception { Logger rootLogger = LogManager.getRootLogger(); boolean thrown = false; rootLogger.setLevel(Level.DEBUG); MockRM rm = new MockRM(); rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 5000); RMApp app = rm.submitApp(2000); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); // request for containers int request = 2; AllocateResponse ar = null; try { ar = am.allocate("h1", 1000, request, new ArrayList<ContainerId>()); Assert.fail(); } catch (ApplicationMasterNotRegisteredException e) { } // kick the scheduler nm1.nodeHeartbeat(true); AllocateResponse amrs = null; try { amrs = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); Assert.fail(); } catch (ApplicationMasterNotRegisteredException e) { } am.registerAppAttempt(); try { am.registerAppAttempt(false); Assert.fail(); } catch (Exception e) { Assert.assertEquals("Application Master is already registered : " + attempt.getAppAttemptId().getApplicationId(), e.getMessage()); } // Simulate an AM that was disconnected and app attempt was removed // (responseMap does not contain attemptid) am.unregisterAppAttempt(); nm1.nodeHeartbeat(attempt.getAppAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); try { amrs = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); Assert.fail(); } catch (ApplicationAttemptNotFoundException e) { } } @Test public void testSetupTokens() throws Exception { MockRM rm = new MockRM(); rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 5000); RMApp app = rm.submitApp(2000); /// kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); MyAMLauncher launcher = new MyAMLauncher(rm.getRMContext(), attempt, AMLauncherEventType.LAUNCH, rm.getConfig()); DataOutputBuffer dob = new DataOutputBuffer(); Credentials ts = new Credentials(); ts.writeTokenStorageToStream(dob); ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance(null, null, null, null, securityTokens, null); ContainerId containerId = ContainerId.newContainerId( attempt.getAppAttemptId(), 0L); try { launcher.setupTokens(amContainer, containerId); } catch (Exception e) { // ignore the first fake exception } try { launcher.setupTokens(amContainer, containerId); } catch (java.io.EOFException e) { Assert.fail("EOFException should not happen."); } } static class MyAMLauncher extends AMLauncher { int count; public MyAMLauncher(RMContext rmContext, RMAppAttempt application, AMLauncherEventType eventType, Configuration conf) { super(rmContext, application, eventType, conf); count = 0; } protected org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> createAndSetAMRMToken() { count++; if (count == 1) { throw new RuntimeException("createAndSetAMRMToken failure"); } return null; } protected void setupTokens(ContainerLaunchContext container, ContainerId containerID) throws IOException { super.setupTokens(container, containerID); } } }
11,518
36.643791
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ParameterizedSchedulerTestBase.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; import org.apache.hadoop.yarn.conf.YarnConfiguration; 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.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public abstract class ParameterizedSchedulerTestBase { protected final static String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); private final static String FS_ALLOC_FILE = new File(TEST_DIR, "test-fs-queues.xml").getAbsolutePath(); private SchedulerType schedulerType; private YarnConfiguration conf = null; public enum SchedulerType { CAPACITY, FAIR } public ParameterizedSchedulerTestBase(SchedulerType type) { schedulerType = type; } public YarnConfiguration getConf() { return conf; } @Parameterized.Parameters public static Collection<SchedulerType[]> getParameters() { return Arrays.asList(new SchedulerType[][]{ {SchedulerType.CAPACITY}, {SchedulerType.FAIR}}); } @Before public void configureScheduler() throws IOException { conf = new YarnConfiguration(); switch (schedulerType) { case CAPACITY: conf.set(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class.getName()); break; case FAIR: configureFairScheduler(conf); break; } } private void configureFairScheduler(YarnConfiguration conf) throws IOException { // Disable queueMaxAMShare limitation for fair scheduler PrintWriter out = new PrintWriter(new FileWriter(FS_ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queueMaxAMShareDefault>-1.0</queueMaxAMShareDefault>"); out.println("<defaultQueueSchedulingPolicy>fair</defaultQueueSchedulingPolicy>"); out.println("<queue name=\"root\">"); out.println(" <schedulingPolicy>drf</schedulingPolicy>"); out.println(" <weight>1.0</weight>"); out.println(" <fairSharePreemptionTimeout>100</fairSharePreemptionTimeout>"); out.println(" <minSharePreemptionTimeout>120</minSharePreemptionTimeout>"); out.println(" <fairSharePreemptionThreshold>.5</fairSharePreemptionThreshold>"); out.println("</queue>"); out.println("</allocations>"); out.close(); conf.set(YarnConfiguration.RM_SCHEDULER, FairScheduler.class.getName()); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, FS_ALLOC_FILE); } public SchedulerType getSchedulerType() { return schedulerType; } }
3,767
34.885714
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockRMWithCustomAMLauncher.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; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.ContainerManagementProtocol; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncherEventType; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.ApplicationMasterLauncher; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; public class MockRMWithCustomAMLauncher extends MockRM { private final ContainerManagementProtocol containerManager; public MockRMWithCustomAMLauncher(ContainerManagementProtocol containerManager) { this(new Configuration(), containerManager); } public MockRMWithCustomAMLauncher(Configuration conf, ContainerManagementProtocol containerManager) { super(conf); this.containerManager = containerManager; } @Override protected ApplicationMasterLauncher createAMLauncher() { return new ApplicationMasterLauncher(getRMContext()) { @Override protected Runnable createRunnableLauncher(RMAppAttempt application, AMLauncherEventType event) { return new AMLauncher(context, application, event, getConfig()) { @Override protected ContainerManagementProtocol getContainerMgrProxy( ContainerId containerId) { return containerManager; } @Override protected Token<AMRMTokenIdentifier> createAndSetAMRMToken() { Token<AMRMTokenIdentifier> amRmToken = super.createAndSetAMRMToken(); InetSocketAddress serviceAddr = getConfig().getSocketAddr( YarnConfiguration.RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT); SecurityUtil.setTokenService(amRmToken, serviceAddr); return amRmToken; } }; } }; } }
3,145
39.857143
90
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/Task.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; import java.util.HashSet; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; public class Task { private static final Log LOG = LogFactory.getLog(Task.class); public enum State {PENDING, ALLOCATED, RUNNING, COMPLETE}; final private ApplicationId applicationId; final private int taskId; final private Priority priority; final private Set<String> hosts = new HashSet<String>(); final private Set<String> racks = new HashSet<String>(); private ContainerId containerId; private org.apache.hadoop.yarn.server.resourcemanager.NodeManager nodeManager; private State state; public Task(Application application, Priority priority, String[] hosts) { this.applicationId = application.getApplicationId(); this.priority = priority; taskId = application.getNextTaskId(); state = State.PENDING; // Special case: Don't care about locality if (!(hosts.length == 1 && hosts[0].equals(ResourceRequest.ANY))) { for (String host : hosts) { this.hosts.add(host); this.racks.add(Application.resolve(host)); } } LOG.info("Task " + taskId + " added to application " + this.applicationId + " with " + this.hosts.size() + " hosts, " + racks.size() + " racks"); } public int getTaskId() { return taskId; } public Priority getPriority() { return priority; } public org.apache.hadoop.yarn.server.resourcemanager.NodeManager getNodeManager() { return nodeManager; } public ContainerId getContainerId() { return containerId; } public ApplicationId getApplicationID() { return applicationId; } public String[] getHosts() { return hosts.toArray(new String[hosts.size()]); } public String[] getRacks() { return racks.toArray(new String[racks.size()]); } public boolean canSchedule(NodeType type, String hostName) { if (type == NodeType.NODE_LOCAL) { return hosts.contains(hostName); } else if (type == NodeType.RACK_LOCAL) { return racks.contains(Application.resolve(hostName)); } return true; } public void start(NodeManager nodeManager, ContainerId containerId) { this.nodeManager = nodeManager; this.containerId = containerId; setState(State.RUNNING); } public void stop() { if (getState() != State.RUNNING) { throw new IllegalStateException("Trying to stop a non-running task: " + getTaskId() + " of application " + getApplicationID()); } this.nodeManager = null; this.containerId = null; setState(State.COMPLETE); } public State getState() { return state; } private void setState(State state) { this.state = state; } @Override public boolean equals(Object obj) { if (obj instanceof Task) { return ((Task)obj).taskId == this.taskId; } return super.equals(obj); } @Override public int hashCode() { return taskId; } }
4,163
27.717241
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/RMDelegationTokenIdentifierForTest.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; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import org.apache.hadoop.io.Text; import org.apache.hadoop.yarn.proto.YarnSecurityTestClientAMTokenProtos.RMDelegationTokenIdentifierForTestProto; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; public class RMDelegationTokenIdentifierForTest extends RMDelegationTokenIdentifier { private RMDelegationTokenIdentifierForTestProto.Builder builder = RMDelegationTokenIdentifierForTestProto.newBuilder(); public RMDelegationTokenIdentifierForTest() { } public RMDelegationTokenIdentifierForTest(RMDelegationTokenIdentifier token, String message) { if (token.getOwner() != null) { setOwner(new Text(token.getOwner())); } if (token.getRenewer() != null) { setRenewer(new Text(token.getRenewer())); } if (token.getRealUser() != null) { setRealUser(new Text(token.getRealUser())); } setIssueDate(token.getIssueDate()); setMaxDate(token.getMaxDate()); setSequenceNumber(token.getSequenceNumber()); setMasterKeyId(token.getMasterKeyId()); builder.setMessage(message); } @Override public void write(DataOutput out) throws IOException { builder.setOwner(getOwner().toString()); builder.setRenewer(getRenewer().toString()); builder.setRealUser(getRealUser().toString()); builder.setIssueDate(getIssueDate()); builder.setMaxDate(getMaxDate()); builder.setSequenceNumber(getSequenceNumber()); builder.setMasterKeyId(getMasterKeyId()); builder.setMessage(getMessage()); builder.build().writeTo((DataOutputStream) out); } @Override public void readFields(DataInput in) throws IOException { builder.mergeFrom((DataInputStream) in); if (builder.getOwner() != null) { setOwner(new Text(builder.getOwner())); } if (builder.getRenewer() != null) { setRenewer(new Text(builder.getRenewer())); } if (builder.getRealUser() != null) { setRealUser(new Text(builder.getRealUser())); } setIssueDate(builder.getIssueDate()); setMaxDate(builder.getMaxDate()); setSequenceNumber(builder.getSequenceNumber()); setMasterKeyId(builder.getMasterKeyId()); } public String getMessage() { return builder.getMessage(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof RMDelegationTokenIdentifierForTest) { RMDelegationTokenIdentifierForTest that = (RMDelegationTokenIdentifierForTest) obj; return this.getSequenceNumber() == that.getSequenceNumber() && this.getIssueDate() == that.getIssueDate() && this.getMaxDate() == that.getMaxDate() && this.getMasterKeyId() == that.getMasterKeyId() && isEqual(this.getOwner(), that.getOwner()) && isEqual(this.getRenewer(), that.getRenewer()) && isEqual(this.getRealUser(), that.getRealUser()) && isEqual(this.getMessage(), that.getMessage()); } return false; } }
3,995
35
112
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestAppManager.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; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl; import static org.mockito.Matchers.isA; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentMap; import org.junit.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.service.Service; import org.apache.hadoop.yarn.MockApps; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.Resource; 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.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.MockRMApp; 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.RMAppMetrics; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AMLivelinessMonitor; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; 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.security.ClientToAMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * Testing applications being retired from RM. * */ public class TestAppManager{ private Log LOG = LogFactory.getLog(TestAppManager.class); private static RMAppEventType appEventType = RMAppEventType.KILL; public synchronized RMAppEventType getAppEventType() { return appEventType; } public synchronized void setAppEventType(RMAppEventType newType) { appEventType = newType; } public static List<RMApp> newRMApps(int n, long time, RMAppState state) { List<RMApp> list = Lists.newArrayList(); for (int i = 0; i < n; ++i) { list.add(new MockRMApp(i, time, state)); } return list; } public RMContext mockRMContext(int n, long time) { final List<RMApp> apps = newRMApps(n, time, RMAppState.FINISHED); final ConcurrentMap<ApplicationId, RMApp> map = Maps.newConcurrentMap(); for (RMApp app : apps) { map.put(app.getApplicationId(), app); } Dispatcher rmDispatcher = new AsyncDispatcher(); ContainerAllocationExpirer containerAllocationExpirer = new ContainerAllocationExpirer( rmDispatcher); AMLivelinessMonitor amLivelinessMonitor = new AMLivelinessMonitor( rmDispatcher); AMLivelinessMonitor amFinishingMonitor = new AMLivelinessMonitor( rmDispatcher); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); RMContext context = new RMContextImpl(rmDispatcher, containerAllocationExpirer, amLivelinessMonitor, amFinishingMonitor, null, null, null, null, null, writer) { @Override public ConcurrentMap<ApplicationId, RMApp> getRMApps() { return map; } }; ((RMContextImpl)context).setStateStore(mock(RMStateStore.class)); metricsPublisher = mock(SystemMetricsPublisher.class); ((RMContextImpl)context).setSystemMetricsPublisher(metricsPublisher); return context; } public class TestAppManagerDispatcher implements EventHandler<RMAppManagerEvent> { public TestAppManagerDispatcher() { } @Override public void handle(RMAppManagerEvent event) { // do nothing } } public class TestDispatcher implements EventHandler<RMAppEvent> { public TestDispatcher() { } @Override public void handle(RMAppEvent event) { //RMApp rmApp = this.rmContext.getRMApps().get(appID); setAppEventType(event.getType()); System.out.println("in handle routine " + getAppEventType().toString()); } } // Extend and make the functions we want to test public public class TestRMAppManager extends RMAppManager { public TestRMAppManager(RMContext context, Configuration conf) { super(context, null, null, new ApplicationACLsManager(conf), conf); } public TestRMAppManager(RMContext context, ClientToAMTokenSecretManagerInRM clientToAMSecretManager, YarnScheduler scheduler, ApplicationMasterService masterService, ApplicationACLsManager applicationACLsManager, Configuration conf) { super(context, scheduler, masterService, applicationACLsManager, conf); } public void checkAppNumCompletedLimit() { super.checkAppNumCompletedLimit(); } public void finishApplication(ApplicationId appId) { super.finishApplication(appId); } public int getCompletedAppsListSize() { return super.getCompletedAppsListSize(); } public int getCompletedAppsInStateStore() { return this.completedAppsInStateStore; } public void submitApplication( ApplicationSubmissionContext submissionContext, String user) throws YarnException { super.submitApplication(submissionContext, System.currentTimeMillis(), user); } } protected void addToCompletedApps(TestRMAppManager appMonitor, RMContext rmContext) { for (RMApp app : rmContext.getRMApps().values()) { if (app.getState() == RMAppState.FINISHED || app.getState() == RMAppState.KILLED || app.getState() == RMAppState.FAILED) { appMonitor.finishApplication(app.getApplicationId()); } } } private RMContext rmContext; private SystemMetricsPublisher metricsPublisher; private TestRMAppManager appMonitor; private ApplicationSubmissionContext asContext; private ApplicationId appId; @SuppressWarnings("deprecation") @Before public void setUp() { long now = System.currentTimeMillis(); rmContext = mockRMContext(1, now - 10); ResourceScheduler scheduler = mockResourceScheduler(); ((RMContextImpl)rmContext).setScheduler(scheduler); Configuration conf = new Configuration(); ApplicationMasterService masterService = new ApplicationMasterService(rmContext, scheduler); appMonitor = new TestRMAppManager(rmContext, new ClientToAMTokenSecretManagerInRM(), scheduler, masterService, new ApplicationACLsManager(conf), conf); appId = MockApps.newAppID(1); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); asContext = recordFactory.newRecordInstance(ApplicationSubmissionContext.class); asContext.setApplicationId(appId); asContext.setAMContainerSpec(mockContainerLaunchContext(recordFactory)); asContext.setResource(mockResource()); setupDispatcher(rmContext, conf); } @After public void tearDown() { setAppEventType(RMAppEventType.KILL); ((Service)rmContext.getDispatcher()).stop(); } @Test public void testRMAppRetireNone() throws Exception { long now = System.currentTimeMillis(); // Create such that none of the applications will retire since // haven't hit max # RMContext rmContext = mockRMContext(10, now - 10); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 10); TestRMAppManager appMonitor = new TestRMAppManager(rmContext,conf); Assert.assertEquals("Number of apps incorrect before checkAppTimeLimit", 10, rmContext.getRMApps().size()); // add them to completed apps list addToCompletedApps(appMonitor, rmContext); // shouldn't have to many apps appMonitor.checkAppNumCompletedLimit(); Assert.assertEquals("Number of apps incorrect after # completed check", 10, rmContext.getRMApps().size()); Assert.assertEquals("Number of completed apps incorrect after check", 10, appMonitor.getCompletedAppsListSize()); verify(rmContext.getStateStore(), never()).removeApplication( isA(RMApp.class)); } @Test public void testRMAppRetireSome() throws Exception { long now = System.currentTimeMillis(); RMContext rmContext = mockRMContext(10, now - 20000); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 3); conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 3); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf); Assert.assertEquals("Number of apps incorrect before", 10, rmContext .getRMApps().size()); // add them to completed apps list addToCompletedApps(appMonitor, rmContext); // shouldn't have to many apps appMonitor.checkAppNumCompletedLimit(); Assert.assertEquals("Number of apps incorrect after # completed check", 3, rmContext.getRMApps().size()); Assert.assertEquals("Number of completed apps incorrect after check", 3, appMonitor.getCompletedAppsListSize()); verify(rmContext.getStateStore(), times(7)).removeApplication( isA(RMApp.class)); } @Test public void testRMAppRetireSomeDifferentStates() throws Exception { long now = System.currentTimeMillis(); // these parameters don't matter, override applications below RMContext rmContext = mockRMContext(10, now - 20000); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 2); conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 2); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf); // clear out applications map rmContext.getRMApps().clear(); Assert.assertEquals("map isn't empty", 0, rmContext.getRMApps().size()); // 6 applications are in final state, 4 are not in final state. // / set with various finished states RMApp app = new MockRMApp(0, now - 20000, RMAppState.KILLED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(1, now - 200000, RMAppState.FAILED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(2, now - 30000, RMAppState.FINISHED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(3, now - 20000, RMAppState.RUNNING); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(4, now - 20000, RMAppState.NEW); rmContext.getRMApps().put(app.getApplicationId(), app); // make sure it doesn't expire these since still running app = new MockRMApp(5, now - 10001, RMAppState.KILLED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(6, now - 30000, RMAppState.ACCEPTED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(7, now - 20000, RMAppState.SUBMITTED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(8, now - 10001, RMAppState.FAILED); rmContext.getRMApps().put(app.getApplicationId(), app); app = new MockRMApp(9, now - 20000, RMAppState.FAILED); rmContext.getRMApps().put(app.getApplicationId(), app); Assert.assertEquals("Number of apps incorrect before", 10, rmContext .getRMApps().size()); // add them to completed apps list addToCompletedApps(appMonitor, rmContext); // shouldn't have to many apps appMonitor.checkAppNumCompletedLimit(); Assert.assertEquals("Number of apps incorrect after # completed check", 6, rmContext.getRMApps().size()); Assert.assertEquals("Number of completed apps incorrect after check", 2, appMonitor.getCompletedAppsListSize()); // 6 applications in final state, 4 of them are removed verify(rmContext.getStateStore(), times(4)).removeApplication( isA(RMApp.class)); } @Test public void testRMAppRetireNullApp() throws Exception { long now = System.currentTimeMillis(); RMContext rmContext = mockRMContext(10, now - 20000); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, new Configuration()); Assert.assertEquals("Number of apps incorrect before", 10, rmContext .getRMApps().size()); appMonitor.finishApplication(null); Assert.assertEquals("Number of completed apps incorrect after check", 0, appMonitor.getCompletedAppsListSize()); } @Test public void testRMAppRetireZeroSetting() throws Exception { long now = System.currentTimeMillis(); RMContext rmContext = mockRMContext(10, now - 20000); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 0); conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 0); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf); Assert.assertEquals("Number of apps incorrect before", 10, rmContext .getRMApps().size()); addToCompletedApps(appMonitor, rmContext); Assert.assertEquals("Number of completed apps incorrect", 10, appMonitor.getCompletedAppsListSize()); appMonitor.checkAppNumCompletedLimit(); Assert.assertEquals("Number of apps incorrect after # completed check", 0, rmContext.getRMApps().size()); Assert.assertEquals("Number of completed apps incorrect after check", 0, appMonitor.getCompletedAppsListSize()); verify(rmContext.getStateStore(), times(10)).removeApplication( isA(RMApp.class)); } @Test public void testStateStoreAppLimitLessThanMemoryAppLimit() { long now = System.currentTimeMillis(); RMContext rmContext = mockRMContext(10, now - 20000); Configuration conf = new YarnConfiguration(); int maxAppsInMemory = 8; int maxAppsInStateStore = 4; conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, maxAppsInMemory); conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, maxAppsInStateStore); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf); addToCompletedApps(appMonitor, rmContext); Assert.assertEquals("Number of completed apps incorrect", 10, appMonitor.getCompletedAppsListSize()); appMonitor.checkAppNumCompletedLimit(); Assert.assertEquals("Number of apps incorrect after # completed check", maxAppsInMemory, rmContext.getRMApps().size()); Assert.assertEquals("Number of completed apps incorrect after check", maxAppsInMemory, appMonitor.getCompletedAppsListSize()); int numRemoveAppsFromStateStore = 10 - maxAppsInStateStore; verify(rmContext.getStateStore(), times(numRemoveAppsFromStateStore)) .removeApplication(isA(RMApp.class)); Assert.assertEquals(maxAppsInStateStore, appMonitor.getCompletedAppsInStateStore()); } @Test public void testStateStoreAppLimitLargerThanMemoryAppLimit() { long now = System.currentTimeMillis(); RMContext rmContext = mockRMContext(10, now - 20000); Configuration conf = new YarnConfiguration(); int maxAppsInMemory = 8; conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, maxAppsInMemory); // larger than maxCompletedAppsInMemory, reset to RM_MAX_COMPLETED_APPLICATIONS. conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 1000); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf); addToCompletedApps(appMonitor, rmContext); Assert.assertEquals("Number of completed apps incorrect", 10, appMonitor.getCompletedAppsListSize()); appMonitor.checkAppNumCompletedLimit(); int numRemoveApps = 10 - maxAppsInMemory; Assert.assertEquals("Number of apps incorrect after # completed check", maxAppsInMemory, rmContext.getRMApps().size()); Assert.assertEquals("Number of completed apps incorrect after check", maxAppsInMemory, appMonitor.getCompletedAppsListSize()); verify(rmContext.getStateStore(), times(numRemoveApps)).removeApplication( isA(RMApp.class)); Assert.assertEquals(maxAppsInMemory, appMonitor.getCompletedAppsInStateStore()); } protected void setupDispatcher(RMContext rmContext, Configuration conf) { TestDispatcher testDispatcher = new TestDispatcher(); TestAppManagerDispatcher testAppManagerDispatcher = new TestAppManagerDispatcher(); rmContext.getDispatcher().register(RMAppEventType.class, testDispatcher); rmContext.getDispatcher().register(RMAppManagerEventType.class, testAppManagerDispatcher); ((Service)rmContext.getDispatcher()).init(conf); ((Service)rmContext.getDispatcher()).start(); Assert.assertEquals("app event type is wrong before", RMAppEventType.KILL, appEventType); } @Test public void testRMAppSubmit() throws Exception { appMonitor.submitApplication(asContext, "test"); RMApp app = rmContext.getRMApps().get(appId); Assert.assertNotNull("app is null", app); Assert.assertEquals("app id doesn't match", appId, app.getApplicationId()); Assert.assertEquals("app state doesn't match", RMAppState.NEW, app.getState()); verify(metricsPublisher).appACLsUpdated( any(RMApp.class), any(String.class), anyLong()); // wait for event to be processed int timeoutSecs = 0; while ((getAppEventType() == RMAppEventType.KILL) && timeoutSecs++ < 20) { Thread.sleep(1000); } Assert.assertEquals("app event type sent is wrong", RMAppEventType.START, getAppEventType()); } @Test public void testRMAppSubmitWithInvalidTokens() throws Exception { // Setup invalid security tokens DataOutputBuffer dob = new DataOutputBuffer(); ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); asContext.getAMContainerSpec().setTokens(securityTokens); try { appMonitor.submitApplication(asContext, "test"); Assert.fail("Application submission should fail because" + " Tokens are invalid."); } catch (YarnException e) { // Exception is expected Assert.assertTrue("The thrown exception is not" + " java.io.EOFException", e.getMessage().contains("java.io.EOFException")); } int timeoutSecs = 0; while ((getAppEventType() == RMAppEventType.KILL) && timeoutSecs++ < 20) { Thread.sleep(1000); } Assert.assertEquals("app event type sent is wrong", RMAppEventType.APP_REJECTED, getAppEventType()); asContext.getAMContainerSpec().setTokens(null); } @Test public void testRMAppSubmitWithValidTokens() throws Exception { // Setup valid security tokens DataOutputBuffer dob = new DataOutputBuffer(); Credentials credentials = new Credentials(); credentials.writeTokenStorageToStream(dob); ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); asContext.getAMContainerSpec().setTokens(securityTokens); appMonitor.submitApplication(asContext, "test"); RMApp app = rmContext.getRMApps().get(appId); Assert.assertNotNull("app is null", app); Assert.assertEquals("app id doesn't match", appId, app.getApplicationId()); Assert.assertEquals("app state doesn't match", RMAppState.NEW, app.getState()); verify(metricsPublisher).appACLsUpdated( any(RMApp.class), any(String.class), anyLong()); // wait for event to be processed int timeoutSecs = 0; while ((getAppEventType() == RMAppEventType.KILL) && timeoutSecs++ < 20) { Thread.sleep(1000); } Assert.assertEquals("app event type sent is wrong", RMAppEventType.START, getAppEventType()); asContext.getAMContainerSpec().setTokens(null); } @Test (timeout = 30000) public void testRMAppSubmitMaxAppAttempts() throws Exception { int[] globalMaxAppAttempts = new int[] { 10, 1 }; int[][] individualMaxAppAttempts = new int[][]{ new int[]{ 9, 10, 11, 0 }, new int[]{ 1, 10, 0, -1 }}; int[][] expectedNums = new int[][]{ new int[]{ 9, 10, 10, 10 }, new int[]{ 1, 1, 1, 1 }}; for (int i = 0; i < globalMaxAppAttempts.length; ++i) { for (int j = 0; j < individualMaxAppAttempts.length; ++j) { ResourceScheduler scheduler = mockResourceScheduler(); Configuration conf = new Configuration(); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, globalMaxAppAttempts[i]); ApplicationMasterService masterService = new ApplicationMasterService(rmContext, scheduler); TestRMAppManager appMonitor = new TestRMAppManager(rmContext, new ClientToAMTokenSecretManagerInRM(), scheduler, masterService, new ApplicationACLsManager(conf), conf); ApplicationId appID = MockApps.newAppID(i * 4 + j + 1); asContext.setApplicationId(appID); if (individualMaxAppAttempts[i][j] != 0) { asContext.setMaxAppAttempts(individualMaxAppAttempts[i][j]); } appMonitor.submitApplication(asContext, "test"); RMApp app = rmContext.getRMApps().get(appID); Assert.assertEquals("max application attempts doesn't match", expectedNums[i][j], app.getMaxAppAttempts()); // wait for event to be processed int timeoutSecs = 0; while ((getAppEventType() == RMAppEventType.KILL) && timeoutSecs++ < 20) { Thread.sleep(1000); } setAppEventType(RMAppEventType.KILL); } } } @Test (timeout = 30000) public void testRMAppSubmitDuplicateApplicationId() throws Exception { ApplicationId appId = MockApps.newAppID(0); asContext.setApplicationId(appId); RMApp appOrig = rmContext.getRMApps().get(appId); Assert.assertTrue("app name matches but shouldn't", "testApp1" != appOrig.getName()); // our testApp1 should be rejected and original app with same id should be left in place try { appMonitor.submitApplication(asContext, "test"); Assert.fail("Exception is expected when applicationId is duplicate."); } catch (YarnException e) { Assert.assertTrue("The thrown exception is not the expectd one.", e.getMessage().contains("Cannot add a duplicate!")); } // make sure original app didn't get removed RMApp app = rmContext.getRMApps().get(appId); Assert.assertNotNull("app is null", app); Assert.assertEquals("app id doesn't match", appId, app.getApplicationId()); Assert.assertEquals("app state doesn't match", RMAppState.FINISHED, app.getState()); } @SuppressWarnings("deprecation") @Test (timeout = 30000) public void testRMAppSubmitInvalidResourceRequest() throws Exception { asContext.setResource(Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB + 1)); // submit an app try { appMonitor.submitApplication(asContext, "test"); Assert.fail("Application submission should fail because resource" + " request is invalid."); } catch (YarnException e) { // Exception is expected // TODO Change this to assert the expected exception type - post YARN-142 // sub-task related to specialized exceptions. Assert.assertTrue("The thrown exception is not" + " InvalidResourceRequestException", e.getMessage().contains("Invalid resource request")); } } @Test (timeout = 30000) public void testEscapeApplicationSummary() { RMApp app = mock(RMAppImpl.class); when(app.getApplicationId()).thenReturn( ApplicationId.newInstance(100L, 1)); when(app.getName()).thenReturn("Multiline\n\n\r\rAppName"); when(app.getUser()).thenReturn("Multiline\n\n\r\rUserName"); when(app.getQueue()).thenReturn("Multiline\n\n\r\rQueueName"); when(app.getState()).thenReturn(RMAppState.RUNNING); when(app.getApplicationType()).thenReturn("MAPREDUCE"); RMAppMetrics metrics = new RMAppMetrics(Resource.newInstance(1234, 56), 10, 1, 16384, 64); when(app.getRMAppMetrics()).thenReturn(metrics); RMAppManager.ApplicationSummary.SummaryBuilder summary = new RMAppManager.ApplicationSummary().createAppSummary(app); String msg = summary.toString(); LOG.info("summary: " + msg); Assert.assertFalse(msg.contains("\n")); Assert.assertFalse(msg.contains("\r")); String escaped = "\\n\\n\\r\\r"; Assert.assertTrue(msg.contains("Multiline" + escaped +"AppName")); Assert.assertTrue(msg.contains("Multiline" + escaped +"UserName")); Assert.assertTrue(msg.contains("Multiline" + escaped +"QueueName")); Assert.assertTrue(msg.contains("memorySeconds=16384")); Assert.assertTrue(msg.contains("vcoreSeconds=64")); Assert.assertTrue(msg.contains("preemptedAMContainers=1")); Assert.assertTrue(msg.contains("preemptedNonAMContainers=10")); Assert.assertTrue(msg.contains("preemptedResources=<memory:1234\\, vCores:56>")); Assert.assertTrue(msg.contains("applicationType=MAPREDUCE")); } private static ResourceScheduler mockResourceScheduler() { ResourceScheduler scheduler = mock(ResourceScheduler.class); when(scheduler.getMinimumResourceCapability()).thenReturn( Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB)); when(scheduler.getMaximumResourceCapability()).thenReturn( Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB)); ResourceCalculator rs = mock(ResourceCalculator.class); when(scheduler.getResourceCalculator()).thenReturn(rs); return scheduler; } private static ContainerLaunchContext mockContainerLaunchContext( RecordFactory recordFactory) { ContainerLaunchContext amContainer = recordFactory.newRecordInstance( ContainerLaunchContext.class); amContainer.setApplicationACLs(new HashMap<ApplicationAccessType, String>());; return amContainer; } private static Resource mockResource() { return Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); } }
28,357
40.098551
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestMoveApplication.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.security.AccessControlException; import java.security.PrivilegedExceptionAction; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.MoveApplicationAcrossQueuesRequest; import org.apache.hadoop.yarn.api.protocolrecords.MoveApplicationAcrossQueuesResponse; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestMoveApplication { private ResourceManager resourceManager = null; private static boolean failMove; private Configuration conf; @Before public void setUp() throws Exception { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoSchedulerWithMove.class, FifoSchedulerWithMove.class); conf.set(YarnConfiguration.YARN_ADMIN_ACL, " "); conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); resourceManager = new MockRM(conf); resourceManager.getRMContext().getContainerTokenSecretManager().rollMasterKey(); resourceManager.getRMContext().getNMTokenSecretManager().rollMasterKey(); resourceManager.start(); failMove = false; } @After public void tearDown() { resourceManager.stop(); } @Test public void testMoveRejectedByScheduler() throws Exception { failMove = true; // Submit application Application application = new Application("user1", resourceManager); application.submit(); // Wait for app to be accepted RMApp app = resourceManager.rmContext.getRMApps() .get(application.getApplicationId()); while (app.getState() != RMAppState.ACCEPTED) { Thread.sleep(100); } ClientRMService clientRMService = resourceManager.getClientRMService(); try { // FIFO scheduler does not support moves clientRMService.moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest.newInstance( application.getApplicationId(), "newqueue")); fail("Should have hit exception"); } catch (YarnException ex) { assertEquals("Move not supported", ex.getCause().getMessage()); } } @Test (timeout = 10000) public void testMoveTooLate() throws Exception { // Submit application Application application = new Application("user1", resourceManager); ApplicationId appId = application.getApplicationId(); application.submit(); ClientRMService clientRMService = resourceManager.getClientRMService(); // Kill the application clientRMService.forceKillApplication( KillApplicationRequest.newInstance(appId)); RMApp rmApp = resourceManager.getRMContext().getRMApps().get(appId); // wait until it's dead while (rmApp.getState() != RMAppState.KILLED) { Thread.sleep(100); } try { clientRMService.moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest.newInstance(appId, "newqueue")); fail("Should have hit exception"); } catch (YarnException ex) { assertEquals(YarnException.class, ex.getClass()); assertEquals("App in KILLED state cannot be moved.", ex.getMessage()); } } @Test (timeout = 10000) public void testMoveSuccessful() throws Exception { MockRM rm1 = new MockRM(conf); rm1.start(); RMApp app = rm1.submitApp(1024); ClientRMService clientRMService = rm1.getClientRMService(); // FIFO scheduler does not support moves clientRMService .moveApplicationAcrossQueues(MoveApplicationAcrossQueuesRequest .newInstance(app.getApplicationId(), "newqueue")); RMApp rmApp = rm1.getRMContext().getRMApps().get(app.getApplicationId()); assertEquals("newqueue", rmApp.getQueue()); rm1.stop(); } @Test public void testMoveRejectedByPermissions() throws Exception { failMove = true; // Submit application final Application application = new Application("user1", resourceManager); application.submit(); final ClientRMService clientRMService = resourceManager.getClientRMService(); try { UserGroupInformation.createRemoteUser("otheruser").doAs( new PrivilegedExceptionAction<MoveApplicationAcrossQueuesResponse>() { @Override public MoveApplicationAcrossQueuesResponse run() throws Exception { return clientRMService.moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest.newInstance( application.getApplicationId(), "newqueue")); } }); fail("Should have hit exception"); } catch (Exception ex) { assertEquals(AccessControlException.class, ex.getCause().getCause().getClass()); } } public static class FifoSchedulerWithMove extends FifoScheduler { @Override public String moveApplication(ApplicationId appId, String newQueue) throws YarnException { if (failMove) { throw new YarnException("Move not supported"); } return newQueue; } @Override public synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName) { return acl != QueueACL.ADMINISTER_QUEUE; } } }
6,678
35.497268
86
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestAMAuthorization.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; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.io.DataInputByteBuffer; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.ContainerManagementProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesResponse; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersResponse; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersResponse; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.util.Records; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class TestAMAuthorization { private static final Log LOG = LogFactory.getLog(TestAMAuthorization.class); private final Configuration conf; private MockRM rm; @Parameters public static Collection<Object[]> configs() { Configuration conf = new Configuration(); Configuration confWithSecurity = new Configuration(); confWithSecurity.set( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, UserGroupInformation.AuthenticationMethod.KERBEROS.toString()); return Arrays.asList(new Object[][] {{ conf }, { confWithSecurity} }); } public TestAMAuthorization(Configuration conf) { this.conf = conf; UserGroupInformation.setConfiguration(conf); } @After public void tearDown() { if (rm != null) { rm.stop(); } } public static final class MyContainerManager implements ContainerManagementProtocol { public ByteBuffer containerTokens; public MyContainerManager() { } @Override public StartContainersResponse startContainers(StartContainersRequest request) throws YarnException { containerTokens = request.getStartContainerRequests().get(0).getContainerLaunchContext().getTokens(); return StartContainersResponse.newInstance(null, null, null); } @Override public StopContainersResponse stopContainers(StopContainersRequest request) throws YarnException { return StopContainersResponse.newInstance(null, null); } @Override public GetContainerStatusesResponse getContainerStatuses( GetContainerStatusesRequest request) throws YarnException { return GetContainerStatusesResponse.newInstance(null, null); } public Credentials getContainerCredentials() throws IOException { Credentials credentials = new Credentials(); DataInputByteBuffer buf = new DataInputByteBuffer(); containerTokens.rewind(); buf.reset(containerTokens); credentials.readTokenStorageStream(buf); return credentials; } } public static class MockRMWithAMS extends MockRMWithCustomAMLauncher { public MockRMWithAMS(Configuration conf, ContainerManagementProtocol containerManager) { super(conf, containerManager); } @Override protected void doSecureLogin() throws IOException { // Skip the login. } @Override protected ApplicationMasterService createApplicationMasterService() { return new ApplicationMasterService(getRMContext(), this.scheduler); } @SuppressWarnings("unchecked") public static Token<? extends TokenIdentifier> setupAndReturnAMRMToken( InetSocketAddress rmBindAddress, Collection<Token<? extends TokenIdentifier>> allTokens) { for (Token<? extends TokenIdentifier> token : allTokens) { if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) { SecurityUtil.setTokenService(token, rmBindAddress); return (Token<AMRMTokenIdentifier>) token; } } return null; } } @Test public void testAuthorizedAccess() throws Exception { MyContainerManager containerManager = new MyContainerManager(); rm = new MockRMWithAMS(conf, containerManager); rm.start(); MockNM nm1 = rm.registerNode("localhost:1234", 5120); Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(2); acls.put(ApplicationAccessType.VIEW_APP, "*"); RMApp app = rm.submitApp(1024, "appname", "appuser", acls); nm1.nodeHeartbeat(true); int waitCount = 0; while (containerManager.containerTokens == null && waitCount++ < 20) { LOG.info("Waiting for AM Launch to happen.."); Thread.sleep(1000); } Assert.assertNotNull(containerManager.containerTokens); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId(); waitForLaunchedState(attempt); // Create a client to the RM. final Configuration conf = rm.getConfig(); final YarnRPC rpc = YarnRPC.create(conf); UserGroupInformation currentUser = UserGroupInformation .createRemoteUser(applicationAttemptId.toString()); Credentials credentials = containerManager.getContainerCredentials(); final InetSocketAddress rmBindAddress = rm.getApplicationMasterService().getBindAddress(); Token<? extends TokenIdentifier> amRMToken = MockRMWithAMS.setupAndReturnAMRMToken(rmBindAddress, credentials.getAllTokens()); currentUser.addToken(amRMToken); ApplicationMasterProtocol client = currentUser .doAs(new PrivilegedAction<ApplicationMasterProtocol>() { @Override public ApplicationMasterProtocol run() { return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, rm .getApplicationMasterService().getBindAddress(), conf); } }); RegisterApplicationMasterRequest request = Records .newRecord(RegisterApplicationMasterRequest.class); RegisterApplicationMasterResponse response = client.registerApplicationMaster(request); Assert.assertNotNull(response.getClientToAMTokenMasterKey()); if (UserGroupInformation.isSecurityEnabled()) { Assert .assertTrue(response.getClientToAMTokenMasterKey().array().length > 0); } Assert.assertEquals("Register response has bad ACLs", "*", response.getApplicationACLs().get(ApplicationAccessType.VIEW_APP)); } @Test public void testUnauthorizedAccess() throws Exception { MyContainerManager containerManager = new MyContainerManager(); rm = new MockRMWithAMS(conf, containerManager); rm.start(); MockNM nm1 = rm.registerNode("localhost:1234", 5120); RMApp app = rm.submitApp(1024); nm1.nodeHeartbeat(true); int waitCount = 0; while (containerManager.containerTokens == null && waitCount++ < 40) { LOG.info("Waiting for AM Launch to happen.."); Thread.sleep(1000); } Assert.assertNotNull(containerManager.containerTokens); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId(); waitForLaunchedState(attempt); final Configuration conf = rm.getConfig(); final YarnRPC rpc = YarnRPC.create(conf); final InetSocketAddress serviceAddr = conf.getSocketAddr( YarnConfiguration.RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT); UserGroupInformation currentUser = UserGroupInformation .createRemoteUser(applicationAttemptId.toString()); // First try contacting NM without tokens ApplicationMasterProtocol client = currentUser .doAs(new PrivilegedAction<ApplicationMasterProtocol>() { @Override public ApplicationMasterProtocol run() { return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, serviceAddr, conf); } }); RegisterApplicationMasterRequest request = Records .newRecord(RegisterApplicationMasterRequest.class); try { client.registerApplicationMaster(request); Assert.fail("Should fail with authorization error"); } catch (Exception e) { if (isCause(AccessControlException.class, e)) { // Because there are no tokens, the request should be rejected as the // server side will assume we are trying simple auth. String expectedMessage = ""; if (UserGroupInformation.isSecurityEnabled()) { expectedMessage = "Client cannot authenticate via:[TOKEN]"; } else { expectedMessage = "SIMPLE authentication is not enabled. Available:[TOKEN]"; } Assert.assertTrue(e.getCause().getMessage().contains(expectedMessage)); } else { throw e; } } // TODO: Add validation of invalid authorization when there's more data in // the AMRMToken } /** * Identify if an expected throwable included in an exception stack. We use * this because sometimes, an exception will be wrapped to another exception * before thrown. Like, * * <pre> * {@code * void methodA() throws IOException { * try { * // something * } catch (AccessControlException e) { * // do process * throw new IOException(e) * } * } * </pre> * * So we cannot simply catch AccessControlException by using * <pre> * {@code * try { * methodA() * } catch (AccessControlException e) { * // do something * } * </pre> * * This method is useful in such cases. */ private static boolean isCause( Class<? extends Throwable> expected, Throwable e ) { return (e != null) && (expected.isInstance(e) || isCause(expected, e.getCause())); } private void waitForLaunchedState(RMAppAttempt attempt) throws InterruptedException { int waitCount = 0; while (attempt.getAppAttemptState() != RMAppAttemptState.LAUNCHED && waitCount++ < 40) { LOG.info("Waiting for AppAttempt to reach LAUNCHED state. " + "Current state is " + attempt.getAppAttemptState()); Thread.sleep(1000); } Assert.assertEquals(attempt.getAppAttemptState(), RMAppAttemptState.LAUNCHED); } }
12,655
35.578035
107
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.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; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.common.base.Supplier; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.SaslRpcServer.AuthMethod; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.service.Service.STATE; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; 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.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.DrainDispatcher; import org.apache.hadoop.yarn.exceptions.ApplicationAttemptNotFoundException; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.records.NodeAction; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; 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.RMStateStoreAMRMTokenEvent; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreEvent; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreRMDTEvent; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreRMDTMasterKeyEvent; 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.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; public class TestRMRestart extends ParameterizedSchedulerTestBase { private final static File TEMP_DIR = new File(System.getProperty( "test.build.data", "/tmp"), "decommision"); private File hostFile = new File(TEMP_DIR + File.separator + "hostFile.txt"); private YarnConfiguration conf; // Fake rmAddr for token-renewal private static InetSocketAddress rmAddr; private List<MockRM> rms = new ArrayList<MockRM>(); public TestRMRestart(SchedulerType type) { super(type); } @Before public void setup() throws IOException { conf = getConf(); Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); UserGroupInformation.setConfiguration(conf); conf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); conf.setBoolean(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_ENABLED, false); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); rmAddr = new InetSocketAddress("localhost", 8032); Assert.assertTrue(YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS > 1); } @After public void tearDown() { for (MockRM rm : rms) { rm.stop(); } rms.clear(); TEMP_DIR.delete(); } /** * * @return a new MockRM that will be stopped at the end of the test. */ private MockRM createMockRM(YarnConfiguration conf, RMStateStore store) { MockRM rm = new MockRM(conf, store); rms.add(rm); return rm; } @SuppressWarnings("rawtypes") @Test (timeout=180000) public void testRMRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // PHASE 1: create state in an RM // start RM MockRM rm1 = createMockRM(conf, memStore); // start like normal because state is empty rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); MockNM nm2 = new MockNM("127.0.0.2:5678", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); nm2.registerNode(); // nm2 will not heartbeat with RM1 // create app that will finish and the final state should be saved. RMApp app0 = rm1.submitApp(200); RMAppAttempt attempt0 = app0.getCurrentAppAttempt(); // spot check that app is saved Assert.assertEquals(1, rmAppState.size()); nm1.nodeHeartbeat(true); MockAM am0 = rm1.sendAMLaunched(attempt0.getAppAttemptId()); am0.registerAppAttempt(); finishApplicationMaster(app0, rm1, nm1, am0); // create app that gets launched and does allocate before RM restart RMApp app1 = rm1.submitApp(200); // assert app1 info is saved ApplicationStateData appState = rmAppState.get(app1.getApplicationId()); Assert.assertNotNull(appState); Assert.assertEquals(0, appState.getAttemptCount()); Assert.assertEquals(appState.getApplicationSubmissionContext() .getApplicationId(), app1.getApplicationSubmissionContext() .getApplicationId()); //kick the scheduling to allocate AM container nm1.nodeHeartbeat(true); // assert app1 attempt is saved RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); ApplicationAttemptId attemptId1 = attempt1.getAppAttemptId(); rm1.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); Assert.assertEquals(1, appState.getAttemptCount()); ApplicationAttemptStateData attemptState = appState.getAttempt(attemptId1); Assert.assertNotNull(attemptState); Assert.assertEquals(BuilderUtils.newContainerId(attemptId1, 1), attemptState.getMasterContainer().getId()); // launch the AM MockAM am1 = rm1.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); // AM request for containers am1.allocate("127.0.0.1" , 1000, 1, new ArrayList<ContainerId>()); // kick the scheduler nm1.nodeHeartbeat(true); List<Container> conts = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (conts.size() == 0) { nm1.nodeHeartbeat(true); conts.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } // create app that does not get launched by RM before RM restart RMApp app2 = rm1.submitApp(200); // assert app2 info is saved appState = rmAppState.get(app2.getApplicationId()); Assert.assertNotNull(appState); Assert.assertEquals(0, appState.getAttemptCount()); Assert.assertEquals(appState.getApplicationSubmissionContext() .getApplicationId(), app2.getApplicationSubmissionContext() .getApplicationId()); // create unmanaged app RMApp appUnmanaged = rm1.submitApp(200, "someApp", "someUser", null, true, null, conf.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null); ApplicationAttemptId unmanagedAttemptId = appUnmanaged.getCurrentAppAttempt().getAppAttemptId(); // assert appUnmanaged info is saved ApplicationId unmanagedAppId = appUnmanaged.getApplicationId(); appState = rmAppState.get(unmanagedAppId); Assert.assertNotNull(appState); // wait for attempt to reach LAUNCHED state rm1.waitForState(unmanagedAttemptId, RMAppAttemptState.LAUNCHED); rm1.waitForState(unmanagedAppId, RMAppState.ACCEPTED); // assert unmanaged attempt info is saved Assert.assertEquals(1, appState.getAttemptCount()); Assert.assertEquals(appState.getApplicationSubmissionContext() .getApplicationId(), appUnmanaged.getApplicationSubmissionContext() .getApplicationId()); // PHASE 2: create new RM and start from old state // create new RM to represent restart and recover state MockRM rm2 = createMockRM(conf, memStore); // start new RM rm2.start(); // change NM to point to new RM nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm2.setResourceTrackerService(rm2.getResourceTrackerService()); // verify load of old state // 4 apps are loaded. // FINISHED app and attempt is also loaded back. // Unmanaged app state is still loaded back but it cannot be restarted by // the RM. this will change with work preserving RM restart in which AMs/NMs // are not rebooted. Assert.assertEquals(4, rm2.getRMContext().getRMApps().size()); // check that earlier finished app and attempt is also loaded back and move // to finished state. rm2.waitForState(app0.getApplicationId(), RMAppState.FINISHED); rm2.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.FINISHED); // verify correct number of attempts and other data RMApp loadedApp1 = rm2.getRMContext().getRMApps().get(app1.getApplicationId()); Assert.assertNotNull(loadedApp1); Assert.assertEquals(1, loadedApp1.getAppAttempts().size()); Assert.assertEquals(app1.getApplicationSubmissionContext() .getApplicationId(), loadedApp1.getApplicationSubmissionContext() .getApplicationId()); RMApp loadedApp2 = rm2.getRMContext().getRMApps().get(app2.getApplicationId()); Assert.assertNotNull(loadedApp2); //Assert.assertEquals(0, loadedApp2.getAppAttempts().size()); Assert.assertEquals(app2.getApplicationSubmissionContext() .getApplicationId(), loadedApp2.getApplicationSubmissionContext() .getApplicationId()); // verify state machine kicked into expected states rm2.waitForState(loadedApp1.getApplicationId(), RMAppState.ACCEPTED); rm2.waitForState(loadedApp2.getApplicationId(), RMAppState.ACCEPTED); // verify attempts for apps // The app for which AM was started will wait for previous am // container finish event to arrive. However for an application for which // no am container was running will start new application attempt. Assert.assertEquals(1, loadedApp1.getAppAttempts().size()); Assert.assertEquals(1, loadedApp2.getAppAttempts().size()); // verify old AM is not accepted // change running AM to talk to new RM am1.setAMRMProtocol(rm2.getApplicationMasterService(), rm2.getRMContext()); try { am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()); Assert.fail(); } catch (ApplicationAttemptNotFoundException e) { Assert.assertTrue(e instanceof ApplicationAttemptNotFoundException); } // NM should be rebooted on heartbeat, even first heartbeat for nm2 NodeHeartbeatResponse hbResponse = nm1.nodeHeartbeat(true); Assert.assertEquals(NodeAction.RESYNC, hbResponse.getNodeAction()); hbResponse = nm2.nodeHeartbeat(true); Assert.assertEquals(NodeAction.RESYNC, hbResponse.getNodeAction()); // new NM to represent NM re-register nm1 = new MockNM("127.0.0.1:1234", 15120, rm2.getResourceTrackerService()); nm2 = new MockNM("127.0.0.2:5678", 15120, rm2.getResourceTrackerService()); NMContainerStatus status = TestRMRestart .createNMContainerStatus(loadedApp1.getCurrentAppAttempt() .getAppAttemptId(), 1, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(status), null); nm2.registerNode(); rm2.waitForState(loadedApp1.getApplicationId(), RMAppState.ACCEPTED); // wait for the 2nd attempt to be started. int timeoutSecs = 0; while (loadedApp1.getAppAttempts().size() != 2 && timeoutSecs++ < 40) {; Thread.sleep(200); } // verify no more reboot response sent hbResponse = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.RESYNC != hbResponse.getNodeAction()); hbResponse = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.RESYNC != hbResponse.getNodeAction()); // assert app1 attempt is saved attempt1 = loadedApp1.getCurrentAppAttempt(); attemptId1 = attempt1.getAppAttemptId(); rm2.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); appState = rmAppState.get(loadedApp1.getApplicationId()); attemptState = appState.getAttempt(attemptId1); Assert.assertNotNull(attemptState); Assert.assertEquals(BuilderUtils.newContainerId(attemptId1, 1), attemptState.getMasterContainer().getId()); // Nodes on which the AM's run MockNM am1Node = nm1; if (attemptState.getMasterContainer().getNodeId().toString() .contains("127.0.0.2")) { am1Node = nm2; } // assert app2 attempt is saved RMAppAttempt attempt2 = loadedApp2.getCurrentAppAttempt(); ApplicationAttemptId attemptId2 = attempt2.getAppAttemptId(); rm2.waitForState(attemptId2, RMAppAttemptState.ALLOCATED); appState = rmAppState.get(loadedApp2.getApplicationId()); attemptState = appState.getAttempt(attemptId2); Assert.assertNotNull(attemptState); Assert.assertEquals(BuilderUtils.newContainerId(attemptId2, 1), attemptState.getMasterContainer().getId()); MockNM am2Node = nm1; if (attemptState.getMasterContainer().getNodeId().toString() .contains("127.0.0.2")) { am2Node = nm2; } // start the AM's am1 = rm2.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); MockAM am2 = rm2.sendAMLaunched(attempt2.getAppAttemptId()); am2.registerAppAttempt(); //request for containers am1.allocate("127.0.0.1" , 1000, 3, new ArrayList<ContainerId>()); am2.allocate("127.0.0.2" , 1000, 1, new ArrayList<ContainerId>()); // verify container allocate continues to work nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); conts = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (conts.size() == 0) { nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); conts.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } // finish the AMs finishApplicationMaster(loadedApp1, rm2, am1Node, am1); finishApplicationMaster(loadedApp2, rm2, am2Node, am2); // stop RM's rm2.stop(); rm1.stop(); // completed apps are not removed immediately after app finish // And finished app is also loaded back. Assert.assertEquals(4, rmAppState.size()); } @Test (timeout = 60000) public void testRMRestartAppRunningAMFailed() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null, "MAPREDUCE", true, true); MockAM am0 = launchAM(app0, rm1, nm1); // fail the AM by sending CONTAINER_FINISHED event without registering. nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am0.waitForState(RMAppAttemptState.FAILED); ApplicationStateData appState = rmAppState.get(app0.getApplicationId()); // assert the AM failed state is saved. Assert.assertEquals(RMAppAttemptState.FAILED, appState.getAttempt(am0.getApplicationAttemptId()).getState()); // assert app state has not been saved. Assert.assertNull(rmAppState.get(app0.getApplicationId()).getState()); // new AM started but not registered, app still stays at ACCECPTED state. rm1.waitForState(app0.getApplicationId(), RMAppState.ACCEPTED); // start new RM MockRM rm2 = createMockRM(conf, memStore); rm2.start(); // assert the previous AM state is loaded back on RM recovery. rm2.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.FAILED); } @Test (timeout = 60000) public void testRMRestartWaitForPreviousAMToFinish() throws Exception { // testing 3 cases // After RM restarts // 1) New application attempt is not started until previous AM container // finish event is reported back to RM as a part of nm registration. // 2) If previous AM container finish event is never reported back (i.e. // node manager on which this AM container was running also went down) in // that case AMLivenessMonitor should time out previous attempt and start // new attempt. // 3) If all the stored attempts had finished then new attempt should // be started immediately. YarnConfiguration conf = new YarnConfiguration(this.conf); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 40); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // start RM final MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234" , 16382, rm1.getResourceTrackerService()); nm1.registerNode(); // submitting app RMApp app1 = rm1.submitApp(200); rm1.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); MockAM am1 = launchAM(app1, rm1, nm1); nm1.nodeHeartbeat(am1.getApplicationAttemptId(), 1, ContainerState.COMPLETE); // Fail first AM. am1.waitForState(RMAppAttemptState.FAILED); // launch another AM. MockAM am2 = launchAM(app1, rm1, nm1); Assert.assertEquals(1, rmAppState.size()); Assert.assertEquals(app1.getState(), RMAppState.RUNNING); Assert.assertEquals(app1.getAppAttempts() .get(app1.getCurrentAppAttempt().getAppAttemptId()) .getAppAttemptState(), RMAppAttemptState.RUNNING); // start new RM. MockRM rm2 = createMockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); NodeHeartbeatResponse res = nm1.nodeHeartbeat(true); Assert.assertEquals(NodeAction.RESYNC, res.getNodeAction()); RMApp rmApp = rm2.getRMContext().getRMApps().get(app1.getApplicationId()); // application should be in ACCEPTED state rm2.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); Assert.assertEquals(RMAppState.ACCEPTED, rmApp.getState()); // new attempt should not be started Assert.assertEquals(2, rmApp.getAppAttempts().size()); // am1 attempt should be in FAILED state where as am2 attempt should be in // LAUNCHED state rm2.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FAILED); rm2.waitForState(am2.getApplicationAttemptId(), RMAppAttemptState.LAUNCHED); Assert.assertEquals(RMAppAttemptState.FAILED, rmApp.getAppAttempts().get(am1.getApplicationAttemptId()) .getAppAttemptState()); Assert.assertEquals(RMAppAttemptState.LAUNCHED, rmApp.getAppAttempts().get(am2.getApplicationAttemptId()) .getAppAttemptState()); NMContainerStatus status = TestRMRestart.createNMContainerStatus( am2.getApplicationAttemptId(), 1, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(status), null); rm2.waitForState(am2.getApplicationAttemptId(), RMAppAttemptState.FAILED); launchAM(rmApp, rm2, nm1); Assert.assertEquals(3, rmApp.getAppAttempts().size()); rm2.waitForState(rmApp.getCurrentAppAttempt().getAppAttemptId(), RMAppAttemptState.RUNNING); // Now restart RM ... // Setting AMLivelinessMonitor interval to be 10 Secs. conf.setInt(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, 10000); MockRM rm3 = createMockRM(conf, memStore); rm3.start(); // Wait for RM to process all the events as a part of rm recovery. nm1.setResourceTrackerService(rm3.getResourceTrackerService()); rmApp = rm3.getRMContext().getRMApps().get(app1.getApplicationId()); // application should be in ACCEPTED state rm3.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); Assert.assertEquals(rmApp.getState(), RMAppState.ACCEPTED); // new attempt should not be started Assert.assertEquals(3, rmApp.getAppAttempts().size()); // am1 and am2 attempts should be in FAILED state where as am3 should be // in LAUNCHED state rm3.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FAILED); rm3.waitForState(am2.getApplicationAttemptId(), RMAppAttemptState.FAILED); ApplicationAttemptId latestAppAttemptId = rmApp.getCurrentAppAttempt().getAppAttemptId(); rm3.waitForState(latestAppAttemptId, RMAppAttemptState.LAUNCHED); Assert.assertEquals(RMAppAttemptState.FAILED, rmApp.getAppAttempts().get(am1.getApplicationAttemptId()) .getAppAttemptState()); Assert.assertEquals(RMAppAttemptState.FAILED, rmApp.getAppAttempts().get(am2.getApplicationAttemptId()) .getAppAttemptState()); Assert.assertEquals(RMAppAttemptState.LAUNCHED,rmApp.getAppAttempts() .get(latestAppAttemptId).getAppAttemptState()); rm3.waitForState(latestAppAttemptId, RMAppAttemptState.FAILED); rm3.waitForState(rmApp.getApplicationId(), RMAppState.ACCEPTED); final int maxRetry = 10; final RMApp rmAppForCheck = rmApp; GenericTestUtils.waitFor( new Supplier<Boolean>() { @Override public Boolean get() { return new Boolean(rmAppForCheck.getAppAttempts().size() == 4); } }, 100, maxRetry); Assert.assertEquals(RMAppAttemptState.FAILED, rmApp.getAppAttempts().get(latestAppAttemptId).getAppAttemptState()); latestAppAttemptId = rmApp.getCurrentAppAttempt().getAppAttemptId(); // The 4th attempt has started but is not yet saved into RMStateStore // It will be saved only when we launch AM. // submitting app but not starting AM for it. RMApp app2 = rm3.submitApp(200); rm3.waitForState(app2.getApplicationId(), RMAppState.ACCEPTED); Assert.assertEquals(1, app2.getAppAttempts().size()); Assert.assertEquals(0, memStore.getState().getApplicationState().get(app2.getApplicationId()) .getAttemptCount()); MockRM rm4 = createMockRM(conf, memStore); rm4.start(); rmApp = rm4.getRMContext().getRMApps().get(app1.getApplicationId()); rm4.waitForState(rmApp.getApplicationId(), RMAppState.ACCEPTED); // wait for the attempt to be created. int timeoutSecs = 0; while (rmApp.getAppAttempts().size() != 2 && timeoutSecs++ < 40) { Thread.sleep(200); } Assert.assertEquals(4, rmApp.getAppAttempts().size()); Assert.assertEquals(RMAppState.ACCEPTED, rmApp.getState()); rm4.waitForState(latestAppAttemptId, RMAppAttemptState.SCHEDULED); Assert.assertEquals(RMAppAttemptState.SCHEDULED, rmApp.getAppAttempts() .get(latestAppAttemptId).getAppAttemptState()); // The initial application for which an AM was not started should be in // ACCEPTED state with one application attempt started. app2 = rm4.getRMContext().getRMApps().get(app2.getApplicationId()); rm4.waitForState(app2.getApplicationId(), RMAppState.ACCEPTED); Assert.assertEquals(RMAppState.ACCEPTED, app2.getState()); Assert.assertEquals(1, app2.getAppAttempts().size()); rm4.waitForState(app2.getCurrentAppAttempt().getAppAttemptId(), RMAppAttemptState.SCHEDULED); Assert.assertEquals(RMAppAttemptState.SCHEDULED, app2 .getCurrentAppAttempt().getAppAttemptState()); } // Test RM restarts after previous attempt succeeded and was saved into state // store but before the RMAppAttempt notifies RMApp that it has succeeded. On // recovery, RMAppAttempt should send the AttemptFinished event to RMApp so // that RMApp can recover its state. @Test (timeout = 60000) public void testRMRestartWaitForPreviousSucceededAttempt() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); MemoryRMStateStore memStore = new MemoryRMStateStore() { int count = 0; @Override public void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws Exception { if (count == 0) { // do nothing; simulate app final state is not saved. LOG.info(appId + " final state is not saved."); count++; } else { super.updateApplicationStateInternal(appId, appStateData); } } }; memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = rm1.registerNode("127.0.0.1:1234", 15120); RMApp app0 = rm1.submitApp(200); MockAM am0 = MockRM.launchAndRegisterAM(app0, rm1, nm1); FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.SUCCEEDED, "", ""); am0.unregisterAppAttempt(req, true); am0.waitForState(RMAppAttemptState.FINISHING); // app final state is not saved. This guarantees that RMApp cannot be // recovered via its own saved state, but only via the event notification // from the RMAppAttempt on recovery. Assert.assertNull(rmAppState.get(app0.getApplicationId()).getState()); // start RM MockRM rm2 = createMockRM(conf, memStore); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); rm2.start(); rm2.waitForState(app0.getCurrentAppAttempt().getAppAttemptId(), RMAppAttemptState.FINISHED); rm2.waitForState(app0.getApplicationId(), RMAppState.FINISHED); // app final state is saved via the finish event from attempt. Assert.assertEquals(RMAppState.FINISHED, rmAppState.get(app0.getApplicationId()).getState()); } @Test (timeout = 60000) public void testRMRestartFailedApp() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // fail the AM by sending CONTAINER_FINISHED event without registering. nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am0.waitForState(RMAppAttemptState.FAILED); rm1.waitForState(app0.getApplicationId(), RMAppState.FAILED); // assert the app/attempt failed state is saved. ApplicationStateData appState = rmAppState.get(app0.getApplicationId()); Assert.assertEquals(RMAppState.FAILED, appState.getState()); Assert.assertEquals(RMAppAttemptState.FAILED, appState.getAttempt(am0.getApplicationAttemptId()).getState()); // start new RM MockRM rm2 = createMockRM(conf, memStore); rm2.start(); RMApp loadedApp0 = rm2.getRMContext().getRMApps().get(app0.getApplicationId()); rm2.waitForState(app0.getApplicationId(), RMAppState.FAILED); rm2.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.FAILED); // no new attempt is created. Assert.assertEquals(1, loadedApp0.getAppAttempts().size()); verifyAppReportAfterRMRestart(app0, rm2); Assert.assertTrue(app0.getDiagnostics().toString() .contains("Failing the application.")); // failed diagnostics from attempt is lost because the diagnostics from // attempt is not yet available by the time app is saving the app state. } @Test (timeout = 60000) public void testRMRestartKilledApp() throws Exception{ conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // kill the app. rm1.killApp(app0.getApplicationId()); rm1.waitForState(app0.getApplicationId(), RMAppState.KILLED); rm1.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.KILLED); // killed state is saved. ApplicationStateData appState = rmAppState.get(app0.getApplicationId()); Assert.assertEquals(RMAppState.KILLED, appState.getState()); Assert.assertEquals(RMAppAttemptState.KILLED, appState.getAttempt(am0.getApplicationAttemptId()).getState()); String trackingUrl = app0.getCurrentAppAttempt().getOriginalTrackingUrl(); Assert.assertNotNull(trackingUrl); // restart rm MockRM rm2 = createMockRM(conf, memStore); rm2.start(); RMApp loadedApp0 = rm2.getRMContext().getRMApps().get(app0.getApplicationId()); rm2.waitForState(app0.getApplicationId(), RMAppState.KILLED); rm2.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.KILLED); // no new attempt is created. Assert.assertEquals(1, loadedApp0.getAppAttempts().size()); ApplicationReport appReport = verifyAppReportAfterRMRestart(app0, rm2); Assert.assertEquals(app0.getDiagnostics().toString(), appReport.getDiagnostics()); Assert.assertEquals(trackingUrl, loadedApp0.getCurrentAppAttempt() .getOriginalTrackingUrl()); } @Test (timeout = 60000) public void testRMRestartKilledAppWithNoAttempts() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore() { @Override public synchronized void storeApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception { // ignore attempt saving request. } @Override public synchronized void updateApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception { // ignore attempt saving request. } }; memStore.init(conf); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); // create app RMApp app0 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null, "MAPREDUCE", false); // kill the app. rm1.killApp(app0.getApplicationId()); rm1.waitForState(app0.getApplicationId(), RMAppState.KILLED); // restart rm MockRM rm2 = createMockRM(conf, memStore); rm2.start(); RMApp loadedApp0 = rm2.getRMContext().getRMApps().get(app0.getApplicationId()); rm2.waitForState(loadedApp0.getApplicationId(), RMAppState.KILLED); Assert.assertTrue(loadedApp0.getAppAttempts().size() == 0); } @Test (timeout = 60000) public void testRMRestartSucceededApp() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create an app and finish the app. RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // unregister am FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.SUCCEEDED, "diagnostics", "trackingUrl"); finishApplicationMaster(app0, rm1, nm1, am0, req); // check the state store about the unregistered info. ApplicationStateData appState = rmAppState.get(app0.getApplicationId()); ApplicationAttemptStateData attemptState0 = appState.getAttempt(am0.getApplicationAttemptId()); Assert.assertEquals("diagnostics", attemptState0.getDiagnostics()); Assert.assertEquals(FinalApplicationStatus.SUCCEEDED, attemptState0.getFinalApplicationStatus()); Assert.assertEquals("trackingUrl", attemptState0.getFinalTrackingUrl()); Assert.assertEquals(app0.getFinishTime(), appState.getFinishTime()); // restart rm MockRM rm2 = createMockRM(conf, memStore); rm2.start(); // verify application report returns the same app info as the app info // before RM restarts. ApplicationReport appReport = verifyAppReportAfterRMRestart(app0, rm2); Assert.assertEquals(FinalApplicationStatus.SUCCEEDED, appReport.getFinalApplicationStatus()); Assert.assertEquals("trackingUrl", appReport.getOriginalTrackingUrl()); } @Test (timeout = 60000) public void testRMRestartGetApplicationList() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // a succeeded app. RMApp app0 = rm1.submitApp(200, "name", "user", null, false, "default", 1, null, "myType"); MockAM am0 = launchAM(app0, rm1, nm1); finishApplicationMaster(app0, rm1, nm1, am0); // a failed app. RMApp app1 = rm1.submitApp(200, "name", "user", null, false, "default", 1, null, "myType"); MockAM am1 = launchAM(app1, rm1, nm1); // fail the AM by sending CONTAINER_FINISHED event without registering. nm1.nodeHeartbeat(am1.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am1.waitForState(RMAppAttemptState.FAILED); rm1.waitForState(app1.getApplicationId(), RMAppState.FAILED); // a killed app. RMApp app2 = rm1.submitApp(200, "name", "user", null, false, "default", 1, null, "myType"); MockAM am2 = launchAM(app2, rm1, nm1); rm1.killApp(app2.getApplicationId()); rm1.waitForState(app2.getApplicationId(), RMAppState.KILLED); rm1.waitForState(am2.getApplicationAttemptId(), RMAppAttemptState.KILLED); // restart rm MockRM rm2 = new MockRM(conf, memStore) { @Override protected RMAppManager createRMAppManager() { return spy(super.createRMAppManager()); } }; rms.add(rm2); rm2.start(); GetApplicationsRequest request1 = GetApplicationsRequest.newInstance(EnumSet.of( YarnApplicationState.FINISHED, YarnApplicationState.KILLED, YarnApplicationState.FAILED)); GetApplicationsResponse response1 = rm2.getClientRMService().getApplications(request1); List<ApplicationReport> appList1 = response1.getApplicationList(); // assert all applications exist according to application state after RM // restarts. boolean forApp0 = false, forApp1 = false, forApp2 = false; for (ApplicationReport report : appList1) { if (report.getApplicationId().equals(app0.getApplicationId())) { Assert.assertEquals(YarnApplicationState.FINISHED, report.getYarnApplicationState()); forApp0 = true; } if (report.getApplicationId().equals(app1.getApplicationId())) { Assert.assertEquals(YarnApplicationState.FAILED, report.getYarnApplicationState()); forApp1 = true; } if (report.getApplicationId().equals(app2.getApplicationId())) { Assert.assertEquals(YarnApplicationState.KILLED, report.getYarnApplicationState()); forApp2 = true; } } Assert.assertTrue(forApp0 && forApp1 && forApp2); // assert all applications exist according to application type after RM // restarts. Set<String> appTypes = new HashSet<String>(); appTypes.add("myType"); GetApplicationsRequest request2 = GetApplicationsRequest.newInstance(appTypes); GetApplicationsResponse response2 = rm2.getClientRMService().getApplications(request2); List<ApplicationReport> appList2 = response2.getApplicationList(); Assert.assertTrue(3 == appList2.size()); // check application summary is logged for the completed apps with timeout // to make sure APP_COMPLETED events are processed, after RM restart. verify(rm2.getRMAppManager(), timeout(1000).times(3)). logApplicationSummary(isA(ApplicationId.class)); } private MockAM launchAM(RMApp app, MockRM rm, MockNM nm) throws Exception { RMAppAttempt attempt = app.getCurrentAppAttempt(); nm.nodeHeartbeat(true); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); return am; } private ApplicationReport verifyAppReportAfterRMRestart(RMApp app, MockRM rm) throws Exception { GetApplicationReportRequest reportRequest = GetApplicationReportRequest.newInstance(app.getApplicationId()); GetApplicationReportResponse response = rm.getClientRMService().getApplicationReport(reportRequest); ApplicationReport report = response.getApplicationReport(); Assert.assertEquals(app.getStartTime(), report.getStartTime()); Assert.assertEquals(app.getFinishTime(), report.getFinishTime()); Assert.assertEquals(app.createApplicationState(), report.getYarnApplicationState()); Assert.assertTrue(1 == report.getProgress()); return response.getApplicationReport(); } private void finishApplicationMaster(RMApp rmApp, MockRM rm, MockNM nm, MockAM am) throws Exception { final FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.SUCCEEDED, "", ""); finishApplicationMaster(rmApp, rm, nm, am, req); } private void finishApplicationMaster(RMApp rmApp, MockRM rm, MockNM nm, MockAM am, FinishApplicationMasterRequest req) throws Exception { RMState rmState = ((MemoryRMStateStore) rm.getRMContext().getStateStore()).getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); am.unregisterAppAttempt(req,true); am.waitForState(RMAppAttemptState.FINISHING); nm.nodeHeartbeat(am.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); rm.waitForState(rmApp.getApplicationId(), RMAppState.FINISHED); // check that app/attempt is saved with the final state ApplicationStateData appState = rmAppState.get(rmApp.getApplicationId()); Assert .assertEquals(RMAppState.FINISHED, appState.getState()); Assert.assertEquals(RMAppAttemptState.FINISHED, appState.getAttempt(am.getApplicationAttemptId()).getState()); } @Test (timeout = 60000) public void testRMRestartOnMaxAppAttempts() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // submit an app with maxAppAttempts equals to 1 RMApp app1 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", 1, null); // submit an app with maxAppAttempts equals to -1 RMApp app2 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null); // assert app1 info is saved ApplicationStateData appState = rmAppState.get(app1.getApplicationId()); Assert.assertNotNull(appState); Assert.assertEquals(0, appState.getAttemptCount()); Assert.assertEquals(appState.getApplicationSubmissionContext() .getApplicationId(), app1.getApplicationSubmissionContext() .getApplicationId()); // Allocate the AM nm1.nodeHeartbeat(true); RMAppAttempt attempt = app1.getCurrentAppAttempt(); ApplicationAttemptId attemptId1 = attempt.getAppAttemptId(); rm1.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); Assert.assertEquals(1, appState.getAttemptCount()); ApplicationAttemptStateData attemptState = appState.getAttempt(attemptId1); Assert.assertNotNull(attemptState); Assert.assertEquals(BuilderUtils.newContainerId(attemptId1, 1), attemptState.getMasterContainer().getId()); // Setting AMLivelinessMonitor interval to be 3 Secs. conf.setInt(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, 3000); // start new RM MockRM rm2 = createMockRM(conf, memStore); rm2.start(); // verify that maxAppAttempts is set to global value Assert.assertEquals(2, rm2.getRMContext().getRMApps().get(app2.getApplicationId()) .getMaxAppAttempts()); // app1 and app2 are loaded back, but app1 failed because it's // hitting max-retry. Assert.assertEquals(2, rm2.getRMContext().getRMApps().size()); rm2.waitForState(app1.getApplicationId(), RMAppState.FAILED); rm2.waitForState(app2.getApplicationId(), RMAppState.ACCEPTED); // app1 failed state is saved in state store. app2 final saved state is not // determined yet. Assert.assertEquals(RMAppState.FAILED, rmAppState.get(app1.getApplicationId()).getState()); Assert.assertNull(rmAppState.get(app2.getApplicationId()).getState()); } @Test (timeout = 60000) public void testDelegationTokenRestoredInDelegationTokenRenewer() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); MockRM rm1 = new TestSecurityMockRM(conf, memStore); rm1.start(); HashSet<Token<RMDelegationTokenIdentifier>> tokenSet = new HashSet<Token<RMDelegationTokenIdentifier>>(); // create an empty credential Credentials ts = new Credentials(); // create tokens and add into credential Text userText1 = new Text("user1"); RMDelegationTokenIdentifier dtId1 = new RMDelegationTokenIdentifier(userText1, new Text("renewer1"), userText1); Token<RMDelegationTokenIdentifier> token1 = new Token<RMDelegationTokenIdentifier>(dtId1, rm1.getRMContext().getRMDelegationTokenSecretManager()); SecurityUtil.setTokenService(token1, rmAddr); ts.addToken(userText1, token1); tokenSet.add(token1); Text userText2 = new Text("user2"); RMDelegationTokenIdentifier dtId2 = new RMDelegationTokenIdentifier(userText2, new Text("renewer2"), userText2); Token<RMDelegationTokenIdentifier> token2 = new Token<RMDelegationTokenIdentifier>(dtId2, rm1.getRMContext().getRMDelegationTokenSecretManager()); SecurityUtil.setTokenService(token2, rmAddr); ts.addToken(userText2, token2); tokenSet.add(token2); // submit an app with customized credential RMApp app = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", 1, ts); // assert app info is saved ApplicationStateData appState = rmAppState.get(app.getApplicationId()); Assert.assertNotNull(appState); // assert delegation tokens exist in rm1 DelegationTokenRenewr Assert.assertEquals(tokenSet, rm1.getRMContext() .getDelegationTokenRenewer().getDelegationTokens()); // assert delegation tokens are saved DataOutputBuffer dob = new DataOutputBuffer(); ts.writeTokenStorageToStream(dob); ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); securityTokens.rewind(); Assert.assertEquals(securityTokens, appState .getApplicationSubmissionContext().getAMContainerSpec() .getTokens()); // start new RM MockRM rm2 = new TestSecurityMockRM(conf, memStore); rm2.start(); // Need to wait for a while as now token renewal happens on another thread // and is asynchronous in nature. waitForTokensToBeRenewed(rm2); // verify tokens are properly populated back to rm2 DelegationTokenRenewer Assert.assertEquals(tokenSet, rm2.getRMContext() .getDelegationTokenRenewer().getDelegationTokens()); } private void waitForTokensToBeRenewed(MockRM rm2) throws Exception { int waitCnt = 20; boolean atleastOneAppInNEWState = true; while (waitCnt-- > 0 && atleastOneAppInNEWState) { atleastOneAppInNEWState = false; for (RMApp rmApp : rm2.getRMContext().getRMApps().values()) { if (rmApp.getState() == RMAppState.NEW) { Thread.sleep(1000); atleastOneAppInNEWState = true; break; } } } } @Test (timeout = 60000) public void testAppAttemptTokensRestoredOnRMRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); MockRM rm1 = new TestSecurityMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("0.0.0.0:4321", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // submit an app RMApp app1 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), "default"); // assert app info is saved ApplicationStateData appState = rmAppState.get(app1.getApplicationId()); Assert.assertNotNull(appState); // Allocate the AM nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); ApplicationAttemptId attemptId1 = attempt1.getAppAttemptId(); rm1.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); // assert attempt info is saved ApplicationAttemptStateData attemptState = appState.getAttempt(attemptId1); Assert.assertNotNull(attemptState); Assert.assertEquals(BuilderUtils.newContainerId(attemptId1, 1), attemptState.getMasterContainer().getId()); // the clientTokenMasterKey that are generated when // RMAppAttempt is created, byte[] clientTokenMasterKey = attempt1.getClientTokenMasterKey().getEncoded(); // assert application credentials are saved Credentials savedCredentials = attemptState.getAppAttemptTokens(); Assert.assertArrayEquals("client token master key not saved", clientTokenMasterKey, savedCredentials.getSecretKey( RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME)); // start new RM MockRM rm2 = new TestSecurityMockRM(conf, memStore); rm2.start(); RMApp loadedApp1 = rm2.getRMContext().getRMApps().get(app1.getApplicationId()); RMAppAttempt loadedAttempt1 = loadedApp1.getRMAppAttempt(attemptId1); // assert loaded attempt recovered Assert.assertNotNull(loadedAttempt1); // assert client token master key is recovered back to api-versioned // client token master key Assert.assertEquals("client token master key not restored", attempt1.getClientTokenMasterKey(), loadedAttempt1.getClientTokenMasterKey()); // assert ClientTokenSecretManager also knows about the key Assert.assertArrayEquals(clientTokenMasterKey, rm2.getClientToAMTokenSecretManager().getMasterKey(attemptId1) .getEncoded()); // assert AMRMTokenSecretManager also knows about the AMRMToken password Token<AMRMTokenIdentifier> amrmToken = loadedAttempt1.getAMRMToken(); Assert.assertArrayEquals(amrmToken.getPassword(), rm2.getRMContext().getAMRMTokenSecretManager().retrievePassword( amrmToken.decodeIdentifier())); } @Test (timeout = 60000) public void testRMDelegationTokenRestoredOnRMRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); conf.set( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); conf.set(YarnConfiguration.RM_ADDRESS, "localhost:8032"); UserGroupInformation.setConfiguration(conf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); RMState rmState = memStore.getState(); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); Map<RMDelegationTokenIdentifier, Long> rmDTState = rmState.getRMDTSecretManagerState().getTokenState(); Set<DelegationKey> rmDTMasterKeyState = rmState.getRMDTSecretManagerState().getMasterKeyState(); MockRM rm1 = new TestSecurityMockRM(conf, memStore); rm1.start(); // create an empty credential Credentials ts = new Credentials(); // request a token and add into credential GetDelegationTokenRequest request1 = GetDelegationTokenRequest.newInstance("renewer1"); UserGroupInformation.getCurrentUser().setAuthenticationMethod( AuthMethod.KERBEROS); GetDelegationTokenResponse response1 = rm1.getClientRMService().getDelegationToken(request1); org.apache.hadoop.yarn.api.records.Token delegationToken1 = response1.getRMDelegationToken(); Token<RMDelegationTokenIdentifier> token1 = ConverterUtils.convertFromYarn(delegationToken1, rmAddr); RMDelegationTokenIdentifier dtId1 = token1.decodeIdentifier(); HashSet<RMDelegationTokenIdentifier> tokenIdentSet = new HashSet<RMDelegationTokenIdentifier>(); ts.addToken(token1.getService(), token1); tokenIdentSet.add(dtId1); // submit an app with customized credential RMApp app = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", 1, ts); // assert app info is saved ApplicationStateData appState = rmAppState.get(app.getApplicationId()); Assert.assertNotNull(appState); // assert all master keys are saved Set<DelegationKey> allKeysRM1 = rm1.getRMContext() .getRMDelegationTokenSecretManager().getAllMasterKeys(); Assert.assertEquals(allKeysRM1, rmDTMasterKeyState); // assert all tokens are saved Map<RMDelegationTokenIdentifier, Long> allTokensRM1 = rm1.getRMContext().getRMDelegationTokenSecretManager().getAllTokens(); Assert.assertEquals(tokenIdentSet, allTokensRM1.keySet()); Assert.assertEquals(allTokensRM1, rmDTState); // assert sequence number is saved Assert.assertEquals(rm1.getRMContext().getRMDelegationTokenSecretManager() .getLatestDTSequenceNumber(), rmState.getRMDTSecretManagerState() .getDTSequenceNumber()); // request one more token GetDelegationTokenRequest request2 = GetDelegationTokenRequest.newInstance("renewer2"); GetDelegationTokenResponse response2 = rm1.getClientRMService().getDelegationToken(request2); org.apache.hadoop.yarn.api.records.Token delegationToken2 = response2.getRMDelegationToken(); Token<RMDelegationTokenIdentifier> token2 = ConverterUtils.convertFromYarn(delegationToken2, rmAddr); RMDelegationTokenIdentifier dtId2 = token2.decodeIdentifier(); // cancel token2 try{ rm1.getRMContext().getRMDelegationTokenSecretManager().cancelToken(token2, UserGroupInformation.getCurrentUser().getUserName()); } catch(Exception e) { Assert.fail(); } // Assert the token which has the latest delegationTokenSequenceNumber is removed Assert.assertEquals(rm1.getRMContext().getRMDelegationTokenSecretManager() .getLatestDTSequenceNumber(), dtId2.getSequenceNumber()); Assert.assertFalse(rmDTState.containsKey(dtId2)); // start new RM MockRM rm2 = new TestSecurityMockRM(conf, memStore); rm2.start(); // assert master keys and tokens are populated back to DTSecretManager Map<RMDelegationTokenIdentifier, Long> allTokensRM2 = rm2.getRMContext().getRMDelegationTokenSecretManager().getAllTokens(); Assert.assertEquals(allTokensRM2.keySet(), allTokensRM1.keySet()); // rm2 has its own master keys when it starts, we use containsAll here Assert.assertTrue(rm2.getRMContext().getRMDelegationTokenSecretManager() .getAllMasterKeys().containsAll(allKeysRM1)); // assert sequenceNumber is properly recovered, // even though the token which has max sequenceNumber is not stored Assert.assertEquals(rm1.getRMContext().getRMDelegationTokenSecretManager() .getLatestDTSequenceNumber(), rm2.getRMContext() .getRMDelegationTokenSecretManager().getLatestDTSequenceNumber()); // renewDate before renewing Long renewDateBeforeRenew = allTokensRM2.get(dtId1); try{ // Sleep for one millisecond to make sure renewDataAfterRenew is greater Thread.sleep(1); // renew recovered token rm2.getRMContext().getRMDelegationTokenSecretManager().renewToken( token1, "renewer1"); } catch(Exception e) { Assert.fail(); } allTokensRM2 = rm2.getRMContext().getRMDelegationTokenSecretManager() .getAllTokens(); Long renewDateAfterRenew = allTokensRM2.get(dtId1); // assert token is renewed Assert.assertTrue(renewDateAfterRenew > renewDateBeforeRenew); // assert new token is added into state store Assert.assertTrue(rmDTState.containsValue(renewDateAfterRenew)); // assert old token is removed from state store Assert.assertFalse(rmDTState.containsValue(renewDateBeforeRenew)); try{ rm2.getRMContext().getRMDelegationTokenSecretManager().cancelToken(token1, UserGroupInformation.getCurrentUser().getUserName()); } catch(Exception e) { Assert.fail(); } // assert token is removed from state after its cancelled allTokensRM2 = rm2.getRMContext().getRMDelegationTokenSecretManager() .getAllTokens(); Assert.assertFalse(allTokensRM2.containsKey(dtId1)); Assert.assertFalse(rmDTState.containsKey(dtId1)); } // This is to test submit an application to the new RM with the old delegation // token got from previous RM. @Test (timeout = 60000) public void testAppSubmissionWithOldDelegationTokenAfterRMRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); conf.set(YarnConfiguration.RM_ADDRESS, "localhost:8032"); UserGroupInformation.setConfiguration(conf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm1 = new TestSecurityMockRM(conf, memStore); rm1.start(); GetDelegationTokenRequest request1 = GetDelegationTokenRequest.newInstance("renewer1"); UserGroupInformation.getCurrentUser().setAuthenticationMethod( AuthMethod.KERBEROS); GetDelegationTokenResponse response1 = rm1.getClientRMService().getDelegationToken(request1); Token<RMDelegationTokenIdentifier> token1 = ConverterUtils.convertFromYarn(response1.getRMDelegationToken(), rmAddr); // start new RM MockRM rm2 = new TestSecurityMockRM(conf, memStore); rm2.start(); // submit an app with the old delegation token got from previous RM. Credentials ts = new Credentials(); ts.addToken(token1.getService(), token1); RMApp app = rm2.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", 1, ts); rm2.waitForState(app.getApplicationId(), RMAppState.ACCEPTED); } @Test (timeout = 60000) public void testRMStateStoreDispatcherDrainedOnRMStop() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore() { volatile boolean wait = true; @Override public void serviceStop() throws Exception { // Unblock app saving request. wait = false; super.serviceStop(); } @Override protected void handleStoreEvent(RMStateStoreEvent event) { // Block app saving request. // Skip if synchronous updation of DTToken if (!(event instanceof RMStateStoreAMRMTokenEvent) && !(event instanceof RMStateStoreRMDTEvent) && !(event instanceof RMStateStoreRMDTMasterKeyEvent)) { while (wait); } super.handleStoreEvent(event); } }; memStore.init(conf); // start RM final MockRM rm1 = createMockRM(conf, memStore); rm1.start(); // create apps. final ArrayList<RMApp> appList = new ArrayList<RMApp>(); final int NUM_APPS = 5; for (int i = 0; i < NUM_APPS; i++) { RMApp app = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null, "MAPREDUCE", false); appList.add(app); rm1.waitForState(app.getApplicationId(), RMAppState.NEW_SAVING); } // all apps's saving request are now enqueued to RMStateStore's dispatcher // queue, and will be processed once rm.stop() is called. // Nothing exist in state store before stop is called. Map<ApplicationId, ApplicationStateData> rmAppState = memStore.getState().getApplicationState(); Assert.assertTrue(rmAppState.size() == 0); // stop rm rm1.stop(); // Assert app info is still saved even if stop is called with pending saving // request on dispatcher. for (RMApp app : appList) { ApplicationStateData appState = rmAppState.get(app.getApplicationId()); Assert.assertNotNull(appState); Assert.assertEquals(0, appState.getAttemptCount()); Assert.assertEquals(appState.getApplicationSubmissionContext() .getApplicationId(), app.getApplicationSubmissionContext() .getApplicationId()); } Assert.assertTrue(rmAppState.size() == NUM_APPS); } @Test (timeout = 60000) public void testFinishedAppRemovalAfterRMRestart() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 1); memStore.init(conf); RMState rmState = memStore.getState(); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create an app and finish the app. RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); finishApplicationMaster(app0, rm1, nm1, am0); MockRM rm2 = createMockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm1 = rm2.registerNode("127.0.0.1:1234", 15120); Map<ApplicationId, ApplicationStateData> rmAppState = rmState.getApplicationState(); // app0 exits in both state store and rmContext Assert.assertEquals(RMAppState.FINISHED, rmAppState.get(app0.getApplicationId()).getState()); rm2.waitForState(app0.getApplicationId(), RMAppState.FINISHED); // create one more app and finish the app. RMApp app1 = rm2.submitApp(200); MockAM am1 = launchAM(app1, rm2, nm1); finishApplicationMaster(app1, rm2, nm1, am1); // the first app0 get kicked out from both rmContext and state store Assert.assertNull(rm2.getRMContext().getRMApps() .get(app0.getApplicationId())); Assert.assertNull(rmAppState.get(app0.getApplicationId())); } // This is to test RM does not get hang on shutdown. @Test (timeout = 10000) public void testRMShutdown() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore() { @Override public synchronized void checkVersion() throws Exception { throw new Exception("Invalid version."); } }; // start RM memStore.init(conf); MockRM rm1 = null; try { rm1 = createMockRM(conf, memStore); rm1.start(); Assert.fail(); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Invalid version.")); } Assert.assertTrue(rm1.getServiceState() == STATE.STOPPED); } // This is to test Killing application should be able to wait until app // reaches killed state and also check that attempt state is saved before app // state is saved. @Test (timeout = 60000) public void testClientRetryOnKillingApplication() throws Exception { MemoryRMStateStore memStore = new TestMemoryRMStateStore(); memStore.init(conf); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200, "name", "user", null, false, "default", 1, null, "myType"); MockAM am1 = launchAM(app1, rm1, nm1); KillApplicationResponse response; int count = 0; while (true) { response = rm1.killApp(app1.getApplicationId()); if (response.getIsKillCompleted()) { break; } Thread.sleep(100); count++; } // we expect at least 2 calls for killApp as the first killApp always return // false. Assert.assertTrue(count >= 1); rm1.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.KILLED); rm1.waitForState(app1.getApplicationId(), RMAppState.KILLED); Assert.assertEquals(1, ((TestMemoryRMStateStore) memStore).updateAttempt); Assert.assertEquals(2, ((TestMemoryRMStateStore) memStore).updateApp); } // Test Application that fails on submission is saved in state store. @Test (timeout = 20000) public void testAppFailedOnSubmissionSavedInStateStore() throws Exception { conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm1 = new TestSecurityMockRM(conf, memStore) { @Override protected RMAppManager createRMAppManager() { return new TestRMAppManager(this.rmContext, this.scheduler, this.masterService, this.applicationACLsManager, conf); } class TestRMAppManager extends RMAppManager { public TestRMAppManager(RMContext context, YarnScheduler scheduler, ApplicationMasterService masterService, ApplicationACLsManager applicationACLsManager, Configuration conf) { super(context, scheduler, masterService, applicationACLsManager, conf); } @Override protected Credentials parseCredentials( ApplicationSubmissionContext application) throws IOException { throw new IOException("Parsing credential error."); } } }; rm1.start(); RMApp app1 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null, "MAPREDUCE", false); rm1.waitForState(app1.getApplicationId(), RMAppState.FAILED); // Check app staet is saved in state store. Assert.assertEquals(RMAppState.FAILED, memStore.getState() .getApplicationState().get(app1.getApplicationId()).getState()); MockRM rm2 = new TestSecurityMockRM(conf, memStore); rm2.start(); // Restarted RM has the failed app info too. rm2.waitForState(app1.getApplicationId(), RMAppState.FAILED); } @Test (timeout = 20000) public void testAppRecoveredInOrderOnRMRestart() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); for (int i = 10; i > 0; i--) { ApplicationStateData appState = mock(ApplicationStateData.class); ApplicationSubmissionContext context = mock(ApplicationSubmissionContext.class); when(appState.getApplicationSubmissionContext()).thenReturn(context); when(context.getApplicationId()).thenReturn( ApplicationId.newInstance(1234, i)); memStore.getState().getApplicationState().put( appState.getApplicationSubmissionContext().getApplicationId(), appState); } MockRM rm1 = new MockRM(conf, memStore) { @Override protected RMAppManager createRMAppManager() { return new TestRMAppManager(this.rmContext, this.scheduler, this.masterService, this.applicationACLsManager, conf); } class TestRMAppManager extends RMAppManager { ApplicationId prevId = ApplicationId.newInstance(1234, 0); public TestRMAppManager(RMContext context, YarnScheduler scheduler, ApplicationMasterService masterService, ApplicationACLsManager applicationACLsManager, Configuration conf) { super(context, scheduler, masterService, applicationACLsManager, conf); } @Override protected void recoverApplication(ApplicationStateData appState, RMState rmState) throws Exception { // check application is recovered in order. Assert.assertTrue(rmState.getApplicationState().size() > 0); Assert.assertTrue(appState.getApplicationSubmissionContext() .getApplicationId().compareTo(prevId) > 0); prevId = appState.getApplicationSubmissionContext().getApplicationId(); } } }; try { rm1.start(); } finally { rm1.stop(); } } @SuppressWarnings("resource") @Test (timeout = 60000) public void testQueueMetricsOnRMRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // PHASE 1: create state in an RM // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); QueueMetrics qm1 = rm1.getResourceScheduler().getRootQueueMetrics(); resetQueueMetrics(qm1); assertQueueMetrics(qm1, 0, 0, 0, 0); // create app that gets launched and does allocate before RM restart RMApp app1 = rm1.submitApp(200); // Need to wait first for AppAttempt to be started (RMAppState.ACCEPTED) // and then for it to reach RMAppAttemptState.SCHEDULED // inorder to ensure appsPending metric is incremented rm1.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); ApplicationAttemptId attemptId1 = attempt1.getAppAttemptId(); rm1.waitForState(attemptId1, RMAppAttemptState.SCHEDULED); assertQueueMetrics(qm1, 1, 1, 0, 0); nm1.nodeHeartbeat(true); rm1.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); MockAM am1 = rm1.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); am1.allocate("127.0.0.1" , 1000, 1, new ArrayList<ContainerId>()); nm1.nodeHeartbeat(true); List<Container> conts = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (conts.size() == 0) { nm1.nodeHeartbeat(true); conts.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } assertQueueMetrics(qm1, 1, 0, 1, 0); // PHASE 2: create new RM and start from old state // create new RM to represent restart and recover state MockRM rm2 = createMockRM(conf, memStore); QueueMetrics qm2 = rm2.getResourceScheduler().getRootQueueMetrics(); resetQueueMetrics(qm2); assertQueueMetrics(qm2, 0, 0, 0, 0); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); // recover app RMApp loadedApp1 = rm2.getRMContext().getRMApps().get(app1.getApplicationId()); nm1.nodeHeartbeat(true); nm1 = new MockNM("127.0.0.1:1234", 15120, rm2.getResourceTrackerService()); NMContainerStatus status = TestRMRestart .createNMContainerStatus(loadedApp1.getCurrentAppAttempt() .getAppAttemptId(), 1, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(status), null); while (loadedApp1.getAppAttempts().size() != 2) { Thread.sleep(200); } attempt1 = loadedApp1.getCurrentAppAttempt(); attemptId1 = attempt1.getAppAttemptId(); rm2.waitForState(attemptId1, RMAppAttemptState.SCHEDULED); assertQueueMetrics(qm2, 1, 1, 0, 0); nm1.nodeHeartbeat(true); rm2.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); assertQueueMetrics(qm2, 1, 0, 1, 0); am1 = rm2.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); am1.allocate("127.0.0.1" , 1000, 3, new ArrayList<ContainerId>()); nm1.nodeHeartbeat(true); conts = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (conts.size() == 0) { nm1.nodeHeartbeat(true); conts.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } // finish the AMs finishApplicationMaster(loadedApp1, rm2, nm1, am1); assertQueueMetrics(qm2, 1, 0, 0, 1); } // The metrics has some carry-on value from the previous RM, because the // test case is in-memory, for the same queue name (e.g. root), there's // always a singleton QueueMetrics object. private int appsSubmittedCarryOn = 0; private int appsPendingCarryOn = 0; private int appsRunningCarryOn = 0; private int appsCompletedCarryOn = 0; private void resetQueueMetrics(QueueMetrics qm) { appsSubmittedCarryOn = qm.getAppsSubmitted(); appsPendingCarryOn = qm.getAppsPending(); appsRunningCarryOn = qm.getAppsRunning(); appsCompletedCarryOn = qm.getAppsCompleted(); } private void assertQueueMetrics(QueueMetrics qm, int appsSubmitted, int appsPending, int appsRunning, int appsCompleted) { Assert.assertEquals(qm.getAppsSubmitted(), appsSubmitted + appsSubmittedCarryOn); Assert.assertEquals(qm.getAppsPending(), appsPending + appsPendingCarryOn); Assert.assertEquals(qm.getAppsRunning(), appsRunning + appsRunningCarryOn); Assert.assertEquals(qm.getAppsCompleted(), appsCompleted + appsCompletedCarryOn); } @Test (timeout = 60000) public void testDecomissionedNMsMetricsOnRMRestart() throws Exception { YarnConfiguration conf = new YarnConfiguration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile.getAbsolutePath()); writeToHostsFile(""); final DrainDispatcher dispatcher = new DrainDispatcher(); MockRM rm1 = null, rm2 = null; try { rm1 = new MockRM(conf) { @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm1.start(); MockNM nm1 = rm1.registerNode("localhost:1234", 8000); MockNM nm2 = rm1.registerNode("host2:1234", 8000); Assert .assertEquals(0, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); String ip = NetUtils.normalizeHostName("localhost"); // Add 2 hosts to exclude list. writeToHostsFile("host2", ip); // refresh nodes rm1.getNodesListManager().refreshNodes(conf); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert .assertTrue( NodeAction.SHUTDOWN.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue("The decommisioned metrics are not updated", NodeAction.SHUTDOWN.equals(nodeHeartbeat.getNodeAction())); dispatcher.await(); Assert .assertEquals(2, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); rm1.stop(); rm1 = null; Assert .assertEquals(0, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); // restart RM. rm2 = new MockRM(conf); rm2.start(); Assert .assertEquals(2, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); } finally { if (rm1 != null) { rm1.stop(); } if (rm2 != null) { rm2.stop(); } } } // Test Delegation token is renewed synchronously so that recover events // can be processed before any other external incoming events, specifically // the ContainerFinished event on NM re-registraton. @Test (timeout = 20000) public void testSynchronouslyRenewDTOnRecovery() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM MockRM rm1 = createMockRM(conf, memStore); rm1.start(); final MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app0 = rm1.submitApp(200); final MockAM am0 = MockRM.launchAndRegisterAM(app0, rm1, nm1); MockRM rm2 = new MockRM(conf, memStore) { @Override protected ResourceTrackerService createResourceTrackerService() { return new ResourceTrackerService(this.rmContext, this.nodesListManager, this.nmLivelinessMonitor, this.rmContext.getContainerTokenSecretManager(), this.rmContext.getNMTokenSecretManager()) { @Override protected void serviceStart() throws Exception { // send the container_finished event as soon as the // ResourceTrackerService is started. super.serviceStart(); nm1.setResourceTrackerService(getResourceTrackerService()); NMContainerStatus status = TestRMRestart.createNMContainerStatus( am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(status), null); } }; } }; try { // Re-start RM rm2.start(); // wait for the 2nd attempt to be started. RMApp loadedApp0 = rm2.getRMContext().getRMApps().get(app0.getApplicationId()); int timeoutSecs = 0; while (loadedApp0.getAppAttempts().size() != 2 && timeoutSecs++ < 40) { Thread.sleep(200); } MockAM am1 = MockRM.launchAndRegisterAM(loadedApp0, rm2, nm1); MockRM.finishAMAndVerifyAppState(loadedApp0, rm2, nm1, am1); } finally { rm2.stop(); } } private void writeToHostsFile(String... hosts) throws IOException { if (!hostFile.exists()) { TEMP_DIR.mkdirs(); hostFile.createNewFile(); } FileOutputStream fStream = null; try { fStream = new FileOutputStream(hostFile); for (int i = 0; i < hosts.length; i++) { fStream.write(hosts[i].getBytes()); fStream.write(System.getProperty("line.separator").getBytes()); } } finally { if (fStream != null) { IOUtils.closeStream(fStream); fStream = null; } } } public static NMContainerStatus createNMContainerStatus( ApplicationAttemptId appAttemptId, int id, ContainerState containerState) { return createNMContainerStatus(appAttemptId, id, containerState, RMNodeLabelsManager.NO_LABEL); } public static NMContainerStatus createNMContainerStatus( ApplicationAttemptId appAttemptId, int id, ContainerState containerState, String nodeLabelExpression) { ContainerId containerId = ContainerId.newContainerId(appAttemptId, id); NMContainerStatus containerReport = NMContainerStatus.newInstance(containerId, containerState, Resource.newInstance(1024, 1), "recover container", 0, Priority.newInstance(0), 0, nodeLabelExpression); return containerReport; } public class TestMemoryRMStateStore extends MemoryRMStateStore { int count = 0; public int updateApp = 0; public int updateAttempt = 0; @Override public void updateApplicationStateInternal(ApplicationId appId, ApplicationStateData appStateData) throws Exception { updateApp = ++count; super.updateApplicationStateInternal(appId, appStateData); } @Override public synchronized void updateApplicationAttemptStateInternal( ApplicationAttemptId attemptId, ApplicationAttemptStateData attemptStateData) throws Exception { updateAttempt = ++count; super.updateApplicationAttemptStateInternal(attemptId, attemptStateData); } } public static class TestSecurityMockRM extends MockRM { public TestSecurityMockRM(Configuration conf, RMStateStore store) { super(conf, store); } @Override public void init(Configuration conf) { // reset localServiceAddress. RMDelegationTokenIdentifier.Renewer.setSecretManager(null, null); super.init(conf); } @Override protected ClientRMService createClientRMService() { return new ClientRMService(getRMContext(), getResourceScheduler(), rmAppManager, applicationACLsManager, null, getRMContext().getRMDelegationTokenSecretManager()){ @Override protected void serviceStart() throws Exception { // do nothing } @Override protected void serviceStop() throws Exception { //do nothing } }; } @Override protected void doSecureLogin() throws IOException { // Do nothing. } } // Test does following verification // 1. Start RM1 with store patch /tmp // 2. Add/remove/replace labels to cluster and node lable and verify // 3. Start RM2 with store patch /tmp only // 4. Get cluster and node lobel, it should be present by recovering it @Test(timeout = 20000) public void testRMRestartRecoveringNodeLabelManager() throws Exception { // Initial FS node label store root dir to a random tmp dir File nodeLabelFsStoreDir = new File("target", this.getClass().getSimpleName() + "-testRMRestartRecoveringNodeLabelManager"); if (nodeLabelFsStoreDir.exists()) { FileUtils.deleteDirectory(nodeLabelFsStoreDir); } nodeLabelFsStoreDir.deleteOnExit(); String nodeLabelFsStoreDirURI = nodeLabelFsStoreDir.toURI().toString(); conf.set(YarnConfiguration.FS_NODE_LABELS_STORE_ROOT_DIR, nodeLabelFsStoreDirURI); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); conf.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true); MockRM rm1 = new MockRM(conf, memStore) { @Override protected RMNodeLabelsManager createNodeLabelManager() { RMNodeLabelsManager mgr = new RMNodeLabelsManager(); mgr.init(getConfig()); return mgr; } }; rm1.init(conf); rm1.start(); RMNodeLabelsManager nodeLabelManager = rm1.getRMContext().getNodeLabelManager(); Set<String> clusterNodeLabels = new HashSet<String>(); clusterNodeLabels.add("x"); clusterNodeLabels.add("y"); clusterNodeLabels.add("z"); // Add node label x,y,z nodeLabelManager.addToCluserNodeLabelsWithDefaultExclusivity(clusterNodeLabels); // Add node Label to Node h1->x NodeId n1 = NodeId.newInstance("h1", 0); nodeLabelManager.addLabelsToNode(ImmutableMap.of(n1, toSet("x"))); clusterNodeLabels.remove("z"); // Remove cluster label z nodeLabelManager.removeFromClusterNodeLabels(toSet("z")); // Replace nodelabel h1->x,y nodeLabelManager.replaceLabelsOnNode(ImmutableMap.of(n1, toSet("y"))); // Wait for updating store.It is expected NodeStore update should happen // very fast since it has separate dispatcher. So waiting for max 5 seconds, // which is sufficient time to update NodeStore. int count = 10; while (count-- > 0) { if (nodeLabelManager.getNodeLabels().size() > 0) { break; } Thread.sleep(500); } Assert.assertEquals(clusterNodeLabels.size(), nodeLabelManager .getClusterNodeLabelNames().size()); Map<NodeId, Set<String>> nodeLabels = nodeLabelManager.getNodeLabels(); Assert.assertEquals(1, nodeLabelManager.getNodeLabels().size()); Assert.assertTrue(nodeLabels.get(n1).equals(toSet("y"))); MockRM rm2 = new MockRM(conf, memStore) { @Override protected RMNodeLabelsManager createNodeLabelManager() { RMNodeLabelsManager mgr = new RMNodeLabelsManager(); mgr.init(getConfig()); return mgr; } }; rm2.init(conf); rm2.start(); nodeLabelManager = rm2.getRMContext().getNodeLabelManager(); Assert.assertEquals(clusterNodeLabels.size(), nodeLabelManager .getClusterNodeLabelNames().size()); nodeLabels = nodeLabelManager.getNodeLabels(); Assert.assertEquals(1, nodeLabelManager.getNodeLabels().size()); Assert.assertTrue(nodeLabels.get(n1).equals(toSet("y"))); rm1.stop(); rm2.stop(); } private <E> Set<E> toSet(E... elements) { Set<E> set = Sets.newHashSet(elements); return set; } }
87,332
39.079394
98
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.resourcemanager.TestRMRestart.TestSecurityMockRM; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeImpl; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueNotFoundException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; 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.ParentQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSParentQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; import org.apache.hadoop.yarn.server.resourcemanager.security.DelegationTokenRenewer; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import com.google.common.base.Supplier; @SuppressWarnings({"rawtypes", "unchecked"}) @RunWith(value = Parameterized.class) public class TestWorkPreservingRMRestart extends ParameterizedSchedulerTestBase { private YarnConfiguration conf; MockRM rm1 = null; MockRM rm2 = null; public TestWorkPreservingRMRestart(SchedulerType type) { super(type); } @Before public void setup() throws UnknownHostException { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); conf = getConf(); UserGroupInformation.setConfiguration(conf); conf.set(YarnConfiguration.RECOVERY_ENABLED, "true"); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); conf.setBoolean(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_ENABLED, true); conf.setLong(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 0); DefaultMetricsSystem.setMiniClusterMode(true); } @After public void tearDown() { if (rm1 != null) { rm1.stop(); } if (rm2 != null) { rm2.stop(); } } // Test common scheduler state including SchedulerAttempt, SchedulerNode, // AppSchedulingInfo can be reconstructed via the container recovery reports // on NM re-registration. // Also test scheduler specific changes: i.e. Queue recovery- // CSQueue/FSQueue/FifoQueue recovery respectively. // Test Strategy: send 3 container recovery reports(AMContainer, running // container, completed container) on NM re-registration, check the states of // SchedulerAttempt, SchedulerNode etc. are updated accordingly. @Test(timeout = 20000) public void testSchedulerRecovery() throws Exception { conf.setBoolean(CapacitySchedulerConfiguration.ENABLE_USER_METRICS, true); conf.set(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, DominantResourceCalculator.class.getName()); int containerMemory = 1024; Resource containerResource = Resource.newInstance(containerMemory, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // clear queue metrics rm1.clearQueueMetrics(app1); // Re-start RM rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); // recover app RMApp recoveredApp1 = rm2.getRMContext().getRMApps().get(app1.getApplicationId()); RMAppAttempt loadedAttempt1 = recoveredApp1.getCurrentAppAttempt(); NMContainerStatus amContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 1, ContainerState.RUNNING); NMContainerStatus runningContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 2, ContainerState.RUNNING); NMContainerStatus completedContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 3, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(amContainer, runningContainer, completedContainer), null); // Wait for RM to settle down on recovering containers; waitForNumContainersToRecover(2, rm2, am1.getApplicationAttemptId()); Set<ContainerId> launchedContainers = ((RMNodeImpl) rm2.getRMContext().getRMNodes().get(nm1.getNodeId())) .getLaunchedContainers(); assertTrue(launchedContainers.contains(amContainer.getContainerId())); assertTrue(launchedContainers.contains(runningContainer.getContainerId())); // check RMContainers are re-recreated and the container state is correct. rm2.waitForState(nm1, amContainer.getContainerId(), RMContainerState.RUNNING); rm2.waitForState(nm1, runningContainer.getContainerId(), RMContainerState.RUNNING); rm2.waitForContainerToComplete(loadedAttempt1, completedContainer); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm2.getResourceScheduler(); SchedulerNode schedulerNode1 = scheduler.getSchedulerNode(nm1.getNodeId()); assertTrue( "SchedulerNode#toString is not in expected format", schedulerNode1 .toString().contains(schedulerNode1.getAvailableResource().toString())); assertTrue( "SchedulerNode#toString is not in expected format", schedulerNode1 .toString().contains(schedulerNode1.getUsedResource().toString())); // ********* check scheduler node state.******* // 2 running containers. Resource usedResources = Resources.multiply(containerResource, 2); Resource nmResource = Resource.newInstance(nm1.getMemory(), nm1.getvCores()); assertTrue(schedulerNode1.isValidContainer(amContainer.getContainerId())); assertTrue(schedulerNode1.isValidContainer(runningContainer .getContainerId())); assertFalse(schedulerNode1.isValidContainer(completedContainer .getContainerId())); // 2 launched containers, 1 completed container assertEquals(2, schedulerNode1.getNumContainers()); assertEquals(Resources.subtract(nmResource, usedResources), schedulerNode1.getAvailableResource()); assertEquals(usedResources, schedulerNode1.getUsedResource()); Resource availableResources = Resources.subtract(nmResource, usedResources); // ***** check queue state based on the underlying scheduler ******** Map<ApplicationId, SchedulerApplication> schedulerApps = ((AbstractYarnScheduler) rm2.getResourceScheduler()) .getSchedulerApplications(); SchedulerApplication schedulerApp = schedulerApps.get(recoveredApp1.getApplicationId()); if (getSchedulerType() == SchedulerType.CAPACITY) { checkCSQueue(rm2, schedulerApp, nmResource, nmResource, usedResources, 2); } else { checkFSQueue(rm2, schedulerApp, usedResources, availableResources); } // *********** check scheduler attempt state.******** SchedulerApplicationAttempt schedulerAttempt = schedulerApp.getCurrentAppAttempt(); assertTrue(schedulerAttempt.getLiveContainers().contains( scheduler.getRMContainer(amContainer.getContainerId()))); assertTrue(schedulerAttempt.getLiveContainers().contains( scheduler.getRMContainer(runningContainer.getContainerId()))); assertEquals(schedulerAttempt.getCurrentConsumption(), usedResources); // *********** check appSchedulingInfo state *********** assertEquals((1L << 40) + 1L, schedulerAttempt.getNewContainerId()); } private void checkCSQueue(MockRM rm, SchedulerApplication<SchedulerApplicationAttempt> app, Resource clusterResource, Resource queueResource, Resource usedResource, int numContainers) throws Exception { checkCSLeafQueue(rm, app, clusterResource, queueResource, usedResource, numContainers); LeafQueue queue = (LeafQueue) app.getQueue(); Resource availableResources = Resources.subtract(queueResource, usedResource); // ************ check app headroom **************** SchedulerApplicationAttempt schedulerAttempt = app.getCurrentAppAttempt(); assertEquals(availableResources, schedulerAttempt.getHeadroom()); // ************* check Queue metrics ************ QueueMetrics queueMetrics = queue.getMetrics(); assertMetrics(queueMetrics, 1, 0, 1, 0, 2, availableResources.getMemory(), availableResources.getVirtualCores(), usedResource.getMemory(), usedResource.getVirtualCores()); // ************ check user metrics *********** QueueMetrics userMetrics = queueMetrics.getUserMetrics(app.getUser()); assertMetrics(userMetrics, 1, 0, 1, 0, 2, availableResources.getMemory(), availableResources.getVirtualCores(), usedResource.getMemory(), usedResource.getVirtualCores()); } private void checkCSLeafQueue(MockRM rm, SchedulerApplication<SchedulerApplicationAttempt> app, Resource clusterResource, Resource queueResource, Resource usedResource, int numContainers) { LeafQueue leafQueue = (LeafQueue) app.getQueue(); // assert queue used resources. assertEquals(usedResource, leafQueue.getUsedResources()); assertEquals(numContainers, leafQueue.getNumContainers()); ResourceCalculator calc = ((CapacityScheduler) rm.getResourceScheduler()).getResourceCalculator(); float usedCapacity = Resources.divide(calc, clusterResource, usedResource, queueResource); // assert queue used capacity assertEquals(usedCapacity, leafQueue.getUsedCapacity(), 1e-8); float absoluteUsedCapacity = Resources.divide(calc, clusterResource, usedResource, clusterResource); // assert queue absolute capacity assertEquals(absoluteUsedCapacity, leafQueue.getAbsoluteUsedCapacity(), 1e-8); // assert user consumed resources. assertEquals(usedResource, leafQueue.getUser(app.getUser()) .getUsed()); } private void checkFSQueue(ResourceManager rm, SchedulerApplication schedulerApp, Resource usedResources, Resource availableResources) throws Exception { // waiting for RM's scheduling apps int retry = 0; Resource assumedFairShare = Resource.newInstance(8192, 8); while (true) { Thread.sleep(100); if (assumedFairShare.equals(((FairScheduler)rm.getResourceScheduler()) .getQueueManager().getRootQueue().getFairShare())) { break; } retry++; if (retry > 30) { Assert.fail("Apps are not scheduled within assumed timeout"); } } FairScheduler scheduler = (FairScheduler) rm.getResourceScheduler(); FSParentQueue root = scheduler.getQueueManager().getRootQueue(); // ************ check cluster used Resources ******** assertTrue(root.getPolicy() instanceof DominantResourceFairnessPolicy); assertEquals(usedResources,root.getResourceUsage()); // ************ check app headroom **************** FSAppAttempt schedulerAttempt = (FSAppAttempt) schedulerApp.getCurrentAppAttempt(); assertEquals(availableResources, schedulerAttempt.getHeadroom()); // ************ check queue metrics **************** QueueMetrics queueMetrics = scheduler.getRootQueueMetrics(); assertMetrics(queueMetrics, 1, 0, 1, 0, 2, availableResources.getMemory(), availableResources.getVirtualCores(), usedResources.getMemory(), usedResources.getVirtualCores()); } // create 3 container reports for AM public static List<NMContainerStatus> createNMContainerStatusForApp(MockAM am) { List<NMContainerStatus> list = new ArrayList<NMContainerStatus>(); NMContainerStatus amContainer = TestRMRestart.createNMContainerStatus(am.getApplicationAttemptId(), 1, ContainerState.RUNNING); NMContainerStatus runningContainer = TestRMRestart.createNMContainerStatus(am.getApplicationAttemptId(), 2, ContainerState.RUNNING); NMContainerStatus completedContainer = TestRMRestart.createNMContainerStatus(am.getApplicationAttemptId(), 3, ContainerState.COMPLETE); list.add(amContainer); list.add(runningContainer); list.add(completedContainer); return list; } private static final String R = "Default"; private static final String A = "QueueA"; private static final String B = "QueueB"; //don't ever create the below queue ;-) private static final String QUEUE_DOESNT_EXIST = "NoSuchQueue"; private static final String USER_1 = "user1"; private static final String USER_2 = "user2"; private void setupQueueConfiguration(CapacitySchedulerConfiguration conf) { conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] { R }); final String Q_R = CapacitySchedulerConfiguration.ROOT + "." + R; conf.setCapacity(Q_R, 100); final String Q_A = Q_R + "." + A; final String Q_B = Q_R + "." + B; conf.setQueues(Q_R, new String[] {A, B}); conf.setCapacity(Q_A, 50); conf.setCapacity(Q_B, 50); conf.setDouble(CapacitySchedulerConfiguration .MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT, 0.5f); } private void setupQueueConfigurationOnlyA( CapacitySchedulerConfiguration conf) { conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] { R }); final String Q_R = CapacitySchedulerConfiguration.ROOT + "." + R; conf.setCapacity(Q_R, 100); final String Q_A = Q_R + "." + A; conf.setQueues(Q_R, new String[] {A}); conf.setCapacity(Q_A, 100); conf.setDouble(CapacitySchedulerConfiguration .MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT, 1.0f); } // Test CS recovery with multi-level queues and multi-users: // 1. setup 2 NMs each with 8GB memory; // 2. setup 2 level queues: Default -> (QueueA, QueueB) // 3. User1 submits 2 apps on QueueA // 4. User2 submits 1 app on QueueB // 5. AM and each container has 1GB memory // 6. Restart RM. // 7. nm1 re-syncs back containers belong to user1 // 8. nm2 re-syncs back containers belong to user2. // 9. Assert the parent queue and 2 leaf queues state and the metrics. // 10. Assert each user's consumption inside the queue. @Test (timeout = 30000) public void testCapacitySchedulerRecovery() throws Exception { if (getSchedulerType() != SchedulerType.CAPACITY) { return; } conf.setBoolean(CapacitySchedulerConfiguration.ENABLE_USER_METRICS, true); conf.set(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, DominantResourceCalculator.class.getName()); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(conf); setupQueueConfiguration(csConf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(csConf); rm1 = new MockRM(csConf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); MockNM nm2 = new MockNM("127.1.1.1:4321", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); nm2.registerNode(); RMApp app1_1 = rm1.submitApp(1024, "app1_1", USER_1, null, A); MockAM am1_1 = MockRM.launchAndRegisterAM(app1_1, rm1, nm1); RMApp app1_2 = rm1.submitApp(1024, "app1_2", USER_1, null, A); MockAM am1_2 = MockRM.launchAndRegisterAM(app1_2, rm1, nm2); RMApp app2 = rm1.submitApp(1024, "app2", USER_2, null, B); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); // clear queue metrics rm1.clearQueueMetrics(app1_1); rm1.clearQueueMetrics(app1_2); rm1.clearQueueMetrics(app2); csConf.set("yarn.scheduler.capacity.root.Default.QueueB.state", "STOPPED"); // Re-start RM rm2 = new MockRM(csConf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm2.setResourceTrackerService(rm2.getResourceTrackerService()); List<NMContainerStatus> am1_1Containers = createNMContainerStatusForApp(am1_1); List<NMContainerStatus> am1_2Containers = createNMContainerStatusForApp(am1_2); am1_1Containers.addAll(am1_2Containers); nm1.registerNode(am1_1Containers, null); List<NMContainerStatus> am2Containers = createNMContainerStatusForApp(am2); nm2.registerNode(am2Containers, null); // Wait for RM to settle down on recovering containers; waitForNumContainersToRecover(2, rm2, am1_1.getApplicationAttemptId()); waitForNumContainersToRecover(2, rm2, am1_2.getApplicationAttemptId()); waitForNumContainersToRecover(2, rm2, am1_2.getApplicationAttemptId()); // Calculate each queue's resource usage. Resource containerResource = Resource.newInstance(1024, 1); Resource nmResource = Resource.newInstance(nm1.getMemory(), nm1.getvCores()); Resource clusterResource = Resources.multiply(nmResource, 2); Resource q1Resource = Resources.multiply(clusterResource, 0.5); Resource q2Resource = Resources.multiply(clusterResource, 0.5); Resource q1UsedResource = Resources.multiply(containerResource, 4); Resource q2UsedResource = Resources.multiply(containerResource, 2); Resource totalUsedResource = Resources.add(q1UsedResource, q2UsedResource); Resource q1availableResources = Resources.subtract(q1Resource, q1UsedResource); Resource q2availableResources = Resources.subtract(q2Resource, q2UsedResource); Resource totalAvailableResource = Resources.add(q1availableResources, q2availableResources); Map<ApplicationId, SchedulerApplication> schedulerApps = ((AbstractYarnScheduler) rm2.getResourceScheduler()) .getSchedulerApplications(); SchedulerApplication schedulerApp1_1 = schedulerApps.get(app1_1.getApplicationId()); // assert queue A state. checkCSLeafQueue(rm2, schedulerApp1_1, clusterResource, q1Resource, q1UsedResource, 4); QueueMetrics queue1Metrics = schedulerApp1_1.getQueue().getMetrics(); assertMetrics(queue1Metrics, 2, 0, 2, 0, 4, q1availableResources.getMemory(), q1availableResources.getVirtualCores(), q1UsedResource.getMemory(), q1UsedResource.getVirtualCores()); // assert queue B state. SchedulerApplication schedulerApp2 = schedulerApps.get(app2.getApplicationId()); checkCSLeafQueue(rm2, schedulerApp2, clusterResource, q2Resource, q2UsedResource, 2); QueueMetrics queue2Metrics = schedulerApp2.getQueue().getMetrics(); assertMetrics(queue2Metrics, 1, 0, 1, 0, 2, q2availableResources.getMemory(), q2availableResources.getVirtualCores(), q2UsedResource.getMemory(), q2UsedResource.getVirtualCores()); // assert parent queue state. LeafQueue leafQueue = (LeafQueue) schedulerApp2.getQueue(); ParentQueue parentQueue = (ParentQueue) leafQueue.getParent(); checkParentQueue(parentQueue, 6, totalUsedResource, (float) 6 / 16, (float) 6 / 16); assertMetrics(parentQueue.getMetrics(), 3, 0, 3, 0, 6, totalAvailableResource.getMemory(), totalAvailableResource.getVirtualCores(), totalUsedResource.getMemory(), totalUsedResource.getVirtualCores()); } //Test that we receive a meaningful exit-causing exception if a queue //is removed during recovery //1. Add some apps to two queues, attempt to add an app to a non-existant // queue to verify that the new logic is not in effect during normal app // submission //2. Remove one of the queues, restart the RM //3. Verify that the expected exception was thrown @Test (timeout = 30000, expected = QueueNotFoundException.class) public void testCapacitySchedulerQueueRemovedRecovery() throws Exception { if (getSchedulerType() != SchedulerType.CAPACITY) { throw new QueueNotFoundException("Dummy"); } conf.setBoolean(CapacitySchedulerConfiguration.ENABLE_USER_METRICS, true); conf.set(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, DominantResourceCalculator.class.getName()); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(conf); setupQueueConfiguration(csConf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(csConf); rm1 = new MockRM(csConf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); MockNM nm2 = new MockNM("127.1.1.1:4321", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); nm2.registerNode(); RMApp app1_1 = rm1.submitApp(1024, "app1_1", USER_1, null, A); MockAM am1_1 = MockRM.launchAndRegisterAM(app1_1, rm1, nm1); RMApp app1_2 = rm1.submitApp(1024, "app1_2", USER_1, null, A); MockAM am1_2 = MockRM.launchAndRegisterAM(app1_2, rm1, nm2); RMApp app2 = rm1.submitApp(1024, "app2", USER_2, null, B); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); //Submit an app with a non existant queue to make sure it does not //cause a fatal failure in the non-recovery case RMApp appNA = rm1.submitApp(1024, "app1_2", USER_1, null, QUEUE_DOESNT_EXIST, false); // clear queue metrics rm1.clearQueueMetrics(app1_1); rm1.clearQueueMetrics(app1_2); rm1.clearQueueMetrics(app2); // Re-start RM csConf = new CapacitySchedulerConfiguration(conf); setupQueueConfigurationOnlyA(csConf); rm2 = new MockRM(csConf, memStore); rm2.start(); } private void checkParentQueue(ParentQueue parentQueue, int numContainers, Resource usedResource, float UsedCapacity, float absoluteUsedCapacity) { assertEquals(numContainers, parentQueue.getNumContainers()); assertEquals(usedResource, parentQueue.getUsedResources()); assertEquals(UsedCapacity, parentQueue.getUsedCapacity(), 1e-8); assertEquals(absoluteUsedCapacity, parentQueue.getAbsoluteUsedCapacity(), 1e-8); } // Test RM shuts down, in the meanwhile, AM fails. Restarted RM scheduler // should not recover the containers that belong to the failed AM. @Test(timeout = 20000) public void testAMfailedBetweenRMRestart() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); conf.setLong(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 0); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); NMContainerStatus amContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 1, ContainerState.COMPLETE); NMContainerStatus runningContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 2, ContainerState.RUNNING); NMContainerStatus completedContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 3, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(amContainer, runningContainer, completedContainer), null); rm2.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FAILED); // Wait for RM to settle down on recovering containers; Thread.sleep(3000); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm2.getResourceScheduler(); // Previous AM failed, The failed AM should once again release the // just-recovered containers. assertNull(scheduler.getRMContainer(runningContainer.getContainerId())); assertNull(scheduler.getRMContainer(completedContainer.getContainerId())); rm2.waitForNewAMToLaunchAndRegister(app1.getApplicationId(), 2, nm1); MockNM nm2 = new MockNM("127.1.1.1:4321", 8192, rm2.getResourceTrackerService()); NMContainerStatus previousAttemptContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 4, ContainerState.RUNNING); nm2.registerNode(Arrays.asList(previousAttemptContainer), null); // Wait for RM to settle down on recovering containers; Thread.sleep(3000); // check containers from previous failed attempt should not be recovered. assertNull(scheduler.getRMContainer(previousAttemptContainer.getContainerId())); } // Apps already completed before RM restart. Restarted RM scheduler should not // recover containers for completed apps. @Test(timeout = 20000) public void testContainersNotRecoveredForCompletedApps() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); MockRM.finishAMAndVerifyAppState(app1, rm1, nm1, am1); rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); NMContainerStatus runningContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 2, ContainerState.RUNNING); NMContainerStatus completedContainer = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 3, ContainerState.COMPLETE); nm1.registerNode(Arrays.asList(runningContainer, completedContainer), null); RMApp recoveredApp1 = rm2.getRMContext().getRMApps().get(app1.getApplicationId()); assertEquals(RMAppState.FINISHED, recoveredApp1.getState()); // Wait for RM to settle down on recovering containers; Thread.sleep(3000); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm2.getResourceScheduler(); // scheduler should not recover containers for finished apps. assertNull(scheduler.getRMContainer(runningContainer.getContainerId())); assertNull(scheduler.getRMContainer(completedContainer.getContainerId())); } @Test (timeout = 600000) public void testAppReregisterOnRMWorkPreservingRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = MockRM.launchAM(app0, rm1, nm1); // Issuing registerAppAttempt() before and after RM restart to confirm // registerApplicationMaster() is idempotent. am0.registerAppAttempt(); // start new RM rm2 = new MockRM(conf, memStore); rm2.start(); rm2.waitForState(app0.getApplicationId(), RMAppState.ACCEPTED); rm2.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.LAUNCHED); am0.setAMRMProtocol(rm2.getApplicationMasterService(), rm2.getRMContext()); // retry registerApplicationMaster() after RM restart. am0.registerAppAttempt(true); rm2.waitForState(app0.getApplicationId(), RMAppState.RUNNING); rm2.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.RUNNING); } @Test (timeout = 30000) public void testAMContainerStatusWithRMRestart() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1_1 = rm1.submitApp(1024); MockAM am1_1 = MockRM.launchAndRegisterAM(app1_1, rm1, nm1); RMAppAttempt attempt0 = app1_1.getCurrentAppAttempt(); AbstractYarnScheduler scheduler = ((AbstractYarnScheduler) rm1.getResourceScheduler()); Assert.assertTrue(scheduler.getRMContainer( attempt0.getMasterContainer().getId()).isAMContainer()); // Re-start RM rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); List<NMContainerStatus> am1_1Containers = createNMContainerStatusForApp(am1_1); nm1.registerNode(am1_1Containers, null); // Wait for RM to settle down on recovering containers; waitForNumContainersToRecover(2, rm2, am1_1.getApplicationAttemptId()); scheduler = ((AbstractYarnScheduler) rm2.getResourceScheduler()); Assert.assertTrue(scheduler.getRMContainer( attempt0.getMasterContainer().getId()).isAMContainer()); } @Test (timeout = 20000) public void testRecoverSchedulerAppAndAttemptSynchronously() throws Exception { // start RM MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = MockRM.launchAndRegisterAM(app0, rm1, nm1); rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); // scheduler app/attempt is immediately available after RM is re-started. Assert.assertNotNull(rm2.getResourceScheduler().getSchedulerAppInfo( am0.getApplicationAttemptId())); // getTransferredContainers should not throw NPE. ((AbstractYarnScheduler) rm2.getResourceScheduler()) .getTransferredContainers(am0.getApplicationAttemptId()); List<NMContainerStatus> containers = createNMContainerStatusForApp(am0); nm1.registerNode(containers, null); waitForNumContainersToRecover(2, rm2, am0.getApplicationAttemptId()); } // Test if RM on recovery receives the container release request from AM // before it receives the container status reported by NM for recovery. this // container should not be recovered. @Test (timeout = 50000) public void testReleasedContainerNotRecovered() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); rm1.start(); RMApp app1 = rm1.submitApp(1024); final MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // Re-start RM conf.setInt(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS, 8000); rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); rm2.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); am1.setAMRMProtocol(rm2.getApplicationMasterService(), rm2.getRMContext()); am1.registerAppAttempt(true); // try to release a container before the container is actually recovered. final ContainerId runningContainer = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); am1.allocate(null, Arrays.asList(runningContainer)); // send container statuses to recover the containers List<NMContainerStatus> containerStatuses = createNMContainerStatusForApp(am1); nm1.registerNode(containerStatuses, null); // only the am container should be recovered. waitForNumContainersToRecover(1, rm2, am1.getApplicationAttemptId()); final AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm2.getResourceScheduler(); // cached release request is cleaned. // assertFalse(scheduler.getPendingRelease().contains(runningContainer)); AllocateResponse response = am1.allocate(null, null); // AM gets notified of the completed container. boolean receivedCompletedContainer = false; for (ContainerStatus status : response.getCompletedContainersStatuses()) { if (status.getContainerId().equals(runningContainer)) { receivedCompletedContainer = true; } } assertTrue(receivedCompletedContainer); GenericTestUtils.waitFor(new Supplier<Boolean>() { public Boolean get() { // release cache is cleaned up and previous running container is not // recovered return scheduler.getApplicationAttempt(am1.getApplicationAttemptId()) .getPendingRelease().isEmpty() && scheduler.getRMContainer(runningContainer) == null; } }, 1000, 20000); } private void assertMetrics(QueueMetrics qm, int appsSubmitted, int appsPending, int appsRunning, int appsCompleted, int allocatedContainers, int availableMB, int availableVirtualCores, int allocatedMB, int allocatedVirtualCores) { assertEquals(appsSubmitted, qm.getAppsSubmitted()); assertEquals(appsPending, qm.getAppsPending()); assertEquals(appsRunning, qm.getAppsRunning()); assertEquals(appsCompleted, qm.getAppsCompleted()); assertEquals(allocatedContainers, qm.getAllocatedContainers()); assertEquals(availableMB, qm.getAvailableMB()); assertEquals(availableVirtualCores, qm.getAvailableVirtualCores()); assertEquals(allocatedMB, qm.getAllocatedMB()); assertEquals(allocatedVirtualCores, qm.getAllocatedVirtualCores()); } public static void waitForNumContainersToRecover(int num, MockRM rm, ApplicationAttemptId attemptId) throws Exception { AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); SchedulerApplicationAttempt attempt = scheduler.getApplicationAttempt(attemptId); while (attempt == null) { System.out.println("Wait for scheduler attempt " + attemptId + " to be created"); Thread.sleep(200); attempt = scheduler.getApplicationAttempt(attemptId); } while (attempt.getLiveContainers().size() < num) { System.out.println("Wait for " + num + " containers to recover. currently: " + attempt.getLiveContainers().size()); Thread.sleep(200); } } @Test (timeout = 20000) public void testNewContainersNotAllocatedDuringSchedulerRecovery() throws Exception { conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 4000); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // Restart RM rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm1.registerNode(); ControlledClock clock = new ControlledClock(new SystemClock()); long startTime = System.currentTimeMillis(); ((RMContextImpl)rm2.getRMContext()).setSystemClock(clock); am1.setAMRMProtocol(rm2.getApplicationMasterService(), rm2.getRMContext()); am1.registerAppAttempt(true); rm2.waitForState(app1.getApplicationId(), RMAppState.RUNNING); // AM request for new containers am1.allocate("127.0.0.1", 1000, 1, new ArrayList<ContainerId>()); List<Container> containers = new ArrayList<Container>(); clock.setTime(startTime + 2000); nm1.nodeHeartbeat(true); // sleep some time as allocation happens asynchronously. Thread.sleep(3000); containers.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); // container is not allocated during scheduling recovery. Assert.assertTrue(containers.isEmpty()); clock.setTime(startTime + 8000); nm1.nodeHeartbeat(true); // Container is created after recovery is done. while (containers.isEmpty()) { containers.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } } /** * Testing to confirm that retried finishApplicationMaster() doesn't throw * InvalidApplicationMasterRequest before and after RM restart. */ @Test (timeout = 20000) public void testRetriedFinishApplicationMasterRequest() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = MockRM.launchAM(app0, rm1, nm1); am0.registerAppAttempt(); // Emulating following a scenario: // RM1 saves the app in RMStateStore and then crashes, // FinishApplicationMasterResponse#isRegistered still return false, // so AM still retry the 2nd RM MockRM.finishAMAndVerifyAppState(app0, rm1, nm1, am0); // start new RM rm2 = new MockRM(conf, memStore); rm2.start(); am0.setAMRMProtocol(rm2.getApplicationMasterService(), rm2.getRMContext()); am0.unregisterAppAttempt(false); } @Test (timeout = 30000) public void testAppFailedToRenewTokenOnRecovery() throws Exception { conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); UserGroupInformation.setConfiguration(conf); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm1 = new TestSecurityMockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); MockRM rm2 = new TestSecurityMockRM(conf, memStore) { protected DelegationTokenRenewer createDelegationTokenRenewer() { return new DelegationTokenRenewer() { @Override public void addApplicationSync(ApplicationId applicationId, Credentials ts, boolean shouldCancelAtEnd, String user) throws IOException { throw new IOException("Token renew failed !!"); } }; } }; nm1.setResourceTrackerService(rm2.getResourceTrackerService()); rm2.start(); NMContainerStatus containerStatus = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 1, ContainerState.RUNNING); nm1.registerNode(Arrays.asList(containerStatus), null); // am re-register rm2.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); am1.setAMRMProtocol(rm2.getApplicationMasterService(), rm2.getRMContext()); am1.registerAppAttempt(true); rm2.waitForState(app1.getApplicationId(), RMAppState.RUNNING); // Because the token expired, am could crash. nm1.nodeHeartbeat(am1.getApplicationAttemptId(), 1, ContainerState.COMPLETE); rm2.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FAILED); rm2.waitForState(app1.getApplicationId(), RMAppState.FAILED); } /** * Test validateAndCreateResourceRequest fails on recovery, app should ignore * this Exception and continue */ @Test (timeout = 30000) public void testAppFailToValidateResourceRequestOnRecovery() throws Exception{ MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // Change the config so that validateAndCreateResourceRequest throws // exception on recovery conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 50); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 100); rm2 = new MockRM(conf, memStore); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); rm2.start(); } @Test(timeout = 20000) public void testContainerCompleteMsgNotLostAfterAMFailedAndRMRestart() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); // submit app with keepContainersAcrossApplicationAttempts true Resource resource = Records.newRecord(Resource.class); resource.setMemory(200); RMApp app0 = rm1.submitApp(resource, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS, null, null, true, true, false, null, 0, null, true, null); MockAM am0 = MockRM.launchAndRegisterAM(app0, rm1, nm1); am0.allocate("127.0.0.1", 1000, 2, new ArrayList<ContainerId>()); nm1.nodeHeartbeat(true); List<Container> conts = am0.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (conts.size() == 0) { nm1.nodeHeartbeat(true); conts.addAll(am0.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } // am failed,and relaunch it nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); rm1.waitForState(app0.getApplicationId(), RMAppState.ACCEPTED); MockAM am1 = MockRM.launchAndRegisterAM(app0, rm1, nm1); // rm failover rm2 = new MockRM(conf, memStore); rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); // container launched by first am completed NMContainerStatus amContainer = TestRMRestart.createNMContainerStatus(am0.getApplicationAttemptId(), 1, ContainerState.RUNNING); NMContainerStatus completedContainer= TestRMRestart.createNMContainerStatus(am0.getApplicationAttemptId(), 2, ContainerState.COMPLETE); NMContainerStatus runningContainer = TestRMRestart.createNMContainerStatus(am0.getApplicationAttemptId(), 3, ContainerState.RUNNING); nm1.registerNode(Arrays.asList(amContainer, runningContainer, completedContainer), null); Thread.sleep(200); // check whether current am could get containerCompleteMsg RMApp recoveredApp0 = rm2.getRMContext().getRMApps().get(app0.getApplicationId()); RMAppAttempt loadedAttempt1 = recoveredApp0.getCurrentAppAttempt(); assertEquals(1,loadedAttempt1.getJustFinishedContainers().size()); } }
47,204
41.719457
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/Application.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; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.resourcemanager.Task.State; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; 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.scheduler.Allocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.resource.Resources; @Private public class Application { private static final Log LOG = LogFactory.getLog(Application.class); private AtomicInteger taskCounter = new AtomicInteger(0); private AtomicInteger numAttempts = new AtomicInteger(0); final private String user; final private String queue; final private ApplicationId applicationId; final private ApplicationAttemptId applicationAttemptId; final private ResourceManager resourceManager; private final static RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); final private Map<Priority, Resource> requestSpec = new TreeMap<Priority, Resource>( new org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.Comparator()); final private Map<Priority, Map<String, ResourceRequest>> requests = new TreeMap<Priority, Map<String, ResourceRequest>>( new org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.Comparator()); final Map<Priority, Set<Task>> tasks = new TreeMap<Priority, Set<Task>>( new org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.Comparator()); final private Set<ResourceRequest> ask = new TreeSet<ResourceRequest>( new org.apache.hadoop.yarn.api.records.ResourceRequest.ResourceRequestComparator()); final private Map<String, NodeManager> nodes = new HashMap<String, NodeManager>(); Resource used = recordFactory.newRecordInstance(Resource.class); public Application(String user, ResourceManager resourceManager) throws YarnException { this(user, "default", resourceManager); } public Application(String user, String queue, ResourceManager resourceManager) throws YarnException { this.user = user; this.queue = queue; this.resourceManager = resourceManager; // register an application GetNewApplicationRequest request = Records.newRecord(GetNewApplicationRequest.class); GetNewApplicationResponse newApp = this.resourceManager.getClientRMService().getNewApplication(request); this.applicationId = newApp.getApplicationId(); this.applicationAttemptId = ApplicationAttemptId.newInstance(this.applicationId, this.numAttempts.getAndIncrement()); } public String getUser() { return user; } public String getQueue() { return queue; } public ApplicationId getApplicationId() { return applicationId; } public ApplicationAttemptId getApplicationAttemptId() { return applicationAttemptId; } public static String resolve(String hostName) { return NetworkTopology.DEFAULT_RACK; } public int getNextTaskId() { return taskCounter.incrementAndGet(); } public Resource getUsedResources() { return used; } @SuppressWarnings("deprecation") public synchronized void submit() throws IOException, YarnException { ApplicationSubmissionContext context = recordFactory.newRecordInstance(ApplicationSubmissionContext.class); context.setApplicationId(this.applicationId); context.setQueue(this.queue); // Set up the container launch context for the application master ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); context.setAMContainerSpec(amContainer); context.setResource(Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB)); SubmitApplicationRequest request = recordFactory .newRecordInstance(SubmitApplicationRequest.class); request.setApplicationSubmissionContext(context); final ResourceScheduler scheduler = resourceManager.getResourceScheduler(); resourceManager.getClientRMService().submitApplication(request); RMAppEvent event = new RMAppEvent(this.applicationId, RMAppEventType.START); resourceManager.getRMContext().getRMApps().get(applicationId).handle(event); event = new RMAppEvent(this.applicationId, RMAppEventType.APP_NEW_SAVED); resourceManager.getRMContext().getRMApps().get(applicationId).handle(event); event = new RMAppEvent(this.applicationId, RMAppEventType.APP_ACCEPTED); resourceManager.getRMContext().getRMApps().get(applicationId).handle(event); // Notify scheduler AppAddedSchedulerEvent addAppEvent = new AppAddedSchedulerEvent(this.applicationId, this.queue, "user"); scheduler.handle(addAppEvent); AppAttemptAddedSchedulerEvent addAttemptEvent = new AppAttemptAddedSchedulerEvent(this.applicationAttemptId, false); scheduler.handle(addAttemptEvent); } public synchronized void addResourceRequestSpec( Priority priority, Resource capability) { Resource currentSpec = requestSpec.put(priority, capability); if (currentSpec != null) { throw new IllegalStateException("Resource spec already exists for " + "priority " + priority.getPriority() + " - " + currentSpec.getMemory()); } } public synchronized void addNodeManager(String host, int containerManagerPort, NodeManager nodeManager) { nodes.put(host + ":" + containerManagerPort, nodeManager); } private synchronized NodeManager getNodeManager(String host) { return nodes.get(host); } public synchronized void addTask(Task task) { Priority priority = task.getPriority(); Map<String, ResourceRequest> requests = this.requests.get(priority); if (requests == null) { requests = new HashMap<String, ResourceRequest>(); this.requests.put(priority, requests); if(LOG.isDebugEnabled()) { LOG.debug("Added priority=" + priority + " application=" + applicationId); } } final Resource capability = requestSpec.get(priority); // Note down the task Set<Task> tasks = this.tasks.get(priority); if (tasks == null) { tasks = new HashSet<Task>(); this.tasks.put(priority, tasks); } tasks.add(task); LOG.info("Added task " + task.getTaskId() + " to application " + applicationId + " at priority " + priority); if(LOG.isDebugEnabled()) { LOG.debug("addTask: application=" + applicationId + " #asks=" + ask.size()); } // Create resource requests for (String host : task.getHosts()) { // Data-local addResourceRequest(priority, requests, host, capability); } // Rack-local for (String rack : task.getRacks()) { addResourceRequest(priority, requests, rack, capability); } // Off-switch addResourceRequest(priority, requests, ResourceRequest.ANY, capability); } public synchronized void finishTask(Task task) throws IOException, YarnException { Set<Task> tasks = this.tasks.get(task.getPriority()); if (!tasks.remove(task)) { throw new IllegalStateException( "Finishing unknown task " + task.getTaskId() + " from application " + applicationId); } NodeManager nodeManager = task.getNodeManager(); ContainerId containerId = task.getContainerId(); task.stop(); List<ContainerId> containerIds = new ArrayList<ContainerId>(); containerIds.add(containerId); StopContainersRequest stopRequest = StopContainersRequest.newInstance(containerIds); nodeManager.stopContainers(stopRequest); Resources.subtractFrom(used, requestSpec.get(task.getPriority())); LOG.info("Finished task " + task.getTaskId() + " of application " + applicationId + " on node " + nodeManager.getHostName() + ", currently using " + used + " resources"); } private synchronized void addResourceRequest( Priority priority, Map<String, ResourceRequest> requests, String resourceName, Resource capability) { ResourceRequest request = requests.get(resourceName); if (request == null) { request = org.apache.hadoop.yarn.server.utils.BuilderUtils.newResourceRequest( priority, resourceName, capability, 1); requests.put(resourceName, request); } else { request.setNumContainers(request.getNumContainers() + 1); } if (request.getNodeLabelExpression() == null) { request.setNodeLabelExpression(RMNodeLabelsManager.NO_LABEL); } // Note this down for next interaction with ResourceManager ask.remove(request); ask.add( org.apache.hadoop.yarn.server.utils.BuilderUtils.newResourceRequest( request)); // clone to ensure the RM doesn't manipulate the same obj if(LOG.isDebugEnabled()) { LOG.debug("addResourceRequest: applicationId=" + applicationId.getId() + " priority=" + priority.getPriority() + " resourceName=" + resourceName + " capability=" + capability + " numContainers=" + request.getNumContainers() + " #asks=" + ask.size()); } } public synchronized List<Container> getResources() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("getResources begin:" + " application=" + applicationId + " #ask=" + ask.size()); for (ResourceRequest request : ask) { LOG.debug("getResources:" + " application=" + applicationId + " ask-request=" + request); } } // Get resources from the ResourceManager Allocation allocation = resourceManager.getResourceScheduler().allocate( applicationAttemptId, new ArrayList<ResourceRequest>(ask), new ArrayList<ContainerId>(), null, null); System.out.println("-=======" + applicationAttemptId); System.out.println("----------" + resourceManager.getRMContext().getRMApps() .get(applicationId).getRMAppAttempt(applicationAttemptId)); List<Container> containers = allocation.getContainers(); // Clear state for next interaction with ResourceManager ask.clear(); if(LOG.isDebugEnabled()) { LOG.debug("getResources() for " + applicationId + ":" + " ask=" + ask.size() + " recieved=" + containers.size()); } return containers; } public synchronized void assign(List<Container> containers) throws IOException, YarnException { int numContainers = containers.size(); // Schedule in priority order for (Priority priority : requests.keySet()) { assign(priority, NodeType.NODE_LOCAL, containers); assign(priority, NodeType.RACK_LOCAL, containers); assign(priority, NodeType.OFF_SWITCH, containers); if (containers.isEmpty()) { break; } } int assignedContainers = numContainers - containers.size(); LOG.info("Application " + applicationId + " assigned " + assignedContainers + "/" + numContainers); } public synchronized void schedule() throws IOException, YarnException { assign(getResources()); } private synchronized void assign(Priority priority, NodeType type, List<Container> containers) throws IOException, YarnException { for (Iterator<Container> i=containers.iterator(); i.hasNext();) { Container container = i.next(); String host = container.getNodeId().toString(); if (Resources.equals(requestSpec.get(priority), container.getResource())) { // See which task can use this container for (Iterator<Task> t=tasks.get(priority).iterator(); t.hasNext();) { Task task = t.next(); if (task.getState() == State.PENDING && task.canSchedule(type, host)) { NodeManager nodeManager = getNodeManager(host); task.start(nodeManager, container.getId()); i.remove(); // Track application resource usage Resources.addTo(used, container.getResource()); LOG.info("Assigned container (" + container + ") of type " + type + " to task " + task.getTaskId() + " at priority " + priority + " on node " + nodeManager.getHostName() + ", currently using " + used + " resources"); // Update resource requests updateResourceRequests(requests.get(priority), type, task); // Launch the container StartContainerRequest scRequest = StartContainerRequest.newInstance(createCLC(), container.getContainerToken()); List<StartContainerRequest> list = new ArrayList<StartContainerRequest>(); list.add(scRequest); StartContainersRequest allRequests = StartContainersRequest.newInstance(list); nodeManager.startContainers(allRequests); break; } } } } } private void updateResourceRequests(Map<String, ResourceRequest> requests, NodeType type, Task task) { if (type == NodeType.NODE_LOCAL) { for (String host : task.getHosts()) { if(LOG.isDebugEnabled()) { LOG.debug("updateResourceRequests:" + " application=" + applicationId + " type=" + type + " host=" + host + " request=" + ((requests == null) ? "null" : requests.get(host))); } updateResourceRequest(requests.get(host)); } } if (type == NodeType.NODE_LOCAL || type == NodeType.RACK_LOCAL) { for (String rack : task.getRacks()) { if(LOG.isDebugEnabled()) { LOG.debug("updateResourceRequests:" + " application=" + applicationId + " type=" + type + " rack=" + rack + " request=" + ((requests == null) ? "null" : requests.get(rack))); } updateResourceRequest(requests.get(rack)); } } updateResourceRequest(requests.get(ResourceRequest.ANY)); if(LOG.isDebugEnabled()) { LOG.debug("updateResourceRequests:" + " application=" + applicationId + " #asks=" + ask.size()); } } private void updateResourceRequest(ResourceRequest request) { request.setNumContainers(request.getNumContainers() - 1); // Note this for next interaction with ResourceManager ask.remove(request); ask.add( org.apache.hadoop.yarn.server.utils.BuilderUtils.newResourceRequest( request)); // clone to ensure the RM doesn't manipulate the same obj if(LOG.isDebugEnabled()) { LOG.debug("updateResourceRequest:" + " application=" + applicationId + " request=" + request); } } private ContainerLaunchContext createCLC() { ContainerLaunchContext clc = recordFactory.newRecordInstance(ContainerLaunchContext.class); return clc; } }
17,946
37.762419
111
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMHAForNodeLabels.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; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableSet; public class TestRMHAForNodeLabels extends RMHATestBase { public static final Log LOG = LogFactory .getLog(TestSubmitApplicationWithRMHA.class); @Before @Override public void setup() throws Exception { super.setup(); // Create directory for node label store File tempDir = File.createTempFile("nlb", ".tmp"); tempDir.delete(); tempDir.mkdirs(); tempDir.deleteOnExit(); confForRM1.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true); confForRM1.set(YarnConfiguration.FS_NODE_LABELS_STORE_ROOT_DIR, tempDir.getAbsolutePath()); confForRM2.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true); confForRM2.set(YarnConfiguration.FS_NODE_LABELS_STORE_ROOT_DIR, tempDir.getAbsolutePath()); } @Test public void testRMHARecoverNodeLabels() throws Exception { // start two RMs, and transit rm1 to active, rm2 to standby startRMs(); // Add labels to rm1 rm1.getRMContext() .getNodeLabelManager() .addToCluserNodeLabels( Arrays.asList(NodeLabel.newInstance("a"), NodeLabel.newInstance("b"), NodeLabel.newInstance("c"))); Map<NodeId, Set<String>> nodeToLabels = new HashMap<>(); nodeToLabels.put(NodeId.newInstance("host1", 0), ImmutableSet.of("a")); nodeToLabels.put(NodeId.newInstance("host2", 0), ImmutableSet.of("b")); rm1.getRMContext().getNodeLabelManager().replaceLabelsOnNode(nodeToLabels); // Do the failover explicitFailover(); // Check labels in rm2 Assert .assertTrue(rm2.getRMContext().getNodeLabelManager() .getClusterNodeLabelNames() .containsAll(ImmutableSet.of("a", "b", "c"))); Assert.assertTrue(rm2.getRMContext().getNodeLabelManager() .getNodeLabels().get(NodeId.newInstance("host1", 0)).contains("a")); Assert.assertTrue(rm2.getRMContext().getNodeLabelManager() .getNodeLabels().get(NodeId.newInstance("host2", 0)).contains("b")); } }
3,355
34.702128
79
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/QueueACLsTestBase.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; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.service.Service.STATE; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; 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.ipc.YarnRPC; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; public abstract class QueueACLsTestBase { protected static final String COMMON_USER = "common_user"; protected static final String QUEUE_A_USER = "queueA_user"; protected static final String QUEUE_B_USER = "queueB_user"; protected static final String ROOT_ADMIN = "root_admin"; protected static final String QUEUE_A_ADMIN = "queueA_admin"; protected static final String QUEUE_B_ADMIN = "queueB_admin"; protected static final String QUEUEA = "queueA"; protected static final String QUEUEB = "queueB"; private static final Log LOG = LogFactory.getLog(TestApplicationACLs.class); MockRM resourceManager; Configuration conf; YarnRPC rpc; InetSocketAddress rmAddress; @Before public void setup() throws InterruptedException, IOException { conf = createConfiguration(); rpc = YarnRPC.create(conf); rmAddress = conf.getSocketAddr( YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS, YarnConfiguration.DEFAULT_RM_PORT); AccessControlList adminACL = new AccessControlList(""); conf.set(YarnConfiguration.YARN_ADMIN_ACL, adminACL.getAclString()); resourceManager = new MockRM(conf) { protected ClientRMService createClientRMService() { return new ClientRMService(getRMContext(), this.scheduler, this.rmAppManager, this.applicationACLsManager, this.queueACLsManager, getRMContext().getRMDelegationTokenSecretManager()); }; @Override protected void doSecureLogin() throws IOException { } }; new Thread() { public void run() { resourceManager.start(); }; }.start(); int waitCount = 0; while (resourceManager.getServiceState() == STATE.INITED && waitCount++ < 60) { LOG.info("Waiting for RM to start..."); Thread.sleep(1500); } if (resourceManager.getServiceState() != STATE.STARTED) { // RM could have failed. throw new IOException("ResourceManager failed to start. Final state is " + resourceManager.getServiceState()); } } @After public void tearDown() { if (resourceManager != null) { resourceManager.stop(); } } @Test public void testApplicationACLs() throws Exception { verifyKillAppSuccess(QUEUE_A_USER, QUEUE_A_USER, QUEUEA, true); verifyKillAppSuccess(QUEUE_A_USER, QUEUE_A_ADMIN, QUEUEA, true); verifyKillAppSuccess(QUEUE_A_USER, COMMON_USER, QUEUEA, true); verifyKillAppSuccess(QUEUE_A_USER, ROOT_ADMIN, QUEUEA, true); verifyKillAppFailure(QUEUE_A_USER, QUEUE_B_USER, QUEUEA, true); verifyKillAppFailure(QUEUE_A_USER, QUEUE_B_ADMIN, QUEUEA, true); verifyKillAppSuccess(QUEUE_B_USER, QUEUE_B_USER, QUEUEB, true); verifyKillAppSuccess(QUEUE_B_USER, QUEUE_B_ADMIN, QUEUEB, true); verifyKillAppSuccess(QUEUE_B_USER, COMMON_USER, QUEUEB, true); verifyKillAppSuccess(QUEUE_B_USER, ROOT_ADMIN, QUEUEB, true); verifyKillAppFailure(QUEUE_B_USER, QUEUE_A_USER, QUEUEB, true); verifyKillAppFailure(QUEUE_B_USER, QUEUE_A_ADMIN, QUEUEB, true); verifyKillAppSuccess(ROOT_ADMIN, ROOT_ADMIN, QUEUEA, false); verifyKillAppSuccess(ROOT_ADMIN, ROOT_ADMIN, QUEUEB, false); verifyGetClientAMToken(QUEUE_A_USER, ROOT_ADMIN, QUEUEA, true); } private void verifyGetClientAMToken(String submitter, String queueAdmin, String queueName, boolean setupACLs) throws Exception { ApplicationId applicationId = submitAppAndGetAppId(submitter, queueName, setupACLs); final GetApplicationReportRequest appReportRequest = GetApplicationReportRequest.newInstance(applicationId); ApplicationClientProtocol submitterClient = getRMClientForUser(submitter); ApplicationClientProtocol adMinUserClient = getRMClientForUser(queueAdmin); GetApplicationReportResponse submitterGetReport = submitterClient.getApplicationReport(appReportRequest); GetApplicationReportResponse adMinUserGetReport = adMinUserClient.getApplicationReport(appReportRequest); Assert.assertEquals(submitterGetReport.getApplicationReport() .getClientToAMToken(), adMinUserGetReport.getApplicationReport() .getClientToAMToken()); } private void verifyKillAppFailure(String submitter, String killer, String queueName, boolean setupACLs) throws Exception { ApplicationId applicationId = submitAppAndGetAppId(submitter, queueName, setupACLs); final KillApplicationRequest finishAppRequest = KillApplicationRequest.newInstance(applicationId); ApplicationClientProtocol killerClient = getRMClientForUser(killer); // Kill app as the killer try { killerClient.forceKillApplication(finishAppRequest); Assert.fail("App killing by the enemy should fail!!"); } catch (YarnException e) { LOG.info("Got exception while killing app as the enemy", e); Assert.assertTrue(e.getMessage().contains( "User " + killer + " cannot perform operation MODIFY_APP on " + applicationId)); } getRMClientForUser(submitter).forceKillApplication(finishAppRequest); } private void verifyKillAppSuccess(String submitter, String killer, String queueName, boolean setupACLs) throws Exception { ApplicationId applicationId = submitAppAndGetAppId(submitter, queueName, setupACLs); final KillApplicationRequest finishAppRequest = KillApplicationRequest.newInstance(applicationId); ApplicationClientProtocol ownerClient = getRMClientForUser(killer); // Kill app as killer ownerClient.forceKillApplication(finishAppRequest); resourceManager.waitForState(applicationId, RMAppState.KILLED); } private ApplicationId submitAppAndGetAppId(String submitter, String queueName, boolean setupACLs) throws Exception { GetNewApplicationRequest newAppRequest = GetNewApplicationRequest.newInstance(); ApplicationClientProtocol submitterClient = getRMClientForUser(submitter); ApplicationId applicationId = submitterClient.getNewApplication(newAppRequest).getApplicationId(); Resource resource = BuilderUtils.newResource(1024, 1); Map<ApplicationAccessType, String> acls = createACLs(submitter, setupACLs); ContainerLaunchContext amContainerSpec = ContainerLaunchContext.newInstance(null, null, null, null, null, acls); ApplicationSubmissionContext appSubmissionContext = ApplicationSubmissionContext.newInstance(applicationId, "applicationName", queueName, null, amContainerSpec, false, true, 1, resource, "applicationType"); appSubmissionContext.setApplicationId(applicationId); appSubmissionContext.setQueue(queueName); SubmitApplicationRequest submitRequest = SubmitApplicationRequest.newInstance(appSubmissionContext); submitterClient.submitApplication(submitRequest); resourceManager.waitForState(applicationId, RMAppState.ACCEPTED); return applicationId; } private Map<ApplicationAccessType, String> createACLs(String submitter, boolean setupACLs) { AccessControlList viewACL = new AccessControlList(""); AccessControlList modifyACL = new AccessControlList(""); if (setupACLs) { viewACL.addUser(submitter); viewACL.addUser(COMMON_USER); modifyACL.addUser(submitter); modifyACL.addUser(COMMON_USER); } Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(); acls.put(ApplicationAccessType.VIEW_APP, viewACL.getAclString()); acls.put(ApplicationAccessType.MODIFY_APP, modifyACL.getAclString()); return acls; } private ApplicationClientProtocol getRMClientForUser(String user) throws IOException, InterruptedException { UserGroupInformation userUGI = UserGroupInformation.createRemoteUser(user); ApplicationClientProtocol userClient = userUGI .doAs(new PrivilegedExceptionAction<ApplicationClientProtocol>() { @Override public ApplicationClientProtocol run() throws Exception { return (ApplicationClientProtocol) rpc.getProxy( ApplicationClientProtocol.class, rmAddress, conf); } }); return userClient; } protected abstract Configuration createConfiguration() throws IOException; }
10,743
38.94052
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockRM.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; import java.io.IOException; import java.nio.ByteBuffer; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DataOutputBuffer; 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.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; 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.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LogAggregationContext; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Priority; 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.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncherEvent; import org.apache.hadoop.yarn.server.resourcemanager.amlauncher.ApplicationMasterLauncher; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; 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.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptLaunchFailedEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeStartedEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.YarnVersionInfo; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.Assert; @SuppressWarnings("unchecked") public class MockRM extends ResourceManager { static final Logger LOG = Logger.getLogger(MockRM.class); static final String ENABLE_WEBAPP = "mockrm.webapp.enabled"; final private boolean useNullRMNodeLabelsManager; public MockRM() { this(new YarnConfiguration()); } public MockRM(Configuration conf) { this(conf, null); } public MockRM(Configuration conf, RMStateStore store) { this(conf, store, true); } public MockRM(Configuration conf, RMStateStore store, boolean useNullRMNodeLabelsManager) { super(); this.useNullRMNodeLabelsManager = useNullRMNodeLabelsManager; init(conf instanceof YarnConfiguration ? conf : new YarnConfiguration(conf)); if(store != null) { setRMStateStore(store); } Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); } @Override protected RMNodeLabelsManager createNodeLabelManager() throws InstantiationException, IllegalAccessException { if (useNullRMNodeLabelsManager) { RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); mgr.init(getConfig()); return mgr; } else { return super.createNodeLabelManager(); } } public void waitForState(ApplicationId appId, RMAppState finalState) throws Exception { RMApp app = getRMContext().getRMApps().get(appId); Assert.assertNotNull("app shouldn't be null", app); final int timeoutMsecs = 80000; final int waitMsPerLoop = 500; int loop = 0; while (!finalState.equals(app.getState()) && ((waitMsPerLoop * loop) < timeoutMsecs)) { LOG.info("App : " + appId + " State is : " + app.getState() + " Waiting for state : " + finalState); Thread.yield(); Thread.sleep(waitMsPerLoop); loop++; } int waitedMsecs = waitMsPerLoop * loop; LOG.info("App State is : " + app.getState()); if (waitedMsecs >= timeoutMsecs) { Assert.fail("App state is not correct (timedout): expected: " + finalState + " actual: " + app.getState()); } } public void waitForState(ApplicationAttemptId attemptId, RMAppAttemptState finalState) throws Exception { RMApp app = getRMContext().getRMApps().get(attemptId.getApplicationId()); Assert.assertNotNull("app shouldn't be null", app); RMAppAttempt attempt = app.getRMAppAttempt(attemptId); final int timeoutMsecs = 40000; final int minWaitMsecs = 1000; final int waitMsPerLoop = 10; int loop = 0; while (!finalState.equals(attempt.getAppAttemptState()) && waitMsPerLoop * loop < timeoutMsecs) { LOG.info("AppAttempt : " + attemptId + " State is : " + attempt.getAppAttemptState() + " Waiting for state : " + finalState); Thread.yield(); Thread.sleep(waitMsPerLoop); loop++; } int waitedMsecs = waitMsPerLoop * loop; if (minWaitMsecs > waitedMsecs) { Thread.sleep(minWaitMsecs - waitedMsecs); } LOG.info("Attempt State is : " + attempt.getAppAttemptState()); if (waitedMsecs >= timeoutMsecs) { Assert.fail("Attempt state is not correct (timedout): expected: " + finalState + " actual: " + attempt.getAppAttemptState()); } } public void waitForContainerAllocated(MockNM nm, ContainerId containerId) throws Exception { int timeoutSecs = 0; while (getResourceScheduler().getRMContainer(containerId) == null && timeoutSecs++ < 40) { System.out.println("Waiting for" + containerId + " to be allocated."); nm.nodeHeartbeat(true); Thread.sleep(200); } Assert.assertNotNull("Failed in waiting for " + containerId + " " + "allocation.", getResourceScheduler().getRMContainer(containerId)); } public void waitForContainerToComplete(RMAppAttempt attempt, NMContainerStatus completedContainer) throws InterruptedException { while (true) { List<ContainerStatus> containers = attempt.getJustFinishedContainers(); System.out.println("Received completed containers " + containers); for (ContainerStatus container : containers) { if (container.getContainerId().equals( completedContainer.getContainerId())) { return; } } Thread.sleep(200); } } public MockAM waitForNewAMToLaunchAndRegister(ApplicationId appId, int attemptSize, MockNM nm) throws Exception { RMApp app = getRMContext().getRMApps().get(appId); Assert.assertNotNull(app); while (app.getAppAttempts().size() != attemptSize) { System.out.println("Application " + appId + " is waiting for AM to restart. Current has " + app.getAppAttempts().size() + " attempts."); Thread.sleep(200); } return launchAndRegisterAM(app, this, nm); } public boolean waitForState(MockNM nm, ContainerId containerId, RMContainerState containerState) throws Exception { // default is wait for 30,000 ms return waitForState(nm, containerId, containerState, 30 * 1000); } public boolean waitForState(MockNM nm, ContainerId containerId, RMContainerState containerState, int timeoutMillisecs) throws Exception { return waitForState(Arrays.asList(nm), containerId, containerState, timeoutMillisecs); } public boolean waitForState(Collection<MockNM> nms, ContainerId containerId, RMContainerState containerState, int timeoutMillisecs) throws Exception { RMContainer container = getResourceScheduler().getRMContainer(containerId); int timeoutSecs = 0; while(container == null && timeoutSecs++ < timeoutMillisecs / 100) { for (MockNM nm : nms) { nm.nodeHeartbeat(true); } container = getResourceScheduler().getRMContainer(containerId); System.out.println("Waiting for container " + containerId + " to be allocated."); Thread.sleep(100); if (timeoutMillisecs <= timeoutSecs * 100) { return false; } } Assert.assertNotNull("Container shouldn't be null", container); while (!containerState.equals(container.getState()) && timeoutSecs++ < timeoutMillisecs / 100) { System.out.println("Container : " + containerId + " State is : " + container.getState() + " Waiting for state : " + containerState); for (MockNM nm : nms) { nm.nodeHeartbeat(true); } Thread.sleep(100); if (timeoutMillisecs <= timeoutSecs * 100) { return false; } } System.out.println("Container State is : " + container.getState()); Assert.assertEquals("Container state is not correct (timedout)", containerState, container.getState()); return true; } // get new application id public GetNewApplicationResponse getNewAppId() throws Exception { ApplicationClientProtocol client = getClientRMService(); return client.getNewApplication(Records .newRecord(GetNewApplicationRequest.class)); } public RMApp submitApp(int masterMemory) throws Exception { return submitApp(masterMemory, false); } public RMApp submitApp(int masterMemory, Priority priority) throws Exception { Resource resource = Resource.newInstance(masterMemory, 0); return submitApp(resource, "", UserGroupInformation.getCurrentUser() .getShortUserName(), null, false, null, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, true, false, false, null, 0, null, true, priority); } public RMApp submitApp(int masterMemory, boolean unmanaged) throws Exception { return submitApp(masterMemory, "", UserGroupInformation.getCurrentUser() .getShortUserName(), unmanaged); } // client public RMApp submitApp(int masterMemory, String name, String user) throws Exception { return submitApp(masterMemory, name, user, false); } public RMApp submitApp(int masterMemory, String name, String user, boolean unmanaged) throws Exception { return submitApp(masterMemory, name, user, null, unmanaged, null, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls) throws Exception { return submitApp(masterMemory, name, user, acls, false, null, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, String queue) throws Exception { return submitApp(masterMemory, name, user, acls, false, queue, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null); } public RMApp submitApp(Resource resource, String name, String user, Map<ApplicationAccessType, String> acls, String queue) throws Exception { return submitApp(resource, name, user, acls, false, queue, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, true, false, false, null, 0, null, true, null); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, String queue, boolean waitForAccepted) throws Exception { return submitApp(masterMemory, name, user, acls, false, queue, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, waitForAccepted); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, boolean unmanaged, String queue, int maxAppAttempts, Credentials ts) throws Exception { return submitApp(masterMemory, name, user, acls, unmanaged, queue, maxAppAttempts, ts, null); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, boolean unmanaged, String queue, int maxAppAttempts, Credentials ts, String appType) throws Exception { return submitApp(masterMemory, name, user, acls, unmanaged, queue, maxAppAttempts, ts, appType, true); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, boolean unmanaged, String queue, int maxAppAttempts, Credentials ts, String appType, boolean waitForAccepted) throws Exception { return submitApp(masterMemory, name, user, acls, unmanaged, queue, maxAppAttempts, ts, appType, waitForAccepted, false); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, boolean unmanaged, String queue, int maxAppAttempts, Credentials ts, String appType, boolean waitForAccepted, boolean keepContainers) throws Exception { Resource resource = Records.newRecord(Resource.class); resource.setMemory(masterMemory); return submitApp(resource, name, user, acls, unmanaged, queue, maxAppAttempts, ts, appType, waitForAccepted, keepContainers, false, null, 0, null, true, Priority.newInstance(0)); } public RMApp submitApp(int masterMemory, long attemptFailuresValidityInterval) throws Exception { Resource resource = Records.newRecord(Resource.class); resource.setMemory(masterMemory); Priority priority = Priority.newInstance(0); return submitApp(resource, "", UserGroupInformation.getCurrentUser() .getShortUserName(), null, false, null, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, true, false, false, null, attemptFailuresValidityInterval, null, true, priority); } public RMApp submitApp(int masterMemory, String name, String user, Map<ApplicationAccessType, String> acls, boolean unmanaged, String queue, int maxAppAttempts, Credentials ts, String appType, boolean waitForAccepted, boolean keepContainers, boolean isAppIdProvided, ApplicationId applicationId) throws Exception { Resource resource = Records.newRecord(Resource.class); resource.setMemory(masterMemory); Priority priority = Priority.newInstance(0); return submitApp(resource, name, user, acls, unmanaged, queue, maxAppAttempts, ts, appType, waitForAccepted, keepContainers, isAppIdProvided, applicationId, 0, null, true, priority); } public RMApp submitApp(int masterMemory, LogAggregationContext logAggregationContext) throws Exception { Resource resource = Records.newRecord(Resource.class); resource.setMemory(masterMemory); Priority priority = Priority.newInstance(0); return submitApp(resource, "", UserGroupInformation.getCurrentUser() .getShortUserName(), null, false, null, super.getConfig().getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, true, false, false, null, 0, logAggregationContext, true, priority); } public RMApp submitApp(Resource capability, String name, String user, Map<ApplicationAccessType, String> acls, boolean unmanaged, String queue, int maxAppAttempts, Credentials ts, String appType, boolean waitForAccepted, boolean keepContainers, boolean isAppIdProvided, ApplicationId applicationId, long attemptFailuresValidityInterval, LogAggregationContext logAggregationContext, boolean cancelTokensWhenComplete, Priority priority) throws Exception { ApplicationId appId = isAppIdProvided ? applicationId : null; ApplicationClientProtocol client = getClientRMService(); if (! isAppIdProvided) { GetNewApplicationResponse resp = client.getNewApplication(Records .newRecord(GetNewApplicationRequest.class)); appId = resp.getApplicationId(); } SubmitApplicationRequest req = Records .newRecord(SubmitApplicationRequest.class); ApplicationSubmissionContext sub = Records .newRecord(ApplicationSubmissionContext.class); sub.setKeepContainersAcrossApplicationAttempts(keepContainers); sub.setApplicationId(appId); sub.setApplicationName(name); sub.setMaxAppAttempts(maxAppAttempts); if (unmanaged) { sub.setUnmanagedAM(true); } if (queue != null) { sub.setQueue(queue); } if (priority != null) { sub.setPriority(priority); } sub.setApplicationType(appType); ContainerLaunchContext clc = Records .newRecord(ContainerLaunchContext.class); sub.setResource(capability); clc.setApplicationACLs(acls); if (ts != null && UserGroupInformation.isSecurityEnabled()) { DataOutputBuffer dob = new DataOutputBuffer(); ts.writeTokenStorageToStream(dob); ByteBuffer securityTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); clc.setTokens(securityTokens); } sub.setAMContainerSpec(clc); sub.setAttemptFailuresValidityInterval(attemptFailuresValidityInterval); if (logAggregationContext != null) { sub.setLogAggregationContext(logAggregationContext); } sub.setCancelTokensWhenComplete(cancelTokensWhenComplete); req.setApplicationSubmissionContext(sub); UserGroupInformation fakeUser = UserGroupInformation.createUserForTesting(user, new String[] {"someGroup"}); PrivilegedAction<SubmitApplicationResponse> action = new PrivilegedAction<SubmitApplicationResponse>() { ApplicationClientProtocol client; SubmitApplicationRequest req; @Override public SubmitApplicationResponse run() { try { return client.submitApplication(req); } catch (YarnException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } PrivilegedAction<SubmitApplicationResponse> setClientReq( ApplicationClientProtocol client, SubmitApplicationRequest req) { this.client = client; this.req = req; return this; } }.setClientReq(client, req); fakeUser.doAs(action); // make sure app is immediately available after submit if (waitForAccepted) { waitForState(appId, RMAppState.ACCEPTED); } RMApp rmApp = getRMContext().getRMApps().get(appId); // unmanaged AM won't go to RMAppAttemptState.SCHEDULED. if (waitForAccepted && !unmanaged) { waitForState(rmApp.getCurrentAppAttempt().getAppAttemptId(), RMAppAttemptState.SCHEDULED); } return rmApp; } public MockNM registerNode(String nodeIdStr, int memory) throws Exception { MockNM nm = new MockNM(nodeIdStr, memory, getResourceTrackerService()); nm.registerNode(); return nm; } public MockNM registerNode(String nodeIdStr, int memory, int vCores) throws Exception { MockNM nm = new MockNM(nodeIdStr, memory, vCores, getResourceTrackerService()); nm.registerNode(); return nm; } public MockNM registerNode(String nodeIdStr, int memory, int vCores, List<ApplicationId> runningApplications) throws Exception { MockNM nm = new MockNM(nodeIdStr, memory, vCores, getResourceTrackerService(), YarnVersionInfo.getVersion()); nm.registerNode(runningApplications); return nm; } public void sendNodeStarted(MockNM nm) throws Exception { RMNodeImpl node = (RMNodeImpl) getRMContext().getRMNodes().get( nm.getNodeId()); node.handle(new RMNodeStartedEvent(nm.getNodeId(), null, null)); } public void sendNodeLost(MockNM nm) throws Exception { RMNodeImpl node = (RMNodeImpl) getRMContext().getRMNodes().get( nm.getNodeId()); node.handle(new RMNodeEvent(nm.getNodeId(), RMNodeEventType.EXPIRE)); } public void NMwaitForState(NodeId nodeid, NodeState finalState) throws Exception { RMNode node = getRMContext().getRMNodes().get(nodeid); Assert.assertNotNull("node shouldn't be null", node); int timeoutSecs = 0; while (!finalState.equals(node.getState()) && timeoutSecs++ < 20) { System.out.println("Node State is : " + node.getState() + " Waiting for state : " + finalState); Thread.sleep(500); } System.out.println("Node State is : " + node.getState()); Assert.assertEquals("Node state is not correct (timedout)", finalState, node.getState()); } public KillApplicationResponse killApp(ApplicationId appId) throws Exception { ApplicationClientProtocol client = getClientRMService(); KillApplicationRequest req = KillApplicationRequest.newInstance(appId); return client.forceKillApplication(req); } // from AMLauncher public MockAM sendAMLaunched(ApplicationAttemptId appAttemptId) throws Exception { MockAM am = new MockAM(getRMContext(), masterService, appAttemptId); am.waitForState(RMAppAttemptState.ALLOCATED); //create and set AMRMToken Token<AMRMTokenIdentifier> amrmToken = this.rmContext.getAMRMTokenSecretManager().createAndGetAMRMToken( appAttemptId); ((RMAppAttemptImpl) this.rmContext.getRMApps() .get(appAttemptId.getApplicationId()).getRMAppAttempt(appAttemptId)) .setAMRMToken(amrmToken); getRMContext() .getDispatcher() .getEventHandler() .handle( new RMAppAttemptEvent(appAttemptId, RMAppAttemptEventType.LAUNCHED)); return am; } public void sendAMLaunchFailed(ApplicationAttemptId appAttemptId) throws Exception { MockAM am = new MockAM(getRMContext(), masterService, appAttemptId); am.waitForState(RMAppAttemptState.ALLOCATED); getRMContext().getDispatcher().getEventHandler() .handle(new RMAppAttemptLaunchFailedEvent(appAttemptId, "Failed")); } @Override protected ClientRMService createClientRMService() { return new ClientRMService(getRMContext(), getResourceScheduler(), rmAppManager, applicationACLsManager, queueACLsManager, getRMContext().getRMDelegationTokenSecretManager()) { @Override protected void serviceStart() { // override to not start rpc handler } @Override protected void serviceStop() { // don't do anything } }; } @Override protected ResourceTrackerService createResourceTrackerService() { RMContainerTokenSecretManager containerTokenSecretManager = getRMContext().getContainerTokenSecretManager(); containerTokenSecretManager.rollMasterKey(); NMTokenSecretManagerInRM nmTokenSecretManager = getRMContext().getNMTokenSecretManager(); nmTokenSecretManager.rollMasterKey(); return new ResourceTrackerService(getRMContext(), nodesListManager, this.nmLivelinessMonitor, containerTokenSecretManager, nmTokenSecretManager) { @Override protected void serviceStart() { // override to not start rpc handler } @Override protected void serviceStop() { // don't do anything } }; } @Override protected ApplicationMasterService createApplicationMasterService() { return new ApplicationMasterService(getRMContext(), scheduler) { @Override protected void serviceStart() { // override to not start rpc handler } @Override protected void serviceStop() { // don't do anything } }; } @Override protected ApplicationMasterLauncher createAMLauncher() { return new ApplicationMasterLauncher(getRMContext()) { @Override protected void serviceStart() { // override to not start rpc handler } @Override public void handle(AMLauncherEvent appEvent) { // don't do anything } @Override protected void serviceStop() { // don't do anything } }; } @Override protected AdminService createAdminService() { return new AdminService(this, getRMContext()) { @Override protected void startServer() { // override to not start rpc handler } @Override protected void stopServer() { // don't do anything } @Override protected EmbeddedElectorService createEmbeddedElectorService() { return null; } }; } public NodesListManager getNodesListManager() { return this.nodesListManager; } public ClientToAMTokenSecretManagerInRM getClientToAMTokenSecretManager() { return this.getRMContext().getClientToAMTokenSecretManager(); } public RMAppManager getRMAppManager() { return this.rmAppManager; } public AdminService getAdminService() { return this.adminService; } @Override protected void startWepApp() { if (getConfig().getBoolean(ENABLE_WEBAPP, false)) { super.startWepApp(); return; } // Disable webapp } public static void finishAMAndVerifyAppState(RMApp rmApp, MockRM rm, MockNM nm, MockAM am) throws Exception { FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.SUCCEEDED, "", ""); am.unregisterAppAttempt(req,true); am.waitForState(RMAppAttemptState.FINISHING); nm.nodeHeartbeat(am.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); rm.waitForState(rmApp.getApplicationId(), RMAppState.FINISHED); } @SuppressWarnings("rawtypes") private static void waitForSchedulerAppAttemptAdded( ApplicationAttemptId attemptId, MockRM rm) throws InterruptedException { int tick = 0; // Wait for at most 5 sec while (null == ((AbstractYarnScheduler) rm.getResourceScheduler()) .getApplicationAttempt(attemptId) && tick < 50) { Thread.sleep(100); if (tick % 10 == 0) { System.out.println("waiting for SchedulerApplicationAttempt=" + attemptId + " added."); } tick++; } Assert.assertNotNull("Timed out waiting for SchedulerApplicationAttempt=" + attemptId + " to be added.", ((AbstractYarnScheduler) rm.getResourceScheduler()).getApplicationAttempt(attemptId)); } public static MockAM launchAM(RMApp app, MockRM rm, MockNM nm) throws Exception { rm.waitForState(app.getApplicationId(), RMAppState.ACCEPTED); RMAppAttempt attempt = app.getCurrentAppAttempt(); waitForSchedulerAppAttemptAdded(attempt.getAppAttemptId(), rm); rm.waitForState(attempt.getAppAttemptId(), RMAppAttemptState.SCHEDULED); System.out.println("Launch AM " + attempt.getAppAttemptId()); nm.nodeHeartbeat(true); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); rm.waitForState(attempt.getAppAttemptId(), RMAppAttemptState.LAUNCHED); return am; } public static MockAM launchAndRegisterAM(RMApp app, MockRM rm, MockNM nm) throws Exception { MockAM am = launchAM(app, rm, nm); am.registerAppAttempt(); rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); return am; } public ApplicationReport getApplicationReport(ApplicationId appId) throws YarnException, IOException { ApplicationClientProtocol client = getClientRMService(); GetApplicationReportResponse response = client.getApplicationReport(GetApplicationReportRequest .newInstance(appId)); return response.getApplicationReport(); } // Explicitly reset queue metrics for testing. @SuppressWarnings("static-access") public void clearQueueMetrics(RMApp app) { ((AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode>) getResourceScheduler()) .getSchedulerApplications().get(app.getApplicationId()).getQueue() .getMetrics().clearQueueMetrics(); } public RMActiveServices getRMActiveService() { return activeServices; } }
31,666
38.933165
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationCleanup.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; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestApplicationCleanup { private static final Log LOG = LogFactory .getLog(TestApplicationCleanup.class); private YarnConfiguration conf; @Before public void setup() throws UnknownHostException { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); conf = new YarnConfiguration(); UserGroupInformation.setConfiguration(conf); conf.set(YarnConfiguration.RECOVERY_ENABLED, "true"); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); Assert.assertTrue(YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS > 1); } @SuppressWarnings("resource") @Test public void testAppCleanup() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); MockRM rm = new MockRM(); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 5000); RMApp app = rm.submitApp(2000); //kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); //request for containers int request = 2; am.allocate("127.0.0.1" , 1000, request, new ArrayList<ContainerId>()); //kick the scheduler nm1.nodeHeartbeat(true); List<Container> conts = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); int contReceived = conts.size(); int waitCount = 0; while (contReceived < request && waitCount++ < 200) { LOG.info("Got " + contReceived + " containers. Waiting to get " + request); Thread.sleep(100); conts = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); contReceived += conts.size(); nm1.nodeHeartbeat(true); } Assert.assertEquals(request, contReceived); am.unregisterAppAttempt(); NodeHeartbeatResponse resp = nm1.nodeHeartbeat(attempt.getAppAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); //currently only containers are cleaned via this //AM container is cleaned via container launcher resp = nm1.nodeHeartbeat(true); List<ContainerId> containersToCleanup = resp.getContainersToCleanup(); List<ApplicationId> appsToCleanup = resp.getApplicationsToCleanup(); int numCleanedContainers = containersToCleanup.size(); int numCleanedApps = appsToCleanup.size(); waitCount = 0; while ((numCleanedContainers < 2 || numCleanedApps < 1) && waitCount++ < 200) { LOG.info("Waiting to get cleanup events.. cleanedConts: " + numCleanedContainers + " cleanedApps: " + numCleanedApps); Thread.sleep(100); resp = nm1.nodeHeartbeat(true); List<ContainerId> deltaContainersToCleanup = resp.getContainersToCleanup(); List<ApplicationId> deltaAppsToCleanup = resp.getApplicationsToCleanup(); // Add the deltas to the global list containersToCleanup.addAll(deltaContainersToCleanup); appsToCleanup.addAll(deltaAppsToCleanup); // Update counts now numCleanedContainers = containersToCleanup.size(); numCleanedApps = appsToCleanup.size(); } Assert.assertEquals(1, appsToCleanup.size()); Assert.assertEquals(app.getApplicationId(), appsToCleanup.get(0)); Assert.assertEquals(1, numCleanedApps); Assert.assertEquals(2, numCleanedContainers); rm.stop(); } @SuppressWarnings("resource") @Test public void testContainerCleanup() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); final DrainDispatcher dispatcher = new DrainDispatcher(); MockRM rm = new MockRM() { @Override protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() { return new SchedulerEventDispatcher(this.scheduler) { @Override public void handle(SchedulerEvent event) { scheduler.handle(event); } }; } @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 5000); RMApp app = rm.submitApp(2000); //kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); //request for containers int request = 2; am.allocate("127.0.0.1" , 1000, request, new ArrayList<ContainerId>()); dispatcher.await(); //kick the scheduler nm1.nodeHeartbeat(true); List<Container> conts = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); int contReceived = conts.size(); int waitCount = 0; while (contReceived < request && waitCount++ < 200) { LOG.info("Got " + contReceived + " containers. Waiting to get " + request); Thread.sleep(100); conts = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); dispatcher.await(); contReceived += conts.size(); nm1.nodeHeartbeat(true); } Assert.assertEquals(request, contReceived); // Release a container. ArrayList<ContainerId> release = new ArrayList<ContainerId>(); release.add(conts.get(0).getId()); am.allocate(new ArrayList<ResourceRequest>(), release); dispatcher.await(); // Send one more heartbeat with a fake running container. This is to // simulate the situation that can happen if the NM reports that container // is running in the same heartbeat when the RM asks it to clean it up. Map<ApplicationId, List<ContainerStatus>> containerStatuses = new HashMap<ApplicationId, List<ContainerStatus>>(); ArrayList<ContainerStatus> containerStatusList = new ArrayList<ContainerStatus>(); containerStatusList.add(BuilderUtils.newContainerStatus(conts.get(0) .getId(), ContainerState.RUNNING, "nothing", 0)); containerStatuses.put(app.getApplicationId(), containerStatusList); NodeHeartbeatResponse resp = nm1.nodeHeartbeat(containerStatuses, true); waitForContainerCleanup(dispatcher, nm1, resp); // Now to test the case when RM already gave cleanup, and NM suddenly // realizes that the container is running. LOG.info("Testing container launch much after release and " + "NM getting cleanup"); containerStatuses.clear(); containerStatusList.clear(); containerStatusList.add(BuilderUtils.newContainerStatus(conts.get(0) .getId(), ContainerState.RUNNING, "nothing", 0)); containerStatuses.put(app.getApplicationId(), containerStatusList); resp = nm1.nodeHeartbeat(containerStatuses, true); // The cleanup list won't be instantaneous as it is given out by scheduler // and not RMNodeImpl. waitForContainerCleanup(dispatcher, nm1, resp); rm.stop(); } protected void waitForContainerCleanup(DrainDispatcher dispatcher, MockNM nm, NodeHeartbeatResponse resp) throws Exception { int waitCount = 0, cleanedConts = 0; List<ContainerId> contsToClean; do { dispatcher.await(); contsToClean = resp.getContainersToCleanup(); cleanedConts += contsToClean.size(); if (cleanedConts >= 1) { break; } Thread.sleep(100); resp = nm.nodeHeartbeat(true); } while(waitCount++ < 200); if (contsToClean.isEmpty()) { LOG.error("Failed to get any containers to cleanup"); } else { LOG.info("Got cleanup for " + contsToClean.get(0)); } Assert.assertEquals(1, cleanedConts); } private void waitForAppCleanupMessageRecved(MockNM nm, ApplicationId appId) throws Exception { while (true) { NodeHeartbeatResponse response = nm.nodeHeartbeat(true); if (response.getApplicationsToCleanup() != null && response.getApplicationsToCleanup().size() == 1 && appId.equals(response.getApplicationsToCleanup().get(0))) { return; } LOG.info("Haven't got application=" + appId.toString() + " in cleanup list from node heartbeat response, " + "sleep for a while before next heartbeat"); Thread.sleep(1000); } } private MockAM launchAM(RMApp app, MockRM rm, MockNM nm) throws Exception { RMAppAttempt attempt = app.getCurrentAppAttempt(); nm.nodeHeartbeat(true); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); return am; } @SuppressWarnings("resource") @Test (timeout = 60000) public void testAppCleanupWhenRMRestartedAfterAppFinished() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM MockRM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); rm1.waitForState(app0.getApplicationId(), RMAppState.FAILED); // start new RM MockRM rm2 = new MockRM(conf, memStore); rm2.start(); // nm1 register to rm2, and do a heartbeat nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm1.registerNode(Arrays.asList(app0.getApplicationId())); rm2.waitForState(app0.getApplicationId(), RMAppState.FAILED); // wait for application cleanup message received waitForAppCleanupMessageRecved(nm1, app0.getApplicationId()); rm1.stop(); rm2.stop(); } @SuppressWarnings("resource") @Test(timeout = 60000) public void testAppCleanupWhenRMRestartedBeforeAppFinished() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM MockRM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 1024, rm1.getResourceTrackerService()); nm1.registerNode(); MockNM nm2 = new MockNM("127.0.0.1:5678", 1024, rm1.getResourceTrackerService()); nm2.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // alloc another container on nm2 AllocateResponse allocResponse = am0.allocate(Arrays.asList(ResourceRequest.newInstance( Priority.newInstance(1), "*", Resource.newInstance(1024, 0), 1)), null); while (null == allocResponse.getAllocatedContainers() || allocResponse.getAllocatedContainers().isEmpty()) { nm2.nodeHeartbeat(true); allocResponse = am0.allocate(null, null); Thread.sleep(1000); } // start new RM MockRM rm2 = new MockRM(conf, memStore); rm2.start(); // nm1/nm2 register to rm2, and do a heartbeat nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm1.registerNode(Arrays.asList(NMContainerStatus.newInstance( ContainerId.newContainerId(am0.getApplicationAttemptId(), 1), ContainerState.COMPLETE, Resource.newInstance(1024, 1), "", 0, Priority.newInstance(0), 1234)), Arrays.asList(app0.getApplicationId())); nm2.setResourceTrackerService(rm2.getResourceTrackerService()); nm2.registerNode(Arrays.asList(app0.getApplicationId())); // assert app state has been saved. rm2.waitForState(app0.getApplicationId(), RMAppState.FAILED); // wait for application cleanup message received on NM1 waitForAppCleanupMessageRecved(nm1, app0.getApplicationId()); // wait for application cleanup message received on NM2 waitForAppCleanupMessageRecved(nm2, app0.getApplicationId()); rm1.stop(); rm2.stop(); } @SuppressWarnings("resource") @Test (timeout = 60000) public void testContainerCleanupWhenRMRestartedAppNotRegistered() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM final DrainDispatcher dispatcher = new DrainDispatcher(); MockRM rm1 = new MockRM(conf, memStore) { @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.RUNNING); rm1.waitForState(app0.getApplicationId(), RMAppState.RUNNING); // start new RM final DrainDispatcher dispatcher2 = new DrainDispatcher(); MockRM rm2 = new MockRM(conf, memStore) { @Override protected Dispatcher createDispatcher() { return dispatcher2; } }; rm2.start(); // nm1 register to rm2, and do a heartbeat nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm1.registerNode(Arrays.asList(app0.getApplicationId())); rm2.waitForState(app0.getApplicationId(), RMAppState.ACCEPTED); // Add unknown container for application unknown to scheduler NodeHeartbeatResponse response = nm1.nodeHeartbeat(am0 .getApplicationAttemptId(), 2, ContainerState.RUNNING); waitForContainerCleanup(dispatcher2, nm1, response); rm1.stop(); rm2.stop(); } @Test (timeout = 60000) public void testAppCleanupWhenNMReconnects() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // start RM MockRM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); rm1.waitForState(app0.getApplicationId(), RMAppState.FAILED); // wait for application cleanup message received waitForAppCleanupMessageRecved(nm1, app0.getApplicationId()); // reconnect NM with application still active nm1.registerNode(Arrays.asList(app0.getApplicationId())); waitForAppCleanupMessageRecved(nm1, app0.getApplicationId()); rm1.stop(); } // The test verifies processing of NMContainerStatuses which are sent during // NM registration. // 1. Start the cluster-RM,NM,Submit app with 1024MB,Launch & register AM // 2. AM sends ResourceRequest for 1 container with memory 2048MB. // 3. Verify for number of container allocated by RM // 4. Verify Memory Usage by cluster, it should be 3072. AM memory + requested // memory. 1024 + 2048=3072 // 5. Re-register NM by sending completed container status // 6. Verify for Memory Used, it should be 1024 // 7. Send AM heatbeat to RM. Allocated response should contain completed // container. @Test(timeout = 60000) public void testProcessingNMContainerStatusesOnNMRestart() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // 1. Start the cluster-RM,NM,Submit app with 1024MB,Launch & register AM MockRM rm1 = new MockRM(conf, memStore); rm1.start(); int nmMemory = 8192; int amMemory = 1024; int containerMemory = 2048; MockNM nm1 = new MockNM("127.0.0.1:1234", nmMemory, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app0 = rm1.submitApp(amMemory); MockAM am0 = MockRM.launchAndRegisterAM(app0, rm1, nm1); // 2. AM sends ResourceRequest for 1 container with memory 2048MB. int noOfContainers = 1; List<Container> allocateContainers = am0.allocateAndWaitForContainers(noOfContainers, containerMemory, nm1); // 3. Verify for number of container allocated by RM Assert.assertEquals(noOfContainers, allocateContainers.size()); Container container = allocateContainers.get(0); nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.RUNNING); nm1.nodeHeartbeat(am0.getApplicationAttemptId(), container.getId() .getContainerId(), ContainerState.RUNNING); rm1.waitForState(app0.getApplicationId(), RMAppState.RUNNING); // 4. Verify Memory Usage by cluster, it should be 3072. AM memory + // requested memory. 1024 + 2048=3072 ResourceScheduler rs = rm1.getRMContext().getScheduler(); int allocatedMB = rs.getRootQueueMetrics().getAllocatedMB(); Assert.assertEquals(amMemory + containerMemory, allocatedMB); // 5. Re-register NM by sending completed container status List<NMContainerStatus> nMContainerStatusForApp = createNMContainerStatusForApp(am0); nm1.registerNode(nMContainerStatusForApp, Arrays.asList(app0.getApplicationId())); waitForClusterMemory(nm1, rs, amMemory); // 6. Verify for Memory Used, it should be 1024 Assert.assertEquals(amMemory, rs.getRootQueueMetrics().getAllocatedMB()); // 7. Send AM heatbeat to RM. Allocated response should contain completed // container AllocateRequest req = AllocateRequest.newInstance(0, 0F, new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>(), null); AllocateResponse allocate = am0.allocate(req); List<ContainerStatus> completedContainersStatuses = allocate.getCompletedContainersStatuses(); Assert.assertEquals(noOfContainers, completedContainersStatuses.size()); // Application clean up should happen Cluster memory used is 0 nm1.nodeHeartbeat(am0.getApplicationAttemptId(), 1, ContainerState.COMPLETE); waitForClusterMemory(nm1, rs, 0); rm1.stop(); } private void waitForClusterMemory(MockNM nm1, ResourceScheduler rs, int clusterMemory) throws Exception, InterruptedException { int counter = 0; while (rs.getRootQueueMetrics().getAllocatedMB() != clusterMemory) { nm1.nodeHeartbeat(true); Thread.sleep(100); if (counter++ == 50) { Assert.fail("Wait for cluster memory is timed out.Expected=" + clusterMemory + " Actual=" + rs.getRootQueueMetrics().getAllocatedMB()); } } } public static List<NMContainerStatus> createNMContainerStatusForApp(MockAM am) { List<NMContainerStatus> list = new ArrayList<NMContainerStatus>(); NMContainerStatus amContainer = createNMContainerStatus(am.getApplicationAttemptId(), 1, ContainerState.RUNNING, 1024); NMContainerStatus completedContainer = createNMContainerStatus(am.getApplicationAttemptId(), 2, ContainerState.COMPLETE, 2048); list.add(amContainer); list.add(completedContainer); return list; } public static NMContainerStatus createNMContainerStatus( ApplicationAttemptId appAttemptId, int id, ContainerState containerState, int memory) { ContainerId containerId = ContainerId.newContainerId(appAttemptId, id); NMContainerStatus containerReport = NMContainerStatus.newInstance(containerId, containerState, Resource.newInstance(memory, 1), "recover container", 0, Priority.newInstance(0), 0); return containerReport; } public static void main(String[] args) throws Exception { TestApplicationCleanup t = new TestApplicationCleanup(); t.testAppCleanup(); } }
23,056
36.985173
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.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; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.nodelabels.NodeLabelTestBase; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.UnRegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.records.NodeAction; import org.apache.hadoop.yarn.server.api.records.NodeStatus; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.YarnVersionInfo; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class TestResourceTrackerService extends NodeLabelTestBase { private final static File TEMP_DIR = new File(System.getProperty( "test.build.data", "/tmp"), "decommision"); private final File hostFile = new File(TEMP_DIR + File.separator + "hostFile.txt"); private MockRM rm; /** * Test RM read NM next heartBeat Interval correctly from Configuration file, * and NM get next heartBeat Interval from RM correctly */ @Test (timeout = 50000) public void testGetNextHeartBeatInterval() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NM_HEARTBEAT_INTERVAL_MS, "4000"); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals(4000, nodeHeartbeat.getNextHeartBeatInterval()); NodeHeartbeatResponse nodeHeartbeat2 = nm2.nodeHeartbeat(true); Assert.assertEquals(4000, nodeHeartbeat2.getNextHeartBeatInterval()); } /** * Decommissioning using a pre-configured include hosts file */ @Test public void testDecommissionWithIncludeHosts() throws Exception { writeToHostsFile("localhost", "host1", "host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert(metrics != null); int metricCount = metrics.getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); // To test that IPs also work String ip = NetUtils.normalizeHostName("localhost"); writeToHostsFile("host1", ip); rm.getNodesListManager().refreshNodes(conf); checkDecommissionedNMCount(rm, ++metricCount); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); Assert .assertEquals(1, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue("Node is not decommisioned.", NodeAction.SHUTDOWN .equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); Assert.assertEquals(metricCount, ClusterMetrics.getMetrics() .getNumDecommisionedNMs()); } /** * Decommissioning using a pre-configured exclude hosts file */ @Test public void testDecommissionWithExcludeHosts() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); final DrainDispatcher dispatcher = new DrainDispatcher(); rm = new MockRM(conf) { @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); dispatcher.await(); int metricCount = ClusterMetrics.getMetrics().getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); dispatcher.await(); // To test that IPs also work String ip = NetUtils.normalizeHostName("localhost"); writeToHostsFile("host2", ip); rm.getNodesListManager().refreshNodes(conf); checkDecommissionedNMCount(rm, metricCount + 2); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue("The decommisioned metrics are not updated", NodeAction.SHUTDOWN.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue("The decommisioned metrics are not updated", NodeAction.SHUTDOWN.equals(nodeHeartbeat.getNodeAction())); dispatcher.await(); writeToHostsFile(""); rm.getNodesListManager().refreshNodes(conf); nm3 = rm.registerNode("localhost:4433", 1024); dispatcher.await(); nodeHeartbeat = nm3.nodeHeartbeat(true); dispatcher.await(); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); // decommissined node is 1 since 1 node is rejoined after updating exclude // file checkDecommissionedNMCount(rm, metricCount + 1); } /** * Decommissioning using a post-configured include hosts file */ @Test public void testAddNewIncludePathToConfiguration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert(metrics != null); int initialMetricCount = metrics.getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); writeToHostsFile("host1"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); checkDecommissionedNMCount(rm, ++initialMetricCount); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( "Node should not have been decomissioned.", NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals("Node should have been decomissioned but is in state" + nodeHeartbeat.getNodeAction(), NodeAction.SHUTDOWN, nodeHeartbeat.getNodeAction()); } /** * Decommissioning using a post-configured exclude hosts file */ @Test public void testAddNewExcludePathToConfiguration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert(metrics != null); int initialMetricCount = metrics.getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); writeToHostsFile("host2"); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); checkDecommissionedNMCount(rm, ++initialMetricCount); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( "Node should not have been decomissioned.", NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals("Node should have been decomissioned but is in state" + nodeHeartbeat.getNodeAction(), NodeAction.SHUTDOWN, nodeHeartbeat.getNodeAction()); } @Test public void testNodeRegistrationSuccess() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); // trying to register a invalid node. RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.NORMAL, response.getNodeAction()); } @Test public void testNodeRegistrationWithLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toSet(NodeLabel.newInstance("A"))); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(registerReq); Assert.assertEquals("Action should be normal on valid Node Labels", NodeAction.NORMAL, response.getNodeAction()); assertCollectionEquals(nodeLabelsMgr.getNodeLabels().get(nodeId), ResourceTrackerService.convertToStringSet(registerReq.getNodeLabels())); Assert.assertTrue("Valid Node Labels were not accepted by RM", response.getAreNodeLabelsAcceptedByRM()); rm.stop(); } @Test public void testNodeRegistrationWithInvalidLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("X", "Y", "Z")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toNodeLabelSet("A", "B", "C")); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(registerReq); Assert.assertEquals( "On Invalid Node Labels action is expected to be normal", NodeAction.NORMAL, response.getNodeAction()); Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); Assert.assertNotNull(response.getDiagnosticsMessage()); Assert.assertFalse("Node Labels should not accepted by RM If Invalid", response.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @Test public void testNodeRegistrationWithInvalidLabelsSyntax() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("X", "Y", "Z")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); req.setNodeLabels(toNodeLabelSet("#Y")); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals( "On Invalid Node Labels action is expected to be normal", NodeAction.NORMAL, response.getNodeAction()); Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); Assert.assertNotNull(response.getDiagnosticsMessage()); Assert.assertFalse("Node Labels should not accepted by RM If Invalid", response.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @Test public void testNodeRegistrationWithCentralLabelConfig() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DEFAULT_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); req.setNodeLabels(toNodeLabelSet("A")); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); // registered to RM with central label config Assert.assertEquals(NodeAction.NORMAL, response.getNodeAction()); Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); Assert .assertFalse( "Node Labels should not accepted by RM If its configured with Central configuration", response.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @SuppressWarnings("unchecked") private NodeStatus getNodeStatusObject(NodeId nodeId) { NodeStatus status = Records.newRecord(NodeStatus.class); status.setNodeId(nodeId); status.setResponseId(0); status.setContainersStatuses(Collections.EMPTY_LIST); status.setKeepAliveApplications(Collections.EMPTY_LIST); return status; } @Test public void testNodeHeartBeatWithLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); // adding valid labels try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } // Registering of labels and other required info to RM ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toNodeLabelSet("A")); // Node register label RegisterNodeManagerResponse registerResponse = resourceTrackerService.registerNodeManager(registerReq); // modification of labels during heartbeat NodeHeartbeatRequest heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(toNodeLabelSet("B")); // Node heartbeat label update NodeStatus nodeStatusObject = getNodeStatusObject(nodeId); heartbeatReq.setNodeStatus(nodeStatusObject); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); NodeHeartbeatResponse nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); Assert.assertEquals("InValid Node Labels were not accepted by RM", NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); assertCollectionEquals(nodeLabelsMgr.getNodeLabels().get(nodeId), ResourceTrackerService.convertToStringSet(heartbeatReq.getNodeLabels())); Assert.assertTrue("Valid Node Labels were not accepted by RM", nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); // After modification of labels next heartbeat sends null informing no update Set<String> oldLabels = nodeLabelsMgr.getNodeLabels().get(nodeId); int responseId = nodeStatusObject.getResponseId(); heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(null); // Node heartbeat label update nodeStatusObject = getNodeStatusObject(nodeId); nodeStatusObject.setResponseId(responseId+2); heartbeatReq.setNodeStatus(nodeStatusObject); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); Assert.assertEquals("InValid Node Labels were not accepted by RM", NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); assertCollectionEquals(nodeLabelsMgr.getNodeLabels().get(nodeId), oldLabels); Assert.assertFalse("Node Labels should not accepted by RM", nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); rm.stop(); } @Test public void testNodeHeartBeatWithInvalidLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toNodeLabelSet("A")); RegisterNodeManagerResponse registerResponse = resourceTrackerService.registerNodeManager(registerReq); NodeHeartbeatRequest heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(toNodeLabelSet("B", "#C")); // Invalid heart beat labels heartbeatReq.setNodeStatus(getNodeStatusObject(nodeId)); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); NodeHeartbeatResponse nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); // response should be NORMAL when RM heartbeat labels are rejected Assert.assertEquals("Response should be NORMAL when RM heartbeat labels" + " are rejected", NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); Assert.assertFalse(nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); Assert.assertNotNull(nodeHeartbeatResponse.getDiagnosticsMessage()); rm.stop(); } @Test public void testNodeHeartbeatWithCentralLabelConfig() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DEFAULT_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); req.setNodeLabels(toNodeLabelSet("A", "B", "C")); RegisterNodeManagerResponse registerResponse = resourceTrackerService.registerNodeManager(req); NodeHeartbeatRequest heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(toNodeLabelSet("B")); // Valid heart beat labels heartbeatReq.setNodeStatus(getNodeStatusObject(nodeId)); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); NodeHeartbeatResponse nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); // response should be ok but the RMacceptNodeLabelsUpdate should be false Assert.assertEquals(NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); // no change in the labels, Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); // heartbeat labels rejected Assert.assertFalse("Invalid Node Labels should not accepted by RM", nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @Test public void testNodeRegistrationVersionLessThanRM() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); conf.set(YarnConfiguration.RM_NODEMANAGER_MINIMUM_VERSION,"EqualToRM" ); rm = new MockRM(conf); rm.start(); String nmVersion = "1.9.9"; ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(nmVersion); // trying to register a invalid node. RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response.getNodeAction()); Assert.assertTrue("Diagnostic message did not contain: 'Disallowed NodeManager " + "Version "+ nmVersion + ", is less than the minimum version'", response.getDiagnosticsMessage().contains("Disallowed NodeManager Version " + nmVersion + ", is less than the minimum version ")); } @Test public void testNodeRegistrationFailure() throws Exception { writeToHostsFile("host1"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); req.setNodeId(nodeId); req.setHttpPort(1234); // trying to register a invalid node. RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response.getNodeAction()); Assert .assertEquals( "Disallowed NodeManager from host2, Sending SHUTDOWN signal to the NodeManager.", response.getDiagnosticsMessage()); } @Test public void testSetRMIdentifierInRegistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm = new MockNM("host1:1234", 5120, rm.getResourceTrackerService()); RegisterNodeManagerResponse response = nm.registerNode(); // Verify the RMIdentifier is correctly set in RegisterNodeManagerResponse Assert.assertEquals(ResourceManager.getClusterTimeStamp(), response.getRMIdentifier()); } @Test public void testNodeRegistrationWithMinimumAllocations() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, "2048"); conf.set(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, "4"); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = BuilderUtils.newNodeId("host", 1234); req.setNodeId(nodeId); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); RegisterNodeManagerResponse response1 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response1.getNodeAction()); capability.setMemory(2048); capability.setVirtualCores(1); req.setResource(capability); RegisterNodeManagerResponse response2 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response2.getNodeAction()); capability.setMemory(1024); capability.setVirtualCores(4); req.setResource(capability); RegisterNodeManagerResponse response3 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response3.getNodeAction()); capability.setMemory(2048); capability.setVirtualCores(4); req.setResource(capability); RegisterNodeManagerResponse response4 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.NORMAL,response4.getNodeAction()); } @Test public void testReboot() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:1234", 2048); int initialMetricCount = ClusterMetrics.getMetrics().getNumRebootedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat( new HashMap<ApplicationId, List<ContainerStatus>>(), true, -100); Assert.assertTrue(NodeAction.RESYNC.equals(nodeHeartbeat.getNodeAction())); Assert.assertEquals("Too far behind rm response id:0 nm response id:-100", nodeHeartbeat.getDiagnosticsMessage()); checkRebootedNMCount(rm, ++initialMetricCount); } private void checkRebootedNMCount(MockRM rm2, int count) throws InterruptedException { int waitCount = 0; while (ClusterMetrics.getMetrics().getNumRebootedNMs() != count && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertEquals("The rebooted metrics are not updated", count, ClusterMetrics.getMetrics().getNumRebootedNMs()); } @Test public void testUnhealthyNodeStatus() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); Assert.assertEquals(0, ClusterMetrics.getMetrics().getUnhealthyNMs()); // node healthy nm1.nodeHeartbeat(true); // node unhealthy nm1.nodeHeartbeat(false); checkUnealthyNMCount(rm, nm1, true, 1); // node healthy again nm1.nodeHeartbeat(true); checkUnealthyNMCount(rm, nm1, false, 0); } private void checkUnealthyNMCount(MockRM rm, MockNM nm1, boolean health, int count) throws Exception { int waitCount = 0; while((rm.getRMContext().getRMNodes().get(nm1.getNodeId()) .getState() != NodeState.UNHEALTHY) == health && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertFalse((rm.getRMContext().getRMNodes().get(nm1.getNodeId()) .getState() != NodeState.UNHEALTHY) == health); Assert.assertEquals("Unhealthy metrics not incremented", count, ClusterMetrics.getMetrics().getUnhealthyNMs()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testHandleContainerStatusInvalidCompletions() throws Exception { rm = new MockRM(new YarnConfiguration()); rm.start(); EventHandler handler = spy(rm.getRMContext().getDispatcher().getEventHandler()); // Case 1: Unmanaged AM RMApp app = rm.submitApp(1024, true); // Case 1.1: AppAttemptId is null NMContainerStatus report = NMContainerStatus.newInstance( ContainerId.newContainerId( ApplicationAttemptId.newInstance(app.getApplicationId(), 2), 1), ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); rm.getResourceTrackerService().handleNMContainerStatus(report, null); verify(handler, never()).handle((Event) any()); // Case 1.2: Master container is null RMAppAttemptImpl currentAttempt = (RMAppAttemptImpl) app.getCurrentAppAttempt(); currentAttempt.setMasterContainer(null); report = NMContainerStatus.newInstance( ContainerId.newContainerId(currentAttempt.getAppAttemptId(), 0), ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); rm.getResourceTrackerService().handleNMContainerStatus(report, null); verify(handler, never()).handle((Event)any()); // Case 2: Managed AM app = rm.submitApp(1024); // Case 2.1: AppAttemptId is null report = NMContainerStatus.newInstance( ContainerId.newContainerId( ApplicationAttemptId.newInstance(app.getApplicationId(), 2), 1), ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); try { rm.getResourceTrackerService().handleNMContainerStatus(report, null); } catch (Exception e) { // expected - ignore } verify(handler, never()).handle((Event)any()); // Case 2.2: Master container is null currentAttempt = (RMAppAttemptImpl) app.getCurrentAppAttempt(); currentAttempt.setMasterContainer(null); report = NMContainerStatus.newInstance( ContainerId.newContainerId(currentAttempt.getAppAttemptId(), 0), ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); try { rm.getResourceTrackerService().handleNMContainerStatus(report, null); } catch (Exception e) { // expected - ignore } verify(handler, never()).handle((Event)any()); } @Test public void testReconnectNode() throws Exception { final DrainDispatcher dispatcher = new DrainDispatcher(); rm = new MockRM() { @Override protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() { return new SchedulerEventDispatcher(this.scheduler) { @Override public void handle(SchedulerEvent event) { scheduler.handle(event); } }; } @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 5120); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(false); dispatcher.await(); checkUnealthyNMCount(rm, nm2, true, 1); final int expectedNMs = ClusterMetrics.getMetrics().getNumActiveNMs(); QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); // TODO Metrics incorrect in case of the FifoScheduler Assert.assertEquals(5120, metrics.getAvailableMB()); // reconnect of healthy node nm1 = rm.registerNode("host1:1234", 5120); NodeHeartbeatResponse response = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); dispatcher.await(); Assert.assertEquals(expectedNMs, ClusterMetrics.getMetrics().getNumActiveNMs()); checkUnealthyNMCount(rm, nm2, true, 1); // reconnect of unhealthy node nm2 = rm.registerNode("host2:5678", 5120); response = nm2.nodeHeartbeat(false); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); dispatcher.await(); Assert.assertEquals(expectedNMs, ClusterMetrics.getMetrics().getNumActiveNMs()); checkUnealthyNMCount(rm, nm2, true, 1); // unhealthy node changed back to healthy nm2 = rm.registerNode("host2:5678", 5120); dispatcher.await(); response = nm2.nodeHeartbeat(true); response = nm2.nodeHeartbeat(true); dispatcher.await(); Assert.assertEquals(5120 + 5120, metrics.getAvailableMB()); // reconnect of node with changed capability nm1 = rm.registerNode("host2:5678", 10240); dispatcher.await(); response = nm1.nodeHeartbeat(true); dispatcher.await(); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); Assert.assertEquals(5120 + 10240, metrics.getAvailableMB()); // reconnect of node with changed capability and running applications List<ApplicationId> runningApps = new ArrayList<ApplicationId>(); runningApps.add(ApplicationId.newInstance(1, 0)); nm1 = rm.registerNode("host2:5678", 15360, 2, runningApps); dispatcher.await(); response = nm1.nodeHeartbeat(true); dispatcher.await(); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); Assert.assertEquals(5120 + 15360, metrics.getAvailableMB()); // reconnect healthy node changing http port nm1 = new MockNM("host1:1234", 5120, rm.getResourceTrackerService()); nm1.setHttpPort(3); nm1.registerNode(); dispatcher.await(); response = nm1.nodeHeartbeat(true); response = nm1.nodeHeartbeat(true); dispatcher.await(); RMNode rmNode = rm.getRMContext().getRMNodes().get(nm1.getNodeId()); Assert.assertEquals(3, rmNode.getHttpPort()); Assert.assertEquals(5120, rmNode.getTotalCapability().getMemory()); Assert.assertEquals(5120 + 15360, metrics.getAvailableMB()); } @Test public void testNMUnregistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm .getResourceTrackerService(); MockNM nm1 = rm.registerNode("host1:1234", 5120); int shutdownNMsCount = ClusterMetrics.getMetrics() .getNumShutdownNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); UnRegisterNodeManagerRequest request = Records .newRecord(UnRegisterNodeManagerRequest.class); request.setNodeId(nm1.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, ++shutdownNMsCount); // The RM should remove the node after unregistration, hence send a reboot // command. nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.RESYNC.equals(nodeHeartbeat.getNodeAction())); } @Test public void testUnhealthyNMUnregistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm .getResourceTrackerService(); MockNM nm1 = rm.registerNode("host1:1234", 5120); Assert.assertEquals(0, ClusterMetrics.getMetrics().getUnhealthyNMs()); // node healthy nm1.nodeHeartbeat(true); int shutdownNMsCount = ClusterMetrics.getMetrics().getNumShutdownNMs(); // node unhealthy nm1.nodeHeartbeat(false); checkUnealthyNMCount(rm, nm1, true, 1); UnRegisterNodeManagerRequest request = Records .newRecord(UnRegisterNodeManagerRequest.class); request.setNodeId(nm1.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, ++shutdownNMsCount); } @Test public void testInvalidNMUnregistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm .getResourceTrackerService(); int shutdownNMsCount = ClusterMetrics.getMetrics() .getNumShutdownNMs(); int decommisionedNMsCount = ClusterMetrics.getMetrics() .getNumDecommisionedNMs(); // Node not found for unregister UnRegisterNodeManagerRequest request = Records .newRecord(UnRegisterNodeManagerRequest.class); request.setNodeId(BuilderUtils.newNodeId("host", 1234)); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, 0); checkDecommissionedNMCount(rm, 0); // 1. Register the Node Manager // 2. Exclude the same Node Manager host // 3. Give NM heartbeat to RM // 4. Unregister the Node Manager MockNM nm1 = new MockNM("host1:1234", 5120, resourceTrackerService); RegisterNodeManagerResponse response = nm1.registerNode(); Assert.assertEquals(NodeAction.NORMAL, response.getNodeAction()); writeToHostsFile("host2"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); NodeHeartbeatResponse heartbeatResponse = nm1.nodeHeartbeat(true); Assert.assertEquals(NodeAction.SHUTDOWN, heartbeatResponse.getNodeAction()); checkShutdownNMCount(rm, shutdownNMsCount); checkDecommissionedNMCount(rm, ++decommisionedNMsCount); request.setNodeId(nm1.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, shutdownNMsCount); checkDecommissionedNMCount(rm, decommisionedNMsCount); // 1. Register the Node Manager // 2. Exclude the same Node Manager host // 3. Unregister the Node Manager MockNM nm2 = new MockNM("host2:1234", 5120, resourceTrackerService); RegisterNodeManagerResponse response2 = nm2.registerNode(); Assert.assertEquals(NodeAction.NORMAL, response2.getNodeAction()); writeToHostsFile("host1"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); request.setNodeId(nm2.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, shutdownNMsCount); checkDecommissionedNMCount(rm, ++decommisionedNMsCount); } private void writeToHostsFile(String... hosts) throws IOException { if (!hostFile.exists()) { TEMP_DIR.mkdirs(); hostFile.createNewFile(); } FileOutputStream fStream = null; try { fStream = new FileOutputStream(hostFile); for (int i = 0; i < hosts.length; i++) { fStream.write(hosts[i].getBytes()); fStream.write("\n".getBytes()); } } finally { if (fStream != null) { IOUtils.closeStream(fStream); fStream = null; } } } private void checkDecommissionedNMCount(MockRM rm, int count) throws InterruptedException { int waitCount = 0; while (ClusterMetrics.getMetrics().getNumDecommisionedNMs() != count && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertEquals(count, ClusterMetrics.getMetrics() .getNumDecommisionedNMs()); Assert.assertEquals("The decommisioned metrics are not updated", count, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); } private void checkShutdownNMCount(MockRM rm, int count) throws InterruptedException { int waitCount = 0; while (ClusterMetrics.getMetrics().getNumShutdownNMs() != count && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertEquals("The shutdown metrics are not updated", count, ClusterMetrics.getMetrics().getNumShutdownNMs()); } @After public void tearDown() { if (hostFile != null && hostFile.exists()) { hostFile.delete(); } ClusterMetrics.destroy(); if (rm != null) { rm.stop(); } MetricsSystem ms = DefaultMetricsSystem.instance(); if (ms.getSource("ClusterMetrics") != null) { DefaultMetricsSystem.shutdown(); } } }
48,760
37.977618
97
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMProxyUsersConf.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; import java.util.Arrays; import java.util.Collection; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AuthorizationException; import org.apache.hadoop.security.authorize.ProxyUsers; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class TestRMProxyUsersConf { private static final UserGroupInformation FOO_USER = UserGroupInformation.createUserForTesting("foo", new String[] { "foo_group" }); private static final UserGroupInformation BAR_USER = UserGroupInformation.createUserForTesting("bar", new String[] { "bar_group" }); private final String ipAddress = "127.0.0.1"; @Parameterized.Parameters public static Collection<Object[]> headers() { return Arrays.asList(new Object[][] { { 0 }, { 1 }, { 2 } }); } private Configuration conf; public TestRMProxyUsersConf(int round) { conf = new YarnConfiguration(); switch (round) { case 0: // hadoop.proxyuser prefix conf.set("hadoop.proxyuser.foo.hosts", ipAddress); conf.set("hadoop.proxyuser.foo.users", "bar"); conf.set("hadoop.proxyuser.foo.groups", "bar_group"); break; case 1: // yarn.resourcemanager.proxyuser prefix conf.set("yarn.resourcemanager.proxyuser.foo.hosts", ipAddress); conf.set("yarn.resourcemanager.proxyuser.foo.users", "bar"); conf.set("yarn.resourcemanager.proxyuser.foo.groups", "bar_group"); break; case 2: // hadoop.proxyuser prefix has been overwritten by // yarn.resourcemanager.proxyuser prefix conf.set("hadoop.proxyuser.foo.hosts", "xyz"); conf.set("hadoop.proxyuser.foo.users", "xyz"); conf.set("hadoop.proxyuser.foo.groups", "xyz"); conf.set("yarn.resourcemanager.proxyuser.foo.hosts", ipAddress); conf.set("yarn.resourcemanager.proxyuser.foo.users", "bar"); conf.set("yarn.resourcemanager.proxyuser.foo.groups", "bar_group"); break; default: break; } } @Test public void testProxyUserConfiguration() throws Exception { MockRM rm = null; try { rm = new MockRM(conf); rm.start(); // wait for web server starting Thread.sleep(10000); UserGroupInformation proxyUser = UserGroupInformation.createProxyUser( BAR_USER.getShortUserName(), FOO_USER); try { ProxyUsers.getDefaultImpersonationProvider().authorize(proxyUser, ipAddress); } catch (AuthorizationException e) { // Exception is not expected Assert.fail(); } } finally { if (rm != null) { rm.stop(); rm.close(); } } } }
3,771
34.252336
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClientRMService.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CyclicBarrier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authentication.util.KerberosName; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.MockApps; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.ApplicationsRequestScope; import org.apache.hadoop.yarn.api.protocolrecords.CancelDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodeLabelsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodeLabelsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainersResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetLabelsToNodesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetLabelsToNodesResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNodesToLabelsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNodesToLabelsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueInfoRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueInfoResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.MoveApplicationAcrossQueuesRequest; import org.apache.hadoop.yarn.api.protocolrecords.RenewDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteResponse; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionResponse; import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateResponse; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; 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.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.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.NullRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystemTestUtil; 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.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerImpl; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppReport; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; 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.security.QueueACLsManager; import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.Records; 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.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; public class TestClientRMService { private static final Log LOG = LogFactory.getLog(TestClientRMService.class); private RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); private String appType = "MockApp"; private static RMDelegationTokenSecretManager dtsm; private final static String QUEUE_1 = "Q-1"; private final static String QUEUE_2 = "Q-2"; private final static String kerberosRule = "RULE:[1:$1@$0](.*@EXAMPLE.COM)s/@.*//\nDEFAULT"; static { KerberosName.setRules(kerberosRule); } @BeforeClass public static void setupSecretManager() throws IOException { RMContext rmContext = mock(RMContext.class); when(rmContext.getStateStore()).thenReturn(new NullRMStateStore()); dtsm = new RMDelegationTokenSecretManager(60000, 60000, 60000, 60000, rmContext); dtsm.startThreads(); } @AfterClass public static void teardownSecretManager() { if (dtsm != null) { dtsm.stopThreads(); } } @Test public void testGetClusterNodes() throws Exception { MockRM rm = new MockRM() { protected ClientRMService createClientRMService() { return new ClientRMService(this.rmContext, scheduler, this.rmAppManager, this.applicationACLsManager, this.queueACLsManager, this.getRMContext().getRMDelegationTokenSecretManager()); }; }; rm.start(); RMNodeLabelsManager labelsMgr = rm.getRMContext().getNodeLabelManager(); labelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); // Add a healthy node with label = x MockNM node = rm.registerNode("host1:1234", 1024); Map<NodeId, Set<String>> map = new HashMap<NodeId, Set<String>>(); map.put(node.getNodeId(), ImmutableSet.of("x")); labelsMgr.replaceLabelsOnNode(map); rm.sendNodeStarted(node); node.nodeHeartbeat(true); // Add and lose a node with label = y MockNM lostNode = rm.registerNode("host2:1235", 1024); rm.sendNodeStarted(lostNode); lostNode.nodeHeartbeat(true); rm.NMwaitForState(lostNode.getNodeId(), NodeState.RUNNING); rm.sendNodeLost(lostNode); // Create a client. Configuration conf = new Configuration(); YarnRPC rpc = YarnRPC.create(conf); InetSocketAddress rmAddress = rm.getClientRMService().getBindAddress(); LOG.info("Connecting to ResourceManager at " + rmAddress); ApplicationClientProtocol client = (ApplicationClientProtocol) rpc .getProxy(ApplicationClientProtocol.class, rmAddress, conf); // Make call GetClusterNodesRequest request = GetClusterNodesRequest.newInstance(EnumSet.of(NodeState.RUNNING)); List<NodeReport> nodeReports = client.getClusterNodes(request).getNodeReports(); Assert.assertEquals(1, nodeReports.size()); Assert.assertNotSame("Node is expected to be healthy!", NodeState.UNHEALTHY, nodeReports.get(0).getNodeState()); // Check node's label = x Assert.assertTrue(nodeReports.get(0).getNodeLabels().contains("x")); // Now make the node unhealthy. node.nodeHeartbeat(false); // Call again nodeReports = client.getClusterNodes(request).getNodeReports(); Assert.assertEquals("Unhealthy nodes should not show up by default", 0, nodeReports.size()); // Change label of host1 to y map = new HashMap<NodeId, Set<String>>(); map.put(node.getNodeId(), ImmutableSet.of("y")); labelsMgr.replaceLabelsOnNode(map); // Now query for UNHEALTHY nodes request = GetClusterNodesRequest.newInstance(EnumSet.of(NodeState.UNHEALTHY)); nodeReports = client.getClusterNodes(request).getNodeReports(); Assert.assertEquals(1, nodeReports.size()); Assert.assertEquals("Node is expected to be unhealthy!", NodeState.UNHEALTHY, nodeReports.get(0).getNodeState()); Assert.assertTrue(nodeReports.get(0).getNodeLabels().contains("y")); // Remove labels of host1 map = new HashMap<NodeId, Set<String>>(); map.put(node.getNodeId(), ImmutableSet.of("y")); labelsMgr.removeLabelsFromNode(map); // Query all states should return all nodes rm.registerNode("host3:1236", 1024); request = GetClusterNodesRequest.newInstance(EnumSet.allOf(NodeState.class)); nodeReports = client.getClusterNodes(request).getNodeReports(); Assert.assertEquals(3, nodeReports.size()); // All host1-3's label should be empty (instead of null) for (NodeReport report : nodeReports) { Assert.assertTrue(report.getNodeLabels() != null && report.getNodeLabels().isEmpty()); } rpc.stopProxy(client, conf); rm.close(); } @Test public void testNonExistingApplicationReport() throws YarnException { RMContext rmContext = mock(RMContext.class); when(rmContext.getRMApps()).thenReturn( new ConcurrentHashMap<ApplicationId, RMApp>()); ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, null); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetApplicationReportRequest request = recordFactory .newRecordInstance(GetApplicationReportRequest.class); request.setApplicationId(ApplicationId.newInstance(0, 0)); try { rmService.getApplicationReport(request); Assert.fail(); } catch (ApplicationNotFoundException ex) { Assert.assertEquals(ex.getMessage(), "Application with id '" + request.getApplicationId() + "' doesn't exist in RM."); } } @Test public void testGetApplicationReport() throws Exception { YarnScheduler yarnScheduler = mock(YarnScheduler.class); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); ApplicationId appId1 = getApplicationId(1); ApplicationACLsManager mockAclsManager = mock(ApplicationACLsManager.class); when( mockAclsManager.checkAccess(UserGroupInformation.getCurrentUser(), ApplicationAccessType.VIEW_APP, null, appId1)).thenReturn(true); ClientRMService rmService = new ClientRMService(rmContext, yarnScheduler, null, mockAclsManager, null, null); try { RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetApplicationReportRequest request = recordFactory .newRecordInstance(GetApplicationReportRequest.class); request.setApplicationId(appId1); GetApplicationReportResponse response = rmService.getApplicationReport(request); ApplicationReport report = response.getApplicationReport(); ApplicationResourceUsageReport usageReport = report.getApplicationResourceUsageReport(); Assert.assertEquals(10, usageReport.getMemorySeconds()); Assert.assertEquals(3, usageReport.getVcoreSeconds()); } finally { rmService.close(); } } @Test public void testGetApplicationAttemptReport() throws YarnException, IOException { ClientRMService rmService = createRMService(); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetApplicationAttemptReportRequest request = recordFactory .newRecordInstance(GetApplicationAttemptReportRequest.class); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(123456, 1), 1); request.setApplicationAttemptId(attemptId); try { GetApplicationAttemptReportResponse response = rmService .getApplicationAttemptReport(request); Assert.assertEquals(attemptId, response.getApplicationAttemptReport() .getApplicationAttemptId()); } catch (ApplicationNotFoundException ex) { Assert.fail(ex.getMessage()); } } @Test public void testGetApplicationResourceUsageReportDummy() throws YarnException, IOException { ApplicationAttemptId attemptId = getApplicationAttemptId(1); YarnScheduler yarnScheduler = mockYarnScheduler(); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); when(rmContext.getDispatcher().getEventHandler()).thenReturn( new EventHandler<Event>() { public void handle(Event event) { } }); ApplicationSubmissionContext asContext = mock(ApplicationSubmissionContext.class); YarnConfiguration config = new YarnConfiguration(); RMAppAttemptImpl rmAppAttemptImpl = new RMAppAttemptImpl(attemptId, rmContext, yarnScheduler, null, asContext, config, false, null); ApplicationResourceUsageReport report = rmAppAttemptImpl .getApplicationResourceUsageReport(); assertEquals(report, RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT); } @Test public void testGetApplicationAttempts() throws YarnException, IOException { ClientRMService rmService = createRMService(); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetApplicationAttemptsRequest request = recordFactory .newRecordInstance(GetApplicationAttemptsRequest.class); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(123456, 1), 1); request.setApplicationId(ApplicationId.newInstance(123456, 1)); try { GetApplicationAttemptsResponse response = rmService .getApplicationAttempts(request); Assert.assertEquals(1, response.getApplicationAttemptList().size()); Assert.assertEquals(attemptId, response.getApplicationAttemptList() .get(0).getApplicationAttemptId()); } catch (ApplicationNotFoundException ex) { Assert.fail(ex.getMessage()); } } @Test public void testGetContainerReport() throws YarnException, IOException { ClientRMService rmService = createRMService(); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetContainerReportRequest request = recordFactory .newRecordInstance(GetContainerReportRequest.class); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(123456, 1), 1); ContainerId containerId = ContainerId.newContainerId(attemptId, 1); request.setContainerId(containerId); try { GetContainerReportResponse response = rmService .getContainerReport(request); Assert.assertEquals(containerId, response.getContainerReport() .getContainerId()); } catch (ApplicationNotFoundException ex) { Assert.fail(ex.getMessage()); } } @Test public void testGetContainers() throws YarnException, IOException { ClientRMService rmService = createRMService(); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetContainersRequest request = recordFactory .newRecordInstance(GetContainersRequest.class); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(123456, 1), 1); ContainerId containerId = ContainerId.newContainerId(attemptId, 1); request.setApplicationAttemptId(attemptId); try { GetContainersResponse response = rmService.getContainers(request); Assert.assertEquals(containerId, response.getContainerList().get(0) .getContainerId()); } catch (ApplicationNotFoundException ex) { Assert.fail(ex.getMessage()); } } public ClientRMService createRMService() throws IOException { YarnScheduler yarnScheduler = mockYarnScheduler(); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); ConcurrentHashMap<ApplicationId, RMApp> apps = getRMApps(rmContext, yarnScheduler); when(rmContext.getRMApps()).thenReturn(apps); when(rmContext.getYarnConfiguration()).thenReturn(new Configuration()); RMAppManager appManager = new RMAppManager(rmContext, yarnScheduler, null, mock(ApplicationACLsManager.class), new Configuration()); when(rmContext.getDispatcher().getEventHandler()).thenReturn( new EventHandler<Event>() { public void handle(Event event) { } }); ApplicationACLsManager mockAclsManager = mock(ApplicationACLsManager.class); QueueACLsManager mockQueueACLsManager = mock(QueueACLsManager.class); when( mockQueueACLsManager.checkAccess(any(UserGroupInformation.class), any(QueueACL.class), anyString())).thenReturn(true); return new ClientRMService(rmContext, yarnScheduler, appManager, mockAclsManager, mockQueueACLsManager, null); } @Test public void testForceKillNonExistingApplication() throws YarnException { RMContext rmContext = mock(RMContext.class); when(rmContext.getRMApps()).thenReturn( new ConcurrentHashMap<ApplicationId, RMApp>()); ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, null); ApplicationId applicationId = BuilderUtils.newApplicationId(System.currentTimeMillis(), 0); KillApplicationRequest request = KillApplicationRequest.newInstance(applicationId); try { rmService.forceKillApplication(request); Assert.fail(); } catch (ApplicationNotFoundException ex) { Assert.assertEquals(ex.getMessage(), "Trying to kill an absent " + "application " + request.getApplicationId()); } } @Test public void testForceKillApplication() throws Exception { YarnConfiguration conf = new YarnConfiguration(); MockRM rm = new MockRM(); rm.init(conf); rm.start(); ClientRMService rmService = rm.getClientRMService(); GetApplicationsRequest getRequest = GetApplicationsRequest.newInstance( EnumSet.of(YarnApplicationState.KILLED)); RMApp app1 = rm.submitApp(1024); RMApp app2 = rm.submitApp(1024, true); assertEquals("Incorrect number of apps in the RM", 0, rmService.getApplications(getRequest).getApplicationList().size()); KillApplicationRequest killRequest1 = KillApplicationRequest.newInstance(app1.getApplicationId()); KillApplicationRequest killRequest2 = KillApplicationRequest.newInstance(app2.getApplicationId()); int killAttemptCount = 0; for (int i = 0; i < 100; i++) { KillApplicationResponse killResponse1 = rmService.forceKillApplication(killRequest1); killAttemptCount++; if (killResponse1.getIsKillCompleted()) { break; } Thread.sleep(10); } assertTrue("Kill attempt count should be greater than 1 for managed AMs", killAttemptCount > 1); assertEquals("Incorrect number of apps in the RM", 1, rmService.getApplications(getRequest).getApplicationList().size()); KillApplicationResponse killResponse2 = rmService.forceKillApplication(killRequest2); assertTrue("Killing UnmanagedAM should falsely acknowledge true", killResponse2.getIsKillCompleted()); for (int i = 0; i < 100; i++) { if (2 == rmService.getApplications(getRequest).getApplicationList().size()) { break; } Thread.sleep(10); } assertEquals("Incorrect number of apps in the RM", 2, rmService.getApplications(getRequest).getApplicationList().size()); } @Test (expected = ApplicationNotFoundException.class) public void testMoveAbsentApplication() throws YarnException { RMContext rmContext = mock(RMContext.class); when(rmContext.getRMApps()).thenReturn( new ConcurrentHashMap<ApplicationId, RMApp>()); ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, null); ApplicationId applicationId = BuilderUtils.newApplicationId(System.currentTimeMillis(), 0); MoveApplicationAcrossQueuesRequest request = MoveApplicationAcrossQueuesRequest.newInstance(applicationId, "newqueue"); rmService.moveApplicationAcrossQueues(request); } @Test public void testGetQueueInfo() throws Exception { YarnScheduler yarnScheduler = mock(YarnScheduler.class); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); ApplicationACLsManager mockAclsManager = mock(ApplicationACLsManager.class); QueueACLsManager mockQueueACLsManager = mock(QueueACLsManager.class); when(mockQueueACLsManager.checkAccess(any(UserGroupInformation.class), any(QueueACL.class), anyString())).thenReturn(true); when(mockAclsManager.checkAccess(any(UserGroupInformation.class), any(ApplicationAccessType.class), anyString(), any(ApplicationId.class))).thenReturn(true); ClientRMService rmService = new ClientRMService(rmContext, yarnScheduler, null, mockAclsManager, mockQueueACLsManager, null); GetQueueInfoRequest request = recordFactory .newRecordInstance(GetQueueInfoRequest.class); request.setQueueName("testqueue"); request.setIncludeApplications(true); GetQueueInfoResponse queueInfo = rmService.getQueueInfo(request); List<ApplicationReport> applications = queueInfo.getQueueInfo() .getApplications(); Assert.assertEquals(2, applications.size()); request.setQueueName("nonexistentqueue"); request.setIncludeApplications(true); // should not throw exception on nonexistent queue queueInfo = rmService.getQueueInfo(request); // Case where user does not have application access ApplicationACLsManager mockAclsManager1 = mock(ApplicationACLsManager.class); QueueACLsManager mockQueueACLsManager1 = mock(QueueACLsManager.class); when(mockQueueACLsManager1.checkAccess(any(UserGroupInformation.class), any(QueueACL.class), anyString())).thenReturn(false); when(mockAclsManager1.checkAccess(any(UserGroupInformation.class), any(ApplicationAccessType.class), anyString(), any(ApplicationId.class))).thenReturn(false); ClientRMService rmService1 = new ClientRMService(rmContext, yarnScheduler, null, mockAclsManager1, mockQueueACLsManager1, null); request.setQueueName("testqueue"); request.setIncludeApplications(true); GetQueueInfoResponse queueInfo1 = rmService1.getQueueInfo(request); List<ApplicationReport> applications1 = queueInfo1.getQueueInfo() .getApplications(); Assert.assertEquals(0, applications1.size()); } private static final UserGroupInformation owner = UserGroupInformation.createRemoteUser("owner"); private static final UserGroupInformation other = UserGroupInformation.createRemoteUser("other"); private static final UserGroupInformation tester = UserGroupInformation.createRemoteUser("tester"); private static final String testerPrincipal = "[email protected]"; private static final String ownerPrincipal = "[email protected]"; private static final String otherPrincipal = "[email protected]"; private static final UserGroupInformation testerKerb = UserGroupInformation.createRemoteUser(testerPrincipal); private static final UserGroupInformation ownerKerb = UserGroupInformation.createRemoteUser(ownerPrincipal); private static final UserGroupInformation otherKerb = UserGroupInformation.createRemoteUser(otherPrincipal); @Test public void testTokenRenewalByOwner() throws Exception { owner.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenRenewal(owner, owner); return null; } }); } @Test public void testTokenRenewalWrongUser() throws Exception { try { owner.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { try { checkTokenRenewal(owner, other); return null; } catch (YarnException ex) { Assert.assertTrue(ex.getMessage().contains(owner.getUserName() + " tries to renew a token with renewer " + other.getUserName())); throw ex; } } }); } catch (Exception e) { return; } Assert.fail("renew should have failed"); } @Test public void testTokenRenewalByLoginUser() throws Exception { UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenRenewal(owner, owner); checkTokenRenewal(owner, other); return null; } }); } private void checkTokenRenewal(UserGroupInformation owner, UserGroupInformation renewer) throws IOException, YarnException { RMDelegationTokenIdentifier tokenIdentifier = new RMDelegationTokenIdentifier( new Text(owner.getUserName()), new Text(renewer.getUserName()), null); Token<?> token = new Token<RMDelegationTokenIdentifier>(tokenIdentifier, dtsm); org.apache.hadoop.yarn.api.records.Token dToken = BuilderUtils.newDelegationToken( token.getIdentifier(), token.getKind().toString(), token.getPassword(), token.getService().toString()); RenewDelegationTokenRequest request = Records.newRecord(RenewDelegationTokenRequest.class); request.setDelegationToken(dToken); RMContext rmContext = mock(RMContext.class); ClientRMService rmService = new ClientRMService( rmContext, null, null, null, null, dtsm); rmService.renewDelegationToken(request); } @Test public void testTokenCancellationByOwner() throws Exception { // two tests required - one with a kerberos name // and with a short name RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); testerKerb.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(rmService, testerKerb, other); return null; } }); owner.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(owner, other); return null; } }); } @Test public void testTokenCancellationByRenewer() throws Exception { // two tests required - one with a kerberos name // and with a short name RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); testerKerb.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(rmService, owner, testerKerb); return null; } }); other.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { checkTokenCancellation(owner, other); return null; } }); } @Test public void testTokenCancellationByWrongUser() { // two sets to test - // 1. try to cancel tokens of short and kerberos users as a kerberos UGI // 2. try to cancel tokens of short and kerberos users as a simple auth UGI RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); UserGroupInformation[] kerbTestOwners = { owner, other, tester, ownerKerb, otherKerb }; UserGroupInformation[] kerbTestRenewers = { owner, other, ownerKerb, otherKerb }; for (final UserGroupInformation tokOwner : kerbTestOwners) { for (final UserGroupInformation tokRenewer : kerbTestRenewers) { try { testerKerb.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { try { checkTokenCancellation(rmService, tokOwner, tokRenewer); Assert.fail("We should not reach here; token owner = " + tokOwner.getUserName() + ", renewer = " + tokRenewer.getUserName()); return null; } catch (YarnException e) { Assert.assertTrue(e.getMessage().contains( testerKerb.getUserName() + " is not authorized to cancel the token")); return null; } } }); } catch (Exception e) { Assert.fail("Unexpected exception; " + e.getMessage()); } } } UserGroupInformation[] simpleTestOwners = { owner, other, ownerKerb, otherKerb, testerKerb }; UserGroupInformation[] simpleTestRenewers = { owner, other, ownerKerb, otherKerb }; for (final UserGroupInformation tokOwner : simpleTestOwners) { for (final UserGroupInformation tokRenewer : simpleTestRenewers) { try { tester.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { try { checkTokenCancellation(tokOwner, tokRenewer); Assert.fail("We should not reach here; token owner = " + tokOwner.getUserName() + ", renewer = " + tokRenewer.getUserName()); return null; } catch (YarnException ex) { Assert.assertTrue(ex.getMessage().contains( tester.getUserName() + " is not authorized to cancel the token")); return null; } } }); } catch (Exception e) { Assert.fail("Unexpected exception; " + e.getMessage()); } } } } private void checkTokenCancellation(UserGroupInformation owner, UserGroupInformation renewer) throws IOException, YarnException { RMContext rmContext = mock(RMContext.class); final ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null, dtsm); checkTokenCancellation(rmService, owner, renewer); } private void checkTokenCancellation(ClientRMService rmService, UserGroupInformation owner, UserGroupInformation renewer) throws IOException, YarnException { RMDelegationTokenIdentifier tokenIdentifier = new RMDelegationTokenIdentifier(new Text(owner.getUserName()), new Text(renewer.getUserName()), null); Token<?> token = new Token<RMDelegationTokenIdentifier>(tokenIdentifier, dtsm); org.apache.hadoop.yarn.api.records.Token dToken = BuilderUtils.newDelegationToken(token.getIdentifier(), token.getKind() .toString(), token.getPassword(), token.getService().toString()); CancelDelegationTokenRequest request = Records.newRecord(CancelDelegationTokenRequest.class); request.setDelegationToken(dToken); rmService.cancelDelegationToken(request); } @Test (timeout = 30000) @SuppressWarnings ("rawtypes") public void testAppSubmit() throws Exception { YarnScheduler yarnScheduler = mockYarnScheduler(); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); RMStateStore stateStore = mock(RMStateStore.class); when(rmContext.getStateStore()).thenReturn(stateStore); RMAppManager appManager = new RMAppManager(rmContext, yarnScheduler, null, mock(ApplicationACLsManager.class), new Configuration()); when(rmContext.getDispatcher().getEventHandler()).thenReturn( new EventHandler<Event>() { public void handle(Event event) {} }); ApplicationId appId1 = getApplicationId(100); ApplicationACLsManager mockAclsManager = mock(ApplicationACLsManager.class); when( mockAclsManager.checkAccess(UserGroupInformation.getCurrentUser(), ApplicationAccessType.VIEW_APP, null, appId1)).thenReturn(true); QueueACLsManager mockQueueACLsManager = mock(QueueACLsManager.class); when(mockQueueACLsManager.checkAccess(any(UserGroupInformation.class), any(QueueACL.class), anyString())).thenReturn(true); ClientRMService rmService = new ClientRMService(rmContext, yarnScheduler, appManager, mockAclsManager, mockQueueACLsManager, null); // without name and queue SubmitApplicationRequest submitRequest1 = mockSubmitAppRequest( appId1, null, null); try { rmService.submitApplication(submitRequest1); } catch (YarnException e) { Assert.fail("Exception is not expected."); } RMApp app1 = rmContext.getRMApps().get(appId1); Assert.assertNotNull("app doesn't exist", app1); Assert.assertEquals("app name doesn't match", YarnConfiguration.DEFAULT_APPLICATION_NAME, app1.getName()); Assert.assertEquals("app queue doesn't match", YarnConfiguration.DEFAULT_QUEUE_NAME, app1.getQueue()); // with name and queue String name = MockApps.newAppName(); String queue = MockApps.newQueue(); ApplicationId appId2 = getApplicationId(101); SubmitApplicationRequest submitRequest2 = mockSubmitAppRequest( appId2, name, queue); submitRequest2.getApplicationSubmissionContext().setApplicationType( "matchType"); try { rmService.submitApplication(submitRequest2); } catch (YarnException e) { Assert.fail("Exception is not expected."); } RMApp app2 = rmContext.getRMApps().get(appId2); Assert.assertNotNull("app doesn't exist", app2); Assert.assertEquals("app name doesn't match", name, app2.getName()); Assert.assertEquals("app queue doesn't match", queue, app2.getQueue()); // duplicate appId try { rmService.submitApplication(submitRequest2); } catch (YarnException e) { Assert.fail("Exception is not expected."); } GetApplicationsRequest getAllAppsRequest = GetApplicationsRequest.newInstance(new HashSet<String>()); GetApplicationsResponse getAllApplicationsResponse = rmService.getApplications(getAllAppsRequest); Assert.assertEquals(5, getAllApplicationsResponse.getApplicationList().size()); Set<String> appTypes = new HashSet<String>(); appTypes.add("matchType"); getAllAppsRequest = GetApplicationsRequest.newInstance(appTypes); getAllApplicationsResponse = rmService.getApplications(getAllAppsRequest); Assert.assertEquals(1, getAllApplicationsResponse.getApplicationList().size()); Assert.assertEquals(appId2, getAllApplicationsResponse.getApplicationList() .get(0).getApplicationId()); } @Test public void testGetApplications() throws IOException, YarnException { /** * 1. Submit 3 applications alternately in two queues * 2. Test each of the filters */ // Basic setup YarnScheduler yarnScheduler = mockYarnScheduler(); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); RMStateStore stateStore = mock(RMStateStore.class); when(rmContext.getStateStore()).thenReturn(stateStore); RMAppManager appManager = new RMAppManager(rmContext, yarnScheduler, null, mock(ApplicationACLsManager.class), new Configuration()); when(rmContext.getDispatcher().getEventHandler()).thenReturn( new EventHandler<Event>() { public void handle(Event event) {} }); ApplicationACLsManager mockAclsManager = mock(ApplicationACLsManager.class); QueueACLsManager mockQueueACLsManager = mock(QueueACLsManager.class); when(mockQueueACLsManager.checkAccess(any(UserGroupInformation.class), any(QueueACL.class), anyString())).thenReturn(true); ClientRMService rmService = new ClientRMService(rmContext, yarnScheduler, appManager, mockAclsManager, mockQueueACLsManager, null); // Initialize appnames and queues String[] queues = {QUEUE_1, QUEUE_2}; String[] appNames = {MockApps.newAppName(), MockApps.newAppName(), MockApps.newAppName()}; ApplicationId[] appIds = {getApplicationId(101), getApplicationId(102), getApplicationId(103)}; List<String> tags = Arrays.asList("Tag1", "Tag2", "Tag3"); long[] submitTimeMillis = new long[3]; // Submit applications for (int i = 0; i < appIds.length; i++) { ApplicationId appId = appIds[i]; when(mockAclsManager.checkAccess(UserGroupInformation.getCurrentUser(), ApplicationAccessType.VIEW_APP, null, appId)).thenReturn(true); SubmitApplicationRequest submitRequest = mockSubmitAppRequest( appId, appNames[i], queues[i % queues.length], new HashSet<String>(tags.subList(0, i + 1))); rmService.submitApplication(submitRequest); submitTimeMillis[i] = System.currentTimeMillis(); } // Test different cases of ClientRMService#getApplications() GetApplicationsRequest request = GetApplicationsRequest.newInstance(); assertEquals("Incorrect total number of apps", 6, rmService.getApplications(request).getApplicationList().size()); // Check limit request.setLimit(1L); assertEquals("Failed to limit applications", 1, rmService.getApplications(request).getApplicationList().size()); // Check start range request = GetApplicationsRequest.newInstance(); request.setStartRange(submitTimeMillis[0], System.currentTimeMillis()); // 2 applications are submitted after first timeMills assertEquals("Incorrect number of matching start range", 2, rmService.getApplications(request).getApplicationList().size()); // 1 application is submitted after the second timeMills request.setStartRange(submitTimeMillis[1], System.currentTimeMillis()); assertEquals("Incorrect number of matching start range", 1, rmService.getApplications(request).getApplicationList().size()); // no application is submitted after the third timeMills request.setStartRange(submitTimeMillis[2], System.currentTimeMillis()); assertEquals("Incorrect number of matching start range", 0, rmService.getApplications(request).getApplicationList().size()); // Check queue request = GetApplicationsRequest.newInstance(); Set<String> queueSet = new HashSet<String>(); request.setQueues(queueSet); queueSet.add(queues[0]); assertEquals("Incorrect number of applications in queue", 2, rmService.getApplications(request).getApplicationList().size()); assertEquals("Incorrect number of applications in queue", 2, rmService.getApplications(request, false).getApplicationList().size()); queueSet.add(queues[1]); assertEquals("Incorrect number of applications in queue", 3, rmService.getApplications(request).getApplicationList().size()); // Check user request = GetApplicationsRequest.newInstance(); Set<String> userSet = new HashSet<String>(); request.setUsers(userSet); userSet.add("random-user-name"); assertEquals("Incorrect number of applications for user", 0, rmService.getApplications(request).getApplicationList().size()); userSet.add(UserGroupInformation.getCurrentUser().getShortUserName()); assertEquals("Incorrect number of applications for user", 3, rmService.getApplications(request).getApplicationList().size()); // Check tags request = GetApplicationsRequest.newInstance( ApplicationsRequestScope.ALL, null, null, null, null, null, null, null, null); Set<String> tagSet = new HashSet<String>(); request.setApplicationTags(tagSet); assertEquals("Incorrect number of matching tags", 6, rmService.getApplications(request).getApplicationList().size()); tagSet = Sets.newHashSet(tags.get(0)); request.setApplicationTags(tagSet); assertEquals("Incorrect number of matching tags", 3, rmService.getApplications(request).getApplicationList().size()); tagSet = Sets.newHashSet(tags.get(1)); request.setApplicationTags(tagSet); assertEquals("Incorrect number of matching tags", 2, rmService.getApplications(request).getApplicationList().size()); tagSet = Sets.newHashSet(tags.get(2)); request.setApplicationTags(tagSet); assertEquals("Incorrect number of matching tags", 1, rmService.getApplications(request).getApplicationList().size()); // Check scope request = GetApplicationsRequest.newInstance( ApplicationsRequestScope.VIEWABLE); assertEquals("Incorrect number of applications for the scope", 6, rmService.getApplications(request).getApplicationList().size()); request = GetApplicationsRequest.newInstance( ApplicationsRequestScope.OWN); assertEquals("Incorrect number of applications for the scope", 3, rmService.getApplications(request).getApplicationList().size()); } @Test(timeout=4000) public void testConcurrentAppSubmit() throws IOException, InterruptedException, BrokenBarrierException, YarnException { YarnScheduler yarnScheduler = mockYarnScheduler(); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); RMStateStore stateStore = mock(RMStateStore.class); when(rmContext.getStateStore()).thenReturn(stateStore); RMAppManager appManager = new RMAppManager(rmContext, yarnScheduler, null, mock(ApplicationACLsManager.class), new Configuration()); final ApplicationId appId1 = getApplicationId(100); final ApplicationId appId2 = getApplicationId(101); final SubmitApplicationRequest submitRequest1 = mockSubmitAppRequest( appId1, null, null); final SubmitApplicationRequest submitRequest2 = mockSubmitAppRequest( appId2, null, null); final CyclicBarrier startBarrier = new CyclicBarrier(2); final CyclicBarrier endBarrier = new CyclicBarrier(2); @SuppressWarnings("rawtypes") EventHandler eventHandler = new EventHandler() { @Override public void handle(Event rawEvent) { if (rawEvent instanceof RMAppEvent) { RMAppEvent event = (RMAppEvent) rawEvent; if (event.getApplicationId().equals(appId1)) { try { startBarrier.await(); endBarrier.await(); } catch (BrokenBarrierException e) { LOG.warn("Broken Barrier", e); } catch (InterruptedException e) { LOG.warn("Interrupted while awaiting barriers", e); } } } } }; when(rmContext.getDispatcher().getEventHandler()).thenReturn(eventHandler); final ClientRMService rmService = new ClientRMService(rmContext, yarnScheduler, appManager, null, null, null); // submit an app and wait for it to block while in app submission Thread t = new Thread() { @Override public void run() { try { rmService.submitApplication(submitRequest1); } catch (YarnException e) {} } }; t.start(); // submit another app, so go through while the first app is blocked startBarrier.await(); rmService.submitApplication(submitRequest2); endBarrier.await(); t.join(); } private SubmitApplicationRequest mockSubmitAppRequest(ApplicationId appId, String name, String queue) { return mockSubmitAppRequest(appId, name, queue, null); } private SubmitApplicationRequest mockSubmitAppRequest(ApplicationId appId, String name, String queue, Set<String> tags) { return mockSubmitAppRequest(appId, name, queue, tags, false); } @SuppressWarnings("deprecation") private SubmitApplicationRequest mockSubmitAppRequest(ApplicationId appId, String name, String queue, Set<String> tags, boolean unmanaged) { ContainerLaunchContext amContainerSpec = mock(ContainerLaunchContext.class); Resource resource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); ApplicationSubmissionContext submissionContext = recordFactory.newRecordInstance(ApplicationSubmissionContext.class); submissionContext.setAMContainerSpec(amContainerSpec); submissionContext.setApplicationName(name); submissionContext.setQueue(queue); submissionContext.setApplicationId(appId); submissionContext.setResource(resource); submissionContext.setApplicationType(appType); submissionContext.setApplicationTags(tags); submissionContext.setUnmanagedAM(unmanaged); SubmitApplicationRequest submitRequest = recordFactory.newRecordInstance(SubmitApplicationRequest.class); submitRequest.setApplicationSubmissionContext(submissionContext); return submitRequest; } private void mockRMContext(YarnScheduler yarnScheduler, RMContext rmContext) throws IOException { Dispatcher dispatcher = mock(Dispatcher.class); when(rmContext.getDispatcher()).thenReturn(dispatcher); EventHandler eventHandler = mock(EventHandler.class); when(dispatcher.getEventHandler()).thenReturn(eventHandler); QueueInfo queInfo = recordFactory.newRecordInstance(QueueInfo.class); queInfo.setQueueName("testqueue"); when(yarnScheduler.getQueueInfo(eq("testqueue"), anyBoolean(), anyBoolean())) .thenReturn(queInfo); when(yarnScheduler.getQueueInfo(eq("nonexistentqueue"), anyBoolean(), anyBoolean())) .thenThrow(new IOException("queue does not exist")); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); when(rmContext.getRMApplicationHistoryWriter()).thenReturn(writer); SystemMetricsPublisher publisher = mock(SystemMetricsPublisher.class); when(rmContext.getSystemMetricsPublisher()).thenReturn(publisher); when(rmContext.getYarnConfiguration()).thenReturn(new YarnConfiguration()); ConcurrentHashMap<ApplicationId, RMApp> apps = getRMApps(rmContext, yarnScheduler); when(rmContext.getRMApps()).thenReturn(apps); when(yarnScheduler.getAppsInQueue(eq("testqueue"))).thenReturn( getSchedulerApps(apps)); ResourceScheduler rs = mock(ResourceScheduler.class); when(rmContext.getScheduler()).thenReturn(rs); } private ConcurrentHashMap<ApplicationId, RMApp> getRMApps( RMContext rmContext, YarnScheduler yarnScheduler) { ConcurrentHashMap<ApplicationId, RMApp> apps = new ConcurrentHashMap<ApplicationId, RMApp>(); ApplicationId applicationId1 = getApplicationId(1); ApplicationId applicationId2 = getApplicationId(2); ApplicationId applicationId3 = getApplicationId(3); YarnConfiguration config = new YarnConfiguration(); apps.put(applicationId1, getRMApp(rmContext, yarnScheduler, applicationId1, config, "testqueue", 10, 3)); apps.put(applicationId2, getRMApp(rmContext, yarnScheduler, applicationId2, config, "a", 20, 2)); apps.put(applicationId3, getRMApp(rmContext, yarnScheduler, applicationId3, config, "testqueue", 40, 5)); return apps; } private List<ApplicationAttemptId> getSchedulerApps( Map<ApplicationId, RMApp> apps) { List<ApplicationAttemptId> schedApps = new ArrayList<ApplicationAttemptId>(); // Return app IDs for the apps in testqueue (as defined in getRMApps) schedApps.add(ApplicationAttemptId.newInstance(getApplicationId(1), 0)); schedApps.add(ApplicationAttemptId.newInstance(getApplicationId(3), 0)); return schedApps; } private static ApplicationId getApplicationId(int id) { return ApplicationId.newInstance(123456, id); } private static ApplicationAttemptId getApplicationAttemptId(int id) { return ApplicationAttemptId.newInstance(getApplicationId(id), 1); } private RMAppImpl getRMApp(RMContext rmContext, YarnScheduler yarnScheduler, ApplicationId applicationId3, YarnConfiguration config, String queueName, final long memorySeconds, final long vcoreSeconds) { ApplicationSubmissionContext asContext = mock(ApplicationSubmissionContext.class); when(asContext.getMaxAppAttempts()).thenReturn(1); RMAppImpl app = spy(new RMAppImpl(applicationId3, rmContext, config, null, null, queueName, asContext, yarnScheduler, null, System.currentTimeMillis(), "YARN", null, BuilderUtils.newResourceRequest( RMAppAttemptImpl.AM_CONTAINER_PRIORITY, ResourceRequest.ANY, Resource.newInstance(1024, 1), 1)){ @Override public ApplicationReport createAndGetApplicationReport( String clientUserName, boolean allowAccess) { ApplicationReport report = super.createAndGetApplicationReport( clientUserName, allowAccess); ApplicationResourceUsageReport usageReport = report.getApplicationResourceUsageReport(); usageReport.setMemorySeconds(memorySeconds); usageReport.setVcoreSeconds(vcoreSeconds); report.setApplicationResourceUsageReport(usageReport); return report; } }); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(123456, 1), 1); RMAppAttemptImpl rmAppAttemptImpl = spy(new RMAppAttemptImpl(attemptId, rmContext, yarnScheduler, null, asContext, config, false, null)); Container container = Container.newInstance( ContainerId.newContainerId(attemptId, 1), null, "", null, null, null); RMContainerImpl containerimpl = spy(new RMContainerImpl(container, attemptId, null, "", rmContext)); Map<ApplicationAttemptId, RMAppAttempt> attempts = new HashMap<ApplicationAttemptId, RMAppAttempt>(); attempts.put(attemptId, rmAppAttemptImpl); when(app.getCurrentAppAttempt()).thenReturn(rmAppAttemptImpl); when(app.getAppAttempts()).thenReturn(attempts); when(rmAppAttemptImpl.getMasterContainer()).thenReturn(container); ResourceScheduler rs = mock(ResourceScheduler.class); when(rmContext.getScheduler()).thenReturn(rs); when(rmContext.getScheduler().getRMContainer(any(ContainerId.class))) .thenReturn(containerimpl); SchedulerAppReport sAppReport = mock(SchedulerAppReport.class); when( rmContext.getScheduler().getSchedulerAppInfo( any(ApplicationAttemptId.class))).thenReturn(sAppReport); List<RMContainer> rmContainers = new ArrayList<RMContainer>(); rmContainers.add(containerimpl); when( rmContext.getScheduler().getSchedulerAppInfo(attemptId) .getLiveContainers()).thenReturn(rmContainers); ContainerStatus cs = mock(ContainerStatus.class); when(containerimpl.getFinishedStatus()).thenReturn(cs); when(containerimpl.getDiagnosticsInfo()).thenReturn("N/A"); when(containerimpl.getContainerExitStatus()).thenReturn(0); when(containerimpl.getContainerState()).thenReturn(ContainerState.COMPLETE); return app; } private static YarnScheduler mockYarnScheduler() { YarnScheduler yarnScheduler = mock(YarnScheduler.class); when(yarnScheduler.getMinimumResourceCapability()).thenReturn( Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB)); when(yarnScheduler.getMaximumResourceCapability()).thenReturn( Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB)); when(yarnScheduler.getAppsInQueue(QUEUE_1)).thenReturn( Arrays.asList(getApplicationAttemptId(101), getApplicationAttemptId(102))); when(yarnScheduler.getAppsInQueue(QUEUE_2)).thenReturn( Arrays.asList(getApplicationAttemptId(103))); ApplicationAttemptId attemptId = getApplicationAttemptId(1); when(yarnScheduler.getAppResourceUsageReport(attemptId)).thenReturn(null); ResourceCalculator rs = mock(ResourceCalculator.class); when(yarnScheduler.getResourceCalculator()).thenReturn(rs); return yarnScheduler; } @Test public void testReservationAPIs() { // initialize CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); ReservationSystemTestUtil.setupQueueConfiguration(conf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); conf.setBoolean(YarnConfiguration.RM_RESERVATION_SYSTEM_ENABLE, true); MockRM rm = new MockRM(conf); rm.start(); MockNM nm; try { nm = rm.registerNode("127.0.0.1:1", 102400, 100); // allow plan follower to synchronize Thread.sleep(1050); } catch (Exception e) { Assert.fail(e.getMessage()); } // Create a client. ClientRMService clientService = rm.getClientRMService(); // create a reservation Clock clock = new UTCClock(); long arrival = clock.getTime(); long duration = 60000; long deadline = (long) (arrival + 1.05 * duration); ReservationSubmissionRequest sRequest = createSimpleReservationRequest(4, arrival, deadline, duration); ReservationSubmissionResponse sResponse = null; try { sResponse = clientService.submitReservation(sRequest); } catch (Exception e) { Assert.fail(e.getMessage()); } Assert.assertNotNull(sResponse); ReservationId reservationID = sResponse.getReservationId(); Assert.assertNotNull(reservationID); LOG.info("Submit reservation response: " + reservationID); // Update the reservation ReservationDefinition rDef = sRequest.getReservationDefinition(); ReservationRequest rr = rDef.getReservationRequests().getReservationResources().get(0); rr.setNumContainers(5); arrival = clock.getTime(); duration = 30000; deadline = (long) (arrival + 1.05 * duration); rr.setDuration(duration); rDef.setArrival(arrival); rDef.setDeadline(deadline); ReservationUpdateRequest uRequest = ReservationUpdateRequest.newInstance(rDef, reservationID); ReservationUpdateResponse uResponse = null; try { uResponse = clientService.updateReservation(uRequest); } catch (Exception e) { Assert.fail(e.getMessage()); } Assert.assertNotNull(sResponse); LOG.info("Update reservation response: " + uResponse); // Delete the reservation ReservationDeleteRequest dRequest = ReservationDeleteRequest.newInstance(reservationID); ReservationDeleteResponse dResponse = null; try { dResponse = clientService.deleteReservation(dRequest); } catch (Exception e) { Assert.fail(e.getMessage()); } Assert.assertNotNull(sResponse); LOG.info("Delete reservation response: " + dResponse); // clean-up rm.stop(); nm = null; rm = null; } private ReservationSubmissionRequest createSimpleReservationRequest( int numContainers, long arrival, long deadline, long duration) { // create a request with a single atomic ask ReservationRequest r = ReservationRequest.newInstance(Resource.newInstance(1024, 1), numContainers, 1, duration); ReservationRequests reqs = ReservationRequests.newInstance(Collections.singletonList(r), ReservationRequestInterpreter.R_ALL); ReservationDefinition rDef = ReservationDefinition.newInstance(arrival, deadline, reqs, "testClientRMService#reservation"); ReservationSubmissionRequest request = ReservationSubmissionRequest.newInstance(rDef, ReservationSystemTestUtil.reservationQ); return request; } @Test public void testGetNodeLabels() throws Exception { MockRM rm = new MockRM() { protected ClientRMService createClientRMService() { return new ClientRMService(this.rmContext, scheduler, this.rmAppManager, this.applicationACLsManager, this.queueACLsManager, this.getRMContext() .getRMDelegationTokenSecretManager()); }; }; rm.start(); NodeLabel labelX = NodeLabel.newInstance("x", false); NodeLabel labelY = NodeLabel.newInstance("y"); RMNodeLabelsManager labelsMgr = rm.getRMContext().getNodeLabelManager(); labelsMgr.addToCluserNodeLabels(ImmutableSet.of(labelX, labelY)); NodeId node1 = NodeId.newInstance("host1", 1234); NodeId node2 = NodeId.newInstance("host2", 1234); Map<NodeId, Set<String>> map = new HashMap<NodeId, Set<String>>(); map.put(node1, ImmutableSet.of("x")); map.put(node2, ImmutableSet.of("y")); labelsMgr.replaceLabelsOnNode(map); // Create a client. Configuration conf = new Configuration(); YarnRPC rpc = YarnRPC.create(conf); InetSocketAddress rmAddress = rm.getClientRMService().getBindAddress(); LOG.info("Connecting to ResourceManager at " + rmAddress); ApplicationClientProtocol client = (ApplicationClientProtocol) rpc .getProxy(ApplicationClientProtocol.class, rmAddress, conf); // Get node labels collection GetClusterNodeLabelsResponse response = client .getClusterNodeLabels(GetClusterNodeLabelsRequest.newInstance()); Assert.assertTrue(response.getNodeLabels().containsAll( Arrays.asList(labelX, labelY))); // Get node labels mapping GetNodesToLabelsResponse response1 = client .getNodeToLabels(GetNodesToLabelsRequest.newInstance()); Map<NodeId, Set<NodeLabel>> nodeToLabels = response1.getNodeToLabels(); Assert.assertTrue(nodeToLabels.keySet().containsAll( Arrays.asList(node1, node2))); Assert.assertTrue(nodeToLabels.get(node1) .containsAll(Arrays.asList(labelX))); Assert.assertTrue(nodeToLabels.get(node2) .containsAll(Arrays.asList(labelY))); // Verify whether labelX's exclusivity is false for (NodeLabel x : nodeToLabels.get(node1)) { Assert.assertFalse(x.isExclusive()); } // Verify whether labelY's exclusivity is true for (NodeLabel y : nodeToLabels.get(node2)) { Assert.assertTrue(y.isExclusive()); } // Below label "x" is not present in the response as exclusivity is true Assert.assertFalse(nodeToLabels.get(node1).containsAll( Arrays.asList(NodeLabel.newInstance("x")))); rpc.stopProxy(client, conf); rm.close(); } @Test public void testGetLabelsToNodes() throws Exception { MockRM rm = new MockRM() { protected ClientRMService createClientRMService() { return new ClientRMService(this.rmContext, scheduler, this.rmAppManager, this.applicationACLsManager, this.queueACLsManager, this.getRMContext() .getRMDelegationTokenSecretManager()); }; }; rm.start(); NodeLabel labelX = NodeLabel.newInstance("x", false); NodeLabel labelY = NodeLabel.newInstance("y", false); NodeLabel labelZ = NodeLabel.newInstance("z", false); RMNodeLabelsManager labelsMgr = rm.getRMContext().getNodeLabelManager(); labelsMgr.addToCluserNodeLabels(ImmutableSet.of(labelX, labelY, labelZ)); NodeId node1A = NodeId.newInstance("host1", 1234); NodeId node1B = NodeId.newInstance("host1", 5678); NodeId node2A = NodeId.newInstance("host2", 1234); NodeId node3A = NodeId.newInstance("host3", 1234); NodeId node3B = NodeId.newInstance("host3", 5678); Map<NodeId, Set<String>> map = new HashMap<NodeId, Set<String>>(); map.put(node1A, ImmutableSet.of("x")); map.put(node1B, ImmutableSet.of("z")); map.put(node2A, ImmutableSet.of("y")); map.put(node3A, ImmutableSet.of("y")); map.put(node3B, ImmutableSet.of("z")); labelsMgr.replaceLabelsOnNode(map); // Create a client. Configuration conf = new Configuration(); YarnRPC rpc = YarnRPC.create(conf); InetSocketAddress rmAddress = rm.getClientRMService().getBindAddress(); LOG.info("Connecting to ResourceManager at " + rmAddress); ApplicationClientProtocol client = (ApplicationClientProtocol) rpc .getProxy(ApplicationClientProtocol.class, rmAddress, conf); // Get node labels collection GetClusterNodeLabelsResponse response = client .getClusterNodeLabels(GetClusterNodeLabelsRequest.newInstance()); Assert.assertTrue(response.getNodeLabels().containsAll( Arrays.asList(labelX, labelY, labelZ))); // Get labels to nodes mapping GetLabelsToNodesResponse response1 = client .getLabelsToNodes(GetLabelsToNodesRequest.newInstance()); Map<NodeLabel, Set<NodeId>> labelsToNodes = response1.getLabelsToNodes(); // Verify whether all NodeLabel's exclusivity are false for (Map.Entry<NodeLabel, Set<NodeId>> nltn : labelsToNodes.entrySet()) { Assert.assertFalse(nltn.getKey().isExclusive()); } Assert.assertTrue(labelsToNodes.keySet().containsAll( Arrays.asList(labelX, labelY, labelZ))); Assert.assertTrue(labelsToNodes.get(labelX).containsAll( Arrays.asList(node1A))); Assert.assertTrue(labelsToNodes.get(labelY).containsAll( Arrays.asList(node2A, node3A))); Assert.assertTrue(labelsToNodes.get(labelZ).containsAll( Arrays.asList(node1B, node3B))); // Get labels to nodes mapping for specific labels Set<String> setlabels = new HashSet<String>(Arrays.asList(new String[]{"x", "z"})); GetLabelsToNodesResponse response2 = client .getLabelsToNodes(GetLabelsToNodesRequest.newInstance(setlabels)); labelsToNodes = response2.getLabelsToNodes(); // Verify whether all NodeLabel's exclusivity are false for (Map.Entry<NodeLabel, Set<NodeId>> nltn : labelsToNodes.entrySet()) { Assert.assertFalse(nltn.getKey().isExclusive()); } Assert.assertTrue(labelsToNodes.keySet().containsAll( Arrays.asList(labelX, labelZ))); Assert.assertTrue(labelsToNodes.get(labelX).containsAll( Arrays.asList(node1A))); Assert.assertTrue(labelsToNodes.get(labelZ).containsAll( Arrays.asList(node1B, node3B))); Assert.assertEquals(labelsToNodes.get(labelY), null); rpc.stopProxy(client, conf); rm.close(); } }
67,030
42.32967
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMHA.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.InetSocketAddress; import javax.ws.rs.core.MediaType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.HAServiceProtocol; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo; import org.apache.hadoop.ha.HealthCheckFailedException; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.conf.HAUtil; 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.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.recovery.StoreFencedException; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.DefaultClientConfig; public class TestRMHA { private Log LOG = LogFactory.getLog(TestRMHA.class); private Configuration configuration; private MockRM rm = null; private RMApp app = null; private RMAppAttempt attempt = null; private static final String STATE_ERR = "ResourceManager is in wrong HA state"; private static final String RM1_ADDRESS = "1.1.1.1:1"; private static final String RM1_NODE_ID = "rm1"; private static final String RM2_ADDRESS = "0.0.0.0:0"; private static final String RM2_NODE_ID = "rm2"; private static final String RM3_ADDRESS = "2.2.2.2:2"; private static final String RM3_NODE_ID = "rm3"; @Before public void setUp() throws Exception { configuration = new Configuration(); UserGroupInformation.setConfiguration(configuration); configuration.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); configuration.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); for (String confKey : YarnConfiguration .getServiceAddressConfKeys(configuration)) { configuration.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS); configuration.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); configuration.set(HAUtil.addSuffix(confKey, RM3_NODE_ID), RM3_ADDRESS); } // Enable webapp to test web-services also configuration.setBoolean(MockRM.ENABLE_WEBAPP, true); configuration.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); ClusterMetrics.destroy(); QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.shutdown(); } private void checkMonitorHealth() throws IOException { try { rm.adminService.monitorHealth(); } catch (HealthCheckFailedException e) { fail("The RM is in bad health: it is Active, but the active services " + "are not running"); } } private void checkStandbyRMFunctionality() throws IOException { assertEquals(STATE_ERR, HAServiceState.STANDBY, rm.adminService.getServiceStatus().getState()); assertFalse("Active RM services are started", rm.areActiveServicesRunning()); assertTrue("RM is not ready to become active", rm.adminService.getServiceStatus().isReadyToBecomeActive()); } private void checkActiveRMFunctionality() throws Exception { assertEquals(STATE_ERR, HAServiceState.ACTIVE, rm.adminService.getServiceStatus().getState()); assertTrue("Active RM services aren't started", rm.areActiveServicesRunning()); assertTrue("RM is not ready to become active", rm.adminService.getServiceStatus().isReadyToBecomeActive()); try { rm.getNewAppId(); rm.registerNode("127.0.0.1:1", 2048); app = rm.submitApp(1024); attempt = app.getCurrentAppAttempt(); rm.waitForState(attempt.getAppAttemptId(), RMAppAttemptState.SCHEDULED); } catch (Exception e) { fail("Unable to perform Active RM functions"); LOG.error("ActiveRM check failed", e); } checkActiveRMWebServices(); } // Do some sanity testing of the web-services after fail-over. private void checkActiveRMWebServices() throws JSONException { // Validate web-service Client webServiceClient = Client.create(new DefaultClientConfig()); InetSocketAddress rmWebappAddr = NetUtils.getConnectAddress(rm.getWebapp().getListenerAddress()); String webappURL = "http://" + rmWebappAddr.getHostName() + ":" + rmWebappAddr.getPort(); WebResource webResource = webServiceClient.resource(webappURL); String path = app.getApplicationId().toString(); ClientResponse response = webResource.path("ws").path("v1").path("cluster").path("apps") .path(path).accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); JSONObject json = response.getEntity(JSONObject.class); assertEquals("incorrect number of elements", 1, json.length()); JSONObject appJson = json.getJSONObject("app"); assertEquals("ACCEPTED", appJson.getString("state")); // Other stuff is verified in the regular web-services related tests } /** * Test to verify the following RM HA transitions to the following states. * 1. Standby: Should be a no-op * 2. Active: Active services should start * 3. Active: Should be a no-op. * While active, submit a couple of jobs * 4. Standby: Active services should stop * 5. Active: Active services should start * 6. Stop the RM: All services should stop and RM should not be ready to * become Active */ @Test (timeout = 30000) public void testFailoverAndTransitions() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(STATE_ERR, HAServiceState.INITIALIZING, rm.adminService.getServiceStatus().getState()); assertFalse("RM is ready to become active before being started", rm.adminService.getServiceStatus().isReadyToBecomeActive()); checkMonitorHealth(); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 1. Transition to Standby - must be a no-op rm.adminService.transitionToStandby(requestInfo); checkMonitorHealth(); checkStandbyRMFunctionality(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 2. Transition to active rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 1, 1, 1, 2048, 1); // 3. Transition to active - no-op rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 2, 2, 2, 2048, 2); // 4. Transition to standby rm.adminService.transitionToStandby(requestInfo); checkMonitorHealth(); checkStandbyRMFunctionality(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 5. Transition to active to check Active->Standby->Active works rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 1, 1, 1, 2048, 1); // 6. Stop the RM. All services should stop and RM should not be ready to // become active rm.stop(); assertEquals(STATE_ERR, HAServiceState.STOPPING, rm.adminService.getServiceStatus().getState()); assertFalse("RM is ready to become active even after it is stopped", rm.adminService.getServiceStatus().isReadyToBecomeActive()); assertFalse("Active RM services are started", rm.areActiveServicesRunning()); checkMonitorHealth(); } @Test public void testTransitionsWhenAutomaticFailoverEnabled() throws Exception { final String ERR_UNFORCED_REQUEST = "User request succeeded even when " + "automatic failover is enabled"; Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); // Transition to standby try { rm.adminService.transitionToStandby(requestInfo); fail(ERR_UNFORCED_REQUEST); } catch (AccessControlException e) { // expected } checkMonitorHealth(); checkStandbyRMFunctionality(); // Transition to active try { rm.adminService.transitionToActive(requestInfo); fail(ERR_UNFORCED_REQUEST); } catch (AccessControlException e) { // expected } checkMonitorHealth(); checkStandbyRMFunctionality(); final String ERR_FORCED_REQUEST = "Forced request by user should work " + "even if automatic failover is enabled"; requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER_FORCED); // Transition to standby try { rm.adminService.transitionToStandby(requestInfo); } catch (AccessControlException e) { fail(ERR_FORCED_REQUEST); } checkMonitorHealth(); checkStandbyRMFunctionality(); // Transition to active try { rm.adminService.transitionToActive(requestInfo); } catch (AccessControlException e) { fail(ERR_FORCED_REQUEST); } checkMonitorHealth(); checkActiveRMFunctionality(); } @Test public void testRMDispatcherForHA() throws IOException { String errorMessageForEventHandler = "Expect to get the same number of handlers"; String errorMessageForService = "Expect to get the same number of services"; configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf) { @Override protected Dispatcher createDispatcher() { return new MyCountingDispatcher(); } }; rm.init(conf); int expectedEventHandlerCount = ((MyCountingDispatcher) rm.getRMContext().getDispatcher()) .getEventHandlerCount(); int expectedServiceCount = rm.getServices().size(); assertTrue(expectedEventHandlerCount != 0); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(STATE_ERR, HAServiceState.INITIALIZING, rm.adminService.getServiceStatus().getState()); assertFalse("RM is ready to become active before being started", rm.adminService.getServiceStatus().isReadyToBecomeActive()); rm.start(); //call transitions to standby and active a couple of times rm.adminService.transitionToStandby(requestInfo); rm.adminService.transitionToActive(requestInfo); rm.adminService.transitionToStandby(requestInfo); rm.adminService.transitionToActive(requestInfo); rm.adminService.transitionToStandby(requestInfo); MyCountingDispatcher dispatcher = (MyCountingDispatcher) rm.getRMContext().getDispatcher(); assertTrue(!dispatcher.isStopped()); rm.adminService.transitionToActive(requestInfo); assertEquals(errorMessageForEventHandler, expectedEventHandlerCount, ((MyCountingDispatcher) rm.getRMContext().getDispatcher()) .getEventHandlerCount()); assertEquals(errorMessageForService, expectedServiceCount, rm.getServices().size()); // Keep the dispatcher reference before transitioning to standby dispatcher = (MyCountingDispatcher) rm.getRMContext().getDispatcher(); rm.adminService.transitionToStandby(requestInfo); assertEquals(errorMessageForEventHandler, expectedEventHandlerCount, ((MyCountingDispatcher) rm.getRMContext().getDispatcher()) .getEventHandlerCount()); assertEquals(errorMessageForService, expectedServiceCount, rm.getServices().size()); assertTrue(dispatcher.isStopped()); rm.stop(); } @Test public void testHAIDLookup() { //test implicitly lookup HA-ID Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); assertEquals(conf.get(YarnConfiguration.RM_HA_ID), RM2_NODE_ID); //test explicitly lookup HA-ID configuration.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); assertEquals(conf.get(YarnConfiguration.RM_HA_ID), RM1_NODE_ID); //test if RM_HA_ID can not be found configuration.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID+ "," + RM3_NODE_ID); configuration.unset(YarnConfiguration.RM_HA_ID); conf = new YarnConfiguration(configuration); try { rm = new MockRM(conf); rm.init(conf); fail("Should get an exception here."); } catch (Exception ex) { Assert.assertTrue(ex.getMessage().contains( "Invalid configuration! Can not find valid RM_HA_ID.")); } } @Test public void testHAWithRMHostName() throws Exception { innerTestHAWithRMHostName(false); configuration.clear(); setUp(); innerTestHAWithRMHostName(true); } @Test(timeout = 30000) public void testFailoverWhenTransitionToActiveThrowException() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); MemoryRMStateStore memStore = new MemoryRMStateStore() { int count = 0; @Override public synchronized void startInternal() throws Exception { // first time throw exception if (count++ == 0) { throw new Exception("Session Expired"); } } }; // start RM memStore.init(conf); rm = new MockRM(conf, memStore); rm.init(conf); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(STATE_ERR, HAServiceState.INITIALIZING, rm.adminService .getServiceStatus().getState()); assertFalse("RM is ready to become active before being started", rm.adminService.getServiceStatus().isReadyToBecomeActive()); checkMonitorHealth(); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Try Transition to active, throw exception try { rm.adminService.transitionToActive(requestInfo); Assert.fail("Transitioned to Active should throw exception."); } catch (Exception e) { assertTrue("Error when transitioning to Active mode".contains(e .getMessage())); } // 3. Transition to active, success rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); } @Test(timeout = 90000) public void testTransitionedToStandbyShouldNotHang() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); MemoryRMStateStore memStore = new MemoryRMStateStore() { @Override public synchronized void updateApplicationState( ApplicationStateData appState) { notifyStoreOperationFailed(new StoreFencedException()); } }; memStore.init(conf); rm = new MockRM(conf, memStore) { @Override void stopActiveServices() throws Exception { Thread.sleep(10000); super.stopActiveServices(); } }; rm.init(conf); final StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(STATE_ERR, HAServiceState.INITIALIZING, rm.adminService .getServiceStatus().getState()); assertFalse("RM is ready to become active before being started", rm.adminService.getServiceStatus().isReadyToBecomeActive()); checkMonitorHealth(); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Transition to Active. rm.adminService.transitionToActive(requestInfo); // 3. Try Transition to standby Thread t = new Thread(new Runnable() { @Override public void run() { try { rm.transitionToStandby(true); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); rm.getRMContext().getStateStore().updateApplicationState(null); t.join(); // wait for thread to finish rm.adminService.transitionToStandby(requestInfo); checkStandbyRMFunctionality(); rm.stop(); } @Test public void testFailoverClearsRMContext() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); configuration.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); Configuration conf = new YarnConfiguration(configuration); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); // 1. start RM rm = new MockRM(conf, memStore); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Transition to active rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 1, 1, 1, 2048, 1); assertEquals(1, rm.getRMContext().getRMNodes().size()); assertEquals(1, rm.getRMContext().getRMApps().size()); // 3. Create new RM rm = new MockRM(conf, memStore) { @Override protected ResourceTrackerService createResourceTrackerService() { return new ResourceTrackerService(this.rmContext, this.nodesListManager, this.nmLivelinessMonitor, this.rmContext.getContainerTokenSecretManager(), this.rmContext.getNMTokenSecretManager()) { @Override protected void serviceStart() throws Exception { throw new Exception("ResourceTracker service failed"); } }; } }; rm.init(conf); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); // 4. Try Transition to active, throw exception try { rm.adminService.transitionToActive(requestInfo); Assert.fail("Transitioned to Active should throw exception."); } catch (Exception e) { assertTrue("Error when transitioning to Active mode".contains(e .getMessage())); } // 5. Clears the metrics verifyClusterMetrics(0, 0, 0, 0, 0, 0); assertEquals(0, rm.getRMContext().getRMNodes().size()); assertEquals(0, rm.getRMContext().getRMApps().size()); } public void innerTestHAWithRMHostName(boolean includeBindHost) { //this is run two times, with and without a bind host configured if (includeBindHost) { configuration.set(YarnConfiguration.RM_BIND_HOST, "9.9.9.9"); } //test if both RM_HOSTBANE_{rm_id} and RM_RPCADDRESS_{rm_id} are set //We should only read rpc addresses from RM_RPCADDRESS_{rm_id} configuration configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM1_NODE_ID), "1.1.1.1"); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM2_NODE_ID), "0.0.0.0"); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM3_NODE_ID), "2.2.2.2"); try { Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(conf)) { assertEquals("RPC address not set for " + confKey, RM1_ADDRESS, conf.get(HAUtil.addSuffix(confKey, RM1_NODE_ID))); assertEquals("RPC address not set for " + confKey, RM2_ADDRESS, conf.get(HAUtil.addSuffix(confKey, RM2_NODE_ID))); assertEquals("RPC address not set for " + confKey, RM3_ADDRESS, conf.get(HAUtil.addSuffix(confKey, RM3_NODE_ID))); if (includeBindHost) { assertEquals("Web address misconfigured WITH bind-host", rm.webAppAddress.substring(0, 7), "9.9.9.9"); } else { //YarnConfiguration tries to figure out which rm host it's on by binding to it, //which doesn't happen for any of these fake addresses, so we end up with 0.0.0.0 assertEquals("Web address misconfigured WITHOUT bind-host", rm.webAppAddress.substring(0, 7), "0.0.0.0"); } } } catch (YarnRuntimeException e) { fail("Should not throw any exceptions."); } //test if only RM_HOSTBANE_{rm_id} is set configuration.clear(); configuration.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); configuration.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM1_NODE_ID), "1.1.1.1"); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM2_NODE_ID), "0.0.0.0"); try { Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); assertEquals("RPC address not set for " + YarnConfiguration.RM_ADDRESS, "1.1.1.1:8032", conf.get(HAUtil.addSuffix(YarnConfiguration.RM_ADDRESS, RM1_NODE_ID))); assertEquals("RPC address not set for " + YarnConfiguration.RM_ADDRESS, "0.0.0.0:8032", conf.get(HAUtil.addSuffix(YarnConfiguration.RM_ADDRESS, RM2_NODE_ID))); } catch (YarnRuntimeException e) { fail("Should not throw any exceptions."); } } private void verifyClusterMetrics(int activeNodes, int appsSubmitted, int appsPending, int containersPending, int availableMB, int activeApplications) throws Exception { int timeoutSecs = 0; QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); ClusterMetrics clusterMetrics = ClusterMetrics.getMetrics(); boolean isAllMetricAssertionDone = false; String message = null; while (timeoutSecs++ < 5) { try { // verify queue metrics assertMetric("appsSubmitted", appsSubmitted, metrics.getAppsSubmitted()); assertMetric("appsPending", appsPending, metrics.getAppsPending()); assertMetric("containersPending", containersPending, metrics.getPendingContainers()); assertMetric("availableMB", availableMB, metrics.getAvailableMB()); assertMetric("activeApplications", activeApplications, metrics.getActiveApps()); // verify node metric assertMetric("activeNodes", activeNodes, clusterMetrics.getNumActiveNMs()); isAllMetricAssertionDone = true; break; } catch (AssertionError e) { message = e.getMessage(); System.out.println("Waiting for metrics assertion to complete"); Thread.sleep(1000); } } assertTrue(message, isAllMetricAssertionDone); } private void assertMetric(String metricName, int expected, int actual) { assertEquals("Incorrect value for metric " + metricName, expected, actual); } @SuppressWarnings("rawtypes") class MyCountingDispatcher extends AbstractService implements Dispatcher { private int eventHandlerCount; private volatile boolean stopped = false; public MyCountingDispatcher() { super("MyCountingDispatcher"); this.eventHandlerCount = 0; } @Override public EventHandler getEventHandler() { return null; } @Override public void register(Class<? extends Enum> eventType, EventHandler handler) { this.eventHandlerCount ++; } public int getEventHandlerCount() { return this.eventHandlerCount; } @Override protected void serviceStop() throws Exception { this.stopped = true; super.serviceStop(); } public boolean isStopped() { return this.stopped; } } }
26,333
35.728033
91
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMEmbeddedElector.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; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.ClientBaseWithFixes; import org.apache.hadoop.ha.ServiceFailedException; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; public class TestRMEmbeddedElector extends ClientBaseWithFixes { private static final Log LOG = LogFactory.getLog(TestRMEmbeddedElector.class.getName()); private static final String RM1_NODE_ID = "rm1"; private static final int RM1_PORT_BASE = 10000; private static final String RM2_NODE_ID = "rm2"; private static final int RM2_PORT_BASE = 20000; private Configuration conf; private AtomicBoolean callbackCalled; @Before public void setup() throws IOException { conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); conf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, true); conf.setBoolean(YarnConfiguration.AUTO_FAILOVER_EMBEDDED, true); conf.set(YarnConfiguration.RM_CLUSTER_ID, "yarn-test-cluster"); conf.set(YarnConfiguration.RM_ZK_ADDRESS, hostPort); conf.setInt(YarnConfiguration.RM_ZK_TIMEOUT_MS, 2000); conf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); conf.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); HATestUtil.setRpcAddressForRM(RM1_NODE_ID, RM1_PORT_BASE, conf); HATestUtil.setRpcAddressForRM(RM2_NODE_ID, RM2_PORT_BASE, conf); conf.setLong(YarnConfiguration.CLIENT_FAILOVER_SLEEPTIME_BASE_MS, 100L); callbackCalled = new AtomicBoolean(false); } /** * Test that tries to see if there is a deadlock between * (a) the thread stopping the RM * (b) thread processing the ZK event asking RM to transition to active * * The test times out if there is a deadlock. */ @Test (timeout = 10000) public void testDeadlockShutdownBecomeActive() throws InterruptedException { MockRM rm = new MockRMWithElector(conf, 1000); rm.start(); LOG.info("Waiting for callback"); while (!callbackCalled.get()); LOG.info("Stopping RM"); rm.stop(); LOG.info("Stopped RM"); } private class MockRMWithElector extends MockRM { private long delayMs = 0; MockRMWithElector(Configuration conf) { super(conf); } MockRMWithElector(Configuration conf, long delayMs) { this(conf); this.delayMs = delayMs; } @Override protected AdminService createAdminService() { return new AdminService(MockRMWithElector.this, getRMContext()) { @Override protected EmbeddedElectorService createEmbeddedElectorService() { return new EmbeddedElectorService(getRMContext()) { @Override public void becomeActive() throws ServiceFailedException { try { callbackCalled.set(true); TestRMEmbeddedElector.LOG.info("Callback called. Sleeping now"); Thread.sleep(delayMs); TestRMEmbeddedElector.LOG.info("Sleep done"); } catch (InterruptedException e) { e.printStackTrace(); } super.becomeActive(); } }; } }; } } }
4,244
34.672269
80
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestSubmitApplicationWithRMHA.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; import org.junit.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.junit.Test; public class TestSubmitApplicationWithRMHA extends RMHATestBase{ public static final Log LOG = LogFactory .getLog(TestSubmitApplicationWithRMHA.class); @Test public void testHandleRMHABeforeSubmitApplicationCallWithSavedApplicationState() throws Exception { // start two RMs, and transit rm1 to active, rm2 to standby startRMs(); // get a new applicationId from rm1 ApplicationId appId = rm1.getNewAppId().getApplicationId(); // Do the failover explicitFailover(); // submit the application with previous assigned applicationId // to current active rm: rm2 RMApp app1 = rm2.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false, true, appId); // verify application submission verifySubmitApp(rm2, app1, appId); } private void verifySubmitApp(MockRM rm, RMApp app, ApplicationId expectedAppId) throws Exception { int maxWaittingTimes = 20; int count = 0; while (true) { YarnApplicationState state = rm.getApplicationReport(app.getApplicationId()) .getYarnApplicationState(); if (!state.equals(YarnApplicationState.NEW) && !state.equals(YarnApplicationState.NEW_SAVING)) { break; } if (count > maxWaittingTimes) { break; } Thread.sleep(200); count++; } // Verify submittion is successful YarnApplicationState state = rm.getApplicationReport(app.getApplicationId()) .getYarnApplicationState(); Assert.assertTrue(state == YarnApplicationState.ACCEPTED || state == YarnApplicationState.SUBMITTED); Assert.assertEquals(expectedAppId, app.getApplicationId()); } // There are two scenarios when RM failover happens // after SubmitApplication Call: // 1) RMStateStore already saved the ApplicationState when failover happens // 2) RMStateStore did not save the ApplicationState when failover happens @Test public void testHandleRMHAafterSubmitApplicationCallWithSavedApplicationState() throws Exception { // Test scenario 1 when RM failover happens // after SubmitApplication Call: // RMStateStore already saved the ApplicationState when failover happens startRMs(); // Submit Application // After submission, the applicationState will be saved in RMStateStore. RMApp app0 = rm1.submitApp(200); // Do the failover explicitFailover(); // Since the applicationState has already been saved in RMStateStore // before failover happens, the current active rm can load the previous // applicationState. ApplicationReport appReport = rm2.getApplicationReport(app0.getApplicationId()); // verify previous submission is successful. Assert.assertTrue(appReport.getYarnApplicationState() == YarnApplicationState.ACCEPTED || appReport.getYarnApplicationState() == YarnApplicationState.SUBMITTED); } @Test public void testHandleRMHAafterSubmitApplicationCallWithoutSavedApplicationState() throws Exception { // Test scenario 2 when RM failover happens // after SubmitApplication Call: // RMStateStore did not save the ApplicationState when failover happens. // Using customized RMAppManager. startRMsWithCustomizedRMAppManager(); // Submit Application // After submission, the applicationState will // not be saved in RMStateStore RMApp app0 = rm1.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false); // Do the failover explicitFailover(); // Since the applicationState is not saved in RMStateStore // when failover happens. The current active RM can not load // previous applicationState. // Expect ApplicationNotFoundException by calling getApplicationReport(). try { rm2.getApplicationReport(app0.getApplicationId()); Assert.fail("Should get ApplicationNotFoundException here"); } catch (ApplicationNotFoundException ex) { // expected ApplicationNotFoundException } // Submit the application with previous ApplicationId to current active RM // This will mimic the similar behavior of YarnClient which will re-submit // Application with previous applicationId // when catches the ApplicationNotFoundException RMApp app1 = rm2.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false, true, app0.getApplicationId()); verifySubmitApp(rm2, app1, app0.getApplicationId()); } /** * Test multiple calls of getApplicationReport, to make sure * it is idempotent */ @Test public void testGetApplicationReportIdempotent() throws Exception{ // start two RMs, and transit rm1 to active, rm2 to standby startRMs(); // Submit Application // After submission, the applicationState will be saved in RMStateStore. RMApp app = rm1.submitApp(200); ApplicationReport appReport1 = rm1.getApplicationReport(app.getApplicationId()); Assert.assertTrue(appReport1.getYarnApplicationState() == YarnApplicationState.ACCEPTED || appReport1.getYarnApplicationState() == YarnApplicationState.SUBMITTED); // call getApplicationReport again ApplicationReport appReport2 = rm1.getApplicationReport(app.getApplicationId()); Assert.assertEquals(appReport1.getApplicationId(), appReport2.getApplicationId()); Assert.assertEquals(appReport1.getYarnApplicationState(), appReport2.getYarnApplicationState()); // Do the failover explicitFailover(); // call getApplicationReport ApplicationReport appReport3 = rm2.getApplicationReport(app.getApplicationId()); Assert.assertEquals(appReport1.getApplicationId(), appReport3.getApplicationId()); Assert.assertEquals(appReport1.getYarnApplicationState(), appReport3.getYarnApplicationState()); // call getApplicationReport again ApplicationReport appReport4 = rm2.getApplicationReport(app.getApplicationId()); Assert.assertEquals(appReport3.getApplicationId(), appReport4.getApplicationId()); Assert.assertEquals(appReport3.getYarnApplicationState(), appReport4.getYarnApplicationState()); } // There are two scenarios when RM failover happens // during SubmitApplication Call: // 1) RMStateStore already saved the ApplicationState when failover happens // 2) RMStateStore did not save the ApplicationState when failover happens @Test (timeout = 5000) public void testHandleRMHADuringSubmitApplicationCallWithSavedApplicationState() throws Exception { // Test scenario 1 when RM failover happens // druing SubmitApplication Call: // RMStateStore already saved the ApplicationState when failover happens startRMs(); // Submit Application // After submission, the applicationState will be saved in RMStateStore. RMApp app0 = rm1.submitApp(200); // Do the failover explicitFailover(); // Since the applicationState has already been saved in RMStateStore // before failover happens, the current active rm can load the previous // applicationState. // This RMApp should exist in the RMContext of current active RM Assert.assertTrue(rm2.getRMContext().getRMApps() .containsKey(app0.getApplicationId())); // When we re-submit the application with same applicationId, it will // check whether this application has been exist. If yes, just simply // return submitApplicationResponse. RMApp app1 = rm2.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false, true, app0.getApplicationId()); Assert.assertEquals(app1.getApplicationId(), app0.getApplicationId()); } @Test (timeout = 5000) public void testHandleRMHADuringSubmitApplicationCallWithoutSavedApplicationState() throws Exception { // Test scenario 2 when RM failover happens // during SubmitApplication Call: // RMStateStore did not save the ApplicationState when failover happens. // Using customized RMAppManager. startRMsWithCustomizedRMAppManager(); // Submit Application // After submission, the applicationState will // not be saved in RMStateStore RMApp app0 = rm1.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false); // Do the failover explicitFailover(); // When failover happens, the RMStateStore has not saved applicationState. // The applicationState of this RMApp is lost. // We should not find the RMApp in the RMContext of current active rm. Assert.assertFalse(rm2.getRMContext().getRMApps() .containsKey(app0.getApplicationId())); // Submit the application with previous ApplicationId to current active RM // This will mimic the similar behavior of ApplicationClientProtocol# // submitApplication() when failover happens during the submission process // because the submitApplication api is marked as idempotent RMApp app1 = rm2.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false, true, app0.getApplicationId()); verifySubmitApp(rm2, app1, app0.getApplicationId()); Assert.assertTrue(rm2.getRMContext().getRMApps() .containsKey(app0.getApplicationId())); } }
12,021
38.032468
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceManager.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; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.http.lib.StaticUserWebFilter; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.security.AuthenticationFilterInitializer; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; 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.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.security.http.RMAuthenticationFilterInitializer; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestResourceManager { private static final Log LOG = LogFactory.getLog(TestResourceManager.class); private ResourceManager resourceManager = null; @Before public void setUp() throws Exception { Configuration conf = new YarnConfiguration(); UserGroupInformation.setConfiguration(conf); resourceManager = new ResourceManager(); resourceManager.init(conf); resourceManager.getRMContext().getContainerTokenSecretManager().rollMasterKey(); resourceManager.getRMContext().getNMTokenSecretManager().rollMasterKey(); } @After public void tearDown() throws Exception { } private org.apache.hadoop.yarn.server.resourcemanager.NodeManager registerNode(String hostName, int containerManagerPort, int httpPort, String rackName, Resource capability) throws IOException, YarnException { org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm = new org.apache.hadoop.yarn.server.resourcemanager.NodeManager( hostName, containerManagerPort, httpPort, rackName, capability, resourceManager); NodeAddedSchedulerEvent nodeAddEvent1 = new NodeAddedSchedulerEvent(resourceManager.getRMContext() .getRMNodes().get(nm.getNodeId())); resourceManager.getResourceScheduler().handle(nodeAddEvent1); return nm; } @Test public void testResourceAllocation() throws IOException, YarnException, InterruptedException { LOG.info("--- START: testResourceAllocation ---"); final int memory = 4 * 1024; final int vcores = 4; // Register node1 String host1 = "host1"; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm1 = registerNode(host1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(memory, vcores)); // Register node2 String host2 = "host2"; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm2 = registerNode(host2, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(memory/2, vcores/2)); // Submit an application Application application = new Application("user1", resourceManager); application.submit(); application.addNodeManager(host1, 1234, nm1); application.addNodeManager(host2, 1234, nm2); // Application resource requirements final int memory1 = 1024; Resource capability1 = Resources.createResource(memory1, 1); Priority priority1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.create(1); application.addResourceRequestSpec(priority1, capability1); Task t1 = new Task(application, priority1, new String[] {host1, host2}); application.addTask(t1); final int memory2 = 2048; Resource capability2 = Resources.createResource(memory2, 1); Priority priority0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.create(0); // higher application.addResourceRequestSpec(priority0, capability2); // Send resource requests to the scheduler application.schedule(); // Send a heartbeat to kick the tires on the Scheduler nodeUpdate(nm1); // Get allocations from the scheduler application.schedule(); checkResourceUsage(nm1, nm2); LOG.info("Adding new tasks..."); Task t2 = new Task(application, priority1, new String[] {host1, host2}); application.addTask(t2); Task t3 = new Task(application, priority0, new String[] {ResourceRequest.ANY}); application.addTask(t3); // Send resource requests to the scheduler application.schedule(); checkResourceUsage(nm1, nm2); // Send heartbeats to kick the tires on the Scheduler nodeUpdate(nm2); nodeUpdate(nm2); nodeUpdate(nm1); nodeUpdate(nm1); // Get allocations from the scheduler LOG.info("Trying to allocate..."); application.schedule(); checkResourceUsage(nm1, nm2); // Complete tasks LOG.info("Finishing up tasks..."); application.finishTask(t1); application.finishTask(t2); application.finishTask(t3); // Notify scheduler application is finished. AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent( application.getApplicationAttemptId(), RMAppAttemptState.FINISHED, false); resourceManager.getResourceScheduler().handle(appRemovedEvent1); checkResourceUsage(nm1, nm2); LOG.info("--- END: testResourceAllocation ---"); } private void nodeUpdate( org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm1) { RMNode node = resourceManager.getRMContext().getRMNodes().get(nm1.getNodeId()); // Send a heartbeat to kick the tires on the Scheduler NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node); resourceManager.getResourceScheduler().handle(nodeUpdate); } @Test public void testNodeHealthReportIsNotNull() throws Exception{ String host1 = "host1"; final int memory = 4 * 1024; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm1 = registerNode(host1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(memory, 1)); nm1.heartbeat(); nm1.heartbeat(); Collection<RMNode> values = resourceManager.getRMContext().getRMNodes().values(); for (RMNode ni : values) { assertNotNull(ni.getHealthReport()); } } private void checkResourceUsage( org.apache.hadoop.yarn.server.resourcemanager.NodeManager... nodes ) { for (org.apache.hadoop.yarn.server.resourcemanager.NodeManager nodeManager : nodes) { nodeManager.checkResourceUsage(); } } @Test (timeout = 30000) public void testResourceManagerInitConfigValidation() throws Exception { Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, -1); try { resourceManager = new MockRM(conf); fail("Exception is expected because the global max attempts" + " is negative."); } catch (YarnRuntimeException e) { // Exception is expected. if (!e.getMessage().startsWith( "Invalid global max attempts configuration")) throw e; } } @Test public void testNMExpiryAndHeartbeatIntervalsValidation() throws Exception { Configuration conf = new YarnConfiguration(); conf.setLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS, 1000); conf.setLong(YarnConfiguration.RM_NM_HEARTBEAT_INTERVAL_MS, 1001); try { resourceManager = new MockRM(conf); } catch (YarnRuntimeException e) { // Exception is expected. if (!e.getMessage().startsWith("Nodemanager expiry interval should be no" + " less than heartbeat interval")) { throw e; } } } @Test(timeout = 50000) public void testFilterOverrides() throws Exception { String filterInitializerConfKey = "hadoop.http.filter.initializers"; String[] filterInitializers = { AuthenticationFilterInitializer.class.getName(), RMAuthenticationFilterInitializer.class.getName(), AuthenticationFilterInitializer.class.getName() + "," + RMAuthenticationFilterInitializer.class.getName(), AuthenticationFilterInitializer.class.getName() + ", " + RMAuthenticationFilterInitializer.class.getName(), AuthenticationFilterInitializer.class.getName() + ", " + this.getClass().getName() }; for (String filterInitializer : filterInitializers) { resourceManager = new ResourceManager() { @Override protected void doSecureLogin() throws IOException { // Skip the login. } }; Configuration conf = new YarnConfiguration(); conf.set(filterInitializerConfKey, filterInitializer); conf.set("hadoop.security.authentication", "kerberos"); conf.set("hadoop.http.authentication.type", "kerberos"); try { try { UserGroupInformation.setConfiguration(conf); } catch (Exception e) { // ignore we just care about getting true for // isSecurityEnabled() LOG.info("Got expected exception"); } resourceManager.init(conf); resourceManager.startWepApp(); } catch (RuntimeException e) { // Exceptions are expected because we didn't setup everything // just want to test filter settings String tmp = resourceManager.getConfig().get(filterInitializerConfKey); if (filterInitializer.contains(this.getClass().getName())) { Assert.assertEquals(RMAuthenticationFilterInitializer.class.getName() + "," + this.getClass().getName(), tmp); } else { Assert.assertEquals( RMAuthenticationFilterInitializer.class.getName(), tmp); } resourceManager.stop(); } } // simple mode overrides String[] simpleFilterInitializers = { "", StaticUserWebFilter.class.getName() }; for (String filterInitializer : simpleFilterInitializers) { resourceManager = new ResourceManager(); Configuration conf = new YarnConfiguration(); conf.set(filterInitializerConfKey, filterInitializer); try { UserGroupInformation.setConfiguration(conf); resourceManager.init(conf); resourceManager.startWepApp(); } catch (RuntimeException e) { // Exceptions are expected because we didn't setup everything // just want to test filter settings String tmp = resourceManager.getConfig().get(filterInitializerConfKey); if (filterInitializer.equals(StaticUserWebFilter.class.getName())) { Assert.assertEquals(RMAuthenticationFilterInitializer.class.getName() + "," + StaticUserWebFilter.class.getName(), tmp); } else { Assert.assertEquals( RMAuthenticationFilterInitializer.class.getName(), tmp); } resourceManager.stop(); } } } }
12,429
37.965517
101
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClusterMetrics.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; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.junit.After; import org.junit.Before; import org.junit.Assert; import org.junit.Test; public class TestClusterMetrics { private ClusterMetrics metrics; /** * Test aMLaunchDelay and aMRegisterDelay Metrics */ @Test public void testAmMetrics() throws Exception { assert(metrics != null); Assert.assertTrue(!metrics.aMLaunchDelay.changed()); Assert.assertTrue(!metrics.aMRegisterDelay.changed()); metrics.addAMLaunchDelay(1); metrics.addAMRegisterDelay(1); Assert.assertTrue(metrics.aMLaunchDelay.changed()); Assert.assertTrue(metrics.aMRegisterDelay.changed()); } @Before public void setup() { DefaultMetricsSystem.initialize("ResourceManager"); metrics = ClusterMetrics.getMetrics(); } @After public void tearDown() { ClusterMetrics.destroy(); MetricsSystem ms = DefaultMetricsSystem.instance(); if (ms.getSource("ClusterMetrics") != null) { DefaultMetricsSystem.shutdown(); } } }
1,955
31.065574
75
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockAM.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; import java.lang.reflect.UndeclaredThrowableException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.util.Records; import org.apache.log4j.Logger; import org.junit.Assert; public class MockAM { private static final Logger LOG = Logger.getLogger(MockAM.class); private volatile int responseId = 0; private final ApplicationAttemptId attemptId; private RMContext context; private ApplicationMasterProtocol amRMProtocol; private UserGroupInformation ugi; private volatile AllocateResponse lastResponse; private final List<ResourceRequest> requests = new ArrayList<ResourceRequest>(); private final List<ContainerId> releases = new ArrayList<ContainerId>(); public MockAM(RMContext context, ApplicationMasterProtocol amRMProtocol, ApplicationAttemptId attemptId) { this.context = context; this.amRMProtocol = amRMProtocol; this.attemptId = attemptId; } public void setAMRMProtocol(ApplicationMasterProtocol amRMProtocol, RMContext context) { this.context = context; this.amRMProtocol = amRMProtocol; } public void waitForState(RMAppAttemptState finalState) throws Exception { RMApp app = context.getRMApps().get(attemptId.getApplicationId()); RMAppAttempt attempt = app.getRMAppAttempt(attemptId); final int timeoutMsecs = 40000; final int minWaitMsecs = 1000; final int waitMsPerLoop = 500; int loop = 0; while (!finalState.equals(attempt.getAppAttemptState()) && waitMsPerLoop * loop < timeoutMsecs) { LOG.info("AppAttempt : " + attemptId + " State is : " + attempt.getAppAttemptState() + " Waiting for state : " + finalState); Thread.yield(); Thread.sleep(waitMsPerLoop); loop++; } int waitedMsecs = waitMsPerLoop * loop; if (minWaitMsecs > waitedMsecs) { Thread.sleep(minWaitMsecs - waitedMsecs); } LOG.info("Attempt State is : " + attempt.getAppAttemptState()); if (waitedMsecs >= timeoutMsecs) { Assert.fail("Attempt state is not correct (timedout): expected: " + finalState + " actual: " + attempt.getAppAttemptState()); } } public RegisterApplicationMasterResponse registerAppAttempt() throws Exception { return registerAppAttempt(true); } public RegisterApplicationMasterResponse registerAppAttempt(boolean wait) throws Exception { if (wait) { waitForState(RMAppAttemptState.LAUNCHED); } responseId = 0; final RegisterApplicationMasterRequest req = Records.newRecord(RegisterApplicationMasterRequest.class); req.setHost(""); req.setRpcPort(1); req.setTrackingUrl(""); if (ugi == null) { ugi = UserGroupInformation.createRemoteUser( attemptId.toString()); Token<AMRMTokenIdentifier> token = context.getRMApps().get(attemptId.getApplicationId()) .getRMAppAttempt(attemptId).getAMRMToken(); ugi.addTokenIdentifier(token.decodeIdentifier()); } try { return ugi .doAs( new PrivilegedExceptionAction<RegisterApplicationMasterResponse>() { @Override public RegisterApplicationMasterResponse run() throws Exception { return amRMProtocol.registerApplicationMaster(req); } }); } catch (UndeclaredThrowableException e) { throw (Exception) e.getCause(); } } public void addRequests(String[] hosts, int memory, int priority, int containers) throws Exception { requests.addAll(createReq(hosts, memory, priority, containers)); } public AllocateResponse schedule() throws Exception { AllocateResponse response = allocate(requests, releases); requests.clear(); releases.clear(); return response; } public void addContainerToBeReleased(ContainerId containerId) { releases.add(containerId); } public AllocateResponse allocate( String host, int memory, int numContainers, List<ContainerId> releases) throws Exception { return allocate(host, memory, numContainers, releases, null); } public AllocateResponse allocate( String host, int memory, int numContainers, List<ContainerId> releases, String labelExpression) throws Exception { return allocate(host, memory, numContainers, 1, releases, labelExpression); } public AllocateResponse allocate( String host, int memory, int numContainers, int priority, List<ContainerId> releases, String labelExpression) throws Exception { List<ResourceRequest> reqs = createReq(new String[] { host }, memory, priority, numContainers, labelExpression); return allocate(reqs, releases); } public List<ResourceRequest> createReq(String[] hosts, int memory, int priority, int containers) throws Exception { return createReq(hosts, memory, priority, containers, null); } public List<ResourceRequest> createReq(String[] hosts, int memory, int priority, int containers, String labelExpression) throws Exception { List<ResourceRequest> reqs = new ArrayList<ResourceRequest>(); if (hosts != null) { for (String host : hosts) { // only add host/rack request when asked host isn't ANY if (!host.equals(ResourceRequest.ANY)) { ResourceRequest hostReq = createResourceReq(host, memory, priority, containers, labelExpression); reqs.add(hostReq); ResourceRequest rackReq = createResourceReq("/default-rack", memory, priority, containers, labelExpression); reqs.add(rackReq); } } } ResourceRequest offRackReq = createResourceReq(ResourceRequest.ANY, memory, priority, containers, labelExpression); reqs.add(offRackReq); return reqs; } public ResourceRequest createResourceReq(String resource, int memory, int priority, int containers) throws Exception { return createResourceReq(resource, memory, priority, containers, null); } public ResourceRequest createResourceReq(String resource, int memory, int priority, int containers, String labelExpression) throws Exception { ResourceRequest req = Records.newRecord(ResourceRequest.class); req.setResourceName(resource); req.setNumContainers(containers); Priority pri = Records.newRecord(Priority.class); pri.setPriority(priority); req.setPriority(pri); Resource capability = Records.newRecord(Resource.class); capability.setMemory(memory); req.setCapability(capability); if (labelExpression != null) { req.setNodeLabelExpression(labelExpression); } return req; } public AllocateResponse allocate( List<ResourceRequest> resourceRequest, List<ContainerId> releases) throws Exception { final AllocateRequest req = AllocateRequest.newInstance(0, 0F, resourceRequest, releases, null); return allocate(req); } public AllocateResponse allocate(AllocateRequest allocateRequest) throws Exception { UserGroupInformation ugi = UserGroupInformation.createRemoteUser(attemptId.toString()); Token<AMRMTokenIdentifier> token = context.getRMApps().get(attemptId.getApplicationId()) .getRMAppAttempt(attemptId).getAMRMToken(); ugi.addTokenIdentifier(token.decodeIdentifier()); lastResponse = doAllocateAs(ugi, allocateRequest); return lastResponse; } public AllocateResponse doAllocateAs(UserGroupInformation ugi, final AllocateRequest req) throws Exception { req.setResponseId(++responseId); try { return ugi.doAs(new PrivilegedExceptionAction<AllocateResponse>() { @Override public AllocateResponse run() throws Exception { return amRMProtocol.allocate(req); } }); } catch (UndeclaredThrowableException e) { throw (Exception) e.getCause(); } } public AllocateResponse doHeartbeat() throws Exception { return allocate(null, null); } public void unregisterAppAttempt() throws Exception { waitForState(RMAppAttemptState.RUNNING); unregisterAppAttempt(true); } public void unregisterAppAttempt(boolean waitForStateRunning) throws Exception { final FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.SUCCEEDED, "", ""); unregisterAppAttempt(req, waitForStateRunning); } public void unregisterAppAttempt(final FinishApplicationMasterRequest req, boolean waitForStateRunning) throws Exception { if (waitForStateRunning) { waitForState(RMAppAttemptState.RUNNING); } if (ugi == null) { ugi = UserGroupInformation.createRemoteUser(attemptId.toString()); Token<AMRMTokenIdentifier> token = context.getRMApps() .get(attemptId.getApplicationId()) .getRMAppAttempt(attemptId).getAMRMToken(); ugi.addTokenIdentifier(token.decodeIdentifier()); } try { ugi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { amRMProtocol.finishApplicationMaster(req); return null; } }); } catch (UndeclaredThrowableException e) { throw (Exception) e.getCause(); } } public ApplicationAttemptId getApplicationAttemptId() { return this.attemptId; } public List<Container> allocateAndWaitForContainers(int nContainer, int memory, MockNM nm) throws Exception { return allocateAndWaitForContainers("ANY", nContainer, memory, nm); } public List<Container> allocateAndWaitForContainers(String host, int nContainer, int memory, MockNM nm) throws Exception { // AM request for containers allocate(host, memory, nContainer, null); // kick the scheduler nm.nodeHeartbeat(true); List<Container> conts = allocate(new ArrayList<ResourceRequest>(), null) .getAllocatedContainers(); while (conts.size() < nContainer) { nm.nodeHeartbeat(true); conts.addAll(allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(500); } return conts; } }
12,428
36.101493
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.ha.HAServiceProtocol; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.GroupMappingServiceProvider; import org.apache.hadoop.security.Groups; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.security.authorize.ProxyUsers; import org.apache.hadoop.security.authorize.ServiceAuthorizationManager; import org.apache.hadoop.yarn.LocalConfigurationProvider; import org.apache.hadoop.yarn.api.records.DecommissionType; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.conf.HAUtil; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeRequest; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; public class TestRMAdminService { private Configuration configuration;; private MockRM rm = null; private FileSystem fs; private Path workingPath; private Path tmpDir; static { YarnConfiguration.addDefaultResource( YarnConfiguration.CS_CONFIGURATION_FILE); } @Before public void setup() throws IOException { configuration = new YarnConfiguration(); configuration.set(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class.getCanonicalName()); fs = FileSystem.get(configuration); workingPath = new Path(new File("target", this.getClass().getSimpleName() + "-remoteDir").getAbsolutePath()); configuration.set(YarnConfiguration.FS_BASED_RM_CONF_STORE, workingPath.toString()); tmpDir = new Path(new File("target", this.getClass().getSimpleName() + "-tmpDir").getAbsolutePath()); fs.delete(workingPath, true); fs.delete(tmpDir, true); fs.mkdirs(workingPath); fs.mkdirs(tmpDir); // reset the groups to what it default test settings MockUnixGroupsMapping.resetGroups(); } @After public void tearDown() throws IOException { if (rm != null) { rm.stop(); } fs.delete(workingPath, true); fs.delete(tmpDir, true); } @Test public void testAdminRefreshQueuesWithLocalConfigurationProvider() throws IOException, YarnException { rm = new MockRM(configuration); rm.init(configuration); rm.start(); CapacityScheduler cs = (CapacityScheduler) rm.getRMContext().getScheduler(); int maxAppsBefore = cs.getConfiguration().getMaximumSystemApplications(); try { rm.adminService.refreshQueues(RefreshQueuesRequest.newInstance()); Assert.assertEquals(maxAppsBefore, cs.getConfiguration() .getMaximumSystemApplications()); } catch (Exception ex) { fail("Using localConfigurationProvider. Should not get any exception."); } } @Test public void testAdminRefreshQueuesWithFileSystemBasedConfigurationProvider() throws IOException, YarnException { configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); //upload default configurations uploadDefaultConfiguration(); try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch(Exception ex) { fail("Should not get any exceptions"); } CapacityScheduler cs = (CapacityScheduler) rm.getRMContext().getScheduler(); int maxAppsBefore = cs.getConfiguration().getMaximumSystemApplications(); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); csConf.set("yarn.scheduler.capacity.maximum-applications", "5000"); uploadConfiguration(csConf, "capacity-scheduler.xml"); rm.adminService.refreshQueues(RefreshQueuesRequest.newInstance()); int maxAppsAfter = cs.getConfiguration().getMaximumSystemApplications(); Assert.assertEquals(maxAppsAfter, 5000); Assert.assertTrue(maxAppsAfter != maxAppsBefore); } @Test public void testAdminAclsWithLocalConfigurationProvider() { rm = new MockRM(configuration); rm.init(configuration); rm.start(); try { rm.adminService.refreshAdminAcls(RefreshAdminAclsRequest.newInstance()); } catch (Exception ex) { fail("Using localConfigurationProvider. Should not get any exception."); } } @Test public void testAdminAclsWithFileSystemBasedConfigurationProvider() throws IOException, YarnException { configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); //upload default configurations uploadDefaultConfiguration(); try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch(Exception ex) { fail("Should not get any exceptions"); } String aclStringBefore = rm.adminService.getAccessControlList().getAclString().trim(); YarnConfiguration yarnConf = new YarnConfiguration(); yarnConf.set(YarnConfiguration.YARN_ADMIN_ACL, "world:anyone:rwcda"); uploadConfiguration(yarnConf, "yarn-site.xml"); rm.adminService.refreshAdminAcls(RefreshAdminAclsRequest.newInstance()); String aclStringAfter = rm.adminService.getAccessControlList().getAclString().trim(); Assert.assertTrue(!aclStringAfter.equals(aclStringBefore)); Assert.assertEquals(aclStringAfter, "world:anyone:rwcda," + UserGroupInformation.getCurrentUser().getShortUserName()); } @Test public void testServiceAclsRefreshWithLocalConfigurationProvider() { configuration.setBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, true); ResourceManager resourceManager = null; try { resourceManager = new ResourceManager(); resourceManager.init(configuration); resourceManager.start(); resourceManager.adminService.refreshServiceAcls(RefreshServiceAclsRequest .newInstance()); } catch (Exception ex) { fail("Using localConfigurationProvider. Should not get any exception."); } finally { if (resourceManager != null) { resourceManager.stop(); } } } @Test public void testServiceAclsRefreshWithFileSystemBasedConfigurationProvider() throws IOException, YarnException { configuration.setBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, true); configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); ResourceManager resourceManager = null; try { //upload default configurations uploadDefaultConfiguration(); Configuration conf = new Configuration(); conf.setBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, true); uploadConfiguration(conf, "core-site.xml"); try { resourceManager = new ResourceManager(); resourceManager.init(configuration); resourceManager.start(); } catch (Exception ex) { fail("Should not get any exceptions"); } String aclsString = "alice,bob users,wheel"; Configuration newConf = new Configuration(); newConf.set("security.applicationclient.protocol.acl", aclsString); uploadConfiguration(newConf, "hadoop-policy.xml"); resourceManager.adminService.refreshServiceAcls(RefreshServiceAclsRequest .newInstance()); // verify service Acls refresh for AdminService ServiceAuthorizationManager adminServiceServiceManager = resourceManager.adminService.getServer() .getServiceAuthorizationManager(); verifyServiceACLsRefresh(adminServiceServiceManager, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify service ACLs refresh for ClientRMService ServiceAuthorizationManager clientRMServiceServiceManager = resourceManager.getRMContext().getClientRMService().getServer() .getServiceAuthorizationManager(); verifyServiceACLsRefresh(clientRMServiceServiceManager, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify service ACLs refresh for ApplicationMasterService ServiceAuthorizationManager appMasterService = resourceManager.getRMContext().getApplicationMasterService() .getServer().getServiceAuthorizationManager(); verifyServiceACLsRefresh(appMasterService, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify service ACLs refresh for ResourceTrackerService ServiceAuthorizationManager RTService = resourceManager.getRMContext().getResourceTrackerService() .getServer().getServiceAuthorizationManager(); verifyServiceACLsRefresh(RTService, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); } finally { if (resourceManager != null) { resourceManager.stop(); } } } private void verifyServiceACLsRefresh(ServiceAuthorizationManager manager, Class<?> protocol, String aclString) { for (Class<?> protocolClass : manager.getProtocolsWithAcls()) { AccessControlList accessList = manager.getProtocolsAcls(protocolClass); if (protocolClass == protocol) { Assert.assertEquals(accessList.getAclString(), aclString); } else { Assert.assertEquals(accessList.getAclString(), "*"); } } } @Test public void testRefreshSuperUserGroupsWithLocalConfigurationProvider() { rm = new MockRM(configuration); rm.init(configuration); rm.start(); try { rm.adminService.refreshSuperUserGroupsConfiguration( RefreshSuperUserGroupsConfigurationRequest.newInstance()); } catch (Exception ex) { fail("Using localConfigurationProvider. Should not get any exception."); } } @Test public void testRefreshSuperUserGroupsWithFileSystemBasedConfigurationProvider() throws IOException, YarnException { configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); //upload default configurations uploadDefaultConfiguration(); try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch(Exception ex) { fail("Should not get any exceptions"); } Configuration coreConf = new Configuration(false); coreConf.set("hadoop.proxyuser.test.groups", "test_groups"); coreConf.set("hadoop.proxyuser.test.hosts", "test_hosts"); uploadConfiguration(coreConf, "core-site.xml"); rm.adminService.refreshSuperUserGroupsConfiguration( RefreshSuperUserGroupsConfigurationRequest.newInstance()); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyGroups() .get("hadoop.proxyuser.test.groups").size() == 1); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyGroups() .get("hadoop.proxyuser.test.groups").contains("test_groups")); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyHosts() .get("hadoop.proxyuser.test.hosts").size() == 1); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyHosts() .get("hadoop.proxyuser.test.hosts").contains("test_hosts")); Configuration yarnConf = new Configuration(false); yarnConf.set("yarn.resourcemanager.proxyuser.test.groups", "test_groups_1"); yarnConf.set("yarn.resourcemanager.proxyuser.test.hosts", "test_hosts_1"); uploadConfiguration(yarnConf, "yarn-site.xml"); // RM specific configs will overwrite the common ones rm.adminService.refreshSuperUserGroupsConfiguration( RefreshSuperUserGroupsConfigurationRequest.newInstance()); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyGroups() .get("hadoop.proxyuser.test.groups").size() == 1); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyGroups() .get("hadoop.proxyuser.test.groups").contains("test_groups_1")); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyHosts() .get("hadoop.proxyuser.test.hosts").size() == 1); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyHosts() .get("hadoop.proxyuser.test.hosts").contains("test_hosts_1")); } @Test public void testRefreshUserToGroupsMappingsWithLocalConfigurationProvider() { rm = new MockRM(configuration); rm.init(configuration); rm.start(); try { rm.adminService .refreshUserToGroupsMappings(RefreshUserToGroupsMappingsRequest .newInstance()); } catch (Exception ex) { fail("Using localConfigurationProvider. Should not get any exception."); } } @Test public void testRefreshUserToGroupsMappingsWithFileSystemBasedConfigurationProvider() throws IOException, YarnException { configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); String[] defaultTestUserGroups = {"dummy_group1", "dummy_group2"}; UserGroupInformation ugi = UserGroupInformation.createUserForTesting ("dummyUser", defaultTestUserGroups); String user = ugi.getUserName(); List<String> groupWithInit = new ArrayList<String>(2); for(int i = 0; i < ugi.getGroupNames().length; i++ ) { groupWithInit.add(ugi.getGroupNames()[i]); } // upload default configurations uploadDefaultConfiguration(); Configuration conf = new Configuration(); conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, MockUnixGroupsMapping.class, GroupMappingServiceProvider.class); uploadConfiguration(conf, "core-site.xml"); try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch (Exception ex) { fail("Should not get any exceptions"); } // Make sure RM will use the updated GroupMappingServiceProvider List<String> groupBefore = new ArrayList<String>(Groups.getUserToGroupsMappingService( configuration).getGroups(user)); Assert.assertTrue(groupBefore.contains("test_group_A") && groupBefore.contains("test_group_B") && groupBefore.contains("test_group_C") && groupBefore.size() == 3); Assert.assertTrue(groupWithInit.size() != groupBefore.size()); Assert.assertFalse(groupWithInit.contains("test_group_A") || groupWithInit.contains("test_group_B") || groupWithInit.contains("test_group_C")); // update the groups MockUnixGroupsMapping.updateGroups(); rm.adminService .refreshUserToGroupsMappings(RefreshUserToGroupsMappingsRequest .newInstance()); List<String> groupAfter = Groups.getUserToGroupsMappingService(configuration).getGroups(user); // should get the updated groups Assert.assertTrue(groupAfter.contains("test_group_D") && groupAfter.contains("test_group_E") && groupAfter.contains("test_group_F") && groupAfter.size() == 3); } @Test public void testRefreshNodesWithLocalConfigurationProvider() { rm = new MockRM(configuration); rm.init(configuration); rm.start(); try { rm.adminService.refreshNodes(RefreshNodesRequest .newInstance(DecommissionType.NORMAL)); } catch (Exception ex) { fail("Using localConfigurationProvider. Should not get any exception."); } } @Test public void testRefreshNodesWithFileSystemBasedConfigurationProvider() throws IOException, YarnException { configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); // upload default configurations uploadDefaultConfiguration(); try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch (Exception ex) { fail("Should not get any exceptions"); } final File excludeHostsFile = new File(tmpDir.toString(), "excludeHosts"); if (excludeHostsFile.exists()) { excludeHostsFile.delete(); } if (!excludeHostsFile.createNewFile()) { Assert.fail("Can not create " + "excludeHosts"); } PrintWriter fileWriter = new PrintWriter(excludeHostsFile); fileWriter.write("0.0.0.0:123"); fileWriter.close(); uploadToRemoteFileSystem(new Path(excludeHostsFile.getAbsolutePath())); Configuration yarnConf = new YarnConfiguration(); yarnConf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, this.workingPath + "/excludeHosts"); uploadConfiguration(yarnConf, YarnConfiguration.YARN_SITE_CONFIGURATION_FILE); rm.adminService.refreshNodes(RefreshNodesRequest .newInstance(DecommissionType.NORMAL)); Set<String> excludeHosts = rm.getNodesListManager().getHostsReader().getExcludedHosts(); Assert.assertTrue(excludeHosts.size() == 1); Assert.assertTrue(excludeHosts.contains("0.0.0.0:123")); } @Test public void testRMHAWithFileSystemBasedConfiguration() throws IOException, YarnException { StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); configuration.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); configuration.set(YarnConfiguration.RM_HA_IDS, "rm1,rm2"); int base = 100; for (String confKey : YarnConfiguration .getServiceAddressConfKeys(configuration)) { configuration.set(HAUtil.addSuffix(confKey, "rm1"), "0.0.0.0:" + (base + 20)); configuration.set(HAUtil.addSuffix(confKey, "rm2"), "0.0.0.0:" + (base + 40)); base = base * 2; } Configuration conf1 = new Configuration(configuration); conf1.set(YarnConfiguration.RM_HA_ID, "rm1"); Configuration conf2 = new Configuration(configuration); conf2.set(YarnConfiguration.RM_HA_ID, "rm2"); // upload default configurations uploadDefaultConfiguration(); MockRM rm1 = null; MockRM rm2 = null; try { rm1 = new MockRM(conf1); rm1.init(conf1); rm1.start(); Assert.assertTrue(rm1.getRMContext().getHAServiceState() == HAServiceState.STANDBY); rm2 = new MockRM(conf2); rm2.init(conf1); rm2.start(); Assert.assertTrue(rm2.getRMContext().getHAServiceState() == HAServiceState.STANDBY); rm1.adminService.transitionToActive(requestInfo); Assert.assertTrue(rm1.getRMContext().getHAServiceState() == HAServiceState.ACTIVE); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); csConf.set("yarn.scheduler.capacity.maximum-applications", "5000"); uploadConfiguration(csConf, "capacity-scheduler.xml"); rm1.adminService.refreshQueues(RefreshQueuesRequest.newInstance()); int maxApps = ((CapacityScheduler) rm1.getRMContext().getScheduler()) .getConfiguration().getMaximumSystemApplications(); Assert.assertEquals(maxApps, 5000); // Before failover happens, the maxApps is // still the default value on the standby rm : rm2 int maxAppsBeforeFailOver = ((CapacityScheduler) rm2.getRMContext().getScheduler()) .getConfiguration().getMaximumSystemApplications(); Assert.assertEquals(maxAppsBeforeFailOver, 10000); // Do the failover rm1.adminService.transitionToStandby(requestInfo); rm2.adminService.transitionToActive(requestInfo); Assert.assertTrue(rm1.getRMContext().getHAServiceState() == HAServiceState.STANDBY); Assert.assertTrue(rm2.getRMContext().getHAServiceState() == HAServiceState.ACTIVE); int maxAppsAfter = ((CapacityScheduler) rm2.getRMContext().getScheduler()) .getConfiguration().getMaximumSystemApplications(); Assert.assertEquals(maxAppsAfter, 5000); } finally { if (rm1 != null) { rm1.stop(); } if (rm2 != null) { rm2.stop(); } } } @Test public void testRMStartsWithoutConfigurationFilesProvided() { // enable FileSystemBasedConfigurationProvider without uploading // any configuration files into Remote File System. configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); // The configurationProvider will return NULL instead of // throwing out Exceptions, if there are no configuration files provided. // RM will not load the remote Configuration files, // and should start successfully. try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch (Exception ex) { fail("Should not get any exceptions"); } } @Test public void testRMInitialsWithFileSystemBasedConfigurationProvider() throws Exception { configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); // upload configurations final File excludeHostsFile = new File(tmpDir.toString(), "excludeHosts"); if (excludeHostsFile.exists()) { excludeHostsFile.delete(); } if (!excludeHostsFile.createNewFile()) { Assert.fail("Can not create " + "excludeHosts"); } PrintWriter fileWriter = new PrintWriter(excludeHostsFile); fileWriter.write("0.0.0.0:123"); fileWriter.close(); uploadToRemoteFileSystem(new Path(excludeHostsFile.getAbsolutePath())); YarnConfiguration yarnConf = new YarnConfiguration(); yarnConf.set(YarnConfiguration.YARN_ADMIN_ACL, "world:anyone:rwcda"); yarnConf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, this.workingPath + "/excludeHosts"); uploadConfiguration(yarnConf, "yarn-site.xml"); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); csConf.set("yarn.scheduler.capacity.maximum-applications", "5000"); uploadConfiguration(csConf, "capacity-scheduler.xml"); String aclsString = "alice,bob users,wheel"; Configuration newConf = new Configuration(); newConf.set("security.applicationclient.protocol.acl", aclsString); uploadConfiguration(newConf, "hadoop-policy.xml"); Configuration conf = new Configuration(); conf.setBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, true); conf.set("hadoop.proxyuser.test.groups", "test_groups"); conf.set("hadoop.proxyuser.test.hosts", "test_hosts"); conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, MockUnixGroupsMapping.class, GroupMappingServiceProvider.class); uploadConfiguration(conf, "core-site.xml"); // update the groups MockUnixGroupsMapping.updateGroups(); ResourceManager resourceManager = null; try { try { resourceManager = new ResourceManager(); resourceManager.init(configuration); resourceManager.start(); } catch (Exception ex) { fail("Should not get any exceptions"); } // validate values for excludeHosts Set<String> excludeHosts = resourceManager.getRMContext().getNodesListManager() .getHostsReader().getExcludedHosts(); Assert.assertTrue(excludeHosts.size() == 1); Assert.assertTrue(excludeHosts.contains("0.0.0.0:123")); // validate values for admin-acls String aclStringAfter = resourceManager.adminService.getAccessControlList() .getAclString().trim(); Assert.assertEquals(aclStringAfter, "world:anyone:rwcda," + UserGroupInformation.getCurrentUser().getShortUserName()); // validate values for queue configuration CapacityScheduler cs = (CapacityScheduler) resourceManager.getRMContext().getScheduler(); int maxAppsAfter = cs.getConfiguration().getMaximumSystemApplications(); Assert.assertEquals(maxAppsAfter, 5000); // verify service Acls for AdminService ServiceAuthorizationManager adminServiceServiceManager = resourceManager.adminService.getServer() .getServiceAuthorizationManager(); verifyServiceACLsRefresh(adminServiceServiceManager, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify service ACLs for ClientRMService ServiceAuthorizationManager clientRMServiceServiceManager = resourceManager.getRMContext().getClientRMService().getServer() .getServiceAuthorizationManager(); verifyServiceACLsRefresh(clientRMServiceServiceManager, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify service ACLs for ApplicationMasterService ServiceAuthorizationManager appMasterService = resourceManager.getRMContext().getApplicationMasterService() .getServer().getServiceAuthorizationManager(); verifyServiceACLsRefresh(appMasterService, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify service ACLs for ResourceTrackerService ServiceAuthorizationManager RTService = resourceManager.getRMContext().getResourceTrackerService() .getServer().getServiceAuthorizationManager(); verifyServiceACLsRefresh(RTService, org.apache.hadoop.yarn.api.ApplicationClientProtocolPB.class, aclsString); // verify ProxyUsers and ProxyHosts ProxyUsers.refreshSuperUserGroupsConfiguration(configuration); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyGroups() .get("hadoop.proxyuser.test.groups").size() == 1); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyGroups() .get("hadoop.proxyuser.test.groups").contains("test_groups")); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyHosts() .get("hadoop.proxyuser.test.hosts").size() == 1); Assert.assertTrue(ProxyUsers.getDefaultImpersonationProvider().getProxyHosts() .get("hadoop.proxyuser.test.hosts").contains("test_hosts")); // verify UserToGroupsMappings List<String> groupAfter = Groups.getUserToGroupsMappingService(configuration).getGroups( UserGroupInformation.getCurrentUser().getUserName()); Assert.assertTrue(groupAfter.contains("test_group_D") && groupAfter.contains("test_group_E") && groupAfter.contains("test_group_F") && groupAfter.size() == 3); } finally { if (resourceManager != null) { resourceManager.stop(); } } } /* For verifying fix for YARN-3804 */ @Test public void testRefreshAclWithDaemonUser() throws Exception { String daemonUser = UserGroupInformation.getCurrentUser().getShortUserName(); configuration.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); uploadDefaultConfiguration(); YarnConfiguration yarnConf = new YarnConfiguration(); yarnConf.set(YarnConfiguration.YARN_ADMIN_ACL, daemonUser + "xyz"); uploadConfiguration(yarnConf, "yarn-site.xml"); try { rm = new MockRM(configuration); rm.init(configuration); rm.start(); } catch(Exception ex) { fail("Should not get any exceptions"); } assertEquals(daemonUser + "xyz," + daemonUser, rm.adminService.getAccessControlList().getAclString().trim()); yarnConf = new YarnConfiguration(); yarnConf.set(YarnConfiguration.YARN_ADMIN_ACL, daemonUser + "abc"); uploadConfiguration(yarnConf, "yarn-site.xml"); try { rm.adminService.refreshAdminAcls(RefreshAdminAclsRequest.newInstance()); } catch (YarnException e) { if (e.getCause() != null && e.getCause() instanceof AccessControlException) { fail("Refresh should not have failed due to incorrect ACL"); } throw e; } assertEquals(daemonUser + "abc," + daemonUser, rm.adminService.getAccessControlList().getAclString().trim()); } @Test public void testModifyLabelsOnNodesWithDistributedConfigurationDisabled() throws IOException, YarnException { // create RM and set it's ACTIVE MockRM rm = new MockRM(); ((RMContextImpl) rm.getRMContext()) .setHAServiceState(HAServiceState.ACTIVE); RMNodeLabelsManager labelMgr = rm.rmContext.getNodeLabelManager(); // by default, distributed configuration for node label is disabled, this // should pass labelMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); rm.adminService.replaceLabelsOnNode(ReplaceLabelsOnNodeRequest .newInstance(ImmutableMap.of(NodeId.newInstance("host", 0), (Set<String>) ImmutableSet.of("x")))); rm.close(); } @Test(expected = YarnException.class) public void testModifyLabelsOnNodesWithDistributedConfigurationEnabled() throws IOException, YarnException { // create RM and set it's ACTIVE, and set distributed node label // configuration to true MockRM rm = new MockRM(); rm.adminService.isDistributedNodeLabelConfiguration = true; ((RMContextImpl) rm.getRMContext()) .setHAServiceState(HAServiceState.ACTIVE); RMNodeLabelsManager labelMgr = rm.rmContext.getNodeLabelManager(); // by default, distributed configuration for node label is disabled, this // should pass labelMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); rm.adminService.replaceLabelsOnNode(ReplaceLabelsOnNodeRequest .newInstance(ImmutableMap.of(NodeId.newInstance("host", 0), (Set<String>) ImmutableSet.of("x")))); rm.close(); } @Test public void testRemoveClusterNodeLabelsWithDistributedConfigurationEnabled() throws IOException, YarnException { // create RM and set it's ACTIVE MockRM rm = new MockRM(); ((RMContextImpl) rm.getRMContext()) .setHAServiceState(HAServiceState.ACTIVE); RMNodeLabelsManager labelMgr = rm.rmContext.getNodeLabelManager(); rm.adminService.isDistributedNodeLabelConfiguration = true; // by default, distributed configuration for node label is disabled, this // should pass labelMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); rm.adminService .removeFromClusterNodeLabels(RemoveFromClusterNodeLabelsRequest .newInstance((Set<String>) ImmutableSet.of("x"))); Set<String> clusterNodeLabels = labelMgr.getClusterNodeLabelNames(); assertEquals(1,clusterNodeLabels.size()); rm.close(); } private String writeConfigurationXML(Configuration conf, String confXMLName) throws IOException { DataOutputStream output = null; try { final File confFile = new File(tmpDir.toString(), confXMLName); if (confFile.exists()) { confFile.delete(); } if (!confFile.createNewFile()) { Assert.fail("Can not create " + confXMLName); } output = new DataOutputStream( new FileOutputStream(confFile)); conf.writeXml(output); return confFile.getAbsolutePath(); } finally { if (output != null) { output.close(); } } } private void uploadToRemoteFileSystem(Path filePath) throws IOException { fs.copyFromLocalFile(filePath, workingPath); } private void uploadConfiguration(Configuration conf, String confFileName) throws IOException { String csConfFile = writeConfigurationXML(conf, confFileName); // upload the file into Remote File System uploadToRemoteFileSystem(new Path(csConfFile)); } private void uploadDefaultConfiguration() throws IOException { Configuration conf = new Configuration(); uploadConfiguration(conf, "core-site.xml"); YarnConfiguration yarnConf = new YarnConfiguration(); yarnConf.set(YarnConfiguration.RM_CONFIGURATION_PROVIDER_CLASS, "org.apache.hadoop.yarn.FileSystemBasedConfigurationProvider"); uploadConfiguration(yarnConf, "yarn-site.xml"); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); uploadConfiguration(csConf, "capacity-scheduler.xml"); Configuration hadoopPolicyConf = new Configuration(false); hadoopPolicyConf .addResource(YarnConfiguration.HADOOP_POLICY_CONFIGURATION_FILE); uploadConfiguration(hadoopPolicyConf, "hadoop-policy.xml"); } private static class MockUnixGroupsMapping implements GroupMappingServiceProvider { private static List<String> group = new ArrayList<String>(); @Override public List<String> getGroups(String user) throws IOException { return group; } @Override public void cacheGroupsRefresh() throws IOException { // Do nothing } @Override public void cacheGroupsAdd(List<String> groups) throws IOException { // Do nothing } public static void updateGroups() { group.clear(); group.add("test_group_D"); group.add("test_group_E"); group.add("test_group_F"); } public static void resetGroups() { group.clear(); group.add("test_group_A"); group.add("test_group_B"); group.add("test_group_C"); } } }
36,519
37.081335
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAuditLogger.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; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.net.InetAddress; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.Server; import org.apache.hadoop.ipc.TestRPC.TestImpl; import org.apache.hadoop.ipc.TestRPC.TestProtocol; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger.Keys; import org.junit.Before; import org.junit.Test; /** * Tests {@link RMAuditLogger}. */ public class TestRMAuditLogger { private static final String USER = "test"; private static final String OPERATION = "oper"; private static final String TARGET = "tgt"; private static final String PERM = "admin group"; private static final String DESC = "description of an audit log"; private static final ApplicationId APPID = mock(ApplicationId.class); private static final ApplicationAttemptId ATTEMPTID = mock(ApplicationAttemptId.class); private static final ContainerId CONTAINERID = mock(ContainerId.class); @Before public void setUp() throws Exception { when(APPID.toString()).thenReturn("app_1"); when(ATTEMPTID.toString()).thenReturn("app_attempt_1"); when(CONTAINERID.toString()).thenReturn("container_1"); } /** * Test the AuditLog format with key-val pair. */ @Test public void testKeyValLogFormat() throws Exception { StringBuilder actLog = new StringBuilder(); StringBuilder expLog = new StringBuilder(); // add the first k=v pair and check RMAuditLogger.start(Keys.USER, USER, actLog); expLog.append("USER=test"); assertEquals(expLog.toString(), actLog.toString()); // append another k1=v1 pair to already added k=v and test RMAuditLogger.add(Keys.OPERATION, OPERATION, actLog); expLog.append("\tOPERATION=oper"); assertEquals(expLog.toString(), actLog.toString()); // append another k1=null pair and test RMAuditLogger.add(Keys.APPID, (String)null, actLog); expLog.append("\tAPPID=null"); assertEquals(expLog.toString(), actLog.toString()); // now add the target and check of the final string RMAuditLogger.add(Keys.TARGET, TARGET, actLog); expLog.append("\tTARGET=tgt"); assertEquals(expLog.toString(), actLog.toString()); } /** * Test the AuditLog format for successful events. */ private void testSuccessLogFormatHelper(boolean checkIP, ApplicationId appId, ApplicationAttemptId attemptId, ContainerId containerId) { String sLog = RMAuditLogger.createSuccessLog(USER, OPERATION, TARGET, appId, attemptId, containerId); StringBuilder expLog = new StringBuilder(); expLog.append("USER=test\t"); if (checkIP) { InetAddress ip = Server.getRemoteIp(); expLog.append(Keys.IP.name() + "=" + ip.getHostAddress() + "\t"); } expLog.append("OPERATION=oper\tTARGET=tgt\tRESULT=SUCCESS"); if (appId != null) { expLog.append("\tAPPID=app_1"); } if (attemptId != null) { expLog.append("\tAPPATTEMPTID=app_attempt_1"); } if (containerId != null) { expLog.append("\tCONTAINERID=container_1"); } assertEquals(expLog.toString(), sLog); } /** * Test the AuditLog format for successful events passing nulls. */ private void testSuccessLogNulls(boolean checkIP) { String sLog = RMAuditLogger.createSuccessLog(null, null, null, null, null, null); StringBuilder expLog = new StringBuilder(); expLog.append("USER=null\t"); if (checkIP) { InetAddress ip = Server.getRemoteIp(); expLog.append(Keys.IP.name() + "=" + ip.getHostAddress() + "\t"); } expLog.append("OPERATION=null\tTARGET=null\tRESULT=SUCCESS"); assertEquals(expLog.toString(), sLog); } /** * Test the AuditLog format for successful events with the various * parameters. */ private void testSuccessLogFormat(boolean checkIP) { testSuccessLogFormatHelper(checkIP, null, null, null); testSuccessLogFormatHelper(checkIP, APPID, null, null); testSuccessLogFormatHelper(checkIP, null, null, CONTAINERID); testSuccessLogFormatHelper(checkIP, null, ATTEMPTID, null); testSuccessLogFormatHelper(checkIP, APPID, ATTEMPTID, null); testSuccessLogFormatHelper(checkIP, APPID, null, CONTAINERID); testSuccessLogFormatHelper(checkIP, null, ATTEMPTID, CONTAINERID); testSuccessLogFormatHelper(checkIP, APPID, ATTEMPTID, CONTAINERID); testSuccessLogNulls(checkIP); } /** * Test the AuditLog format for failure events. */ private void testFailureLogFormatHelper(boolean checkIP, ApplicationId appId, ApplicationAttemptId attemptId, ContainerId containerId) { String fLog = RMAuditLogger.createFailureLog(USER, OPERATION, PERM, TARGET, DESC, appId, attemptId, containerId); StringBuilder expLog = new StringBuilder(); expLog.append("USER=test\t"); if (checkIP) { InetAddress ip = Server.getRemoteIp(); expLog.append(Keys.IP.name() + "=" + ip.getHostAddress() + "\t"); } expLog.append("OPERATION=oper\tTARGET=tgt\tRESULT=FAILURE\t"); expLog.append("DESCRIPTION=description of an audit log"); expLog.append("\tPERMISSIONS=admin group"); if (appId != null) { expLog.append("\tAPPID=app_1"); } if (attemptId != null) { expLog.append("\tAPPATTEMPTID=app_attempt_1"); } if (containerId != null) { expLog.append("\tCONTAINERID=container_1"); } assertEquals(expLog.toString(), fLog); } /** * Test the AuditLog format for failure events with the various * parameters. */ private void testFailureLogFormat(boolean checkIP) { testFailureLogFormatHelper(checkIP, null, null, null); testFailureLogFormatHelper(checkIP, APPID, null, null); testFailureLogFormatHelper(checkIP, null, null, CONTAINERID); testFailureLogFormatHelper(checkIP, null, ATTEMPTID, null); testFailureLogFormatHelper(checkIP, APPID, ATTEMPTID, null); testFailureLogFormatHelper(checkIP, APPID, null, CONTAINERID); testFailureLogFormatHelper(checkIP, null, ATTEMPTID, CONTAINERID); testFailureLogFormatHelper(checkIP, APPID, ATTEMPTID, CONTAINERID); } /** * Test {@link RMAuditLogger} without IP set. */ @Test public void testRMAuditLoggerWithoutIP() throws Exception { // test without ip testSuccessLogFormat(false); testFailureLogFormat(false); } /** * A special extension of {@link TestImpl} RPC server with * {@link TestImpl#ping()} testing the audit logs. */ private class MyTestRPCServer extends TestImpl { @Override public void ping() { // test with ip set testSuccessLogFormat(true); testFailureLogFormat(true); } } /** * Test {@link RMAuditLogger} with IP set. */ @Test public void testRMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); // start the IPC server Server server = new RPC.Builder(conf).setProtocol(TestProtocol.class) .setInstance(new MyTestRPCServer()).setBindAddress("0.0.0.0") .setPort(0).setNumHandlers(5).setVerbose(true).build(); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); // Make a client connection and test the audit log TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); // Start the testcase proxy.ping(); server.stop(); } }
8,620
34.771784
89
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestKillApplicationWithRMHA.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; import static org.junit.Assert.fail; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.security.QueueACLsManager; import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.junit.Assert; import org.junit.Test; public class TestKillApplicationWithRMHA extends RMHATestBase{ public static final Log LOG = LogFactory .getLog(TestKillApplicationWithRMHA.class); @Test (timeout = 20000) public void testKillAppWhenFailoverHappensAtNewState() throws Exception { // create a customized RMAppManager // During the process of Application submission, // the RMAppState will always be NEW. // The ApplicationState will not be saved in RMStateStore. startRMsWithCustomizedRMAppManager(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // Submit the application RMApp app0 = rm1.submitApp(200, "", UserGroupInformation .getCurrentUser().getShortUserName(), null, false, null, configuration.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS), null, null, false, false); // failover and kill application // When FailOver happens, the state of this application is NEW, // and ApplicationState is not saved in RMStateStore. The active RM // can not load the ApplicationState of this application. // Expected to get ApplicationNotFoundException // when receives the KillApplicationRequest try { failOverAndKillApp(app0.getApplicationId(), RMAppState.NEW); fail("Should get an exception here"); } catch (ApplicationNotFoundException ex) { Assert.assertTrue(ex.getMessage().contains( "Trying to kill an absent application " + app0.getApplicationId())); } } @Test (timeout = 20000) public void testKillAppWhenFailoverHappensAtRunningState() throws Exception { startRMs(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // failover and kill application // The application is at RUNNING State when failOver happens. // Since RMStateStore has already saved ApplicationState, the active RM // will load the ApplicationState. After that, the application will be at // ACCEPTED State. Because the application is not at Final State, // KillApplicationResponse.getIsKillCompleted is expected to return false. failOverAndKillApp(app0.getApplicationId(), am0.getApplicationAttemptId(), RMAppState.RUNNING, RMAppAttemptState.RUNNING, RMAppState.ACCEPTED); } @Test (timeout = 20000) public void testKillAppWhenFailoverHappensAtFinalState() throws Exception { startRMs(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // kill the app. rm1.killApp(app0.getApplicationId()); rm1.waitForState(app0.getApplicationId(), RMAppState.KILLED); rm1.waitForState(am0.getApplicationAttemptId(), RMAppAttemptState.KILLED); // failover and kill application // The application is at Killed State and RMStateStore has already // saved this applicationState. After failover happens, the current // active RM will load the ApplicationState whose RMAppState is killed. // Because this application is at Final State, // KillApplicationResponse.getIsKillCompleted is expected to return true. failOverAndKillApp(app0.getApplicationId(), am0.getApplicationAttemptId(), RMAppState.KILLED, RMAppAttemptState.KILLED, RMAppState.KILLED); } @Test (timeout = 20000) public void testKillAppWhenFailOverHappensDuringApplicationKill() throws Exception { // create a customized ClientRMService // When receives the killApplicationRequest, simply return the response // and make sure the application will not be KILLED State startRMsWithCustomizedClientRMService(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(200); MockAM am0 = launchAM(app0, rm1, nm1); // ensure that the app is in running state Assert.assertEquals(app0.getState(), RMAppState.RUNNING); // kill the app. rm1.killApp(app0.getApplicationId()); // failover happens before this application goes to final state. // The RMAppState that will be loaded by the active rm // should be ACCEPTED. failOverAndKillApp(app0.getApplicationId(), am0.getApplicationAttemptId(), RMAppState.RUNNING, RMAppAttemptState.RUNNING, RMAppState.ACCEPTED); } private void failOverAndKillApp(ApplicationId appId, ApplicationAttemptId appAttemptId, RMAppState initialRMAppState, RMAppAttemptState initialRMAppAttemptState, RMAppState expectedAppStateBeforeKillApp) throws Exception { Assert.assertEquals(initialRMAppState, rm1.getRMContext().getRMApps().get(appId).getState()); Assert.assertEquals(initialRMAppAttemptState, rm1.getRMContext() .getRMApps().get(appId).getAppAttempts().get(appAttemptId).getState()); explicitFailover(); Assert.assertEquals(expectedAppStateBeforeKillApp, rm2.getRMContext().getRMApps().get(appId).getState()); killApplication(rm2, appId, appAttemptId, initialRMAppState); } private void failOverAndKillApp(ApplicationId appId, RMAppState initialRMAppState) throws Exception { Assert.assertEquals(initialRMAppState, rm1.getRMContext().getRMApps().get(appId).getState()); explicitFailover(); Assert.assertTrue(rm2.getRMContext().getRMApps().get(appId) == null); killApplication(rm2, appId, null, initialRMAppState); } private void startRMsWithCustomizedClientRMService() throws IOException { final Configuration conf1 = new Configuration(confForRM1); rm1 = new MockRM(conf1) { @Override protected ClientRMService createClientRMService() { return new MyClientRMService(this.rmContext, this.scheduler, this.rmAppManager, this.applicationACLsManager, this.queueACLsManager, getRMContext().getRMDelegationTokenSecretManager()); } }; rm2 = new MockRM(confForRM2); startRMs(rm1, conf1, rm2, confForRM2); } private static class MyClientRMService extends ClientRMService { private RMContext rmContext; public MyClientRMService(RMContext rmContext, YarnScheduler scheduler, RMAppManager rmAppManager, ApplicationACLsManager applicationACLsManager, QueueACLsManager queueACLsManager, RMDelegationTokenSecretManager rmDTSecretManager) { super(rmContext, scheduler, rmAppManager, applicationACLsManager, queueACLsManager, rmDTSecretManager); this.rmContext = rmContext; } @Override protected void serviceStart() { // override to not start rpc handler } @Override protected void serviceStop() { // don't do anything } @Override public KillApplicationResponse forceKillApplication( KillApplicationRequest request) throws YarnException { ApplicationId applicationId = request.getApplicationId(); RMApp application = this.rmContext.getRMApps().get(applicationId); if (application.isAppFinalStateStored()) { return KillApplicationResponse.newInstance(true); } else { return KillApplicationResponse.newInstance(false); } } } private void killApplication(MockRM rm, ApplicationId appId, ApplicationAttemptId appAttemptId, RMAppState rmAppState) throws Exception { KillApplicationResponse response = rm.killApp(appId); Assert .assertTrue(response.getIsKillCompleted() == isFinalState(rmAppState)); RMApp loadedApp0 = rm.getRMContext().getRMApps().get(appId); rm.waitForState(appId, RMAppState.KILLED); if (appAttemptId != null) { rm.waitForState(appAttemptId, RMAppAttemptState.KILLED); } // no new attempt is created. Assert.assertEquals(1, loadedApp0.getAppAttempts().size()); } }
10,379
38.923077
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNM.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; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse; import org.apache.hadoop.yarn.server.api.records.MasterKey; import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus; import org.apache.hadoop.yarn.server.api.records.NodeStatus; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.YarnVersionInfo; import org.mortbay.log.Log; public class MockNM { private int responseId; private NodeId nodeId; private final int memory; private final int vCores; private ResourceTrackerService resourceTracker; private int httpPort = 2; private MasterKey currentContainerTokenMasterKey; private MasterKey currentNMTokenMasterKey; private String version; public MockNM(String nodeIdStr, int memory, ResourceTrackerService resourceTracker) { // scale vcores based on the requested memory this(nodeIdStr, memory, Math.max(1, (memory * YarnConfiguration.DEFAULT_NM_VCORES) / YarnConfiguration.DEFAULT_NM_PMEM_MB), resourceTracker); } public MockNM(String nodeIdStr, int memory, int vcores, ResourceTrackerService resourceTracker) { this(nodeIdStr, memory, vcores, resourceTracker, YarnVersionInfo.getVersion()); } public MockNM(String nodeIdStr, int memory, int vcores, ResourceTrackerService resourceTracker, String version) { this.memory = memory; this.vCores = vcores; this.resourceTracker = resourceTracker; this.version = version; String[] splits = nodeIdStr.split(":"); nodeId = BuilderUtils.newNodeId(splits[0], Integer.parseInt(splits[1])); } public NodeId getNodeId() { return nodeId; } public int getHttpPort() { return httpPort; } public void setHttpPort(int port) { httpPort = port; } public void setResourceTrackerService(ResourceTrackerService resourceTracker) { this.resourceTracker = resourceTracker; } public void containerStatus(ContainerStatus containerStatus) throws Exception { Map<ApplicationId, List<ContainerStatus>> conts = new HashMap<ApplicationId, List<ContainerStatus>>(); conts.put(containerStatus.getContainerId().getApplicationAttemptId().getApplicationId(), Arrays.asList(new ContainerStatus[] { containerStatus })); nodeHeartbeat(conts, true); } public RegisterNodeManagerResponse registerNode() throws Exception { return registerNode(null, null); } public RegisterNodeManagerResponse registerNode( List<ApplicationId> runningApplications) throws Exception { return registerNode(null, runningApplications); } public RegisterNodeManagerResponse registerNode( List<NMContainerStatus> containerReports, List<ApplicationId> runningApplications) throws Exception { RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); req.setNodeId(nodeId); req.setHttpPort(httpPort); Resource resource = BuilderUtils.newResource(memory, vCores); req.setResource(resource); req.setContainerStatuses(containerReports); req.setNMVersion(version); req.setRunningApplications(runningApplications); RegisterNodeManagerResponse registrationResponse = resourceTracker.registerNodeManager(req); this.currentContainerTokenMasterKey = registrationResponse.getContainerTokenMasterKey(); this.currentNMTokenMasterKey = registrationResponse.getNMTokenMasterKey(); return registrationResponse; } public NodeHeartbeatResponse nodeHeartbeat(boolean isHealthy) throws Exception { return nodeHeartbeat(new HashMap<ApplicationId, List<ContainerStatus>>(), isHealthy, ++responseId); } public NodeHeartbeatResponse nodeHeartbeat(ApplicationAttemptId attemptId, long containerId, ContainerState containerState) throws Exception { HashMap<ApplicationId, List<ContainerStatus>> nodeUpdate = new HashMap<ApplicationId, List<ContainerStatus>>(1); ContainerStatus containerStatus = BuilderUtils.newContainerStatus( BuilderUtils.newContainerId(attemptId, containerId), containerState, "Success", 0); ArrayList<ContainerStatus> containerStatusList = new ArrayList<ContainerStatus>(1); containerStatusList.add(containerStatus); Log.info("ContainerStatus: " + containerStatus); nodeUpdate.put(attemptId.getApplicationId(), containerStatusList); return nodeHeartbeat(nodeUpdate, true); } public NodeHeartbeatResponse nodeHeartbeat(Map<ApplicationId, List<ContainerStatus>> conts, boolean isHealthy) throws Exception { return nodeHeartbeat(conts, isHealthy, ++responseId); } public NodeHeartbeatResponse nodeHeartbeat(Map<ApplicationId, List<ContainerStatus>> conts, boolean isHealthy, int resId) throws Exception { NodeHeartbeatRequest req = Records.newRecord(NodeHeartbeatRequest.class); NodeStatus status = Records.newRecord(NodeStatus.class); status.setResponseId(resId); status.setNodeId(nodeId); for (Map.Entry<ApplicationId, List<ContainerStatus>> entry : conts.entrySet()) { Log.info("entry.getValue() " + entry.getValue()); status.setContainersStatuses(entry.getValue()); } NodeHealthStatus healthStatus = Records.newRecord(NodeHealthStatus.class); healthStatus.setHealthReport(""); healthStatus.setIsNodeHealthy(isHealthy); healthStatus.setLastHealthReportTime(1); status.setNodeHealthStatus(healthStatus); req.setNodeStatus(status); req.setLastKnownContainerTokenMasterKey(this.currentContainerTokenMasterKey); req.setLastKnownNMTokenMasterKey(this.currentNMTokenMasterKey); NodeHeartbeatResponse heartbeatResponse = resourceTracker.nodeHeartbeat(req); MasterKey masterKeyFromRM = heartbeatResponse.getContainerTokenMasterKey(); if (masterKeyFromRM != null && masterKeyFromRM.getKeyId() != this.currentContainerTokenMasterKey .getKeyId()) { this.currentContainerTokenMasterKey = masterKeyFromRM; } masterKeyFromRM = heartbeatResponse.getNMTokenMasterKey(); if (masterKeyFromRM != null && masterKeyFromRM.getKeyId() != this.currentNMTokenMasterKey .getKeyId()) { this.currentNMTokenMasterKey = masterKeyFromRM; } return heartbeatResponse; } public int getMemory() { return memory; } public int getvCores() { return vCores; } }
8,169
38.660194
92
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterService.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; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.proto.YarnServiceProtos.SchedulerResourceTypes; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; 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.fair.FairScheduler; import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.AllocateRequestPBImpl; import org.apache.hadoop.yarn.api.records.*; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException; import org.apache.hadoop.yarn.exceptions.InvalidContainerReleaseException; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.*; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Assert; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.lang.Thread.sleep; public class TestApplicationMasterService { private static final Log LOG = LogFactory .getLog(TestApplicationMasterService.class); private final int GB = 1024; private static YarnConfiguration conf; @BeforeClass public static void setup() { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); } @Test(timeout = 3000000) public void testRMIdentifierOnContainerAllocation() throws Exception { MockRM rm = new MockRM(conf); rm.start(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); // Submit an application RMApp app1 = rm.submitApp(2048); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); am1.addRequests(new String[] { "127.0.0.1" }, GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); // send the request // kick the scheduler nm1.nodeHeartbeat(true); while (alloc1Response.getAllocatedContainers().size() < 1) { LOG.info("Waiting for containers to be created for app 1..."); sleep(1000); alloc1Response = am1.schedule(); } // assert RMIdentifer is set properly in allocated containers Container allocatedContainer = alloc1Response.getAllocatedContainers().get(0); ContainerTokenIdentifier tokenId = BuilderUtils.newContainerTokenIdentifier(allocatedContainer .getContainerToken()); Assert.assertEquals(MockRM.getClusterTimeStamp(), tokenId.getRMIdentifier()); rm.stop(); } @Test(timeout=600000) public void testInvalidContainerReleaseRequest() throws Exception { MockRM rm = new MockRM(conf); try { rm.start(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); // Submit an application RMApp app1 = rm.submitApp(1024); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); am1.addRequests(new String[] { "127.0.0.1" }, GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); // send the request // kick the scheduler nm1.nodeHeartbeat(true); while (alloc1Response.getAllocatedContainers().size() < 1) { LOG.info("Waiting for containers to be created for app 1..."); sleep(1000); alloc1Response = am1.schedule(); } Assert.assertTrue(alloc1Response.getAllocatedContainers().size() > 0); RMApp app2 = rm.submitApp(1024); nm1.nodeHeartbeat(true); RMAppAttempt attempt2 = app2.getCurrentAppAttempt(); MockAM am2 = rm.sendAMLaunched(attempt2.getAppAttemptId()); am2.registerAppAttempt(); // Now trying to release container allocated for app1 -> appAttempt1. ContainerId cId = alloc1Response.getAllocatedContainers().get(0).getId(); am2.addContainerToBeReleased(cId); try { am2.schedule(); Assert.fail("Exception was expected!!"); } catch (InvalidContainerReleaseException e) { StringBuilder sb = new StringBuilder("Cannot release container : "); sb.append(cId.toString()); sb.append(" not belonging to this application attempt : "); sb.append(attempt2.getAppAttemptId().toString()); Assert.assertTrue(e.getMessage().contains(sb.toString())); } } finally { if (rm != null) { rm.stop(); } } } @Test(timeout=1200000) public void testProgressFilter() throws Exception{ MockRM rm = new MockRM(conf); rm.start(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); // Submit an application RMApp app1 = rm.submitApp(2048); nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); AllocateRequestPBImpl allocateRequest = new AllocateRequestPBImpl(); List<ContainerId> release = new ArrayList<ContainerId>(); List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); allocateRequest.setReleaseList(release); allocateRequest.setAskList(ask); allocateRequest.setProgress(Float.POSITIVE_INFINITY); am1.allocate(allocateRequest); while(attempt1.getProgress()!=1){ LOG.info("Waiting for allocate event to be handled ..."); sleep(100); } allocateRequest.setProgress(Float.NaN); am1.allocate(allocateRequest); while(attempt1.getProgress()!=0){ LOG.info("Waiting for allocate event to be handled ..."); sleep(100); } allocateRequest.setProgress((float)9); am1.allocate(allocateRequest); while(attempt1.getProgress()!=1){ LOG.info("Waiting for allocate event to be handled ..."); sleep(100); } allocateRequest.setProgress(Float.NEGATIVE_INFINITY); am1.allocate(allocateRequest); while(attempt1.getProgress()!=0){ LOG.info("Waiting for allocate event to be handled ..."); sleep(100); } allocateRequest.setProgress((float)0.5); am1.allocate(allocateRequest); while(attempt1.getProgress()!=0.5){ LOG.info("Waiting for allocate event to be handled ..."); sleep(100); } allocateRequest.setProgress((float)-1); am1.allocate(allocateRequest); while(attempt1.getProgress()!=0){ LOG.info("Waiting for allocate event to be handled ..."); sleep(100); } } @Test(timeout=1200000) public void testFinishApplicationMasterBeforeRegistering() throws Exception { MockRM rm = new MockRM(conf); try { rm.start(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); // Submit an application RMApp app1 = rm.submitApp(2048); MockAM am1 = MockRM.launchAM(app1, rm, nm1); FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.FAILED, "", ""); try { am1.unregisterAppAttempt(req, false); Assert.fail("ApplicationMasterNotRegisteredException should be thrown"); } catch (ApplicationMasterNotRegisteredException e) { Assert.assertNotNull(e); Assert.assertNotNull(e.getMessage()); Assert.assertTrue(e.getMessage().contains( "Application Master is trying to unregister before registering for:" )); } catch (Exception e) { Assert.fail("ApplicationMasterNotRegisteredException should be thrown"); } am1.registerAppAttempt(); am1.unregisterAppAttempt(req, false); am1.waitForState(RMAppAttemptState.FINISHING); } finally { if (rm != null) { rm.stop(); } } } @Test(timeout = 3000000) public void testResourceTypes() throws Exception { HashMap<YarnConfiguration, EnumSet<SchedulerResourceTypes>> driver = new HashMap<YarnConfiguration, EnumSet<SchedulerResourceTypes>>(); CapacitySchedulerConfiguration csconf = new CapacitySchedulerConfiguration(); csconf.setResourceComparator(DominantResourceCalculator.class); YarnConfiguration testCapacityDRConf = new YarnConfiguration(csconf); testCapacityDRConf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); YarnConfiguration testCapacityDefConf = new YarnConfiguration(); testCapacityDefConf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); YarnConfiguration testFairDefConf = new YarnConfiguration(); testFairDefConf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class, ResourceScheduler.class); driver.put(conf, EnumSet.of(SchedulerResourceTypes.MEMORY)); driver.put(testCapacityDRConf, EnumSet.of(SchedulerResourceTypes.CPU, SchedulerResourceTypes.MEMORY)); driver.put(testCapacityDefConf, EnumSet.of(SchedulerResourceTypes.MEMORY)); driver.put(testFairDefConf, EnumSet.of(SchedulerResourceTypes.MEMORY, SchedulerResourceTypes.CPU)); for (Map.Entry<YarnConfiguration, EnumSet<SchedulerResourceTypes>> entry : driver .entrySet()) { EnumSet<SchedulerResourceTypes> expectedValue = entry.getValue(); MockRM rm = new MockRM(entry.getKey()); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); RMApp app1 = rm.submitApp(2048); nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); RegisterApplicationMasterResponse resp = am1.registerAppAttempt(); EnumSet<SchedulerResourceTypes> types = resp.getSchedulerResourceTypes(); LOG.info("types = " + types.toString()); Assert.assertEquals(expectedValue, types); rm.stop(); } } @Test(timeout=1200000) public void testAllocateAfterUnregister() throws Exception { MyResourceManager rm = new MyResourceManager(conf); rm.start(); DrainDispatcher rmDispatcher = (DrainDispatcher) rm.getRMContext() .getDispatcher(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); // Submit an application RMApp app1 = rm.submitApp(2048); nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); // unregister app attempt FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.KILLED, "", ""); am1.unregisterAppAttempt(req, false); // request container after unregister am1.addRequests(new String[] { "127.0.0.1" }, GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); nm1.nodeHeartbeat(true); rmDispatcher.await(); alloc1Response = am1.schedule(); Assert.assertEquals(0, alloc1Response.getAllocatedContainers().size()); } private static class MyResourceManager extends MockRM { public MyResourceManager(YarnConfiguration conf) { super(conf); } @Override protected Dispatcher createDispatcher() { return new DrainDispatcher(); } } }
13,281
36.100559
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/NodeManager.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; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.junit.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.yarn.api.ContainerManagementProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesResponse; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersResponse; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.StopContainersResponse; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus; import org.apache.hadoop.yarn.server.api.records.NodeStatus; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.YarnVersionInfo; import org.apache.hadoop.yarn.util.resource.Resources; @Private public class NodeManager implements ContainerManagementProtocol { private static final Log LOG = LogFactory.getLog(NodeManager.class); private static final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); final private String containerManagerAddress; final private String nodeHttpAddress; final private String rackName; final private NodeId nodeId; final private Resource capability; final private ResourceManager resourceManager; Resource available = recordFactory.newRecordInstance(Resource.class); Resource used = recordFactory.newRecordInstance(Resource.class); final ResourceTrackerService resourceTrackerService; final Map<ApplicationId, List<Container>> containers = new HashMap<ApplicationId, List<Container>>(); final Map<Container, ContainerStatus> containerStatusMap = new HashMap<Container, ContainerStatus>(); public NodeManager(String hostName, int containerManagerPort, int httpPort, String rackName, Resource capability, ResourceManager resourceManager) throws IOException, YarnException { this.containerManagerAddress = hostName + ":" + containerManagerPort; this.nodeHttpAddress = hostName + ":" + httpPort; this.rackName = rackName; this.resourceTrackerService = resourceManager.getResourceTrackerService(); this.capability = capability; Resources.addTo(available, capability); this.nodeId = NodeId.newInstance(hostName, containerManagerPort); RegisterNodeManagerRequest request = recordFactory .newRecordInstance(RegisterNodeManagerRequest.class); request.setHttpPort(httpPort); request.setResource(capability); request.setNodeId(this.nodeId); request.setNMVersion(YarnVersionInfo.getVersion()); resourceTrackerService.registerNodeManager(request); this.resourceManager = resourceManager; resourceManager.getResourceScheduler().getNodeReport(this.nodeId); } public String getHostName() { return containerManagerAddress; } public String getRackName() { return rackName; } public NodeId getNodeId() { return nodeId; } public Resource getCapability() { return capability; } public Resource getAvailable() { return available; } public Resource getUsed() { return used; } int responseID = 0; private List<ContainerStatus> getContainerStatuses(Map<ApplicationId, List<Container>> containers) { List<ContainerStatus> containerStatuses = new ArrayList<ContainerStatus>(); for (List<Container> appContainers : containers.values()) { for (Container container : appContainers) { containerStatuses.add(containerStatusMap.get(container)); } } return containerStatuses; } public void heartbeat() throws IOException, YarnException { NodeStatus nodeStatus = org.apache.hadoop.yarn.server.resourcemanager.NodeManager.createNodeStatus( nodeId, getContainerStatuses(containers)); nodeStatus.setResponseId(responseID); NodeHeartbeatRequest request = recordFactory .newRecordInstance(NodeHeartbeatRequest.class); request.setNodeStatus(nodeStatus); NodeHeartbeatResponse response = resourceTrackerService .nodeHeartbeat(request); responseID = response.getResponseId(); } @Override synchronized public StartContainersResponse startContainers( StartContainersRequest requests) throws YarnException { for (StartContainerRequest request : requests.getStartContainerRequests()) { Token containerToken = request.getContainerToken(); ContainerTokenIdentifier tokenId = null; try { tokenId = BuilderUtils.newContainerTokenIdentifier(containerToken); } catch (IOException e) { throw RPCUtil.getRemoteException(e); } ContainerId containerID = tokenId.getContainerID(); ApplicationId applicationId = containerID.getApplicationAttemptId().getApplicationId(); List<Container> applicationContainers = containers.get(applicationId); if (applicationContainers == null) { applicationContainers = new ArrayList<Container>(); containers.put(applicationId, applicationContainers); } // Sanity check for (Container container : applicationContainers) { if (container.getId().compareTo(containerID) == 0) { throw new IllegalStateException("Container " + containerID + " already setup on node " + containerManagerAddress); } } Container container = BuilderUtils.newContainer(containerID, this.nodeId, nodeHttpAddress, tokenId.getResource(), null, null // DKDC - Doesn't matter ); ContainerStatus containerStatus = BuilderUtils.newContainerStatus(container.getId(), ContainerState.NEW, "", -1000); applicationContainers.add(container); containerStatusMap.put(container, containerStatus); Resources.subtractFrom(available, tokenId.getResource()); Resources.addTo(used, tokenId.getResource()); if (LOG.isDebugEnabled()) { LOG.debug("startContainer:" + " node=" + containerManagerAddress + " application=" + applicationId + " container=" + container + " available=" + available + " used=" + used); } } StartContainersResponse response = StartContainersResponse.newInstance(null, null, null); return response; } synchronized public void checkResourceUsage() { LOG.info("Checking resource usage for " + containerManagerAddress); Assert.assertEquals(available.getMemory(), resourceManager.getResourceScheduler().getNodeReport( this.nodeId).getAvailableResource().getMemory()); Assert.assertEquals(used.getMemory(), resourceManager.getResourceScheduler().getNodeReport( this.nodeId).getUsedResource().getMemory()); } @Override synchronized public StopContainersResponse stopContainers(StopContainersRequest request) throws YarnException { for (ContainerId containerID : request.getContainerIds()) { String applicationId = String.valueOf(containerID.getApplicationAttemptId() .getApplicationId().getId()); // Mark the container as COMPLETE List<Container> applicationContainers = containers.get(containerID.getApplicationAttemptId() .getApplicationId()); for (Container c : applicationContainers) { if (c.getId().compareTo(containerID) == 0) { ContainerStatus containerStatus = containerStatusMap.get(c); containerStatus.setState(ContainerState.COMPLETE); containerStatusMap.put(c, containerStatus); } } // Send a heartbeat try { heartbeat(); } catch (IOException ioe) { throw RPCUtil.getRemoteException(ioe); } // Remove container and update status int ctr = 0; Container container = null; for (Iterator<Container> i = applicationContainers.iterator(); i .hasNext();) { container = i.next(); if (container.getId().compareTo(containerID) == 0) { i.remove(); ++ctr; } } if (ctr != 1) { throw new IllegalStateException("Container " + containerID + " stopped " + ctr + " times!"); } Resources.addTo(available, container.getResource()); Resources.subtractFrom(used, container.getResource()); if (LOG.isDebugEnabled()) { LOG.debug("stopContainer:" + " node=" + containerManagerAddress + " application=" + applicationId + " container=" + containerID + " available=" + available + " used=" + used); } } return StopContainersResponse.newInstance(null,null); } @Override synchronized public GetContainerStatusesResponse getContainerStatuses( GetContainerStatusesRequest request) throws YarnException { List<ContainerStatus> statuses = new ArrayList<ContainerStatus>(); for (ContainerId containerId : request.getContainerIds()) { List<Container> appContainers = containers.get(containerId.getApplicationAttemptId() .getApplicationId()); Container container = null; for (Container c : appContainers) { if (c.getId().equals(containerId)) { container = c; } } if (container != null && containerStatusMap.get(container).getState() != null) { statuses.add(containerStatusMap.get(container)); } } return GetContainerStatusesResponse.newInstance(statuses, null); } public static org.apache.hadoop.yarn.server.api.records.NodeStatus createNodeStatus(NodeId nodeId, List<ContainerStatus> containers) { RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); org.apache.hadoop.yarn.server.api.records.NodeStatus nodeStatus = recordFactory.newRecordInstance(org.apache.hadoop.yarn.server.api.records.NodeStatus.class); nodeStatus.setNodeId(nodeId); nodeStatus.setContainersStatuses(containers); NodeHealthStatus nodeHealthStatus = recordFactory.newRecordInstance(NodeHealthStatus.class); nodeHealthStatus.setIsNodeHealthy(true); nodeStatus.setNodeHealthStatus(nodeHealthStatus); return nodeStatus; } }
12,380
38.682692
102
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.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; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.hadoop.net.Node; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; /** * Test helper to generate mock nodes */ public class MockNodes { private static int NODE_ID = 0; private static RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public static List<RMNode> newNodes(int racks, int nodesPerRack, Resource perNode) { List<RMNode> list = Lists.newArrayList(); for (int i = 0; i < racks; ++i) { for (int j = 0; j < nodesPerRack; ++j) { if (j == (nodesPerRack - 1)) { // One unhealthy node per rack. list.add(nodeInfo(i, perNode, NodeState.UNHEALTHY)); } if (j == 0) { // One node with label list.add(nodeInfo(i, perNode, NodeState.RUNNING, ImmutableSet.of("x"))); } else { list.add(newNodeInfo(i, perNode)); } } } return list; } public static List<RMNode> deactivatedNodes(int racks, int nodesPerRack, Resource perNode) { List<RMNode> list = Lists.newArrayList(); for (int i = 0; i < racks; ++i) { for (int j = 0; j < nodesPerRack; ++j) { NodeState[] allStates = NodeState.values(); list.add(nodeInfo(i, perNode, allStates[j % allStates.length])); } } return list; } public static Resource newResource(int mem) { Resource rs = recordFactory.newRecordInstance(Resource.class); rs.setMemory(mem); return rs; } public static Resource newUsedResource(Resource total) { Resource rs = recordFactory.newRecordInstance(Resource.class); rs.setMemory((int)(Math.random() * total.getMemory())); return rs; } public static Resource newAvailResource(Resource total, Resource used) { Resource rs = recordFactory.newRecordInstance(Resource.class); rs.setMemory(total.getMemory() - used.getMemory()); return rs; } private static class MockRMNodeImpl implements RMNode { private NodeId nodeId; private String hostName; private String nodeAddr; private String httpAddress; private int cmdPort; private Resource perNode; private String rackName; private String healthReport; private long lastHealthReportTime; private NodeState state; private Set<String> labels; public MockRMNodeImpl(NodeId nodeId, String nodeAddr, String httpAddress, Resource perNode, String rackName, String healthReport, long lastHealthReportTime, int cmdPort, String hostName, NodeState state, Set<String> labels) { this.nodeId = nodeId; this.nodeAddr = nodeAddr; this.httpAddress = httpAddress; this.perNode = perNode; this.rackName = rackName; this.healthReport = healthReport; this.lastHealthReportTime = lastHealthReportTime; this.cmdPort = cmdPort; this.hostName = hostName; this.state = state; this.labels = labels; } @Override public NodeId getNodeID() { return this.nodeId; } @Override public String getHostName() { return this.hostName; } @Override public int getCommandPort() { return this.cmdPort; } @Override public int getHttpPort() { return 0; } @Override public String getNodeAddress() { return this.nodeAddr; } @Override public String getHttpAddress() { return this.httpAddress; } @Override public Resource getTotalCapability() { return this.perNode; } @Override public String getRackName() { return this.rackName; } @Override public Node getNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public NodeState getState() { return this.state; } @Override public List<ContainerId> getContainersToCleanUp() { return null; } @Override public List<ApplicationId> getAppsToCleanup() { return null; } @Override public List<ApplicationId> getRunningApps() { return null; } @Override public void updateNodeHeartbeatResponseForCleanup(NodeHeartbeatResponse response) { } @Override public NodeHeartbeatResponse getLastNodeHeartBeatResponse() { return null; } @Override public String getNodeManagerVersion() { return null; } @Override public List<UpdatedContainerInfo> pullContainerUpdates() { return new ArrayList<UpdatedContainerInfo>(); } @Override public String getHealthReport() { return healthReport; } @Override public long getLastHealthReportTime() { return lastHealthReportTime; } @Override public Set<String> getNodeLabels() { if (labels != null) { return labels; } return CommonNodeLabelsManager.EMPTY_STRING_SET; } }; private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr) { return buildRMNode(rack, perNode, state, httpAddr, null); } private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr, Set<String> labels) { return buildRMNode(rack, perNode, state, httpAddr, NODE_ID++, null, 123, labels); } private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr, int hostnum, String hostName, int port) { return buildRMNode(rack, perNode, state, httpAddr, hostnum, hostName, port, null); } private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr, int hostnum, String hostName, int port, Set<String> labels) { final String rackName = "rack"+ rack; final int nid = hostnum; final String nodeAddr = hostName + ":" + nid; if (hostName == null) { hostName = "host"+ nid; } final NodeId nodeID = NodeId.newInstance(hostName, port); final String httpAddress = httpAddr; String healthReport = (state == NodeState.UNHEALTHY) ? null : "HealthyMe"; return new MockRMNodeImpl(nodeID, nodeAddr, httpAddress, perNode, rackName, healthReport, 0, nid, hostName, state, labels); } public static RMNode nodeInfo(int rack, final Resource perNode, NodeState state) { return buildRMNode(rack, perNode, state, "N/A"); } public static RMNode nodeInfo(int rack, final Resource perNode, NodeState state, Set<String> labels) { return buildRMNode(rack, perNode, state, "N/A", labels); } public static RMNode newNodeInfo(int rack, final Resource perNode) { return buildRMNode(rack, perNode, NodeState.RUNNING, "localhost:0"); } public static RMNode newNodeInfo(int rack, final Resource perNode, int hostnum) { return buildRMNode(rack, perNode, null, "localhost:0", hostnum, null, 123); } public static RMNode newNodeInfo(int rack, final Resource perNode, int hostnum, String hostName) { return buildRMNode(rack, perNode, null, "localhost:0", hostnum, hostName, 123); } public static RMNode newNodeInfo(int rack, final Resource perNode, int hostnum, String hostName, int port) { return buildRMNode(rack, perNode, null, "localhost:0", hostnum, hostName, port); } }
9,025
29.59661
92
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRM.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; import org.junit.Before; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.junit.After; import org.junit.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.NMToken; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AbstractEvent; 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.server.resourcemanager.TestRMRestart.TestSecurityMockRM; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; 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.RMAppState; 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.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @SuppressWarnings({"unchecked", "rawtypes"}) public class TestRM extends ParameterizedSchedulerTestBase { private static final Log LOG = LogFactory.getLog(TestRM.class); // Milliseconds to sleep for when waiting for something to happen private final static int WAIT_SLEEP_MS = 100; private YarnConfiguration conf; public TestRM(SchedulerType type) { super(type); } @Before public void setup() { conf = getConf(); } @After public void tearDown() { ClusterMetrics.destroy(); QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.shutdown(); } @Test public void testGetNewAppId() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); MockRM rm = new MockRM(conf); rm.start(); GetNewApplicationResponse resp = rm.getNewAppId(); assert (resp.getApplicationId().getId() != 0); assert (resp.getMaximumResourceCapability().getMemory() > 0); rm.stop(); } @Test (timeout = 30000) public void testAppWithNoContainers() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 5120); RMApp app = rm.submitApp(2000); //kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); am.unregisterAppAttempt(); nm1.nodeHeartbeat(attempt.getAppAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); rm.stop(); } @Test (timeout = 30000) public void testAppOnMultiNode() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); conf.set("yarn.scheduler.capacity.node-locality-delay", "-1"); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 5120); MockNM nm2 = rm.registerNode("h2:5678", 10240); RMApp app = rm.submitApp(2000); //kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); //request for containers int request = 13; am.allocate("h1" , 1000, request, new ArrayList<ContainerId>()); //kick the scheduler List<Container> conts = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); int contReceived = conts.size(); while (contReceived < 3) {//only 3 containers are available on node1 nm1.nodeHeartbeat(true); conts.addAll(am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); contReceived = conts.size(); LOG.info("Got " + contReceived + " containers. Waiting to get " + 3); Thread.sleep(WAIT_SLEEP_MS); } Assert.assertEquals(3, conts.size()); //send node2 heartbeat conts = am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); contReceived = conts.size(); while (contReceived < 10) { nm2.nodeHeartbeat(true); conts.addAll(am.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); contReceived = conts.size(); LOG.info("Got " + contReceived + " containers. Waiting to get " + 10); Thread.sleep(WAIT_SLEEP_MS); } Assert.assertEquals(10, conts.size()); am.unregisterAppAttempt(); nm1.nodeHeartbeat(attempt.getAppAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); rm.stop(); } // Test even if AM container is allocated with containerId not equal to 1, the // following allocate requests from AM should be able to retrieve the // corresponding NM Token. @Test (timeout = 20000) public void testNMTokenSentForNormalContainer() throws Exception { conf.set(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class.getCanonicalName()); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 5120); RMApp app = rm.submitApp(2000); RMAppAttempt attempt = app.getCurrentAppAttempt(); // Call getNewContainerId to increase container Id so that the AM container // Id doesn't equal to one. CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); cs.getApplicationAttempt(attempt.getAppAttemptId()).getNewContainerId(); // kick the scheduling nm1.nodeHeartbeat(true); MockAM am = MockRM.launchAM(app, rm, nm1); // am container Id not equal to 1. Assert.assertTrue( attempt.getMasterContainer().getId().getContainerId() != 1); // NMSecretManager doesn't record the node on which the am is allocated. Assert.assertFalse(rm.getRMContext().getNMTokenSecretManager() .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm1.getNodeId())); am.registerAppAttempt(); rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); int NUM_CONTAINERS = 1; List<Container> containers = new ArrayList<Container>(); // nmTokens keeps track of all the nmTokens issued in the allocate call. List<NMToken> expectedNMTokens = new ArrayList<NMToken>(); // am1 allocate 1 container on nm1. while (true) { AllocateResponse response = am.allocate("127.0.0.1", 2000, NUM_CONTAINERS, new ArrayList<ContainerId>()); nm1.nodeHeartbeat(true); containers.addAll(response.getAllocatedContainers()); expectedNMTokens.addAll(response.getNMTokens()); if (containers.size() == NUM_CONTAINERS) { break; } Thread.sleep(200); System.out.println("Waiting for container to be allocated."); } NodeId nodeId = expectedNMTokens.get(0).getNodeId(); // NMToken is sent for the allocated container. Assert.assertEquals(nm1.getNodeId(), nodeId); } @Test (timeout = 40000) public void testNMToken() throws Exception { MockRM rm = new MockRM(conf); try { rm.start(); MockNM nm1 = rm.registerNode("h1:1234", 10000); NMTokenSecretManagerInRM nmTokenSecretManager = rm.getRMContext().getNMTokenSecretManager(); // submitting new application RMApp app = rm.submitApp(1000); // start scheduling. nm1.nodeHeartbeat(true); // Starting application attempt and launching // It should get registered with NMTokenSecretManager. RMAppAttempt attempt = app.getCurrentAppAttempt(); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptRegistered(attempt.getAppAttemptId())); // This will register application master. am.registerAppAttempt(); ArrayList<Container> containersReceivedForNM1 = new ArrayList<Container>(); List<ContainerId> releaseContainerList = new ArrayList<ContainerId>(); HashMap<String, Token> nmTokens = new HashMap<String, Token>(); // initially requesting 2 containers. AllocateResponse response = am.allocate("h1", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM1, 2, nmTokens, nm1); Assert.assertEquals(1, nmTokens.size()); // requesting 2 more containers. response = am.allocate("h1", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM1, 4, nmTokens, nm1); Assert.assertEquals(1, nmTokens.size()); // We will be simulating NM restart so restarting newly added h2:1234 // NM 2 now registers. MockNM nm2 = rm.registerNode("h2:1234", 10000); nm2.nodeHeartbeat(true); ArrayList<Container> containersReceivedForNM2 = new ArrayList<Container>(); response = am.allocate("h2", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 2, nmTokens, nm2); Assert.assertEquals(2, nmTokens.size()); // Simulating NM-2 restart. nm2 = rm.registerNode("h2:1234", 10000); // Wait for reconnect to make it through the RM and create a new RMNode Map<NodeId, RMNode> nodes = rm.getRMContext().getRMNodes(); while (nodes.get(nm2.getNodeId()).getLastNodeHeartBeatResponse() .getResponseId() > 0) { Thread.sleep(WAIT_SLEEP_MS); } int interval = 40; // Wait for nm Token to be cleared. while (nmTokenSecretManager .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId()) && interval-- > 0) { LOG.info("waiting for nmToken to be cleared for : " + nm2.getNodeId()); Thread.sleep(WAIT_SLEEP_MS); } Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptRegistered(attempt.getAppAttemptId())); // removing NMToken for h2:1234 nmTokens.remove(nm2.getNodeId().toString()); Assert.assertEquals(1, nmTokens.size()); // We should again receive the NMToken. response = am.allocate("h2", 1000, 2, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 4, nmTokens, nm2); Assert.assertEquals(2, nmTokens.size()); // Now rolling over NMToken masterKey. it should resend the NMToken in // next allocate call. Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm1.getNodeId())); Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId())); nmTokenSecretManager.rollMasterKey(); nmTokenSecretManager.activateNextMasterKey(); Assert.assertFalse(nmTokenSecretManager .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm1.getNodeId())); Assert.assertFalse(nmTokenSecretManager .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId())); // It should not remove application attempt entry. Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptRegistered(attempt.getAppAttemptId())); nmTokens.clear(); Assert.assertEquals(0, nmTokens.size()); // We should again receive the NMToken. response = am.allocate("h2", 1000, 1, releaseContainerList); Assert.assertEquals(0, response.getAllocatedContainers().size()); allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 5, nmTokens, nm2); Assert.assertEquals(1, nmTokens.size()); Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(), nm2.getNodeId())); // After AM is finished making sure that nmtoken entry for app Assert.assertTrue(nmTokenSecretManager .isApplicationAttemptRegistered(attempt.getAppAttemptId())); am.unregisterAppAttempt(); // marking all the containers as finished. for (Container container : containersReceivedForNM1) { nm1.nodeHeartbeat(attempt.getAppAttemptId(), container.getId().getContainerId(), ContainerState.COMPLETE); } for (Container container : containersReceivedForNM2) { nm2.nodeHeartbeat(attempt.getAppAttemptId(), container.getId().getContainerId(), ContainerState.COMPLETE); } nm1.nodeHeartbeat(am.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am.waitForState(RMAppAttemptState.FINISHED); Assert.assertFalse(nmTokenSecretManager .isApplicationAttemptRegistered(attempt.getAppAttemptId())); } finally { rm.stop(); } } protected void allocateContainersAndValidateNMTokens(MockAM am, ArrayList<Container> containersReceived, int totalContainerRequested, HashMap<String, Token> nmTokens, MockNM nm) throws Exception, InterruptedException { ArrayList<ContainerId> releaseContainerList = new ArrayList<ContainerId>(); AllocateResponse response; ArrayList<ResourceRequest> resourceRequest = new ArrayList<ResourceRequest>(); while (containersReceived.size() < totalContainerRequested) { nm.nodeHeartbeat(true); LOG.info("requesting containers.."); response = am.allocate(resourceRequest, releaseContainerList); containersReceived.addAll(response.getAllocatedContainers()); if (!response.getNMTokens().isEmpty()) { for (NMToken nmToken : response.getNMTokens()) { String nodeId = nmToken.getNodeId().toString(); if (nmTokens.containsKey(nodeId)) { Assert.fail("Duplicate NMToken received for : " + nodeId); } nmTokens.put(nodeId, nmToken.getToken()); } } LOG.info("Got " + containersReceived.size() + " containers. Waiting to get " + totalContainerRequested); Thread.sleep(WAIT_SLEEP_MS); } } @Test (timeout = 300000) public void testActivatingApplicationAfterAddingNM() throws Exception { MockRM rm1 = new MockRM(conf); // start like normal because state is empty rm1.start(); // app that gets launched RMApp app1 = rm1.submitApp(200); // app that does not get launched RMApp app2 = rm1.submitApp(200); // app1 and app2 should be scheduled, but because no resource is available, // they are not activated. RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); ApplicationAttemptId attemptId1 = attempt1.getAppAttemptId(); rm1.waitForState(attemptId1, RMAppAttemptState.SCHEDULED); RMAppAttempt attempt2 = app2.getCurrentAppAttempt(); ApplicationAttemptId attemptId2 = attempt2.getAppAttemptId(); rm1.waitForState(attemptId2, RMAppAttemptState.SCHEDULED); MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService()); MockNM nm2 = new MockNM("h2:5678", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); nm2.registerNode(); //kick the scheduling nm1.nodeHeartbeat(true); // app1 should be allocated now rm1.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); rm1.waitForState(attemptId2, RMAppAttemptState.SCHEDULED); nm2.nodeHeartbeat(true); // app2 should be allocated now rm1.waitForState(attemptId1, RMAppAttemptState.ALLOCATED); rm1.waitForState(attemptId2, RMAppAttemptState.ALLOCATED); rm1.stop(); } // This is to test AM Host and rpc port are invalidated after the am attempt // is killed or failed, so that client doesn't get the wrong information. @Test (timeout = 80000) public void testInvalidateAMHostPortWhenAMFailedOrKilled() throws Exception { conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); MockRM rm1 = new MockRM(conf); rm1.start(); // a succeeded app RMApp app1 = rm1.submitApp(200); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); MockRM.finishAMAndVerifyAppState(app1, rm1, nm1, am1); // a failed app RMApp app2 = rm1.submitApp(200); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1); nm1.nodeHeartbeat(am2.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am2.waitForState(RMAppAttemptState.FAILED); rm1.waitForState(app2.getApplicationId(), RMAppState.FAILED); // a killed app RMApp app3 = rm1.submitApp(200); MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm1); rm1.killApp(app3.getApplicationId()); rm1.waitForState(app3.getApplicationId(), RMAppState.KILLED); rm1.waitForState(am3.getApplicationAttemptId(), RMAppAttemptState.KILLED); GetApplicationsRequest request1 = GetApplicationsRequest.newInstance(EnumSet.of( YarnApplicationState.FINISHED, YarnApplicationState.KILLED, YarnApplicationState.FAILED)); GetApplicationsResponse response1 = rm1.getClientRMService().getApplications(request1); List<ApplicationReport> appList1 = response1.getApplicationList(); Assert.assertEquals(3, appList1.size()); for (ApplicationReport report : appList1) { // killed/failed apps host and rpc port are invalidated. if (report.getApplicationId().equals(app2.getApplicationId()) || report.getApplicationId().equals(app3.getApplicationId())) { Assert.assertEquals("N/A", report.getHost()); Assert.assertEquals(-1, report.getRpcPort()); } // succeeded app's host and rpc port is not invalidated if (report.getApplicationId().equals(app1.getApplicationId())) { Assert.assertFalse(report.getHost().equals("N/A")); Assert.assertTrue(report.getRpcPort() != -1); } } } @Test (timeout = 60000) public void testInvalidatedAMHostPortOnAMRestart() throws Exception { MockRM rm1 = new MockRM(conf); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // a failed app RMApp app2 = rm1.submitApp(200); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1); nm1 .nodeHeartbeat(am2.getApplicationAttemptId(), 1, ContainerState.COMPLETE); am2.waitForState(RMAppAttemptState.FAILED); rm1.waitForState(app2.getApplicationId(), RMAppState.ACCEPTED); // before new attempt is launched, the app report returns the invalid AM // host and port. GetApplicationReportRequest request1 = GetApplicationReportRequest.newInstance(app2.getApplicationId()); ApplicationReport report1 = rm1.getClientRMService().getApplicationReport(request1) .getApplicationReport(); Assert.assertEquals("N/A", report1.getHost()); Assert.assertEquals(-1, report1.getRpcPort()); } /** * Validate killing an application when it is at accepted state. * @throws Exception exception */ @Test (timeout = 60000) public void testApplicationKillAtAcceptedState() throws Exception { final Dispatcher dispatcher = new AsyncDispatcher() { @Override public EventHandler getEventHandler() { class EventArgMatcher extends ArgumentMatcher<AbstractEvent> { @Override public boolean matches(Object argument) { if (argument instanceof RMAppAttemptEvent) { if (((RMAppAttemptEvent) argument).getType().equals( RMAppAttemptEventType.KILL)) { return true; } } return false; } } EventHandler handler = spy(super.getEventHandler()); doNothing().when(handler).handle(argThat(new EventArgMatcher())); return handler; } }; MockRM rm = new MockRM(conf) { @Override protected Dispatcher createDispatcher() { return dispatcher; } }; // test metrics QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); int appsKilled = metrics.getAppsKilled(); int appsSubmitted = metrics.getAppsSubmitted(); rm.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm.getResourceTrackerService()); nm1.registerNode(); // a failed app RMApp application = rm.submitApp(200); MockAM am = MockRM.launchAM(application, rm, nm1); am.waitForState(RMAppAttemptState.LAUNCHED); nm1.nodeHeartbeat(am.getApplicationAttemptId(), 1, ContainerState.RUNNING); rm.waitForState(application.getApplicationId(), RMAppState.ACCEPTED); // Now kill the application before new attempt is launched, the app report // returns the invalid AM host and port. KillApplicationRequest request = KillApplicationRequest.newInstance(application.getApplicationId()); rm.getClientRMService().forceKillApplication(request); // Specific test for YARN-1689 follows // Now let's say a race causes AM to register now. This should not crash RM. am.registerAppAttempt(false); // We explicitly intercepted the kill-event to RMAppAttempt, so app should // still be in KILLING state. rm.waitForState(application.getApplicationId(), RMAppState.KILLING); // AM should now be in running rm.waitForState(am.getApplicationAttemptId(), RMAppAttemptState.RUNNING); // Simulate that appAttempt is killed. rm.getRMContext().getDispatcher().getEventHandler().handle( new RMAppEvent(application.getApplicationId(), RMAppEventType.ATTEMPT_KILLED)); rm.waitForState(application.getApplicationId(), RMAppState.KILLED); // test metrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); Assert.assertEquals(appsKilled + 1, metrics.getAppsKilled()); Assert.assertEquals(appsSubmitted + 1, metrics.getAppsSubmitted()); } // Test Kill an app while the app is finishing in the meanwhile. @Test (timeout = 30000) public void testKillFinishingApp() throws Exception{ // this dispatcher ignores RMAppAttemptEventType.KILL event final Dispatcher dispatcher = new AsyncDispatcher() { @Override public EventHandler getEventHandler() { class EventArgMatcher extends ArgumentMatcher<AbstractEvent> { @Override public boolean matches(Object argument) { if (argument instanceof RMAppAttemptEvent) { if (((RMAppAttemptEvent) argument).getType().equals( RMAppAttemptEventType.KILL)) { return true; } } return false; } } EventHandler handler = spy(super.getEventHandler()); doNothing().when(handler).handle(argThat(new EventArgMatcher())); return handler; } }; MockRM rm1 = new MockRM(conf){ @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); rm1.killApp(app1.getApplicationId()); FinishApplicationMasterRequest req = FinishApplicationMasterRequest.newInstance( FinalApplicationStatus.SUCCEEDED, "", ""); am1.unregisterAppAttempt(req,true); rm1.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FINISHING); nm1.nodeHeartbeat(am1.getApplicationAttemptId(), 1, ContainerState.COMPLETE); rm1.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FINISHED); rm1.waitForState(app1.getApplicationId(), RMAppState.FINISHED); } // Test Kill an app while the app is failing @Test (timeout = 30000) public void testKillFailingApp() throws Exception{ // this dispatcher ignores RMAppAttemptEventType.KILL event final Dispatcher dispatcher = new AsyncDispatcher() { @Override public EventHandler getEventHandler() { class EventArgMatcher extends ArgumentMatcher<AbstractEvent> { @Override public boolean matches(Object argument) { if (argument instanceof RMAppAttemptEvent) { if (((RMAppAttemptEvent) argument).getType().equals( RMAppAttemptEventType.KILL)) { return true; } } return false; } } EventHandler handler = spy(super.getEventHandler()); doNothing().when(handler).handle(argThat(new EventArgMatcher())); return handler; } }; MockRM rm1 = new MockRM(conf){ @Override protected Dispatcher createDispatcher() { return dispatcher; } }; rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); rm1.killApp(app1.getApplicationId()); // fail the app by sending container_finished event. nm1.nodeHeartbeat(am1.getApplicationAttemptId(), 1, ContainerState.COMPLETE); rm1.waitForState(am1.getApplicationAttemptId(), RMAppAttemptState.FAILED); // app is killed, not launching a new attempt rm1.waitForState(app1.getApplicationId(), RMAppState.KILLED); } }
29,334
37.957503
90
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestSchedulerApplicationAttempt.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.scheduler; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; 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.api.records.ResourceRequest; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.junit.After; import org.junit.Test; public class TestSchedulerApplicationAttempt { private static final NodeId nodeId = NodeId.newInstance("somehost", 5); private Configuration conf = new Configuration(); @After public void tearDown() { QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.shutdown(); } @Test public void testMove() { final String user = "user1"; Queue parentQueue = createQueue("parent", null); Queue oldQueue = createQueue("old", parentQueue); Queue newQueue = createQueue("new", parentQueue); QueueMetrics parentMetrics = parentQueue.getMetrics(); QueueMetrics oldMetrics = oldQueue.getMetrics(); QueueMetrics newMetrics = newQueue.getMetrics(); ApplicationAttemptId appAttId = createAppAttemptId(0, 0); RMContext rmContext = mock(RMContext.class); when(rmContext.getEpoch()).thenReturn(3L); SchedulerApplicationAttempt app = new SchedulerApplicationAttempt(appAttId, user, oldQueue, oldQueue.getActiveUsersManager(), rmContext); oldMetrics.submitApp(user); // confirm that containerId is calculated based on epoch. assertEquals(0x30000000001L, app.getNewContainerId()); // Resource request Resource requestedResource = Resource.newInstance(1536, 2); Priority requestedPriority = Priority.newInstance(2); ResourceRequest request = ResourceRequest.newInstance(requestedPriority, ResourceRequest.ANY, requestedResource, 3); app.updateResourceRequests(Arrays.asList(request)); // Allocated container RMContainer container1 = createRMContainer(appAttId, 1, requestedResource); app.liveContainers.put(container1.getContainerId(), container1); SchedulerNode node = createNode(); app.appSchedulingInfo.allocate(NodeType.OFF_SWITCH, node, requestedPriority, request, container1.getContainer()); // Reserved container Priority prio1 = Priority.newInstance(1); Resource reservedResource = Resource.newInstance(2048, 3); RMContainer container2 = createReservedRMContainer(appAttId, 1, reservedResource, node.getNodeID(), prio1); Map<NodeId, RMContainer> reservations = new HashMap<NodeId, RMContainer>(); reservations.put(node.getNodeID(), container2); app.reservedContainers.put(prio1, reservations); oldMetrics.reserveResource(user, reservedResource); checkQueueMetrics(oldMetrics, 1, 1, 1536, 2, 2048, 3, 3072, 4); checkQueueMetrics(newMetrics, 0, 0, 0, 0, 0, 0, 0, 0); checkQueueMetrics(parentMetrics, 1, 1, 1536, 2, 2048, 3, 3072, 4); app.move(newQueue); checkQueueMetrics(oldMetrics, 0, 0, 0, 0, 0, 0, 0, 0); checkQueueMetrics(newMetrics, 1, 1, 1536, 2, 2048, 3, 3072, 4); checkQueueMetrics(parentMetrics, 1, 1, 1536, 2, 2048, 3, 3072, 4); } private void checkQueueMetrics(QueueMetrics metrics, int activeApps, int runningApps, int allocMb, int allocVcores, int reservedMb, int reservedVcores, int pendingMb, int pendingVcores) { assertEquals(activeApps, metrics.getActiveApps()); assertEquals(runningApps, metrics.getAppsRunning()); assertEquals(allocMb, metrics.getAllocatedMB()); assertEquals(allocVcores, metrics.getAllocatedVirtualCores()); assertEquals(reservedMb, metrics.getReservedMB()); assertEquals(reservedVcores, metrics.getReservedVirtualCores()); assertEquals(pendingMb, metrics.getPendingMB()); assertEquals(pendingVcores, metrics.getPendingVirtualCores()); } private SchedulerNode createNode() { SchedulerNode node = mock(SchedulerNode.class); when(node.getNodeName()).thenReturn("somehost"); when(node.getRackName()).thenReturn("somerack"); when(node.getNodeID()).thenReturn(nodeId); return node; } private RMContainer createReservedRMContainer(ApplicationAttemptId appAttId, int id, Resource resource, NodeId nodeId, Priority reservedPriority) { RMContainer container = createRMContainer(appAttId, id, resource); when(container.getReservedResource()).thenReturn(resource); when(container.getReservedPriority()).thenReturn(reservedPriority); when(container.getReservedNode()).thenReturn(nodeId); return container; } private RMContainer createRMContainer(ApplicationAttemptId appAttId, int id, Resource resource) { ContainerId containerId = ContainerId.newContainerId(appAttId, id); RMContainer rmContainer = mock(RMContainer.class); Container container = mock(Container.class); when(container.getResource()).thenReturn(resource); when(container.getNodeId()).thenReturn(nodeId); when(rmContainer.getContainer()).thenReturn(container); when(rmContainer.getContainerId()).thenReturn(containerId); return rmContainer; } private Queue createQueue(String name, Queue parent) { QueueMetrics metrics = QueueMetrics.forQueue(name, parent, false, conf); ActiveUsersManager activeUsersManager = new ActiveUsersManager(metrics); Queue queue = mock(Queue.class); when(queue.getMetrics()).thenReturn(metrics); when(queue.getActiveUsersManager()).thenReturn(activeUsersManager); return queue; } private ApplicationAttemptId createAppAttemptId(int appId, int attemptId) { ApplicationId appIdImpl = ApplicationId.newInstance(0, appId); ApplicationAttemptId attId = ApplicationAttemptId.newInstance(appIdImpl, attemptId); return attId; } }
7,154
41.844311
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestSchedulerHealth.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.scheduler; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.util.Time; import org.apache.hadoop.yarn.api.records.ContainerId; 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.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.NodeManager; import org.apache.hadoop.yarn.server.resourcemanager.Application; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.Task; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import static org.junit.Assume.assumeTrue; public class TestSchedulerHealth { private ResourceManager resourceManager; public void setup() { resourceManager = new ResourceManager() { @Override protected RMNodeLabelsManager createNodeLabelManager() { RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); mgr.init(getConfig()); return mgr; } }; YarnConfiguration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); resourceManager.init(conf); resourceManager.getRMContext().getContainerTokenSecretManager() .rollMasterKey(); resourceManager.getRMContext().getNMTokenSecretManager().rollMasterKey(); ((AsyncDispatcher) resourceManager.getRMContext().getDispatcher()).start(); } @Test public void testCounts() { SchedulerHealth sh = new SchedulerHealth(); int value = 1; for (int i = 0; i < 2; ++i) { sh.updateSchedulerPreemptionCounts(value); sh.updateSchedulerAllocationCounts(value); sh.updateSchedulerReservationCounts(value); sh.updateSchedulerReleaseCounts(value); Assert.assertEquals(value, sh.getAllocationCount().longValue()); Assert.assertEquals(value, sh.getReleaseCount().longValue()); Assert.assertEquals(value, sh.getReservationCount().longValue()); Assert.assertEquals(value, sh.getPreemptionCount().longValue()); Assert.assertEquals(value * (i + 1), sh.getAggregateAllocationCount() .longValue()); Assert.assertEquals(value * (i + 1), sh.getAggregateReleaseCount() .longValue()); Assert.assertEquals(value * (i + 1), sh.getAggregateReservationCount() .longValue()); Assert.assertEquals(value * (i + 1), sh.getAggregatePreemptionCount() .longValue()); } } @Test public void testOperationDetails() { SchedulerHealth sh = new SchedulerHealth(); long now = Time.now(); sh.updateRelease(now, NodeId.newInstance("testhost", 1234), ContainerId.fromString("container_1427562107907_0002_01_000001"), "testqueue"); Assert.assertEquals("container_1427562107907_0002_01_000001", sh .getLastReleaseDetails().getContainerId().toString()); Assert.assertEquals("testhost:1234", sh.getLastReleaseDetails().getNodeId() .toString()); Assert.assertEquals("testqueue", sh.getLastReleaseDetails().getQueue()); Assert.assertEquals(now, sh.getLastReleaseDetails().getTimestamp()); Assert.assertEquals(0, sh.getLastSchedulerRunTime()); now = Time.now(); sh.updateReservation(now, NodeId.newInstance("testhost1", 1234), ContainerId.fromString("container_1427562107907_0003_01_000001"), "testqueue1"); Assert.assertEquals("container_1427562107907_0003_01_000001", sh .getLastReservationDetails().getContainerId().toString()); Assert.assertEquals("testhost1:1234", sh.getLastReservationDetails() .getNodeId().toString()); Assert .assertEquals("testqueue1", sh.getLastReservationDetails().getQueue()); Assert.assertEquals(now, sh.getLastReservationDetails().getTimestamp()); Assert.assertEquals(0, sh.getLastSchedulerRunTime()); now = Time.now(); sh.updateAllocation(now, NodeId.newInstance("testhost2", 1234), ContainerId.fromString("container_1427562107907_0004_01_000001"), "testqueue2"); Assert.assertEquals("container_1427562107907_0004_01_000001", sh .getLastAllocationDetails().getContainerId().toString()); Assert.assertEquals("testhost2:1234", sh.getLastAllocationDetails() .getNodeId().toString()); Assert.assertEquals("testqueue2", sh.getLastAllocationDetails().getQueue()); Assert.assertEquals(now, sh.getLastAllocationDetails().getTimestamp()); Assert.assertEquals(0, sh.getLastSchedulerRunTime()); now = Time.now(); sh.updatePreemption(now, NodeId.newInstance("testhost3", 1234), ContainerId.fromString("container_1427562107907_0005_01_000001"), "testqueue3"); Assert.assertEquals("container_1427562107907_0005_01_000001", sh .getLastPreemptionDetails().getContainerId().toString()); Assert.assertEquals("testhost3:1234", sh.getLastPreemptionDetails() .getNodeId().toString()); Assert.assertEquals("testqueue3", sh.getLastPreemptionDetails().getQueue()); Assert.assertEquals(now, sh.getLastPreemptionDetails().getTimestamp()); Assert.assertEquals(0, sh.getLastSchedulerRunTime()); } @Test public void testResourceUpdate() { SchedulerHealth sh = new SchedulerHealth(); long now = Time.now(); sh.updateSchedulerRunDetails(now, Resource.newInstance(1024, 1), Resource.newInstance(2048, 1)); Assert.assertEquals(now, sh.getLastSchedulerRunTime()); Assert.assertEquals(Resource.newInstance(1024, 1), sh.getResourcesAllocated()); Assert.assertEquals(Resource.newInstance(2048, 1), sh.getResourcesReserved()); now = Time.now(); sh.updateSchedulerReleaseDetails(now, Resource.newInstance(3072, 1)); Assert.assertEquals(now, sh.getLastSchedulerRunTime()); Assert.assertEquals(Resource.newInstance(3072, 1), sh.getResourcesReleased()); } private NodeManager registerNode(String hostName, int containerManagerPort, int httpPort, String rackName, Resource capability) throws IOException, YarnException { NodeManager nm = new NodeManager(hostName, containerManagerPort, httpPort, rackName, capability, resourceManager); NodeAddedSchedulerEvent nodeAddEvent1 = new NodeAddedSchedulerEvent(resourceManager.getRMContext().getRMNodes() .get(nm.getNodeId())); resourceManager.getResourceScheduler().handle(nodeAddEvent1); return nm; } private void nodeUpdate(NodeManager nm) { RMNode node = resourceManager.getRMContext().getRMNodes().get(nm.getNodeId()); // Send a heartbeat to kick the tires on the Scheduler NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node); resourceManager.getResourceScheduler().handle(nodeUpdate); } @Test public void testCapacitySchedulerAllocation() throws Exception { setup(); boolean isCapacityScheduler = resourceManager.getResourceScheduler() instanceof CapacityScheduler; assumeTrue("This test is only supported on Capacity Scheduler", isCapacityScheduler); // Register node1 String host_0 = "host_0"; NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(5 * 1024, 1)); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(1); // Submit an application Application application_0 = new Application("user_0", "default", resourceManager); application_0.submit(); application_0.addNodeManager(host_0, 1234, nm_0); Resource capability_0_0 = Resources.createResource(1024, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * 1024, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] { host_0 }); application_0.addTask(task_0_0); Task task_0_1 = new Task(application_0, priority_0, new String[] { host_0 }); application_0.addTask(task_0_1); // Send resource requests to the scheduler application_0.schedule(); // Send a heartbeat to kick the tires on the Scheduler nodeUpdate(nm_0); SchedulerHealth sh = ((CapacityScheduler) resourceManager.getResourceScheduler()) .getSchedulerHealth(); Assert.assertEquals(2, sh.getAllocationCount().longValue()); Assert.assertEquals(Resource.newInstance(3 * 1024, 2), sh.getResourcesAllocated()); Assert.assertEquals(2, sh.getAggregateAllocationCount().longValue()); Assert.assertEquals("host_0:1234", sh.getLastAllocationDetails() .getNodeId().toString()); Assert.assertEquals("root.default", sh.getLastAllocationDetails() .getQueue()); Task task_0_2 = new Task(application_0, priority_0, new String[] { host_0 }); application_0.addTask(task_0_2); application_0.schedule(); nodeUpdate(nm_0); Assert.assertEquals(1, sh.getAllocationCount().longValue()); Assert.assertEquals(Resource.newInstance(2 * 1024, 1), sh.getResourcesAllocated()); Assert.assertEquals(3, sh.getAggregateAllocationCount().longValue()); Assert.assertEquals("host_0:1234", sh.getLastAllocationDetails() .getNodeId().toString()); Assert.assertEquals("root.default", sh.getLastAllocationDetails() .getQueue()); } @Test public void testCapacitySchedulerReservation() throws Exception { setup(); boolean isCapacityScheduler = resourceManager.getResourceScheduler() instanceof CapacityScheduler; assumeTrue("This test is only supported on Capacity Scheduler", isCapacityScheduler); // Register nodes String host_0 = "host_0"; NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(2 * 1024, 1)); String host_1 = "host_1"; NodeManager nm_1 = registerNode(host_1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(5 * 1024, 1)); nodeUpdate(nm_0); nodeUpdate(nm_1); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(1); // Submit an application Application application_0 = new Application("user_0", "default", resourceManager); application_0.submit(); application_0.addNodeManager(host_0, 1234, nm_0); application_0.addNodeManager(host_1, 1234, nm_1); Resource capability_0_0 = Resources.createResource(1024, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * 1024, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] { host_0 }); application_0.addTask(task_0_0); // Send resource requests to the scheduler application_0.schedule(); // Send a heartbeat to kick the tires on the Scheduler nodeUpdate(nm_0); SchedulerHealth sh = ((CapacityScheduler) resourceManager.getResourceScheduler()) .getSchedulerHealth(); Assert.assertEquals(1, sh.getAllocationCount().longValue()); Assert.assertEquals(Resource.newInstance(1024, 1), sh.getResourcesAllocated()); Assert.assertEquals(1, sh.getAggregateAllocationCount().longValue()); Assert.assertEquals("host_0:1234", sh.getLastAllocationDetails() .getNodeId().toString()); Assert.assertEquals("root.default", sh.getLastAllocationDetails() .getQueue()); Task task_0_1 = new Task(application_0, priority_0, new String[] { host_0 }); application_0.addTask(task_0_1); application_0.schedule(); nodeUpdate(nm_0); Assert.assertEquals(0, sh.getAllocationCount().longValue()); Assert.assertEquals(1, sh.getReservationCount().longValue()); Assert.assertEquals(Resource.newInstance(2 * 1024, 1), sh.getResourcesReserved()); Assert.assertEquals(1, sh.getAggregateAllocationCount().longValue()); Assert.assertEquals("host_0:1234", sh.getLastAllocationDetails() .getNodeId().toString()); Assert.assertEquals("root.default", sh.getLastAllocationDetails() .getQueue()); } }
14,242
39.463068
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestSchedulerUtils.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.scheduler; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; 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.NodeLabel; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceBlacklistRequest; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.impl.pb.ResourceRequestPBImpl; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.exceptions.InvalidResourceBlacklistRequestException; import org.apache.hadoop.yarn.exceptions.InvalidResourceRequestException; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MockRMWithAMS; import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MyContainerManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; 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.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; public class TestSchedulerUtils { private static final Log LOG = LogFactory.getLog(TestSchedulerUtils.class); private RMContext rmContext = getMockRMContext(); @Test (timeout = 30000) public void testNormalizeRequest() { ResourceCalculator resourceCalculator = new DefaultResourceCalculator(); final int minMemory = 1024; final int maxMemory = 8192; Resource minResource = Resources.createResource(minMemory, 0); Resource maxResource = Resources.createResource(maxMemory, 0); ResourceRequest ask = new ResourceRequestPBImpl(); // case negative memory ask.setCapability(Resources.createResource(-1024)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(minMemory, ask.getCapability().getMemory()); // case zero memory ask.setCapability(Resources.createResource(0)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(minMemory, ask.getCapability().getMemory()); // case memory is a multiple of minMemory ask.setCapability(Resources.createResource(2 * minMemory)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(2 * minMemory, ask.getCapability().getMemory()); // case memory is not a multiple of minMemory ask.setCapability(Resources.createResource(minMemory + 10)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(2 * minMemory, ask.getCapability().getMemory()); // case memory is equal to max allowed ask.setCapability(Resources.createResource(maxMemory)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(maxMemory, ask.getCapability().getMemory()); // case memory is just less than max ask.setCapability(Resources.createResource(maxMemory - 10)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(maxMemory, ask.getCapability().getMemory()); // max is not a multiple of min maxResource = Resources.createResource(maxMemory - 10, 0); ask.setCapability(Resources.createResource(maxMemory - 100)); // multiple of minMemory > maxMemory, then reduce to maxMemory SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(maxResource.getMemory(), ask.getCapability().getMemory()); // ask is more than max maxResource = Resources.createResource(maxMemory, 0); ask.setCapability(Resources.createResource(maxMemory + 100)); SchedulerUtils.normalizeRequest(ask, resourceCalculator, null, minResource, maxResource); assertEquals(maxResource.getMemory(), ask.getCapability().getMemory()); } @Test (timeout = 30000) public void testNormalizeRequestWithDominantResourceCalculator() { ResourceCalculator resourceCalculator = new DominantResourceCalculator(); Resource minResource = Resources.createResource(1024, 1); Resource maxResource = Resources.createResource(10240, 10); Resource clusterResource = Resources.createResource(10 * 1024, 10); ResourceRequest ask = new ResourceRequestPBImpl(); // case negative memory/vcores ask.setCapability(Resources.createResource(-1024, -1)); SchedulerUtils.normalizeRequest( ask, resourceCalculator, clusterResource, minResource, maxResource); assertEquals(minResource, ask.getCapability()); // case zero memory/vcores ask.setCapability(Resources.createResource(0, 0)); SchedulerUtils.normalizeRequest( ask, resourceCalculator, clusterResource, minResource, maxResource); assertEquals(minResource, ask.getCapability()); assertEquals(1, ask.getCapability().getVirtualCores()); assertEquals(1024, ask.getCapability().getMemory()); // case non-zero memory & zero cores ask.setCapability(Resources.createResource(1536, 0)); SchedulerUtils.normalizeRequest( ask, resourceCalculator, clusterResource, minResource, maxResource); assertEquals(Resources.createResource(2048, 1), ask.getCapability()); assertEquals(1, ask.getCapability().getVirtualCores()); assertEquals(2048, ask.getCapability().getMemory()); } @Test (timeout = 30000) public void testValidateResourceRequestWithErrorLabelsPermission() throws IOException { // mock queue and scheduler YarnScheduler scheduler = mock(YarnScheduler.class); Set<String> queueAccessibleNodeLabels = Sets.newHashSet(); QueueInfo queueInfo = mock(QueueInfo.class); when(queueInfo.getQueueName()).thenReturn("queue"); when(queueInfo.getAccessibleNodeLabels()).thenReturn(queueAccessibleNodeLabels); when(scheduler.getQueueInfo(any(String.class), anyBoolean(), anyBoolean())) .thenReturn(queueInfo); Resource maxResource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); // queue has labels, success cases try { // set queue accessible node labesl to [x, y] queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays.asList("x", "y")); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"), NodeLabel.newInstance("y"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression("y"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression(""); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression(" "); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); } catch (InvalidResourceRequestException e) { e.printStackTrace(); fail("Should be valid when request labels is a subset of queue labels"); } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x", "y")); } // same as above, but cluster node labels don't contains label being // requested. should fail try { // set queue accessible node labesl to [x, y] queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays.asList("x", "y")); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } // queue has labels, failed cases (when ask a label not included by queue) try { // set queue accessible node labesl to [x, y] queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays.asList("x", "y")); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"), NodeLabel.newInstance("y"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("z"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x", "y")); } // we don't allow specify more than two node labels in a single expression // now try { // set queue accessible node labesl to [x, y] queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays.asList("x", "y")); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"), NodeLabel.newInstance("y"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("x && y"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x", "y")); } // queue doesn't have label, succeed (when request no label) queueAccessibleNodeLabels.clear(); try { // set queue accessible node labels to empty queueAccessibleNodeLabels.clear(); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression(""); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression(" "); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); } catch (InvalidResourceRequestException e) { e.printStackTrace(); fail("Should be valid when request labels is empty"); } // queue doesn't have label, failed (when request any label) try { // set queue accessible node labels to empty queueAccessibleNodeLabels.clear(); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x")); } // queue is "*", always succeeded try { // set queue accessible node labels to empty queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.add(RMNodeLabelsManager.ANY); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"), NodeLabel.newInstance("y"), NodeLabel.newInstance("z"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression("y"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); resReq.setNodeLabelExpression("z"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); } catch (InvalidResourceRequestException e) { e.printStackTrace(); fail("Should be valid when queue can access any labels"); } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x", "y", "z")); } // same as above, but cluster node labels don't contains label, should fail try { // set queue accessible node labels to empty queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.add(RMNodeLabelsManager.ANY); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } // we don't allow resource name other than ANY and specify label try { // set queue accessible node labesl to [x, y] queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays.asList("x", "y")); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"), NodeLabel.newInstance("y"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), "rack", resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x", "y")); } // we don't allow resource name other than ANY and specify label even if // queue has accessible label = * try { // set queue accessible node labesl to * queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays .asList(CommonNodeLabelsManager.ANY)); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), "rack", resource, 1); resReq.setNodeLabelExpression("x"); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); fail("Should fail"); } catch (InvalidResourceRequestException e) { } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x")); } } @Test (timeout = 30000) public void testValidateResourceRequest() { YarnScheduler mockScheduler = mock(YarnScheduler.class); Resource maxResource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); // zero memory try { Resource resource = Resources.createResource(0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); } catch (InvalidResourceRequestException e) { fail("Zero memory should be accepted"); } // zero vcores try { Resource resource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); } catch (InvalidResourceRequestException e) { fail("Zero vcores should be accepted"); } // max memory try { Resource resource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); } catch (InvalidResourceRequestException e) { fail("Max memory should be accepted"); } // max vcores try { Resource resource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); } catch (InvalidResourceRequestException e) { fail("Max vcores should not be accepted"); } // negative memory try { Resource resource = Resources.createResource(-1, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); fail("Negative memory should not be accepted"); } catch (InvalidResourceRequestException e) { // expected } // negative vcores try { Resource resource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB, -1); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); fail("Negative vcores should not be accepted"); } catch (InvalidResourceRequestException e) { // expected } // more than max memory try { Resource resource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB + 1, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); fail("More than max memory should not be accepted"); } catch (InvalidResourceRequestException e) { // expected } // more than max vcores try { Resource resource = Resources .createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES + 1); ResourceRequest resReq = BuilderUtils.newResourceRequest(mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, null, mockScheduler, rmContext); fail("More than max vcores should not be accepted"); } catch (InvalidResourceRequestException e) { // expected } } @Test public void testValidateResourceBlacklistRequest() throws Exception { MyContainerManager containerManager = new MyContainerManager(); final MockRMWithAMS rm = new MockRMWithAMS(new YarnConfiguration(), containerManager); rm.start(); MockNM nm1 = rm.registerNode("localhost:1234", 5120); Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(2); acls.put(ApplicationAccessType.VIEW_APP, "*"); RMApp app = rm.submitApp(1024, "appname", "appuser", acls); nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId(); waitForLaunchedState(attempt); // Create a client to the RM. final Configuration conf = rm.getConfig(); final YarnRPC rpc = YarnRPC.create(conf); UserGroupInformation currentUser = UserGroupInformation.createRemoteUser(applicationAttemptId.toString()); Credentials credentials = containerManager.getContainerCredentials(); final InetSocketAddress rmBindAddress = rm.getApplicationMasterService().getBindAddress(); Token<? extends TokenIdentifier> amRMToken = MockRMWithAMS.setupAndReturnAMRMToken(rmBindAddress, credentials.getAllTokens()); currentUser.addToken(amRMToken); ApplicationMasterProtocol client = currentUser.doAs(new PrivilegedAction<ApplicationMasterProtocol>() { @Override public ApplicationMasterProtocol run() { return (ApplicationMasterProtocol) rpc.getProxy( ApplicationMasterProtocol.class, rmBindAddress, conf); } }); RegisterApplicationMasterRequest request = Records .newRecord(RegisterApplicationMasterRequest.class); client.registerApplicationMaster(request); ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( Collections.singletonList(ResourceRequest.ANY), null); AllocateRequest allocateRequest = AllocateRequest.newInstance(0, 0.0f, null, null, blacklistRequest); boolean error = false; try { client.allocate(allocateRequest); } catch (InvalidResourceBlacklistRequestException e) { error = true; } rm.stop(); Assert.assertTrue( "Didn't not catch InvalidResourceBlacklistRequestException", error); } private void waitForLaunchedState(RMAppAttempt attempt) throws InterruptedException { int waitCount = 0; while (attempt.getAppAttemptState() != RMAppAttemptState.LAUNCHED && waitCount++ < 20) { LOG.info("Waiting for AppAttempt to reach LAUNCHED state. " + "Current state is " + attempt.getAppAttemptState()); Thread.sleep(1000); } Assert.assertEquals(attempt.getAppAttemptState(), RMAppAttemptState.LAUNCHED); } @Test public void testComparePriorities(){ Priority high = Priority.newInstance(1); Priority low = Priority.newInstance(2); assertTrue(high.compareTo(low) > 0); } @Test public void testCreateAbnormalContainerStatus() { ContainerStatus cd = SchedulerUtils.createAbnormalContainerStatus( ContainerId.newContainerId(ApplicationAttemptId.newInstance( ApplicationId.newInstance(System.currentTimeMillis(), 1), 1), 1), "x"); Assert.assertEquals(ContainerExitStatus.ABORTED, cd.getExitStatus()); } @Test public void testCreatePreemptedContainerStatus() { ContainerStatus cd = SchedulerUtils.createPreemptedContainerStatus( ContainerId.newContainerId(ApplicationAttemptId.newInstance( ApplicationId.newInstance(System.currentTimeMillis(), 1), 1), 1), "x"); Assert.assertEquals(ContainerExitStatus.PREEMPTED, cd.getExitStatus()); } @Test (timeout = 30000) public void testNormalizeNodeLabelExpression() throws IOException { // mock queue and scheduler YarnScheduler scheduler = mock(YarnScheduler.class); Set<String> queueAccessibleNodeLabels = Sets.newHashSet(); QueueInfo queueInfo = mock(QueueInfo.class); when(queueInfo.getQueueName()).thenReturn("queue"); when(queueInfo.getAccessibleNodeLabels()).thenReturn(queueAccessibleNodeLabels); when(queueInfo.getDefaultNodeLabelExpression()).thenReturn(" x "); when(scheduler.getQueueInfo(any(String.class), anyBoolean(), anyBoolean())) .thenReturn(queueInfo); Resource maxResource = Resources.createResource( YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); // queue has labels, success cases try { // set queue accessible node labels to [x, y] queueAccessibleNodeLabels.clear(); queueAccessibleNodeLabels.addAll(Arrays.asList("x", "y")); rmContext.getNodeLabelManager().addToCluserNodeLabels( ImmutableSet.of(NodeLabel.newInstance("x"), NodeLabel.newInstance("y"))); Resource resource = Resources.createResource( 0, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); ResourceRequest resReq = BuilderUtils.newResourceRequest( mock(Priority.class), ResourceRequest.ANY, resource, 1); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); Assert.assertTrue(resReq.getNodeLabelExpression().equals("x")); resReq.setNodeLabelExpression(" y "); SchedulerUtils.normalizeAndvalidateRequest(resReq, maxResource, "queue", scheduler, rmContext); Assert.assertTrue(resReq.getNodeLabelExpression().equals("y")); } catch (InvalidResourceRequestException e) { e.printStackTrace(); fail("Should be valid when request labels is a subset of queue labels"); } finally { rmContext.getNodeLabelManager().removeFromClusterNodeLabels( Arrays.asList("x", "y")); } } public static SchedulerApplication<SchedulerApplicationAttempt> verifyAppAddedAndRemovedFromScheduler( Map<ApplicationId, SchedulerApplication<SchedulerApplicationAttempt>> applications, EventHandler<SchedulerEvent> handler, String queueName) throws Exception { ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1); AppAddedSchedulerEvent appAddedEvent = new AppAddedSchedulerEvent(appId, queueName, "user"); handler.handle(appAddedEvent); SchedulerApplication<SchedulerApplicationAttempt> app = applications.get(appId); // verify application is added. Assert.assertNotNull(app); Assert.assertEquals("user", app.getUser()); AppRemovedSchedulerEvent appRemoveEvent = new AppRemovedSchedulerEvent(appId, RMAppState.FINISHED); handler.handle(appRemoveEvent); Assert.assertNull(applications.get(appId)); return app; } private static RMContext getMockRMContext() { RMContext rmContext = mock(RMContext.class); RMNodeLabelsManager nlm = new NullRMNodeLabelsManager(); nlm.init(new Configuration(false)); when(rmContext.getNodeLabelManager()).thenReturn(nlm); return rmContext; } }
32,849
41.332474
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestQueueMetrics.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.scheduler; import static org.apache.hadoop.test.MetricsAsserts.assertCounter; import static org.apache.hadoop.test.MetricsAsserts.assertGauge; import static org.apache.hadoop.test.MetricsAsserts.getMetrics; import static org.apache.hadoop.test.MockitoMaker.make; import static org.apache.hadoop.test.MockitoMaker.stub; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics2.MetricsRecordBuilder; import org.apache.hadoop.metrics2.MetricsSource; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.impl.MetricsSystemImpl; import org.apache.hadoop.test.MetricsAsserts; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestQueueMetrics { static final int GB = 1024; // MB private static final Configuration conf = new Configuration(); private MetricsSystem ms; @Before public void setUp() { ms = new MetricsSystemImpl(); QueueMetrics.clearQueueMetrics(); } @Test public void testDefaultSingleQueueMetrics() { String queueName = "single"; String user = "alice"; QueueMetrics metrics = QueueMetrics.forQueue(ms, queueName, null, false, conf); MetricsSource queueSource= queueSource(ms, queueName); AppSchedulingInfo app = mockApp(user); metrics.submitApp(user); MetricsSource userSource = userSource(ms, queueName, user); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); metrics.submitAppAttempt(user); checkApps(queueSource, 1, 1, 0, 0, 0, 0, true); metrics.setAvailableResourcesToQueue(Resources.createResource(100*GB, 100)); metrics.incrPendingResources(user, 5, Resources.createResource(3*GB, 3)); // Available resources is set externally, as it depends on dynamic // configurable cluster/queue resources checkResources(queueSource, 0, 0, 0, 0, 0, 100*GB, 100, 15*GB, 15, 5, 0, 0, 0); metrics.runAppAttempt(app.getApplicationId(), user); checkApps(queueSource, 1, 0, 1, 0, 0, 0, true); metrics.allocateResources(user, 3, Resources.createResource(2*GB, 2), true); checkResources(queueSource, 6*GB, 6, 3, 3, 0, 100*GB, 100, 9*GB, 9, 2, 0, 0, 0); metrics.releaseResources(user, 1, Resources.createResource(2*GB, 2)); checkResources(queueSource, 4*GB, 4, 2, 3, 1, 100*GB, 100, 9*GB, 9, 2, 0, 0, 0); metrics.finishAppAttempt( app.getApplicationId(), app.isPending(), app.getUser()); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); metrics.finishApp(user, RMAppState.FINISHED); checkApps(queueSource, 1, 0, 0, 1, 0, 0, true); assertNull(userSource); } @Test public void testQueueAppMetricsForMultipleFailures() { String queueName = "single"; String user = "alice"; QueueMetrics metrics = QueueMetrics.forQueue(ms, queueName, null, false, new Configuration()); MetricsSource queueSource = queueSource(ms, queueName); AppSchedulingInfo app = mockApp(user); metrics.submitApp(user); MetricsSource userSource = userSource(ms, queueName, user); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); metrics.submitAppAttempt(user); checkApps(queueSource, 1, 1, 0, 0, 0, 0, true); metrics.runAppAttempt(app.getApplicationId(), user); checkApps(queueSource, 1, 0, 1, 0, 0, 0, true); metrics.finishAppAttempt( app.getApplicationId(), app.isPending(), app.getUser()); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); // As the application has failed, framework retries the same application // based on configuration metrics.submitAppAttempt(user); checkApps(queueSource, 1, 1, 0, 0, 0, 0, true); metrics.runAppAttempt(app.getApplicationId(), user); checkApps(queueSource, 1, 0, 1, 0, 0, 0, true); // Suppose say application has failed this time as well. metrics.finishAppAttempt( app.getApplicationId(), app.isPending(), app.getUser()); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); // As the application has failed, framework retries the same application // based on configuration metrics.submitAppAttempt(user); checkApps(queueSource, 1, 1, 0, 0, 0, 0, true); metrics.runAppAttempt(app.getApplicationId(), user); checkApps(queueSource, 1, 0, 1, 0, 0, 0, true); // Suppose say application has failed, and there's no more retries. metrics.finishAppAttempt( app.getApplicationId(), app.isPending(), app.getUser()); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); metrics.finishApp(user, RMAppState.FAILED); checkApps(queueSource, 1, 0, 0, 0, 1, 0, true); assertNull(userSource); } @Test public void testSingleQueueWithUserMetrics() { String queueName = "single2"; String user = "dodo"; QueueMetrics metrics = QueueMetrics.forQueue(ms, queueName, null, true, conf); MetricsSource queueSource = queueSource(ms, queueName); AppSchedulingInfo app = mockApp(user); metrics.submitApp(user); MetricsSource userSource = userSource(ms, queueName, user); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); checkApps(userSource, 1, 0, 0, 0, 0, 0, true); metrics.submitAppAttempt(user); checkApps(queueSource, 1, 1, 0, 0, 0, 0, true); checkApps(userSource, 1, 1, 0, 0, 0, 0, true); metrics.setAvailableResourcesToQueue(Resources.createResource(100*GB, 100)); metrics.setAvailableResourcesToUser(user, Resources.createResource(10*GB, 10)); metrics.incrPendingResources(user, 5, Resources.createResource(3*GB, 3)); // Available resources is set externally, as it depends on dynamic // configurable cluster/queue resources checkResources(queueSource, 0, 0, 0, 0, 0, 100*GB, 100, 15*GB, 15, 5, 0, 0, 0); checkResources(userSource, 0, 0, 0, 0, 0, 10*GB, 10, 15*GB, 15, 5, 0, 0, 0); metrics.runAppAttempt(app.getApplicationId(), user); checkApps(queueSource, 1, 0, 1, 0, 0, 0, true); checkApps(userSource, 1, 0, 1, 0, 0, 0, true); metrics.allocateResources(user, 3, Resources.createResource(2*GB, 2), true); checkResources(queueSource, 6*GB, 6, 3, 3, 0, 100*GB, 100, 9*GB, 9, 2, 0, 0, 0); checkResources(userSource, 6*GB, 6, 3, 3, 0, 10*GB, 10, 9*GB, 9, 2, 0, 0, 0); metrics.releaseResources(user, 1, Resources.createResource(2*GB, 2)); checkResources(queueSource, 4*GB, 4, 2, 3, 1, 100*GB, 100, 9*GB, 9, 2, 0, 0, 0); checkResources(userSource, 4*GB, 4, 2, 3, 1, 10*GB, 10, 9*GB, 9, 2, 0, 0, 0); metrics.finishAppAttempt( app.getApplicationId(), app.isPending(), app.getUser()); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); checkApps(userSource, 1, 0, 0, 0, 0, 0, true); metrics.finishApp(user, RMAppState.FINISHED); checkApps(queueSource, 1, 0, 0, 1, 0, 0, true); checkApps(userSource, 1, 0, 0, 1, 0, 0, true); } @Test public void testTwoLevelWithUserMetrics() { String parentQueueName = "root"; String leafQueueName = "root.leaf"; String user = "alice"; QueueMetrics parentMetrics = QueueMetrics.forQueue(ms, parentQueueName, null, true, conf); Queue parentQueue = make(stub(Queue.class).returning(parentMetrics). from.getMetrics()); QueueMetrics metrics = QueueMetrics.forQueue(ms, leafQueueName, parentQueue, true, conf); MetricsSource parentQueueSource = queueSource(ms, parentQueueName); MetricsSource queueSource = queueSource(ms, leafQueueName); AppSchedulingInfo app = mockApp(user); metrics.submitApp(user); MetricsSource userSource = userSource(ms, leafQueueName, user); MetricsSource parentUserSource = userSource(ms, parentQueueName, user); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); checkApps(parentQueueSource, 1, 0, 0, 0, 0, 0, true); checkApps(userSource, 1, 0, 0, 0, 0, 0, true); checkApps(parentUserSource, 1, 0, 0, 0, 0, 0, true); metrics.submitAppAttempt(user); checkApps(queueSource, 1, 1, 0, 0, 0, 0, true); checkApps(parentQueueSource, 1, 1, 0, 0, 0, 0, true); checkApps(userSource, 1, 1, 0, 0, 0, 0, true); checkApps(parentUserSource, 1, 1, 0, 0, 0, 0, true); parentMetrics.setAvailableResourcesToQueue(Resources.createResource(100*GB, 100)); metrics.setAvailableResourcesToQueue(Resources.createResource(100*GB, 100)); parentMetrics.setAvailableResourcesToUser(user, Resources.createResource(10*GB, 10)); metrics.setAvailableResourcesToUser(user, Resources.createResource(10*GB, 10)); metrics.incrPendingResources(user, 5, Resources.createResource(3*GB, 3)); checkResources(queueSource, 0, 0, 0, 0, 0, 100*GB, 100, 15*GB, 15, 5, 0, 0, 0); checkResources(parentQueueSource, 0, 0, 0, 0, 0, 100*GB, 100, 15*GB, 15, 5, 0, 0, 0); checkResources(userSource, 0, 0, 0, 0, 0, 10*GB, 10, 15*GB, 15, 5, 0, 0, 0); checkResources(parentUserSource, 0, 0, 0, 0, 0, 10*GB, 10, 15*GB, 15, 5, 0, 0, 0); metrics.runAppAttempt(app.getApplicationId(), user); checkApps(queueSource, 1, 0, 1, 0, 0, 0, true); checkApps(userSource, 1, 0, 1, 0, 0, 0, true); metrics.allocateResources(user, 3, Resources.createResource(2*GB, 2), true); metrics.reserveResource(user, Resources.createResource(3*GB, 3)); // Available resources is set externally, as it depends on dynamic // configurable cluster/queue resources checkResources(queueSource, 6*GB, 6, 3, 3, 0, 100*GB, 100, 9*GB, 9, 2, 3*GB, 3, 1); checkResources(parentQueueSource, 6*GB, 6, 3, 3, 0, 100*GB, 100, 9*GB, 9, 2, 3*GB, 3, 1); checkResources(userSource, 6*GB, 6, 3, 3, 0, 10*GB, 10, 9*GB, 9, 2, 3*GB, 3, 1); checkResources(parentUserSource, 6*GB, 6, 3, 3, 0, 10*GB, 10, 9*GB, 9, 2, 3*GB, 3, 1); metrics.releaseResources(user, 1, Resources.createResource(2*GB, 2)); metrics.unreserveResource(user, Resources.createResource(3*GB, 3)); checkResources(queueSource, 4*GB, 4, 2, 3, 1, 100*GB, 100, 9*GB, 9, 2, 0, 0, 0); checkResources(parentQueueSource, 4*GB, 4, 2, 3, 1, 100*GB, 100, 9*GB, 9, 2, 0, 0, 0); checkResources(userSource, 4*GB, 4, 2, 3, 1, 10*GB, 10, 9*GB, 9, 2, 0, 0, 0); checkResources(parentUserSource, 4*GB, 4, 2, 3, 1, 10*GB, 10, 9*GB, 9, 2, 0, 0, 0); metrics.finishAppAttempt( app.getApplicationId(), app.isPending(), app.getUser()); checkApps(queueSource, 1, 0, 0, 0, 0, 0, true); checkApps(parentQueueSource, 1, 0, 0, 0, 0, 0, true); checkApps(userSource, 1, 0, 0, 0, 0, 0, true); checkApps(parentUserSource, 1, 0, 0, 0, 0, 0, true); metrics.finishApp(user, RMAppState.FINISHED); checkApps(queueSource, 1, 0, 0, 1, 0, 0, true); checkApps(parentQueueSource, 1, 0, 0, 1, 0, 0, true); checkApps(userSource, 1, 0, 0, 1, 0, 0, true); checkApps(parentUserSource, 1, 0, 0, 1, 0, 0, true); } @Test public void testMetricsCache() { MetricsSystem ms = new MetricsSystemImpl("cache"); ms.start(); try { String p1 = "root1"; String leafQueueName = "root1.leaf"; QueueMetrics p1Metrics = QueueMetrics.forQueue(ms, p1, null, true, conf); Queue parentQueue1 = make(stub(Queue.class).returning(p1Metrics). from.getMetrics()); QueueMetrics metrics = QueueMetrics.forQueue(ms, leafQueueName, parentQueue1, true, conf); Assert.assertNotNull("QueueMetrics for A shoudn't be null", metrics); // Re-register to check for cache hit, shouldn't blow up metrics-system... // also, verify parent-metrics QueueMetrics alterMetrics = QueueMetrics.forQueue(ms, leafQueueName, parentQueue1, true, conf); Assert.assertNotNull("QueueMetrics for alterMetrics shoudn't be null", alterMetrics); } finally { ms.shutdown(); } } @Test public void testMetricsInitializedOnRMInit() { YarnConfiguration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); checkApps(metrics, 0, 0, 0, 0, 0, 0, true); MetricsAsserts.assertGauge("ReservedContainers", 0, metrics); } // This is to test all metrics can consistently show up if specified true to // collect all metrics, even though they are not modified from last time they // are collected. If not collecting all metrics, only modified metrics will show up. @Test public void testCollectAllMetrics() { String queueName = "single"; QueueMetrics.forQueue(ms, queueName, null, false, conf); MetricsSource queueSource = queueSource(ms, queueName); checkApps(queueSource, 0, 0, 0, 0, 0, 0, true); try { // do not collect all metrics checkApps(queueSource, 0, 0, 0, 0, 0, 0, false); Assert.fail(); } catch (AssertionError e) { Assert.assertTrue(e.getMessage().contains( "Expected exactly one metric for name ")); } // collect all metrics checkApps(queueSource, 0, 0, 0, 0, 0, 0, true); } public static void checkApps(MetricsSource source, int submitted, int pending, int running, int completed, int failed, int killed, boolean all) { MetricsRecordBuilder rb = getMetrics(source, all); assertCounter("AppsSubmitted", submitted, rb); assertGauge("AppsPending", pending, rb); assertGauge("AppsRunning", running, rb); assertCounter("AppsCompleted", completed, rb); assertCounter("AppsFailed", failed, rb); assertCounter("AppsKilled", killed, rb); } public static void checkResources(MetricsSource source, int allocatedMB, int allocatedCores, int allocCtnrs, long aggreAllocCtnrs, long aggreReleasedCtnrs, int availableMB, int availableCores, int pendingMB, int pendingCores, int pendingCtnrs, int reservedMB, int reservedCores, int reservedCtnrs) { MetricsRecordBuilder rb = getMetrics(source); assertGauge("AllocatedMB", allocatedMB, rb); assertGauge("AllocatedVCores", allocatedCores, rb); assertGauge("AllocatedContainers", allocCtnrs, rb); assertCounter("AggregateContainersAllocated", aggreAllocCtnrs, rb); assertCounter("AggregateContainersReleased", aggreReleasedCtnrs, rb); assertGauge("AvailableMB", availableMB, rb); assertGauge("AvailableVCores", availableCores, rb); assertGauge("PendingMB", pendingMB, rb); assertGauge("PendingVCores", pendingCores, rb); assertGauge("PendingContainers", pendingCtnrs, rb); assertGauge("ReservedMB", reservedMB, rb); assertGauge("ReservedVCores", reservedCores, rb); assertGauge("ReservedContainers", reservedCtnrs, rb); } private static AppSchedulingInfo mockApp(String user) { AppSchedulingInfo app = mock(AppSchedulingInfo.class); when(app.getUser()).thenReturn(user); ApplicationId appId = BuilderUtils.newApplicationId(1, 1); ApplicationAttemptId id = BuilderUtils.newApplicationAttemptId(appId, 1); when(app.getApplicationAttemptId()).thenReturn(id); return app; } public static MetricsSource queueSource(MetricsSystem ms, String queue) { MetricsSource s = ms.getSource(QueueMetrics.sourceName(queue).toString()); return s; } public static MetricsSource userSource(MetricsSystem ms, String queue, String user) { MetricsSource s = ms.getSource(QueueMetrics.sourceName(queue). append(",user=").append(user).toString()); return s; } }
16,856
42.112532
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestResourceUsage.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.scheduler; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.records.Resource; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class TestResourceUsage { private static final Log LOG = LogFactory.getLog(TestResourceUsage.class); private String suffix; @Parameterized.Parameters public static Collection<String[]> getParameters() { return Arrays.asList(new String[][] { { "Pending" }, { "Used" }, { "Reserved" }, { "AMUsed" } }); } public TestResourceUsage(String suffix) { this.suffix = suffix; } private static void dec(ResourceUsage obj, String suffix, Resource res, String label) throws Exception { executeByName(obj, "dec" + suffix, res, label); } private static void inc(ResourceUsage obj, String suffix, Resource res, String label) throws Exception { executeByName(obj, "inc" + suffix, res, label); } private static void set(ResourceUsage obj, String suffix, Resource res, String label) throws Exception { executeByName(obj, "set" + suffix, res, label); } private static Resource get(ResourceUsage obj, String suffix, String label) throws Exception { return executeByName(obj, "get" + suffix, null, label); } // Use reflection to avoid too much avoid code private static Resource executeByName(ResourceUsage obj, String methodName, Resource arg, String label) throws Exception { // We have 4 kinds of method // 1. getXXX() : Resource // 2. getXXX(label) : Resource // 3. set/inc/decXXX(res) : void // 4. set/inc/decXXX(label, res) : void if (methodName.startsWith("get")) { Resource result; if (label == null) { // 1. Method method = ResourceUsage.class.getDeclaredMethod(methodName); result = (Resource) method.invoke(obj); } else { // 2. Method method = ResourceUsage.class.getDeclaredMethod(methodName, String.class); result = (Resource) method.invoke(obj, label); } return result; } else { if (label == null) { // 3. Method method = ResourceUsage.class.getDeclaredMethod(methodName, Resource.class); method.invoke(obj, arg); } else { // 4. Method method = ResourceUsage.class.getDeclaredMethod(methodName, String.class, Resource.class); method.invoke(obj, label, arg); } return null; } } private void internalTestModifyAndRead(String label) throws Exception { ResourceUsage usage = new ResourceUsage(); Resource res; // First get returns 0 always res = get(usage, suffix, label); check(0, 0, res); // Add 1,1 should returns 1,1 inc(usage, suffix, Resource.newInstance(1, 1), label); check(1, 1, get(usage, suffix, label)); // Set 2,2 set(usage, suffix, Resource.newInstance(2, 2), label); check(2, 2, get(usage, suffix, label)); // dec 2,2 dec(usage, suffix, Resource.newInstance(2, 2), label); check(0, 0, get(usage, suffix, label)); } void check(int mem, int cpu, Resource res) { Assert.assertEquals(mem, res.getMemory()); Assert.assertEquals(cpu, res.getVirtualCores()); } @Test public void testModifyAndRead() throws Exception { LOG.info("Test - " + suffix); internalTestModifyAndRead(null); internalTestModifyAndRead("label"); } }
4,512
31.467626
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestAbstractYarnScheduler.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.scheduler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceOption; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.ParameterizedSchedulerTestBase; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.MockRMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Assert; import org.junit.Test; @SuppressWarnings("unchecked") public class TestAbstractYarnScheduler extends ParameterizedSchedulerTestBase { public TestAbstractYarnScheduler(SchedulerType type) { super(type); } @Test public void testMaximimumAllocationMemory() throws Exception { final int node1MaxMemory = 15 * 1024; final int node2MaxMemory = 5 * 1024; final int node3MaxMemory = 6 * 1024; final int configuredMaxMemory = 10 * 1024; configureScheduler(); YarnConfiguration conf = getConf(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, configuredMaxMemory); conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 1000 * 1000); MockRM rm = new MockRM(conf); try { rm.start(); testMaximumAllocationMemoryHelper( (AbstractYarnScheduler) rm.getResourceScheduler(), node1MaxMemory, node2MaxMemory, node3MaxMemory, configuredMaxMemory, configuredMaxMemory, configuredMaxMemory, configuredMaxMemory, configuredMaxMemory, configuredMaxMemory); } finally { rm.stop(); } conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 0); rm = new MockRM(conf); try { rm.start(); testMaximumAllocationMemoryHelper( (AbstractYarnScheduler) rm.getResourceScheduler(), node1MaxMemory, node2MaxMemory, node3MaxMemory, configuredMaxMemory, configuredMaxMemory, configuredMaxMemory, node2MaxMemory, node3MaxMemory, node2MaxMemory); } finally { rm.stop(); } } private void testMaximumAllocationMemoryHelper( AbstractYarnScheduler scheduler, final int node1MaxMemory, final int node2MaxMemory, final int node3MaxMemory, final int... expectedMaxMemory) throws Exception { Assert.assertEquals(6, expectedMaxMemory.length); Assert.assertEquals(0, scheduler.getNumClusterNodes()); int maxMemory = scheduler.getMaximumResourceCapability().getMemory(); Assert.assertEquals(expectedMaxMemory[0], maxMemory); RMNode node1 = MockNodes.newNodeInfo( 0, Resources.createResource(node1MaxMemory), 1, "127.0.0.2"); scheduler.handle(new NodeAddedSchedulerEvent(node1)); Assert.assertEquals(1, scheduler.getNumClusterNodes()); maxMemory = scheduler.getMaximumResourceCapability().getMemory(); Assert.assertEquals(expectedMaxMemory[1], maxMemory); scheduler.handle(new NodeRemovedSchedulerEvent(node1)); Assert.assertEquals(0, scheduler.getNumClusterNodes()); maxMemory = scheduler.getMaximumResourceCapability().getMemory(); Assert.assertEquals(expectedMaxMemory[2], maxMemory); RMNode node2 = MockNodes.newNodeInfo( 0, Resources.createResource(node2MaxMemory), 2, "127.0.0.3"); scheduler.handle(new NodeAddedSchedulerEvent(node2)); Assert.assertEquals(1, scheduler.getNumClusterNodes()); maxMemory = scheduler.getMaximumResourceCapability().getMemory(); Assert.assertEquals(expectedMaxMemory[3], maxMemory); RMNode node3 = MockNodes.newNodeInfo( 0, Resources.createResource(node3MaxMemory), 3, "127.0.0.4"); scheduler.handle(new NodeAddedSchedulerEvent(node3)); Assert.assertEquals(2, scheduler.getNumClusterNodes()); maxMemory = scheduler.getMaximumResourceCapability().getMemory(); Assert.assertEquals(expectedMaxMemory[4], maxMemory); scheduler.handle(new NodeRemovedSchedulerEvent(node3)); Assert.assertEquals(1, scheduler.getNumClusterNodes()); maxMemory = scheduler.getMaximumResourceCapability().getMemory(); Assert.assertEquals(expectedMaxMemory[5], maxMemory); scheduler.handle(new NodeRemovedSchedulerEvent(node2)); Assert.assertEquals(0, scheduler.getNumClusterNodes()); } @Test public void testMaximimumAllocationVCores() throws Exception { final int node1MaxVCores = 15; final int node2MaxVCores = 5; final int node3MaxVCores = 6; final int configuredMaxVCores = 10; configureScheduler(); YarnConfiguration conf = getConf(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, configuredMaxVCores); conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 1000 * 1000); MockRM rm = new MockRM(conf); try { rm.start(); testMaximumAllocationVCoresHelper( (AbstractYarnScheduler) rm.getResourceScheduler(), node1MaxVCores, node2MaxVCores, node3MaxVCores, configuredMaxVCores, configuredMaxVCores, configuredMaxVCores, configuredMaxVCores, configuredMaxVCores, configuredMaxVCores); } finally { rm.stop(); } conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 0); rm = new MockRM(conf); try { rm.start(); testMaximumAllocationVCoresHelper( (AbstractYarnScheduler) rm.getResourceScheduler(), node1MaxVCores, node2MaxVCores, node3MaxVCores, configuredMaxVCores, configuredMaxVCores, configuredMaxVCores, node2MaxVCores, node3MaxVCores, node2MaxVCores); } finally { rm.stop(); } } private void testMaximumAllocationVCoresHelper( AbstractYarnScheduler scheduler, final int node1MaxVCores, final int node2MaxVCores, final int node3MaxVCores, final int... expectedMaxVCores) throws Exception { Assert.assertEquals(6, expectedMaxVCores.length); Assert.assertEquals(0, scheduler.getNumClusterNodes()); int maxVCores = scheduler.getMaximumResourceCapability().getVirtualCores(); Assert.assertEquals(expectedMaxVCores[0], maxVCores); RMNode node1 = MockNodes.newNodeInfo( 0, Resources.createResource(1024, node1MaxVCores), 1, "127.0.0.2"); scheduler.handle(new NodeAddedSchedulerEvent(node1)); Assert.assertEquals(1, scheduler.getNumClusterNodes()); maxVCores = scheduler.getMaximumResourceCapability().getVirtualCores(); Assert.assertEquals(expectedMaxVCores[1], maxVCores); scheduler.handle(new NodeRemovedSchedulerEvent(node1)); Assert.assertEquals(0, scheduler.getNumClusterNodes()); maxVCores = scheduler.getMaximumResourceCapability().getVirtualCores(); Assert.assertEquals(expectedMaxVCores[2], maxVCores); RMNode node2 = MockNodes.newNodeInfo( 0, Resources.createResource(1024, node2MaxVCores), 2, "127.0.0.3"); scheduler.handle(new NodeAddedSchedulerEvent(node2)); Assert.assertEquals(1, scheduler.getNumClusterNodes()); maxVCores = scheduler.getMaximumResourceCapability().getVirtualCores(); Assert.assertEquals(expectedMaxVCores[3], maxVCores); RMNode node3 = MockNodes.newNodeInfo( 0, Resources.createResource(1024, node3MaxVCores), 3, "127.0.0.4"); scheduler.handle(new NodeAddedSchedulerEvent(node3)); Assert.assertEquals(2, scheduler.getNumClusterNodes()); maxVCores = scheduler.getMaximumResourceCapability().getVirtualCores(); Assert.assertEquals(expectedMaxVCores[4], maxVCores); scheduler.handle(new NodeRemovedSchedulerEvent(node3)); Assert.assertEquals(1, scheduler.getNumClusterNodes()); maxVCores = scheduler.getMaximumResourceCapability().getVirtualCores(); Assert.assertEquals(expectedMaxVCores[5], maxVCores); scheduler.handle(new NodeRemovedSchedulerEvent(node2)); Assert.assertEquals(0, scheduler.getNumClusterNodes()); } @Test public void testUpdateMaxAllocationUsesTotal() throws IOException { final int configuredMaxVCores = 20; final int configuredMaxMemory = 10 * 1024; Resource configuredMaximumResource = Resource.newInstance (configuredMaxMemory, configuredMaxVCores); configureScheduler(); YarnConfiguration conf = getConf(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, configuredMaxVCores); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, configuredMaxMemory); conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 0); MockRM rm = new MockRM(conf); try { rm.start(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm .getResourceScheduler(); Resource emptyResource = Resource.newInstance(0, 0); Resource fullResource1 = Resource.newInstance(1024, 5); Resource fullResource2 = Resource.newInstance(2048, 10); SchedulerNode mockNode1 = mock(SchedulerNode.class); when(mockNode1.getNodeID()).thenReturn(NodeId.newInstance("foo", 8080)); when(mockNode1.getAvailableResource()).thenReturn(emptyResource); when(mockNode1.getTotalResource()).thenReturn(fullResource1); SchedulerNode mockNode2 = mock(SchedulerNode.class); when(mockNode1.getNodeID()).thenReturn(NodeId.newInstance("bar", 8081)); when(mockNode2.getAvailableResource()).thenReturn(emptyResource); when(mockNode2.getTotalResource()).thenReturn(fullResource2); verifyMaximumResourceCapability(configuredMaximumResource, scheduler); scheduler.nodes = new HashMap<NodeId, SchedulerNode>(); scheduler.nodes.put(mockNode1.getNodeID(), mockNode1); scheduler.updateMaximumAllocation(mockNode1, true); verifyMaximumResourceCapability(fullResource1, scheduler); scheduler.nodes.put(mockNode2.getNodeID(), mockNode2); scheduler.updateMaximumAllocation(mockNode2, true); verifyMaximumResourceCapability(fullResource2, scheduler); scheduler.nodes.remove(mockNode2.getNodeID()); scheduler.updateMaximumAllocation(mockNode2, false); verifyMaximumResourceCapability(fullResource1, scheduler); scheduler.nodes.remove(mockNode1.getNodeID()); scheduler.updateMaximumAllocation(mockNode1, false); verifyMaximumResourceCapability(configuredMaximumResource, scheduler); } finally { rm.stop(); } } @Test public void testMaxAllocationAfterUpdateNodeResource() throws IOException { final int configuredMaxVCores = 20; final int configuredMaxMemory = 10 * 1024; Resource configuredMaximumResource = Resource.newInstance (configuredMaxMemory, configuredMaxVCores); configureScheduler(); YarnConfiguration conf = getConf(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, configuredMaxVCores); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, configuredMaxMemory); conf.setLong( YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_SCHEDULING_WAIT_MS, 0); MockRM rm = new MockRM(conf); try { rm.start(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm .getResourceScheduler(); verifyMaximumResourceCapability(configuredMaximumResource, scheduler); Resource resource1 = Resource.newInstance(2048, 5); Resource resource2 = Resource.newInstance(4096, 10); Resource resource3 = Resource.newInstance(512, 1); Resource resource4 = Resource.newInstance(1024, 2); RMNode node1 = MockNodes.newNodeInfo( 0, resource1, 1, "127.0.0.2"); scheduler.handle(new NodeAddedSchedulerEvent(node1)); RMNode node2 = MockNodes.newNodeInfo( 0, resource3, 2, "127.0.0.3"); scheduler.handle(new NodeAddedSchedulerEvent(node2)); verifyMaximumResourceCapability(resource1, scheduler); // increase node1 resource scheduler.updateNodeResource(node1, ResourceOption.newInstance( resource2, 0)); verifyMaximumResourceCapability(resource2, scheduler); // decrease node1 resource scheduler.updateNodeResource(node1, ResourceOption.newInstance( resource1, 0)); verifyMaximumResourceCapability(resource1, scheduler); // increase node2 resource scheduler.updateNodeResource(node2, ResourceOption.newInstance( resource4, 0)); verifyMaximumResourceCapability(resource1, scheduler); // decrease node2 resource scheduler.updateNodeResource(node2, ResourceOption.newInstance( resource3, 0)); verifyMaximumResourceCapability(resource1, scheduler); } finally { rm.stop(); } } /* * This test case is to test the pending containers are cleared from the * attempt even if one of the application in the list have current attempt as * null (no attempt). */ @SuppressWarnings({ "rawtypes" }) @Test(timeout = 10000) public void testReleasedContainerIfAppAttemptisNull() throws Exception { YarnConfiguration conf=getConf(); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm1 = new MockRM(conf, memStore); try { rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 8192, rm1.getResourceTrackerService()); nm1.registerNode(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm1.getResourceScheduler(); // Mock App without attempt RMApp mockAPp = new MockRMApp(125, System.currentTimeMillis(), RMAppState.NEW); SchedulerApplication<FiCaSchedulerApp> application = new SchedulerApplication<FiCaSchedulerApp>(null, mockAPp.getUser()); // Second app with one app attempt RMApp app = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app, rm1, nm1); final ContainerId runningContainer = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); am1.allocate(null, Arrays.asList(runningContainer)); Map schedulerApplications = scheduler.getSchedulerApplications(); SchedulerApplication schedulerApp = (SchedulerApplication) scheduler.getSchedulerApplications().get( app.getApplicationId()); schedulerApplications.put(mockAPp.getApplicationId(), application); scheduler.clearPendingContainerCache(); Assert.assertEquals("Pending containers are not released " + "when one of the application attempt is null !", schedulerApp .getCurrentAppAttempt().getPendingRelease().size(), 0); } finally { if (rm1 != null) { rm1.stop(); } } } @Test(timeout = 60000) public void testResourceRequestRestoreWhenRMContainerIsAtAllocated() throws Exception { configureScheduler(); YarnConfiguration conf = getConf(); MockRM rm1 = new MockRM(conf); try { rm1.start(); RMApp app1 = rm1.submitApp(200, "name", "user", new HashMap<ApplicationAccessType, String>(), false, "default", -1, null, "Test", false, true); MockNM nm1 = new MockNM("127.0.0.1:1234", 10240, rm1.getResourceTrackerService()); nm1.registerNode(); MockNM nm2 = new MockNM("127.0.0.1:2351", 10240, rm1.getResourceTrackerService()); nm2.registerNode(); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); int NUM_CONTAINERS = 1; // allocate NUM_CONTAINERS containers am1.allocate("127.0.0.1", 1024, NUM_CONTAINERS, new ArrayList<ContainerId>()); nm1.nodeHeartbeat(true); // wait for containers to be allocated. List<Container> containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (containers.size() != NUM_CONTAINERS) { nm1.nodeHeartbeat(true); containers.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(200); } // launch the 2nd container, for testing running container transferred. nm1.nodeHeartbeat(am1.getApplicationAttemptId(), 2, ContainerState.RUNNING); ContainerId containerId2 = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); rm1.waitForState(nm1, containerId2, RMContainerState.RUNNING); // 3rd container is in Allocated state. am1.allocate("127.0.0.1", 1024, NUM_CONTAINERS, new ArrayList<ContainerId>()); nm2.nodeHeartbeat(true); ContainerId containerId3 = ContainerId.newContainerId(am1.getApplicationAttemptId(), 3); rm1.waitForContainerAllocated(nm2, containerId3); rm1.waitForState(nm2, containerId3, RMContainerState.ALLOCATED); // NodeManager restart nm2.registerNode(); // NM restart kills all allocated and running containers. rm1.waitForState(nm2, containerId3, RMContainerState.KILLED); // The killed RMContainer request should be restored. In successive // nodeHeartBeats AM should be able to get container allocated. containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); while (containers.size() != NUM_CONTAINERS) { nm2.nodeHeartbeat(true); containers.addAll(am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers()); Thread.sleep(200); } nm2.nodeHeartbeat(am1.getApplicationAttemptId(), 4, ContainerState.RUNNING); ContainerId containerId4 = ContainerId.newContainerId(am1.getApplicationAttemptId(), 4); rm1.waitForState(nm2, containerId4, RMContainerState.RUNNING); } finally { rm1.stop(); } } private void verifyMaximumResourceCapability( Resource expectedMaximumResource, AbstractYarnScheduler scheduler) { final Resource schedulerMaximumResourceCapability = scheduler .getMaximumResourceCapability(); Assert.assertEquals(expectedMaximumResource.getMemory(), schedulerMaximumResourceCapability.getMemory()); Assert.assertEquals(expectedMaximumResource.getVirtualCores(), schedulerMaximumResourceCapability.getVirtualCores()); } }
20,767
39.962525
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/policy/TestFairOrderingPolicy.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.scheduler.policy; import java.util.*; import org.junit.Assert; import org.junit.Test; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; public class TestFairOrderingPolicy { final static int GB = 1024; @Test public void testSimpleComparison() { FairOrderingPolicy<MockSchedulableEntity> policy = new FairOrderingPolicy<MockSchedulableEntity>(); MockSchedulableEntity r1 = new MockSchedulableEntity(); MockSchedulableEntity r2 = new MockSchedulableEntity(); Assert.assertTrue(policy.getComparator().compare(r1, r2) == 0); //consumption r1.setUsed(Resources.createResource(1, 0)); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( r1.getSchedulingResourceUsage()); Assert.assertTrue(policy.getComparator().compare(r1, r2) > 0); } @Test public void testSizeBasedWeight() { FairOrderingPolicy<MockSchedulableEntity> policy = new FairOrderingPolicy<MockSchedulableEntity>(); policy.setSizeBasedWeight(true); MockSchedulableEntity r1 = new MockSchedulableEntity(); MockSchedulableEntity r2 = new MockSchedulableEntity(); //No changes, equal Assert.assertTrue(policy.getComparator().compare(r1, r2) == 0); r1.setUsed(Resources.createResource(4 * GB)); r2.setUsed(Resources.createResource(4 * GB)); r1.setPending(Resources.createResource(4 * GB)); r2.setPending(Resources.createResource(4 * GB)); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( r1.getSchedulingResourceUsage()); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( r2.getSchedulingResourceUsage()); //Same, equal Assert.assertTrue(policy.getComparator().compare(r1, r2) == 0); r2.setUsed(Resources.createResource(5 * GB)); r2.setPending(Resources.createResource(5 * GB)); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( r2.getSchedulingResourceUsage()); //More demand and consumption, but not enough more demand to overcome //additional consumption Assert.assertTrue(policy.getComparator().compare(r1, r2) < 0); //High demand, enough to reverse sbw r2.setPending(Resources.createResource(100 * GB)); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( r2.getSchedulingResourceUsage()); Assert.assertTrue(policy.getComparator().compare(r1, r2) > 0); } @Test public void testIterators() { OrderingPolicy<MockSchedulableEntity> schedOrder = new FairOrderingPolicy<MockSchedulableEntity>(); MockSchedulableEntity msp1 = new MockSchedulableEntity(); MockSchedulableEntity msp2 = new MockSchedulableEntity(); MockSchedulableEntity msp3 = new MockSchedulableEntity(); msp1.setId("1"); msp2.setId("2"); msp3.setId("3"); msp1.setUsed(Resources.createResource(3)); msp2.setUsed(Resources.createResource(2)); msp3.setUsed(Resources.createResource(1)); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( msp1.getSchedulingResourceUsage()); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( msp2.getSchedulingResourceUsage()); AbstractComparatorOrderingPolicy.updateSchedulingResourceUsage( msp2.getSchedulingResourceUsage()); schedOrder.addSchedulableEntity(msp1); schedOrder.addSchedulableEntity(msp2); schedOrder.addSchedulableEntity(msp3); //Assignment, least to greatest consumption checkIds(schedOrder.getAssignmentIterator(), new String[]{"3", "2", "1"}); //Preemption, greatest to least checkIds(schedOrder.getPreemptionIterator(), new String[]{"1", "2", "3"}); //Change value without inform, should see no change msp2.setUsed(Resources.createResource(6)); checkIds(schedOrder.getAssignmentIterator(), new String[]{"3", "2", "1"}); checkIds(schedOrder.getPreemptionIterator(), new String[]{"1", "2", "3"}); //Do inform, will reorder schedOrder.containerAllocated(msp2, null); checkIds(schedOrder.getAssignmentIterator(), new String[]{"3", "1", "2"}); checkIds(schedOrder.getPreemptionIterator(), new String[]{"2", "1", "3"}); } public void checkIds(Iterator<MockSchedulableEntity> si, String[] ids) { for (int i = 0;i < ids.length;i++) { Assert.assertEquals(si.next().getId(), ids[i]); } } }
5,499
35.666667
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/policy/TestFifoOrderingPolicy.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.scheduler.policy; import java.util.*; import org.junit.Assert; import org.junit.Test; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; public class TestFifoOrderingPolicy { @Test public void testFifoOrderingPolicy() { FifoOrderingPolicy<MockSchedulableEntity> policy = new FifoOrderingPolicy<MockSchedulableEntity>(); MockSchedulableEntity r1 = new MockSchedulableEntity(); MockSchedulableEntity r2 = new MockSchedulableEntity(); Assert.assertEquals(policy.getComparator().compare(r1, r2), 0); r1.setSerial(1); Assert.assertEquals(policy.getComparator().compare(r1, r2), 1); r2.setSerial(2); Assert.assertEquals(policy.getComparator().compare(r1, r2), -1); } @Test public void testIterators() { OrderingPolicy<MockSchedulableEntity> schedOrder = new FifoOrderingPolicy<MockSchedulableEntity>(); MockSchedulableEntity msp1 = new MockSchedulableEntity(); MockSchedulableEntity msp2 = new MockSchedulableEntity(); MockSchedulableEntity msp3 = new MockSchedulableEntity(); msp1.setSerial(3); msp2.setSerial(2); msp3.setSerial(1); schedOrder.addSchedulableEntity(msp1); schedOrder.addSchedulableEntity(msp2); schedOrder.addSchedulableEntity(msp3); //Assignment, oldest to youngest checkSerials(schedOrder.getAssignmentIterator(), new long[]{1, 2, 3}); //Preemption, youngest to oldest checkSerials(schedOrder.getPreemptionIterator(), new long[]{3, 2, 1}); } public void checkSerials(Iterator<MockSchedulableEntity> si, long[] serials) { for (int i = 0;i < serials.length;i++) { Assert.assertEquals(si.next().getSerial(), serials[i]); } } }
2,907
33.619048
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/policy/MockSchedulableEntity.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.scheduler.policy; import java.util.*; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; public class MockSchedulableEntity implements SchedulableEntity { private String id; private long serial = 0; private Priority priority; public MockSchedulableEntity() { } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setSerial(long serial) { this.serial = serial; } public long getSerial() { return serial; } public void setUsed(Resource value) { schedulingResourceUsage.setUsed(CommonNodeLabelsManager.ANY, value); } public void setPending(Resource value) { schedulingResourceUsage.setPending(CommonNodeLabelsManager.ANY, value); } private ResourceUsage schedulingResourceUsage = new ResourceUsage(); @Override public ResourceUsage getSchedulingResourceUsage() { return schedulingResourceUsage; } @Override public int compareInputOrderTo(SchedulableEntity other) { if (other instanceof MockSchedulableEntity) { MockSchedulableEntity r2 = (MockSchedulableEntity) other; int res = (int) Math.signum(getSerial() - r2.getSerial()); return res; } return 1;//let other types go before this, if any } @Override public Priority getPriority() { return priority; } public void setApplicationPriority(Priority priority) { this.priority = priority; } }
2,554
28.034091
77
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/TestFifoScheduler.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.scheduler.fifo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceOption; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.event.InlineDispatcher; import org.apache.hadoop.yarn.exceptions.YarnException; 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.server.api.protocolrecords.UpdateNodeResourceRequest; import org.apache.hadoop.yarn.server.resourcemanager.Application; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.Task; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; 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.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation; 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.SchedulerAppReport; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNodeReport; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.TestSchedulerUtils; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeResourceUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestFifoScheduler { private static final Log LOG = LogFactory.getLog(TestFifoScheduler.class); private final int GB = 1024; private ResourceManager resourceManager = null; private static Configuration conf; private static final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); @Before public void setUp() throws Exception { conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); resourceManager = new MockRM(conf); } @After public void tearDown() throws Exception { resourceManager.stop(); } private org.apache.hadoop.yarn.server.resourcemanager.NodeManager registerNode(String hostName, int containerManagerPort, int nmHttpPort, String rackName, Resource capability) throws IOException, YarnException { return new org.apache.hadoop.yarn.server.resourcemanager.NodeManager( hostName, containerManagerPort, nmHttpPort, rackName, capability, resourceManager); } private ApplicationAttemptId createAppAttemptId(int appId, int attemptId) { ApplicationId appIdImpl = ApplicationId.newInstance(0, appId); ApplicationAttemptId attId = ApplicationAttemptId.newInstance(appIdImpl, attemptId); return attId; } private ResourceRequest createResourceRequest(int memory, String host, int priority, int numContainers) { ResourceRequest request = recordFactory .newRecordInstance(ResourceRequest.class); request.setCapability(Resources.createResource(memory)); request.setResourceName(host); request.setNumContainers(numContainers); Priority prio = recordFactory.newRecordInstance(Priority.class); prio.setPriority(priority); request.setPriority(prio); return request; } @Test(timeout=5000) public void testFifoSchedulerCapacityWhenNoNMs() { FifoScheduler scheduler = new FifoScheduler(); QueueInfo queueInfo = scheduler.getQueueInfo(null, false, false); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity(), 0.0f); } @Test(timeout=5000) public void testAppAttemptMetrics() throws Exception { AsyncDispatcher dispatcher = new InlineDispatcher(); FifoScheduler scheduler = new FifoScheduler(); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); RMContext rmContext = new RMContextImpl(dispatcher, null, null, null, null, null, null, null, null, writer, scheduler); ((RMContextImpl) rmContext).setSystemMetricsPublisher( mock(SystemMetricsPublisher.class)); Configuration conf = new Configuration(); scheduler.setRMContext(rmContext); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, rmContext); QueueMetrics metrics = scheduler.getRootQueueMetrics(); int beforeAppsSubmitted = metrics.getAppsSubmitted(); ApplicationId appId = BuilderUtils.newApplicationId(200, 1); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId( appId, 1); SchedulerEvent appEvent = new AppAddedSchedulerEvent(appId, "queue", "user"); scheduler.handle(appEvent); SchedulerEvent attemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId, false); scheduler.handle(attemptEvent); appAttemptId = BuilderUtils.newApplicationAttemptId(appId, 2); SchedulerEvent attemptEvent2 = new AppAttemptAddedSchedulerEvent(appAttemptId, false); scheduler.handle(attemptEvent2); int afterAppsSubmitted = metrics.getAppsSubmitted(); Assert.assertEquals(1, afterAppsSubmitted - beforeAppsSubmitted); scheduler.stop(); } @Test(timeout=2000) public void testNodeLocalAssignment() throws Exception { AsyncDispatcher dispatcher = new InlineDispatcher(); Configuration conf = new Configuration(); RMContainerTokenSecretManager containerTokenSecretManager = new RMContainerTokenSecretManager(conf); containerTokenSecretManager.rollMasterKey(); NMTokenSecretManagerInRM nmTokenSecretManager = new NMTokenSecretManagerInRM(conf); nmTokenSecretManager.rollMasterKey(); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); FifoScheduler scheduler = new FifoScheduler(); RMContext rmContext = new RMContextImpl(dispatcher, null, null, null, null, null, containerTokenSecretManager, nmTokenSecretManager, null, writer, scheduler); ((RMContextImpl) rmContext).setSystemMetricsPublisher( mock(SystemMetricsPublisher.class)); ((RMContextImpl) rmContext).setYarnConfiguration(new YarnConfiguration()); scheduler.setRMContext(rmContext); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(new Configuration(), rmContext); RMNode node0 = MockNodes.newNodeInfo(1, Resources.createResource(1024 * 64), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node0); scheduler.handle(nodeEvent1); int _appId = 1; int _appAttemptId = 1; ApplicationAttemptId appAttemptId = createAppAttemptId(_appId, _appAttemptId); createMockRMApp(appAttemptId, rmContext); AppAddedSchedulerEvent appEvent = new AppAddedSchedulerEvent(appAttemptId.getApplicationId(), "queue1", "user1"); scheduler.handle(appEvent); AppAttemptAddedSchedulerEvent attemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId, false); scheduler.handle(attemptEvent); int memory = 64; int nConts = 3; int priority = 20; List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); ResourceRequest nodeLocal = createResourceRequest(memory, node0.getHostName(), priority, nConts); ResourceRequest rackLocal = createResourceRequest(memory, node0.getRackName(), priority, nConts); ResourceRequest any = createResourceRequest(memory, ResourceRequest.ANY, priority, nConts); ask.add(nodeLocal); ask.add(rackLocal); ask.add(any); scheduler.allocate(appAttemptId, ask, new ArrayList<ContainerId>(), null, null); NodeUpdateSchedulerEvent node0Update = new NodeUpdateSchedulerEvent(node0); // Before the node update event, there are 3 local requests outstanding Assert.assertEquals(3, nodeLocal.getNumContainers()); scheduler.handle(node0Update); // After the node update event, check that there are no more local requests // outstanding Assert.assertEquals(0, nodeLocal.getNumContainers()); //Also check that the containers were scheduled SchedulerAppReport info = scheduler.getSchedulerAppInfo(appAttemptId); Assert.assertEquals(3, info.getLiveContainers().size()); scheduler.stop(); } @Test(timeout=2000) public void testUpdateResourceOnNode() throws Exception { AsyncDispatcher dispatcher = new InlineDispatcher(); Configuration conf = new Configuration(); RMContainerTokenSecretManager containerTokenSecretManager = new RMContainerTokenSecretManager(conf); containerTokenSecretManager.rollMasterKey(); NMTokenSecretManagerInRM nmTokenSecretManager = new NMTokenSecretManagerInRM(conf); nmTokenSecretManager.rollMasterKey(); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); FifoScheduler scheduler = new FifoScheduler(){ @SuppressWarnings("unused") public Map<NodeId, FiCaSchedulerNode> getNodes(){ return nodes; } }; RMContext rmContext = new RMContextImpl(dispatcher, null, null, null, null, null, containerTokenSecretManager, nmTokenSecretManager, null, writer, scheduler); ((RMContextImpl) rmContext).setSystemMetricsPublisher( mock(SystemMetricsPublisher.class)); ((RMContextImpl) rmContext).setYarnConfiguration(new YarnConfiguration()); NullRMNodeLabelsManager nlm = new NullRMNodeLabelsManager(); nlm.init(new Configuration()); rmContext.setNodeLabelManager(nlm); scheduler.setRMContext(rmContext); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(new Configuration(), rmContext); RMNode node0 = MockNodes.newNodeInfo(1, Resources.createResource(2048, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node0); scheduler.handle(nodeEvent1); Method method = scheduler.getClass().getDeclaredMethod("getNodes"); @SuppressWarnings("unchecked") Map<NodeId, FiCaSchedulerNode> schedulerNodes = (Map<NodeId, FiCaSchedulerNode>) method.invoke(scheduler); assertEquals(schedulerNodes.values().size(), 1); Resource newResource = Resources.createResource(1024, 4); NodeResourceUpdateSchedulerEvent node0ResourceUpdate = new NodeResourceUpdateSchedulerEvent(node0, ResourceOption.newInstance( newResource, RMNode.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT)); scheduler.handle(node0ResourceUpdate); // SchedulerNode's total resource and available resource are changed. assertEquals(schedulerNodes.get(node0.getNodeID()).getTotalResource() .getMemory(), 1024); assertEquals(schedulerNodes.get(node0.getNodeID()). getAvailableResource().getMemory(), 1024); QueueInfo queueInfo = scheduler.getQueueInfo(null, false, false); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity(), 0.0f); int _appId = 1; int _appAttemptId = 1; ApplicationAttemptId appAttemptId = createAppAttemptId(_appId, _appAttemptId); createMockRMApp(appAttemptId, rmContext); AppAddedSchedulerEvent appEvent = new AppAddedSchedulerEvent(appAttemptId.getApplicationId(), "queue1", "user1"); scheduler.handle(appEvent); AppAttemptAddedSchedulerEvent attemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId, false); scheduler.handle(attemptEvent); int memory = 1024; int priority = 1; List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); ResourceRequest nodeLocal = createResourceRequest(memory, node0.getHostName(), priority, 1); ResourceRequest rackLocal = createResourceRequest(memory, node0.getRackName(), priority, 1); ResourceRequest any = createResourceRequest(memory, ResourceRequest.ANY, priority, 1); ask.add(nodeLocal); ask.add(rackLocal); ask.add(any); scheduler.allocate(appAttemptId, ask, new ArrayList<ContainerId>(), null, null); // Before the node update event, there are one local request Assert.assertEquals(1, nodeLocal.getNumContainers()); NodeUpdateSchedulerEvent node0Update = new NodeUpdateSchedulerEvent(node0); // Now schedule. scheduler.handle(node0Update); // After the node update event, check no local request Assert.assertEquals(0, nodeLocal.getNumContainers()); // Also check that one container was scheduled SchedulerAppReport info = scheduler.getSchedulerAppInfo(appAttemptId); Assert.assertEquals(1, info.getLiveContainers().size()); // And check the default Queue now is full. queueInfo = scheduler.getQueueInfo(null, false, false); Assert.assertEquals(1.0f, queueInfo.getCurrentCapacity(), 0.0f); } // @Test public void testFifoScheduler() throws Exception { LOG.info("--- START: testFifoScheduler ---"); final int GB = 1024; // Register node1 String host_0 = "host_0"; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(4 * GB, 1)); nm_0.heartbeat(); // Register node2 String host_1 = "host_1"; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_1 = registerNode(host_1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(2 * GB, 1)); nm_1.heartbeat(); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.create(1); // Submit an application Application application_0 = new Application("user_0", resourceManager); application_0.submit(); application_0.addNodeManager(host_0, 1234, nm_0); application_0.addNodeManager(host_1, 1234, nm_1); Resource capability_0_0 = Resources.createResource(GB); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * GB); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] {host_0, host_1}); application_0.addTask(task_0_0); // Submit another application Application application_1 = new Application("user_1", resourceManager); application_1.submit(); application_1.addNodeManager(host_0, 1234, nm_0); application_1.addNodeManager(host_1, 1234, nm_1); Resource capability_1_0 = Resources.createResource(3 * GB); application_1.addResourceRequestSpec(priority_1, capability_1_0); Resource capability_1_1 = Resources.createResource(4 * GB); application_1.addResourceRequestSpec(priority_0, capability_1_1); Task task_1_0 = new Task(application_1, priority_1, new String[] {host_0, host_1}); application_1.addTask(task_1_0); // Send resource requests to the scheduler LOG.info("Send resource requests to the scheduler"); application_0.schedule(); application_1.schedule(); // Send a heartbeat to kick the tires on the Scheduler LOG.info("Send a heartbeat to kick the tires on the Scheduler... " + "nm0 -> task_0_0 and task_1_0 allocated, used=4G " + "nm1 -> nothing allocated"); nm_0.heartbeat(); // task_0_0 and task_1_0 allocated, used=4G nm_1.heartbeat(); // nothing allocated // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(GB, application_0); application_1.schedule(); // task_1_0 checkApplicationResourceUsage(3 * GB, application_1); nm_0.heartbeat(); nm_1.heartbeat(); checkNodeResourceUsage(4*GB, nm_0); // task_0_0 (1G) and task_1_0 (3G) checkNodeResourceUsage(0*GB, nm_1); // no tasks, 2G available LOG.info("Adding new tasks..."); Task task_1_1 = new Task(application_1, priority_1, new String[] {ResourceRequest.ANY}); application_1.addTask(task_1_1); Task task_1_2 = new Task(application_1, priority_1, new String[] {ResourceRequest.ANY}); application_1.addTask(task_1_2); Task task_1_3 = new Task(application_1, priority_0, new String[] {ResourceRequest.ANY}); application_1.addTask(task_1_3); application_1.schedule(); Task task_0_1 = new Task(application_0, priority_1, new String[] {host_0, host_1}); application_0.addTask(task_0_1); Task task_0_2 = new Task(application_0, priority_1, new String[] {host_0, host_1}); application_0.addTask(task_0_2); Task task_0_3 = new Task(application_0, priority_0, new String[] {ResourceRequest.ANY}); application_0.addTask(task_0_3); application_0.schedule(); // Send a heartbeat to kick the tires on the Scheduler LOG.info("Sending hb from " + nm_0.getHostName()); nm_0.heartbeat(); // nothing new, used=4G LOG.info("Sending hb from " + nm_1.getHostName()); nm_1.heartbeat(); // task_0_3, used=2G // Get allocations from the scheduler LOG.info("Trying to allocate..."); application_0.schedule(); checkApplicationResourceUsage(3 * GB, application_0); application_1.schedule(); checkApplicationResourceUsage(3 * GB, application_1); nm_0.heartbeat(); nm_1.heartbeat(); checkNodeResourceUsage(4*GB, nm_0); checkNodeResourceUsage(2*GB, nm_1); // Complete tasks LOG.info("Finishing up task_0_0"); application_0.finishTask(task_0_0); // Now task_0_1 application_0.schedule(); application_1.schedule(); nm_0.heartbeat(); nm_1.heartbeat(); checkApplicationResourceUsage(3 * GB, application_0); checkApplicationResourceUsage(3 * GB, application_1); checkNodeResourceUsage(4*GB, nm_0); checkNodeResourceUsage(2*GB, nm_1); LOG.info("Finishing up task_1_0"); application_1.finishTask(task_1_0); // Now task_0_2 application_0.schedule(); // final overcommit for app0 caused here application_1.schedule(); nm_0.heartbeat(); // final overcommit for app0 occurs here nm_1.heartbeat(); checkApplicationResourceUsage(4 * GB, application_0); checkApplicationResourceUsage(0 * GB, application_1); //checkNodeResourceUsage(1*GB, nm_0); // final over-commit -> rm.node->1G, test.node=2G checkNodeResourceUsage(2*GB, nm_1); LOG.info("Finishing up task_0_3"); application_0.finishTask(task_0_3); // No more application_0.schedule(); application_1.schedule(); nm_0.heartbeat(); nm_1.heartbeat(); checkApplicationResourceUsage(2 * GB, application_0); checkApplicationResourceUsage(0 * GB, application_1); //checkNodeResourceUsage(2*GB, nm_0); // final over-commit, rm.node->1G, test.node->2G checkNodeResourceUsage(0*GB, nm_1); LOG.info("Finishing up task_0_1"); application_0.finishTask(task_0_1); application_0.schedule(); application_1.schedule(); nm_0.heartbeat(); nm_1.heartbeat(); checkApplicationResourceUsage(1 * GB, application_0); checkApplicationResourceUsage(0 * GB, application_1); LOG.info("Finishing up task_0_2"); application_0.finishTask(task_0_2); // now task_1_3 can go! application_0.schedule(); application_1.schedule(); nm_0.heartbeat(); nm_1.heartbeat(); checkApplicationResourceUsage(0 * GB, application_0); checkApplicationResourceUsage(4 * GB, application_1); LOG.info("Finishing up task_1_3"); application_1.finishTask(task_1_3); // now task_1_1 application_0.schedule(); application_1.schedule(); nm_0.heartbeat(); nm_1.heartbeat(); checkApplicationResourceUsage(0 * GB, application_0); checkApplicationResourceUsage(3 * GB, application_1); LOG.info("Finishing up task_1_1"); application_1.finishTask(task_1_1); application_0.schedule(); application_1.schedule(); nm_0.heartbeat(); nm_1.heartbeat(); checkApplicationResourceUsage(0 * GB, application_0); checkApplicationResourceUsage(3 * GB, application_1); LOG.info("--- END: testFifoScheduler ---"); } @Test public void testGetAppsInQueue() throws Exception { Application application_0 = new Application("user_0", resourceManager); application_0.submit(); Application application_1 = new Application("user_0", resourceManager); application_1.submit(); ResourceScheduler scheduler = resourceManager.getResourceScheduler(); List<ApplicationAttemptId> appsInDefault = scheduler.getAppsInQueue("default"); assertTrue(appsInDefault.contains(application_0.getApplicationAttemptId())); assertTrue(appsInDefault.contains(application_1.getApplicationAttemptId())); assertEquals(2, appsInDefault.size()); Assert.assertNull(scheduler.getAppsInQueue("someotherqueue")); } @Test public void testAddAndRemoveAppFromFiFoScheduler() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); @SuppressWarnings("unchecked") AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode> fs = (AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode>) rm .getResourceScheduler(); TestSchedulerUtils.verifyAppAddedAndRemovedFromScheduler( fs.getSchedulerApplications(), fs, "queue"); } @Test(timeout = 30000) public void testConfValidation() throws Exception { FifoScheduler scheduler = new FifoScheduler(); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 2048); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 1024); try { scheduler.serviceInit(conf); fail("Exception is expected because the min memory allocation is" + " larger than the max memory allocation."); } catch (YarnRuntimeException e) { // Exception is expected. assertTrue("The thrown exception is not the expected one.", e .getMessage().startsWith("Invalid resource scheduler memory")); } } @Test(timeout = 60000) public void testAllocateContainerOnNodeWithoutOffSwitchSpecified() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); RMApp app1 = rm.submitApp(2048); // kick the scheduling, 2 GB given to AM1, remaining 4GB on nm1 nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); // add request for containers List<ResourceRequest> requests = new ArrayList<ResourceRequest>(); requests.add(am1.createResourceReq("127.0.0.1", 1 * GB, 1, 1)); requests.add(am1.createResourceReq("/default-rack", 1 * GB, 1, 1)); am1.allocate(requests, null); // send the request try { // kick the schedule nm1.nodeHeartbeat(true); } catch (NullPointerException e) { Assert.fail("NPE when allocating container on node but " + "forget to set off-switch request should be handled"); } rm.stop(); } @Test(timeout = 60000) public void testFifoScheduling() throws Exception { Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.DEBUG); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); MockNM nm2 = rm.registerNode("127.0.0.2:5678", 4 * GB); RMApp app1 = rm.submitApp(2048); // kick the scheduling, 2 GB given to AM1, remaining 4GB on nm1 nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(2 * GB, report_nm1.getUsedResource().getMemory()); RMApp app2 = rm.submitApp(2048); // kick the scheduling, 2GB given to AM, remaining 2 GB on nm2 nm2.nodeHeartbeat(true); RMAppAttempt attempt2 = app2.getCurrentAppAttempt(); MockAM am2 = rm.sendAMLaunched(attempt2.getAppAttemptId()); am2.registerAppAttempt(); SchedulerNodeReport report_nm2 = rm.getResourceScheduler().getNodeReport(nm2.getNodeId()); Assert.assertEquals(2 * GB, report_nm2.getUsedResource().getMemory()); // add request for containers am1.addRequests(new String[] { "127.0.0.1", "127.0.0.2" }, GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); // send the request // add request for containers am2.addRequests(new String[] { "127.0.0.1", "127.0.0.2" }, 3 * GB, 0, 1); AllocateResponse alloc2Response = am2.schedule(); // send the request // kick the scheduler, 1 GB and 3 GB given to AM1 and AM2, remaining 0 nm1.nodeHeartbeat(true); while (alloc1Response.getAllocatedContainers().size() < 1) { LOG.info("Waiting for containers to be created for app 1..."); Thread.sleep(1000); alloc1Response = am1.schedule(); } while (alloc2Response.getAllocatedContainers().size() < 1) { LOG.info("Waiting for containers to be created for app 2..."); Thread.sleep(1000); alloc2Response = am2.schedule(); } // kick the scheduler, nothing given remaining 2 GB. nm2.nodeHeartbeat(true); List<Container> allocated1 = alloc1Response.getAllocatedContainers(); Assert.assertEquals(1, allocated1.size()); Assert.assertEquals(1 * GB, allocated1.get(0).getResource().getMemory()); Assert.assertEquals(nm1.getNodeId(), allocated1.get(0).getNodeId()); List<Container> allocated2 = alloc2Response.getAllocatedContainers(); Assert.assertEquals(1, allocated2.size()); Assert.assertEquals(3 * GB, allocated2.get(0).getResource().getMemory()); Assert.assertEquals(nm1.getNodeId(), allocated2.get(0).getNodeId()); report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); report_nm2 = rm.getResourceScheduler().getNodeReport(nm2.getNodeId()); Assert.assertEquals(0, report_nm1.getAvailableResource().getMemory()); Assert.assertEquals(2 * GB, report_nm2.getAvailableResource().getMemory()); Assert.assertEquals(6 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(2 * GB, report_nm2.getUsedResource().getMemory()); Container c1 = allocated1.get(0); Assert.assertEquals(GB, c1.getResource().getMemory()); ContainerStatus containerStatus = BuilderUtils.newContainerStatus(c1.getId(), ContainerState.COMPLETE, "", 0); nm1.containerStatus(containerStatus); int waitCount = 0; while (attempt1.getJustFinishedContainers().size() < 1 && waitCount++ != 20) { LOG.info("Waiting for containers to be finished for app 1... Tried " + waitCount + " times already.."); Thread.sleep(1000); } Assert.assertEquals(1, attempt1.getJustFinishedContainers().size()); Assert.assertEquals(1, am1.schedule().getCompletedContainersStatuses() .size()); report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(5 * GB, report_nm1.getUsedResource().getMemory()); rm.stop(); } @Test(timeout = 60000) public void testNodeUpdateBeforeAppAttemptInit() throws Exception { FifoScheduler scheduler = new FifoScheduler(); MockRM rm = new MockRM(conf); scheduler.setRMContext(rm.getRMContext()); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, rm.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(1024, 4), 1, "127.0.0.1"); scheduler.handle(new NodeAddedSchedulerEvent(node)); ApplicationId appId = ApplicationId.newInstance(0, 1); scheduler.addApplication(appId, "queue1", "user1", false); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); try { scheduler.handle(updateEvent); } catch (NullPointerException e) { Assert.fail(); } ApplicationAttemptId attId = ApplicationAttemptId.newInstance(appId, 1); scheduler.addApplicationAttempt(attId, false, false); rm.stop(); } private void testMinimumAllocation(YarnConfiguration conf, int testAlloc) throws Exception { MockRM rm = new MockRM(conf); rm.start(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); // Submit an application RMApp app1 = rm.submitApp(testAlloc); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); int checkAlloc = conf.getInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); Assert.assertEquals(checkAlloc, report_nm1.getUsedResource().getMemory()); rm.stop(); } @Test(timeout = 60000) public void testDefaultMinimumAllocation() throws Exception { // Test with something lesser than default testMinimumAllocation(new YarnConfiguration(TestFifoScheduler.conf), YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB / 2); } @Test(timeout = 60000) public void testNonDefaultMinimumAllocation() throws Exception { // Set custom min-alloc to test tweaking it int allocMB = 1536; YarnConfiguration conf = new YarnConfiguration(TestFifoScheduler.conf); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, allocMB); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, allocMB * 10); // Test for something lesser than this. testMinimumAllocation(conf, allocMB / 2); } @Test(timeout = 50000) public void testReconnectedNode() throws Exception { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); conf.setQueues("default", new String[] { "default" }); conf.setCapacity("default", 100); FifoScheduler fs = new FifoScheduler(); fs.init(conf); fs.start(); // mock rmContext to avoid NPE. RMContext context = mock(RMContext.class); fs.reinitialize(conf, null); fs.setRMContext(context); RMNode n1 = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1, "127.0.0.2"); RMNode n2 = MockNodes.newNodeInfo(0, MockNodes.newResource(2 * GB), 2, "127.0.0.3"); fs.handle(new NodeAddedSchedulerEvent(n1)); fs.handle(new NodeAddedSchedulerEvent(n2)); fs.handle(new NodeUpdateSchedulerEvent(n1)); Assert.assertEquals(6 * GB, fs.getRootQueueMetrics().getAvailableMB()); // reconnect n1 with downgraded memory n1 = MockNodes.newNodeInfo(0, MockNodes.newResource(2 * GB), 1, "127.0.0.2"); fs.handle(new NodeRemovedSchedulerEvent(n1)); fs.handle(new NodeAddedSchedulerEvent(n1)); fs.handle(new NodeUpdateSchedulerEvent(n1)); Assert.assertEquals(4 * GB, fs.getRootQueueMetrics().getAvailableMB()); fs.stop(); } @Test(timeout = 50000) public void testBlackListNodes() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); FifoScheduler fs = (FifoScheduler) rm.getResourceScheduler(); int rack_num_0 = 0; int rack_num_1 = 1; // Add 4 nodes in 2 racks // host_0_0 in rack0 String host_0_0 = "127.0.0.1"; RMNode n1 = MockNodes.newNodeInfo(rack_num_0, MockNodes.newResource(4 * GB), 1, host_0_0); fs.handle(new NodeAddedSchedulerEvent(n1)); // host_0_1 in rack0 String host_0_1 = "127.0.0.2"; RMNode n2 = MockNodes.newNodeInfo(rack_num_0, MockNodes.newResource(4 * GB), 1, host_0_1); fs.handle(new NodeAddedSchedulerEvent(n2)); // host_1_0 in rack1 String host_1_0 = "127.0.0.3"; RMNode n3 = MockNodes.newNodeInfo(rack_num_1, MockNodes.newResource(4 * GB), 1, host_1_0); fs.handle(new NodeAddedSchedulerEvent(n3)); // host_1_1 in rack1 String host_1_1 = "127.0.0.4"; RMNode n4 = MockNodes.newNodeInfo(rack_num_1, MockNodes.newResource(4 * GB), 1, host_1_1); fs.handle(new NodeAddedSchedulerEvent(n4)); // Add one application ApplicationId appId1 = BuilderUtils.newApplicationId(100, 1); ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId(appId1, 1); createMockRMApp(appAttemptId1, rm.getRMContext()); SchedulerEvent appEvent = new AppAddedSchedulerEvent(appId1, "queue", "user"); fs.handle(appEvent); SchedulerEvent attemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId1, false); fs.handle(attemptEvent); List<ContainerId> emptyId = new ArrayList<ContainerId>(); List<ResourceRequest> emptyAsk = new ArrayList<ResourceRequest>(); // Allow rack-locality for rack_1, but blacklist host_1_0 // Set up resource requests // Ask for a 1 GB container for app 1 List<ResourceRequest> ask1 = new ArrayList<ResourceRequest>(); ask1.add(BuilderUtils.newResourceRequest(BuilderUtils.newPriority(0), "rack1", BuilderUtils.newResource(GB, 1), 1)); ask1.add(BuilderUtils.newResourceRequest(BuilderUtils.newPriority(0), ResourceRequest.ANY, BuilderUtils.newResource(GB, 1), 1)); fs.allocate(appAttemptId1, ask1, emptyId, Collections.singletonList(host_1_0), null); // Trigger container assignment fs.handle(new NodeUpdateSchedulerEvent(n3)); // Get the allocation for the application and verify no allocation on // blacklist node Allocation allocation1 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("allocation1", 0, allocation1.getContainers().size()); // verify host_1_1 can get allocated as not in blacklist fs.handle(new NodeUpdateSchedulerEvent(n4)); Allocation allocation2 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("allocation2", 1, allocation2.getContainers().size()); List<Container> containerList = allocation2.getContainers(); for (Container container : containerList) { Assert.assertEquals("Container is allocated on n4", container.getNodeId(), n4.getNodeID()); } // Ask for a 1 GB container again for app 1 List<ResourceRequest> ask2 = new ArrayList<ResourceRequest>(); // this time, rack0 is also in blacklist, so only host_1_1 is available to // be assigned ask2.add(BuilderUtils.newResourceRequest(BuilderUtils.newPriority(0), ResourceRequest.ANY, BuilderUtils.newResource(GB, 1), 1)); fs.allocate(appAttemptId1, ask2, emptyId, Collections.singletonList("rack0"), null); // verify n1 is not qualified to be allocated fs.handle(new NodeUpdateSchedulerEvent(n1)); Allocation allocation3 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("allocation3", 0, allocation3.getContainers().size()); // verify n2 is not qualified to be allocated fs.handle(new NodeUpdateSchedulerEvent(n2)); Allocation allocation4 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("allocation4", 0, allocation4.getContainers().size()); // verify n3 is not qualified to be allocated fs.handle(new NodeUpdateSchedulerEvent(n3)); Allocation allocation5 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("allocation5", 0, allocation5.getContainers().size()); fs.handle(new NodeUpdateSchedulerEvent(n4)); Allocation allocation6 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("allocation6", 1, allocation6.getContainers().size()); containerList = allocation6.getContainers(); for (Container container : containerList) { Assert.assertEquals("Container is allocated on n4", container.getNodeId(), n4.getNodeID()); } rm.stop(); } @Test(timeout = 50000) public void testHeadroom() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); FifoScheduler fs = (FifoScheduler) rm.getResourceScheduler(); // Add a node RMNode n1 = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1, "127.0.0.2"); fs.handle(new NodeAddedSchedulerEvent(n1)); // Add two applications ApplicationId appId1 = BuilderUtils.newApplicationId(100, 1); ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId(appId1, 1); createMockRMApp(appAttemptId1, rm.getRMContext()); SchedulerEvent appEvent = new AppAddedSchedulerEvent(appId1, "queue", "user"); fs.handle(appEvent); SchedulerEvent attemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId1, false); fs.handle(attemptEvent); ApplicationId appId2 = BuilderUtils.newApplicationId(200, 2); ApplicationAttemptId appAttemptId2 = BuilderUtils.newApplicationAttemptId(appId2, 1); createMockRMApp(appAttemptId2, rm.getRMContext()); SchedulerEvent appEvent2 = new AppAddedSchedulerEvent(appId2, "queue", "user"); fs.handle(appEvent2); SchedulerEvent attemptEvent2 = new AppAttemptAddedSchedulerEvent(appAttemptId2, false); fs.handle(attemptEvent2); List<ContainerId> emptyId = new ArrayList<ContainerId>(); List<ResourceRequest> emptyAsk = new ArrayList<ResourceRequest>(); // Set up resource requests // Ask for a 1 GB container for app 1 List<ResourceRequest> ask1 = new ArrayList<ResourceRequest>(); ask1.add(BuilderUtils.newResourceRequest(BuilderUtils.newPriority(0), ResourceRequest.ANY, BuilderUtils.newResource(GB, 1), 1)); fs.allocate(appAttemptId1, ask1, emptyId, null, null); // Ask for a 2 GB container for app 2 List<ResourceRequest> ask2 = new ArrayList<ResourceRequest>(); ask2.add(BuilderUtils.newResourceRequest(BuilderUtils.newPriority(0), ResourceRequest.ANY, BuilderUtils.newResource(2 * GB, 1), 1)); fs.allocate(appAttemptId2, ask2, emptyId, null, null); // Trigger container assignment fs.handle(new NodeUpdateSchedulerEvent(n1)); // Get the allocation for the applications and verify headroom Allocation allocation1 = fs.allocate(appAttemptId1, emptyAsk, emptyId, null, null); Assert.assertEquals("Allocation headroom", 1 * GB, allocation1 .getResourceLimit().getMemory()); Allocation allocation2 = fs.allocate(appAttemptId2, emptyAsk, emptyId, null, null); Assert.assertEquals("Allocation headroom", 1 * GB, allocation2 .getResourceLimit().getMemory()); rm.stop(); } @Test(timeout = 60000) public void testResourceOverCommit() throws Exception { MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 4 * GB); RMApp app1 = rm.submitApp(2048); // kick the scheduling, 2 GB given to AM1, remaining 2GB on nm1 nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); // check node report, 2 GB used and 2 GB available Assert.assertEquals(2 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(2 * GB, report_nm1.getAvailableResource().getMemory()); // add request for containers am1.addRequests(new String[] { "127.0.0.1", "127.0.0.2" }, 2 * GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); // send the request // kick the scheduler, 2 GB given to AM1, resource remaining 0 nm1.nodeHeartbeat(true); while (alloc1Response.getAllocatedContainers().size() < 1) { LOG.info("Waiting for containers to be created for app 1..."); Thread.sleep(1000); alloc1Response = am1.schedule(); } List<Container> allocated1 = alloc1Response.getAllocatedContainers(); Assert.assertEquals(1, allocated1.size()); Assert.assertEquals(2 * GB, allocated1.get(0).getResource().getMemory()); Assert.assertEquals(nm1.getNodeId(), allocated1.get(0).getNodeId()); report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); // check node report, 4 GB used and 0 GB available Assert.assertEquals(0, report_nm1.getAvailableResource().getMemory()); Assert.assertEquals(4 * GB, report_nm1.getUsedResource().getMemory()); // check container is assigned with 2 GB. Container c1 = allocated1.get(0); Assert.assertEquals(2 * GB, c1.getResource().getMemory()); // update node resource to 2 GB, so resource is over-consumed. Map<NodeId, ResourceOption> nodeResourceMap = new HashMap<NodeId, ResourceOption>(); nodeResourceMap.put(nm1.getNodeId(), ResourceOption.newInstance(Resource.newInstance(2 * GB, 1), -1)); UpdateNodeResourceRequest request = UpdateNodeResourceRequest.newInstance(nodeResourceMap); rm.getAdminService().updateNodeResource(request); // Now, the used resource is still 4 GB, and available resource is minus // value. report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(4 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(-2 * GB, report_nm1.getAvailableResource().getMemory()); // Check container can complete successfully in case of resource // over-commitment. ContainerStatus containerStatus = BuilderUtils.newContainerStatus(c1.getId(), ContainerState.COMPLETE, "", 0); nm1.containerStatus(containerStatus); int waitCount = 0; while (attempt1.getJustFinishedContainers().size() < 1 && waitCount++ != 20) { LOG.info("Waiting for containers to be finished for app 1... Tried " + waitCount + " times already.."); Thread.sleep(100); } Assert.assertEquals(1, attempt1.getJustFinishedContainers().size()); Assert.assertEquals(1, am1.schedule().getCompletedContainersStatuses() .size()); report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(2 * GB, report_nm1.getUsedResource().getMemory()); // As container return 2 GB back, the available resource becomes 0 again. Assert.assertEquals(0 * GB, report_nm1.getAvailableResource().getMemory()); rm.stop(); } private void checkApplicationResourceUsage(int expected, Application application) { Assert.assertEquals(expected, application.getUsedResources().getMemory()); } private void checkNodeResourceUsage(int expected, org.apache.hadoop.yarn.server.resourcemanager.NodeManager node) { Assert.assertEquals(expected, node.getUsed().getMemory()); node.checkResourceUsage(); } public static void main(String[] arg) throws Exception { TestFifoScheduler t = new TestFifoScheduler(); t.setUp(); t.testFifoScheduler(); t.tearDown(); } private RMAppImpl createMockRMApp(ApplicationAttemptId attemptId, RMContext context) { RMAppImpl app = mock(RMAppImpl.class); when(app.getApplicationId()).thenReturn(attemptId.getApplicationId()); RMAppAttemptImpl attempt = mock(RMAppAttemptImpl.class); when(attempt.getAppAttemptId()).thenReturn(attemptId); RMAppAttemptMetrics attemptMetric = mock(RMAppAttemptMetrics.class); when(attempt.getRMAppAttemptMetrics()).thenReturn(attemptMetric); when(app.getCurrentAppAttempt()).thenReturn(attempt); ApplicationSubmissionContext submissionContext = mock(ApplicationSubmissionContext.class); when(submissionContext.getUnmanagedAM()).thenReturn(false); when(attempt.getSubmissionContext()).thenReturn(submissionContext); context.getRMApps().putIfAbsent(attemptId.getApplicationId(), app); return app; } }
49,443
40.27212
103
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFSLeafQueue.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.scheduler.fair; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestFSLeafQueue extends FairSchedulerTestBase { private final static String ALLOC_FILE = new File(TEST_DIR, TestFSLeafQueue.class.getName() + ".xml").getAbsolutePath(); private Resource maxResource = Resources.createResource(1024 * 8); @Before public void setup() throws IOException { conf = createConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class, ResourceScheduler.class); } @After public void teardown() { if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } conf = null; } @Test public void testUpdateDemand() { conf.set(FairSchedulerConfiguration.ASSIGN_MULTIPLE, "false"); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); scheduler.allocConf = mock(AllocationConfiguration.class); String queueName = "root.queue1"; when(scheduler.allocConf.getMaxResources(queueName)).thenReturn(maxResource); when(scheduler.allocConf.getMinResources(queueName)).thenReturn(Resources.none()); FSLeafQueue schedulable = new FSLeafQueue(queueName, scheduler, null); FSAppAttempt app = mock(FSAppAttempt.class); Mockito.when(app.getDemand()).thenReturn(maxResource); schedulable.addAppSchedulable(app); schedulable.addAppSchedulable(app); schedulable.updateDemand(); assertTrue("Demand is greater than max allowed ", Resources.equals(schedulable.getDemand(), maxResource)); } @Test (timeout = 5000) public void test() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("</queue>"); out.println("</allocations>"); out.close(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); scheduler.update(); // Queue A wants 3 * 1024. Node update gives this all to A createSchedulingRequest(3 * 1024, "queueA", "user1"); scheduler.update(); NodeUpdateSchedulerEvent nodeEvent2 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeEvent2); // Queue B arrives and wants 1 * 1024 createSchedulingRequest(1 * 1024, "queueB", "user1"); scheduler.update(); Collection<FSLeafQueue> queues = scheduler.getQueueManager().getLeafQueues(); assertEquals(3, queues.size()); // Queue A should be above min share, B below. FSLeafQueue queueA = scheduler.getQueueManager().getLeafQueue("queueA", false); FSLeafQueue queueB = scheduler.getQueueManager().getLeafQueue("queueB", false); assertFalse(queueA.isStarvedForMinShare()); assertTrue(queueB.isStarvedForMinShare()); // Node checks in again, should allocate for B scheduler.handle(nodeEvent2); // Now B should have min share ( = demand here) assertFalse(queueB.isStarvedForMinShare()); } @Test (timeout = 5000) public void testIsStarvedForFairShare() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.2</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.8</weight>"); out.println("<fairSharePreemptionThreshold>.4</fairSharePreemptionThreshold>"); out.println("<queue name=\"queueB1\">"); out.println("</queue>"); out.println("<queue name=\"queueB2\">"); out.println("<fairSharePreemptionThreshold>.6</fairSharePreemptionThreshold>"); out.println("</queue>"); out.println("</queue>"); out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>"); out.println("</allocations>"); out.close(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(10 * 1024, 10), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); scheduler.update(); // Queue A wants 4 * 1024. Node update gives this all to A createSchedulingRequest(1 * 1024, "queueA", "user1", 4); scheduler.update(); NodeUpdateSchedulerEvent nodeEvent2 = new NodeUpdateSchedulerEvent(node1); for (int i = 0; i < 4; i ++) { scheduler.handle(nodeEvent2); } QueueManager queueMgr = scheduler.getQueueManager(); FSLeafQueue queueA = queueMgr.getLeafQueue("queueA", false); assertEquals(4 * 1024, queueA.getResourceUsage().getMemory()); // Both queue B1 and queue B2 want 3 * 1024 createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 3); createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 3); scheduler.update(); for (int i = 0; i < 4; i ++) { scheduler.handle(nodeEvent2); } FSLeafQueue queueB1 = queueMgr.getLeafQueue("queueB.queueB1", false); FSLeafQueue queueB2 = queueMgr.getLeafQueue("queueB.queueB2", false); assertEquals(2 * 1024, queueB1.getResourceUsage().getMemory()); assertEquals(2 * 1024, queueB2.getResourceUsage().getMemory()); // For queue B1, the fairSharePreemptionThreshold is 0.4, and the fair share // threshold is 1.6 * 1024 assertFalse(queueB1.isStarvedForFairShare()); // For queue B2, the fairSharePreemptionThreshold is 0.6, and the fair share // threshold is 2.4 * 1024 assertTrue(queueB2.isStarvedForFairShare()); // Node checks in again scheduler.handle(nodeEvent2); scheduler.handle(nodeEvent2); assertEquals(3 * 1024, queueB1.getResourceUsage().getMemory()); assertEquals(3 * 1024, queueB2.getResourceUsage().getMemory()); // Both queue B1 and queue B2 usages go to 3 * 1024 assertFalse(queueB1.isStarvedForFairShare()); assertFalse(queueB2.isStarvedForFairShare()); } @Test (timeout = 5000) public void testIsStarvedForFairShareDRF() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.5</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.5</weight>"); out.println("</queue>"); out.println("<defaultFairSharePreemptionThreshold>1</defaultFairSharePreemptionThreshold>"); out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>"); out.println("</allocations>"); out.close(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(10 * 1024, 10), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); scheduler.update(); // Queue A wants 7 * 1024, 1. Node update gives this all to A createSchedulingRequest(7 * 1024, 1, "queueA", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent nodeEvent2 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeEvent2); QueueManager queueMgr = scheduler.getQueueManager(); FSLeafQueue queueA = queueMgr.getLeafQueue("queueA", false); assertEquals(7 * 1024, queueA.getResourceUsage().getMemory()); assertEquals(1, queueA.getResourceUsage().getVirtualCores()); // Queue B has 3 reqs : // 1) 2 * 1024, 5 .. which will be granted // 2) 1 * 1024, 1 .. which will be granted // 3) 1 * 1024, 1 .. which wont createSchedulingRequest(2 * 1024, 5, "queueB", "user1", 1); createSchedulingRequest(1 * 1024, 2, "queueB", "user1", 2); scheduler.update(); for (int i = 0; i < 3; i ++) { scheduler.handle(nodeEvent2); } FSLeafQueue queueB = queueMgr.getLeafQueue("queueB", false); assertEquals(3 * 1024, queueB.getResourceUsage().getMemory()); assertEquals(6, queueB.getResourceUsage().getVirtualCores()); scheduler.update(); // Verify that Queue us not starved for fair share.. // Since the Starvation logic now uses DRF when the policy = drf, The // Queue should not be starved assertFalse(queueB.isStarvedForFairShare()); } @Test public void testConcurrentAccess() { conf.set(FairSchedulerConfiguration.ASSIGN_MULTIPLE, "false"); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); String queueName = "root.queue1"; final FSLeafQueue schedulable = scheduler.getQueueManager(). getLeafQueue(queueName, true); ApplicationAttemptId applicationAttemptId = createAppAttemptId(1, 1); RMContext rmContext = resourceManager.getRMContext(); final FSAppAttempt app = new FSAppAttempt(scheduler, applicationAttemptId, "user1", schedulable, null, rmContext); // this needs to be in sync with the number of runnables declared below int testThreads = 2; List<Runnable> runnables = new ArrayList<Runnable>(); // add applications to modify the list runnables.add(new Runnable() { @Override public void run() { for (int i=0; i < 500; i++) { schedulable.addAppSchedulable(app); } } }); // iterate over the list a couple of times in a different thread runnables.add(new Runnable() { @Override public void run() { for (int i=0; i < 500; i++) { schedulable.getResourceUsage(); } } }); final List<Throwable> exceptions = Collections.synchronizedList( new ArrayList<Throwable>()); final ExecutorService threadPool = Executors.newFixedThreadPool( testThreads); try { final CountDownLatch allExecutorThreadsReady = new CountDownLatch(testThreads); final CountDownLatch startBlocker = new CountDownLatch(1); final CountDownLatch allDone = new CountDownLatch(testThreads); for (final Runnable submittedTestRunnable : runnables) { threadPool.submit(new Runnable() { public void run() { allExecutorThreadsReady.countDown(); try { startBlocker.await(); submittedTestRunnable.run(); } catch (final Throwable e) { exceptions.add(e); } finally { allDone.countDown(); } } }); } // wait until all threads are ready allExecutorThreadsReady.await(); // start all test runners startBlocker.countDown(); int testTimeout = 2; assertTrue("Timeout waiting for more than " + testTimeout + " seconds", allDone.await(testTimeout, TimeUnit.SECONDS)); } catch (InterruptedException ie) { exceptions.add(ie); } finally { threadPool.shutdownNow(); } assertTrue("Test failed with exception(s)" + exceptions, exceptions.isEmpty()); } }
14,635
37.414698
97
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestComputeFairShares.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.scheduler.fair; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceType; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.ComputeFairShares; import org.junit.Before; import org.junit.Test; /** * Exercise the computeFairShares method in SchedulingAlgorithms. */ public class TestComputeFairShares { private List<Schedulable> scheds; @Before public void setUp() throws Exception { scheds = new ArrayList<Schedulable>(); } /** * Basic test - pools with different demands that are all higher than their * fair share (of 10 slots) should each get their fair share. */ @Test public void testEqualSharing() { scheds.add(new FakeSchedulable()); scheds.add(new FakeSchedulable()); scheds.add(new FakeSchedulable()); scheds.add(new FakeSchedulable()); ComputeFairShares.computeShares(scheds, Resources.createResource(40), ResourceType.MEMORY); verifyMemoryShares(10, 10, 10, 10); } /** * In this test, pool 4 has a smaller demand than the 40 / 4 = 10 slots that * it would be assigned with equal sharing. It should only get the 3 slots * it demands. The other pools must then split the remaining 37 slots, but * pool 3, with 11 slots demanded, is now below its share of 37/3 ~= 12.3, * so it only gets 11 slots. Pools 1 and 2 split the rest and get 13 each. */ @Test public void testLowMaxShares() { scheds.add(new FakeSchedulable(0, 100)); scheds.add(new FakeSchedulable(0, 50)); scheds.add(new FakeSchedulable(0, 11)); scheds.add(new FakeSchedulable(0, 3)); ComputeFairShares.computeShares(scheds, Resources.createResource(40), ResourceType.MEMORY); verifyMemoryShares(13, 13, 11, 3); } /** * In this test, some pools have minimum shares set. Pool 1 has a min share * of 20 so it gets 20 slots. Pool 2 also has a min share of 20, but its * demand is only 10 so it can only get 10 slots. The remaining pools have * 10 slots to split between them. Pool 4 gets 3 slots because its demand is * only 3, and pool 3 gets the remaining 7 slots. Pool 4 also had a min share * of 2 slots but this should not affect the outcome. */ @Test public void testMinShares() { scheds.add(new FakeSchedulable(20)); scheds.add(new FakeSchedulable(18)); scheds.add(new FakeSchedulable(0)); scheds.add(new FakeSchedulable(2)); ComputeFairShares.computeShares(scheds, Resources.createResource(40), ResourceType.MEMORY); verifyMemoryShares(20, 18, 0, 2); } /** * Basic test for weighted shares with no minimum shares and no low demands. * Each pool should get slots in proportion to its weight. */ @Test public void testWeightedSharing() { scheds.add(new FakeSchedulable(0, 2.0)); scheds.add(new FakeSchedulable(0, 1.0)); scheds.add(new FakeSchedulable(0, 1.0)); scheds.add(new FakeSchedulable(0, 0.5)); ComputeFairShares.computeShares(scheds, Resources.createResource(45), ResourceType.MEMORY); verifyMemoryShares(20, 10, 10, 5); } /** * Weighted sharing test where pools 1 and 2 are now given lower demands than * above. Pool 1 stops at 10 slots, leaving 35. If the remaining pools split * this into a 1:1:0.5 ratio, they would get 14:14:7 slots respectively, but * pool 2's demand is only 11, so it only gets 11. The remaining 2 pools split * the 24 slots left into a 1:0.5 ratio, getting 16 and 8 slots respectively. */ @Test public void testWeightedSharingWithMaxShares() { scheds.add(new FakeSchedulable(0, 10, 2.0)); scheds.add(new FakeSchedulable(0, 11, 1.0)); scheds.add(new FakeSchedulable(0, 30, 1.0)); scheds.add(new FakeSchedulable(0, 20, 0.5)); ComputeFairShares.computeShares(scheds, Resources.createResource(45), ResourceType.MEMORY); verifyMemoryShares(10, 11, 16, 8); } /** * Weighted fair sharing test with min shares. As in the min share test above, * pool 1 has a min share greater than its demand so it only gets its demand. * Pool 3 has a min share of 15 even though its weight is very small, so it * gets 15 slots. The remaining pools share the remaining 20 slots equally, * getting 10 each. Pool 3's min share of 5 slots doesn't affect this. */ @Test public void testWeightedSharingWithMinShares() { scheds.add(new FakeSchedulable(20, 2.0)); scheds.add(new FakeSchedulable(0, 1.0)); scheds.add(new FakeSchedulable(5, 1.0)); scheds.add(new FakeSchedulable(15, 0.5)); ComputeFairShares.computeShares(scheds, Resources.createResource(45), ResourceType.MEMORY); verifyMemoryShares(20, 5, 5, 15); } /** * Test that shares are computed accurately even when the number of slots is * very large. */ @Test public void testLargeShares() { int million = 1000 * 1000; scheds.add(new FakeSchedulable()); scheds.add(new FakeSchedulable()); scheds.add(new FakeSchedulable()); scheds.add(new FakeSchedulable()); ComputeFairShares.computeShares(scheds, Resources.createResource(40 * million), ResourceType.MEMORY); verifyMemoryShares(10 * million, 10 * million, 10 * million, 10 * million); } /** * Test that being called on an empty list doesn't confuse the algorithm. */ @Test public void testEmptyList() { ComputeFairShares.computeShares(scheds, Resources.createResource(40), ResourceType.MEMORY); verifyMemoryShares(); } /** * Test that CPU works as well as memory */ @Test public void testCPU() { scheds.add(new FakeSchedulable(Resources.createResource(0, 20), new ResourceWeights(2.0f))); scheds.add(new FakeSchedulable(Resources.createResource(0, 0), new ResourceWeights(1.0f))); scheds.add(new FakeSchedulable(Resources.createResource(0, 5), new ResourceWeights(1.0f))); scheds.add(new FakeSchedulable(Resources.createResource(0, 15), new ResourceWeights(0.5f))); ComputeFairShares.computeShares(scheds, Resources.createResource(0, 45), ResourceType.CPU); verifyCPUShares(20, 5, 5, 15); } /** * Check that a given list of shares have been assigned to this.scheds. */ private void verifyMemoryShares(int... shares) { Assert.assertEquals(scheds.size(), shares.length); for (int i = 0; i < shares.length; i++) { Assert.assertEquals(shares[i], scheds.get(i).getFairShare().getMemory()); } } /** * Check that a given list of shares have been assigned to this.scheds. */ private void verifyCPUShares(int... shares) { Assert.assertEquals(scheds.size(), shares.length); for (int i = 0; i < shares.length; i++) { Assert.assertEquals(shares[i], scheds.get(i).getFairShare().getVirtualCores()); } } }
7,901
36.098592
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairSchedulerTestBase.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.scheduler.fair; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; 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.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; 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.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Clock; public class FairSchedulerTestBase { public final static String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); private static RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); protected int APP_ID = 1; // Incrementing counter for scheduling apps protected int ATTEMPT_ID = 1; // Incrementing counter for scheduling attempts protected Configuration conf; protected FairScheduler scheduler; protected ResourceManager resourceManager; // Helper methods public Configuration createConfiguration() { Configuration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class, ResourceScheduler.class); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0); conf.setInt(FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_MB, 1024); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 10240); conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, false); conf.setFloat(FairSchedulerConfiguration.PREEMPTION_THRESHOLD, 0f); return conf; } protected ApplicationAttemptId createAppAttemptId(int appId, int attemptId) { ApplicationId appIdImpl = ApplicationId.newInstance(0, appId); return ApplicationAttemptId.newInstance(appIdImpl, attemptId); } protected ResourceRequest createResourceRequest( int memory, String host, int priority, int numContainers, boolean relaxLocality) { return createResourceRequest(memory, 1, host, priority, numContainers, relaxLocality); } protected ResourceRequest createResourceRequest( int memory, int vcores, String host, int priority, int numContainers, boolean relaxLocality) { ResourceRequest request = recordFactory.newRecordInstance(ResourceRequest.class); request.setCapability(BuilderUtils.newResource(memory, vcores)); request.setResourceName(host); request.setNumContainers(numContainers); Priority prio = recordFactory.newRecordInstance(Priority.class); prio.setPriority(priority); request.setPriority(prio); request.setRelaxLocality(relaxLocality); return request; } /** * Creates a single container priority-1 request and submits to * scheduler. */ protected ApplicationAttemptId createSchedulingRequest( int memory, String queueId, String userId) { return createSchedulingRequest(memory, queueId, userId, 1); } protected ApplicationAttemptId createSchedulingRequest( int memory, int vcores, String queueId, String userId) { return createSchedulingRequest(memory, vcores, queueId, userId, 1); } protected ApplicationAttemptId createSchedulingRequest( int memory, String queueId, String userId, int numContainers) { return createSchedulingRequest(memory, queueId, userId, numContainers, 1); } protected ApplicationAttemptId createSchedulingRequest( int memory, int vcores, String queueId, String userId, int numContainers) { return createSchedulingRequest(memory, vcores, queueId, userId, numContainers, 1); } protected ApplicationAttemptId createSchedulingRequest( int memory, String queueId, String userId, int numContainers, int priority) { return createSchedulingRequest(memory, 1, queueId, userId, numContainers, priority); } protected ApplicationAttemptId createSchedulingRequest( int memory, int vcores, String queueId, String userId, int numContainers, int priority) { ApplicationAttemptId id = createAppAttemptId(this.APP_ID++, this.ATTEMPT_ID++); scheduler.addApplication(id.getApplicationId(), queueId, userId, false); // This conditional is for testAclSubmitApplication where app is rejected // and no app is added. if (scheduler.getSchedulerApplications().containsKey(id.getApplicationId())) { scheduler.addApplicationAttempt(id, false, false); } List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); ResourceRequest request = createResourceRequest(memory, vcores, ResourceRequest.ANY, priority, numContainers, true); ask.add(request); RMApp rmApp = mock(RMApp.class); RMAppAttempt rmAppAttempt = mock(RMAppAttempt.class); when(rmApp.getCurrentAppAttempt()).thenReturn(rmAppAttempt); when(rmAppAttempt.getRMAppAttemptMetrics()).thenReturn( new RMAppAttemptMetrics(id, resourceManager.getRMContext())); ApplicationSubmissionContext submissionContext = mock(ApplicationSubmissionContext.class); when(submissionContext.getUnmanagedAM()).thenReturn(false); when(rmAppAttempt.getSubmissionContext()).thenReturn(submissionContext); Container container = mock(Container.class); when(rmAppAttempt.getMasterContainer()).thenReturn(container); resourceManager.getRMContext().getRMApps() .put(id.getApplicationId(), rmApp); scheduler.allocate(id, ask, new ArrayList<ContainerId>(), null, null); return id; } protected ApplicationAttemptId createSchedulingRequest(String queueId, String userId, List<ResourceRequest> ask) { ApplicationAttemptId id = createAppAttemptId(this.APP_ID++, this.ATTEMPT_ID++); scheduler.addApplication(id.getApplicationId(), queueId, userId, false); // This conditional is for testAclSubmitApplication where app is rejected // and no app is added. if (scheduler.getSchedulerApplications().containsKey(id.getApplicationId())) { scheduler.addApplicationAttempt(id, false, false); } RMApp rmApp = mock(RMApp.class); RMAppAttempt rmAppAttempt = mock(RMAppAttempt.class); when(rmApp.getCurrentAppAttempt()).thenReturn(rmAppAttempt); when(rmAppAttempt.getRMAppAttemptMetrics()).thenReturn( new RMAppAttemptMetrics(id,resourceManager.getRMContext())); ApplicationSubmissionContext submissionContext = mock(ApplicationSubmissionContext.class); when(submissionContext.getUnmanagedAM()).thenReturn(false); when(rmAppAttempt.getSubmissionContext()).thenReturn(submissionContext); resourceManager.getRMContext().getRMApps() .put(id.getApplicationId(), rmApp); scheduler.allocate(id, ask, new ArrayList<ContainerId>(), null, null); return id; } protected void createSchedulingRequestExistingApplication( int memory, int priority, ApplicationAttemptId attId) { ResourceRequest request = createResourceRequest(memory, ResourceRequest.ANY, priority, 1, true); createSchedulingRequestExistingApplication(request, attId); } protected void createSchedulingRequestExistingApplication( int memory, int vcores, int priority, ApplicationAttemptId attId) { ResourceRequest request = createResourceRequest(memory, vcores, ResourceRequest.ANY, priority, 1, true); createSchedulingRequestExistingApplication(request, attId); } protected void createSchedulingRequestExistingApplication( ResourceRequest request, ApplicationAttemptId attId) { List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); ask.add(request); scheduler.allocate(attId, ask, new ArrayList<ContainerId>(), null, null); } protected void createApplicationWithAMResource(ApplicationAttemptId attId, String queue, String user, Resource amResource) { RMContext rmContext = resourceManager.getRMContext(); ApplicationId appId = attId.getApplicationId(); RMApp rmApp = new RMAppImpl(appId, rmContext, conf, null, user, null, ApplicationSubmissionContext.newInstance(appId, null, queue, null, null, false, false, 0, amResource, null), null, null, 0, null, null, null); rmContext.getRMApps().put(appId, rmApp); RMAppEvent event = new RMAppEvent(appId, RMAppEventType.START); resourceManager.getRMContext().getRMApps().get(appId).handle(event); event = new RMAppEvent(appId, RMAppEventType.APP_NEW_SAVED); resourceManager.getRMContext().getRMApps().get(appId).handle(event); event = new RMAppEvent(appId, RMAppEventType.APP_ACCEPTED); resourceManager.getRMContext().getRMApps().get(appId).handle(event); AppAddedSchedulerEvent appAddedEvent = new AppAddedSchedulerEvent( appId, queue, user); scheduler.handle(appAddedEvent); AppAttemptAddedSchedulerEvent attempAddedEvent = new AppAttemptAddedSchedulerEvent(attId, false); scheduler.handle(attempAddedEvent); } protected RMApp createMockRMApp(ApplicationAttemptId attemptId) { RMApp app = mock(RMAppImpl.class); when(app.getApplicationId()).thenReturn(attemptId.getApplicationId()); RMAppAttemptImpl attempt = mock(RMAppAttemptImpl.class); when(attempt.getAppAttemptId()).thenReturn(attemptId); RMAppAttemptMetrics attemptMetric = mock(RMAppAttemptMetrics.class); when(attempt.getRMAppAttemptMetrics()).thenReturn(attemptMetric); when(app.getCurrentAppAttempt()).thenReturn(attempt); ApplicationSubmissionContext submissionContext = mock(ApplicationSubmissionContext.class); when(submissionContext.getUnmanagedAM()).thenReturn(false); when(attempt.getSubmissionContext()).thenReturn(submissionContext); resourceManager.getRMContext().getRMApps() .put(attemptId.getApplicationId(), app); return app; } }
12,035
46.2
99
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestContinuousScheduling.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.scheduler.fair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class TestContinuousScheduling extends FairSchedulerTestBase { private ControlledClock mockClock; @Override public Configuration createConfiguration() { Configuration conf = super.createConfiguration(); conf.setBoolean( FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_ENABLED, true); conf.setInt(FairSchedulerConfiguration.LOCALITY_DELAY_NODE_MS, 100); conf.setInt(FairSchedulerConfiguration.LOCALITY_DELAY_RACK_MS, 100); return conf; } @Before public void setup() { mockClock = new ControlledClock(); conf = createConfiguration(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); scheduler.setClock(mockClock); assertTrue(scheduler.isContinuousSchedulingEnabled()); assertEquals( FairSchedulerConfiguration.DEFAULT_CONTINUOUS_SCHEDULING_SLEEP_MS, scheduler.getContinuousSchedulingSleepMs()); assertEquals(mockClock, scheduler.getClock()); } @After public void teardown() { if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } } @Test (timeout = 60000) public void testSchedulingDelay() throws InterruptedException { // Add one node String host = "127.0.0.1"; RMNode node1 = MockNodes.newNodeInfo( 1, Resources.createResource(4096, 4), 1, host); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); NodeUpdateSchedulerEvent nodeUpdateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeUpdateEvent); // Create one application and submit one each of node-local, rack-local // and ANY requests ApplicationAttemptId appAttemptId = createAppAttemptId(this.APP_ID++, this.ATTEMPT_ID++); createMockRMApp(appAttemptId); scheduler.addApplication(appAttemptId.getApplicationId(), "queue11", "user11", false); scheduler.addApplicationAttempt(appAttemptId, false, false); List<ResourceRequest> ask = new ArrayList<>(); ask.add(createResourceRequest(1024, 1, ResourceRequest.ANY, 1, 1, true)); scheduler.allocate( appAttemptId, ask, new ArrayList<ContainerId>(), null, null); FSAppAttempt app = scheduler.getSchedulerApp(appAttemptId); // Advance time and let continuous scheduling kick in mockClock.tickSec(1); while (1024 != app.getCurrentConsumption().getMemory()) { Thread.sleep(100); } assertEquals(1024, app.getCurrentConsumption().getMemory()); } }
4,382
37.787611
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestQueueManager.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.scheduler.fair; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.HashSet; import java.util.Set; import org.apache.hadoop.yarn.util.SystemClock; import org.junit.Before; import org.junit.Test; import com.google.common.collect.Sets; public class TestQueueManager { private FairSchedulerConfiguration conf; private QueueManager queueManager; private Set<FSQueue> notEmptyQueues; @Before public void setUp() throws Exception { conf = new FairSchedulerConfiguration(); FairScheduler scheduler = mock(FairScheduler.class); AllocationConfiguration allocConf = new AllocationConfiguration(conf); when(scheduler.getAllocationConfiguration()).thenReturn(allocConf); when(scheduler.getConf()).thenReturn(conf); SystemClock clock = new SystemClock(); when(scheduler.getClock()).thenReturn(clock); notEmptyQueues = new HashSet<FSQueue>(); queueManager = new QueueManager(scheduler) { @Override public boolean isEmpty(FSQueue queue) { return !notEmptyQueues.contains(queue); } }; FSQueueMetrics.forQueue("root", null, true, conf); queueManager.initialize(conf); } @Test public void testReloadTurnsLeafQueueIntoParent() throws Exception { updateConfiguredLeafQueues(queueManager, "queue1"); // When no apps are running in the leaf queue, should be fine turning it // into a parent. updateConfiguredLeafQueues(queueManager, "queue1.queue2"); assertNull(queueManager.getLeafQueue("queue1", false)); assertNotNull(queueManager.getLeafQueue("queue1.queue2", false)); // When leaf queues are empty, should be ok deleting them and // turning parent into a leaf. updateConfiguredLeafQueues(queueManager, "queue1"); assertNull(queueManager.getLeafQueue("queue1.queue2", false)); assertNotNull(queueManager.getLeafQueue("queue1", false)); // When apps exist in leaf queue, we shouldn't be able to create // children under it, but things should work otherwise. notEmptyQueues.add(queueManager.getLeafQueue("queue1", false)); updateConfiguredLeafQueues(queueManager, "queue1.queue2"); assertNull(queueManager.getLeafQueue("queue1.queue2", false)); assertNotNull(queueManager.getLeafQueue("queue1", false)); // When apps exist in leaf queues under a parent queue, shouldn't be // able to turn it into a leaf queue, but things should work otherwise. notEmptyQueues.clear(); updateConfiguredLeafQueues(queueManager, "queue1.queue2"); notEmptyQueues.add(queueManager.getQueue("root.queue1")); updateConfiguredLeafQueues(queueManager, "queue1"); assertNotNull(queueManager.getLeafQueue("queue1.queue2", false)); assertNull(queueManager.getLeafQueue("queue1", false)); // Should never to be able to create a queue under the default queue updateConfiguredLeafQueues(queueManager, "default.queue3"); assertNull(queueManager.getLeafQueue("default.queue3", false)); assertNotNull(queueManager.getLeafQueue("default", false)); } @Test public void testReloadTurnsLeafToParentWithNoLeaf() { AllocationConfiguration allocConf = new AllocationConfiguration(conf); // Create a leaf queue1 allocConf.configuredQueues.get(FSQueueType.LEAF).add("root.queue1"); queueManager.updateAllocationConfiguration(allocConf); assertNotNull(queueManager.getLeafQueue("root.queue1", false)); // Lets say later on admin makes queue1 a parent queue by // specifying "type=parent" in the alloc xml and lets say apps running in // queue1 notEmptyQueues.add(queueManager.getLeafQueue("root.queue1", false)); allocConf = new AllocationConfiguration(conf); allocConf.configuredQueues.get(FSQueueType.PARENT) .add("root.queue1"); // When allocs are reloaded queue1 shouldn't be converter to parent queueManager.updateAllocationConfiguration(allocConf); assertNotNull(queueManager.getLeafQueue("root.queue1", false)); assertNull(queueManager.getParentQueue("root.queue1", false)); // Now lets assume apps completed and there are no apps in queue1 notEmptyQueues.clear(); // We should see queue1 transform from leaf queue to parent queue. queueManager.updateAllocationConfiguration(allocConf); assertNull(queueManager.getLeafQueue("root.queue1", false)); assertNotNull(queueManager.getParentQueue("root.queue1", false)); // this parent should not have any children assertTrue(queueManager.getParentQueue("root.queue1", false) .getChildQueues().isEmpty()); } @Test public void testCheckQueueNodeName() { assertFalse(queueManager.isQueueNameValid("")); assertFalse(queueManager.isQueueNameValid(" ")); assertFalse(queueManager.isQueueNameValid(" a")); assertFalse(queueManager.isQueueNameValid("a ")); assertFalse(queueManager.isQueueNameValid(" a ")); assertTrue(queueManager.isQueueNameValid("a b")); assertTrue(queueManager.isQueueNameValid("a")); } private void updateConfiguredLeafQueues(QueueManager queueMgr, String... confLeafQueues) { AllocationConfiguration allocConf = new AllocationConfiguration(conf); allocConf.configuredQueues.get(FSQueueType.LEAF).addAll(Sets.newHashSet(confLeafQueues)); queueMgr.updateAllocationConfiguration(allocConf); } }
6,192
42.006944
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestAllocationFileLoaderService.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.scheduler.fair; import static org.junit.Assert.*; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueuePlacementRule.NestedUserQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FairSharePolicy; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Test; public class TestAllocationFileLoaderService { final static String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); final static String ALLOC_FILE = new File(TEST_DIR, "test-queues").getAbsolutePath(); @Test public void testGetAllocationFileFromClasspath() { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, "test-fair-scheduler.xml"); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); File allocationFile = allocLoader.getAllocationFile(conf); assertEquals("test-fair-scheduler.xml", allocationFile.getName()); assertTrue(allocationFile.exists()); } @Test (timeout = 10000) public void testReload() throws Exception { PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println(" <queue name=\"queueA\">"); out.println(" <maxRunningApps>1</maxRunningApps>"); out.println(" </queue>"); out.println(" <queue name=\"queueB\" />"); out.println(" <queuePlacementPolicy>"); out.println(" <rule name='default' />"); out.println(" </queuePlacementPolicy>"); out.println("</allocations>"); out.close(); ControlledClock clock = new ControlledClock(); clock.setTime(0); Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService( clock); allocLoader.reloadIntervalMs = 5; allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration allocConf = confHolder.allocConf; // Verify conf QueuePlacementPolicy policy = allocConf.getPlacementPolicy(); List<QueuePlacementRule> rules = policy.getRules(); assertEquals(1, rules.size()); assertEquals(QueuePlacementRule.Default.class, rules.get(0).getClass()); assertEquals(1, allocConf.getQueueMaxApps("root.queueA")); assertEquals(2, allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .size()); assertTrue(allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueA")); assertTrue(allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueB")); confHolder.allocConf = null; // Modify file and advance the clock out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println(" <queue name=\"queueB\">"); out.println(" <maxRunningApps>3</maxRunningApps>"); out.println(" </queue>"); out.println(" <queuePlacementPolicy>"); out.println(" <rule name='specified' />"); out.println(" <rule name='nestedUserQueue' >"); out.println(" <rule name='primaryGroup' />"); out.println(" </rule>"); out.println(" <rule name='default' />"); out.println(" </queuePlacementPolicy>"); out.println("</allocations>"); out.close(); clock.tickMsec(System.currentTimeMillis() + AllocationFileLoaderService.ALLOC_RELOAD_WAIT_MS + 10000); allocLoader.start(); while (confHolder.allocConf == null) { Thread.sleep(20); } // Verify conf allocConf = confHolder.allocConf; policy = allocConf.getPlacementPolicy(); rules = policy.getRules(); assertEquals(3, rules.size()); assertEquals(QueuePlacementRule.Specified.class, rules.get(0).getClass()); assertEquals(QueuePlacementRule.NestedUserQueue.class, rules.get(1) .getClass()); assertEquals(QueuePlacementRule.PrimaryGroup.class, ((NestedUserQueue) (rules.get(1))).nestedRule.getClass()); assertEquals(QueuePlacementRule.Default.class, rules.get(2).getClass()); assertEquals(3, allocConf.getQueueMaxApps("root.queueB")); assertEquals(1, allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .size()); assertTrue(allocConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueB")); } @Test public void testAllocationFileParsing() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); // Give queue A a minimum of 1024 M out.println("<queue name=\"queueA\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); // Give queue B a minimum of 2048 M out.println("<queue name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("<aclAdministerApps>alice,bob admins</aclAdministerApps>"); out.println("<schedulingPolicy>fair</schedulingPolicy>"); out.println("</queue>"); // Give queue C no minimum out.println("<queue name=\"queueC\">"); out.println("<aclSubmitApps>alice,bob admins</aclSubmitApps>"); out.println("</queue>"); // Give queue D a limit of 3 running apps and 0.4f maxAMShare out.println("<queue name=\"queueD\">"); out.println("<maxRunningApps>3</maxRunningApps>"); out.println("<maxAMShare>0.4</maxAMShare>"); out.println("</queue>"); // Give queue E a preemption timeout of one minute out.println("<queue name=\"queueE\">"); out.println("<minSharePreemptionTimeout>60</minSharePreemptionTimeout>"); out.println("</queue>"); //Make queue F a parent queue without configured leaf queues using the 'type' attribute out.println("<queue name=\"queueF\" type=\"parent\" >"); out.println("</queue>"); // Create hierarchical queues G,H, with different min/fair share preemption // timeouts and preemption thresholds out.println("<queue name=\"queueG\">"); out.println("<fairSharePreemptionTimeout>120</fairSharePreemptionTimeout>"); out.println("<minSharePreemptionTimeout>50</minSharePreemptionTimeout>"); out.println("<fairSharePreemptionThreshold>0.6</fairSharePreemptionThreshold>"); out.println(" <queue name=\"queueH\">"); out.println(" <fairSharePreemptionTimeout>180</fairSharePreemptionTimeout>"); out.println(" <minSharePreemptionTimeout>40</minSharePreemptionTimeout>"); out.println(" <fairSharePreemptionThreshold>0.7</fairSharePreemptionThreshold>"); out.println(" </queue>"); out.println("</queue>"); // Set default limit of apps per queue to 15 out.println("<queueMaxAppsDefault>15</queueMaxAppsDefault>"); // Set default limit of apps per user to 5 out.println("<userMaxAppsDefault>5</userMaxAppsDefault>"); // Set default limit of AMResourceShare to 0.5f out.println("<queueMaxAMShareDefault>0.5f</queueMaxAMShareDefault>"); // Give user1 a limit of 10 jobs out.println("<user name=\"user1\">"); out.println("<maxRunningApps>10</maxRunningApps>"); out.println("</user>"); // Set default min share preemption timeout to 2 minutes out.println("<defaultMinSharePreemptionTimeout>120" + "</defaultMinSharePreemptionTimeout>"); // Set default fair share preemption timeout to 5 minutes out.println("<defaultFairSharePreemptionTimeout>300</defaultFairSharePreemptionTimeout>"); // Set default fair share preemption threshold to 0.4 out.println("<defaultFairSharePreemptionThreshold>0.4</defaultFairSharePreemptionThreshold>"); // Set default scheduling policy to DRF out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>"); out.println("</allocations>"); out.close(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration queueConf = confHolder.allocConf; assertEquals(6, queueConf.getConfiguredQueues().get(FSQueueType.LEAF).size()); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(1024, 0), queueConf.getMinResources("root.queueA")); assertEquals(Resources.createResource(2048, 0), queueConf.getMinResources("root.queueB")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueC")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueD")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueE")); assertEquals(15, queueConf.getQueueMaxApps("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(15, queueConf.getQueueMaxApps("root.queueA")); assertEquals(15, queueConf.getQueueMaxApps("root.queueB")); assertEquals(15, queueConf.getQueueMaxApps("root.queueC")); assertEquals(3, queueConf.getQueueMaxApps("root.queueD")); assertEquals(15, queueConf.getQueueMaxApps("root.queueE")); assertEquals(10, queueConf.getUserMaxApps("user1")); assertEquals(5, queueConf.getUserMaxApps("user2")); assertEquals(.5f, queueConf.getQueueMaxAMShare("root." + YarnConfiguration.DEFAULT_QUEUE_NAME), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueA"), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueB"), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueC"), 0.01); assertEquals(.4f, queueConf.getQueueMaxAMShare("root.queueD"), 0.01); assertEquals(.5f, queueConf.getQueueMaxAMShare("root.queueE"), 0.01); // Root should get * ACL assertEquals("*", queueConf.getQueueAcl("root", QueueACL.ADMINISTER_QUEUE).getAclString()); assertEquals("*", queueConf.getQueueAcl("root", QueueACL.SUBMIT_APPLICATIONS).getAclString()); // Unspecified queues should get default ACL assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.ADMINISTER_QUEUE).getAclString()); assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.SUBMIT_APPLICATIONS).getAclString()); // Queue B ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueB", QueueACL.ADMINISTER_QUEUE).getAclString()); // Queue C ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueC", QueueACL.SUBMIT_APPLICATIONS).getAclString()); assertEquals(120000, queueConf.getMinSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueD")); assertEquals(60000, queueConf.getMinSharePreemptionTimeout("root.queueE")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueF")); assertEquals(50000, queueConf.getMinSharePreemptionTimeout("root.queueG")); assertEquals(40000, queueConf.getMinSharePreemptionTimeout("root.queueG.queueH")); assertEquals(300000, queueConf.getFairSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueD")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueE")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueF")); assertEquals(120000, queueConf.getFairSharePreemptionTimeout("root.queueG")); assertEquals(180000, queueConf.getFairSharePreemptionTimeout("root.queueG.queueH")); assertEquals(.4f, queueConf.getFairSharePreemptionThreshold("root"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root." + YarnConfiguration.DEFAULT_QUEUE_NAME), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueA"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueB"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueC"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueD"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueE"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueF"), 0.01); assertEquals(.6f, queueConf.getFairSharePreemptionThreshold("root.queueG"), 0.01); assertEquals(.7f, queueConf.getFairSharePreemptionThreshold("root.queueG.queueH"), 0.01); assertTrue(queueConf.getConfiguredQueues() .get(FSQueueType.PARENT) .contains("root.queueF")); assertTrue(queueConf.getConfiguredQueues().get(FSQueueType.PARENT) .contains("root.queueG")); assertTrue(queueConf.getConfiguredQueues().get(FSQueueType.LEAF) .contains("root.queueG.queueH")); // Verify existing queues have default scheduling policy assertEquals(DominantResourceFairnessPolicy.NAME, queueConf.getSchedulingPolicy("root").getName()); assertEquals(DominantResourceFairnessPolicy.NAME, queueConf.getSchedulingPolicy("root.queueA").getName()); // Verify default is overriden if specified explicitly assertEquals(FairSharePolicy.NAME, queueConf.getSchedulingPolicy("root.queueB").getName()); // Verify new queue gets default scheduling policy assertEquals(DominantResourceFairnessPolicy.NAME, queueConf.getSchedulingPolicy("root.newqueue").getName()); } @Test public void testBackwardsCompatibleAllocationFileParsing() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); // Give queue A a minimum of 1024 M out.println("<pool name=\"queueA\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</pool>"); // Give queue B a minimum of 2048 M out.println("<pool name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("<aclAdministerApps>alice,bob admins</aclAdministerApps>"); out.println("</pool>"); // Give queue C no minimum out.println("<pool name=\"queueC\">"); out.println("<aclSubmitApps>alice,bob admins</aclSubmitApps>"); out.println("</pool>"); // Give queue D a limit of 3 running apps out.println("<pool name=\"queueD\">"); out.println("<maxRunningApps>3</maxRunningApps>"); out.println("</pool>"); // Give queue E a preemption timeout of one minute and 0.3f threshold out.println("<pool name=\"queueE\">"); out.println("<minSharePreemptionTimeout>60</minSharePreemptionTimeout>"); out.println("<fairSharePreemptionThreshold>0.3</fairSharePreemptionThreshold>"); out.println("</pool>"); // Set default limit of apps per queue to 15 out.println("<queueMaxAppsDefault>15</queueMaxAppsDefault>"); // Set default limit of apps per user to 5 out.println("<userMaxAppsDefault>5</userMaxAppsDefault>"); // Give user1 a limit of 10 jobs out.println("<user name=\"user1\">"); out.println("<maxRunningApps>10</maxRunningApps>"); out.println("</user>"); // Set default min share preemption timeout to 2 minutes out.println("<defaultMinSharePreemptionTimeout>120" + "</defaultMinSharePreemptionTimeout>"); // Set fair share preemption timeout to 5 minutes out.println("<fairSharePreemptionTimeout>300</fairSharePreemptionTimeout>"); // Set default fair share preemption threshold to 0.6f out.println("<defaultFairSharePreemptionThreshold>0.6</defaultFairSharePreemptionThreshold>"); out.println("</allocations>"); out.close(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration queueConf = confHolder.allocConf; assertEquals(5, queueConf.getConfiguredQueues().get(FSQueueType.LEAF).size()); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(0), queueConf.getMinResources("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(Resources.createResource(1024, 0), queueConf.getMinResources("root.queueA")); assertEquals(Resources.createResource(2048, 0), queueConf.getMinResources("root.queueB")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueC")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueD")); assertEquals(Resources.createResource(0), queueConf.getMinResources("root.queueE")); assertEquals(15, queueConf.getQueueMaxApps("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(15, queueConf.getQueueMaxApps("root.queueA")); assertEquals(15, queueConf.getQueueMaxApps("root.queueB")); assertEquals(15, queueConf.getQueueMaxApps("root.queueC")); assertEquals(3, queueConf.getQueueMaxApps("root.queueD")); assertEquals(15, queueConf.getQueueMaxApps("root.queueE")); assertEquals(10, queueConf.getUserMaxApps("user1")); assertEquals(5, queueConf.getUserMaxApps("user2")); // Unspecified queues should get default ACL assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.ADMINISTER_QUEUE).getAclString()); assertEquals(" ", queueConf.getQueueAcl("root.queueA", QueueACL.SUBMIT_APPLICATIONS).getAclString()); // Queue B ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueB", QueueACL.ADMINISTER_QUEUE).getAclString()); // Queue C ACL assertEquals("alice,bob admins", queueConf.getQueueAcl("root.queueC", QueueACL.SUBMIT_APPLICATIONS).getAclString()); assertEquals(120000, queueConf.getMinSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getMinSharePreemptionTimeout("root.queueD")); assertEquals(60000, queueConf.getMinSharePreemptionTimeout("root.queueE")); assertEquals(300000, queueConf.getFairSharePreemptionTimeout("root")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root." + YarnConfiguration.DEFAULT_QUEUE_NAME)); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueA")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueB")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueC")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueD")); assertEquals(-1, queueConf.getFairSharePreemptionTimeout("root.queueE")); assertEquals(.6f, queueConf.getFairSharePreemptionThreshold("root"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root." + YarnConfiguration.DEFAULT_QUEUE_NAME), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueA"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueB"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueC"), 0.01); assertEquals(-1, queueConf.getFairSharePreemptionThreshold("root.queueD"), 0.01); assertEquals(.3f, queueConf.getFairSharePreemptionThreshold("root.queueE"), 0.01); } @Test public void testSimplePlacementPolicyFromConf() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); conf.setBoolean(FairSchedulerConfiguration.ALLOW_UNDECLARED_POOLS, false); conf.setBoolean(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, false); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration allocConf = confHolder.allocConf; QueuePlacementPolicy placementPolicy = allocConf.getPlacementPolicy(); List<QueuePlacementRule> rules = placementPolicy.getRules(); assertEquals(2, rules.size()); assertEquals(QueuePlacementRule.Specified.class, rules.get(0).getClass()); assertEquals(false, rules.get(0).create); assertEquals(QueuePlacementRule.Default.class, rules.get(1).getClass()); } /** * Verify that you can't place queues at the same level as the root queue in * the allocations file. */ @Test (expected = AllocationConfigurationException.class) public void testQueueAlongsideRoot() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println("</queue>"); out.println("<queue name=\"other\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } /** * Verify that you can't include periods as the queue name in the allocations * file. */ @Test (expected = AllocationConfigurationException.class) public void testQueueNameContainingPeriods() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"parent1.child1\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } /** * Verify that you can't have the queue name with whitespace only in the * allocations file. */ @Test (expected = AllocationConfigurationException.class) public void testQueueNameContainingOnlyWhitespace() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\" \">"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } @Test public void testReservableQueue() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"reservable\">"); out.println("<reservation>"); out.println("</reservation>"); out.println("</queue>"); out.println("<queue name=\"other\">"); out.println("</queue>"); out.println("<reservation-agent>DummyAgentName</reservation-agent>"); out.println("<reservation-policy>AnyAdmissionPolicy</reservation-policy>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); AllocationConfiguration allocConf = confHolder.allocConf; String reservableQueueName = "root.reservable"; String nonreservableQueueName = "root.other"; assertFalse(allocConf.isReservable(nonreservableQueueName)); assertTrue(allocConf.isReservable(reservableQueueName)); assertTrue(allocConf.getMoveOnExpiry(reservableQueueName)); assertEquals(ReservationSchedulerConfiguration.DEFAULT_RESERVATION_WINDOW, allocConf.getReservationWindow(reservableQueueName)); assertEquals(100, allocConf.getInstantaneousMaxCapacity (reservableQueueName), 0.0001); assertEquals( "DummyAgentName", allocConf.getReservationAgent(reservableQueueName)); assertEquals(100, allocConf.getAverageCapacity(reservableQueueName), 0.001); assertFalse(allocConf.getShowReservationAsQueues(reservableQueueName)); assertEquals("AnyAdmissionPolicy", allocConf.getReservationAdmissionPolicy(reservableQueueName)); assertEquals(ReservationSchedulerConfiguration .DEFAULT_RESERVATION_PLANNER_NAME, allocConf.getReplanner(reservableQueueName)); assertEquals(ReservationSchedulerConfiguration .DEFAULT_RESERVATION_ENFORCEMENT_WINDOW, allocConf.getEnforcementWindow(reservableQueueName)); } /** * Verify that you can't have dynamic user queue and reservable queue on * the same queue */ @Test (expected = AllocationConfigurationException.class) public void testReservableCannotBeCombinedWithDynamicUserQueue() throws Exception { Configuration conf = new Configuration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"notboth\" type=\"parent\" >"); out.println("<reservation>"); out.println("</reservation>"); out.println("</queue>"); out.println("</allocations>"); out.close(); AllocationFileLoaderService allocLoader = new AllocationFileLoaderService(); allocLoader.init(conf); ReloadListener confHolder = new ReloadListener(); allocLoader.setReloadListener(confHolder); allocLoader.reloadAllocations(); } private class ReloadListener implements AllocationFileLoaderService.Listener { public AllocationConfiguration allocConf; @Override public void onReload(AllocationConfiguration info) { allocConf = info; } } }
30,025
44.841221
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/PeriodGroupsMapping.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.scheduler.fair; import org.apache.hadoop.security.GroupMappingServiceProvider; import java.io.IOException; import java.util.Arrays; import java.util.List; public class PeriodGroupsMapping implements GroupMappingServiceProvider { @Override public List<String> getGroups(String user) { return Arrays.asList(user + ".group", user + "subgroup1", user + "subgroup2"); } @Override public void cacheGroupsRefresh() throws IOException { throw new UnsupportedOperationException(); } @Override public void cacheGroupsAdd(List<String> groups) throws IOException { throw new UnsupportedOperationException(); } }
1,501
32.377778
82
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerEventLog.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.scheduler.fair; import java.io.File; import java.io.IOException; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.junit.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestFairSchedulerEventLog { private File logFile; private FairScheduler scheduler; private ResourceManager resourceManager; @Before public void setUp() throws IOException { scheduler = new FairScheduler(); Configuration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class, ResourceScheduler.class); conf.set("yarn.scheduler.fair.event-log-enabled", "true"); // All tests assume only one assignment per node update conf.set(FairSchedulerConfiguration.ASSIGN_MULTIPLE, "false"); resourceManager = new MockRM(conf); ((AsyncDispatcher)resourceManager.getRMContext().getDispatcher()).start(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); } /** * Make sure the scheduler creates the event log. */ @Test public void testCreateEventLog() throws IOException { FairSchedulerEventLog eventLog = scheduler.getEventLog(); logFile = new File(eventLog.getLogFile()); Assert.assertTrue(logFile.exists()); } @After public void tearDown() { logFile.delete(); logFile.getParentFile().delete(); // fairscheduler/ if (scheduler != null) { scheduler.stop(); scheduler = null; } if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } } }
2,813
32.5
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestAppRunnability.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.scheduler.fair; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; 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.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; /* * This class is to test the fair scheduler functionality of * deciding the number of runnable application under various conditions. */ public class TestAppRunnability extends FairSchedulerTestBase { private final static String ALLOC_FILE = new File(TEST_DIR, "test-queues").getAbsolutePath(); @Before public void setUp() throws IOException { conf = createConfiguration(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); } @After public void tearDown() { if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.shutdown(); } @Test public void testUserAsDefaultQueue() throws Exception { conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "true"); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId appAttemptId = createAppAttemptId(1, 1); createApplicationWithAMResource(appAttemptId, "default", "user1", null); assertEquals(1, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); assertEquals(0, scheduler.getQueueManager().getLeafQueue("default", true) .getNumRunnableApps()); assertEquals("root.user1", resourceManager.getRMContext().getRMApps() .get(appAttemptId.getApplicationId()).getQueue()); } @Test public void testNotUserAsDefaultQueue() throws Exception { // Restarting resource manager since the Conf object is changed changed. resourceManager.stop(); conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false"); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); ApplicationAttemptId appAttemptId = createAppAttemptId(1, 1); createApplicationWithAMResource(appAttemptId, "default", "user2", null); assertEquals(0, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); assertEquals(1, scheduler.getQueueManager().getLeafQueue("default", true) .getNumRunnableApps()); assertEquals(0, scheduler.getQueueManager().getLeafQueue("user2", true) .getNumRunnableApps()); } @Test public void testAppAdditionAndRemoval() throws Exception { ApplicationAttemptId attemptId = createAppAttemptId(1, 1); AppAddedSchedulerEvent appAddedEvent = new AppAddedSchedulerEvent(attemptId.getApplicationId(), "default", "user1"); scheduler.handle(appAddedEvent); AppAttemptAddedSchedulerEvent attemptAddedEvent = new AppAttemptAddedSchedulerEvent(createAppAttemptId(1, 1), false); scheduler.handle(attemptAddedEvent); // Scheduler should have two queues (the default and the one created for // user1) assertEquals(2, scheduler.getQueueManager().getLeafQueues().size()); // That queue should have one app assertEquals(1, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent(createAppAttemptId(1, 1), RMAppAttemptState.FINISHED, false); // Now remove app scheduler.handle(appRemovedEvent1); // Queue should have no apps assertEquals(0, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); } @Test public void testPreemptionVariablesForQueueCreatedRuntime() throws Exception { // Set preemption variables for the root queue FSParentQueue root = scheduler.getQueueManager().getRootQueue(); root.setMinSharePreemptionTimeout(10000); root.setFairSharePreemptionTimeout(15000); root.setFairSharePreemptionThreshold(.6f); // User1 submits one application ApplicationAttemptId appAttemptId = createAppAttemptId(1, 1); createApplicationWithAMResource(appAttemptId, "default", "user1", null); // The user1 queue should inherit the configurations from the root queue FSLeafQueue userQueue = scheduler.getQueueManager().getLeafQueue("user1", true); assertEquals(1, userQueue.getNumRunnableApps()); assertEquals(10000, userQueue.getMinSharePreemptionTimeout()); assertEquals(15000, userQueue.getFairSharePreemptionTimeout()); assertEquals(.6f, userQueue.getFairSharePreemptionThreshold(), 0.001); } @Test public void testDontAllowUndeclaredPools() throws Exception { conf.setBoolean(FairSchedulerConfiguration.ALLOW_UNDECLARED_POOLS, false); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"jerry\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); // Restarting resource manager since the file location and content is // changed. resourceManager.stop(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); QueueManager queueManager = scheduler.getQueueManager(); FSLeafQueue jerryQueue = queueManager.getLeafQueue("jerry", false); FSLeafQueue defaultQueue = queueManager.getLeafQueue("default", false); // Should get put into jerry createSchedulingRequest(1024, "jerry", "someuser"); assertEquals(1, jerryQueue.getNumRunnableApps()); // Should get forced into default createSchedulingRequest(1024, "newqueue", "someuser"); assertEquals(1, jerryQueue.getNumRunnableApps()); assertEquals(1, defaultQueue.getNumRunnableApps()); // Would get put into someuser because of user-as-default-queue, but should // be forced into default createSchedulingRequest(1024, "default", "someuser"); assertEquals(1, jerryQueue.getNumRunnableApps()); assertEquals(2, defaultQueue.getNumRunnableApps()); // Should get put into jerry because of user-as-default-queue createSchedulingRequest(1024, "default", "jerry"); assertEquals(2, jerryQueue.getNumRunnableApps()); assertEquals(2, defaultQueue.getNumRunnableApps()); } @Test public void testMoveRunnableApp() throws Exception { scheduler.reinitialize(conf, resourceManager.getRMContext()); QueueManager queueMgr = scheduler.getQueueManager(); FSLeafQueue oldQueue = queueMgr.getLeafQueue("queue1", true); FSLeafQueue targetQueue = queueMgr.getLeafQueue("queue2", true); ApplicationAttemptId appAttId = createSchedulingRequest(1024, 1, "queue1", "user1", 3); ApplicationId appId = appAttId.getApplicationId(); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(1024)); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); scheduler.handle(updateEvent); assertEquals(Resource.newInstance(1024, 1), oldQueue.getResourceUsage()); scheduler.update(); assertEquals(Resource.newInstance(3072, 3), oldQueue.getDemand()); scheduler.moveApplication(appId, "queue2"); FSAppAttempt app = scheduler.getSchedulerApp(appAttId); assertSame(targetQueue, app.getQueue()); assertFalse(oldQueue.isRunnableApp(app)); assertTrue(targetQueue.isRunnableApp(app)); assertEquals(Resource.newInstance(0, 0), oldQueue.getResourceUsage()); assertEquals(Resource.newInstance(1024, 1), targetQueue.getResourceUsage()); assertEquals(0, oldQueue.getNumRunnableApps()); assertEquals(1, targetQueue.getNumRunnableApps()); assertEquals(1, queueMgr.getRootQueue().getNumRunnableApps()); scheduler.update(); assertEquals(Resource.newInstance(0, 0), oldQueue.getDemand()); assertEquals(Resource.newInstance(3072, 3), targetQueue.getDemand()); } @Test public void testMoveNonRunnableApp() throws Exception { QueueManager queueMgr = scheduler.getQueueManager(); FSLeafQueue oldQueue = queueMgr.getLeafQueue("queue1", true); FSLeafQueue targetQueue = queueMgr.getLeafQueue("queue2", true); scheduler.getAllocationConfiguration().queueMaxApps.put("root.queue1", 0); scheduler.getAllocationConfiguration().queueMaxApps.put("root.queue2", 0); ApplicationAttemptId appAttId = createSchedulingRequest(1024, 1, "queue1", "user1", 3); assertEquals(0, oldQueue.getNumRunnableApps()); scheduler.moveApplication(appAttId.getApplicationId(), "queue2"); assertEquals(0, oldQueue.getNumRunnableApps()); assertEquals(0, targetQueue.getNumRunnableApps()); assertEquals(0, queueMgr.getRootQueue().getNumRunnableApps()); } @Test public void testMoveMakesAppRunnable() throws Exception { QueueManager queueMgr = scheduler.getQueueManager(); FSLeafQueue oldQueue = queueMgr.getLeafQueue("queue1", true); FSLeafQueue targetQueue = queueMgr.getLeafQueue("queue2", true); scheduler.getAllocationConfiguration().queueMaxApps.put("root.queue1", 0); ApplicationAttemptId appAttId = createSchedulingRequest(1024, 1, "queue1", "user1", 3); FSAppAttempt app = scheduler.getSchedulerApp(appAttId); assertTrue(oldQueue.isNonRunnableApp(app)); scheduler.moveApplication(appAttId.getApplicationId(), "queue2"); assertFalse(oldQueue.isNonRunnableApp(app)); assertFalse(targetQueue.isNonRunnableApp(app)); assertTrue(targetQueue.isRunnableApp(app)); assertEquals(1, targetQueue.getNumRunnableApps()); assertEquals(1, queueMgr.getRootQueue().getNumRunnableApps()); } }
12,079
41.535211
101
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestSchedulingPolicy.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.scheduler.fair; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FairSharePolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FifoPolicy; import org.junit.Test; import org.mockito.Mockito; public class TestSchedulingPolicy { @Test(timeout = 1000) public void testParseSchedulingPolicy() throws AllocationConfigurationException { // Class name SchedulingPolicy sm = SchedulingPolicy .parse(FairSharePolicy.class.getName()); assertTrue("Invalid scheduler name", sm.getName().equals(FairSharePolicy.NAME)); // Canonical name sm = SchedulingPolicy.parse(FairSharePolicy.class .getCanonicalName()); assertTrue("Invalid scheduler name", sm.getName().equals(FairSharePolicy.NAME)); // Class sm = SchedulingPolicy.getInstance(FairSharePolicy.class); assertTrue("Invalid scheduler name", sm.getName().equals(FairSharePolicy.NAME)); // Shortname - drf sm = SchedulingPolicy.parse("drf"); assertTrue("Invalid scheduler name", sm.getName().equals(DominantResourceFairnessPolicy.NAME)); // Shortname - fair sm = SchedulingPolicy.parse("fair"); assertTrue("Invalid scheduler name", sm.getName().equals(FairSharePolicy.NAME)); // Shortname - fifo sm = SchedulingPolicy.parse("fifo"); assertTrue("Invalid scheduler name", sm.getName().equals(FifoPolicy.NAME)); } /** * Trivial tests that make sure * {@link SchedulingPolicy#isApplicableTo(SchedulingPolicy, byte)} works as * expected for the possible values of depth * * @throws AllocationConfigurationException */ @Test(timeout = 1000) public void testIsApplicableTo() throws AllocationConfigurationException { final String ERR = "Broken SchedulingPolicy#isApplicableTo"; // fifo SchedulingPolicy policy = SchedulingPolicy.parse("fifo"); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_LEAF)); assertFalse(ERR, SchedulingPolicy.isApplicableTo( SchedulingPolicy.parse("fifo"), SchedulingPolicy.DEPTH_INTERMEDIATE)); assertFalse(ERR, SchedulingPolicy.isApplicableTo( SchedulingPolicy.parse("fifo"), SchedulingPolicy.DEPTH_ROOT)); // fair policy = SchedulingPolicy.parse("fair"); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_LEAF)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_INTERMEDIATE)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_ROOT)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_PARENT)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_ANY)); // drf policy = SchedulingPolicy.parse("drf"); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_LEAF)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_INTERMEDIATE)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_ROOT)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_PARENT)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_ANY)); policy = Mockito.mock(SchedulingPolicy.class); Mockito.when(policy.getApplicableDepth()).thenReturn( SchedulingPolicy.DEPTH_PARENT); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_INTERMEDIATE)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_ROOT)); assertTrue(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_PARENT)); assertFalse(ERR, SchedulingPolicy.isApplicableTo(policy, SchedulingPolicy.DEPTH_ANY)); } }
5,053
38.178295
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FakeSchedulable.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.scheduler.fair; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.resource.Resources; /** * Dummy implementation of Schedulable for unit testing. */ public class FakeSchedulable implements Schedulable { private Resource usage; private Resource minShare; private Resource maxShare; private Resource fairShare; private ResourceWeights weights; private Priority priority; private long startTime; public FakeSchedulable() { this(0, Integer.MAX_VALUE, 1, 0, 0, 0); } public FakeSchedulable(int minShare) { this(minShare, Integer.MAX_VALUE, 1, 0, 0, 0); } public FakeSchedulable(int minShare, int maxShare) { this(minShare, maxShare, 1, 0, 0, 0); } public FakeSchedulable(int minShare, double memoryWeight) { this(minShare, Integer.MAX_VALUE, memoryWeight, 0, 0, 0); } public FakeSchedulable(int minShare, int maxShare, double memoryWeight) { this(minShare, maxShare, memoryWeight, 0, 0, 0); } public FakeSchedulable(int minShare, int maxShare, double weight, int fairShare, int usage, long startTime) { this(Resources.createResource(minShare, 0), Resources.createResource(maxShare, 0), new ResourceWeights((float)weight), Resources.createResource(fairShare, 0), Resources.createResource(usage, 0), startTime); } public FakeSchedulable(Resource minShare, ResourceWeights weights) { this(minShare, Resources.createResource(Integer.MAX_VALUE, Integer.MAX_VALUE), weights, Resources.createResource(0, 0), Resources.createResource(0, 0), 0); } public FakeSchedulable(Resource minShare, Resource maxShare, ResourceWeights weight, Resource fairShare, Resource usage, long startTime) { this.minShare = minShare; this.maxShare = maxShare; this.weights = weight; setFairShare(fairShare); this.usage = usage; this.priority = Records.newRecord(Priority.class); this.startTime = startTime; } @Override public Resource assignContainer(FSSchedulerNode node) { return null; } @Override public RMContainer preemptContainer() { return null; } @Override public Resource getFairShare() { return this.fairShare; } @Override public void setFairShare(Resource fairShare) { this.fairShare = fairShare; } @Override public Resource getDemand() { return null; } @Override public String getName() { return "FakeSchedulable" + this.hashCode(); } @Override public Priority getPriority() { return priority; } @Override public Resource getResourceUsage() { return usage; } @Override public long getStartTime() { return startTime; } @Override public ResourceWeights getWeights() { return weights; } @Override public Resource getMinShare() { return minShare; } @Override public Resource getMaxShare() { return maxShare; } @Override public void updateDemand() {} }
4,088
27.006849
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerConfiguration.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.scheduler.fair; import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration.parseResourceConfigValue; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.Test; public class TestFairSchedulerConfiguration { @Test public void testParseResourceConfigValue() throws Exception { assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue("2 vcores, 1024 mb")); assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue("1024 mb, 2 vcores")); assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue("2vcores,1024mb")); assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue("1024mb,2vcores")); assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue("1024 mb, 2 vcores")); assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue("1024 Mb, 2 vCores")); assertEquals(BuilderUtils.newResource(1024, 2), parseResourceConfigValue(" 1024 mb, 2 vcores ")); } @Test(expected = AllocationConfigurationException.class) public void testNoUnits() throws Exception { parseResourceConfigValue("1024"); } @Test(expected = AllocationConfigurationException.class) public void testOnlyMemory() throws Exception { parseResourceConfigValue("1024mb"); } @Test(expected = AllocationConfigurationException.class) public void testOnlyCPU() throws Exception { parseResourceConfigValue("1024vcores"); } @Test(expected = AllocationConfigurationException.class) public void testGibberish() throws Exception { parseResourceConfigValue("1o24vc0res"); } }
2,717
37.28169
127
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/SimpleGroupsMapping.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.scheduler.fair; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.hadoop.security.GroupMappingServiceProvider; public class SimpleGroupsMapping implements GroupMappingServiceProvider { @Override public List<String> getGroups(String user) { return Arrays.asList(user + "group", user + "subgroup1", user + "subgroup2"); } @Override public void cacheGroupsRefresh() throws IOException { throw new UnsupportedOperationException(); } @Override public void cacheGroupsAdd(List<String> groups) throws IOException { throw new UnsupportedOperationException(); } }
1,500
32.355556
81
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestQueuePlacementPolicy.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.scheduler.fair; import static org.junit.Assert.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.security.GroupMappingServiceProvider; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; public class TestQueuePlacementPolicy { private final static Configuration conf = new Configuration(); private Map<FSQueueType, Set<String>> configuredQueues; @BeforeClass public static void setup() { conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, SimpleGroupsMapping.class, GroupMappingServiceProvider.class); } @Before public void initTest() { configuredQueues = new HashMap<FSQueueType, Set<String>>(); for (FSQueueType type : FSQueueType.values()) { configuredQueues.put(type, new HashSet<String>()); } } @Test public void testSpecifiedUserPolicy() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='user' />"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.specifiedq", policy.assignAppToQueue("specifiedq", "someuser")); assertEquals("root.someuser", policy.assignAppToQueue("default", "someuser")); assertEquals("root.otheruser", policy.assignAppToQueue("default", "otheruser")); } @Test public void testNoCreate() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='user' create=\"false\" />"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); configuredQueues.get(FSQueueType.LEAF).add("root.someuser"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.specifiedq", policy.assignAppToQueue("specifiedq", "someuser")); assertEquals("root.someuser", policy.assignAppToQueue("default", "someuser")); assertEquals("root.specifiedq", policy.assignAppToQueue("specifiedq", "otheruser")); assertEquals("root.default", policy.assignAppToQueue("default", "otheruser")); } @Test public void testSpecifiedThenReject() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='reject' />"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.specifiedq", policy.assignAppToQueue("specifiedq", "someuser")); assertEquals(null, policy.assignAppToQueue("default", "someuser")); } @Test (expected = AllocationConfigurationException.class) public void testOmittedTerminalRule() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='user' create=\"false\" />"); sb.append("</queuePlacementPolicy>"); parse(sb.toString()); } @Test (expected = AllocationConfigurationException.class) public void testTerminalRuleInMiddle() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='default' />"); sb.append(" <rule name='user' />"); sb.append("</queuePlacementPolicy>"); parse(sb.toString()); } @Test public void testTerminals() throws Exception { // Should make it through without an exception StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='secondaryGroupExistingQueue' create='true'/>"); sb.append(" <rule name='default' create='false'/>"); sb.append("</queuePlacementPolicy>"); parse(sb.toString()); } @Test public void testDefaultRuleWithQueueAttribute() throws Exception { // This test covers the use case where we would like default rule // to point to a different queue by default rather than root.default configuredQueues.get(FSQueueType.LEAF).add("root.someDefaultQueue"); StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' create='false' />"); sb.append(" <rule name='default' queue='root.someDefaultQueue'/>"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.someDefaultQueue", policy.assignAppToQueue("root.default", "user1")); } @Test public void testNestedUserQueueParsingErrors() { // No nested rule specified in hierarchical user queue StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='nestedUserQueue'/>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); assertIfExceptionThrown(sb); // Specified nested rule is not a QueuePlacementRule sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='unknownRule'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); assertIfExceptionThrown(sb); } private void assertIfExceptionThrown(StringBuffer sb) { Throwable th = null; try { parse(sb.toString()); } catch (Exception e) { th = e; } assertTrue(th instanceof AllocationConfigurationException); } @Test public void testNestedUserQueueParsing() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' />"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='primaryGroup'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); Throwable th = null; try { parse(sb.toString()); } catch (Exception e) { th = e; } assertNull(th); } @Test public void testNestedUserQueuePrimaryGroup() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' create='false' />"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='primaryGroup'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); // User queue would be created under primary group queue QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.user1group.user1", policy.assignAppToQueue("root.default", "user1")); // Other rules above and below hierarchical user queue rule should work as // usual configuredQueues.get(FSQueueType.LEAF).add("root.specifiedq"); // test if specified rule(above nestedUserQueue rule) works ok assertEquals("root.specifiedq", policy.assignAppToQueue("root.specifiedq", "user2")); // test if default rule(below nestedUserQueue rule) works configuredQueues.get(FSQueueType.LEAF).add("root.user3group"); assertEquals("root.default", policy.assignAppToQueue("root.default", "user3")); } @Test public void testNestedUserQueuePrimaryGroupNoCreate() throws Exception { // Primary group rule has create='false' StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='primaryGroup' create='false'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); // Should return root.default since primary group 'root.user1group' is not // configured assertEquals("root.default", policy.assignAppToQueue("root.default", "user1")); // Let's configure primary group and check if user queue is created configuredQueues.get(FSQueueType.PARENT).add("root.user1group"); policy = parse(sb.toString()); assertEquals("root.user1group.user1", policy.assignAppToQueue("root.default", "user1")); // Both Primary group and nestedUserQueue rule has create='false' sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='nestedUserQueue' create='false'>"); sb.append(" <rule name='primaryGroup' create='false'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); // Should return root.default since primary group and user queue for user 2 // are not configured. assertEquals("root.default", policy.assignAppToQueue("root.default", "user2")); // Now configure both primary group and the user queue for user2 configuredQueues.get(FSQueueType.PARENT).add("root.user2group"); configuredQueues.get(FSQueueType.LEAF).add("root.user2group.user2"); policy = parse(sb.toString()); assertEquals("root.user2group.user2", policy.assignAppToQueue("root.default", "user2")); } @Test public void testNestedUserQueueSecondaryGroup() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='secondaryGroupExistingQueue'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); // Should return root.default since secondary groups are not configured assertEquals("root.default", policy.assignAppToQueue("root.default", "user1")); // configure secondary group for user1 configuredQueues.get(FSQueueType.PARENT).add("root.user1subgroup1"); policy = parse(sb.toString()); // user queue created should be created under secondary group assertEquals("root.user1subgroup1.user1", policy.assignAppToQueue("root.default", "user1")); } @Test public void testNestedUserQueueSpecificRule() throws Exception { // This test covers the use case where users can specify different parent // queues and want user queues under those. StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='specified' create='false'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); // Let's create couple of parent queues configuredQueues.get(FSQueueType.PARENT).add("root.parent1"); configuredQueues.get(FSQueueType.PARENT).add("root.parent2"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.parent1.user1", policy.assignAppToQueue("root.parent1", "user1")); assertEquals("root.parent2.user2", policy.assignAppToQueue("root.parent2", "user2")); } @Test public void testNestedUserQueueDefaultRule() throws Exception { // This test covers the use case where we would like user queues to be // created under a default parent queue configuredQueues.get(FSQueueType.PARENT).add("root.parentq"); StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' create='false' />"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='default' queue='root.parentq'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.parentq.user1", policy.assignAppToQueue("root.default", "user1")); } @Test public void testUserContainsPeriod() throws Exception { // This test covers the user case where the username contains periods. StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='user' />"); sb.append("</queuePlacementPolicy>"); QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.first_dot_last", policy.assignAppToQueue("default", "first.last")); sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' create='false' />"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='default'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); policy = parse(sb.toString()); assertEquals("root.default.first_dot_last", policy.assignAppToQueue("root.default", "first.last")); } @Test public void testGroupContainsPeriod() throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<queuePlacementPolicy>"); sb.append(" <rule name='specified' create='false' />"); sb.append(" <rule name='nestedUserQueue'>"); sb.append(" <rule name='primaryGroup'/>"); sb.append(" </rule>"); sb.append(" <rule name='default' />"); sb.append("</queuePlacementPolicy>"); conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, PeriodGroupsMapping.class, GroupMappingServiceProvider.class); // User queue would be created under primary group queue, and the period // in the group name should be converted into _dot_ QueuePlacementPolicy policy = parse(sb.toString()); assertEquals("root.user1_dot_group.user1", policy.assignAppToQueue("root.default", "user1")); conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, SimpleGroupsMapping.class, GroupMappingServiceProvider.class); } private QueuePlacementPolicy parse(String str) throws Exception { // Read and parse the allocations file. DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); docBuilderFactory.setIgnoringComments(true); DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(str)); Element root = doc.getDocumentElement(); return QueuePlacementPolicy.fromXml(root, configuredQueues, conf); } }
15,800
37.823096
88
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFSAppAttempt.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.scheduler.fair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import static org.junit.Assert.assertEquals; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FairSharePolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FifoPolicy; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestFSAppAttempt extends FairSchedulerTestBase { @Before public void setup() { Configuration conf = createConfiguration(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); } @Test public void testDelayScheduling() { FSLeafQueue queue = Mockito.mock(FSLeafQueue.class); Priority prio = Mockito.mock(Priority.class); Mockito.when(prio.getPriority()).thenReturn(1); double nodeLocalityThreshold = .5; double rackLocalityThreshold = .6; ApplicationAttemptId applicationAttemptId = createAppAttemptId(1, 1); RMContext rmContext = resourceManager.getRMContext(); FSAppAttempt schedulerApp = new FSAppAttempt(scheduler, applicationAttemptId, "user1", queue , null, rmContext); // Default level should be node-local assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); // First five scheduling opportunities should remain node local for (int i = 0; i < 5; i++) { schedulerApp.addSchedulingOpportunity(prio); assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); } // After five it should switch to rack local schedulerApp.addSchedulingOpportunity(prio); assertEquals(NodeType.RACK_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); // Manually set back to node local schedulerApp.resetAllowedLocalityLevel(prio, NodeType.NODE_LOCAL); schedulerApp.resetSchedulingOpportunities(prio); assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); // Now escalate again to rack-local, then to off-switch for (int i = 0; i < 5; i++) { schedulerApp.addSchedulingOpportunity(prio); assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); } schedulerApp.addSchedulingOpportunity(prio); assertEquals(NodeType.RACK_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); for (int i = 0; i < 6; i++) { schedulerApp.addSchedulingOpportunity(prio); assertEquals(NodeType.RACK_LOCAL, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); } schedulerApp.addSchedulingOpportunity(prio); assertEquals(NodeType.OFF_SWITCH, schedulerApp.getAllowedLocalityLevel( prio, 10, nodeLocalityThreshold, rackLocalityThreshold)); } @Test public void testDelaySchedulingForContinuousScheduling() throws InterruptedException { FSLeafQueue queue = scheduler.getQueueManager().getLeafQueue("queue", true); Priority prio = Mockito.mock(Priority.class); Mockito.when(prio.getPriority()).thenReturn(1); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); long nodeLocalityDelayMs = 5 * 1000L; // 5 seconds long rackLocalityDelayMs = 6 * 1000L; // 6 seconds RMContext rmContext = resourceManager.getRMContext(); ApplicationAttemptId applicationAttemptId = createAppAttemptId(1, 1); FSAppAttempt schedulerApp = new FSAppAttempt(scheduler, applicationAttemptId, "user1", queue, null, rmContext); // Default level should be node-local assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevelByTime(prio, nodeLocalityDelayMs, rackLocalityDelayMs, clock.getTime())); // after 4 seconds should remain node local clock.tickSec(4); assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevelByTime(prio, nodeLocalityDelayMs, rackLocalityDelayMs, clock.getTime())); // after 6 seconds should switch to rack local clock.tickSec(2); assertEquals(NodeType.RACK_LOCAL, schedulerApp.getAllowedLocalityLevelByTime(prio, nodeLocalityDelayMs, rackLocalityDelayMs, clock.getTime())); // manually set back to node local schedulerApp.resetAllowedLocalityLevel(prio, NodeType.NODE_LOCAL); schedulerApp.resetSchedulingOpportunities(prio, clock.getTime()); assertEquals(NodeType.NODE_LOCAL, schedulerApp.getAllowedLocalityLevelByTime(prio, nodeLocalityDelayMs, rackLocalityDelayMs, clock.getTime())); // Now escalate again to rack-local, then to off-switch clock.tickSec(6); assertEquals(NodeType.RACK_LOCAL, schedulerApp.getAllowedLocalityLevelByTime(prio, nodeLocalityDelayMs, rackLocalityDelayMs, clock.getTime())); clock.tickSec(7); assertEquals(NodeType.OFF_SWITCH, schedulerApp.getAllowedLocalityLevelByTime(prio, nodeLocalityDelayMs, rackLocalityDelayMs, clock.getTime())); } @Test /** * Ensure that when negative paramaters are given (signaling delay scheduling * no tin use), the least restrictive locality level is returned. */ public void testLocalityLevelWithoutDelays() { FSLeafQueue queue = Mockito.mock(FSLeafQueue.class); Priority prio = Mockito.mock(Priority.class); Mockito.when(prio.getPriority()).thenReturn(1); RMContext rmContext = resourceManager.getRMContext(); ApplicationAttemptId applicationAttemptId = createAppAttemptId(1, 1); FSAppAttempt schedulerApp = new FSAppAttempt(scheduler, applicationAttemptId, "user1", queue , null, rmContext); assertEquals(NodeType.OFF_SWITCH, schedulerApp.getAllowedLocalityLevel( prio, 10, -1.0, -1.0)); } @Test public void testHeadroom() { final FairScheduler mockScheduler = Mockito.mock(FairScheduler.class); Mockito.when(mockScheduler.getClock()).thenReturn(scheduler.getClock()); final FSLeafQueue mockQueue = Mockito.mock(FSLeafQueue.class); final Resource queueMaxResources = Resource.newInstance(5 * 1024, 3); final Resource queueFairShare = Resources.createResource(4096, 2); final Resource queueUsage = Resource.newInstance(2048, 2); final Resource queueStarvation = Resources.subtract(queueFairShare, queueUsage); final Resource queueMaxResourcesAvailable = Resources.subtract(queueMaxResources, queueUsage); final Resource clusterResource = Resources.createResource(8192, 8); final Resource clusterUsage = Resources.createResource(2048, 2); final Resource clusterAvailable = Resources.subtract(clusterResource, clusterUsage); final QueueMetrics fakeRootQueueMetrics = Mockito.mock(QueueMetrics.class); Mockito.when(mockQueue.getMaxShare()).thenReturn(queueMaxResources); Mockito.when(mockQueue.getFairShare()).thenReturn(queueFairShare); Mockito.when(mockQueue.getResourceUsage()).thenReturn(queueUsage); Mockito.when(mockScheduler.getClusterResource()).thenReturn (clusterResource); Mockito.when(fakeRootQueueMetrics.getAllocatedResources()).thenReturn (clusterUsage); Mockito.when(mockScheduler.getRootQueueMetrics()).thenReturn (fakeRootQueueMetrics); ApplicationAttemptId applicationAttemptId = createAppAttemptId(1, 1); RMContext rmContext = resourceManager.getRMContext(); FSAppAttempt schedulerApp = new FSAppAttempt(mockScheduler, applicationAttemptId, "user1", mockQueue , null, rmContext); // Min of Memory and CPU across cluster and queue is used in // DominantResourceFairnessPolicy Mockito.when(mockQueue.getPolicy()).thenReturn(SchedulingPolicy .getInstance(DominantResourceFairnessPolicy.class)); verifyHeadroom(schedulerApp, min(queueStarvation.getMemory(), clusterAvailable.getMemory(), queueMaxResourcesAvailable.getMemory()), min(queueStarvation.getVirtualCores(), clusterAvailable.getVirtualCores(), queueMaxResourcesAvailable.getVirtualCores()) ); // Fair and Fifo ignore CPU of queue, so use cluster available CPU Mockito.when(mockQueue.getPolicy()).thenReturn(SchedulingPolicy .getInstance(FairSharePolicy.class)); verifyHeadroom(schedulerApp, min(queueStarvation.getMemory(), clusterAvailable.getMemory(), queueMaxResourcesAvailable.getMemory()), Math.min( clusterAvailable.getVirtualCores(), queueMaxResourcesAvailable.getVirtualCores()) ); Mockito.when(mockQueue.getPolicy()).thenReturn(SchedulingPolicy .getInstance(FifoPolicy.class)); verifyHeadroom(schedulerApp, min(queueStarvation.getMemory(), clusterAvailable.getMemory(), queueMaxResourcesAvailable.getMemory()), Math.min( clusterAvailable.getVirtualCores(), queueMaxResourcesAvailable.getVirtualCores()) ); } private static int min(int value1, int value2, int value3) { return Math.min(Math.min(value1, value2), value3); } protected void verifyHeadroom(FSAppAttempt schedulerApp, int expectedMemory, int expectedCPU) { Resource headroom = schedulerApp.getHeadroom(); assertEquals(expectedMemory, headroom.getMemory()); assertEquals(expectedCPU, headroom.getVirtualCores()); } }
11,445
41.392593
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestSchedulingUpdate.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.scheduler.fair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics2.AbstractMetric; import org.apache.hadoop.metrics2.MetricsRecord; import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class TestSchedulingUpdate extends FairSchedulerTestBase { @Override public Configuration createConfiguration() { Configuration conf = super.createConfiguration(); // Make the update loop to never finish to ensure zero update calls conf.setInt( FairSchedulerConfiguration.UPDATE_INTERVAL_MS, Integer.MAX_VALUE); return conf; } @Before public void setup() { conf = createConfiguration(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); } @After public void teardown() { if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } } @Test (timeout = 3000) public void testSchedulingUpdateOnNodeJoinLeave() throws InterruptedException { verifyNoCalls(); // Add one node String host = "127.0.0.1"; final int memory = 4096; final int cores = 4; RMNode node1 = MockNodes.newNodeInfo( 1, Resources.createResource(memory, cores), 1, host); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); long expectedCalls = 1; verifyExpectedCalls(expectedCalls, memory, cores); // Remove the node NodeRemovedSchedulerEvent nodeEvent2 = new NodeRemovedSchedulerEvent(node1); scheduler.handle(nodeEvent2); expectedCalls = 2; verifyExpectedCalls(expectedCalls, 0, 0); } private void verifyExpectedCalls(long expectedCalls, int memory, int vcores) throws InterruptedException { boolean verified = false; int count = 0; while (count < 100) { if (scheduler.fsOpDurations.hasUpdateThreadRunChanged()) { break; } count++; Thread.sleep(10); } assertTrue("Update Thread has not run based on its metrics", scheduler.fsOpDurations.hasUpdateThreadRunChanged()); assertEquals("Root queue metrics memory does not have expected value", memory, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals("Root queue metrics cpu does not have expected value", vcores, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); MetricsCollectorImpl collector = new MetricsCollectorImpl(); scheduler.fsOpDurations.getMetrics(collector, true); MetricsRecord record = collector.getRecords().get(0); for (AbstractMetric abstractMetric : record.metrics()) { if (abstractMetric.name().contains("UpdateThreadRunNumOps")) { assertEquals("Update Thread did not run expected number of times " + "based on metric record count", expectedCalls, abstractMetric.value()); verified = true; } } assertTrue("Did not find metric for UpdateThreadRunNumOps", verified); } private void verifyNoCalls() { assertFalse("Update thread should not have executed", scheduler.fsOpDurations.hasUpdateThreadRunChanged()); assertEquals("Scheduler queue memory should not have been updated", 0, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals("Scheduler queue cpu should not have been updated", 0,scheduler.getRootQueueMetrics().getAvailableVirtualCores()); } }
4,999
35.764706
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestMaxRunningAppsEnforcer.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.scheduler.fair; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.util.ControlledClock; import org.junit.Before; import org.junit.Test; public class TestMaxRunningAppsEnforcer { private QueueManager queueManager; private Map<String, Integer> queueMaxApps; private Map<String, Integer> userMaxApps; private MaxRunningAppsEnforcer maxAppsEnforcer; private int appNum; private ControlledClock clock; private RMContext rmContext; private FairScheduler scheduler; @Before public void setup() throws Exception { Configuration conf = new Configuration(); clock = new ControlledClock(); scheduler = mock(FairScheduler.class); when(scheduler.getConf()).thenReturn( new FairSchedulerConfiguration(conf)); when(scheduler.getClock()).thenReturn(clock); AllocationConfiguration allocConf = new AllocationConfiguration( conf); when(scheduler.getAllocationConfiguration()).thenReturn(allocConf); queueManager = new QueueManager(scheduler); queueManager.initialize(conf); queueMaxApps = allocConf.queueMaxApps; userMaxApps = allocConf.userMaxApps; maxAppsEnforcer = new MaxRunningAppsEnforcer(scheduler); appNum = 0; rmContext = mock(RMContext.class); when(rmContext.getEpoch()).thenReturn(0L); } private FSAppAttempt addApp(FSLeafQueue queue, String user) { ApplicationId appId = ApplicationId.newInstance(0l, appNum++); ApplicationAttemptId attId = ApplicationAttemptId.newInstance(appId, 0); boolean runnable = maxAppsEnforcer.canAppBeRunnable(queue, user); FSAppAttempt app = new FSAppAttempt(scheduler, attId, user, queue, null, rmContext); queue.addApp(app, runnable); if (runnable) { maxAppsEnforcer.trackRunnableApp(app); } else { maxAppsEnforcer.trackNonRunnableApp(app); } return app; } private void removeApp(FSAppAttempt app) { app.getQueue().removeApp(app); maxAppsEnforcer.untrackRunnableApp(app); maxAppsEnforcer.updateRunnabilityOnAppRemoval(app, app.getQueue()); } @Test public void testRemoveDoesNotEnableAnyApp() { FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1", true); FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue2", true); queueMaxApps.put("root", 2); queueMaxApps.put("root.queue1", 1); queueMaxApps.put("root.queue2", 1); FSAppAttempt app1 = addApp(leaf1, "user"); addApp(leaf2, "user"); addApp(leaf2, "user"); assertEquals(1, leaf1.getNumRunnableApps()); assertEquals(1, leaf2.getNumRunnableApps()); assertEquals(1, leaf2.getNumNonRunnableApps()); removeApp(app1); assertEquals(0, leaf1.getNumRunnableApps()); assertEquals(1, leaf2.getNumRunnableApps()); assertEquals(1, leaf2.getNumNonRunnableApps()); } @Test public void testRemoveEnablesAppOnCousinQueue() { FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.subqueue1.leaf1", true); FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.subqueue2.leaf2", true); queueMaxApps.put("root.queue1", 2); FSAppAttempt app1 = addApp(leaf1, "user"); addApp(leaf2, "user"); addApp(leaf2, "user"); assertEquals(1, leaf1.getNumRunnableApps()); assertEquals(1, leaf2.getNumRunnableApps()); assertEquals(1, leaf2.getNumNonRunnableApps()); removeApp(app1); assertEquals(0, leaf1.getNumRunnableApps()); assertEquals(2, leaf2.getNumRunnableApps()); assertEquals(0, leaf2.getNumNonRunnableApps()); } @Test public void testRemoveEnablesOneByQueueOneByUser() { FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.leaf1", true); FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.leaf2", true); queueMaxApps.put("root.queue1.leaf1", 2); userMaxApps.put("user1", 1); FSAppAttempt app1 = addApp(leaf1, "user1"); addApp(leaf1, "user2"); addApp(leaf1, "user3"); addApp(leaf2, "user1"); assertEquals(2, leaf1.getNumRunnableApps()); assertEquals(1, leaf1.getNumNonRunnableApps()); assertEquals(1, leaf2.getNumNonRunnableApps()); removeApp(app1); assertEquals(2, leaf1.getNumRunnableApps()); assertEquals(1, leaf2.getNumRunnableApps()); assertEquals(0, leaf1.getNumNonRunnableApps()); assertEquals(0, leaf2.getNumNonRunnableApps()); } @Test public void testRemoveEnablingOrderedByStartTime() { FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.subqueue1.leaf1", true); FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.subqueue2.leaf2", true); queueMaxApps.put("root.queue1", 2); FSAppAttempt app1 = addApp(leaf1, "user"); addApp(leaf2, "user"); addApp(leaf2, "user"); clock.tickSec(20); addApp(leaf1, "user"); assertEquals(1, leaf1.getNumRunnableApps()); assertEquals(1, leaf2.getNumRunnableApps()); assertEquals(1, leaf1.getNumNonRunnableApps()); assertEquals(1, leaf2.getNumNonRunnableApps()); removeApp(app1); assertEquals(0, leaf1.getNumRunnableApps()); assertEquals(2, leaf2.getNumRunnableApps()); assertEquals(0, leaf2.getNumNonRunnableApps()); } @Test public void testMultipleAppsWaitingOnCousinQueue() { FSLeafQueue leaf1 = queueManager.getLeafQueue("root.queue1.subqueue1.leaf1", true); FSLeafQueue leaf2 = queueManager.getLeafQueue("root.queue1.subqueue2.leaf2", true); queueMaxApps.put("root.queue1", 2); FSAppAttempt app1 = addApp(leaf1, "user"); addApp(leaf2, "user"); addApp(leaf2, "user"); addApp(leaf2, "user"); assertEquals(1, leaf1.getNumRunnableApps()); assertEquals(1, leaf2.getNumRunnableApps()); assertEquals(2, leaf2.getNumNonRunnableApps()); removeApp(app1); assertEquals(0, leaf1.getNumRunnableApps()); assertEquals(2, leaf2.getNumRunnableApps()); assertEquals(1, leaf2.getNumNonRunnableApps()); } @Test public void testMultiListStartTimeIteratorEmptyAppLists() { List<List<FSAppAttempt>> lists = new ArrayList<List<FSAppAttempt>>(); lists.add(Arrays.asList(mockAppAttempt(1))); lists.add(Arrays.asList(mockAppAttempt(2))); Iterator<FSAppAttempt> iter = new MaxRunningAppsEnforcer.MultiListStartTimeIterator(lists); assertEquals(1, iter.next().getStartTime()); assertEquals(2, iter.next().getStartTime()); } private FSAppAttempt mockAppAttempt(long startTime) { FSAppAttempt schedApp = mock(FSAppAttempt.class); when(schedApp.getStartTime()).thenReturn(startTime); return schedApp; } }
7,832
37.777228
87
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerQueueACLs.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.scheduler.fair; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.QueueACLsTestBase; public class TestFairSchedulerQueueACLs extends QueueACLsTestBase { @Override protected Configuration createConfiguration() throws IOException { FairSchedulerConfiguration fsConf = new FairSchedulerConfiguration(); final String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); final String ALLOC_FILE = new File(TEST_DIR, "test-queues.xml") .getAbsolutePath(); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println(" <aclSubmitApps> </aclSubmitApps>"); out.println(" <aclAdministerApps>root_admin </aclAdministerApps>"); out.println(" <queue name=\"queueA\">"); out.println(" <aclSubmitApps>queueA_user,common_user </aclSubmitApps>"); out.println(" <aclAdministerApps>queueA_admin </aclAdministerApps>"); out.println(" </queue>"); out.println(" <queue name=\"queueB\">"); out.println(" <aclSubmitApps>queueB_user,common_user </aclSubmitApps>"); out.println(" <aclAdministerApps>queueB_admin </aclAdministerApps>"); out.println(" </queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); fsConf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); fsConf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); fsConf.set("yarn.resourcemanager.scheduler.class", FairScheduler.class.getName()); return fsConf; } }
2,704
41.936508
86
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.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.scheduler.fair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestFairSchedulerPreemption extends FairSchedulerTestBase { private final static String ALLOC_FILE = new File(TEST_DIR, TestFairSchedulerPreemption.class.getName() + ".xml").getAbsolutePath(); private ControlledClock clock; private static class StubbedFairScheduler extends FairScheduler { public int lastPreemptMemory = -1; @Override protected void preemptResources(Resource toPreempt) { lastPreemptMemory = toPreempt.getMemory(); } public void resetLastPreemptResources() { lastPreemptMemory = -1; } } public Configuration createConfiguration() { Configuration conf = super.createConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, StubbedFairScheduler.class, ResourceScheduler.class); conf.setBoolean(FairSchedulerConfiguration.PREEMPTION, true); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); return conf; } @Before public void setup() throws IOException { conf = createConfiguration(); clock = new ControlledClock(); } @After public void teardown() { if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } conf = null; } private void startResourceManager(float utilizationThreshold) { conf.setFloat(FairSchedulerConfiguration.PREEMPTION_THRESHOLD, utilizationThreshold); resourceManager = new MockRM(conf); resourceManager.start(); assertTrue( resourceManager.getResourceScheduler() instanceof StubbedFairScheduler); scheduler = (FairScheduler)resourceManager.getResourceScheduler(); scheduler.setClock(clock); scheduler.updateInterval = 60 * 1000; } private void registerNodeAndSubmitApp( int memory, int vcores, int appContainers, int appMemory) { RMNode node1 = MockNodes.newNodeInfo( 1, Resources.createResource(memory, vcores), 1, "node1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); assertEquals("Incorrect amount of resources in the cluster", memory, scheduler.rootMetrics.getAvailableMB()); assertEquals("Incorrect amount of resources in the cluster", vcores, scheduler.rootMetrics.getAvailableVirtualCores()); createSchedulingRequest(appMemory, "queueA", "user1", appContainers); scheduler.update(); // Sufficient node check-ins to fully schedule containers for (int i = 0; i < 3; i++) { NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeUpdate1); } assertEquals("app1's request is not met", memory - appContainers * appMemory, scheduler.rootMetrics.getAvailableMB()); } @Test public void testPreemptionWithFreeResources() throws Exception { PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"default\">"); out.println("<maxResources>0mb,0vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queueA\">"); out.println("<weight>1</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>1</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.print("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>"); out.print("<fairSharePreemptionTimeout>10</fairSharePreemptionTimeout>"); out.println("</allocations>"); out.close(); startResourceManager(0f); // Create node with 4GB memory and 4 vcores registerNodeAndSubmitApp(4 * 1024, 4, 2, 1024); // Verify submitting another request triggers preemption createSchedulingRequest(1024, "queueB", "user1", 1, 1); scheduler.update(); clock.tickSec(6); ((StubbedFairScheduler) scheduler).resetLastPreemptResources(); scheduler.preemptTasksIfNecessary(); assertEquals("preemptResources() should have been called", 1024, ((StubbedFairScheduler) scheduler).lastPreemptMemory); resourceManager.stop(); startResourceManager(0.8f); // Create node with 4GB memory and 4 vcores registerNodeAndSubmitApp(4 * 1024, 4, 3, 1024); // Verify submitting another request doesn't trigger preemption createSchedulingRequest(1024, "queueB", "user1", 1, 1); scheduler.update(); clock.tickSec(6); ((StubbedFairScheduler) scheduler).resetLastPreemptResources(); scheduler.preemptTasksIfNecessary(); assertEquals("preemptResources() should not have been called", -1, ((StubbedFairScheduler) scheduler).lastPreemptMemory); resourceManager.stop(); startResourceManager(0.7f); // Create node with 4GB memory and 4 vcores registerNodeAndSubmitApp(4 * 1024, 4, 3, 1024); // Verify submitting another request triggers preemption createSchedulingRequest(1024, "queueB", "user1", 1, 1); scheduler.update(); clock.tickSec(6); ((StubbedFairScheduler) scheduler).resetLastPreemptResources(); scheduler.preemptTasksIfNecessary(); assertEquals("preemptResources() should have been called", 1024, ((StubbedFairScheduler) scheduler).lastPreemptMemory); } }
7,249
36.564767
94
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.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.scheduler.fair; import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.security.GroupMappingServiceProvider; import org.apache.hadoop.yarn.MockApps; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; 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.QueueInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; 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.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceType; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.MockRMApp; 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.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.TestSchedulerUtils; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; 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.scheduler.event.ContainerExpiredSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerRescheduledEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueuePlacementRule.Default; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FifoPolicy; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.ControlledClock; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import com.google.common.collect.Sets; @SuppressWarnings("unchecked") public class TestFairScheduler extends FairSchedulerTestBase { private final static String ALLOC_FILE = new File(TEST_DIR, "test-queues").getAbsolutePath(); @Before public void setUp() throws IOException { scheduler = new FairScheduler(); conf = createConfiguration(); resourceManager = new MockRM(conf); // TODO: This test should really be using MockRM. For now starting stuff // that is needed at a bare minimum. ((AsyncDispatcher)resourceManager.getRMContext().getDispatcher()).start(); resourceManager.getRMContext().getStateStore().start(); // to initialize the master key resourceManager.getRMContext().getContainerTokenSecretManager().rollMasterKey(); scheduler.setRMContext(resourceManager.getRMContext()); } @After public void tearDown() { if (scheduler != null) { scheduler.stop(); scheduler = null; } if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.shutdown(); } @Test (timeout = 30000) public void testConfValidation() throws Exception { scheduler = new FairScheduler(); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 2048); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 1024); try { scheduler.serviceInit(conf); fail("Exception is expected because the min memory allocation is" + " larger than the max memory allocation."); } catch (YarnRuntimeException e) { // Exception is expected. assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler memory")); } conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, 2); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, 1); try { scheduler.serviceInit(conf); fail("Exception is expected because the min vcores allocation is" + " larger than the max vcores allocation."); } catch (YarnRuntimeException e) { // Exception is expected. assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler vcores")); } } // TESTS @Test(timeout=2000) public void testLoadConfigurationOnInitialize() throws IOException { conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, true); conf.setInt(FairSchedulerConfiguration.MAX_ASSIGN, 3); conf.setBoolean(FairSchedulerConfiguration.SIZE_BASED_WEIGHT, true); conf.setFloat(FairSchedulerConfiguration.LOCALITY_THRESHOLD_NODE, .5f); conf.setFloat(FairSchedulerConfiguration.LOCALITY_THRESHOLD_RACK, .7f); conf.setBoolean(FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_ENABLED, true); conf.setInt(FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_SLEEP_MS, 10); conf.setInt(FairSchedulerConfiguration.LOCALITY_DELAY_RACK_MS, 5000); conf.setInt(FairSchedulerConfiguration.LOCALITY_DELAY_NODE_MS, 5000); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 1024); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 512); conf.setInt(FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_MB, 128); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); Assert.assertEquals(true, scheduler.assignMultiple); Assert.assertEquals(3, scheduler.maxAssign); Assert.assertEquals(true, scheduler.sizeBasedWeight); Assert.assertEquals(.5, scheduler.nodeLocalityThreshold, .01); Assert.assertEquals(.7, scheduler.rackLocalityThreshold, .01); Assert.assertTrue("The continuous scheduling should be enabled", scheduler.continuousSchedulingEnabled); Assert.assertEquals(10, scheduler.continuousSchedulingSleepMs); Assert.assertEquals(5000, scheduler.nodeLocalityDelayMs); Assert.assertEquals(5000, scheduler.rackLocalityDelayMs); Assert.assertEquals(1024, scheduler.getMaximumResourceCapability().getMemory()); Assert.assertEquals(512, scheduler.getMinimumResourceCapability().getMemory()); Assert.assertEquals(128, scheduler.getIncrementResourceCapability().getMemory()); } @Test public void testNonMinZeroResourcesSettings() throws IOException { scheduler = new FairScheduler(); YarnConfiguration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 256); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, 1); conf.setInt( FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_MB, 512); conf.setInt( FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_VCORES, 2); scheduler.init(conf); scheduler.reinitialize(conf, null); Assert.assertEquals(256, scheduler.getMinimumResourceCapability().getMemory()); Assert.assertEquals(1, scheduler.getMinimumResourceCapability().getVirtualCores()); Assert.assertEquals(512, scheduler.getIncrementResourceCapability().getMemory()); Assert.assertEquals(2, scheduler.getIncrementResourceCapability().getVirtualCores()); } @Test public void testMinZeroResourcesSettings() throws IOException { scheduler = new FairScheduler(); YarnConfiguration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, 0); conf.setInt( FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_MB, 512); conf.setInt( FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_VCORES, 2); scheduler.init(conf); scheduler.reinitialize(conf, null); Assert.assertEquals(0, scheduler.getMinimumResourceCapability().getMemory()); Assert.assertEquals(0, scheduler.getMinimumResourceCapability().getVirtualCores()); Assert.assertEquals(512, scheduler.getIncrementResourceCapability().getMemory()); Assert.assertEquals(2, scheduler.getIncrementResourceCapability().getVirtualCores()); } @Test public void testAggregateCapacityTracking() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); assertEquals(1024, scheduler.getClusterResource().getMemory()); // Add another node RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(512), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); assertEquals(1536, scheduler.getClusterResource().getMemory()); // Remove the first node NodeRemovedSchedulerEvent nodeEvent3 = new NodeRemovedSchedulerEvent(node1); scheduler.handle(nodeEvent3); assertEquals(512, scheduler.getClusterResource().getMemory()); } @Test public void testSimpleFairShareCalculation() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(10 * 1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Have two queues which want entire cluster capacity createSchedulingRequest(10 * 1024, "queue1", "user1"); createSchedulingRequest(10 * 1024, "queue2", "user1"); createSchedulingRequest(10 * 1024, "root.default", "user1"); scheduler.update(); scheduler.getQueueManager().getRootQueue() .setSteadyFairShare(scheduler.getClusterResource()); scheduler.getQueueManager().getRootQueue().recomputeSteadyShares(); Collection<FSLeafQueue> queues = scheduler.getQueueManager().getLeafQueues(); assertEquals(3, queues.size()); // Divided three ways - between the two queues and the default queue for (FSLeafQueue p : queues) { assertEquals(3414, p.getFairShare().getMemory()); assertEquals(3414, p.getMetrics().getFairShareMB()); assertEquals(3414, p.getSteadyFairShare().getMemory()); assertEquals(3414, p.getMetrics().getSteadyFairShareMB()); } } @Test public void testFairShareWithMaxResources() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); // set queueA and queueB maxResources, // the sum of queueA and queueB maxResources is more than // Integer.MAX_VALUE. PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<maxResources>1073741824 mb 1000 vcores</maxResources>"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<maxResources>1073741824 mb 1000 vcores</maxResources>"); out.println("<weight>.75</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue A wants 1 * 1024. createSchedulingRequest(1 * 1024, "queueA", "user1"); // Queue B wants 6 * 1024 createSchedulingRequest(6 * 1024, "queueB", "user1"); scheduler.update(); FSLeafQueue queue = scheduler.getQueueManager().getLeafQueue( "queueA", false); // queueA's weight is 0.25, so its fair share should be 2 * 1024. assertEquals(2 * 1024, queue.getFairShare().getMemory()); // queueB's weight is 0.75, so its fair share should be 6 * 1024. queue = scheduler.getQueueManager().getLeafQueue( "queueB", false); assertEquals(6 * 1024, queue.getFairShare().getMemory()); } @Test public void testFairShareWithZeroWeight() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); // set queueA and queueB weight zero. PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>0.0</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>0.0</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue A wants 2 * 1024. createSchedulingRequest(2 * 1024, "queueA", "user1"); // Queue B wants 6 * 1024 createSchedulingRequest(6 * 1024, "queueB", "user1"); scheduler.update(); FSLeafQueue queue = scheduler.getQueueManager().getLeafQueue( "queueA", false); // queueA's weight is 0.0, so its fair share should be 0. assertEquals(0, queue.getFairShare().getMemory()); // queueB's weight is 0.0, so its fair share should be 0. queue = scheduler.getQueueManager().getLeafQueue( "queueB", false); assertEquals(0, queue.getFairShare().getMemory()); } @Test public void testFairShareWithZeroWeightNoneZeroMinRes() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); // set queueA and queueB weight zero. // set queueA and queueB minResources 1. PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<minResources>1 mb 1 vcores</minResources>"); out.println("<weight>0.0</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<minResources>1 mb 1 vcores</minResources>"); out.println("<weight>0.0</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue A wants 2 * 1024. createSchedulingRequest(2 * 1024, "queueA", "user1"); // Queue B wants 6 * 1024 createSchedulingRequest(6 * 1024, "queueB", "user1"); scheduler.update(); FSLeafQueue queue = scheduler.getQueueManager().getLeafQueue( "queueA", false); // queueA's weight is 0.0 and minResources is 1, // so its fair share should be 1 (minShare). assertEquals(1, queue.getFairShare().getMemory()); // queueB's weight is 0.0 and minResources is 1, // so its fair share should be 1 (minShare). queue = scheduler.getQueueManager().getLeafQueue( "queueB", false); assertEquals(1, queue.getFairShare().getMemory()); } @Test public void testFairShareWithNoneZeroWeightNoneZeroMinRes() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); // set queueA and queueB weight 0.5. // set queueA and queueB minResources 1024. PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<minResources>1024 mb 1 vcores</minResources>"); out.println("<weight>0.5</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<minResources>1024 mb 1 vcores</minResources>"); out.println("<weight>0.5</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue A wants 4 * 1024. createSchedulingRequest(4 * 1024, "queueA", "user1"); // Queue B wants 4 * 1024 createSchedulingRequest(4 * 1024, "queueB", "user1"); scheduler.update(); FSLeafQueue queue = scheduler.getQueueManager().getLeafQueue( "queueA", false); // queueA's weight is 0.5 and minResources is 1024, // so its fair share should be 4096. assertEquals(4096, queue.getFairShare().getMemory()); // queueB's weight is 0.5 and minResources is 1024, // so its fair share should be 4096. queue = scheduler.getQueueManager().getLeafQueue( "queueB", false); assertEquals(4096, queue.getFairShare().getMemory()); } @Test public void testQueueInfo() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.75</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue A wants 1 * 1024. createSchedulingRequest(1 * 1024, "queueA", "user1"); // Queue B wants 6 * 1024 createSchedulingRequest(6 * 1024, "queueB", "user1"); scheduler.update(); // Capacity should be the same as weight of Queue, // because the sum of all active Queues' weight are 1. // Before NodeUpdate Event, CurrentCapacity should be 0 QueueInfo queueInfo = scheduler.getQueueInfo("queueA", false, false); Assert.assertEquals(0.25f, queueInfo.getCapacity(), 0.0f); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity(), 0.0f); queueInfo = scheduler.getQueueInfo("queueB", false, false); Assert.assertEquals(0.75f, queueInfo.getCapacity(), 0.0f); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity(), 0.0f); // Each NodeUpdate Event will only assign one container. // To assign two containers, call handle NodeUpdate Event twice. NodeUpdateSchedulerEvent nodeEvent2 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeEvent2); scheduler.handle(nodeEvent2); // After NodeUpdate Event, CurrentCapacity for queueA should be 1/2=0.5 // and CurrentCapacity for queueB should be 6/6=1. queueInfo = scheduler.getQueueInfo("queueA", false, false); Assert.assertEquals(0.25f, queueInfo.getCapacity(), 0.0f); Assert.assertEquals(0.5f, queueInfo.getCurrentCapacity(), 0.0f); queueInfo = scheduler.getQueueInfo("queueB", false, false); Assert.assertEquals(0.75f, queueInfo.getCapacity(), 0.0f); Assert.assertEquals(1.0f, queueInfo.getCurrentCapacity(), 0.0f); } @Test public void testSimpleHierarchicalFairShareCalculation() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) int capacity = 10 * 24; RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(capacity), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Have two queues which want entire cluster capacity createSchedulingRequest(10 * 1024, "parent.queue2", "user1"); createSchedulingRequest(10 * 1024, "parent.queue3", "user1"); createSchedulingRequest(10 * 1024, "root.default", "user1"); scheduler.update(); scheduler.getQueueManager().getRootQueue() .setSteadyFairShare(scheduler.getClusterResource()); scheduler.getQueueManager().getRootQueue().recomputeSteadyShares(); QueueManager queueManager = scheduler.getQueueManager(); Collection<FSLeafQueue> queues = queueManager.getLeafQueues(); assertEquals(3, queues.size()); FSLeafQueue queue1 = queueManager.getLeafQueue("default", true); FSLeafQueue queue2 = queueManager.getLeafQueue("parent.queue2", true); FSLeafQueue queue3 = queueManager.getLeafQueue("parent.queue3", true); assertEquals(capacity / 2, queue1.getFairShare().getMemory()); assertEquals(capacity / 2, queue1.getMetrics().getFairShareMB()); assertEquals(capacity / 2, queue1.getSteadyFairShare().getMemory()); assertEquals(capacity / 2, queue1.getMetrics().getSteadyFairShareMB()); assertEquals(capacity / 4, queue2.getFairShare().getMemory()); assertEquals(capacity / 4, queue2.getMetrics().getFairShareMB()); assertEquals(capacity / 4, queue2.getSteadyFairShare().getMemory()); assertEquals(capacity / 4, queue2.getMetrics().getSteadyFairShareMB()); assertEquals(capacity / 4, queue3.getFairShare().getMemory()); assertEquals(capacity / 4, queue3.getMetrics().getFairShareMB()); assertEquals(capacity / 4, queue3.getSteadyFairShare().getMemory()); assertEquals(capacity / 4, queue3.getMetrics().getSteadyFairShareMB()); } @Test public void testHierarchicalQueuesSimilarParents() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); QueueManager queueManager = scheduler.getQueueManager(); FSLeafQueue leafQueue = queueManager.getLeafQueue("parent.child", true); Assert.assertEquals(2, queueManager.getLeafQueues().size()); Assert.assertNotNull(leafQueue); Assert.assertEquals("root.parent.child", leafQueue.getName()); FSLeafQueue leafQueue2 = queueManager.getLeafQueue("parent", true); Assert.assertNull(leafQueue2); Assert.assertEquals(2, queueManager.getLeafQueues().size()); FSLeafQueue leafQueue3 = queueManager.getLeafQueue("parent.child.grandchild", true); Assert.assertNull(leafQueue3); Assert.assertEquals(2, queueManager.getLeafQueues().size()); FSLeafQueue leafQueue4 = queueManager.getLeafQueue("parent.sister", true); Assert.assertNotNull(leafQueue4); Assert.assertEquals("root.parent.sister", leafQueue4.getName()); Assert.assertEquals(3, queueManager.getLeafQueues().size()); } @Test public void testSchedulerRootQueueMetrics() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(1024)); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue 1 requests full capacity of node createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // Now queue 2 requests likewise createSchedulingRequest(1024, "queue2", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // Make sure reserved memory gets updated correctly assertEquals(1024, scheduler.rootMetrics.getReservedMB()); // Now another node checks in with capacity RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(1024)); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); NodeUpdateSchedulerEvent updateEvent2 = new NodeUpdateSchedulerEvent(node2); scheduler.handle(nodeEvent2); scheduler.handle(updateEvent2); // The old reservation should still be there... assertEquals(1024, scheduler.rootMetrics.getReservedMB()); // ... but it should disappear when we update the first node. scheduler.handle(updateEvent); assertEquals(0, scheduler.rootMetrics.getReservedMB()); } @Test (timeout = 5000) public void testSimpleContainerAllocation() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(1024, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Add another node RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(512, 2), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); createSchedulingRequest(512, 2, "queue1", "user1", 2); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // Asked for less than increment allocation. assertEquals(FairSchedulerConfiguration.DEFAULT_RM_SCHEDULER_INCREMENT_ALLOCATION_MB, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getMemory()); NodeUpdateSchedulerEvent updateEvent2 = new NodeUpdateSchedulerEvent(node2); scheduler.handle(updateEvent2); assertEquals(1024, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getMemory()); assertEquals(2, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getVirtualCores()); // verify metrics QueueMetrics queue1Metrics = scheduler.getQueueManager().getQueue("queue1") .getMetrics(); assertEquals(1024, queue1Metrics.getAllocatedMB()); assertEquals(2, queue1Metrics.getAllocatedVirtualCores()); assertEquals(1024, scheduler.getRootQueueMetrics().getAllocatedMB()); assertEquals(2, scheduler.getRootQueueMetrics().getAllocatedVirtualCores()); assertEquals(512, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(4, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); } @Test (timeout = 5000) public void testSimpleContainerReservation() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue 1 requests full capacity of node createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // Make sure queue 1 is allocated app capacity assertEquals(1024, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getMemory()); // Now queue 2 requests likewise ApplicationAttemptId attId = createSchedulingRequest(1024, "queue2", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // Make sure queue 2 is waiting with a reservation assertEquals(0, scheduler.getQueueManager().getQueue("queue2"). getResourceUsage().getMemory()); assertEquals(1024, scheduler.getSchedulerApp(attId).getCurrentReservation().getMemory()); // Now another node checks in with capacity RMNode node2 = MockNodes .newNodeInfo(1, Resources.createResource(1024), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); NodeUpdateSchedulerEvent updateEvent2 = new NodeUpdateSchedulerEvent(node2); scheduler.handle(nodeEvent2); scheduler.handle(updateEvent2); // Make sure this goes to queue 2 assertEquals(1024, scheduler.getQueueManager().getQueue("queue2"). getResourceUsage().getMemory()); // The old reservation should still be there... assertEquals(1024, scheduler.getSchedulerApp(attId).getCurrentReservation().getMemory()); // ... but it should disappear when we update the first node. scheduler.handle(updateEvent); assertEquals(0, scheduler.getSchedulerApp(attId).getCurrentReservation().getMemory()); } @Test (timeout = 500000) public void testContainerReservationAttemptExceedingQueueMax() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println("<queue name=\"queue1\">"); out.println("<maxResources>2048mb,5vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queue2\">"); out.println("<maxResources>2048mb,10vcores</maxResources>"); out.println("</queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(3072, 5), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue 1 requests full capacity of the queue createSchedulingRequest(2048, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // Make sure queue 1 is allocated app capacity assertEquals(2048, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getMemory()); // Now queue 2 requests likewise createSchedulingRequest(1024, "queue2", "user2", 1); scheduler.update(); scheduler.handle(updateEvent); // Make sure queue 2 is allocated app capacity assertEquals(1024, scheduler.getQueueManager().getQueue("queue2"). getResourceUsage().getMemory()); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // Ensure the reservation does not get created as allocated memory of // queue1 exceeds max assertEquals(0, scheduler.getSchedulerApp(attId1). getCurrentReservation().getMemory()); } @Test (timeout = 500000) public void testContainerReservationNotExceedingQueueMax() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println("<queue name=\"queue1\">"); out.println("<maxResources>3072mb,10vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queue2\">"); out.println("<maxResources>2048mb,10vcores</maxResources>"); out.println("</queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(3072, 5), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue 1 requests full capacity of the queue createSchedulingRequest(2048, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // Make sure queue 1 is allocated app capacity assertEquals(2048, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getMemory()); // Now queue 2 requests likewise createSchedulingRequest(1024, "queue2", "user2", 1); scheduler.update(); scheduler.handle(updateEvent); // Make sure queue 2 is allocated app capacity assertEquals(1024, scheduler.getQueueManager().getQueue("queue2"). getResourceUsage().getMemory()); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // Make sure queue 1 is waiting with a reservation assertEquals(1024, scheduler.getSchedulerApp(attId1) .getCurrentReservation().getMemory()); // Exercise checks that reservation fits scheduler.handle(updateEvent); // Ensure the reservation still exists as allocated memory of queue1 doesn't // exceed max assertEquals(1024, scheduler.getSchedulerApp(attId1). getCurrentReservation().getMemory()); // Now reduce max Resources of queue1 down to 2048 out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println("<queue name=\"queue1\">"); out.println("<maxResources>2048mb,10vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queue2\">"); out.println("<maxResources>2048mb,10vcores</maxResources>"); out.println("</queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.reinitialize(conf, resourceManager.getRMContext()); createSchedulingRequest(1024, "queue2", "user2", 1); scheduler.handle(updateEvent); // Make sure allocated memory of queue1 doesn't exceed its maximum assertEquals(2048, scheduler.getQueueManager().getQueue("queue1"). getResourceUsage().getMemory()); //the reservation of queue1 should be reclaim assertEquals(0, scheduler.getSchedulerApp(attId1). getCurrentReservation().getMemory()); assertEquals(1024, scheduler.getQueueManager().getQueue("queue2"). getResourceUsage().getMemory()); } @Test public void testEmptyQueueName() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // only default queue assertEquals(1, scheduler.getQueueManager().getLeafQueues().size()); // submit app with empty queue ApplicationAttemptId appAttemptId = createAppAttemptId(1, 1); AppAddedSchedulerEvent appAddedEvent = new AppAddedSchedulerEvent(appAttemptId.getApplicationId(), "", "user1"); scheduler.handle(appAddedEvent); // submission rejected assertEquals(1, scheduler.getQueueManager().getLeafQueues().size()); assertNull(scheduler.getSchedulerApp(appAttemptId)); assertEquals(0, resourceManager.getRMContext().getRMApps().size()); } @Test public void testQueueuNameWithPeriods() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // only default queue assertEquals(1, scheduler.getQueueManager().getLeafQueues().size()); // submit app with queue name (.A) ApplicationAttemptId appAttemptId1 = createAppAttemptId(1, 1); AppAddedSchedulerEvent appAddedEvent1 = new AppAddedSchedulerEvent(appAttemptId1.getApplicationId(), ".A", "user1"); scheduler.handle(appAddedEvent1); // submission rejected assertEquals(1, scheduler.getQueueManager().getLeafQueues().size()); assertNull(scheduler.getSchedulerApp(appAttemptId1)); assertEquals(0, resourceManager.getRMContext().getRMApps().size()); // submit app with queue name (A.) ApplicationAttemptId appAttemptId2 = createAppAttemptId(2, 1); AppAddedSchedulerEvent appAddedEvent2 = new AppAddedSchedulerEvent(appAttemptId2.getApplicationId(), "A.", "user1"); scheduler.handle(appAddedEvent2); // submission rejected assertEquals(1, scheduler.getQueueManager().getLeafQueues().size()); assertNull(scheduler.getSchedulerApp(appAttemptId2)); assertEquals(0, resourceManager.getRMContext().getRMApps().size()); // submit app with queue name (A.B) ApplicationAttemptId appAttemptId3 = createAppAttemptId(3, 1); AppAddedSchedulerEvent appAddedEvent3 = new AppAddedSchedulerEvent(appAttemptId3.getApplicationId(), "A.B", "user1"); scheduler.handle(appAddedEvent3); // submission accepted assertEquals(2, scheduler.getQueueManager().getLeafQueues().size()); assertNull(scheduler.getSchedulerApp(appAttemptId3)); assertEquals(0, resourceManager.getRMContext().getRMApps().size()); } @Test public void testAssignToQueue() throws Exception { conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "true"); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMApp rmApp1 = new MockRMApp(0, 0, RMAppState.NEW); RMApp rmApp2 = new MockRMApp(1, 1, RMAppState.NEW); FSLeafQueue queue1 = scheduler.assignToQueue(rmApp1, "default", "asterix"); FSLeafQueue queue2 = scheduler.assignToQueue(rmApp2, "notdefault", "obelix"); // assert FSLeafQueue's name is the correct name is the one set in the RMApp assertEquals(rmApp1.getQueue(), queue1.getName()); assertEquals("root.asterix", rmApp1.getQueue()); assertEquals(rmApp2.getQueue(), queue2.getName()); assertEquals("root.notdefault", rmApp2.getQueue()); } @Test public void testAssignToNonLeafQueueReturnsNull() throws Exception { conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "true"); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); scheduler.getQueueManager().getLeafQueue("root.child1.granchild", true); scheduler.getQueueManager().getLeafQueue("root.child2", true); RMApp rmApp1 = new MockRMApp(0, 0, RMAppState.NEW); RMApp rmApp2 = new MockRMApp(1, 1, RMAppState.NEW); // Trying to assign to non leaf queue would return null assertNull(scheduler.assignToQueue(rmApp1, "root.child1", "tintin")); assertNotNull(scheduler.assignToQueue(rmApp2, "root.child2", "snowy")); } @Test public void testQueuePlacementWithPolicy() throws Exception { conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, SimpleGroupsMapping.class, GroupMappingServiceProvider.class); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId appId; List<QueuePlacementRule> rules = new ArrayList<QueuePlacementRule>(); rules.add(new QueuePlacementRule.Specified().initialize(true, null)); rules.add(new QueuePlacementRule.User().initialize(false, null)); rules.add(new QueuePlacementRule.PrimaryGroup().initialize(false, null)); rules.add(new QueuePlacementRule.SecondaryGroupExistingQueue().initialize(false, null)); rules.add(new QueuePlacementRule.Default().initialize(true, null)); Set<String> queues = Sets.newHashSet("root.user1", "root.user3group", "root.user4subgroup1", "root.user4subgroup2" , "root.user5subgroup2"); Map<FSQueueType, Set<String>> configuredQueues = new HashMap<FSQueueType, Set<String>>(); configuredQueues.put(FSQueueType.LEAF, queues); configuredQueues.put(FSQueueType.PARENT, new HashSet<String>()); scheduler.getAllocationConfiguration().placementPolicy = new QueuePlacementPolicy(rules, configuredQueues, conf); appId = createSchedulingRequest(1024, "somequeue", "user1"); assertEquals("root.somequeue", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "default", "user1"); assertEquals("root.user1", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "default", "user3"); assertEquals("root.user3group", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "default", "user4"); assertEquals("root.user4subgroup1", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "default", "user5"); assertEquals("root.user5subgroup2", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "default", "otheruser"); assertEquals("root.default", scheduler.getSchedulerApp(appId).getQueueName()); // test without specified as first rule rules = new ArrayList<QueuePlacementRule>(); rules.add(new QueuePlacementRule.User().initialize(false, null)); rules.add(new QueuePlacementRule.Specified().initialize(true, null)); rules.add(new QueuePlacementRule.Default().initialize(true, null)); scheduler.getAllocationConfiguration().placementPolicy = new QueuePlacementPolicy(rules, configuredQueues, conf); appId = createSchedulingRequest(1024, "somequeue", "user1"); assertEquals("root.user1", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "somequeue", "otheruser"); assertEquals("root.somequeue", scheduler.getSchedulerApp(appId).getQueueName()); appId = createSchedulingRequest(1024, "default", "otheruser"); assertEquals("root.default", scheduler.getSchedulerApp(appId).getQueueName()); } @Test public void testFairShareWithMinAlloc() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one big node (only care about aggregate capacity) RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); createSchedulingRequest(2 * 1024, "queueA", "user1"); createSchedulingRequest(2 * 1024, "queueB", "user1"); scheduler.update(); Collection<FSLeafQueue> queues = scheduler.getQueueManager().getLeafQueues(); assertEquals(3, queues.size()); for (FSLeafQueue p : queues) { if (p.getName().equals("root.queueA")) { assertEquals(1024, p.getFairShare().getMemory()); } else if (p.getName().equals("root.queueB")) { assertEquals(2048, p.getFairShare().getMemory()); } } } @Test public void testNestedUserQueue() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, SimpleGroupsMapping.class, GroupMappingServiceProvider.class); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"user1group\" type=\"parent\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queuePlacementPolicy>"); out.println("<rule name=\"specified\" create=\"false\" />"); out.println("<rule name=\"nestedUserQueue\">"); out.println(" <rule name=\"primaryGroup\" create=\"false\" />"); out.println("</rule>"); out.println("<rule name=\"default\" />"); out.println("</queuePlacementPolicy>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMApp rmApp1 = new MockRMApp(0, 0, RMAppState.NEW); FSLeafQueue user1Leaf = scheduler.assignToQueue(rmApp1, "root.default", "user1"); assertEquals("root.user1group.user1", user1Leaf.getName()); } @Test public void testFairShareAndWeightsInNestedUserQueueRule() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"parentq\" type=\"parent\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queuePlacementPolicy>"); out.println("<rule name=\"nestedUserQueue\">"); out.println(" <rule name=\"specified\" create=\"false\" />"); out.println("</rule>"); out.println("<rule name=\"default\" />"); out.println("</queuePlacementPolicy>"); out.println("</allocations>"); out.close(); RMApp rmApp1 = new MockRMApp(0, 0, RMAppState.NEW); RMApp rmApp2 = new MockRMApp(1, 1, RMAppState.NEW); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); int capacity = 16 * 1024; // create node with 16 G RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(capacity), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // user1,user2 submit their apps to parentq and create user queues createSchedulingRequest(10 * 1024, "root.parentq", "user1"); createSchedulingRequest(10 * 1024, "root.parentq", "user2"); // user3 submits app in default queue createSchedulingRequest(10 * 1024, "root.default", "user3"); scheduler.update(); scheduler.getQueueManager().getRootQueue() .setSteadyFairShare(scheduler.getClusterResource()); scheduler.getQueueManager().getRootQueue().recomputeSteadyShares(); Collection<FSLeafQueue> leafQueues = scheduler.getQueueManager() .getLeafQueues(); for (FSLeafQueue leaf : leafQueues) { if (leaf.getName().equals("root.parentq.user1") || leaf.getName().equals("root.parentq.user2")) { // assert that the fair share is 1/4th node1's capacity assertEquals(capacity / 4, leaf.getFairShare().getMemory()); // assert that the steady fair share is 1/4th node1's capacity assertEquals(capacity / 4, leaf.getSteadyFairShare().getMemory()); // assert weights are equal for both the user queues assertEquals(1.0, leaf.getWeights().getWeight(ResourceType.MEMORY), 0); } } } @Test public void testSteadyFairShareWithReloadAndNodeAddRemove() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<defaultQueueSchedulingPolicy>fair</defaultQueueSchedulingPolicy>"); out.println("<queue name=\"root\">"); out.println(" <schedulingPolicy>drf</schedulingPolicy>"); out.println(" <queue name=\"child1\">"); out.println(" <weight>1</weight>"); out.println(" </queue>"); out.println(" <queue name=\"child2\">"); out.println(" <weight>1</weight>"); out.println(" </queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // The steady fair share for all queues should be 0 QueueManager queueManager = scheduler.getQueueManager(); assertEquals(0, queueManager.getLeafQueue("child1", false) .getSteadyFairShare().getMemory()); assertEquals(0, queueManager.getLeafQueue("child2", false) .getSteadyFairShare().getMemory()); // Add one node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(6144), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); assertEquals(6144, scheduler.getClusterResource().getMemory()); // The steady fair shares for all queues should be updated assertEquals(2048, queueManager.getLeafQueue("child1", false) .getSteadyFairShare().getMemory()); assertEquals(2048, queueManager.getLeafQueue("child2", false) .getSteadyFairShare().getMemory()); // Reload the allocation configuration file out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<defaultQueueSchedulingPolicy>fair</defaultQueueSchedulingPolicy>"); out.println("<queue name=\"root\">"); out.println(" <schedulingPolicy>drf</schedulingPolicy>"); out.println(" <queue name=\"child1\">"); out.println(" <weight>1</weight>"); out.println(" </queue>"); out.println(" <queue name=\"child2\">"); out.println(" <weight>2</weight>"); out.println(" </queue>"); out.println(" <queue name=\"child3\">"); out.println(" <weight>2</weight>"); out.println(" </queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // The steady fair shares for all queues should be updated assertEquals(1024, queueManager.getLeafQueue("child1", false) .getSteadyFairShare().getMemory()); assertEquals(2048, queueManager.getLeafQueue("child2", false) .getSteadyFairShare().getMemory()); assertEquals(2048, queueManager.getLeafQueue("child3", false) .getSteadyFairShare().getMemory()); // Remove the node, steady fair shares should back to 0 NodeRemovedSchedulerEvent nodeEvent2 = new NodeRemovedSchedulerEvent(node1); scheduler.handle(nodeEvent2); assertEquals(0, scheduler.getClusterResource().getMemory()); assertEquals(0, queueManager.getLeafQueue("child1", false) .getSteadyFairShare().getMemory()); assertEquals(0, queueManager.getLeafQueue("child2", false) .getSteadyFairShare().getMemory()); } @Test public void testSteadyFairShareWithQueueCreatedRuntime() throws Exception { conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, SimpleGroupsMapping.class, GroupMappingServiceProvider.class); conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "true"); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add one node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(6144), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); assertEquals(6144, scheduler.getClusterResource().getMemory()); assertEquals(6144, scheduler.getQueueManager().getRootQueue() .getSteadyFairShare().getMemory()); assertEquals(6144, scheduler.getQueueManager() .getLeafQueue("default", false).getSteadyFairShare().getMemory()); // Submit one application ApplicationAttemptId appAttemptId1 = createAppAttemptId(1, 1); createApplicationWithAMResource(appAttemptId1, "default", "user1", null); assertEquals(3072, scheduler.getQueueManager() .getLeafQueue("default", false).getSteadyFairShare().getMemory()); assertEquals(3072, scheduler.getQueueManager() .getLeafQueue("user1", false).getSteadyFairShare().getMemory()); } /** * Make allocation requests and ensure they are reflected in queue demand. */ @Test public void testQueueDemandCalculation() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId id11 = createAppAttemptId(1, 1); createMockRMApp(id11); scheduler.addApplication(id11.getApplicationId(), "root.queue1", "user1", false); scheduler.addApplicationAttempt(id11, false, false); ApplicationAttemptId id21 = createAppAttemptId(2, 1); createMockRMApp(id21); scheduler.addApplication(id21.getApplicationId(), "root.queue2", "user1", false); scheduler.addApplicationAttempt(id21, false, false); ApplicationAttemptId id22 = createAppAttemptId(2, 2); createMockRMApp(id22); scheduler.addApplication(id22.getApplicationId(), "root.queue2", "user1", false); scheduler.addApplicationAttempt(id22, false, false); int minReqSize = FairSchedulerConfiguration.DEFAULT_RM_SCHEDULER_INCREMENT_ALLOCATION_MB; // First ask, queue1 requests 1 large (minReqSize * 2). List<ResourceRequest> ask1 = new ArrayList<ResourceRequest>(); ResourceRequest request1 = createResourceRequest(minReqSize * 2, ResourceRequest.ANY, 1, 1, true); ask1.add(request1); scheduler.allocate(id11, ask1, new ArrayList<ContainerId>(), null, null); // Second ask, queue2 requests 1 large + (2 * minReqSize) List<ResourceRequest> ask2 = new ArrayList<ResourceRequest>(); ResourceRequest request2 = createResourceRequest(2 * minReqSize, "foo", 1, 1, false); ResourceRequest request3 = createResourceRequest(minReqSize, "bar", 1, 2, false); ask2.add(request2); ask2.add(request3); scheduler.allocate(id21, ask2, new ArrayList<ContainerId>(), null, null); // Third ask, queue2 requests 1 large List<ResourceRequest> ask3 = new ArrayList<ResourceRequest>(); ResourceRequest request4 = createResourceRequest(2 * minReqSize, ResourceRequest.ANY, 1, 1, true); ask3.add(request4); scheduler.allocate(id22, ask3, new ArrayList<ContainerId>(), null, null); scheduler.update(); assertEquals(2 * minReqSize, scheduler.getQueueManager().getQueue("root.queue1") .getDemand().getMemory()); assertEquals(2 * minReqSize + 2 * minReqSize + (2 * minReqSize), scheduler .getQueueManager().getQueue("root.queue2").getDemand() .getMemory()); } @Test public void testHierarchicalQueueAllocationFileParsing() throws IOException, SAXException, AllocationConfigurationException, ParserConfigurationException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("<queue name=\"queueC\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueD\">"); out.println("<minResources>2048mb,0vcores</minResources>"); out.println("</queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); QueueManager queueManager = scheduler.getQueueManager(); Collection<FSLeafQueue> leafQueues = queueManager.getLeafQueues(); Assert.assertEquals(4, leafQueues.size()); Assert.assertNotNull(queueManager.getLeafQueue("queueA", false)); Assert.assertNotNull(queueManager.getLeafQueue("queueB.queueC", false)); Assert.assertNotNull(queueManager.getLeafQueue("queueB.queueD", false)); Assert.assertNotNull(queueManager.getLeafQueue("default", false)); // Make sure querying for queues didn't create any new ones: Assert.assertEquals(4, leafQueues.size()); } @Test public void testConfigureRootQueue() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<defaultQueueSchedulingPolicy>fair</defaultQueueSchedulingPolicy>"); out.println("<queue name=\"root\">"); out.println(" <schedulingPolicy>drf</schedulingPolicy>"); out.println(" <queue name=\"child1\">"); out.println(" <minResources>1024mb,1vcores</minResources>"); out.println(" </queue>"); out.println(" <queue name=\"child2\">"); out.println(" <minResources>1024mb,4vcores</minResources>"); out.println(" </queue>"); out.println(" <fairSharePreemptionTimeout>100</fairSharePreemptionTimeout>"); out.println(" <minSharePreemptionTimeout>120</minSharePreemptionTimeout>"); out.println(" <fairSharePreemptionThreshold>.5</fairSharePreemptionThreshold>"); out.println("</queue>"); out.println("<defaultFairSharePreemptionTimeout>300</defaultFairSharePreemptionTimeout>"); out.println("<defaultMinSharePreemptionTimeout>200</defaultMinSharePreemptionTimeout>"); out.println("<defaultFairSharePreemptionThreshold>.6</defaultFairSharePreemptionThreshold>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); QueueManager queueManager = scheduler.getQueueManager(); FSQueue root = queueManager.getRootQueue(); assertTrue(root.getPolicy() instanceof DominantResourceFairnessPolicy); assertNotNull(queueManager.getLeafQueue("child1", false)); assertNotNull(queueManager.getLeafQueue("child2", false)); assertEquals(100000, root.getFairSharePreemptionTimeout()); assertEquals(120000, root.getMinSharePreemptionTimeout()); assertEquals(0.5f, root.getFairSharePreemptionThreshold(), 0.01); } @Test (timeout = 5000) /** * Make sure containers are chosen to be preempted in the correct order. */ public void testChoiceOfPreemptedContainers() throws Exception { conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000); conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE + ".allocation.file", ALLOC_FILE); conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false"); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("<queue name=\"queueC\">"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("<queue name=\"default\">"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Create two nodes RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); // Queue A and B each request two applications ApplicationAttemptId app1 = createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 1); createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1); ApplicationAttemptId app2 = createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 3); createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app2); ApplicationAttemptId app3 = createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 1); createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app3); ApplicationAttemptId app4 = createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 3); createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app4); scheduler.update(); scheduler.getQueueManager().getLeafQueue("queueA", true) .setPolicy(SchedulingPolicy.parse("fifo")); scheduler.getQueueManager().getLeafQueue("queueB", true) .setPolicy(SchedulingPolicy.parse("fair")); // Sufficient node check-ins to fully schedule containers NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1); NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2); for (int i = 0; i < 4; i++) { scheduler.handle(nodeUpdate1); scheduler.handle(nodeUpdate2); } assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size()); assertEquals(2, scheduler.getSchedulerApp(app2).getLiveContainers().size()); assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size()); assertEquals(2, scheduler.getSchedulerApp(app4).getLiveContainers().size()); // Now new requests arrive from queueC and default createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1); createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1); createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1); createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1); scheduler.update(); // We should be able to claw back one container from queueA and queueB each. scheduler.preemptResources(Resources.createResource(2 * 1024)); assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size()); assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size()); // First verify we are adding containers to preemption list for the app. // For queueA (fifo), app2 is selected. // For queueB (fair), app4 is selected. assertTrue("App2 should have container to be preempted", !Collections.disjoint( scheduler.getSchedulerApp(app2).getLiveContainers(), scheduler.getSchedulerApp(app2).getPreemptionContainers())); assertTrue("App4 should have container to be preempted", !Collections.disjoint( scheduler.getSchedulerApp(app2).getLiveContainers(), scheduler.getSchedulerApp(app2).getPreemptionContainers())); // Pretend 15 seconds have passed clock.tickSec(15); // Trigger a kill by insisting we want containers back scheduler.preemptResources(Resources.createResource(2 * 1024)); // At this point the containers should have been killed (since we are not simulating AM) assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size()); assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size()); // Inside each app, containers are sorted according to their priorities. // Containers with priority 4 are preempted for app2 and app4. Set<RMContainer> set = new HashSet<RMContainer>(); for (RMContainer container : scheduler.getSchedulerApp(app2).getLiveContainers()) { if (container.getAllocatedPriority().getPriority() == 4) { set.add(container); } } for (RMContainer container : scheduler.getSchedulerApp(app4).getLiveContainers()) { if (container.getAllocatedPriority().getPriority() == 4) { set.add(container); } } assertTrue("Containers with priority=4 in app2 and app4 should be " + "preempted.", set.isEmpty()); // Trigger a kill by insisting we want containers back scheduler.preemptResources(Resources.createResource(2 * 1024)); // Pretend 15 seconds have passed clock.tickSec(15); // We should be able to claw back another container from A and B each. // For queueA (fifo), continue preempting from app2. // For queueB (fair), even app4 has a lowest priority container with p=4, it // still preempts from app3 as app3 is most over fair share. scheduler.preemptResources(Resources.createResource(2 * 1024)); assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size()); assertEquals(0, scheduler.getSchedulerApp(app2).getLiveContainers().size()); assertEquals(1, scheduler.getSchedulerApp(app3).getLiveContainers().size()); assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size()); // Now A and B are below fair share, so preemption shouldn't do anything scheduler.preemptResources(Resources.createResource(2 * 1024)); assertTrue("App1 should have no container to be preempted", scheduler.getSchedulerApp(app1).getPreemptionContainers().isEmpty()); assertTrue("App2 should have no container to be preempted", scheduler.getSchedulerApp(app2).getPreemptionContainers().isEmpty()); assertTrue("App3 should have no container to be preempted", scheduler.getSchedulerApp(app3).getPreemptionContainers().isEmpty()); assertTrue("App4 should have no container to be preempted", scheduler.getSchedulerApp(app4).getPreemptionContainers().isEmpty()); } @Test public void testPreemptionIsNotDelayedToNextRound() throws Exception { conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000); conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false"); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>8</weight>"); out.println("<queue name=\"queueA1\" />"); out.println("<queue name=\"queueA2\" />"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>2</weight>"); out.println("</queue>"); out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>"); out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node of 8G RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Run apps in queueA.A1 and queueB ApplicationAttemptId app1 = createSchedulingRequest(1 * 1024, 1, "queueA.queueA1", "user1", 7, 1); // createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1); ApplicationAttemptId app2 = createSchedulingRequest(1 * 1024, 1, "queueB", "user2", 1, 1); scheduler.update(); NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1); for (int i = 0; i < 8; i++) { scheduler.handle(nodeUpdate1); } // verify if the apps got the containers they requested assertEquals(7, scheduler.getSchedulerApp(app1).getLiveContainers().size()); assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size()); // Now submit an app in queueA.queueA2 ApplicationAttemptId app3 = createSchedulingRequest(1 * 1024, 1, "queueA.queueA2", "user3", 7, 1); scheduler.update(); // Let 11 sec pass clock.tickSec(11); scheduler.update(); Resource toPreempt = scheduler.resourceDeficit(scheduler.getQueueManager() .getLeafQueue("queueA.queueA2", false), clock.getTime()); assertEquals(3277, toPreempt.getMemory()); // verify if the 3 containers required by queueA2 are preempted in the same // round scheduler.preemptResources(toPreempt); assertEquals(3, scheduler.getSchedulerApp(app1).getPreemptionContainers() .size()); } @Test (timeout = 5000) /** * Tests the timing of decision to preempt tasks. */ public void testPreemptionDecision() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"default\">"); out.println("<maxResources>0mb,0vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueC\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueD\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>"); out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>"); out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Create four nodes RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); RMNode node3 = MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 3, "127.0.0.3"); NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3); scheduler.handle(nodeEvent3); // Queue A and B each request three containers ApplicationAttemptId app1 = createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1); ApplicationAttemptId app2 = createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2); ApplicationAttemptId app3 = createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3); ApplicationAttemptId app4 = createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1); ApplicationAttemptId app5 = createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2); ApplicationAttemptId app6 = createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3); scheduler.update(); // Sufficient node check-ins to fully schedule containers for (int i = 0; i < 2; i++) { NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeUpdate1); NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2); scheduler.handle(nodeUpdate2); NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3); scheduler.handle(nodeUpdate3); } // Now new requests arrive from queues C and D ApplicationAttemptId app7 = createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1); ApplicationAttemptId app8 = createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2); ApplicationAttemptId app9 = createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3); ApplicationAttemptId app10 = createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 1); ApplicationAttemptId app11 = createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 2); ApplicationAttemptId app12 = createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 3); scheduler.update(); FSLeafQueue schedC = scheduler.getQueueManager().getLeafQueue("queueC", true); FSLeafQueue schedD = scheduler.getQueueManager().getLeafQueue("queueD", true); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(schedC, clock.getTime()))); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(schedD, clock.getTime()))); // After minSharePreemptionTime has passed, they should want to preempt min // share. clock.tickSec(6); assertEquals( 1024, scheduler.resourceDeficit(schedC, clock.getTime()).getMemory()); assertEquals( 1024, scheduler.resourceDeficit(schedD, clock.getTime()).getMemory()); // After fairSharePreemptionTime has passed, they should want to preempt // fair share. scheduler.update(); clock.tickSec(6); assertEquals( 1536 , scheduler.resourceDeficit(schedC, clock.getTime()).getMemory()); assertEquals( 1536, scheduler.resourceDeficit(schedD, clock.getTime()).getMemory()); } @Test /** * Tests the timing of decision to preempt tasks. */ public void testPreemptionDecisionWithDRF() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"default\">"); out.println("<maxResources>0mb,0vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,1vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,2vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueC\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,3vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueD\">"); out.println("<weight>.25</weight>"); out.println("<minResources>1024mb,2vcores</minResources>"); out.println("</queue>"); out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>"); out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>"); out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>"); out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Create four nodes RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); RMNode node3 = MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 3, "127.0.0.3"); NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3); scheduler.handle(nodeEvent3); // Queue A and B each request three containers ApplicationAttemptId app1 = createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1); ApplicationAttemptId app2 = createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2); ApplicationAttemptId app3 = createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3); ApplicationAttemptId app4 = createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1); ApplicationAttemptId app5 = createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2); ApplicationAttemptId app6 = createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3); scheduler.update(); // Sufficient node check-ins to fully schedule containers for (int i = 0; i < 2; i++) { NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeUpdate1); NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2); scheduler.handle(nodeUpdate2); NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3); scheduler.handle(nodeUpdate3); } // Now new requests arrive from queues C and D ApplicationAttemptId app7 = createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1); ApplicationAttemptId app8 = createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2); ApplicationAttemptId app9 = createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3); ApplicationAttemptId app10 = createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 1); ApplicationAttemptId app11 = createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 2); ApplicationAttemptId app12 = createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 3); scheduler.update(); FSLeafQueue schedC = scheduler.getQueueManager().getLeafQueue("queueC", true); FSLeafQueue schedD = scheduler.getQueueManager().getLeafQueue("queueD", true); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(schedC, clock.getTime()))); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(schedD, clock.getTime()))); // Test : // 1) whether componentWise min works as expected. // 2) DRF calculator is used // After minSharePreemptionTime has passed, they should want to preempt min // share. clock.tickSec(6); Resource res = scheduler.resourceDeficit(schedC, clock.getTime()); assertEquals(1024, res.getMemory()); // Demand = 3 assertEquals(3, res.getVirtualCores()); res = scheduler.resourceDeficit(schedD, clock.getTime()); assertEquals(1024, res.getMemory()); // Demand = 6, but min share = 2 assertEquals(2, res.getVirtualCores()); // After fairSharePreemptionTime has passed, they should want to preempt // fair share. scheduler.update(); clock.tickSec(6); res = scheduler.resourceDeficit(schedC, clock.getTime()); assertEquals(1536, res.getMemory()); assertEquals(3, res.getVirtualCores()); res = scheduler.resourceDeficit(schedD, clock.getTime()); assertEquals(1536, res.getMemory()); // Demand = 6, but fair share = 3 assertEquals(3, res.getVirtualCores()); } @Test /** * Tests the various timing of decision to preempt tasks. */ public void testPreemptionDecisionWithVariousTimeout() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"default\">"); out.println("<maxResources>0mb,0vcores</maxResources>"); out.println("</queue>"); out.println("<queue name=\"queueA\">"); out.println("<weight>1</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>2</weight>"); out.println("<minSharePreemptionTimeout>10</minSharePreemptionTimeout>"); out.println("<fairSharePreemptionTimeout>25</fairSharePreemptionTimeout>"); out.println("<queue name=\"queueB1\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>"); out.println("</queue>"); out.println("<queue name=\"queueB2\">"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("<fairSharePreemptionTimeout>20</fairSharePreemptionTimeout>"); out.println("</queue>"); out.println("</queue>"); out.println("<queue name=\"queueC\">"); out.println("<weight>1</weight>"); out.println("<minResources>1024mb,0vcores</minResources>"); out.println("</queue>"); out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>"); out.print("<defaultFairSharePreemptionTimeout>30</defaultFairSharePreemptionTimeout>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Check the min/fair share preemption timeout for each queue QueueManager queueMgr = scheduler.getQueueManager(); assertEquals(30000, queueMgr.getQueue("root") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("default") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueA") .getFairSharePreemptionTimeout()); assertEquals(25000, queueMgr.getQueue("queueB") .getFairSharePreemptionTimeout()); assertEquals(25000, queueMgr.getQueue("queueB.queueB1") .getFairSharePreemptionTimeout()); assertEquals(20000, queueMgr.getQueue("queueB.queueB2") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueC") .getFairSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("root") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("default") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("queueA") .getMinSharePreemptionTimeout()); assertEquals(10000, queueMgr.getQueue("queueB") .getMinSharePreemptionTimeout()); assertEquals(5000, queueMgr.getQueue("queueB.queueB1") .getMinSharePreemptionTimeout()); assertEquals(10000, queueMgr.getQueue("queueB.queueB2") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("queueC") .getMinSharePreemptionTimeout()); // Create one big node RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(6 * 1024, 6), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Queue A takes all resources for (int i = 0; i < 6; i ++) { createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1); } scheduler.update(); // Sufficient node check-ins to fully schedule containers NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1); for (int i = 0; i < 6; i++) { scheduler.handle(nodeUpdate1); } // Now new requests arrive from queues B1, B2 and C createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 1); createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 2); createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 3); createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 1); createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 2); createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 3); createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1); createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2); createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3); scheduler.update(); FSLeafQueue queueB1 = queueMgr.getLeafQueue("queueB.queueB1", true); FSLeafQueue queueB2 = queueMgr.getLeafQueue("queueB.queueB2", true); FSLeafQueue queueC = queueMgr.getLeafQueue("queueC", true); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(queueB1, clock.getTime()))); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(queueB2, clock.getTime()))); assertTrue(Resources.equals( Resources.none(), scheduler.resourceDeficit(queueC, clock.getTime()))); // After 5 seconds, queueB1 wants to preempt min share scheduler.update(); clock.tickSec(6); assertEquals( 1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory()); assertEquals( 0, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory()); assertEquals( 0, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory()); // After 10 seconds, queueB2 wants to preempt min share scheduler.update(); clock.tickSec(5); assertEquals( 1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory()); assertEquals( 1024, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory()); assertEquals( 0, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory()); // After 15 seconds, queueC wants to preempt min share scheduler.update(); clock.tickSec(5); assertEquals( 1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory()); assertEquals( 1024, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory()); assertEquals( 1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory()); // After 20 seconds, queueB2 should want to preempt fair share scheduler.update(); clock.tickSec(5); assertEquals( 1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory()); assertEquals( 1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory()); assertEquals( 1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory()); // After 25 seconds, queueB1 should want to preempt fair share scheduler.update(); clock.tickSec(5); assertEquals( 1536, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory()); assertEquals( 1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory()); assertEquals( 1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory()); // After 30 seconds, queueC should want to preempt fair share scheduler.update(); clock.tickSec(5); assertEquals( 1536, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory()); assertEquals( 1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory()); assertEquals( 1536, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory()); } @Test public void testBackwardsCompatiblePreemptionConfiguration() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"default\">"); out.println("</queue>"); out.println("<queue name=\"queueA\">"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<queue name=\"queueB1\">"); out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>"); out.println("</queue>"); out.println("<queue name=\"queueB2\">"); out.println("</queue>"); out.println("</queue>"); out.println("<queue name=\"queueC\">"); out.println("</queue>"); out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>"); out.print("<defaultFairSharePreemptionTimeout>30</defaultFairSharePreemptionTimeout>"); out.print("<fairSharePreemptionTimeout>40</fairSharePreemptionTimeout>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Check the min/fair share preemption timeout for each queue QueueManager queueMgr = scheduler.getQueueManager(); assertEquals(30000, queueMgr.getQueue("root") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("default") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueA") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueB") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueB.queueB1") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueB.queueB2") .getFairSharePreemptionTimeout()); assertEquals(30000, queueMgr.getQueue("queueC") .getFairSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("root") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("default") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("queueA") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("queueB") .getMinSharePreemptionTimeout()); assertEquals(5000, queueMgr.getQueue("queueB.queueB1") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("queueB.queueB2") .getMinSharePreemptionTimeout()); assertEquals(15000, queueMgr.getQueue("queueC") .getMinSharePreemptionTimeout()); // If both exist, we take the default one out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"default\">"); out.println("</queue>"); out.println("<queue name=\"queueA\">"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<queue name=\"queueB1\">"); out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>"); out.println("</queue>"); out.println("<queue name=\"queueB2\">"); out.println("</queue>"); out.println("</queue>"); out.println("<queue name=\"queueC\">"); out.println("</queue>"); out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>"); out.print("<defaultFairSharePreemptionTimeout>25</defaultFairSharePreemptionTimeout>"); out.print("<fairSharePreemptionTimeout>30</fairSharePreemptionTimeout>"); out.println("</allocations>"); out.close(); scheduler.reinitialize(conf, resourceManager.getRMContext()); assertEquals(25000, queueMgr.getQueue("root") .getFairSharePreemptionTimeout()); } @Test(timeout = 5000) public void testMultipleContainersWaitingForReservation() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Request full capacity of node createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue2", "user2", 1); ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue3", "user3", 1); scheduler.update(); scheduler.handle(updateEvent); // One container should get reservation and the other should get nothing assertEquals(1024, scheduler.getSchedulerApp(attId1).getCurrentReservation().getMemory()); assertEquals(0, scheduler.getSchedulerApp(attId2).getCurrentReservation().getMemory()); } @Test (timeout = 5000) public void testUserMaxRunningApps() throws Exception { // Set max running apps conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<user name=\"user1\">"); out.println("<maxRunningApps>1</maxRunningApps>"); out.println("</user>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(8192, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Request for app 1 ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // App 1 should be running assertEquals(1, scheduler.getSchedulerApp(attId1).getLiveContainers().size()); ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // App 2 should not be running assertEquals(0, scheduler.getSchedulerApp(attId2).getLiveContainers().size()); // Request another container for app 1 createSchedulingRequestExistingApplication(1024, 1, attId1); scheduler.update(); scheduler.handle(updateEvent); // Request should be fulfilled assertEquals(2, scheduler.getSchedulerApp(attId1).getLiveContainers().size()); } @Test (timeout = 5000) public void testIncreaseQueueMaxRunningAppsOnTheFly() throws Exception { String allocBefore = "<?xml version=\"1.0\"?>" + "<allocations>" + "<queue name=\"root\">" + "<queue name=\"queue1\">" + "<maxRunningApps>1</maxRunningApps>" + "</queue>" + "</queue>" + "</allocations>"; String allocAfter = "<?xml version=\"1.0\"?>" + "<allocations>" + "<queue name=\"root\">" + "<queue name=\"queue1\">" + "<maxRunningApps>3</maxRunningApps>" + "</queue>" + "</queue>" + "</allocations>"; testIncreaseQueueSettingOnTheFlyInternal(allocBefore, allocAfter); } @Test (timeout = 5000) public void testIncreaseUserMaxRunningAppsOnTheFly() throws Exception { String allocBefore = "<?xml version=\"1.0\"?>"+ "<allocations>"+ "<queue name=\"root\">"+ "<queue name=\"queue1\">"+ "<maxRunningApps>10</maxRunningApps>"+ "</queue>"+ "</queue>"+ "<user name=\"user1\">"+ "<maxRunningApps>1</maxRunningApps>"+ "</user>"+ "</allocations>"; String allocAfter = "<?xml version=\"1.0\"?>"+ "<allocations>"+ "<queue name=\"root\">"+ "<queue name=\"queue1\">"+ "<maxRunningApps>10</maxRunningApps>"+ "</queue>"+ "</queue>"+ "<user name=\"user1\">"+ "<maxRunningApps>3</maxRunningApps>"+ "</user>"+ "</allocations>"; testIncreaseQueueSettingOnTheFlyInternal(allocBefore, allocAfter); } private void testIncreaseQueueSettingOnTheFlyInternal(String allocBefore, String allocAfter) throws Exception { // Set max running apps conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println(allocBefore); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(8192, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Request for app 1 ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // App 1 should be running assertEquals(1, scheduler.getSchedulerApp(attId1).getLiveContainers().size()); ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); ApplicationAttemptId attId3 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); ApplicationAttemptId attId4 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // App 2 should not be running assertEquals(0, scheduler.getSchedulerApp(attId2).getLiveContainers().size()); // App 3 should not be running assertEquals(0, scheduler.getSchedulerApp(attId3).getLiveContainers().size()); // App 4 should not be running assertEquals(0, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println(allocAfter); out.close(); scheduler.reinitialize(conf, resourceManager.getRMContext()); scheduler.update(); scheduler.handle(updateEvent); // App 2 should be running assertEquals(1, scheduler.getSchedulerApp(attId2).getLiveContainers().size()); scheduler.update(); scheduler.handle(updateEvent); // App 3 should be running assertEquals(1, scheduler.getSchedulerApp(attId3).getLiveContainers().size()); scheduler.update(); scheduler.handle(updateEvent); // App 4 should not be running assertEquals(0, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); // Now remove app 1 AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent( attId1, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); scheduler.update(); scheduler.handle(updateEvent); // App 4 should be running assertEquals(1, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); } @Test (timeout = 5000) public void testDecreaseQueueMaxRunningAppsOnTheFly() throws Exception { String allocBefore = "<?xml version=\"1.0\"?>" + "<allocations>" + "<queue name=\"root\">" + "<queue name=\"queue1\">" + "<maxRunningApps>3</maxRunningApps>" + "</queue>" + "</queue>" + "</allocations>"; String allocAfter = "<?xml version=\"1.0\"?>" + "<allocations>" + "<queue name=\"root\">" + "<queue name=\"queue1\">" + "<maxRunningApps>1</maxRunningApps>" + "</queue>" + "</queue>" + "</allocations>"; testDecreaseQueueSettingOnTheFlyInternal(allocBefore, allocAfter); } @Test (timeout = 5000) public void testDecreaseUserMaxRunningAppsOnTheFly() throws Exception { String allocBefore = "<?xml version=\"1.0\"?>"+ "<allocations>"+ "<queue name=\"root\">"+ "<queue name=\"queue1\">"+ "<maxRunningApps>10</maxRunningApps>"+ "</queue>"+ "</queue>"+ "<user name=\"user1\">"+ "<maxRunningApps>3</maxRunningApps>"+ "</user>"+ "</allocations>"; String allocAfter = "<?xml version=\"1.0\"?>"+ "<allocations>"+ "<queue name=\"root\">"+ "<queue name=\"queue1\">"+ "<maxRunningApps>10</maxRunningApps>"+ "</queue>"+ "</queue>"+ "<user name=\"user1\">"+ "<maxRunningApps>1</maxRunningApps>"+ "</user>"+ "</allocations>"; testDecreaseQueueSettingOnTheFlyInternal(allocBefore, allocAfter); } private void testDecreaseQueueSettingOnTheFlyInternal(String allocBefore, String allocAfter) throws Exception { // Set max running apps conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println(allocBefore); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(8192, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Request for app 1 ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); // App 1 should be running assertEquals(1, scheduler.getSchedulerApp(attId1).getLiveContainers().size()); ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); ApplicationAttemptId attId3 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); ApplicationAttemptId attId4 = createSchedulingRequest(1024, "queue1", "user1", 1); scheduler.update(); scheduler.handle(updateEvent); // App 2 should be running assertEquals(1, scheduler.getSchedulerApp(attId2).getLiveContainers().size()); // App 3 should be running assertEquals(1, scheduler.getSchedulerApp(attId3).getLiveContainers().size()); // App 4 should not be running assertEquals(0, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println(allocAfter); out.close(); scheduler.reinitialize(conf, resourceManager.getRMContext()); scheduler.update(); scheduler.handle(updateEvent); // App 2 should still be running assertEquals(1, scheduler.getSchedulerApp(attId2).getLiveContainers().size()); scheduler.update(); scheduler.handle(updateEvent); // App 3 should still be running assertEquals(1, scheduler.getSchedulerApp(attId3).getLiveContainers().size()); scheduler.update(); scheduler.handle(updateEvent); // App 4 should not be running assertEquals(0, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); // Now remove app 1 AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent( attId1, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); scheduler.update(); scheduler.handle(updateEvent); // App 4 should not be running assertEquals(0, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); // Now remove app 2 appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent( attId2, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); scheduler.update(); scheduler.handle(updateEvent); // App 4 should not be running assertEquals(0, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); // Now remove app 3 appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent( attId3, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); scheduler.update(); scheduler.handle(updateEvent); // App 4 should be running now assertEquals(1, scheduler.getSchedulerApp(attId4).getLiveContainers().size()); } @Test (timeout = 5000) public void testReservationWhileMultiplePriorities() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // Add a node RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(1024, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); ApplicationAttemptId attId = createSchedulingRequest(1024, 4, "queue1", "user1", 1, 2); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); FSAppAttempt app = scheduler.getSchedulerApp(attId); assertEquals(1, app.getLiveContainers().size()); ContainerId containerId = scheduler.getSchedulerApp(attId) .getLiveContainers().iterator().next().getContainerId(); // Cause reservation to be created createSchedulingRequestExistingApplication(1024, 4, 2, attId); scheduler.update(); scheduler.handle(updateEvent); assertEquals(1, app.getLiveContainers().size()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); // Create request at higher priority createSchedulingRequestExistingApplication(1024, 4, 1, attId); scheduler.update(); scheduler.handle(updateEvent); assertEquals(1, app.getLiveContainers().size()); // Reserved container should still be at lower priority for (RMContainer container : app.getReservedContainers()) { assertEquals(2, container.getReservedPriority().getPriority()); } // Complete container scheduler.allocate(attId, new ArrayList<ResourceRequest>(), Arrays.asList(containerId), null, null); assertEquals(1024, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(4, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); // Schedule at opening scheduler.update(); scheduler.handle(updateEvent); // Reserved container (at lower priority) should be run Collection<RMContainer> liveContainers = app.getLiveContainers(); assertEquals(1, liveContainers.size()); for (RMContainer liveContainer : liveContainers) { Assert.assertEquals(2, liveContainer.getContainer().getPriority() .getPriority()); } assertEquals(0, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); } @Test public void testAclSubmitApplication() throws Exception { // Set acl's conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println(" <aclSubmitApps> </aclSubmitApps>"); out.println(" <aclAdministerApps> </aclAdministerApps>"); out.println(" <queue name=\"queue1\">"); out.println(" <aclSubmitApps>norealuserhasthisname</aclSubmitApps>"); out.println(" <aclAdministerApps>norealuserhasthisname</aclAdministerApps>"); out.println(" </queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "norealuserhasthisname", 1); ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue1", "norealuserhasthisname2", 1); FSAppAttempt app1 = scheduler.getSchedulerApp(attId1); assertNotNull("The application was not allowed", app1); FSAppAttempt app2 = scheduler.getSchedulerApp(attId2); assertNull("The application was allowed", app2); } @Test (timeout = 5000) public void testMultipleNodesSingleRackRequest() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); RMNode node2 = MockNodes .newNodeInfo(1, Resources.createResource(1024), 2, "127.0.0.2"); RMNode node3 = MockNodes .newNodeInfo(2, Resources.createResource(1024), 3, "127.0.0.3"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); ApplicationAttemptId attemptId = createAppAttemptId(this.APP_ID++, this.ATTEMPT_ID++); createMockRMApp(attemptId); scheduler.addApplication(attemptId.getApplicationId(), "queue1", "user1", false); scheduler.addApplicationAttempt(attemptId, false, false); // 1 request with 2 nodes on the same rack. another request with 1 node on // a different rack List<ResourceRequest> asks = new ArrayList<ResourceRequest>(); asks.add(createResourceRequest(1024, node1.getHostName(), 1, 1, true)); asks.add(createResourceRequest(1024, node2.getHostName(), 1, 1, true)); asks.add(createResourceRequest(1024, node3.getHostName(), 1, 1, true)); asks.add(createResourceRequest(1024, node1.getRackName(), 1, 1, true)); asks.add(createResourceRequest(1024, node3.getRackName(), 1, 1, true)); asks.add(createResourceRequest(1024, ResourceRequest.ANY, 1, 2, true)); scheduler.allocate(attemptId, asks, new ArrayList<ContainerId>(), null, null); // node 1 checks in scheduler.update(); NodeUpdateSchedulerEvent updateEvent1 = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent1); // should assign node local assertEquals(1, scheduler.getSchedulerApp(attemptId).getLiveContainers() .size()); // node 2 checks in scheduler.update(); NodeUpdateSchedulerEvent updateEvent2 = new NodeUpdateSchedulerEvent(node2); scheduler.handle(updateEvent2); // should assign rack local assertEquals(2, scheduler.getSchedulerApp(attemptId).getLiveContainers() .size()); } @Test (timeout = 5000) public void testFifoWithinQueue() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(3072, 3), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); // Even if submitted at exact same time, apps will be deterministically // ordered by name. ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 2); ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue1", "user1", 2); FSAppAttempt app1 = scheduler.getSchedulerApp(attId1); FSAppAttempt app2 = scheduler.getSchedulerApp(attId2); FSLeafQueue queue1 = scheduler.getQueueManager().getLeafQueue("queue1", true); queue1.setPolicy(new FifoPolicy()); scheduler.update(); // First two containers should go to app 1, third should go to app 2. // Because tests set assignmultiple to false, each heartbeat assigns a single // container. NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); assertEquals(1, app1.getLiveContainers().size()); assertEquals(0, app2.getLiveContainers().size()); scheduler.handle(updateEvent); assertEquals(2, app1.getLiveContainers().size()); assertEquals(0, app2.getLiveContainers().size()); scheduler.handle(updateEvent); assertEquals(2, app1.getLiveContainers().size()); assertEquals(1, app2.getLiveContainers().size()); } @Test(timeout = 3000) public void testMaxAssign() throws Exception { conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, true); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(16384, 16), 0, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); ApplicationAttemptId attId = createSchedulingRequest(1024, "root.default", "user", 8); FSAppAttempt app = scheduler.getSchedulerApp(attId); // set maxAssign to 2: only 2 containers should be allocated scheduler.maxAssign = 2; scheduler.update(); scheduler.handle(updateEvent); assertEquals("Incorrect number of containers allocated", 2, app .getLiveContainers().size()); // set maxAssign to -1: all remaining containers should be allocated scheduler.maxAssign = -1; scheduler.update(); scheduler.handle(updateEvent); assertEquals("Incorrect number of containers allocated", 8, app .getLiveContainers().size()); } @Test(timeout = 3000) public void testMaxAssignWithZeroMemoryContainers() throws Exception { conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, true); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(16384, 16), 0, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); ApplicationAttemptId attId = createSchedulingRequest(0, 1, "root.default", "user", 8); FSAppAttempt app = scheduler.getSchedulerApp(attId); // set maxAssign to 2: only 2 containers should be allocated scheduler.maxAssign = 2; scheduler.update(); scheduler.handle(updateEvent); assertEquals("Incorrect number of containers allocated", 2, app .getLiveContainers().size()); // set maxAssign to -1: all remaining containers should be allocated scheduler.maxAssign = -1; scheduler.update(); scheduler.handle(updateEvent); assertEquals("Incorrect number of containers allocated", 8, app .getLiveContainers().size()); } /** * Test to verify the behavior of * {@link FSQueue#assignContainer(FSSchedulerNode)}) * * Create two queues under root (fifoQueue and fairParent), and two queues * under fairParent (fairChild1 and fairChild2). Submit two apps to the * fifoQueue and one each to the fairChild* queues, all apps requiring 4 * containers each of the total 16 container capacity * * Assert the number of containers for each app after 4, 8, 12 and 16 updates. * * @throws Exception */ @Test(timeout = 5000) public void testAssignContainer() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); final String user = "user1"; final String fifoQueue = "fifo"; final String fairParent = "fairParent"; final String fairChild1 = fairParent + ".fairChild1"; final String fairChild2 = fairParent + ".fairChild2"; RMNode node1 = MockNodes .newNodeInfo(1, Resources.createResource(8192, 8), 1, "127.0.0.1"); RMNode node2 = MockNodes .newNodeInfo(1, Resources.createResource(8192, 8), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent1); scheduler.handle(nodeEvent2); ApplicationAttemptId attId1 = createSchedulingRequest(1024, fifoQueue, user, 4); ApplicationAttemptId attId2 = createSchedulingRequest(1024, fairChild1, user, 4); ApplicationAttemptId attId3 = createSchedulingRequest(1024, fairChild2, user, 4); ApplicationAttemptId attId4 = createSchedulingRequest(1024, fifoQueue, user, 4); FSAppAttempt app1 = scheduler.getSchedulerApp(attId1); FSAppAttempt app2 = scheduler.getSchedulerApp(attId2); FSAppAttempt app3 = scheduler.getSchedulerApp(attId3); FSAppAttempt app4 = scheduler.getSchedulerApp(attId4); scheduler.getQueueManager().getLeafQueue(fifoQueue, true) .setPolicy(SchedulingPolicy.parse("fifo")); scheduler.update(); NodeUpdateSchedulerEvent updateEvent1 = new NodeUpdateSchedulerEvent(node1); NodeUpdateSchedulerEvent updateEvent2 = new NodeUpdateSchedulerEvent(node2); for (int i = 0; i < 8; i++) { scheduler.handle(updateEvent1); scheduler.handle(updateEvent2); if ((i + 1) % 2 == 0) { // 4 node updates: fifoQueue should have received 2, and fairChild* // should have received one each String ERR = "Wrong number of assigned containers after " + (i + 1) + " updates"; if (i < 4) { // app1 req still not met assertEquals(ERR, (i + 1), app1.getLiveContainers().size()); assertEquals(ERR, 0, app4.getLiveContainers().size()); } else { // app1 req has been met, app4 should be served now assertEquals(ERR, 4, app1.getLiveContainers().size()); assertEquals(ERR, (i - 3), app4.getLiveContainers().size()); } assertEquals(ERR, (i + 1) / 2, app2.getLiveContainers().size()); assertEquals(ERR, (i + 1) / 2, app3.getLiveContainers().size()); } } } @SuppressWarnings("unchecked") @Test public void testNotAllowSubmitApplication() throws Exception { // Set acl's conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\">"); out.println(" <aclSubmitApps> </aclSubmitApps>"); out.println(" <aclAdministerApps> </aclAdministerApps>"); out.println(" <queue name=\"queue1\">"); out.println(" <aclSubmitApps>userallow</aclSubmitApps>"); out.println(" <aclAdministerApps>userallow</aclAdministerApps>"); out.println(" </queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); int appId = this.APP_ID++; String user = "usernotallow"; String queue = "queue1"; ApplicationId applicationId = MockApps.newAppID(appId); String name = MockApps.newAppName(); ApplicationMasterService masterService = new ApplicationMasterService(resourceManager.getRMContext(), scheduler); ApplicationSubmissionContext submissionContext = new ApplicationSubmissionContextPBImpl(); ContainerLaunchContext clc = BuilderUtils.newContainerLaunchContext(null, null, null, null, null, null); submissionContext.setApplicationId(applicationId); submissionContext.setAMContainerSpec(clc); RMApp application = new RMAppImpl(applicationId, resourceManager.getRMContext(), conf, name, user, queue, submissionContext, scheduler, masterService, System.currentTimeMillis(), "YARN", null, null); resourceManager.getRMContext().getRMApps().putIfAbsent(applicationId, application); application.handle(new RMAppEvent(applicationId, RMAppEventType.START)); final int MAX_TRIES=20; int numTries = 0; while (!application.getState().equals(RMAppState.SUBMITTED) && numTries < MAX_TRIES) { try { Thread.sleep(100); } catch (InterruptedException ex) {ex.printStackTrace();} numTries++; } assertEquals("The application doesn't reach SUBMITTED.", RMAppState.SUBMITTED, application.getState()); ApplicationAttemptId attId = ApplicationAttemptId.newInstance(applicationId, this.ATTEMPT_ID++); scheduler.addApplication(attId.getApplicationId(), queue, user, false); numTries = 0; while (application.getFinishTime() == 0 && numTries < MAX_TRIES) { try { Thread.sleep(100); } catch (InterruptedException ex) {ex.printStackTrace();} numTries++; } assertEquals(FinalApplicationStatus.FAILED, application.getFinalApplicationStatus()); } @Test public void testRemoveNodeUpdatesRootQueueMetrics() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(1024, 4), 1, "127.0.0.1"); NodeAddedSchedulerEvent addEvent = new NodeAddedSchedulerEvent(node1); scheduler.handle(addEvent); assertEquals(1024, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(4, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); scheduler.update(); // update shouldn't change things assertEquals(1024, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(4, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); NodeRemovedSchedulerEvent removeEvent = new NodeRemovedSchedulerEvent(node1); scheduler.handle(removeEvent); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); scheduler.update(); // update shouldn't change things assertEquals(0, scheduler.getRootQueueMetrics().getAvailableMB()); assertEquals(0, scheduler.getRootQueueMetrics().getAvailableVirtualCores()); } @Test public void testStrictLocality() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 0); ResourceRequest nodeRequest = createResourceRequest(1024, node1.getHostName(), 1, 1, true); ResourceRequest rackRequest = createResourceRequest(1024, node1.getRackName(), 1, 1, false); ResourceRequest anyRequest = createResourceRequest(1024, ResourceRequest.ANY, 1, 1, false); createSchedulingRequestExistingApplication(nodeRequest, attId1); createSchedulingRequestExistingApplication(rackRequest, attId1); createSchedulingRequestExistingApplication(anyRequest, attId1); scheduler.update(); NodeUpdateSchedulerEvent node1UpdateEvent = new NodeUpdateSchedulerEvent(node1); NodeUpdateSchedulerEvent node2UpdateEvent = new NodeUpdateSchedulerEvent(node2); // no matter how many heartbeats, node2 should never get a container FSAppAttempt app = scheduler.getSchedulerApp(attId1); for (int i = 0; i < 10; i++) { scheduler.handle(node2UpdateEvent); assertEquals(0, app.getLiveContainers().size()); assertEquals(0, app.getReservedContainers().size()); } // then node1 should get the container scheduler.handle(node1UpdateEvent); assertEquals(1, app.getLiveContainers().size()); } @Test public void testCancelStrictLocality() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 0); ResourceRequest nodeRequest = createResourceRequest(1024, node1.getHostName(), 1, 1, true); ResourceRequest rackRequest = createResourceRequest(1024, "rack1", 1, 1, false); ResourceRequest anyRequest = createResourceRequest(1024, ResourceRequest.ANY, 1, 1, false); createSchedulingRequestExistingApplication(nodeRequest, attId1); createSchedulingRequestExistingApplication(rackRequest, attId1); createSchedulingRequestExistingApplication(anyRequest, attId1); scheduler.update(); NodeUpdateSchedulerEvent node2UpdateEvent = new NodeUpdateSchedulerEvent(node2); // no matter how many heartbeats, node2 should never get a container FSAppAttempt app = scheduler.getSchedulerApp(attId1); for (int i = 0; i < 10; i++) { scheduler.handle(node2UpdateEvent); assertEquals(0, app.getLiveContainers().size()); } // relax locality List<ResourceRequest> update = Arrays.asList( createResourceRequest(1024, node1.getHostName(), 1, 0, true), createResourceRequest(1024, "rack1", 1, 0, true), createResourceRequest(1024, ResourceRequest.ANY, 1, 1, true)); scheduler.allocate(attId1, update, new ArrayList<ContainerId>(), null, null); // then node2 should get the container scheduler.handle(node2UpdateEvent); assertEquals(1, app.getLiveContainers().size()); } /** * If we update our ask to strictly request a node, it doesn't make sense to keep * a reservation on another. */ @Test public void testReservationsStrictLocality() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1"); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent2); ApplicationAttemptId attId = createSchedulingRequest(1024, "queue1", "user1", 0); FSAppAttempt app = scheduler.getSchedulerApp(attId); ResourceRequest nodeRequest = createResourceRequest(1024, node2.getHostName(), 1, 2, true); ResourceRequest rackRequest = createResourceRequest(1024, "rack1", 1, 2, true); ResourceRequest anyRequest = createResourceRequest(1024, ResourceRequest.ANY, 1, 2, false); createSchedulingRequestExistingApplication(nodeRequest, attId); createSchedulingRequestExistingApplication(rackRequest, attId); createSchedulingRequestExistingApplication(anyRequest, attId); scheduler.update(); NodeUpdateSchedulerEvent nodeUpdateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(nodeUpdateEvent); assertEquals(1, app.getLiveContainers().size()); scheduler.handle(nodeUpdateEvent); assertEquals(1, app.getReservedContainers().size()); // now, make our request node-specific (on a different node) rackRequest = createResourceRequest(1024, "rack1", 1, 1, false); anyRequest = createResourceRequest(1024, ResourceRequest.ANY, 1, 1, false); scheduler.allocate(attId, Arrays.asList(rackRequest, anyRequest), new ArrayList<ContainerId>(), null, null); scheduler.handle(nodeUpdateEvent); assertEquals(0, app.getReservedContainers().size()); } @Test public void testNoMoreCpuOnNode() throws IOException { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(2048, 1), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); ApplicationAttemptId attId = createSchedulingRequest(1024, 1, "default", "user1", 2); FSAppAttempt app = scheduler.getSchedulerApp(attId); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node1); scheduler.handle(updateEvent); assertEquals(1, app.getLiveContainers().size()); scheduler.handle(updateEvent); assertEquals(1, app.getLiveContainers().size()); } @Test public void testBasicDRFAssignment() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, BuilderUtils.newResource(8192, 5)); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); scheduler.handle(nodeEvent); ApplicationAttemptId appAttId1 = createSchedulingRequest(2048, 1, "queue1", "user1", 2); FSAppAttempt app1 = scheduler.getSchedulerApp(appAttId1); ApplicationAttemptId appAttId2 = createSchedulingRequest(1024, 2, "queue1", "user1", 2); FSAppAttempt app2 = scheduler.getSchedulerApp(appAttId2); DominantResourceFairnessPolicy drfPolicy = new DominantResourceFairnessPolicy(); drfPolicy.initialize(scheduler.getClusterResource()); scheduler.getQueueManager().getQueue("queue1").setPolicy(drfPolicy); scheduler.update(); // First both apps get a container // Then the first gets another container because its dominant share of // 2048/8192 is less than the other's of 2/5 NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(updateEvent); Assert.assertEquals(1, app1.getLiveContainers().size()); Assert.assertEquals(0, app2.getLiveContainers().size()); scheduler.handle(updateEvent); Assert.assertEquals(1, app1.getLiveContainers().size()); Assert.assertEquals(1, app2.getLiveContainers().size()); scheduler.handle(updateEvent); Assert.assertEquals(2, app1.getLiveContainers().size()); Assert.assertEquals(1, app2.getLiveContainers().size()); } /** * Two apps on one queue, one app on another */ @Test public void testBasicDRFWithQueues() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, BuilderUtils.newResource(8192, 7), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); scheduler.handle(nodeEvent); ApplicationAttemptId appAttId1 = createSchedulingRequest(3072, 1, "queue1", "user1", 2); FSAppAttempt app1 = scheduler.getSchedulerApp(appAttId1); ApplicationAttemptId appAttId2 = createSchedulingRequest(2048, 2, "queue1", "user1", 2); FSAppAttempt app2 = scheduler.getSchedulerApp(appAttId2); ApplicationAttemptId appAttId3 = createSchedulingRequest(1024, 2, "queue2", "user1", 2); FSAppAttempt app3 = scheduler.getSchedulerApp(appAttId3); DominantResourceFairnessPolicy drfPolicy = new DominantResourceFairnessPolicy(); drfPolicy.initialize(scheduler.getClusterResource()); scheduler.getQueueManager().getQueue("root").setPolicy(drfPolicy); scheduler.getQueueManager().getQueue("queue1").setPolicy(drfPolicy); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(updateEvent); Assert.assertEquals(1, app1.getLiveContainers().size()); scheduler.handle(updateEvent); Assert.assertEquals(1, app3.getLiveContainers().size()); scheduler.handle(updateEvent); Assert.assertEquals(2, app3.getLiveContainers().size()); scheduler.handle(updateEvent); Assert.assertEquals(1, app2.getLiveContainers().size()); } @Test public void testDRFHierarchicalQueues() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, BuilderUtils.newResource(12288, 12), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); scheduler.handle(nodeEvent); ApplicationAttemptId appAttId1 = createSchedulingRequest(3074, 1, "queue1.subqueue1", "user1", 2); Thread.sleep(3); // so that start times will be different FSAppAttempt app1 = scheduler.getSchedulerApp(appAttId1); ApplicationAttemptId appAttId2 = createSchedulingRequest(1024, 3, "queue1.subqueue1", "user1", 2); Thread.sleep(3); // so that start times will be different FSAppAttempt app2 = scheduler.getSchedulerApp(appAttId2); ApplicationAttemptId appAttId3 = createSchedulingRequest(2048, 2, "queue1.subqueue2", "user1", 2); Thread.sleep(3); // so that start times will be different FSAppAttempt app3 = scheduler.getSchedulerApp(appAttId3); ApplicationAttemptId appAttId4 = createSchedulingRequest(1024, 2, "queue2", "user1", 2); Thread.sleep(3); // so that start times will be different FSAppAttempt app4 = scheduler.getSchedulerApp(appAttId4); DominantResourceFairnessPolicy drfPolicy = new DominantResourceFairnessPolicy(); drfPolicy.initialize(scheduler.getClusterResource()); scheduler.getQueueManager().getQueue("root").setPolicy(drfPolicy); scheduler.getQueueManager().getQueue("queue1").setPolicy(drfPolicy); scheduler.getQueueManager().getQueue("queue1.subqueue1").setPolicy(drfPolicy); scheduler.update(); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(updateEvent); // app1 gets first container because it asked first Assert.assertEquals(1, app1.getLiveContainers().size()); scheduler.handle(updateEvent); // app4 gets second container because it's on queue2 Assert.assertEquals(1, app4.getLiveContainers().size()); scheduler.handle(updateEvent); // app4 gets another container because queue2's dominant share of memory // is still less than queue1's of cpu Assert.assertEquals(2, app4.getLiveContainers().size()); scheduler.handle(updateEvent); // app3 gets one because queue1 gets one and queue1.subqueue2 is behind // queue1.subqueue1 Assert.assertEquals(1, app3.getLiveContainers().size()); scheduler.handle(updateEvent); // app4 would get another one, but it doesn't have any requests // queue1.subqueue2 is still using less than queue1.subqueue1, so it // gets another Assert.assertEquals(2, app3.getLiveContainers().size()); // queue1.subqueue1 is behind again, so it gets one, which it gives to app2 scheduler.handle(updateEvent); Assert.assertEquals(1, app2.getLiveContainers().size()); // at this point, we've used all our CPU up, so nobody else should get a container scheduler.handle(updateEvent); Assert.assertEquals(1, app1.getLiveContainers().size()); Assert.assertEquals(1, app2.getLiveContainers().size()); Assert.assertEquals(2, app3.getLiveContainers().size()); Assert.assertEquals(2, app4.getLiveContainers().size()); } @Test(timeout = 30000) public void testHostPortNodeName() throws Exception { conf.setBoolean(YarnConfiguration .RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME, true); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 1, "127.0.0.1", 1); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(1024), 2, "127.0.0.1", 2); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1", 0); ResourceRequest nodeRequest = createResourceRequest(1024, node1.getNodeID().getHost() + ":" + node1.getNodeID().getPort(), 1, 1, true); ResourceRequest rackRequest = createResourceRequest(1024, node1.getRackName(), 1, 1, false); ResourceRequest anyRequest = createResourceRequest(1024, ResourceRequest.ANY, 1, 1, false); createSchedulingRequestExistingApplication(nodeRequest, attId1); createSchedulingRequestExistingApplication(rackRequest, attId1); createSchedulingRequestExistingApplication(anyRequest, attId1); scheduler.update(); NodeUpdateSchedulerEvent node1UpdateEvent = new NodeUpdateSchedulerEvent(node1); NodeUpdateSchedulerEvent node2UpdateEvent = new NodeUpdateSchedulerEvent(node2); // no matter how many heartbeats, node2 should never get a container FSAppAttempt app = scheduler.getSchedulerApp(attId1); for (int i = 0; i < 10; i++) { scheduler.handle(node2UpdateEvent); assertEquals(0, app.getLiveContainers().size()); assertEquals(0, app.getReservedContainers().size()); } // then node1 should get the container scheduler.handle(node1UpdateEvent); assertEquals(1, app.getLiveContainers().size()); } private void verifyAppRunnable(ApplicationAttemptId attId, boolean runnable) { FSAppAttempt app = scheduler.getSchedulerApp(attId); FSLeafQueue queue = app.getQueue(); assertEquals(runnable, queue.isRunnableApp(app)); assertEquals(!runnable, queue.isNonRunnableApp(app)); } private void verifyQueueNumRunnable(String queueName, int numRunnableInQueue, int numNonRunnableInQueue) { FSLeafQueue queue = scheduler.getQueueManager().getLeafQueue(queueName, false); assertEquals(numRunnableInQueue, queue.getNumRunnableApps()); assertEquals(numNonRunnableInQueue, queue.getNumNonRunnableApps()); } @Test public void testUserAndQueueMaxRunningApps() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queue1\">"); out.println("<maxRunningApps>2</maxRunningApps>"); out.println("</queue>"); out.println("<user name=\"user1\">"); out.println("<maxRunningApps>1</maxRunningApps>"); out.println("</user>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // exceeds no limits ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1", "user1"); verifyAppRunnable(attId1, true); verifyQueueNumRunnable("queue1", 1, 0); // exceeds user limit ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue2", "user1"); verifyAppRunnable(attId2, false); verifyQueueNumRunnable("queue2", 0, 1); // exceeds no limits ApplicationAttemptId attId3 = createSchedulingRequest(1024, "queue1", "user2"); verifyAppRunnable(attId3, true); verifyQueueNumRunnable("queue1", 2, 0); // exceeds queue limit ApplicationAttemptId attId4 = createSchedulingRequest(1024, "queue1", "user2"); verifyAppRunnable(attId4, false); verifyQueueNumRunnable("queue1", 2, 1); // Remove app 1 and both app 2 and app 4 should becomes runnable in its place AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent(attId1, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); verifyAppRunnable(attId2, true); verifyQueueNumRunnable("queue2", 1, 0); verifyAppRunnable(attId4, true); verifyQueueNumRunnable("queue1", 2, 0); // A new app to queue1 should not be runnable ApplicationAttemptId attId5 = createSchedulingRequest(1024, "queue1", "user2"); verifyAppRunnable(attId5, false); verifyQueueNumRunnable("queue1", 2, 1); } @Test public void testQueueMaxAMShare() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queue1\">"); out.println("<maxAMShare>0.2</maxAMShare>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(20480, 20), 0, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); scheduler.update(); FSLeafQueue queue1 = scheduler.getQueueManager().getLeafQueue("queue1", true); assertEquals("Queue queue1's fair share should be 0", 0, queue1 .getFairShare().getMemory()); createSchedulingRequest(1 * 1024, "root.default", "user1"); scheduler.update(); scheduler.handle(updateEvent); Resource amResource1 = Resource.newInstance(1024, 1); Resource amResource2 = Resource.newInstance(2048, 2); Resource amResource3 = Resource.newInstance(1860, 2); int amPriority = RMAppAttemptImpl.AM_CONTAINER_PRIORITY.getPriority(); // Exceeds no limits ApplicationAttemptId attId1 = createAppAttemptId(1, 1); createApplicationWithAMResource(attId1, "queue1", "user1", amResource1); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId1); FSAppAttempt app1 = scheduler.getSchedulerApp(attId1); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application1's AM requests 1024 MB memory", 1024, app1.getAMResource().getMemory()); assertEquals("Application1's AM should be running", 1, app1.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 1024 MB memory", 1024, queue1.getAmResourceUsage().getMemory()); // Exceeds no limits ApplicationAttemptId attId2 = createAppAttemptId(2, 1); createApplicationWithAMResource(attId2, "queue1", "user1", amResource1); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId2); FSAppAttempt app2 = scheduler.getSchedulerApp(attId2); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application2's AM requests 1024 MB memory", 1024, app2.getAMResource().getMemory()); assertEquals("Application2's AM should be running", 1, app2.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Exceeds queue limit ApplicationAttemptId attId3 = createAppAttemptId(3, 1); createApplicationWithAMResource(attId3, "queue1", "user1", amResource1); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId3); FSAppAttempt app3 = scheduler.getSchedulerApp(attId3); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application3's AM resource shouldn't be updated", 0, app3.getAMResource().getMemory()); assertEquals("Application3's AM should not be running", 0, app3.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Still can run non-AM container createSchedulingRequestExistingApplication(1024, 1, attId1); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application1 should have two running containers", 2, app1.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Remove app1, app3's AM should become running AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent(attId1, RMAppAttemptState.FINISHED, false); scheduler.update(); scheduler.handle(appRemovedEvent1); scheduler.handle(updateEvent); assertEquals("Application1's AM should be finished", 0, app1.getLiveContainers().size()); assertEquals("Application3's AM should be running", 1, app3.getLiveContainers().size()); assertEquals("Application3's AM requests 1024 MB memory", 1024, app3.getAMResource().getMemory()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Exceeds queue limit ApplicationAttemptId attId4 = createAppAttemptId(4, 1); createApplicationWithAMResource(attId4, "queue1", "user1", amResource2); createSchedulingRequestExistingApplication(2048, 2, amPriority, attId4); FSAppAttempt app4 = scheduler.getSchedulerApp(attId4); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application4's AM resource shouldn't be updated", 0, app4.getAMResource().getMemory()); assertEquals("Application4's AM should not be running", 0, app4.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Exceeds queue limit ApplicationAttemptId attId5 = createAppAttemptId(5, 1); createApplicationWithAMResource(attId5, "queue1", "user1", amResource2); createSchedulingRequestExistingApplication(2048, 2, amPriority, attId5); FSAppAttempt app5 = scheduler.getSchedulerApp(attId5); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application5's AM resource shouldn't be updated", 0, app5.getAMResource().getMemory()); assertEquals("Application5's AM should not be running", 0, app5.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Remove un-running app doesn't affect others AppAttemptRemovedSchedulerEvent appRemovedEvent4 = new AppAttemptRemovedSchedulerEvent(attId4, RMAppAttemptState.KILLED, false); scheduler.handle(appRemovedEvent4); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application5's AM should not be running", 0, app5.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Remove app2 and app3, app5's AM should become running AppAttemptRemovedSchedulerEvent appRemovedEvent2 = new AppAttemptRemovedSchedulerEvent(attId2, RMAppAttemptState.FINISHED, false); AppAttemptRemovedSchedulerEvent appRemovedEvent3 = new AppAttemptRemovedSchedulerEvent(attId3, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent2); scheduler.handle(appRemovedEvent3); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application2's AM should be finished", 0, app2.getLiveContainers().size()); assertEquals("Application3's AM should be finished", 0, app3.getLiveContainers().size()); assertEquals("Application5's AM should be running", 1, app5.getLiveContainers().size()); assertEquals("Application5's AM requests 2048 MB memory", 2048, app5.getAMResource().getMemory()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // request non-AM container for app5 createSchedulingRequestExistingApplication(1024, 1, attId5); assertEquals("Application5's AM should have 1 container", 1, app5.getLiveContainers().size()); // complete AM container before non-AM container is allocated. // spark application hit this situation. RMContainer amContainer5 = (RMContainer)app5.getLiveContainers().toArray()[0]; ContainerExpiredSchedulerEvent containerExpired = new ContainerExpiredSchedulerEvent(amContainer5.getContainerId()); scheduler.handle(containerExpired); assertEquals("Application5's AM should have 0 container", 0, app5.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); scheduler.update(); scheduler.handle(updateEvent); // non-AM container should be allocated // check non-AM container allocation is not rejected // due to queue MaxAMShare limitation. assertEquals("Application5 should have 1 container", 1, app5.getLiveContainers().size()); // check non-AM container allocation won't affect queue AmResourceUsage assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Check amResource normalization ApplicationAttemptId attId6 = createAppAttemptId(6, 1); createApplicationWithAMResource(attId6, "queue1", "user1", amResource3); createSchedulingRequestExistingApplication(1860, 2, amPriority, attId6); FSAppAttempt app6 = scheduler.getSchedulerApp(attId6); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application6's AM should not be running", 0, app6.getLiveContainers().size()); assertEquals("Application6's AM resource shouldn't be updated", 0, app6.getAMResource().getMemory()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); // Remove all apps AppAttemptRemovedSchedulerEvent appRemovedEvent5 = new AppAttemptRemovedSchedulerEvent(attId5, RMAppAttemptState.FINISHED, false); AppAttemptRemovedSchedulerEvent appRemovedEvent6 = new AppAttemptRemovedSchedulerEvent(attId6, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent5); scheduler.handle(appRemovedEvent6); scheduler.update(); assertEquals("Queue1's AM resource usage should be 0", 0, queue1.getAmResourceUsage().getMemory()); } @Test public void testQueueMaxAMShareDefault() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queue1\">"); out.println("</queue>"); out.println("<queue name=\"queue2\">"); out.println("<maxAMShare>0.4</maxAMShare>"); out.println("</queue>"); out.println("<queue name=\"queue3\">"); out.println("</queue>"); out.println("<queue name=\"queue4\">"); out.println("</queue>"); out.println("<queue name=\"queue5\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(8192, 20), 0, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); scheduler.update(); FSLeafQueue queue1 = scheduler.getQueueManager().getLeafQueue("queue1", true); assertEquals("Queue queue1's fair share should be 0", 0, queue1 .getFairShare().getMemory()); FSLeafQueue queue2 = scheduler.getQueueManager().getLeafQueue("queue2", true); assertEquals("Queue queue2's fair share should be 0", 0, queue2 .getFairShare().getMemory()); FSLeafQueue queue3 = scheduler.getQueueManager().getLeafQueue("queue3", true); assertEquals("Queue queue3's fair share should be 0", 0, queue3 .getFairShare().getMemory()); FSLeafQueue queue4 = scheduler.getQueueManager().getLeafQueue("queue4", true); assertEquals("Queue queue4's fair share should be 0", 0, queue4 .getFairShare().getMemory()); FSLeafQueue queue5 = scheduler.getQueueManager().getLeafQueue("queue5", true); assertEquals("Queue queue5's fair share should be 0", 0, queue5 .getFairShare().getMemory()); List<String> queues = Arrays.asList("root.queue3", "root.queue4", "root.queue5"); for (String queue : queues) { createSchedulingRequest(1 * 1024, queue, "user1"); scheduler.update(); scheduler.handle(updateEvent); } Resource amResource1 = Resource.newInstance(1024, 1); int amPriority = RMAppAttemptImpl.AM_CONTAINER_PRIORITY.getPriority(); // The fair share is 2048 MB, and the default maxAMShare is 0.5f, // so the AM is accepted. ApplicationAttemptId attId1 = createAppAttemptId(1, 1); createApplicationWithAMResource(attId1, "queue1", "test1", amResource1); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId1); FSAppAttempt app1 = scheduler.getSchedulerApp(attId1); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application1's AM requests 1024 MB memory", 1024, app1.getAMResource().getMemory()); assertEquals("Application1's AM should be running", 1, app1.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 1024 MB memory", 1024, queue1.getAmResourceUsage().getMemory()); // Now the fair share is 1639 MB, and the maxAMShare is 0.4f, // so the AM is not accepted. ApplicationAttemptId attId2 = createAppAttemptId(2, 1); createApplicationWithAMResource(attId2, "queue2", "test1", amResource1); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId2); FSAppAttempt app2 = scheduler.getSchedulerApp(attId2); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Application2's AM resource shouldn't be updated", 0, app2.getAMResource().getMemory()); assertEquals("Application2's AM should not be running", 0, app2.getLiveContainers().size()); assertEquals("Queue2's AM resource usage should be 0 MB memory", 0, queue2.getAmResourceUsage().getMemory()); } /** * The test verifies container gets reserved when not over maxAMShare, * reserved container gets unreserved when over maxAMShare, * container doesn't get reserved when over maxAMShare, * reserved container is turned into an allocation and * superfluously reserved container gets unreserved. * 1. create three nodes: Node1 is 10G, Node2 is 10G and Node3 is 5G. * 2. APP1 allocated 1G on Node1 and APP2 allocated 1G on Node2. * 3. APP3 reserved 10G on Node1 and Node2. * 4. APP4 allocated 5G on Node3, which makes APP3 over maxAMShare. * 5. Remove APP1 to make Node1 have 10G available resource. * 6. APP3 unreserved its container on Node1 because it is over maxAMShare. * 7. APP5 allocated 1G on Node1 after APP3 unreserved its container. * 8. Remove APP3. * 9. APP6 failed to reserve a 10G container on Node1 due to AMShare limit. * 10. APP7 allocated 1G on Node1. * 11. Remove APP4 and APP5. * 12. APP6 reserved 10G on Node1 and Node2. * 13. APP8 failed to allocate a 1G container on Node1 and Node2 because * APP6 reserved Node1 and Node2. * 14. Remove APP2. * 15. APP6 turned the 10G reservation into an allocation on node2. * 16. APP6 unreserved its container on node1, APP8 allocated 1G on Node1. */ @Test public void testQueueMaxAMShareWithContainerReservation() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queue1\">"); out.println("<maxAMShare>0.5</maxAMShare>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(10240, 10), 1, "127.0.0.1"); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(10240, 10), 2, "127.0.0.2"); RMNode node3 = MockNodes.newNodeInfo(1, Resources.createResource(5120, 5), 3, "127.0.0.3"); NodeAddedSchedulerEvent nodeE1 = new NodeAddedSchedulerEvent(node1); NodeUpdateSchedulerEvent updateE1 = new NodeUpdateSchedulerEvent(node1); NodeAddedSchedulerEvent nodeE2 = new NodeAddedSchedulerEvent(node2); NodeUpdateSchedulerEvent updateE2 = new NodeUpdateSchedulerEvent(node2); NodeAddedSchedulerEvent nodeE3 = new NodeAddedSchedulerEvent(node3); NodeUpdateSchedulerEvent updateE3 = new NodeUpdateSchedulerEvent(node3); scheduler.handle(nodeE1); scheduler.handle(nodeE2); scheduler.handle(nodeE3); scheduler.update(); FSLeafQueue queue1 = scheduler.getQueueManager().getLeafQueue("queue1", true); Resource amResource1 = Resource.newInstance(1024, 1); Resource amResource2 = Resource.newInstance(1024, 1); Resource amResource3 = Resource.newInstance(10240, 1); Resource amResource4 = Resource.newInstance(5120, 1); Resource amResource5 = Resource.newInstance(1024, 1); Resource amResource6 = Resource.newInstance(10240, 1); Resource amResource7 = Resource.newInstance(1024, 1); Resource amResource8 = Resource.newInstance(1024, 1); int amPriority = RMAppAttemptImpl.AM_CONTAINER_PRIORITY.getPriority(); ApplicationAttemptId attId1 = createAppAttemptId(1, 1); createApplicationWithAMResource(attId1, "queue1", "user1", amResource1); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId1); FSAppAttempt app1 = scheduler.getSchedulerApp(attId1); scheduler.update(); // Allocate app1's AM container on node1. scheduler.handle(updateE1); assertEquals("Application1's AM requests 1024 MB memory", 1024, app1.getAMResource().getMemory()); assertEquals("Application1's AM should be running", 1, app1.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 1024 MB memory", 1024, queue1.getAmResourceUsage().getMemory()); ApplicationAttemptId attId2 = createAppAttemptId(2, 1); createApplicationWithAMResource(attId2, "queue1", "user1", amResource2); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId2); FSAppAttempt app2 = scheduler.getSchedulerApp(attId2); scheduler.update(); // Allocate app2's AM container on node2. scheduler.handle(updateE2); assertEquals("Application2's AM requests 1024 MB memory", 1024, app2.getAMResource().getMemory()); assertEquals("Application2's AM should be running", 1, app2.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); ApplicationAttemptId attId3 = createAppAttemptId(3, 1); createApplicationWithAMResource(attId3, "queue1", "user1", amResource3); createSchedulingRequestExistingApplication(10240, 1, amPriority, attId3); FSAppAttempt app3 = scheduler.getSchedulerApp(attId3); scheduler.update(); // app3 reserves a container on node1 because node1's available resource // is less than app3's AM container resource. scheduler.handle(updateE1); // Similarly app3 reserves a container on node2. scheduler.handle(updateE2); assertEquals("Application3's AM resource shouldn't be updated", 0, app3.getAMResource().getMemory()); assertEquals("Application3's AM should not be running", 0, app3.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); ApplicationAttemptId attId4 = createAppAttemptId(4, 1); createApplicationWithAMResource(attId4, "queue1", "user1", amResource4); createSchedulingRequestExistingApplication(5120, 1, amPriority, attId4); FSAppAttempt app4 = scheduler.getSchedulerApp(attId4); scheduler.update(); // app4 can't allocate its AM container on node1 because // app3 already reserved its container on node1. scheduler.handle(updateE1); assertEquals("Application4's AM resource shouldn't be updated", 0, app4.getAMResource().getMemory()); assertEquals("Application4's AM should not be running", 0, app4.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); scheduler.update(); // Allocate app4's AM container on node3. scheduler.handle(updateE3); assertEquals("Application4's AM requests 5120 MB memory", 5120, app4.getAMResource().getMemory()); assertEquals("Application4's AM should be running", 1, app4.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 7168 MB memory", 7168, queue1.getAmResourceUsage().getMemory()); AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent(attId1, RMAppAttemptState.FINISHED, false); // Release app1's AM container on node1. scheduler.handle(appRemovedEvent1); assertEquals("Queue1's AM resource usage should be 6144 MB memory", 6144, queue1.getAmResourceUsage().getMemory()); ApplicationAttemptId attId5 = createAppAttemptId(5, 1); createApplicationWithAMResource(attId5, "queue1", "user1", amResource5); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId5); FSAppAttempt app5 = scheduler.getSchedulerApp(attId5); scheduler.update(); // app5 can allocate its AM container on node1 after // app3 unreserve its container on node1 due to // exceeding queue MaxAMShare limit. scheduler.handle(updateE1); assertEquals("Application5's AM requests 1024 MB memory", 1024, app5.getAMResource().getMemory()); assertEquals("Application5's AM should be running", 1, app5.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 7168 MB memory", 7168, queue1.getAmResourceUsage().getMemory()); AppAttemptRemovedSchedulerEvent appRemovedEvent3 = new AppAttemptRemovedSchedulerEvent(attId3, RMAppAttemptState.FINISHED, false); // Remove app3. scheduler.handle(appRemovedEvent3); assertEquals("Queue1's AM resource usage should be 7168 MB memory", 7168, queue1.getAmResourceUsage().getMemory()); ApplicationAttemptId attId6 = createAppAttemptId(6, 1); createApplicationWithAMResource(attId6, "queue1", "user1", amResource6); createSchedulingRequestExistingApplication(10240, 1, amPriority, attId6); FSAppAttempt app6 = scheduler.getSchedulerApp(attId6); scheduler.update(); // app6 can't reserve a container on node1 because // it exceeds queue MaxAMShare limit. scheduler.handle(updateE1); assertEquals("Application6's AM resource shouldn't be updated", 0, app6.getAMResource().getMemory()); assertEquals("Application6's AM should not be running", 0, app6.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 7168 MB memory", 7168, queue1.getAmResourceUsage().getMemory()); ApplicationAttemptId attId7 = createAppAttemptId(7, 1); createApplicationWithAMResource(attId7, "queue1", "user1", amResource7); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId7); FSAppAttempt app7 = scheduler.getSchedulerApp(attId7); scheduler.update(); // Allocate app7's AM container on node1 to prove // app6 didn't reserve a container on node1. scheduler.handle(updateE1); assertEquals("Application7's AM requests 1024 MB memory", 1024, app7.getAMResource().getMemory()); assertEquals("Application7's AM should be running", 1, app7.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 8192 MB memory", 8192, queue1.getAmResourceUsage().getMemory()); AppAttemptRemovedSchedulerEvent appRemovedEvent4 = new AppAttemptRemovedSchedulerEvent(attId4, RMAppAttemptState.FINISHED, false); // Release app4's AM container on node3. scheduler.handle(appRemovedEvent4); assertEquals("Queue1's AM resource usage should be 3072 MB memory", 3072, queue1.getAmResourceUsage().getMemory()); AppAttemptRemovedSchedulerEvent appRemovedEvent5 = new AppAttemptRemovedSchedulerEvent(attId5, RMAppAttemptState.FINISHED, false); // Release app5's AM container on node1. scheduler.handle(appRemovedEvent5); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); scheduler.update(); // app6 reserves a container on node1 because node1's available resource // is less than app6's AM container resource and // app6 is not over AMShare limit. scheduler.handle(updateE1); // Similarly app6 reserves a container on node2. scheduler.handle(updateE2); ApplicationAttemptId attId8 = createAppAttemptId(8, 1); createApplicationWithAMResource(attId8, "queue1", "user1", amResource8); createSchedulingRequestExistingApplication(1024, 1, amPriority, attId8); FSAppAttempt app8 = scheduler.getSchedulerApp(attId8); scheduler.update(); // app8 can't allocate a container on node1 because // app6 already reserved a container on node1. scheduler.handle(updateE1); assertEquals("Application8's AM resource shouldn't be updated", 0, app8.getAMResource().getMemory()); assertEquals("Application8's AM should not be running", 0, app8.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); scheduler.update(); // app8 can't allocate a container on node2 because // app6 already reserved a container on node2. scheduler.handle(updateE2); assertEquals("Application8's AM resource shouldn't be updated", 0, app8.getAMResource().getMemory()); assertEquals("Application8's AM should not be running", 0, app8.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 2048 MB memory", 2048, queue1.getAmResourceUsage().getMemory()); AppAttemptRemovedSchedulerEvent appRemovedEvent2 = new AppAttemptRemovedSchedulerEvent(attId2, RMAppAttemptState.FINISHED, false); // Release app2's AM container on node2. scheduler.handle(appRemovedEvent2); assertEquals("Queue1's AM resource usage should be 1024 MB memory", 1024, queue1.getAmResourceUsage().getMemory()); scheduler.update(); // app6 turns the reservation into an allocation on node2. scheduler.handle(updateE2); assertEquals("Application6's AM requests 10240 MB memory", 10240, app6.getAMResource().getMemory()); assertEquals("Application6's AM should be running", 1, app6.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 11264 MB memory", 11264, queue1.getAmResourceUsage().getMemory()); scheduler.update(); // app6 unreserve its container on node1 because // it already got a container on node2. // Now app8 can allocate its AM container on node1. scheduler.handle(updateE1); assertEquals("Application8's AM requests 1024 MB memory", 1024, app8.getAMResource().getMemory()); assertEquals("Application8's AM should be running", 1, app8.getLiveContainers().size()); assertEquals("Queue1's AM resource usage should be 12288 MB memory", 12288, queue1.getAmResourceUsage().getMemory()); } @Test public void testMaxRunningAppsHierarchicalQueues() throws Exception { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queue1\">"); out.println(" <maxRunningApps>3</maxRunningApps>"); out.println(" <queue name=\"sub1\"></queue>"); out.println(" <queue name=\"sub2\"></queue>"); out.println(" <queue name=\"sub3\">"); out.println(" <maxRunningApps>1</maxRunningApps>"); out.println(" </queue>"); out.println("</queue>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // exceeds no limits ApplicationAttemptId attId1 = createSchedulingRequest(1024, "queue1.sub1", "user1"); verifyAppRunnable(attId1, true); verifyQueueNumRunnable("queue1.sub1", 1, 0); clock.tickSec(10); // exceeds no limits ApplicationAttemptId attId2 = createSchedulingRequest(1024, "queue1.sub3", "user1"); verifyAppRunnable(attId2, true); verifyQueueNumRunnable("queue1.sub3", 1, 0); clock.tickSec(10); // exceeds no limits ApplicationAttemptId attId3 = createSchedulingRequest(1024, "queue1.sub2", "user1"); verifyAppRunnable(attId3, true); verifyQueueNumRunnable("queue1.sub2", 1, 0); clock.tickSec(10); // exceeds queue1 limit ApplicationAttemptId attId4 = createSchedulingRequest(1024, "queue1.sub2", "user1"); verifyAppRunnable(attId4, false); verifyQueueNumRunnable("queue1.sub2", 1, 1); clock.tickSec(10); // exceeds sub3 limit ApplicationAttemptId attId5 = createSchedulingRequest(1024, "queue1.sub3", "user1"); verifyAppRunnable(attId5, false); verifyQueueNumRunnable("queue1.sub3", 1, 1); clock.tickSec(10); // Even though the app was removed from sub3, the app from sub2 gets to go // because it came in first AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent(attId2, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); verifyAppRunnable(attId4, true); verifyQueueNumRunnable("queue1.sub2", 2, 0); verifyAppRunnable(attId5, false); verifyQueueNumRunnable("queue1.sub3", 0, 1); // Now test removal of a non-runnable app AppAttemptRemovedSchedulerEvent appRemovedEvent2 = new AppAttemptRemovedSchedulerEvent(attId5, RMAppAttemptState.KILLED, true); scheduler.handle(appRemovedEvent2); assertEquals(0, scheduler.maxRunningEnforcer.usersNonRunnableApps .get("user1").size()); // verify app gone in queue accounting verifyQueueNumRunnable("queue1.sub3", 0, 0); // verify it doesn't become runnable when there would be space for it AppAttemptRemovedSchedulerEvent appRemovedEvent3 = new AppAttemptRemovedSchedulerEvent(attId4, RMAppAttemptState.FINISHED, true); scheduler.handle(appRemovedEvent3); verifyQueueNumRunnable("queue1.sub2", 1, 0); verifyQueueNumRunnable("queue1.sub3", 0, 0); } @Test (timeout = 10000) public void testContinuousScheduling() throws Exception { // set continuous scheduling enabled scheduler = new FairScheduler(); Configuration conf = createConfiguration(); conf.setBoolean(FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_ENABLED, true); scheduler.setRMContext(resourceManager.getRMContext()); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); Assert.assertTrue("Continuous scheduling should be enabled.", scheduler.isContinuousSchedulingEnabled()); // Add two nodes RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); // available resource Assert.assertEquals(scheduler.getClusterResource().getMemory(), 16 * 1024); Assert.assertEquals(scheduler.getClusterResource().getVirtualCores(), 16); // send application request ApplicationAttemptId appAttemptId = createAppAttemptId(this.APP_ID++, this.ATTEMPT_ID++); createMockRMApp(appAttemptId); scheduler.addApplication(appAttemptId.getApplicationId(), "queue11", "user11", false); scheduler.addApplicationAttempt(appAttemptId, false, false); List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); ResourceRequest request = createResourceRequest(1024, 1, ResourceRequest.ANY, 1, 1, true); ask.add(request); scheduler.allocate(appAttemptId, ask, new ArrayList<ContainerId>(), null, null); // waiting for continuous_scheduler_sleep_time // at least one pass Thread.sleep(scheduler.getConf().getContinuousSchedulingSleepMs() + 500); FSAppAttempt app = scheduler.getSchedulerApp(appAttemptId); // Wait until app gets resources. while (app.getCurrentConsumption().equals(Resources.none())) { } // check consumption Assert.assertEquals(1024, app.getCurrentConsumption().getMemory()); Assert.assertEquals(1, app.getCurrentConsumption().getVirtualCores()); // another request request = createResourceRequest(1024, 1, ResourceRequest.ANY, 2, 1, true); ask.clear(); ask.add(request); scheduler.stop(); scheduler.allocate(appAttemptId, ask, new ArrayList<ContainerId>(), null, null); scheduler.continuousSchedulingAttempt(); Assert.assertEquals(2048, app.getCurrentConsumption().getMemory()); Assert.assertEquals(2, app.getCurrentConsumption().getVirtualCores()); // 2 containers should be assigned to 2 nodes Set<NodeId> nodes = new HashSet<NodeId>(); Iterator<RMContainer> it = app.getLiveContainers().iterator(); while (it.hasNext()) { nodes.add(it.next().getContainer().getNodeId()); } Assert.assertEquals(2, nodes.size()); } @Test public void testContinuousSchedulingWithNodeRemoved() throws Exception { // Disable continuous scheduling, will invoke continuous scheduling once manually scheduler.init(conf); scheduler.start(); Assert.assertTrue("Continuous scheduling should be disabled.", !scheduler.isContinuousSchedulingEnabled()); // Add two nodes RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); RMNode node2 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 2, "127.0.0.2"); NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2); scheduler.handle(nodeEvent2); Assert.assertEquals("We should have two alive nodes.", 2, scheduler.getNumClusterNodes()); // Remove one node NodeRemovedSchedulerEvent removeNode1 = new NodeRemovedSchedulerEvent(node1); scheduler.handle(removeNode1); Assert.assertEquals("We should only have one alive node.", 1, scheduler.getNumClusterNodes()); // Invoke the continuous scheduling once try { scheduler.continuousSchedulingAttempt(); } catch (Exception e) { fail("Exception happened when doing continuous scheduling. " + e.toString()); } } @Test public void testSchedulingOnRemovedNode() throws Exception { // Disable continuous scheduling, will invoke continuous scheduling manually scheduler.init(conf); scheduler.start(); Assert.assertTrue("Continuous scheduling should be disabled.", !scheduler.isContinuousSchedulingEnabled()); ApplicationAttemptId id11 = createAppAttemptId(1, 1); createMockRMApp(id11); scheduler.addApplication(id11.getApplicationId(), "root.queue1", "user1", false); scheduler.addApplicationAttempt(id11, false, false); List<ResourceRequest> ask1 = new ArrayList<>(); ResourceRequest request1 = createResourceRequest(1024, 8, ResourceRequest.ANY, 1, 1, true); ask1.add(request1); scheduler.allocate(id11, ask1, new ArrayList<ContainerId>(), null, null); String hostName = "127.0.0.1"; RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(8 * 1024, 8), 1, hostName); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); FSSchedulerNode node = (FSSchedulerNode)scheduler.getSchedulerNode( node1.getNodeID()); NodeRemovedSchedulerEvent removeNode1 = new NodeRemovedSchedulerEvent(node1); scheduler.handle(removeNode1); scheduler.attemptScheduling(node); AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent(id11, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); } @Test public void testDefaultRuleInitializesProperlyWhenPolicyNotConfigured() throws IOException { // This test verifies if default rule in queue placement policy // initializes properly when policy is not configured and // undeclared pools is not allowed. conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); conf.setBoolean(FairSchedulerConfiguration.ALLOW_UNDECLARED_POOLS, false); // Create an alloc file with no queue placement policy PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); List<QueuePlacementRule> rules = scheduler.allocConf.placementPolicy.getRules(); for (QueuePlacementRule rule : rules) { if (rule instanceof Default) { Default defaultRule = (Default) rule; assertNotNull(defaultRule.defaultQueueName); } } } @Test(timeout = 5000) public void testRecoverRequestAfterPreemption() throws Exception { conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10); ControlledClock clock = new ControlledClock(); scheduler.setClock(clock); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); Priority priority = Priority.newInstance(20); String host = "127.0.0.1"; int GB = 1024; // Create Node and raised Node Added event RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(16 * 1024, 4), 0, host); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); scheduler.handle(nodeEvent); // Create 3 container requests and place it in ask List<ResourceRequest> ask = new ArrayList<ResourceRequest>(); ResourceRequest nodeLocalRequest = createResourceRequest(GB, 1, host, priority.getPriority(), 1, true); ResourceRequest rackLocalRequest = createResourceRequest(GB, 1, node.getRackName(), priority.getPriority(), 1, true); ResourceRequest offRackRequest = createResourceRequest(GB, 1, ResourceRequest.ANY, priority.getPriority(), 1, true); ask.add(nodeLocalRequest); ask.add(rackLocalRequest); ask.add(offRackRequest); // Create Request and update ApplicationAttemptId appAttemptId = createSchedulingRequest("queueA", "user1", ask); scheduler.update(); // Sufficient node check-ins to fully schedule containers NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeUpdate); assertEquals(1, scheduler.getSchedulerApp(appAttemptId).getLiveContainers() .size()); FSAppAttempt app = scheduler.getSchedulerApp(appAttemptId); // ResourceRequest will be empty once NodeUpdate is completed Assert.assertNull(app.getResourceRequest(priority, host)); ContainerId containerId1 = ContainerId.newContainerId(appAttemptId, 1); RMContainer rmContainer = app.getRMContainer(containerId1); // Create a preempt event and register for preemption scheduler.warnOrKillContainer(rmContainer); // Wait for few clock ticks clock.tickSec(5); // preempt now scheduler.warnOrKillContainer(rmContainer); // Trigger container rescheduled event scheduler.handle(new ContainerRescheduledEvent(rmContainer)); List<ResourceRequest> requests = rmContainer.getResourceRequests(); // Once recovered, resource request will be present again in app Assert.assertEquals(3, requests.size()); for (ResourceRequest request : requests) { Assert.assertEquals(1, app.getResourceRequest(priority, request.getResourceName()) .getNumContainers()); } // Send node heartbeat scheduler.update(); scheduler.handle(nodeUpdate); List<Container> containers = scheduler.allocate(appAttemptId, Collections.<ResourceRequest> emptyList(), Collections.<ContainerId> emptyList(), null, null).getContainers(); // Now with updated ResourceRequest, a container is allocated for AM. Assert.assertTrue(containers.size() == 1); } @SuppressWarnings("resource") @Test public void testBlacklistNodes() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); final int GB = 1024; String host = "127.0.0.1"; RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(16 * GB, 16), 0, host); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); ApplicationAttemptId appAttemptId = createSchedulingRequest(GB, "root.default", "user", 1); FSAppAttempt app = scheduler.getSchedulerApp(appAttemptId); // Verify the blacklist can be updated independent of requesting containers scheduler.allocate(appAttemptId, Collections.<ResourceRequest>emptyList(), Collections.<ContainerId>emptyList(), Collections.singletonList(host), null); assertTrue(app.isBlacklisted(host)); scheduler.allocate(appAttemptId, Collections.<ResourceRequest>emptyList(), Collections.<ContainerId>emptyList(), null, Collections.singletonList(host)); assertFalse(scheduler.getSchedulerApp(appAttemptId).isBlacklisted(host)); List<ResourceRequest> update = Arrays.asList( createResourceRequest(GB, node.getHostName(), 1, 0, true)); // Verify a container does not actually get placed on the blacklisted host scheduler.allocate(appAttemptId, update, Collections.<ContainerId>emptyList(), Collections.singletonList(host), null); assertTrue(app.isBlacklisted(host)); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Incorrect number of containers allocated", 0, app .getLiveContainers().size()); // Verify a container gets placed on the empty blacklist scheduler.allocate(appAttemptId, update, Collections.<ContainerId>emptyList(), null, Collections.singletonList(host)); assertFalse(app.isBlacklisted(host)); createSchedulingRequest(GB, "root.default", "user", 1); scheduler.update(); scheduler.handle(updateEvent); assertEquals("Incorrect number of containers allocated", 1, app .getLiveContainers().size()); } @Test public void testGetAppsInQueue() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId appAttId1 = createSchedulingRequest(1024, 1, "queue1.subqueue1", "user1"); ApplicationAttemptId appAttId2 = createSchedulingRequest(1024, 1, "queue1.subqueue2", "user1"); ApplicationAttemptId appAttId3 = createSchedulingRequest(1024, 1, "default", "user1"); List<ApplicationAttemptId> apps = scheduler.getAppsInQueue("queue1.subqueue1"); assertEquals(1, apps.size()); assertEquals(appAttId1, apps.get(0)); // with and without root prefix should work apps = scheduler.getAppsInQueue("root.queue1.subqueue1"); assertEquals(1, apps.size()); assertEquals(appAttId1, apps.get(0)); apps = scheduler.getAppsInQueue("user1"); assertEquals(1, apps.size()); assertEquals(appAttId3, apps.get(0)); // with and without root prefix should work apps = scheduler.getAppsInQueue("root.user1"); assertEquals(1, apps.size()); assertEquals(appAttId3, apps.get(0)); // apps in subqueues should be included apps = scheduler.getAppsInQueue("queue1"); Assert.assertEquals(2, apps.size()); Set<ApplicationAttemptId> appAttIds = Sets.newHashSet(apps.get(0), apps.get(1)); assertTrue(appAttIds.contains(appAttId1)); assertTrue(appAttIds.contains(appAttId2)); } @Test public void testAddAndRemoveAppFromFairScheduler() throws Exception { AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode> scheduler = (AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode>) resourceManager .getResourceScheduler(); TestSchedulerUtils.verifyAppAddedAndRemovedFromScheduler( scheduler.getSchedulerApplications(), scheduler, "default"); } @Test (expected = YarnException.class) public void testMoveWouldViolateMaxAppsConstraints() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); QueueManager queueMgr = scheduler.getQueueManager(); queueMgr.getLeafQueue("queue2", true); scheduler.getAllocationConfiguration().queueMaxApps.put("root.queue2", 0); ApplicationAttemptId appAttId = createSchedulingRequest(1024, 1, "queue1", "user1", 3); scheduler.moveApplication(appAttId.getApplicationId(), "queue2"); } @Test (expected = YarnException.class) public void testMoveWouldViolateMaxResourcesConstraints() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); QueueManager queueMgr = scheduler.getQueueManager(); FSLeafQueue oldQueue = queueMgr.getLeafQueue("queue1", true); queueMgr.getLeafQueue("queue2", true); scheduler.getAllocationConfiguration().maxQueueResources.put("root.queue2", Resource.newInstance(1024, 1)); ApplicationAttemptId appAttId = createSchedulingRequest(1024, 1, "queue1", "user1", 3); RMNode node = MockNodes.newNodeInfo(1, Resources.createResource(2048, 2)); NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node); NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node); scheduler.handle(nodeEvent); scheduler.handle(updateEvent); scheduler.handle(updateEvent); assertEquals(Resource.newInstance(2048, 2), oldQueue.getResourceUsage()); scheduler.moveApplication(appAttId.getApplicationId(), "queue2"); } @Test (expected = YarnException.class) public void testMoveToNonexistentQueue() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); scheduler.getQueueManager().getLeafQueue("queue1", true); ApplicationAttemptId appAttId = createSchedulingRequest(1024, 1, "queue1", "user1", 3); scheduler.moveApplication(appAttId.getApplicationId(), "queue2"); } @Test public void testLowestCommonAncestorForNonRootParent() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); FSLeafQueue aQueue = mock(FSLeafQueue.class); FSLeafQueue bQueue = mock(FSLeafQueue.class); when(aQueue.getName()).thenReturn("root.queue1.a"); when(bQueue.getName()).thenReturn("root.queue1.b"); QueueManager queueManager = scheduler.getQueueManager(); FSParentQueue queue1 = queueManager.getParentQueue("queue1", true); queue1.addChildQueue(aQueue); queue1.addChildQueue(bQueue); FSQueue ancestorQueue = scheduler.findLowestCommonAncestorQueue(aQueue, bQueue); assertEquals(ancestorQueue, queue1); } @Test public void testLowestCommonAncestorRootParent() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); FSLeafQueue aQueue = mock(FSLeafQueue.class); FSLeafQueue bQueue = mock(FSLeafQueue.class); when(aQueue.getName()).thenReturn("root.a"); when(bQueue.getName()).thenReturn("root.b"); QueueManager queueManager = scheduler.getQueueManager(); FSParentQueue queue1 = queueManager.getParentQueue("root", false); queue1.addChildQueue(aQueue); queue1.addChildQueue(bQueue); FSQueue ancestorQueue = scheduler.findLowestCommonAncestorQueue(aQueue, bQueue); assertEquals(ancestorQueue, queue1); } @Test public void testLowestCommonAncestorDeeperHierarchy() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); FSQueue aQueue = mock(FSLeafQueue.class); FSQueue bQueue = mock(FSLeafQueue.class); FSQueue a1Queue = mock(FSLeafQueue.class); FSQueue b1Queue = mock(FSLeafQueue.class); when(a1Queue.getName()).thenReturn("root.queue1.a.a1"); when(b1Queue.getName()).thenReturn("root.queue1.b.b1"); when(aQueue.getChildQueues()).thenReturn(Arrays.asList(a1Queue)); when(bQueue.getChildQueues()).thenReturn(Arrays.asList(b1Queue)); QueueManager queueManager = scheduler.getQueueManager(); FSParentQueue queue1 = queueManager.getParentQueue("queue1", true); queue1.addChildQueue(aQueue); queue1.addChildQueue(bQueue); FSQueue ancestorQueue = scheduler.findLowestCommonAncestorQueue(a1Queue, b1Queue); assertEquals(ancestorQueue, queue1); } @Test public void testThreadLifeCycle() throws InterruptedException { conf.setBoolean( FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_ENABLED, true); scheduler.init(conf); scheduler.start(); Thread updateThread = scheduler.updateThread; Thread schedulingThread = scheduler.schedulingThread; assertTrue(updateThread.isAlive()); assertTrue(schedulingThread.isAlive()); scheduler.stop(); int numRetries = 100; while (numRetries-- > 0 && (updateThread.isAlive() || schedulingThread.isAlive())) { Thread.sleep(50); } assertNotEquals("One of the threads is still alive", 0, numRetries); } @Test public void testPerfMetricsInited() { scheduler.init(conf); scheduler.start(); MetricsCollectorImpl collector = new MetricsCollectorImpl(); scheduler.fsOpDurations.getMetrics(collector, true); assertEquals("Incorrect number of perf metrics", 1, collector.getRecords().size()); } @Test public void testQueueNameWithTrailingSpace() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); // only default queue assertEquals(1, scheduler.getQueueManager().getLeafQueues().size()); // submit app with queue name "A" ApplicationAttemptId appAttemptId1 = createAppAttemptId(1, 1); AppAddedSchedulerEvent appAddedEvent1 = new AppAddedSchedulerEvent( appAttemptId1.getApplicationId(), "A", "user1"); scheduler.handle(appAddedEvent1); // submission accepted assertEquals(2, scheduler.getQueueManager().getLeafQueues().size()); assertNotNull(scheduler.getSchedulerApplications().get(appAttemptId1. getApplicationId())); AppAttemptAddedSchedulerEvent attempAddedEvent = new AppAttemptAddedSchedulerEvent(appAttemptId1, false); scheduler.handle(attempAddedEvent); // That queue should have one app assertEquals(1, scheduler.getQueueManager().getLeafQueue("A", true) .getNumRunnableApps()); assertNotNull(scheduler.getSchedulerApp(appAttemptId1)); // submit app with queue name "A " ApplicationAttemptId appAttemptId2 = createAppAttemptId(2, 1); AppAddedSchedulerEvent appAddedEvent2 = new AppAddedSchedulerEvent( appAttemptId2.getApplicationId(), "A ", "user1"); scheduler.handle(appAddedEvent2); // submission rejected assertEquals(2, scheduler.getQueueManager().getLeafQueues().size()); assertNull(scheduler.getSchedulerApplications().get(appAttemptId2. getApplicationId())); assertNull(scheduler.getSchedulerApp(appAttemptId2)); // submit app with queue name "B.C" ApplicationAttemptId appAttemptId3 = createAppAttemptId(3, 1); AppAddedSchedulerEvent appAddedEvent3 = new AppAddedSchedulerEvent( appAttemptId3.getApplicationId(), "B.C", "user1"); scheduler.handle(appAddedEvent3); // submission accepted assertEquals(3, scheduler.getQueueManager().getLeafQueues().size()); assertNotNull(scheduler.getSchedulerApplications().get(appAttemptId3. getApplicationId())); attempAddedEvent = new AppAttemptAddedSchedulerEvent(appAttemptId3, false); scheduler.handle(attempAddedEvent); // That queue should have one app assertEquals(1, scheduler.getQueueManager().getLeafQueue("B.C", true) .getNumRunnableApps()); assertNotNull(scheduler.getSchedulerApp(appAttemptId3)); } @Test public void testEmptyQueueNameInConfigFile() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); // set empty queue name PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"\">"); out.println("</queue>"); out.println("</allocations>"); out.close(); try { scheduler.init(conf); Assert.fail("scheduler init should fail because" + " empty queue name."); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains( "Failed to initialize FairScheduler")); } } @Test public void testUserAsDefaultQueueWithLeadingTrailingSpaceUserName() throws Exception { conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "true"); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId appAttemptId = createAppAttemptId(1, 1); createApplicationWithAMResource(appAttemptId, "default", " user1", null); assertEquals(1, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); assertEquals(0, scheduler.getQueueManager().getLeafQueue("default", true) .getNumRunnableApps()); assertEquals("root.user1", resourceManager.getRMContext().getRMApps() .get(appAttemptId.getApplicationId()).getQueue()); ApplicationAttemptId attId2 = createAppAttemptId(2, 1); createApplicationWithAMResource(attId2, "default", "user1 ", null); assertEquals(2, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); assertEquals(0, scheduler.getQueueManager().getLeafQueue("default", true) .getNumRunnableApps()); assertEquals("root.user1", resourceManager.getRMContext().getRMApps() .get(attId2.getApplicationId()).getQueue()); ApplicationAttemptId attId3 = createAppAttemptId(3, 1); createApplicationWithAMResource(attId3, "default", "user1", null); assertEquals(3, scheduler.getQueueManager().getLeafQueue("user1", true) .getNumRunnableApps()); assertEquals(0, scheduler.getQueueManager().getLeafQueue("default", true) .getNumRunnableApps()); assertEquals("root.user1", resourceManager.getRMContext().getRMApps() .get(attId3.getApplicationId()).getQueue()); } }
203,011
40.849516
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerFairShare.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.scheduler.fair; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestFairSchedulerFairShare extends FairSchedulerTestBase { private final static String ALLOC_FILE = new File(TEST_DIR, TestFairSchedulerFairShare.class.getName() + ".xml").getAbsolutePath(); @Before public void setup() throws IOException { conf = createConfiguration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); } @After public void teardown() { if (resourceManager != null) { resourceManager.stop(); resourceManager = null; } conf = null; } private void createClusterWithQueuesAndOneNode(int mem, String policy) throws IOException { createClusterWithQueuesAndOneNode(mem, 0, policy); } private void createClusterWithQueuesAndOneNode(int mem, int vCores, String policy) throws IOException { PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"root\" >"); out.println(" <queue name=\"parentA\" >"); out.println(" <weight>8</weight>"); out.println(" <queue name=\"childA1\" />"); out.println(" <queue name=\"childA2\" />"); out.println(" <queue name=\"childA3\" />"); out.println(" <queue name=\"childA4\" />"); out.println(" </queue>"); out.println(" <queue name=\"parentB\" >"); out.println(" <weight>1</weight>"); out.println(" <queue name=\"childB1\" />"); out.println(" <queue name=\"childB2\" />"); out.println(" </queue>"); out.println("</queue>"); out.println("<defaultQueueSchedulingPolicy>" + policy + "</defaultQueueSchedulingPolicy>"); out.println("</allocations>"); out.close(); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(mem, vCores), 1, "127.0.0.1"); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); } @Test public void testFairShareNoAppsRunning() throws IOException { int nodeCapacity = 16 * 1024; createClusterWithQueuesAndOneNode(nodeCapacity, "fair"); scheduler.update(); // No apps are running in the cluster,verify if fair share is zero // for all queues under parentA and parentB. Collection<FSLeafQueue> leafQueues = scheduler.getQueueManager() .getLeafQueues(); for (FSLeafQueue leaf : leafQueues) { if (leaf.getName().startsWith("root.parentA")) { assertEquals(0, (double) leaf.getFairShare().getMemory() / nodeCapacity, 0); } else if (leaf.getName().startsWith("root.parentB")) { assertEquals(0, (double) leaf.getFairShare().getMemory() / nodeCapacity, 0); } } verifySteadyFairShareMemory(leafQueues, nodeCapacity); } @Test public void testFairShareOneAppRunning() throws IOException { int nodeCapacity = 16 * 1024; createClusterWithQueuesAndOneNode(nodeCapacity, "fair"); // Run a app in a childA1. Verify whether fair share is 100% in childA1, // since it is the only active queue. // Also verify if fair share is 0 for childA2. since no app is // running in it. createSchedulingRequest(2 * 1024, "root.parentA.childA1", "user1"); scheduler.update(); assertEquals( 100, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA1", false).getFairShare() .getMemory() / nodeCapacity * 100, 0.1); assertEquals( 0, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA2", false).getFairShare() .getMemory() / nodeCapacity, 0.1); verifySteadyFairShareMemory(scheduler.getQueueManager().getLeafQueues(), nodeCapacity); } @Test public void testFairShareMultipleActiveQueuesUnderSameParent() throws IOException { int nodeCapacity = 16 * 1024; createClusterWithQueuesAndOneNode(nodeCapacity, "fair"); // Run apps in childA1,childA2,childA3 createSchedulingRequest(2 * 1024, "root.parentA.childA1", "user1"); createSchedulingRequest(2 * 1024, "root.parentA.childA2", "user2"); createSchedulingRequest(2 * 1024, "root.parentA.childA3", "user3"); scheduler.update(); // Verify if fair share is 100 / 3 = 33% for (int i = 1; i <= 3; i++) { assertEquals( 33, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA" + i, false).getFairShare() .getMemory() / nodeCapacity * 100, .9); } verifySteadyFairShareMemory(scheduler.getQueueManager().getLeafQueues(), nodeCapacity); } @Test public void testFairShareMultipleActiveQueuesUnderDifferentParent() throws IOException { int nodeCapacity = 16 * 1024; createClusterWithQueuesAndOneNode(nodeCapacity, "fair"); // Run apps in childA1,childA2 which are under parentA createSchedulingRequest(2 * 1024, "root.parentA.childA1", "user1"); createSchedulingRequest(3 * 1024, "root.parentA.childA2", "user2"); // Run app in childB1 which is under parentB createSchedulingRequest(1 * 1024, "root.parentB.childB1", "user3"); // Run app in root.default queue createSchedulingRequest(1 * 1024, "root.default", "user4"); scheduler.update(); // The two active child queues under parentA would // get fair share of 80/2=40% for (int i = 1; i <= 2; i++) { assertEquals( 40, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA" + i, false).getFairShare() .getMemory() / nodeCapacity * 100, .9); } // The child queue under parentB would get a fair share of 10%, // basically all of parentB's fair share assertEquals( 10, (double) scheduler.getQueueManager() .getLeafQueue("root.parentB.childB1", false).getFairShare() .getMemory() / nodeCapacity * 100, .9); verifySteadyFairShareMemory(scheduler.getQueueManager().getLeafQueues(), nodeCapacity); } @Test public void testFairShareResetsToZeroWhenAppsComplete() throws IOException { int nodeCapacity = 16 * 1024; createClusterWithQueuesAndOneNode(nodeCapacity, "fair"); // Run apps in childA1,childA2 which are under parentA ApplicationAttemptId app1 = createSchedulingRequest(2 * 1024, "root.parentA.childA1", "user1"); ApplicationAttemptId app2 = createSchedulingRequest(3 * 1024, "root.parentA.childA2", "user2"); scheduler.update(); // Verify if both the active queues under parentA get 50% fair // share for (int i = 1; i <= 2; i++) { assertEquals( 50, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA" + i, false).getFairShare() .getMemory() / nodeCapacity * 100, .9); } // Let app under childA1 complete. This should cause the fair share // of queue childA1 to be reset to zero,since the queue has no apps running. // Queue childA2's fair share would increase to 100% since its the only // active queue. AppAttemptRemovedSchedulerEvent appRemovedEvent1 = new AppAttemptRemovedSchedulerEvent( app1, RMAppAttemptState.FINISHED, false); scheduler.handle(appRemovedEvent1); scheduler.update(); assertEquals( 0, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA1", false).getFairShare() .getMemory() / nodeCapacity * 100, 0); assertEquals( 100, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA2", false).getFairShare() .getMemory() / nodeCapacity * 100, 0.1); verifySteadyFairShareMemory(scheduler.getQueueManager().getLeafQueues(), nodeCapacity); } @Test public void testFairShareWithDRFMultipleActiveQueuesUnderDifferentParent() throws IOException { int nodeMem = 16 * 1024; int nodeVCores = 10; createClusterWithQueuesAndOneNode(nodeMem, nodeVCores, "drf"); // Run apps in childA1,childA2 which are under parentA createSchedulingRequest(2 * 1024, "root.parentA.childA1", "user1"); createSchedulingRequest(3 * 1024, "root.parentA.childA2", "user2"); // Run app in childB1 which is under parentB createSchedulingRequest(1 * 1024, "root.parentB.childB1", "user3"); // Run app in root.default queue createSchedulingRequest(1 * 1024, "root.default", "user4"); scheduler.update(); // The two active child queues under parentA would // get 80/2=40% memory and vcores for (int i = 1; i <= 2; i++) { assertEquals( 40, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA" + i, false).getFairShare() .getMemory() / nodeMem * 100, .9); assertEquals( 40, (double) scheduler.getQueueManager() .getLeafQueue("root.parentA.childA" + i, false).getFairShare() .getVirtualCores() / nodeVCores * 100, .9); } // The only active child queue under parentB would get 10% memory and vcores assertEquals( 10, (double) scheduler.getQueueManager() .getLeafQueue("root.parentB.childB1", false).getFairShare() .getMemory() / nodeMem * 100, .9); assertEquals( 10, (double) scheduler.getQueueManager() .getLeafQueue("root.parentB.childB1", false).getFairShare() .getVirtualCores() / nodeVCores * 100, .9); Collection<FSLeafQueue> leafQueues = scheduler.getQueueManager() .getLeafQueues(); for (FSLeafQueue leaf : leafQueues) { if (leaf.getName().startsWith("root.parentA")) { assertEquals(0.2, (double) leaf.getSteadyFairShare().getMemory() / nodeMem, 0.001); assertEquals(0.2, (double) leaf.getSteadyFairShare().getVirtualCores() / nodeVCores, 0.001); } else if (leaf.getName().startsWith("root.parentB")) { assertEquals(0.05, (double) leaf.getSteadyFairShare().getMemory() / nodeMem, 0.001); assertEquals(0.1, (double) leaf.getSteadyFairShare().getVirtualCores() / nodeVCores, 0.001); } } } /** * Verify whether steady fair shares for all leaf queues still follow * their weight, not related to active/inactive status. * * @param leafQueues * @param nodeCapacity */ private void verifySteadyFairShareMemory(Collection<FSLeafQueue> leafQueues, int nodeCapacity) { for (FSLeafQueue leaf : leafQueues) { if (leaf.getName().startsWith("root.parentA")) { assertEquals(0.2, (double) leaf.getSteadyFairShare().getMemory() / nodeCapacity, 0.001); } else if (leaf.getName().startsWith("root.parentB")) { assertEquals(0.05, (double) leaf.getSteadyFairShare().getMemory() / nodeCapacity, 0.001); } } } }
13,051
35.155125
101
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/TestEmptyQueues.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.scheduler.fair.policies; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.Schedulable; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.SchedulingPolicy; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; public class TestEmptyQueues { private Collection<? extends Schedulable> schedulables; @Before public void setup() { schedulables = new ArrayList<Schedulable>(); } private void testComputeShares(SchedulingPolicy policy) { policy.computeShares(schedulables, Resources.none()); } @Test (timeout = 1000) public void testFifoPolicy() { testComputeShares(SchedulingPolicy.getInstance(FifoPolicy.class)); } @Test (timeout = 1000) public void testFairSharePolicy() { testComputeShares(SchedulingPolicy.getInstance(FairSharePolicy.class)); } @Test (timeout = 1000) public void testDRFPolicy() { testComputeShares( SchedulingPolicy.getInstance(DominantResourceFairnessPolicy.class)); } }
1,959
32.793103
85
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/TestDominantResourceFairnessPolicy.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.scheduler.fair.policies; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Comparator; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceType; import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FakeSchedulable; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.Schedulable; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Test; /** * comparator.compare(sched1, sched2) < 0 means that sched1 should get a * container before sched2 */ public class TestDominantResourceFairnessPolicy { private Comparator<Schedulable> createComparator(int clusterMem, int clusterCpu) { DominantResourceFairnessPolicy policy = new DominantResourceFairnessPolicy(); policy.initialize(BuilderUtils.newResource(clusterMem, clusterCpu)); return policy.getComparator(); } private Schedulable createSchedulable(int memUsage, int cpuUsage) { return createSchedulable(memUsage, cpuUsage, ResourceWeights.NEUTRAL, 0, 0); } private Schedulable createSchedulable(int memUsage, int cpuUsage, int minMemShare, int minCpuShare) { return createSchedulable(memUsage, cpuUsage, ResourceWeights.NEUTRAL, minMemShare, minCpuShare); } private Schedulable createSchedulable(int memUsage, int cpuUsage, ResourceWeights weights) { return createSchedulable(memUsage, cpuUsage, weights, 0, 0); } private Schedulable createSchedulable(int memUsage, int cpuUsage, ResourceWeights weights, int minMemShare, int minCpuShare) { Resource usage = BuilderUtils.newResource(memUsage, cpuUsage); Resource minShare = BuilderUtils.newResource(minMemShare, minCpuShare); return new FakeSchedulable(minShare, Resources.createResource(Integer.MAX_VALUE, Integer.MAX_VALUE), weights, Resources.none(), usage, 0l); } @Test public void testSameDominantResource() { assertTrue(createComparator(8000, 4).compare( createSchedulable(1000, 1), createSchedulable(2000, 1)) < 0); } @Test public void testDifferentDominantResource() { assertTrue(createComparator(8000, 8).compare( createSchedulable(4000, 3), createSchedulable(2000, 5)) < 0); } @Test public void testOneIsNeedy() { assertTrue(createComparator(8000, 8).compare( createSchedulable(2000, 5, 0, 6), createSchedulable(4000, 3, 0, 0)) < 0); } @Test public void testBothAreNeedy() { assertTrue(createComparator(8000, 100).compare( // dominant share is 2000/8000 createSchedulable(2000, 5), // dominant share is 4000/8000 createSchedulable(4000, 3)) < 0); assertTrue(createComparator(8000, 100).compare( // dominant min share is 2/3 createSchedulable(2000, 5, 3000, 6), // dominant min share is 4/5 createSchedulable(4000, 3, 5000, 4)) < 0); } @Test public void testEvenWeightsSameDominantResource() { assertTrue(createComparator(8000, 8).compare( createSchedulable(3000, 1, new ResourceWeights(2.0f)), createSchedulable(2000, 1)) < 0); assertTrue(createComparator(8000, 8).compare( createSchedulable(1000, 3, new ResourceWeights(2.0f)), createSchedulable(1000, 2)) < 0); } @Test public void testEvenWeightsDifferentDominantResource() { assertTrue(createComparator(8000, 8).compare( createSchedulable(1000, 3, new ResourceWeights(2.0f)), createSchedulable(2000, 1)) < 0); assertTrue(createComparator(8000, 8).compare( createSchedulable(3000, 1, new ResourceWeights(2.0f)), createSchedulable(1000, 2)) < 0); } @Test public void testUnevenWeightsSameDominantResource() { assertTrue(createComparator(8000, 8).compare( createSchedulable(3000, 1, new ResourceWeights(2.0f, 1.0f)), createSchedulable(2000, 1)) < 0); assertTrue(createComparator(8000, 8).compare( createSchedulable(1000, 3, new ResourceWeights(1.0f, 2.0f)), createSchedulable(1000, 2)) < 0); } @Test public void testUnevenWeightsDifferentDominantResource() { assertTrue(createComparator(8000, 8).compare( createSchedulable(1000, 3, new ResourceWeights(1.0f, 2.0f)), createSchedulable(2000, 1)) < 0); assertTrue(createComparator(8000, 8).compare( createSchedulable(3000, 1, new ResourceWeights(2.0f, 1.0f)), createSchedulable(1000, 2)) < 0); } @Test public void testCalculateShares() { Resource used = Resources.createResource(10, 5); Resource capacity = Resources.createResource(100, 10); ResourceType[] resourceOrder = new ResourceType[2]; ResourceWeights shares = new ResourceWeights(); DominantResourceFairnessPolicy.DominantResourceFairnessComparator comparator = new DominantResourceFairnessPolicy.DominantResourceFairnessComparator(); comparator.calculateShares(used, capacity, shares, resourceOrder, ResourceWeights.NEUTRAL); assertEquals(.1, shares.getWeight(ResourceType.MEMORY), .00001); assertEquals(.5, shares.getWeight(ResourceType.CPU), .00001); assertEquals(ResourceType.CPU, resourceOrder[0]); assertEquals(ResourceType.MEMORY, resourceOrder[1]); } }
6,355
37.756098
84
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservations.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.HashMap; import java.util.Map; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerImpl; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Before; import org.junit.Test; public class TestReservations { private static final Log LOG = LogFactory.getLog(TestReservations.class); private final RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); RMContext rmContext; RMContext spyRMContext; CapacityScheduler cs; // CapacitySchedulerConfiguration csConf; CapacitySchedulerContext csContext; private final ResourceCalculator resourceCalculator = new DefaultResourceCalculator(); CSQueue root; Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); Map<String, CSQueue> oldQueues = new HashMap<String, CSQueue>(); final static int GB = 1024; final static String DEFAULT_RACK = "/default"; @Before public void setUp() throws Exception { CapacityScheduler spyCs = new CapacityScheduler(); cs = spy(spyCs); rmContext = TestUtils.getMockRMContext(); } private void setup(CapacitySchedulerConfiguration csConf) throws Exception { csConf.setBoolean("yarn.scheduler.capacity.user-metrics.enable", true); final String newRoot = "root" + System.currentTimeMillis(); // final String newRoot = "root"; setupQueueConfiguration(csConf, newRoot); YarnConfiguration conf = new YarnConfiguration(); cs.setConf(conf); csContext = mock(CapacitySchedulerContext.class); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getConf()).thenReturn(conf); when(csContext.getMinimumResourceCapability()).thenReturn( Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(16 * GB, 12)); when(csContext.getClusterResource()).thenReturn( Resources.createResource(100 * 16 * GB, 100 * 12)); when(csContext.getApplicationComparator()).thenReturn( CapacityScheduler.applicationComparator); when(csContext.getNonPartitionedQueueComparator()).thenReturn( CapacityScheduler.nonPartitionedQueueComparator); when(csContext.getResourceCalculator()).thenReturn(resourceCalculator); when(csContext.getRMContext()).thenReturn(rmContext); RMContainerTokenSecretManager containerTokenSecretManager = new RMContainerTokenSecretManager( conf); containerTokenSecretManager.rollMasterKey(); when(csContext.getContainerTokenSecretManager()).thenReturn( containerTokenSecretManager); root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); spyRMContext = spy(rmContext); when(spyRMContext.getScheduler()).thenReturn(cs); when(spyRMContext.getYarnConfiguration()) .thenReturn(new YarnConfiguration()); cs.setRMContext(spyRMContext); cs.init(csConf); cs.start(); when(cs.getNumClusterNodes()).thenReturn(3); } private static final String A = "a"; private void setupQueueConfiguration(CapacitySchedulerConfiguration conf, final String newRoot) { // Define top-level queues conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] { newRoot }); conf.setMaximumCapacity(CapacitySchedulerConfiguration.ROOT, 100); conf.setAcl(CapacitySchedulerConfiguration.ROOT, QueueACL.SUBMIT_APPLICATIONS, " "); final String Q_newRoot = CapacitySchedulerConfiguration.ROOT + "." + newRoot; conf.setQueues(Q_newRoot, new String[] { A }); conf.setCapacity(Q_newRoot, 100); conf.setMaximumCapacity(Q_newRoot, 100); conf.setAcl(Q_newRoot, QueueACL.SUBMIT_APPLICATIONS, " "); final String Q_A = Q_newRoot + "." + A; conf.setCapacity(Q_A, 100f); conf.setMaximumCapacity(Q_A, 100); conf.setAcl(Q_A, QueueACL.SUBMIT_APPLICATIONS, "*"); } static LeafQueue stubLeafQueue(LeafQueue queue) { return queue; } @Test public void testReservation() throws Exception { // Test that we now unreserve and use a node that has space CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); rmContext.getRMApps().put(app_0.getApplicationId(), mock(RMApp.class)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); String host_2 = "host_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, DEFAULT_RACK, 0, 8 * GB); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); when(csContext.getNode(node_2.getNodeID())).thenReturn(node_2); cs.getAllNodes().put(node_0.getNodeID(), node_0); cs.getAllNodes().put(node_1.getNodeID(), node_1); cs.getAllNodes().put(node_2.getNodeID(), node_2); final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (8 * GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priorityAM = TestUtils.createMockPriority(1); Priority priorityMap = TestUtils.createMockPriority(5); Priority priorityReduce = TestUtils.createMockPriority(10); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 2 * GB, 1, true, priorityAM, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 5 * GB, 2, true, priorityReduce, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 3 * GB, 2, true, priorityMap, recordFactory))); // Start testing... // Only AM a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2 * GB, a.getUsedResources().getMemory()); assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(2 * GB, a.getMetrics().getAllocatedMB()); assertEquals(22 * GB, a.getMetrics().getAvailableMB()); assertEquals(2 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // Only 1 map - simulating reduce a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5 * GB, a.getUsedResources().getMemory()); assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(5 * GB, a.getMetrics().getAllocatedMB()); assertEquals(19 * GB, a.getMetrics().getAvailableMB()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // Only 1 map to other node - simulating reduce a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(16 * GB, a.getMetrics().getAvailableMB()); assertEquals(16 * GB, app_0.getHeadroom().getMemory()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); assertEquals(2, app_0.getTotalRequiredResources(priorityReduce)); // try to assign reducer (5G on node 0 and should reserve) a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(11 * GB, a.getMetrics().getAvailableMB()); assertEquals(11 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getReservedContainer().getReservedResource() .getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); assertEquals(2, app_0.getTotalRequiredResources(priorityReduce)); // assign reducer to node 2 a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(18 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(6 * GB, a.getMetrics().getAvailableMB()); assertEquals(6 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getReservedContainer().getReservedResource() .getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); assertEquals(1, app_0.getTotalRequiredResources(priorityReduce)); // node_1 heartbeat and unreserves from node_0 in order to allocate // on node_1 a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(18 * GB, a.getUsedResources().getMemory()); assertEquals(18 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(18 * GB, a.getMetrics().getAllocatedMB()); assertEquals(6 * GB, a.getMetrics().getAvailableMB()); assertEquals(6 * GB, app_0.getHeadroom().getMemory()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(8 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); assertEquals(0, app_0.getTotalRequiredResources(priorityReduce)); } @Test public void testReservationNoContinueLook() throws Exception { // Test that with reservations-continue-look-all-nodes feature off // we don't unreserve and show we could get stuck queues = new HashMap<String, CSQueue>(); // test that the deadlock occurs when turned off CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); csConf.setBoolean( "yarn.scheduler.capacity.reservations-continue-look-all-nodes", false); setup(csConf); // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); rmContext.getRMApps().put(app_0.getApplicationId(), mock(RMApp.class)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); String host_2 = "host_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, DEFAULT_RACK, 0, 8 * GB); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); when(csContext.getNode(node_2.getNodeID())).thenReturn(node_2); final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (8 * GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priorityAM = TestUtils.createMockPriority(1); Priority priorityMap = TestUtils.createMockPriority(5); Priority priorityReduce = TestUtils.createMockPriority(10); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 2 * GB, 1, true, priorityAM, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 5 * GB, 2, true, priorityReduce, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 3 * GB, 2, true, priorityMap, recordFactory))); // Start testing... // Only AM a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2 * GB, a.getUsedResources().getMemory()); assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(2 * GB, a.getMetrics().getAllocatedMB()); assertEquals(22 * GB, a.getMetrics().getAvailableMB()); assertEquals(2 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // Only 1 map - simulating reduce a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5 * GB, a.getUsedResources().getMemory()); assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(5 * GB, a.getMetrics().getAllocatedMB()); assertEquals(19 * GB, a.getMetrics().getAvailableMB()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // Only 1 map to other node - simulating reduce a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(16 * GB, a.getMetrics().getAvailableMB()); assertEquals(16 * GB, app_0.getHeadroom().getMemory()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); assertEquals(2, app_0.getTotalRequiredResources(priorityReduce)); // try to assign reducer (5G on node 0 and should reserve) a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(11 * GB, a.getMetrics().getAvailableMB()); assertEquals(11 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getReservedContainer().getReservedResource() .getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); assertEquals(2, app_0.getTotalRequiredResources(priorityReduce)); // assign reducer to node 2 a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(18 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(6 * GB, a.getMetrics().getAvailableMB()); assertEquals(6 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getReservedContainer().getReservedResource() .getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); assertEquals(1, app_0.getTotalRequiredResources(priorityReduce)); // node_1 heartbeat and won't unreserve from node_0, potentially stuck // if AM doesn't handle a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(18 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(6 * GB, a.getMetrics().getAvailableMB()); assertEquals(6 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getReservedContainer().getReservedResource() .getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); assertEquals(1, app_0.getTotalRequiredResources(priorityReduce)); } @Test public void testAssignContainersNeedToUnreserve() throws Exception { // Test that we now unreserve and use a node that has space CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); rmContext.getRMApps().put(app_0.getApplicationId(), mock(RMApp.class)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); cs.getAllNodes().put(node_0.getNodeID(), node_0); cs.getAllNodes().put(node_1.getNodeID(), node_1); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (8 * GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priorityAM = TestUtils.createMockPriority(1); Priority priorityMap = TestUtils.createMockPriority(5); Priority priorityReduce = TestUtils.createMockPriority(10); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 2 * GB, 1, true, priorityAM, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 5 * GB, 2, true, priorityReduce, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 3 * GB, 2, true, priorityMap, recordFactory))); // Start testing... // Only AM a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2 * GB, a.getUsedResources().getMemory()); assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(2 * GB, a.getMetrics().getAllocatedMB()); assertEquals(14 * GB, a.getMetrics().getAvailableMB()); assertEquals(2 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); // Only 1 map - simulating reduce a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5 * GB, a.getUsedResources().getMemory()); assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(5 * GB, a.getMetrics().getAllocatedMB()); assertEquals(11 * GB, a.getMetrics().getAvailableMB()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); // Only 1 map to other node - simulating reduce a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(8 * GB, a.getMetrics().getAvailableMB()); assertEquals(8 * GB, app_0.getHeadroom().getMemory()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(2, app_0.getTotalRequiredResources(priorityReduce)); // try to assign reducer (5G on node 0 and should reserve) a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(3 * GB, a.getMetrics().getAvailableMB()); assertEquals(3 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getReservedContainer().getReservedResource() .getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(2, app_0.getTotalRequiredResources(priorityReduce)); // could allocate but told need to unreserve first CSAssignment csAssignment = a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(3 * GB, a.getMetrics().getAvailableMB()); assertEquals(3 * GB, app_0.getHeadroom().getMemory()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(8 * GB, node_1.getUsedResource().getMemory()); assertEquals(1, app_0.getTotalRequiredResources(priorityReduce)); } @Test public void testGetAppToUnreserve() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); final String user_0 = "user_0"; final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); Resource clusterResource = Resources.createResource(2 * 8 * GB); // Setup resource-requests Priority priorityMap = TestUtils.createMockPriority(5); Resource capability = Resources.createResource(2*GB, 0); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); SystemMetricsPublisher publisher = mock(SystemMetricsPublisher.class); RMContext rmContext = mock(RMContext.class); ContainerAllocationExpirer expirer = mock(ContainerAllocationExpirer.class); DrainDispatcher drainDispatcher = new DrainDispatcher(); when(rmContext.getContainerAllocationExpirer()).thenReturn(expirer); when(rmContext.getDispatcher()).thenReturn(drainDispatcher); when(rmContext.getRMApplicationHistoryWriter()).thenReturn(writer); when(rmContext.getSystemMetricsPublisher()).thenReturn(publisher); when(rmContext.getYarnConfiguration()).thenReturn(new YarnConfiguration()); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId( app_0.getApplicationId(), 1); ContainerId containerId = BuilderUtils.newContainerId(appAttemptId, 1); Container container = TestUtils.getMockContainer(containerId, node_1.getNodeID(), Resources.createResource(2*GB), priorityMap); RMContainer rmContainer = new RMContainerImpl(container, appAttemptId, node_1.getNodeID(), "user", rmContext); Container container_1 = TestUtils.getMockContainer(containerId, node_0.getNodeID(), Resources.createResource(1*GB), priorityMap); RMContainer rmContainer_1 = new RMContainerImpl(container_1, appAttemptId, node_0.getNodeID(), "user", rmContext); // no reserved containers NodeId unreserveId = app_0.getNodeIdToUnreserve(priorityMap, capability, cs.getResourceCalculator(), clusterResource); assertEquals(null, unreserveId); // no reserved containers - reserve then unreserve app_0.reserve(node_0, priorityMap, rmContainer_1, container_1); app_0.unreserve(node_0, priorityMap); unreserveId = app_0.getNodeIdToUnreserve(priorityMap, capability, cs.getResourceCalculator(), clusterResource); assertEquals(null, unreserveId); // no container large enough is reserved app_0.reserve(node_0, priorityMap, rmContainer_1, container_1); unreserveId = app_0.getNodeIdToUnreserve(priorityMap, capability, cs.getResourceCalculator(), clusterResource); assertEquals(null, unreserveId); // reserve one that is now large enough app_0.reserve(node_1, priorityMap, rmContainer, container); unreserveId = app_0.getNodeIdToUnreserve(priorityMap, capability, cs.getResourceCalculator(), clusterResource); assertEquals(node_1.getNodeID(), unreserveId); } @Test public void testFindNodeToUnreserve() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); final String user_0 = "user_0"; final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); // Setup resource-requests Priority priorityMap = TestUtils.createMockPriority(5); Resource capability = Resources.createResource(2 * GB, 0); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); SystemMetricsPublisher publisher = mock(SystemMetricsPublisher.class); RMContext rmContext = mock(RMContext.class); ContainerAllocationExpirer expirer = mock(ContainerAllocationExpirer.class); DrainDispatcher drainDispatcher = new DrainDispatcher(); when(rmContext.getContainerAllocationExpirer()).thenReturn(expirer); when(rmContext.getDispatcher()).thenReturn(drainDispatcher); when(rmContext.getRMApplicationHistoryWriter()).thenReturn(writer); when(rmContext.getSystemMetricsPublisher()).thenReturn(publisher); when(rmContext.getYarnConfiguration()).thenReturn(new YarnConfiguration()); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId( app_0.getApplicationId(), 1); ContainerId containerId = BuilderUtils.newContainerId(appAttemptId, 1); Container container = TestUtils.getMockContainer(containerId, node_1.getNodeID(), Resources.createResource(2*GB), priorityMap); RMContainer rmContainer = new RMContainerImpl(container, appAttemptId, node_1.getNodeID(), "user", rmContext); // nothing reserved RMContainer toUnreserveContainer = app_0.findNodeToUnreserve(csContext.getClusterResource(), node_1, priorityMap, capability); assertTrue(toUnreserveContainer == null); // reserved but scheduler doesn't know about that node. app_0.reserve(node_1, priorityMap, rmContainer, container); node_1.reserveResource(app_0, priorityMap, rmContainer); toUnreserveContainer = app_0.findNodeToUnreserve(csContext.getClusterResource(), node_1, priorityMap, capability); assertTrue(toUnreserveContainer == null); } @Test public void testAssignToQueue() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); rmContext.getRMApps().put(app_0.getApplicationId(), mock(RMApp.class)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); String host_2 = "host_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, DEFAULT_RACK, 0, 8 * GB); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); when(csContext.getNode(node_2.getNodeID())).thenReturn(node_2); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (8 * GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priorityAM = TestUtils.createMockPriority(1); Priority priorityMap = TestUtils.createMockPriority(5); Priority priorityReduce = TestUtils.createMockPriority(10); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 2 * GB, 1, true, priorityAM, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 5 * GB, 2, true, priorityReduce, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 3 * GB, 2, true, priorityMap, recordFactory))); // Start testing... // Only AM a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2 * GB, a.getUsedResources().getMemory()); assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(2 * GB, a.getMetrics().getAllocatedMB()); assertEquals(14 * GB, a.getMetrics().getAvailableMB()); assertEquals(2 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); // Only 1 map - simulating reduce a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5 * GB, a.getUsedResources().getMemory()); assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(5 * GB, a.getMetrics().getAllocatedMB()); assertEquals(11 * GB, a.getMetrics().getAvailableMB()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); // Only 1 map to other node - simulating reduce a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(8 * GB, a.getMetrics().getAvailableMB()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); // now add in reservations and make sure it continues if config set // allocate to queue so that the potential new capacity is greater then // absoluteMaxCapacity a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(3 * GB, a.getMetrics().getAvailableMB()); assertEquals(3 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); ResourceLimits limits = new ResourceLimits(Resources.createResource(13 * GB)); boolean res = a.canAssignToThisQueue(Resources.createResource(13 * GB), RMNodeLabelsManager.NO_LABEL, limits, Resources.createResource(3 * GB), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertTrue(res); // 16GB total, 13GB consumed (8 allocated, 5 reserved). asking for 5GB so we would have to // unreserve 2GB to get the total 5GB needed. // also note vcore checks not enabled assertEquals(0, limits.getHeadroom().getMemory()); refreshQueuesTurnOffReservationsContLook(a, csConf); // should return false since reservations continue look is off. limits = new ResourceLimits(Resources.createResource(13 * GB)); res = a.canAssignToThisQueue(Resources.createResource(13 * GB), RMNodeLabelsManager.NO_LABEL, limits, Resources.createResource(3 * GB), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertFalse(res); } public void refreshQueuesTurnOffReservationsContLook(LeafQueue a, CapacitySchedulerConfiguration csConf) throws Exception { // before reinitialization assertEquals(true, a.getReservationContinueLooking()); assertEquals(true, ((ParentQueue) a.getParent()).getReservationContinueLooking()); csConf.setBoolean( CapacitySchedulerConfiguration.RESERVE_CONT_LOOK_ALL_NODES, false); Map<String, CSQueue> newQueues = new HashMap<String, CSQueue>(); CSQueue newRoot = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, newQueues, queues, TestUtils.spyHook); queues = newQueues; root.reinitialize(newRoot, cs.getClusterResource()); // after reinitialization assertEquals(false, a.getReservationContinueLooking()); assertEquals(false, ((ParentQueue) a.getParent()).getReservationContinueLooking()); } @Test public void testContinueLookingReservationsAfterQueueRefresh() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); // Manipulate queue 'e' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); refreshQueuesTurnOffReservationsContLook(a, csConf); } @Test public void testAssignToUser() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); rmContext.getRMApps().put(app_0.getApplicationId(), mock(RMApp.class)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); String host_2 = "host_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, DEFAULT_RACK, 0, 8 * GB); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); when(csContext.getNode(node_2.getNodeID())).thenReturn(node_2); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (8 * GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priorityAM = TestUtils.createMockPriority(1); Priority priorityMap = TestUtils.createMockPriority(5); Priority priorityReduce = TestUtils.createMockPriority(10); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 2 * GB, 1, true, priorityAM, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 3 * GB, 2, true, priorityMap, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 5 * GB, 2, true, priorityReduce, recordFactory))); // Start testing... // Only AM a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2 * GB, a.getUsedResources().getMemory()); assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(2 * GB, a.getMetrics().getAllocatedMB()); assertEquals(14 * GB, a.getMetrics().getAvailableMB()); assertEquals(2 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); // Only 1 map - simulating reduce a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5 * GB, a.getUsedResources().getMemory()); assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(5 * GB, a.getMetrics().getAllocatedMB()); assertEquals(11 * GB, a.getMetrics().getAvailableMB()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); // Only 1 map to other node - simulating reduce a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(8 * GB, a.getMetrics().getAvailableMB()); assertEquals(null, node_0.getReservedContainer()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); // now add in reservations and make sure it continues if config set // allocate to queue so that the potential new capacity is greater then // absoluteMaxCapacity a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(5 * GB, app_0.getCurrentReservation().getMemory()); assertEquals(5 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(3 * GB, a.getMetrics().getAvailableMB()); assertEquals(3 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); // not over the limit Resource limit = Resources.createResource(14 * GB, 0); ResourceLimits userResourceLimits = new ResourceLimits(clusterResource); boolean res = a.canAssignToUser(clusterResource, user_0, limit, app_0, "", userResourceLimits); assertTrue(res); assertEquals(Resources.none(), userResourceLimits.getAmountNeededUnreserve()); // set limit so it subtracts reservations and it can continue limit = Resources.createResource(12 * GB, 0); userResourceLimits = new ResourceLimits(clusterResource); res = a.canAssignToUser(clusterResource, user_0, limit, app_0, "", userResourceLimits); assertTrue(res); // limit set to 12GB, we are using 13GB (8 allocated, 5 reserved), to get under limit // we need to unreserve 1GB // also note vcore checks not enabled assertEquals(Resources.createResource(1 * GB, 4), userResourceLimits.getAmountNeededUnreserve()); refreshQueuesTurnOffReservationsContLook(a, csConf); userResourceLimits = new ResourceLimits(clusterResource); // should now return false since feature off res = a.canAssignToUser(clusterResource, user_0, limit, app_0, "", userResourceLimits); assertFalse(res); assertEquals(Resources.none(), userResourceLimits.getAmountNeededUnreserve()); } @Test public void testReservationsNoneAvailable() throws Exception { // Test that we now unreserve and use a node that has space CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setup(csConf); // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(A)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); rmContext.getRMApps().put(app_0.getApplicationId(), mock(RMApp.class)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes String host_0 = "host_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); String host_1 = "host_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8 * GB); String host_2 = "host_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, DEFAULT_RACK, 0, 8 * GB); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); when(csContext.getNode(node_2.getNodeID())).thenReturn(node_2); final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (8 * GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priorityAM = TestUtils.createMockPriority(1); Priority priorityMap = TestUtils.createMockPriority(5); Priority priorityReduce = TestUtils.createMockPriority(10); Priority priorityLast = TestUtils.createMockPriority(12); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 2 * GB, 1, true, priorityAM, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 3 * GB, 2, true, priorityMap, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 5 * GB, 1, true, priorityReduce, recordFactory))); app_0.updateResourceRequests(Collections.singletonList(TestUtils .createResourceRequest(ResourceRequest.ANY, 8 * GB, 2, true, priorityLast, recordFactory))); // Start testing... // Only AM a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2 * GB, a.getUsedResources().getMemory()); assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(2 * GB, a.getMetrics().getAllocatedMB()); assertEquals(22 * GB, a.getMetrics().getAvailableMB()); assertEquals(2 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // Only 1 map - simulating reduce a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5 * GB, a.getUsedResources().getMemory()); assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(5 * GB, a.getMetrics().getAllocatedMB()); assertEquals(19 * GB, a.getMetrics().getAvailableMB()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(0 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // Only 1 map to other node - simulating reduce a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(16 * GB, a.getMetrics().getAvailableMB()); assertEquals(16 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // try to assign reducer (5G on node 0), but tell it's resource limits < // used (8G) + required (5G). It will not reserved since it has to unreserve // some resource. Even with continous reservation looking, we don't allow // unreserve resource to reserve container. a.assignContainers(clusterResource, node_0, new ResourceLimits(Resources.createResource(10 * GB)), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(16 * GB, a.getMetrics().getAvailableMB()); // app_0's headroom = limit (10G) - used (8G) = 2G assertEquals(2 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // try to assign reducer (5G on node 0), but tell it's resource limits < // used (8G) + required (5G). It will not reserved since it has to unreserve // some resource. Unfortunately, there's nothing to unreserve. a.assignContainers(clusterResource, node_2, new ResourceLimits(Resources.createResource(10 * GB)), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8 * GB, a.getUsedResources().getMemory()); assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(8 * GB, a.getMetrics().getAllocatedMB()); assertEquals(16 * GB, a.getMetrics().getAvailableMB()); // app_0's headroom = limit (10G) - used (8G) = 2G assertEquals(2 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(0 * GB, node_2.getUsedResource().getMemory()); // let it assign 5G to node_2 a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(13 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(11 * GB, a.getMetrics().getAvailableMB()); assertEquals(11 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); // reserve 8G node_0 a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(21 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(8 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(3 * GB, a.getMetrics().getAvailableMB()); assertEquals(3 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); // try to assign (8G on node 2). No room to allocate, // continued to try due to having reservation above, // but hits queue limits so can't reserve anymore. a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(21 * GB, a.getUsedResources().getMemory()); assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); assertEquals(8 * GB, a.getMetrics().getReservedMB()); assertEquals(13 * GB, a.getMetrics().getAllocatedMB()); assertEquals(3 * GB, a.getMetrics().getAvailableMB()); assertEquals(3 * GB, app_0.getHeadroom().getMemory()); assertEquals(5 * GB, node_0.getUsedResource().getMemory()); assertEquals(3 * GB, node_1.getUsedResource().getMemory()); assertEquals(5 * GB, node_2.getUsedResource().getMemory()); } }
58,576
46.662327
109
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservationQueue.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerDynamicEditException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.QueueEntitlement; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Before; import org.junit.Test; public class TestReservationQueue { CapacitySchedulerConfiguration csConf; CapacitySchedulerContext csContext; final static int DEF_MAX_APPS = 10000; final static int GB = 1024; private final ResourceCalculator resourceCalculator = new DefaultResourceCalculator(); ReservationQueue reservationQueue; @Before public void setup() throws IOException { // setup a context / conf csConf = new CapacitySchedulerConfiguration(); YarnConfiguration conf = new YarnConfiguration(); csContext = mock(CapacitySchedulerContext.class); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getConf()).thenReturn(conf); when(csContext.getMinimumResourceCapability()).thenReturn( Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(16 * GB, 32)); when(csContext.getClusterResource()).thenReturn( Resources.createResource(100 * 16 * GB, 100 * 32)); when(csContext.getResourceCalculator()).thenReturn(resourceCalculator); RMContext mockRMContext = TestUtils.getMockRMContext(); when(csContext.getRMContext()).thenReturn(mockRMContext); // create a queue PlanQueue pq = new PlanQueue(csContext, "root", null, null); reservationQueue = new ReservationQueue(csContext, "a", pq); } private void validateReservationQueue(double capacity) { assertTrue(" actual capacity: " + reservationQueue.getCapacity(), reservationQueue.getCapacity() - capacity < CSQueueUtils.EPSILON); assertEquals(reservationQueue.maxApplications, DEF_MAX_APPS); assertEquals(reservationQueue.maxApplicationsPerUser, DEF_MAX_APPS); } @Test public void testAddSubtractCapacity() throws Exception { // verify that setting, adding, subtracting capacity works reservationQueue.setCapacity(1.0F); validateReservationQueue(1); reservationQueue.setEntitlement(new QueueEntitlement(0.9f, 1f)); validateReservationQueue(0.9); reservationQueue.setEntitlement(new QueueEntitlement(1f, 1f)); validateReservationQueue(1); reservationQueue.setEntitlement(new QueueEntitlement(0f, 1f)); validateReservationQueue(0); try { reservationQueue.setEntitlement(new QueueEntitlement(1.1f, 1f)); fail(); } catch (SchedulerDynamicEditException iae) { // expected validateReservationQueue(1); } try { reservationQueue.setEntitlement(new QueueEntitlement(-0.1f, 1f)); fail(); } catch (SchedulerDynamicEditException iae) { // expected validateReservationQueue(1); } } }
4,290
37.657658
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestQueueCapacities.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.scheduler.capacity; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.api.records.Resource; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class TestQueueCapacities { private static final Log LOG = LogFactory.getLog(TestQueueCapacities.class); private String suffix; @Parameterized.Parameters public static Collection<String[]> getParameters() { return Arrays.asList(new String[][] { { "Capacity" }, { "AbsoluteCapacity" }, { "UsedCapacity" }, { "AbsoluteUsedCapacity" }, { "MaximumCapacity" }, { "AbsoluteMaximumCapacity" } }); } public TestQueueCapacities(String suffix) { this.suffix = suffix; } private static float get(QueueCapacities obj, String suffix, String label) throws Exception { return executeByName(obj, "get" + suffix, label, -1f); } private static void set(QueueCapacities obj, String suffix, String label, float value) throws Exception { executeByName(obj, "set" + suffix, label, value); } // Use reflection to avoid too much avoid code private static float executeByName(QueueCapacities obj, String methodName, String label, float value) throws Exception { // We have 4 kinds of method // 1. getXXX() : float // 2. getXXX(label) : float // 3. setXXX(float) : void // 4. setXXX(label, float) : void if (methodName.startsWith("get")) { float result; if (label == null) { // 1. Method method = QueueCapacities.class.getDeclaredMethod(methodName); result = (float) method.invoke(obj); } else { // 2. Method method = QueueCapacities.class.getDeclaredMethod(methodName, String.class); result = (float) method.invoke(obj, label); } return result; } else { if (label == null) { // 3. Method method = QueueCapacities.class.getDeclaredMethod(methodName, Float.TYPE); method.invoke(obj, value); } else { // 4. Method method = QueueCapacities.class.getDeclaredMethod(methodName, String.class, Float.TYPE); method.invoke(obj, label, value); } return -1f; } } private void internalTestModifyAndRead(String label) throws Exception { QueueCapacities qc = new QueueCapacities(false); // First get returns 0 always Assert.assertEquals(0f, get(qc, suffix, label), 1e-8); // Set to 1, and check set(qc, suffix, label, 1f); Assert.assertEquals(1f, get(qc, suffix, label), 1e-8); // Set to 2, and check set(qc, suffix, label, 2f); Assert.assertEquals(2f, get(qc, suffix, label), 1e-8); } void check(int mem, int cpu, Resource res) { Assert.assertEquals(mem, res.getMemory()); Assert.assertEquals(cpu, res.getVirtualCores()); } @Test public void testModifyAndRead() throws Exception { LOG.info("Test - " + suffix); internalTestModifyAndRead(null); internalTestModifyAndRead("label"); } }
4,140
31.606299
78
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestApplicationPriority.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl; 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.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNodeReport; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestApplicationPriority { private final int GB = 1024; private YarnConfiguration conf; @Before public void setUp() throws Exception { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); } @Test public void testApplicationOrderingWithPriority() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); LeafQueue q = (LeafQueue) cs.getQueue("default"); Assert.assertNotNull(q); String host = "127.0.0.1"; RMNode node = MockNodes.newNodeInfo(0, MockNodes.newResource(16 * GB), 1, host); cs.handle(new NodeAddedSchedulerEvent(node)); // add app 1 start ApplicationId appId1 = BuilderUtils.newApplicationId(100, 1); ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId( appId1, 1); RMAppAttemptMetrics attemptMetric1 = new RMAppAttemptMetrics(appAttemptId1, rm.getRMContext()); RMAppImpl app1 = mock(RMAppImpl.class); when(app1.getApplicationId()).thenReturn(appId1); RMAppAttemptImpl attempt1 = mock(RMAppAttemptImpl.class); when(attempt1.getAppAttemptId()).thenReturn(appAttemptId1); when(attempt1.getRMAppAttemptMetrics()).thenReturn(attemptMetric1); when(app1.getCurrentAppAttempt()).thenReturn(attempt1); rm.getRMContext().getRMApps().put(appId1, app1); SchedulerEvent addAppEvent1 = new AppAddedSchedulerEvent(appId1, "default", "user", null, Priority.newInstance(5)); cs.handle(addAppEvent1); SchedulerEvent addAttemptEvent1 = new AppAttemptAddedSchedulerEvent( appAttemptId1, false); cs.handle(addAttemptEvent1); // add app1 end // add app2 begin ApplicationId appId2 = BuilderUtils.newApplicationId(100, 2); ApplicationAttemptId appAttemptId2 = BuilderUtils.newApplicationAttemptId( appId2, 1); RMAppAttemptMetrics attemptMetric2 = new RMAppAttemptMetrics(appAttemptId2, rm.getRMContext()); RMAppImpl app2 = mock(RMAppImpl.class); when(app2.getApplicationId()).thenReturn(appId2); RMAppAttemptImpl attempt2 = mock(RMAppAttemptImpl.class); when(attempt2.getAppAttemptId()).thenReturn(appAttemptId2); when(attempt2.getRMAppAttemptMetrics()).thenReturn(attemptMetric2); when(app2.getCurrentAppAttempt()).thenReturn(attempt2); rm.getRMContext().getRMApps().put(appId2, app2); SchedulerEvent addAppEvent2 = new AppAddedSchedulerEvent(appId2, "default", "user", null, Priority.newInstance(8)); cs.handle(addAppEvent2); SchedulerEvent addAttemptEvent2 = new AppAttemptAddedSchedulerEvent( appAttemptId2, false); cs.handle(addAttemptEvent2); // add app end // Now, the first assignment will be for app2 since app2 is of highest // priority assertEquals(q.getApplications().size(), 2); assertEquals(q.getApplications().iterator().next() .getApplicationAttemptId(), appAttemptId2); rm.stop(); } @Test public void testApplicationPriorityAllocation() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); // Set Max Application Priority as 10 conf.setInt(YarnConfiguration.MAX_CLUSTER_LEVEL_APPLICATION_PRIORITY, 10); MockRM rm = new MockRM(conf); rm.start(); Priority appPriority1 = Priority.newInstance(5); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 16 * GB); RMApp app1 = rm.submitApp(1 * GB, appPriority1); // kick the scheduler, 1 GB given to AM1, remaining 15GB on nm1 MockAM am1 = MockRM.launchAM(app1, rm, nm1); am1.registerAppAttempt(); // allocate 7 containers for App1 List<Container> allocated1 = am1.allocateAndWaitForContainers("127.0.0.1", 7, 2 * GB, nm1); Assert.assertEquals(7, allocated1.size()); Assert.assertEquals(2 * GB, allocated1.get(0).getResource().getMemory()); // check node report, 15 GB used (1 AM and 7 containers) and 1 GB available SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport( nm1.getNodeId()); Assert.assertEquals(15 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(1 * GB, report_nm1.getAvailableResource().getMemory()); // Submit the second app App2 with priority 8 (Higher than App1) Priority appPriority2 = Priority.newInstance(8); RMApp app2 = rm.submitApp(1 * GB, appPriority2); // kick the scheduler, 1 GB which was free is given to AM of App2 MockAM am2 = MockRM.launchAM(app2, rm, nm1); am2.registerAppAttempt(); // check node report, 16 GB used and 0 GB available report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(16 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(0 * GB, report_nm1.getAvailableResource().getMemory()); // get scheduler CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); // get scheduler app FiCaSchedulerApp schedulerAppAttempt = cs.getSchedulerApplications() .get(app1.getApplicationId()).getCurrentAppAttempt(); // kill 2 containers of App1 to free up some space int counter = 0; for (Container c : allocated1) { if (++counter > 2) { break; } cs.killContainer(schedulerAppAttempt.getRMContainer(c.getId())); } // check node report, 12 GB used and 4 GB available report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(12 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(4 * GB, report_nm1.getAvailableResource().getMemory()); // send updated request for App1 am1.allocate("127.0.0.1", 2 * GB, 10, new ArrayList<ContainerId>()); // kick the scheduler, since App2 priority is more than App1, it will get // remaining cluster space. List<Container> allocated2 = am2.allocateAndWaitForContainers("127.0.0.1", 2, 2 * GB, nm1); // App2 has got 2 containers now. Assert.assertEquals(2, allocated2.size()); // check node report, 16 GB used and 0 GB available report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(16 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(0 * GB, report_nm1.getAvailableResource().getMemory()); rm.stop(); } @Test public void testPriorityWithPendingApplications() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); // Set Max Application Priority as 10 conf.setInt(YarnConfiguration.MAX_CLUSTER_LEVEL_APPLICATION_PRIORITY, 10); MockRM rm = new MockRM(conf); rm.start(); Priority appPriority1 = Priority.newInstance(5); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 8 * GB); RMApp app1 = rm.submitApp(1 * GB, appPriority1); // kick the scheduler, 1 GB given to AM1, remaining 7GB on nm1 MockAM am1 = MockRM.launchAM(app1, rm, nm1); am1.registerAppAttempt(); // kick the scheduler, 7 containers will be allocated for App1 List<Container> allocated1 = am1.allocateAndWaitForContainers("127.0.0.1", 7, 1 * GB, nm1); Assert.assertEquals(7, allocated1.size()); Assert.assertEquals(1 * GB, allocated1.get(0).getResource().getMemory()); // check node report, 8 GB used (1 AM and 7 containers) and 0 GB available SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport( nm1.getNodeId()); Assert.assertEquals(8 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(0 * GB, report_nm1.getAvailableResource().getMemory()); // Submit the second app App2 with priority 7 Priority appPriority2 = Priority.newInstance(7); RMApp app2 = rm.submitApp(1 * GB, appPriority2); // Submit the third app App3 with priority 8 Priority appPriority3 = Priority.newInstance(8); RMApp app3 = rm.submitApp(1 * GB, appPriority3); // Submit the second app App4 with priority 6 Priority appPriority4 = Priority.newInstance(6); RMApp app4 = rm.submitApp(1 * GB, appPriority4); // Only one app can run as AM resource limit restricts it. Kill app1, // If app3 (highest priority among rest) gets active, it indicates that // priority is working with pendingApplications. rm.killApp(app1.getApplicationId()); // kick the scheduler, app3 (high among pending) gets free space MockAM am3 = MockRM.launchAM(app3, rm, nm1); am3.registerAppAttempt(); // check node report, 1 GB used and 7 GB available report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(1 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(7 * GB, report_nm1.getAvailableResource().getMemory()); rm.stop(); } @Test public void testMaxPriorityValidation() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); // Set Max Application Priority as 10 conf.setInt(YarnConfiguration.MAX_CLUSTER_LEVEL_APPLICATION_PRIORITY, 10); Priority maxPriority = Priority.newInstance(10); MockRM rm = new MockRM(conf); rm.start(); Priority appPriority1 = Priority.newInstance(15); rm.registerNode("127.0.0.1:1234", 8 * GB); RMApp app1 = rm.submitApp(1 * GB, appPriority1); // Application submission should be successful and verify priority Assert.assertEquals(app1.getApplicationSubmissionContext().getPriority(), maxPriority); rm.stop(); } }
12,841
40.292605
99
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CyclicBarrier; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; 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.scheduler.event.AppRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.policy.FairOrderingPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.policy.FifoOrderingPolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.policy.OrderingPolicy; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; public class TestLeafQueue { private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); RMContext rmContext; RMContext spyRMContext; ResourceRequest amResourceRequest; CapacityScheduler cs; CapacitySchedulerConfiguration csConf; CapacitySchedulerContext csContext; CSQueue root; Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); final static int GB = 1024; final static String DEFAULT_RACK = "/default"; private final ResourceCalculator resourceCalculator = new DefaultResourceCalculator(); @Before public void setUp() throws Exception { CapacityScheduler spyCs = new CapacityScheduler(); cs = spy(spyCs); rmContext = TestUtils.getMockRMContext(); spyRMContext = spy(rmContext); ConcurrentMap<ApplicationId, RMApp> spyApps = spy(new ConcurrentHashMap<ApplicationId, RMApp>()); RMApp rmApp = mock(RMApp.class); when(rmApp.getRMAppAttempt((ApplicationAttemptId)Matchers.any())).thenReturn(null); amResourceRequest = mock(ResourceRequest.class); when(amResourceRequest.getCapability()).thenReturn( Resources.createResource(0, 0)); when(rmApp.getAMResourceRequest()).thenReturn(amResourceRequest); Mockito.doReturn(rmApp).when(spyApps).get((ApplicationId)Matchers.any()); when(spyRMContext.getRMApps()).thenReturn(spyApps); csConf = new CapacitySchedulerConfiguration(); csConf.setBoolean("yarn.scheduler.capacity.user-metrics.enable", true); final String newRoot = "root" + System.currentTimeMillis(); setupQueueConfiguration(csConf, newRoot); YarnConfiguration conf = new YarnConfiguration(); cs.setConf(conf); csContext = mock(CapacitySchedulerContext.class); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getConf()).thenReturn(conf); when(csContext.getMinimumResourceCapability()). thenReturn(Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()). thenReturn(Resources.createResource(16*GB, 32)); when(csContext.getClusterResource()). thenReturn(Resources.createResource(100 * 16 * GB, 100 * 32)); when(csContext.getApplicationComparator()). thenReturn(CapacityScheduler.applicationComparator); when(csContext.getNonPartitionedQueueComparator()). thenReturn(CapacityScheduler.nonPartitionedQueueComparator); when(csContext.getResourceCalculator()). thenReturn(resourceCalculator); when(csContext.getRMContext()).thenReturn(rmContext); RMContainerTokenSecretManager containerTokenSecretManager = new RMContainerTokenSecretManager(conf); containerTokenSecretManager.rollMasterKey(); when(csContext.getContainerTokenSecretManager()).thenReturn( containerTokenSecretManager); root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); cs.setRMContext(spyRMContext); cs.init(csConf); cs.start(); when(spyRMContext.getScheduler()).thenReturn(cs); when(spyRMContext.getYarnConfiguration()) .thenReturn(new YarnConfiguration()); when(cs.getNumClusterNodes()).thenReturn(3); } private static final String A = "a"; private static final String B = "b"; private static final String C = "c"; private static final String C1 = "c1"; private static final String D = "d"; private static final String E = "e"; private void setupQueueConfiguration( CapacitySchedulerConfiguration conf, final String newRoot) { // Define top-level queues conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {newRoot}); conf.setMaximumCapacity(CapacitySchedulerConfiguration.ROOT, 100); conf.setAcl(CapacitySchedulerConfiguration.ROOT, QueueACL.SUBMIT_APPLICATIONS, " "); final String Q_newRoot = CapacitySchedulerConfiguration.ROOT + "." + newRoot; conf.setQueues(Q_newRoot, new String[] {A, B, C, D, E}); conf.setCapacity(Q_newRoot, 100); conf.setMaximumCapacity(Q_newRoot, 100); conf.setAcl(Q_newRoot, QueueACL.SUBMIT_APPLICATIONS, " "); final String Q_A = Q_newRoot + "." + A; conf.setCapacity(Q_A, 8.5f); conf.setMaximumCapacity(Q_A, 20); conf.setAcl(Q_A, QueueACL.SUBMIT_APPLICATIONS, "*"); final String Q_B = Q_newRoot + "." + B; conf.setCapacity(Q_B, 80); conf.setMaximumCapacity(Q_B, 99); conf.setAcl(Q_B, QueueACL.SUBMIT_APPLICATIONS, "*"); final String Q_C = Q_newRoot + "." + C; conf.setCapacity(Q_C, 1.5f); conf.setMaximumCapacity(Q_C, 10); conf.setAcl(Q_C, QueueACL.SUBMIT_APPLICATIONS, " "); conf.setQueues(Q_C, new String[] {C1}); final String Q_C1 = Q_C + "." + C1; conf.setCapacity(Q_C1, 100); final String Q_D = Q_newRoot + "." + D; conf.setCapacity(Q_D, 9); conf.setMaximumCapacity(Q_D, 11); conf.setAcl(Q_D, QueueACL.SUBMIT_APPLICATIONS, "user_d"); final String Q_E = Q_newRoot + "." + E; conf.setCapacity(Q_E, 1); conf.setMaximumCapacity(Q_E, 1); conf.setAcl(Q_E, QueueACL.SUBMIT_APPLICATIONS, "user_e"); } static LeafQueue stubLeafQueue(LeafQueue queue) { // Mock some methods for ease in these unit tests // 1. Stub out LeafQueue.parent.completedContainer CSQueue parent = queue.getParent(); doNothing().when(parent).completedContainer( any(Resource.class), any(FiCaSchedulerApp.class), any(FiCaSchedulerNode.class), any(RMContainer.class), any(ContainerStatus.class), any(RMContainerEventType.class), any(CSQueue.class), anyBoolean()); return queue; } @Test public void testInitializeQueue() throws Exception { final float epsilon = 1e-5f; //can add more sturdy test with 3-layer queues //once MAPREDUCE:3410 is resolved LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); assertEquals(0.085, a.getCapacity(), epsilon); assertEquals(0.085, a.getAbsoluteCapacity(), epsilon); assertEquals(0.2, a.getMaximumCapacity(), epsilon); assertEquals(0.2, a.getAbsoluteMaximumCapacity(), epsilon); LeafQueue b = stubLeafQueue((LeafQueue)queues.get(B)); assertEquals(0.80, b.getCapacity(), epsilon); assertEquals(0.80, b.getAbsoluteCapacity(), epsilon); assertEquals(0.99, b.getMaximumCapacity(), epsilon); assertEquals(0.99, b.getAbsoluteMaximumCapacity(), epsilon); ParentQueue c = (ParentQueue)queues.get(C); assertEquals(0.015, c.getCapacity(), epsilon); assertEquals(0.015, c.getAbsoluteCapacity(), epsilon); assertEquals(0.1, c.getMaximumCapacity(), epsilon); assertEquals(0.1, c.getAbsoluteMaximumCapacity(), epsilon); //Verify the value for getAMResourceLimit for queues with < .1 maxcap Resource clusterResource = Resource.newInstance(50 * GB, 50); a.updateClusterResource(clusterResource, new ResourceLimits(clusterResource)); assertEquals(Resource.newInstance(1 * GB, 1), a.getAMResourceLimit()); b.updateClusterResource(clusterResource, new ResourceLimits(clusterResource)); assertEquals(Resource.newInstance(5 * GB, 1), b.getAMResourceLimit()); } @Test public void testSingleQueueOneUserMetrics() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(B)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8*GB); final int numNodes = 1; Resource clusterResource = Resources.createResource(numNodes * (8*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 3, true, priority, recordFactory))); // Start testing... // Only 1 container a.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals( (int)(node_0.getTotalResource().getMemory() * a.getCapacity()) - (1*GB), a.getMetrics().getAvailableMB()); } @Test public void testUserQueueAcl() throws Exception { // Manipulate queue 'a' LeafQueue d = stubLeafQueue((LeafQueue) queues.get(D)); // Users final String user_d = "user_d"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 1); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_d, d, null, spyRMContext); d.submitApplicationAttempt(app_0, user_d); // Attempt the same application again final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(0, 2); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_d, d, null, spyRMContext); d.submitApplicationAttempt(app_1, user_d); // same user } @Test public void testPolicyConfiguration() throws Exception { CapacitySchedulerConfiguration testConf = new CapacitySchedulerConfiguration(); String tproot = CapacitySchedulerConfiguration.ROOT + "." + "testPolicyRoot" + System.currentTimeMillis(); OrderingPolicy<FiCaSchedulerApp> comPol = testConf.<FiCaSchedulerApp>getOrderingPolicy(tproot); } @Test public void testAppAttemptMetrics() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(B)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils .getMockApplicationAttemptId(0, 1); AppAddedSchedulerEvent addAppEvent = new AppAddedSchedulerEvent(appAttemptId_0.getApplicationId(), a.getQueueName(), user_0); cs.handle(addAppEvent); AppAttemptAddedSchedulerEvent addAttemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId_0, false); cs.handle(addAttemptEvent); AppAttemptRemovedSchedulerEvent event = new AppAttemptRemovedSchedulerEvent( appAttemptId_0, RMAppAttemptState.FAILED, false); cs.handle(event); assertEquals(0, a.getMetrics().getAppsPending()); assertEquals(0, a.getMetrics().getAppsFailed()); // Attempt the same application again final ApplicationAttemptId appAttemptId_1 = TestUtils .getMockApplicationAttemptId(0, 2); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, null, spyRMContext); app_1.setAMResource(Resource.newInstance(100, 1)); a.submitApplicationAttempt(app_1, user_0); // same user assertEquals(1, a.getMetrics().getAppsSubmitted()); assertEquals(1, a.getMetrics().getAppsPending()); assertEquals(1, a.getUser(user_0).getActiveApplications()); assertEquals(app_1.getAMResource().getMemory(), a.getMetrics() .getUsedAMResourceMB()); assertEquals(app_1.getAMResource().getVirtualCores(), a.getMetrics() .getUsedAMResourceVCores()); event = new AppAttemptRemovedSchedulerEvent(appAttemptId_0, RMAppAttemptState.FINISHED, false); cs.handle(event); AppRemovedSchedulerEvent rEvent = new AppRemovedSchedulerEvent( appAttemptId_0.getApplicationId(), RMAppState.FINISHED); cs.handle(rEvent); assertEquals(1, a.getMetrics().getAppsSubmitted()); assertEquals(0, a.getMetrics().getAppsPending()); assertEquals(0, a.getMetrics().getAppsFailed()); assertEquals(1, a.getMetrics().getAppsCompleted()); QueueMetrics userMetrics = a.getMetrics().getUserMetrics(user_0); assertEquals(1, userMetrics.getAppsSubmitted()); } @Test public void testFairConfiguration() throws Exception { CapacitySchedulerConfiguration testConf = new CapacitySchedulerConfiguration(); String tproot = CapacitySchedulerConfiguration.ROOT + "." + "testPolicyRoot" + System.currentTimeMillis(); OrderingPolicy<FiCaSchedulerApp> schedOrder = testConf.<FiCaSchedulerApp>getOrderingPolicy(tproot); //override default to fair String policyType = CapacitySchedulerConfiguration.PREFIX + tproot + "." + CapacitySchedulerConfiguration.ORDERING_POLICY; testConf.set(policyType, CapacitySchedulerConfiguration.FAIR_ORDERING_POLICY); schedOrder = testConf.<FiCaSchedulerApp>getOrderingPolicy(tproot); FairOrderingPolicy fop = (FairOrderingPolicy<FiCaSchedulerApp>) schedOrder; assertFalse(fop.getSizeBasedWeight()); //Now with sizeBasedWeight String sbwConfig = CapacitySchedulerConfiguration.PREFIX + tproot + "." + CapacitySchedulerConfiguration.ORDERING_POLICY + "." + FairOrderingPolicy.ENABLE_SIZE_BASED_WEIGHT; testConf.set(sbwConfig, "true"); schedOrder = testConf.<FiCaSchedulerApp>getOrderingPolicy(tproot); fop = (FairOrderingPolicy<FiCaSchedulerApp>) schedOrder; assertTrue(fop.getSizeBasedWeight()); } @Test public void testSingleQueueWithOneUser() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8*GB); final int numNodes = 1; Resource clusterResource = Resources.createResource(numNodes * (8*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 3, true, priority, recordFactory))); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); // Start testing... // Only 1 container a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(1*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(1*GB, a.getMetrics().getAllocatedMB()); assertEquals(0*GB, a.getMetrics().getAvailableMB()); // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also // you can get one container more than user-limit a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(2*GB, a.getMetrics().getAllocatedMB()); // Can't allocate 3rd due to user-limit a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(2*GB, a.getMetrics().getAllocatedMB()); // Bump up user-limit-factor, now allocate should work a.setUserLimitFactor(10); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(3*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(3*GB, a.getMetrics().getAllocatedMB()); // One more should work, for app_1, due to user-limit-factor a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(4*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(4*GB, a.getMetrics().getAllocatedMB()); // Test max-capacity // Now - no more allocs since we are at max-cap a.setMaxCapacity(0.5f); a.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(4*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(4*GB, a.getMetrics().getAllocatedMB()); // Release each container from app_0 for (RMContainer rmContainer : app_0.getLiveContainers()) { a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); } assertEquals(1*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(1*GB, a.getMetrics().getAllocatedMB()); // Release each container from app_1 for (RMContainer rmContainer : app_1.getLiveContainers()) { a.completedContainer(clusterResource, app_1, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); } assertEquals(0*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(0*GB, a.getMetrics().getAllocatedMB()); assertEquals((int)(a.getCapacity() * node_0.getTotalResource().getMemory()), a.getMetrics().getAvailableMB()); } @Test public void testUserLimits() throws Exception { // Mock the queue LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_1, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_2, user_1); // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8*GB); String host_1 = "127.0.0.2"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8*GB); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (8*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, priority, recordFactory))); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); /** * Start testing... */ // Set user-limit a.setUserLimit(50); a.setUserLimitFactor(2); // Now, only user_0 should be active since he is the only one with // outstanding requests assertEquals("There should only be 1 active user!", 1, a.getActiveUsersManager().getNumActiveUsers()); // This commented code is key to test 'activeUsers'. // It should fail the test if uncommented since // it would increase 'activeUsers' to 2 and stop user_2 // Pre MAPREDUCE-3732 this test should fail without this block too // app_2.updateResourceRequests(Collections.singletonList( // TestUtils.createResourceRequest(RMNodeImpl.ANY, 1*GB, 1, priority, // recordFactory))); // 1 container to user_0 a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // Again one to user_0 since he hasn't exceeded user limit yet a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(3*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); // One more to user_0 since he is the only active user a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(4*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(2*GB, app_1.getCurrentConsumption().getMemory()); } @Test public void testComputeUserLimitAndSetHeadroom(){ LeafQueue qb = stubLeafQueue((LeafQueue)queues.get(B)); qb.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; //create nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8*GB); String host_1 = "127.0.0.2"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8*GB); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (8*GB), 1); when(csContext.getNumClusterNodes()).thenReturn(numNodes); //our test plan contains three cases //1. single user dominate the queue, we test the headroom //2. two users, but user_0 is assigned 100% of the queue resource, // submit user_1's application, check headroom correctness //3. two users, each is assigned 50% of the queue resource // each user submit one application and check their headrooms //4. similarly to 3. but user_0 has no quote left and there are // free resources left, check headroom //test case 1 qb.setUserLimit(100); qb.setUserLimitFactor(1); final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, qb, qb.getActiveUsersManager(), spyRMContext); qb.submitApplicationAttempt(app_0, user_0); Priority u0Priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 4*GB, 1, true, u0Priority, recordFactory))); assertEquals("There should only be 1 active user!", 1, qb.getActiveUsersManager().getNumActiveUsers()); //get headroom qb.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); qb.computeUserLimitAndSetHeadroom(app_0, clusterResource, "", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); //maxqueue 16G, userlimit 13G, - 4G used = 9G assertEquals(9*GB,app_0.getHeadroom().getMemory()); //test case 2 final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_1, qb, qb.getActiveUsersManager(), spyRMContext); Priority u1Priority = TestUtils.createMockPriority(2); app_2.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 4*GB, 1, true, u1Priority, recordFactory))); qb.submitApplicationAttempt(app_2, user_1); qb.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); qb.computeUserLimitAndSetHeadroom(app_0, clusterResource, "", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8*GB, qb.getUsedResources().getMemory()); assertEquals(4*GB, app_0.getCurrentConsumption().getMemory()); //maxqueue 16G, userlimit 13G, - 4G used = 9G BUT //maxqueue 16G - used 8G (4 each app/user) = 8G max headroom (the new logic) assertEquals(8*GB, app_0.getHeadroom().getMemory()); assertEquals(4*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(8*GB, app_2.getHeadroom().getMemory()); //test case 3 qb.finishApplication(app_0.getApplicationId(), user_0); qb.finishApplication(app_2.getApplicationId(), user_1); qb.releaseResource(clusterResource, app_0, app_0.getResource(u0Priority), null, null); qb.releaseResource(clusterResource, app_2, app_2.getResource(u1Priority), null, null); qb.setUserLimit(50); qb.setUserLimitFactor(1); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, qb, qb.getActiveUsersManager(), spyRMContext); final ApplicationAttemptId appAttemptId_3 = TestUtils.getMockApplicationAttemptId(3, 0); FiCaSchedulerApp app_3 = new FiCaSchedulerApp(appAttemptId_3, user_1, qb, qb.getActiveUsersManager(), spyRMContext); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, u0Priority, recordFactory))); app_3.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, u1Priority, recordFactory))); qb.submitApplicationAttempt(app_1, user_0); qb.submitApplicationAttempt(app_3, user_1); qb.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); qb.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); qb.computeUserLimitAndSetHeadroom(app_3, clusterResource, "", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(4*GB, qb.getUsedResources().getMemory()); //maxqueue 16G, userlimit 7G, used (by each user) 2G, headroom 5G (both) assertEquals(5*GB, app_3.getHeadroom().getMemory()); assertEquals(5*GB, app_1.getHeadroom().getMemory()); //test case 4 final ApplicationAttemptId appAttemptId_4 = TestUtils.getMockApplicationAttemptId(4, 0); FiCaSchedulerApp app_4 = new FiCaSchedulerApp(appAttemptId_4, user_0, qb, qb.getActiveUsersManager(), spyRMContext); qb.submitApplicationAttempt(app_4, user_0); app_4.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 6*GB, 1, true, u0Priority, recordFactory))); qb.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); qb.computeUserLimitAndSetHeadroom(app_4, clusterResource, "", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); qb.computeUserLimitAndSetHeadroom(app_3, clusterResource, "", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); //app3 is user1, active from last test case //maxqueue 16G, userlimit 13G, used 2G, would be headroom 10G BUT //10G in use, so max possible headroom is 6G (new logic) assertEquals(6*GB, app_3.getHeadroom().getMemory()); //testcase3 still active - 2+2+6=10 assertEquals(10*GB, qb.getUsedResources().getMemory()); //app4 is user 0 //maxqueue 16G, userlimit 13G, used 8G, headroom 5G //(8G used is 6G from this test case - app4, 2 from last test case, app_1) assertEquals(5*GB, app_4.getHeadroom().getMemory()); } @Test public void testUserHeadroomMultiApp() throws Exception { // Mock the queue LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_1, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_2, user_1); // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 16*GB); String host_1 = "127.0.0.2"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 16*GB); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (16*GB), 1); when(csContext.getNumClusterNodes()).thenReturn(numNodes); Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory))); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(1*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); //Now, headroom is the same for all apps for a given user + queue combo //and a change to any app's headroom is reflected for all the user's apps //once those apps are active/have themselves calculated headroom for //allocation at least one time assertEquals(2*GB, app_0.getHeadroom().getMemory()); assertEquals(0*GB, app_1.getHeadroom().getMemory());//not yet active assertEquals(0*GB, app_2.getHeadroom().getMemory());//not yet active app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_0.getHeadroom().getMemory()); assertEquals(1*GB, app_1.getHeadroom().getMemory());//now active assertEquals(0*GB, app_2.getHeadroom().getMemory());//not yet active //Complete container and verify that headroom is updated, for both apps //for the user RMContainer rmContainer = app_0.getLiveContainers().iterator().next(); a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); assertEquals(2*GB, app_0.getHeadroom().getMemory()); assertEquals(2*GB, app_1.getHeadroom().getMemory()); } @Test public void testHeadroomWithMaxCap() throws Exception { // Mock the queue LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_1, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_2, user_1); // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8*GB); String host_1 = "127.0.0.2"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 8*GB); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (8*GB), 1); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, priority, recordFactory))); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); /** * Start testing... */ // Set user-limit a.setUserLimit(50); a.setUserLimitFactor(2); // Now, only user_0 should be active since he is the only one with // outstanding requests assertEquals("There should only be 1 active user!", 1, a.getActiveUsersManager().getNumActiveUsers()); // 1 container to user_0 a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // TODO, fix headroom in the future patch assertEquals(1*GB, app_0.getHeadroom().getMemory()); // User limit = 4G, 2 in use assertEquals(0*GB, app_1.getHeadroom().getMemory()); // the application is not yet active // Again one to user_0 since he hasn't exceeded user limit yet a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(3*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_0.getHeadroom().getMemory()); // 4G - 3G assertEquals(1*GB, app_1.getHeadroom().getMemory()); // 4G - 3G // Submit requests for app_1 and set max-cap a.setMaxCapacity(.1f); app_2.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory))); assertEquals(2, a.getActiveUsersManager().getNumActiveUsers()); // No more to user_0 since he is already over user-limit // and no more containers to queue since it's already at max-cap a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(3*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_0.getHeadroom().getMemory()); assertEquals(0*GB, app_1.getHeadroom().getMemory()); // Check headroom for app_2 app_1.updateResourceRequests(Collections.singletonList( // unset TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 0, true, priority, recordFactory))); assertEquals(1, a.getActiveUsersManager().getNumActiveUsers()); a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(0*GB, app_2.getHeadroom().getMemory()); // hit queue max-cap } @Test public void testSingleQueueWithMultipleUsers() throws Exception { // Mock the queue LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; final String user_2 = "user_2"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_1, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_2, user_1); final ApplicationAttemptId appAttemptId_3 = TestUtils.getMockApplicationAttemptId(3, 0); FiCaSchedulerApp app_3 = new FiCaSchedulerApp(appAttemptId_3, user_2, a, a.getActiveUsersManager(), spyRMContext); a.submitApplicationAttempt(app_3, user_2); // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8*GB); final int numNodes = 1; Resource clusterResource = Resources.createResource(numNodes * (8*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 10, true, priority, recordFactory))); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 10, true, priority, recordFactory))); /** * Start testing... */ // Only 1 container a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(1*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also // you can get one container more than user-limit a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // Can't allocate 3rd due to user-limit a.setUserLimit(25); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // Submit resource requests for other apps now to 'activate' them app_2.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 3*GB, 1, true, priority, recordFactory))); app_3.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); // Now allocations should goto app_2 since // user_0 is at limit inspite of high user-limit-factor a.setUserLimitFactor(10); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(3*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_3.getCurrentConsumption().getMemory()); // Now allocations should goto app_0 since // user_0 is at user-limit not above it a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(6*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(3*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_3.getCurrentConsumption().getMemory()); // Test max-capacity // Now - no more allocs since we are at max-cap a.setMaxCapacity(0.5f); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(6*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(3*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_3.getCurrentConsumption().getMemory()); // Revert max-capacity and user-limit-factor // Now, allocations should goto app_3 since it's under user-limit a.setMaxCapacity(1.0f); a.setUserLimitFactor(1); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(7*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(3*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(1*GB, app_3.getCurrentConsumption().getMemory()); // Now we should assign to app_3 again since user_2 is under user-limit a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(8*GB, a.getUsedResources().getMemory()); assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(3*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(2*GB, app_3.getCurrentConsumption().getMemory()); // 8. Release each container from app_0 for (RMContainer rmContainer : app_0.getLiveContainers()) { a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); } assertEquals(5*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(3*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(2*GB, app_3.getCurrentConsumption().getMemory()); // 9. Release each container from app_2 for (RMContainer rmContainer : app_2.getLiveContainers()) { a.completedContainer(clusterResource, app_2, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); } assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(2*GB, app_3.getCurrentConsumption().getMemory()); // 10. Release each container from app_3 for (RMContainer rmContainer : app_3.getLiveContainers()) { a.completedContainer(clusterResource, app_3, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); } assertEquals(0*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_2.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_3.getCurrentConsumption().getMemory()); } @Test public void testReservation() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_1, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_1); // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 4*GB); final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (4*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 4*GB, 1, true, priority, recordFactory))); // Start testing... // Only 1 container a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(1*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(1*GB, a.getMetrics().getAllocatedMB()); assertEquals(0*GB, a.getMetrics().getAvailableMB()); // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also // you can get one container more than user-limit a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(2*GB, a.getMetrics().getAllocatedMB()); // Now, reservation should kick in for app_1 a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(6*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentReservation().getMemory()); assertEquals(2*GB, node_0.getUsedResource().getMemory()); assertEquals(4*GB, a.getMetrics().getReservedMB()); assertEquals(2*GB, a.getMetrics().getAllocatedMB()); // Now free 1 container from app_0 i.e. 1G RMContainer rmContainer = app_0.getLiveContainers().iterator().next(); a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentReservation().getMemory()); assertEquals(1*GB, node_0.getUsedResource().getMemory()); assertEquals(4*GB, a.getMetrics().getReservedMB()); assertEquals(1*GB, a.getMetrics().getAllocatedMB()); // Now finish another container from app_0 and fulfill the reservation rmContainer = app_0.getLiveContainers().iterator().next(); a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(4*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentReservation().getMemory()); assertEquals(4*GB, node_0.getUsedResource().getMemory()); assertEquals(0*GB, a.getMetrics().getReservedMB()); assertEquals(4*GB, a.getMetrics().getAllocatedMB()); } @Test public void testReservationExchange() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity a.setMaxCapacity(1.0f); a.setUserLimitFactor(10); // Users final String user_0 = "user_0"; final String user_1 = "user_1"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_1, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_1); // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 4*GB); String host_1 = "127.0.0.2"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 4*GB); when(csContext.getNode(node_0.getNodeID())).thenReturn(node_0); when(csContext.getNode(node_1.getNodeID())).thenReturn(node_1); final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (4*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(4*GB, 16)); when(a.getMaximumAllocation()).thenReturn( Resources.createResource(4*GB, 16)); when(a.getMinimumAllocationFactor()).thenReturn(0.25f); // 1G / 4G // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority, recordFactory))); app_1.updateResourceRequests(Collections.singletonList( TestUtils.createResourceRequest(ResourceRequest.ANY, 4*GB, 1, true, priority, recordFactory))); // Start testing... // Only 1 container a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(1*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also // you can get one container more than user-limit a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(2*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); // Now, reservation should kick in for app_1 a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(6*GB, a.getUsedResources().getMemory()); assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentReservation().getMemory()); assertEquals(2*GB, node_0.getUsedResource().getMemory()); // Now free 1 container from app_0 i.e. 1G, and re-reserve it RMContainer rmContainer = app_0.getLiveContainers().iterator().next(); a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentReservation().getMemory()); assertEquals(1*GB, node_0.getUsedResource().getMemory()); assertEquals(1, app_1.getReReservations(priority)); // Re-reserve a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(5*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentReservation().getMemory()); assertEquals(1*GB, node_0.getUsedResource().getMemory()); assertEquals(2, app_1.getReReservations(priority)); // Try to schedule on node_1 now, should *move* the reservation a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(9*GB, a.getUsedResources().getMemory()); assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentReservation().getMemory()); assertEquals(4*GB, node_1.getUsedResource().getMemory()); // Doesn't change yet... only when reservation is cancelled or a different // container is reserved assertEquals(2, app_1.getReReservations(priority)); // Now finish another container from app_0 and see the reservation cancelled rmContainer = app_0.getLiveContainers().iterator().next(); a.completedContainer(clusterResource, app_0, node_0, rmContainer, ContainerStatus.newInstance(rmContainer.getContainerId(), ContainerState.COMPLETE, "", ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), RMContainerEventType.KILL, null, true); a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(4*GB, a.getUsedResources().getMemory()); assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); assertEquals(0*GB, app_1.getCurrentReservation().getMemory()); assertEquals(0*GB, node_0.getUsedResource().getMemory()); } private void verifyContainerAllocated(CSAssignment assignment, NodeType nodeType) { Assert.assertTrue(Resources.greaterThan(resourceCalculator, null, assignment.getResource(), Resources.none())); Assert .assertTrue(assignment.getAssignmentInformation().getNumAllocations() > 0); Assert.assertEquals(nodeType, assignment.getType()); } private void verifyNoContainerAllocated(CSAssignment assignment) { Assert.assertTrue(Resources.equals(assignment.getResource(), Resources.none())); Assert .assertTrue(assignment.getAssignmentInformation().getNumAllocations() == 0); } @Test public void testLocalityScheduling() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); // User String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); // Setup some nodes and racks String host_0 = "127.0.0.1"; String rack_0 = "rack_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, rack_0, 0, 8*GB); String host_1 = "127.0.0.2"; String rack_1 = "rack_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, rack_1, 0, 8*GB); String host_2 = "127.0.0.3"; String rack_2 = "rack_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, rack_2, 0, 8*GB); final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (8*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests and submit Priority priority = TestUtils.createMockPriority(1); List<ResourceRequest> app_0_requests_0 = new ArrayList<ResourceRequest>(); app_0_requests_0.add( TestUtils.createResourceRequest(host_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(host_1, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 3, // one extra true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); // Start testing... CSAssignment assignment = null; // Start with off switch, shouldn't allocate due to delay scheduling assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(1, app_0.getSchedulingOpportunities(priority)); assertEquals(3, app_0.getTotalRequiredResources(priority)); assertEquals(NodeType.NODE_LOCAL, assignment.getType()); // None->NODE_LOCAL // Another off switch, shouldn't allocate due to delay scheduling assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(2, app_0.getSchedulingOpportunities(priority)); assertEquals(3, app_0.getTotalRequiredResources(priority)); assertEquals(NodeType.NODE_LOCAL, assignment.getType()); // None->NODE_LOCAL // Another off switch, shouldn't allocate due to delay scheduling assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(3, app_0.getSchedulingOpportunities(priority)); assertEquals(3, app_0.getTotalRequiredResources(priority)); assertEquals(NodeType.NODE_LOCAL, assignment.getType()); // None->NODE_LOCAL // Another off switch, now we should allocate // since missedOpportunities=3 and reqdContainers=3 assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.OFF_SWITCH); assertEquals(4, app_0.getSchedulingOpportunities(priority)); // should NOT reset assertEquals(2, app_0.getTotalRequiredResources(priority)); // NODE_LOCAL - node_0 assignment = a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.NODE_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset assertEquals(1, app_0.getTotalRequiredResources(priority)); // NODE_LOCAL - node_1 assignment = a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.NODE_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset assertEquals(0, app_0.getTotalRequiredResources(priority)); assertEquals(NodeType.NODE_LOCAL, assignment.getType()); // Add 1 more request to check for RACK_LOCAL app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(host_1, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, // one extra true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); assertEquals(2, app_0.getTotalRequiredResources(priority)); String host_3 = "127.0.0.4"; // on rack_1 FiCaSchedulerNode node_3 = TestUtils.getMockNode(host_3, rack_1, 0, 8*GB); // Rack-delay doReturn(1).when(a).getNodeLocalityDelay(); // Shouldn't assign RACK_LOCAL yet assignment = a.assignContainers(clusterResource, node_3, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); assertEquals(1, app_0.getSchedulingOpportunities(priority)); assertEquals(2, app_0.getTotalRequiredResources(priority)); // Should assign RACK_LOCAL now assignment = a.assignContainers(clusterResource, node_3, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.RACK_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset assertEquals(1, app_0.getTotalRequiredResources(priority)); } @Test public void testApplicationPriorityScheduling() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); // User String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); // Setup some nodes and racks String host_0 = "127.0.0.1"; String rack_0 = "rack_0"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, rack_0, 0, 8*GB); String host_1 = "127.0.0.2"; String rack_1 = "rack_1"; FiCaSchedulerNode node_1 = TestUtils.getMockNode(host_1, rack_1, 0, 8*GB); String host_2 = "127.0.0.3"; String rack_2 = "rack_2"; FiCaSchedulerNode node_2 = TestUtils.getMockNode(host_2, rack_2, 0, 8*GB); final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (8*GB), 1); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests and submit List<ResourceRequest> app_0_requests_0 = new ArrayList<ResourceRequest>(); // P1 Priority priority_1 = TestUtils.createMockPriority(1); app_0_requests_0.add( TestUtils.createResourceRequest(host_0, 1*GB, 1, true, priority_1, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_0, 1*GB, 1, true, priority_1, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(host_1, 1*GB, 1, true, priority_1, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, true, priority_1, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 2, true, priority_1, recordFactory)); // P2 Priority priority_2 = TestUtils.createMockPriority(2); app_0_requests_0.add( TestUtils.createResourceRequest(host_2, 2*GB, 1, true, priority_2, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_2, 2*GB, 1, true, priority_2, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, priority_2, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); // Start testing... // Start with off switch, shouldn't allocate P1 due to delay scheduling // thus, no P2 either! CSAssignment assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(1, app_0.getSchedulingOpportunities(priority_1)); assertEquals(2, app_0.getTotalRequiredResources(priority_1)); assertEquals(0, app_0.getSchedulingOpportunities(priority_2)); assertEquals(1, app_0.getTotalRequiredResources(priority_2)); // Another off-switch, shouldn't allocate P1 due to delay scheduling // thus, no P2 either! assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(2, app_0.getSchedulingOpportunities(priority_1)); assertEquals(2, app_0.getTotalRequiredResources(priority_1)); assertEquals(0, app_0.getSchedulingOpportunities(priority_2)); assertEquals(1, app_0.getTotalRequiredResources(priority_2)); // Another off-switch, shouldn't allocate OFF_SWITCH P1 assignment = a.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.OFF_SWITCH); assertEquals(3, app_0.getSchedulingOpportunities(priority_1)); assertEquals(1, app_0.getTotalRequiredResources(priority_1)); assertEquals(0, app_0.getSchedulingOpportunities(priority_2)); assertEquals(1, app_0.getTotalRequiredResources(priority_2)); // Now, DATA_LOCAL for P1 assignment = a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.NODE_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority_1)); assertEquals(0, app_0.getTotalRequiredResources(priority_1)); assertEquals(0, app_0.getSchedulingOpportunities(priority_2)); assertEquals(1, app_0.getTotalRequiredResources(priority_2)); // Now, OFF_SWITCH for P2 assignment = a.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.OFF_SWITCH); assertEquals(0, app_0.getSchedulingOpportunities(priority_1)); assertEquals(0, app_0.getTotalRequiredResources(priority_1)); assertEquals(1, app_0.getSchedulingOpportunities(priority_2)); assertEquals(0, app_0.getTotalRequiredResources(priority_2)); } @Test public void testSchedulingConstraints() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); // User String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); // Setup some nodes and racks String host_0_0 = "127.0.0.1"; String rack_0 = "rack_0"; FiCaSchedulerNode node_0_0 = TestUtils.getMockNode(host_0_0, rack_0, 0, 8*GB); String host_0_1 = "127.0.0.2"; FiCaSchedulerNode node_0_1 = TestUtils.getMockNode(host_0_1, rack_0, 0, 8*GB); String host_1_0 = "127.0.0.3"; String rack_1 = "rack_1"; FiCaSchedulerNode node_1_0 = TestUtils.getMockNode(host_1_0, rack_1, 0, 8*GB); final int numNodes = 3; Resource clusterResource = Resources.createResource( numNodes * (8*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests and submit Priority priority = TestUtils.createMockPriority(1); List<ResourceRequest> app_0_requests_0 = new ArrayList<ResourceRequest>(); app_0_requests_0.add( TestUtils.createResourceRequest(host_0_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(host_0_1, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(host_1_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); // Start testing... // Add one request app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, // only one true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); // NODE_LOCAL - node_0_1 CSAssignment assignment = a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.NODE_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset assertEquals(0, app_0.getTotalRequiredResources(priority)); // No allocation on node_1_0 even though it's node/rack local since // required(ANY) == 0 assignment = a.assignContainers(clusterResource, node_1_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // Still zero // since #req=0 assertEquals(0, app_0.getTotalRequiredResources(priority)); // Add one request app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, // only one true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); // No allocation on node_0_1 even though it's node/rack local since // required(rack_1) == 0 assignment = a.assignContainers(clusterResource, node_0_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(1, app_0.getSchedulingOpportunities(priority)); assertEquals(1, app_0.getTotalRequiredResources(priority)); // NODE_LOCAL - node_1 assignment = a.assignContainers(clusterResource, node_1_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.NODE_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset assertEquals(0, app_0.getTotalRequiredResources(priority)); } @Test (timeout = 30000) public void testActivateApplicationAfterQueueRefresh() throws Exception { // Manipulate queue 'e' LeafQueue e = stubLeafQueue((LeafQueue)queues.get(E)); // Users final String user_e = "user_e"; when(amResourceRequest.getCapability()).thenReturn( Resources.createResource(1 * GB, 0)); // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_e, e, mock(ActiveUsersManager.class), spyRMContext); e.submitApplicationAttempt(app_0, user_e); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_e, e, mock(ActiveUsersManager.class), spyRMContext); e.submitApplicationAttempt(app_1, user_e); // same user final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_e, e, mock(ActiveUsersManager.class), spyRMContext); e.submitApplicationAttempt(app_2, user_e); // same user // before reinitialization assertEquals(2, e.getNumActiveApplications()); assertEquals(1, e.pendingApplications.size()); csConf.setDouble(CapacitySchedulerConfiguration .MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT, CapacitySchedulerConfiguration .DEFAULT_MAXIMUM_APPLICATIONMASTERS_RESOURCE_PERCENT * 2); Map<String, CSQueue> newQueues = new HashMap<String, CSQueue>(); CSQueue newRoot = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, newQueues, queues, TestUtils.spyHook); queues = newQueues; root.reinitialize(newRoot, csContext.getClusterResource()); // after reinitialization assertEquals(3, e.getNumActiveApplications()); assertEquals(0, e.pendingApplications.size()); } @Test (timeout = 30000) public void testNodeLocalityAfterQueueRefresh() throws Exception { // Manipulate queue 'e' LeafQueue e = stubLeafQueue((LeafQueue)queues.get(E)); // before reinitialization assertEquals(40, e.getNodeLocalityDelay()); csConf.setInt(CapacitySchedulerConfiguration .NODE_LOCALITY_DELAY, 60); Map<String, CSQueue> newQueues = new HashMap<String, CSQueue>(); CSQueue newRoot = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, newQueues, queues, TestUtils.spyHook); queues = newQueues; root.reinitialize(newRoot, cs.getClusterResource()); // after reinitialization assertEquals(60, e.getNodeLocalityDelay()); } @Test (timeout = 30000) public void testActivateApplicationByUpdatingClusterResource() throws Exception { // Manipulate queue 'e' LeafQueue e = stubLeafQueue((LeafQueue)queues.get(E)); // Users final String user_e = "user_e"; when(amResourceRequest.getCapability()).thenReturn( Resources.createResource(1 * GB, 0)); // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_e, e, mock(ActiveUsersManager.class), spyRMContext); e.submitApplicationAttempt(app_0, user_e); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_e, e, mock(ActiveUsersManager.class), spyRMContext); e.submitApplicationAttempt(app_1, user_e); // same user final ApplicationAttemptId appAttemptId_2 = TestUtils.getMockApplicationAttemptId(2, 0); FiCaSchedulerApp app_2 = new FiCaSchedulerApp(appAttemptId_2, user_e, e, mock(ActiveUsersManager.class), spyRMContext); e.submitApplicationAttempt(app_2, user_e); // same user // before updating cluster resource assertEquals(2, e.getNumActiveApplications()); assertEquals(1, e.pendingApplications.size()); Resource clusterResource = Resources.createResource(200 * 16 * GB, 100 * 32); e.updateClusterResource(clusterResource, new ResourceLimits(clusterResource)); // after updating cluster resource assertEquals(3, e.getNumActiveApplications()); assertEquals(0, e.pendingApplications.size()); } public boolean hasQueueACL(List<QueueUserACLInfo> aclInfos, QueueACL acl) { for (QueueUserACLInfo aclInfo : aclInfos) { if (aclInfo.getUserAcls().contains(acl)) { return true; } } return false; } @Test public void testInheritedQueueAcls() throws IOException { UserGroupInformation user = UserGroupInformation.getCurrentUser(); LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); LeafQueue b = stubLeafQueue((LeafQueue)queues.get(B)); ParentQueue c = (ParentQueue)queues.get(C); LeafQueue c1 = stubLeafQueue((LeafQueue)queues.get(C1)); assertFalse(root.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertTrue(a.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertTrue(b.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertFalse(c.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertFalse(c1.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertTrue(hasQueueACL( a.getQueueUserAclInfo(user), QueueACL.SUBMIT_APPLICATIONS)); assertTrue(hasQueueACL( b.getQueueUserAclInfo(user), QueueACL.SUBMIT_APPLICATIONS)); assertFalse(hasQueueACL( c.getQueueUserAclInfo(user), QueueACL.SUBMIT_APPLICATIONS)); assertFalse(hasQueueACL( c1.getQueueUserAclInfo(user), QueueACL.SUBMIT_APPLICATIONS)); } @Test public void testLocalityConstraints() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); // User String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // Setup some nodes and racks String host_0_0 = "127.0.0.1"; String rack_0 = "rack_0"; String host_0_1 = "127.0.0.2"; FiCaSchedulerNode node_0_1 = TestUtils.getMockNode(host_0_1, rack_0, 0, 8*GB); String host_1_0 = "127.0.0.3"; String rack_1 = "rack_1"; FiCaSchedulerNode node_1_0 = TestUtils.getMockNode(host_1_0, rack_1, 0, 8*GB); String host_1_1 = "127.0.0.4"; FiCaSchedulerNode node_1_1 = TestUtils.getMockNode(host_1_1, rack_1, 0, 8*GB); final int numNodes = 4; Resource clusterResource = Resources.createResource( numNodes * (8*GB), numNodes * 1); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests // resourceName: <priority, memory, #containers, relaxLocality> // host_0_0: < 1, 1GB, 1, true > // host_0_1: < null > // rack_0: < null > <---- // host_1_0: < 1, 1GB, 1, true > // host_1_1: < null > // rack_1: < 1, 1GB, 1, false > <---- // ANY: < 1, 1GB, 1, false > <---- // Availability: // host_0_0: 8G // host_0_1: 8G // host_1_0: 8G // host_1_1: 8G // Blacklist: <host_0_0> Priority priority = TestUtils.createMockPriority(1); List<ResourceRequest> app_0_requests_0 = new ArrayList<ResourceRequest>(); app_0_requests_0.add( TestUtils.createResourceRequest(host_0_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(host_1_0, 1*GB, 1, true, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, false, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, // only one false, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_0.updateBlacklist(Collections.singletonList(host_0_0), null); app_0_requests_0.clear(); // // Start testing... // // node_0_1 // Shouldn't allocate since RR(rack_0) = null && RR(ANY) = relax: false CSAssignment assignment = a.assignContainers(clusterResource, node_0_1, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 // resourceName: <priority, memory, #containers, relaxLocality> // host_0_0: < 1, 1GB, 1, true > // host_0_1: < null > // rack_0: < null > <---- // host_1_0: < 1, 1GB, 1, true > // host_1_1: < null > // rack_1: < 1, 1GB, 1, false > <---- // ANY: < 1, 1GB, 1, false > <---- // Availability: // host_0_0: 8G // host_0_1: 8G // host_1_0: 8G // host_1_1: 8G // Blacklist: <host_0_0> // node_1_1 // Shouldn't allocate since RR(rack_1) = relax: false assignment = a.assignContainers(clusterResource, node_1_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 // Allow rack-locality for rack_1, but blacklist node_1_1 app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_0.updateBlacklist(Collections.singletonList(host_1_1), null); app_0_requests_0.clear(); // resourceName: <priority, memory, #containers, relaxLocality> // host_0_0: < 1, 1GB, 1, true > // host_0_1: < null > // rack_0: < null > // host_1_0: < 1, 1GB, 1, true > // host_1_1: < null > // rack_1: < 1, 1GB, 1, true > // ANY: < 1, 1GB, 1, false > // Availability: // host_0_0: 8G // host_0_1: 8G // host_1_0: 8G // host_1_1: 8G // Blacklist: < host_0_0 , host_1_1 > <---- // node_1_1 // Shouldn't allocate since node_1_1 is blacklisted assignment = a.assignContainers(clusterResource, node_1_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 // Now, remove node_1_1 from blacklist, but add rack_1 to blacklist app_0.updateResourceRequests(app_0_requests_0); app_0.updateBlacklist( Collections.singletonList(rack_1), Collections.singletonList(host_1_1)); app_0_requests_0.clear(); // resourceName: <priority, memory, #containers, relaxLocality> // host_0_0: < 1, 1GB, 1, true > // host_0_1: < null > // rack_0: < null > // host_1_0: < 1, 1GB, 1, true > // host_1_1: < null > // rack_1: < 1, 1GB, 1, true > // ANY: < 1, 1GB, 1, false > // Availability: // host_0_0: 8G // host_0_1: 8G // host_1_0: 8G // host_1_1: 8G // Blacklist: < host_0_0 , rack_1 > <---- // node_1_1 // Shouldn't allocate since rack_1 is blacklisted assignment = a.assignContainers(clusterResource, node_1_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 // Now remove rack_1 from blacklist app_0.updateResourceRequests(app_0_requests_0); app_0.updateBlacklist(null, Collections.singletonList(rack_1)); app_0_requests_0.clear(); // resourceName: <priority, memory, #containers, relaxLocality> // host_0_0: < 1, 1GB, 1, true > // host_0_1: < null > // rack_0: < null > // host_1_0: < 1, 1GB, 1, true > // host_1_1: < null > // rack_1: < 1, 1GB, 1, true > // ANY: < 1, 1GB, 1, false > // Availability: // host_0_0: 8G // host_0_1: 8G // host_1_0: 8G // host_1_1: 8G // Blacklist: < host_0_0 > <---- // Now, should allocate since RR(rack_1) = relax: true assignment = a.assignContainers(clusterResource, node_1_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyNoContainerAllocated(assignment); assertEquals(0, app_0.getSchedulingOpportunities(priority)); assertEquals(1, app_0.getTotalRequiredResources(priority)); // Now sanity-check node_local app_0_requests_0.add( TestUtils.createResourceRequest(rack_1, 1*GB, 1, false, priority, recordFactory)); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, // only one false, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_0_requests_0.clear(); // resourceName: <priority, memory, #containers, relaxLocality> // host_0_0: < 1, 1GB, 1, true > // host_0_1: < null > // rack_0: < null > // host_1_0: < 1, 1GB, 1, true > // host_1_1: < null > // rack_1: < 1, 1GB, 1, false > <---- // ANY: < 1, 1GB, 1, false > <---- // Availability: // host_0_0: 8G // host_0_1: 8G // host_1_0: 8G // host_1_1: 7G assignment = a.assignContainers(clusterResource, node_1_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyContainerAllocated(assignment, NodeType.NODE_LOCAL); assertEquals(0, app_0.getSchedulingOpportunities(priority)); assertEquals(0, app_0.getTotalRequiredResources(priority)); } @Test public void testMaxAMResourcePerQueuePercentAfterQueueRefresh() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); Resource clusterResource = Resources .createResource(100 * 16 * GB, 100 * 32); CapacitySchedulerContext csContext = mockCSContext(csConf, clusterResource); when(csContext.getRMContext()).thenReturn(rmContext); csConf.setFloat(CapacitySchedulerConfiguration. MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT, 0.1f); ParentQueue root = new ParentQueue(csContext, CapacitySchedulerConfiguration.ROOT, null, null); csConf.setCapacity(CapacitySchedulerConfiguration.ROOT + "." + A, 80); LeafQueue a = new LeafQueue(csContext, A, root, null); assertEquals(0.1f, a.getMaxAMResourcePerQueuePercent(), 1e-3f); assertEquals(a.getAMResourceLimit(), Resources.createResource(160 * GB, 1)); csConf.setFloat(CapacitySchedulerConfiguration. MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT, 0.2f); LeafQueue newA = new LeafQueue(csContext, A, root, null); a.reinitialize(newA, clusterResource); assertEquals(0.2f, a.getMaxAMResourcePerQueuePercent(), 1e-3f); assertEquals(a.getAMResourceLimit(), Resources.createResource(320 * GB, 1)); Resource newClusterResource = Resources.createResource(100 * 20 * GB, 100 * 32); a.updateClusterResource(newClusterResource, new ResourceLimits(newClusterResource)); // 100 * 20 * 0.2 = 400 assertEquals(a.getAMResourceLimit(), Resources.createResource(400 * GB, 1)); } @Test public void testAllocateContainerOnNodeWithoutOffSwitchSpecified() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue) queues.get(B)); // Users final String user_0 = "user_0"; // Submit applications final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext); a.submitApplicationAttempt(app_1, user_0); // same user // Setup some nodes String host_0 = "127.0.0.1"; FiCaSchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 8 * GB); final int numNodes = 1; Resource clusterResource = Resources.createResource(numNodes * (8 * GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Setup resource-requests Priority priority = TestUtils.createMockPriority(1); app_0.updateResourceRequests(Arrays.asList(TestUtils.createResourceRequest( "127.0.0.1", 1 * GB, 3, true, priority, recordFactory), TestUtils .createResourceRequest(DEFAULT_RACK, 1 * GB, 3, true, priority, recordFactory))); try { a.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); } catch (NullPointerException e) { Assert.fail("NPE when allocating container on node but " + "forget to set off-switch request should be handled"); } } @Test public void testFifoAssignment() throws Exception { LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); a.setOrderingPolicy(new FifoOrderingPolicy<FiCaSchedulerApp>()); String host_0_0 = "127.0.0.1"; String rack_0 = "rack_0"; FiCaSchedulerNode node_0_0 = TestUtils.getMockNode(host_0_0, rack_0, 0, 16*GB); final int numNodes = 4; Resource clusterResource = Resources.createResource( numNodes * (16*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); String user_0 = "user_0"; final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = spy(new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = spy(new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext)); a.submitApplicationAttempt(app_1, user_0); Priority priority = TestUtils.createMockPriority(1); List<ResourceRequest> app_0_requests_0 = new ArrayList<ResourceRequest>(); List<ResourceRequest> app_1_requests_0 = new ArrayList<ResourceRequest>(); app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_1_requests_0.clear(); app_1_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory)); app_1.updateResourceRequests(app_1_requests_0); a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_1_requests_0.clear(); app_1_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory)); app_1.updateResourceRequests(app_1_requests_0); //Even thought it already has more resources, app_0 will still get //assigned first a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); Assert.assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); //and only then will app_1 a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(2*GB, app_1.getCurrentConsumption().getMemory()); } @Test public void testConcurrentAccess() throws Exception { YarnConfiguration conf = new YarnConfiguration(); MockRM rm = new MockRM(); rm.init(conf); rm.start(); final String queue = "default"; final String user = "user"; CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); final LeafQueue defaultQueue = (LeafQueue) cs.getQueue(queue); final List<FiCaSchedulerApp> listOfApps = createListOfApps(10000, user, defaultQueue); final CyclicBarrier cb = new CyclicBarrier(2); final List<ConcurrentModificationException> conException = new ArrayList<ConcurrentModificationException>(); Thread submitAndRemove = new Thread(new Runnable() { @Override public void run() { for (FiCaSchedulerApp fiCaSchedulerApp : listOfApps) { defaultQueue.submitApplicationAttempt(fiCaSchedulerApp, user); } try { cb.await(); } catch (Exception e) { // Ignore } for (FiCaSchedulerApp fiCaSchedulerApp : listOfApps) { defaultQueue.finishApplicationAttempt(fiCaSchedulerApp, queue); } } }, "SubmitAndRemoveApplicationAttempt Thread"); Thread getAppsInQueue = new Thread(new Runnable() { List<ApplicationAttemptId> apps = new ArrayList<ApplicationAttemptId>(); @Override public void run() { try { try { cb.await(); } catch (Exception e) { // Ignore } defaultQueue.collectSchedulerApplications(apps); } catch (ConcurrentModificationException e) { conException.add(e); } } }, "GetAppsInQueue Thread"); submitAndRemove.start(); getAppsInQueue.start(); submitAndRemove.join(); getAppsInQueue.join(); assertTrue("ConcurrentModificationException is thrown", conException.isEmpty()); rm.stop(); } @Test public void testFairAssignment() throws Exception { LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); OrderingPolicy<FiCaSchedulerApp> schedulingOrder = new FairOrderingPolicy<FiCaSchedulerApp>(); a.setOrderingPolicy(schedulingOrder); String host_0_0 = "127.0.0.1"; String rack_0 = "rack_0"; FiCaSchedulerNode node_0_0 = TestUtils.getMockNode(host_0_0, rack_0, 0, 16*GB); final int numNodes = 4; Resource clusterResource = Resources.createResource( numNodes * (16*GB), numNodes * 16); when(csContext.getNumClusterNodes()).thenReturn(numNodes); String user_0 = "user_0"; final ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(0, 0); FiCaSchedulerApp app_0 = spy(new FiCaSchedulerApp(appAttemptId_0, user_0, a, mock(ActiveUsersManager.class), spyRMContext)); a.submitApplicationAttempt(app_0, user_0); final ApplicationAttemptId appAttemptId_1 = TestUtils.getMockApplicationAttemptId(1, 0); FiCaSchedulerApp app_1 = spy(new FiCaSchedulerApp(appAttemptId_1, user_0, a, mock(ActiveUsersManager.class), spyRMContext)); a.submitApplicationAttempt(app_1, user_0); Priority priority = TestUtils.createMockPriority(1); List<ResourceRequest> app_0_requests_0 = new ArrayList<ResourceRequest>(); List<ResourceRequest> app_1_requests_0 = new ArrayList<ResourceRequest>(); app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 2*GB, 1, true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_1_requests_0.clear(); app_1_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory)); app_1.updateResourceRequests(app_1_requests_0); a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); app_0_requests_0.clear(); app_0_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory)); app_0.updateResourceRequests(app_0_requests_0); app_1_requests_0.clear(); app_1_requests_0.add( TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory)); app_1.updateResourceRequests(app_1_requests_0); //Since it already has more resources, app_0 will not get //assigned first, but app_1 will a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); Assert.assertEquals(2*GB, app_1.getCurrentConsumption().getMemory()); //and only then will app_0 a.assignContainers(clusterResource, node_0_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); Assert.assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); } private List<FiCaSchedulerApp> createListOfApps(int noOfApps, String user, LeafQueue defaultQueue) { List<FiCaSchedulerApp> appsLists = new ArrayList<FiCaSchedulerApp>(); for (int i = 0; i < noOfApps; i++) { ApplicationAttemptId appAttemptId_0 = TestUtils.getMockApplicationAttemptId(i, 0); FiCaSchedulerApp app_0 = new FiCaSchedulerApp(appAttemptId_0, user, defaultQueue, mock(ActiveUsersManager.class), spyRMContext); appsLists.add(app_0); } return appsLists; } private CapacitySchedulerContext mockCSContext( CapacitySchedulerConfiguration csConf, Resource clusterResource) { CapacitySchedulerContext csContext = mock(CapacitySchedulerContext.class); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getConf()).thenReturn(new YarnConfiguration()); when(csContext.getResourceCalculator()).thenReturn(resourceCalculator); when(csContext.getClusterResource()).thenReturn(clusterResource); when(csContext.getMinimumResourceCapability()).thenReturn( Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(2 * GB, 2)); return csContext; } @After public void tearDown() throws Exception { if (cs != null) { cs.stop(); } } }
111,639
41.790341
133
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestUtils.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.scheduler.capacity; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.util.Set; 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.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; 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.api.records.ResourceRequest; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMActiveServiceContext; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.security.AMRMTokenSecretManager; import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import com.google.common.collect.Sets; public class TestUtils { private static final Log LOG = LogFactory.getLog(TestUtils.class); /** * Get a mock {@link RMContext} for use in test cases. * @return a mock {@link RMContext} for use in test cases */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static RMContext getMockRMContext() { // Null dispatcher Dispatcher nullDispatcher = new Dispatcher() { private final EventHandler handler = new EventHandler() { @Override public void handle(Event event) { } }; @Override public void register(Class<? extends Enum> eventType, EventHandler handler) { } @Override public EventHandler getEventHandler() { return handler; } }; // No op ContainerAllocationExpirer cae = new ContainerAllocationExpirer(nullDispatcher); Configuration conf = new Configuration(); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); RMContextImpl rmContext = new RMContextImpl(nullDispatcher, cae, null, null, null, new AMRMTokenSecretManager(conf, null), new RMContainerTokenSecretManager(conf), new NMTokenSecretManagerInRM(conf), new ClientToAMTokenSecretManagerInRM(), writer); RMNodeLabelsManager nlm = mock(RMNodeLabelsManager.class); when( nlm.getQueueResource(any(String.class), any(Set.class), any(Resource.class))).thenAnswer(new Answer<Resource>() { @Override public Resource answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (Resource) args[2]; } }); when(nlm.getResourceByLabel(any(String.class), any(Resource.class))) .thenAnswer(new Answer<Resource>() { @Override public Resource answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (Resource) args[1]; } }); rmContext.setNodeLabelManager(nlm); rmContext.setSystemMetricsPublisher(mock(SystemMetricsPublisher.class)); ResourceScheduler mockScheduler = mock(ResourceScheduler.class); when(mockScheduler.getResourceCalculator()).thenReturn( new DefaultResourceCalculator()); rmContext.setScheduler(mockScheduler); return rmContext; } /** * Hook to spy on queues. */ static class SpyHook extends CapacityScheduler.QueueHook { @Override public CSQueue hook(CSQueue queue) { return spy(queue); } } public static SpyHook spyHook = new SpyHook(); private static final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public static Priority createMockPriority( int priority) { // Priority p = mock(Priority.class); // when(p.getPriority()).thenReturn(priority); Priority p = recordFactory.newRecordInstance(Priority.class); p.setPriority(priority); return p; } public static ResourceRequest createResourceRequest( String resourceName, int memory, int numContainers, boolean relaxLocality, Priority priority, RecordFactory recordFactory) { ResourceRequest request = recordFactory.newRecordInstance(ResourceRequest.class); Resource capability = Resources.createResource(memory, 1); request.setNumContainers(numContainers); request.setResourceName(resourceName); request.setCapability(capability); request.setRelaxLocality(relaxLocality); request.setPriority(priority); request.setNodeLabelExpression(RMNodeLabelsManager.NO_LABEL); return request; } public static ApplicationId getMockApplicationId(int appId) { return ApplicationId.newInstance(0L, appId); } public static ApplicationAttemptId getMockApplicationAttemptId(int appId, int attemptId) { ApplicationId applicationId = BuilderUtils.newApplicationId(0l, appId); return ApplicationAttemptId.newInstance(applicationId, attemptId); } public static FiCaSchedulerNode getMockNode( String host, String rack, int port, int capability) { NodeId nodeId = NodeId.newInstance(host, port); RMNode rmNode = mock(RMNode.class); when(rmNode.getNodeID()).thenReturn(nodeId); when(rmNode.getTotalCapability()).thenReturn( Resources.createResource(capability, 1)); when(rmNode.getNodeAddress()).thenReturn(host+":"+port); when(rmNode.getHostName()).thenReturn(host); when(rmNode.getRackName()).thenReturn(rack); FiCaSchedulerNode node = spy(new FiCaSchedulerNode(rmNode, false)); LOG.info("node = " + host + " avail=" + node.getAvailableResource()); when(node.getNodeID()).thenReturn(nodeId); return node; } @SuppressWarnings("deprecation") public static ContainerId getMockContainerId(FiCaSchedulerApp application) { ContainerId containerId = mock(ContainerId.class); doReturn(application.getApplicationAttemptId()). when(containerId).getApplicationAttemptId(); long id = application.getNewContainerId(); doReturn((int)id).when(containerId).getId(); doReturn(id).when(containerId).getContainerId(); return containerId; } public static Container getMockContainer( ContainerId containerId, NodeId nodeId, Resource resource, Priority priority) { Container container = mock(Container.class); when(container.getId()).thenReturn(containerId); when(container.getNodeId()).thenReturn(nodeId); when(container.getResource()).thenReturn(resource); when(container.getPriority()).thenReturn(priority); return container; } @SuppressWarnings("unchecked") private static <E> Set<E> toSet(E... elements) { Set<E> set = Sets.newHashSet(elements); return set; } /** * Get a queue structure: * <pre> * Root * / | \ * a b c * | | | * a1 b1 c1 * (x) (y) * </pre> */ public static Configuration getConfigurationWithQueueLabels(Configuration config) { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(config); // Define top-level queues conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {"a", "b", "c"}); conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, "x", 100); conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, "y", 100); final String A = CapacitySchedulerConfiguration.ROOT + ".a"; conf.setCapacity(A, 10); conf.setMaximumCapacity(A, 15); conf.setAccessibleNodeLabels(A, toSet("x")); conf.setCapacityByLabel(A, "x", 100); final String B = CapacitySchedulerConfiguration.ROOT + ".b"; conf.setCapacity(B, 20); conf.setAccessibleNodeLabels(B, toSet("y")); conf.setCapacityByLabel(B, "y", 100); final String C = CapacitySchedulerConfiguration.ROOT + ".c"; conf.setCapacity(C, 70); conf.setMaximumCapacity(C, 70); conf.setAccessibleNodeLabels(C, RMNodeLabelsManager.EMPTY_STRING_SET); // Define 2nd-level queues final String A1 = A + ".a1"; conf.setQueues(A, new String[] {"a1"}); conf.setCapacity(A1, 100); conf.setMaximumCapacity(A1, 100); conf.setCapacityByLabel(A1, "x", 100); final String B1 = B + ".b1"; conf.setQueues(B, new String[] {"b1"}); conf.setCapacity(B1, 100); conf.setMaximumCapacity(B1, 100); conf.setCapacityByLabel(B1, "y", 100); conf.setMaximumApplicationMasterResourcePerQueuePercent(B1, 1f); final String C1 = C + ".c1"; conf.setQueues(C, new String[] {"c1"}); conf.setCapacity(C1, 100); conf.setMaximumCapacity(C1, 100); return conf; } public static Configuration getComplexConfigurationWithQueueLabels( Configuration config) { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(config); // Define top-level queues conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {"a", "b"}); conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, "x", 100); conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, "y", 100); conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, "z", 100); final String A = CapacitySchedulerConfiguration.ROOT + ".a"; conf.setCapacity(A, 10); conf.setMaximumCapacity(A, 10); conf.setAccessibleNodeLabels(A, toSet("x", "y")); conf.setCapacityByLabel(A, "x", 100); conf.setCapacityByLabel(A, "y", 50); final String B = CapacitySchedulerConfiguration.ROOT + ".b"; conf.setCapacity(B, 90); conf.setMaximumCapacity(B, 100); conf.setAccessibleNodeLabels(B, toSet("y", "z")); conf.setCapacityByLabel(B, "y", 50); conf.setCapacityByLabel(B, "z", 100); // Define 2nd-level queues final String A1 = A + ".a1"; conf.setQueues(A, new String[] {"a1"}); conf.setCapacity(A1, 100); conf.setMaximumCapacity(A1, 100); conf.setAccessibleNodeLabels(A1, toSet("x", "y")); conf.setDefaultNodeLabelExpression(A1, "x"); conf.setCapacityByLabel(A1, "x", 100); conf.setCapacityByLabel(A1, "y", 100); conf.setQueues(B, new String[] {"b1", "b2"}); final String B1 = B + ".b1"; conf.setCapacity(B1, 50); conf.setMaximumCapacity(B1, 50); conf.setAccessibleNodeLabels(B1, RMNodeLabelsManager.EMPTY_STRING_SET); final String B2 = B + ".b2"; conf.setCapacity(B2, 50); conf.setMaximumCapacity(B2, 50); conf.setAccessibleNodeLabels(B2, toSet("y", "z")); conf.setCapacityByLabel(B2, "y", 100); conf.setCapacityByLabel(B2, "z", 100); return conf; } public static Configuration getConfigurationWithDefaultQueueLabels( Configuration config) { final String A = CapacitySchedulerConfiguration.ROOT + ".a"; final String B = CapacitySchedulerConfiguration.ROOT + ".b"; CapacitySchedulerConfiguration conf = (CapacitySchedulerConfiguration) getConfigurationWithQueueLabels(config); new CapacitySchedulerConfiguration(config); conf.setDefaultNodeLabelExpression(A, "x"); conf.setDefaultNodeLabelExpression(B, "y"); return conf; } }
13,797
37.977401
95
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestParentQueue { private static final Log LOG = LogFactory.getLog(TestParentQueue.class); RMContext rmContext; YarnConfiguration conf; CapacitySchedulerConfiguration csConf; CapacitySchedulerContext csContext; final static int GB = 1024; final static String DEFAULT_RACK = "/default"; private final ResourceCalculator resourceComparator = new DefaultResourceCalculator(); @Before public void setUp() throws Exception { rmContext = TestUtils.getMockRMContext(); conf = new YarnConfiguration(); csConf = new CapacitySchedulerConfiguration(); csContext = mock(CapacitySchedulerContext.class); when(csContext.getConf()).thenReturn(conf); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getMinimumResourceCapability()).thenReturn( Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(16*GB, 32)); when(csContext.getClusterResource()). thenReturn(Resources.createResource(100 * 16 * GB, 100 * 32)); when(csContext.getApplicationComparator()). thenReturn(CapacityScheduler.applicationComparator); when(csContext.getNonPartitionedQueueComparator()). thenReturn(CapacityScheduler.nonPartitionedQueueComparator); when(csContext.getResourceCalculator()). thenReturn(resourceComparator); when(csContext.getRMContext()).thenReturn(rmContext); } private static final String A = "a"; private static final String B = "b"; private void setupSingleLevelQueues(CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {A, B}); final String Q_A = CapacitySchedulerConfiguration.ROOT + "." + A; conf.setCapacity(Q_A, 30); final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + B; conf.setCapacity(Q_B, 70); LOG.info("Setup top-level queues a and b"); } private FiCaSchedulerApp getMockApplication(int appId, String user) { FiCaSchedulerApp application = mock(FiCaSchedulerApp.class); doReturn(user).when(application).getUser(); doReturn(Resources.createResource(0, 0)).when(application).getHeadroom(); return application; } private void stubQueueAllocation(final CSQueue queue, final Resource clusterResource, final FiCaSchedulerNode node, final int allocation) { stubQueueAllocation(queue, clusterResource, node, allocation, NodeType.NODE_LOCAL); } private void stubQueueAllocation(final CSQueue queue, final Resource clusterResource, final FiCaSchedulerNode node, final int allocation, final NodeType type) { // Simulate the queue allocation doAnswer(new Answer<CSAssignment>() { @Override public CSAssignment answer(InvocationOnMock invocation) throws Throwable { try { throw new Exception(); } catch (Exception e) { LOG.info("FOOBAR q.assignContainers q=" + queue.getQueueName() + " alloc=" + allocation + " node=" + node.getNodeName()); } final Resource allocatedResource = Resources.createResource(allocation); if (queue instanceof ParentQueue) { ((ParentQueue)queue).allocateResource(clusterResource, allocatedResource, RMNodeLabelsManager.NO_LABEL); } else { FiCaSchedulerApp app1 = getMockApplication(0, ""); ((LeafQueue)queue).allocateResource(clusterResource, app1, allocatedResource, null, null); } // Next call - nothing if (allocation > 0) { doReturn(new CSAssignment(Resources.none(), type)).when(queue) .assignContainers(eq(clusterResource), eq(node), any(ResourceLimits.class), any(SchedulingMode.class)); // Mock the node's resource availability Resource available = node.getAvailableResource(); doReturn(Resources.subtractFrom(available, allocatedResource)). when(node).getAvailableResource(); } return new CSAssignment(allocatedResource, type); } }).when(queue).assignContainers(eq(clusterResource), eq(node), any(ResourceLimits.class), any(SchedulingMode.class)); } private float computeQueueAbsoluteUsedCapacity(CSQueue queue, int expectedMemory, Resource clusterResource) { return ( ((float)expectedMemory / (float)clusterResource.getMemory()) ); } private float computeQueueUsedCapacity(CSQueue queue, int expectedMemory, Resource clusterResource) { return (expectedMemory / (clusterResource.getMemory() * queue.getAbsoluteCapacity())); } final static float DELTA = 0.0001f; private void verifyQueueMetrics(CSQueue queue, int expectedMemory, Resource clusterResource) { assertEquals( computeQueueAbsoluteUsedCapacity(queue, expectedMemory, clusterResource), queue.getAbsoluteUsedCapacity(), DELTA); assertEquals( computeQueueUsedCapacity(queue, expectedMemory, clusterResource), queue.getUsedCapacity(), DELTA); } @Test public void testSingleLevelQueues() throws Exception { // Setup queue configs setupSingleLevelQueues(csConf); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CSQueue root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); // Setup some nodes final int memoryPerNode = 10; final int coresPerNode = 16; final int numNodes = 2; FiCaSchedulerNode node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, memoryPerNode*GB); FiCaSchedulerNode node_1 = TestUtils.getMockNode("host_1", DEFAULT_RACK, 0, memoryPerNode*GB); final Resource clusterResource = Resources.createResource(numNodes * (memoryPerNode*GB), numNodes * coresPerNode); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Start testing LeafQueue a = (LeafQueue)queues.get(A); LeafQueue b = (LeafQueue)queues.get(B); a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() .incPending(Resources.createResource(1 * GB)); // Simulate B returning a container on node_0 stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 1*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(a, 0*GB, clusterResource); verifyQueueMetrics(b, 1*GB, clusterResource); // Now, A should get the scheduling opportunity since A=0G/6G, B=1G/14G stubQueueAllocation(a, clusterResource, node_1, 2*GB); stubQueueAllocation(b, clusterResource, node_1, 1*GB); root.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); InOrder allocationOrder = inOrder(a, b); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 2*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); // Now, B should get the scheduling opportunity // since A has 2/6G while B has 2/14G stubQueueAllocation(a, clusterResource, node_0, 1*GB); stubQueueAllocation(b, clusterResource, node_0, 2*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); allocationOrder = inOrder(b, a); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 3*GB, clusterResource); verifyQueueMetrics(b, 4*GB, clusterResource); // Now, B should still get the scheduling opportunity // since A has 3/6G while B has 4/14G stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 4*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); allocationOrder = inOrder(b, a); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 3*GB, clusterResource); verifyQueueMetrics(b, 8*GB, clusterResource); // Now, A should get the scheduling opportunity // since A has 3/6G while B has 8/14G stubQueueAllocation(a, clusterResource, node_1, 1*GB); stubQueueAllocation(b, clusterResource, node_1, 1*GB); root.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); allocationOrder = inOrder(a, b); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 4*GB, clusterResource); verifyQueueMetrics(b, 9*GB, clusterResource); } @Test public void testSingleLevelQueuesPrecision() throws Exception { // Setup queue configs setupSingleLevelQueues(csConf); final String Q_A = CapacitySchedulerConfiguration.ROOT + "." + "a"; csConf.setCapacity(Q_A, 30); final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + "b"; csConf.setCapacity(Q_B, 70.5F); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); boolean exceptionOccured = false; try { CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); } catch (IllegalArgumentException ie) { exceptionOccured = true; } if (!exceptionOccured) { Assert.fail("Capacity is more then 100% so should be failed."); } csConf.setCapacity(Q_A, 30); csConf.setCapacity(Q_B, 70); exceptionOccured = false; queues.clear(); try { CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); } catch (IllegalArgumentException ie) { exceptionOccured = true; } if (exceptionOccured) { Assert.fail("Capacity is 100% so should not be failed."); } csConf.setCapacity(Q_A, 30); csConf.setCapacity(Q_B, 70.005F); exceptionOccured = false; queues.clear(); try { CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); } catch (IllegalArgumentException ie) { exceptionOccured = true; } if (exceptionOccured) { Assert .fail("Capacity is under PRECISION which is .05% so should not be failed."); } } private static final String C = "c"; private static final String C1 = "c1"; private static final String C11 = "c11"; private static final String C111 = "c111"; private static final String C1111 = "c1111"; private static final String D = "d"; private static final String A1 = "a1"; private static final String A2 = "a2"; private static final String B1 = "b1"; private static final String B2 = "b2"; private static final String B3 = "b3"; private void setupMultiLevelQueues(CapacitySchedulerConfiguration conf) { // Define top-level queues csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {A, B, C, D}); final String Q_A = CapacitySchedulerConfiguration.ROOT + "." + A; conf.setCapacity(Q_A, 10); final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + B; conf.setCapacity(Q_B, 50); final String Q_C = CapacitySchedulerConfiguration.ROOT + "." + C; conf.setCapacity(Q_C, 19.5f); final String Q_D = CapacitySchedulerConfiguration.ROOT + "." + D; conf.setCapacity(Q_D, 20.5f); // Define 2-nd level queues conf.setQueues(Q_A, new String[] {A1, A2}); conf.setCapacity(Q_A + "." + A1, 50); conf.setCapacity(Q_A + "." + A2, 50); conf.setQueues(Q_B, new String[] {B1, B2, B3}); conf.setCapacity(Q_B + "." + B1, 10); conf.setCapacity(Q_B + "." + B2, 20); conf.setCapacity(Q_B + "." + B3, 70); conf.setQueues(Q_C, new String[] {C1}); final String Q_C1= Q_C + "." + C1; conf.setCapacity(Q_C1, 100); conf.setQueues(Q_C1, new String[] {C11}); final String Q_C11= Q_C1 + "." + C11; conf.setCapacity(Q_C11, 100); conf.setQueues(Q_C11, new String[] {C111}); final String Q_C111= Q_C11 + "." + C111; conf.setCapacity(Q_C111, 100); //Leaf Queue conf.setQueues(Q_C111, new String[] {C1111}); final String Q_C1111= Q_C111 + "." + C1111; conf.setCapacity(Q_C1111, 100); } @Test public void testMultiLevelQueues() throws Exception { /* * Structure of queue: * Root * ____________ * / | \ \ * A B C D * / | / | \ \ * A1 A2 B1 B2 B3 C1 * \ * C11 * \ * C111 * \ * C1111 */ // Setup queue configs setupMultiLevelQueues(csConf); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CSQueue root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); // Setup some nodes final int memoryPerNode = 10; final int coresPerNode = 16; final int numNodes = 3; FiCaSchedulerNode node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, memoryPerNode*GB); FiCaSchedulerNode node_1 = TestUtils.getMockNode("host_1", DEFAULT_RACK, 0, memoryPerNode*GB); FiCaSchedulerNode node_2 = TestUtils.getMockNode("host_2", DEFAULT_RACK, 0, memoryPerNode*GB); final Resource clusterResource = Resources.createResource(numNodes * (memoryPerNode*GB), numNodes * coresPerNode); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Start testing CSQueue a = queues.get(A); a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue b = queues.get(B); b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue c = queues.get(C); c.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue d = queues.get(D); d.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue a1 = queues.get(A1); a1.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue a2 = queues.get(A2); a2.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue b1 = queues.get(B1); b1.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue b2 = queues.get(B2); b2.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); CSQueue b3 = queues.get(B3); b3.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() .incPending(Resources.createResource(1 * GB)); // Simulate C returning a container on node_0 stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 0*GB); stubQueueAllocation(c, clusterResource, node_0, 1*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(a, 0*GB, clusterResource); verifyQueueMetrics(b, 0*GB, clusterResource); verifyQueueMetrics(c, 1*GB, clusterResource); verifyQueueMetrics(d, 0*GB, clusterResource); reset(a); reset(b); reset(c); // Now get B2 to allocate // A = 0/3, B = 0/15, C = 1/6, D=0/6 stubQueueAllocation(a, clusterResource, node_1, 0*GB); stubQueueAllocation(b2, clusterResource, node_1, 4*GB); stubQueueAllocation(c, clusterResource, node_1, 0*GB); root.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(a, 0*GB, clusterResource); verifyQueueMetrics(b, 4*GB, clusterResource); verifyQueueMetrics(c, 1*GB, clusterResource); reset(a); reset(b); reset(c); // Now get both A1, C & B3 to allocate in right order // A = 0/3, B = 4/15, C = 1/6, D=0/6 stubQueueAllocation(a1, clusterResource, node_0, 1*GB); stubQueueAllocation(b3, clusterResource, node_0, 2*GB); stubQueueAllocation(c, clusterResource, node_0, 2*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); InOrder allocationOrder = inOrder(a, c, b); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(c).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 1*GB, clusterResource); verifyQueueMetrics(b, 6*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); reset(a); reset(b); reset(c); // Now verify max-capacity // A = 1/3, B = 6/15, C = 3/6, D=0/6 // Ensure a1 won't alloc above max-cap although it should get // scheduling opportunity now, right after a2 LOG.info("here"); ((ParentQueue)a).setMaxCapacity(.1f); // a should be capped at 3/30 stubQueueAllocation(a1, clusterResource, node_2, 1*GB); // shouldn't be // allocated due // to max-cap stubQueueAllocation(a2, clusterResource, node_2, 2*GB); stubQueueAllocation(b3, clusterResource, node_2, 1*GB); stubQueueAllocation(b1, clusterResource, node_2, 1*GB); stubQueueAllocation(c, clusterResource, node_2, 1*GB); root.assignContainers(clusterResource, node_2, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); allocationOrder = inOrder(a, a2, a1, b, c); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(a2).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(c).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 3*GB, clusterResource); verifyQueueMetrics(b, 8*GB, clusterResource); verifyQueueMetrics(c, 4*GB, clusterResource); reset(a); reset(b); reset(c); } @Test (expected=IllegalArgumentException.class) public void testQueueCapacitySettingChildZero() throws Exception { // Setup queue configs setupMultiLevelQueues(csConf); // set child queues capacity to 0 when parents not 0 final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + B; csConf.setCapacity(Q_B + "." + B1, 0); csConf.setCapacity(Q_B + "." + B2, 0); csConf.setCapacity(Q_B + "." + B3, 0); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); } @Test (expected=IllegalArgumentException.class) public void testQueueCapacitySettingParentZero() throws Exception { // Setup queue configs setupMultiLevelQueues(csConf); // set parent capacity to 0 when child not 0 final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + B; csConf.setCapacity(Q_B, 0); final String Q_A = CapacitySchedulerConfiguration.ROOT + "." + A; csConf.setCapacity(Q_A, 60); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); } @Test public void testQueueCapacityZero() throws Exception { // Setup queue configs setupMultiLevelQueues(csConf); // set parent and child capacity to 0 final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + B; csConf.setCapacity(Q_B, 0); csConf.setCapacity(Q_B + "." + B1, 0); csConf.setCapacity(Q_B + "." + B2, 0); csConf.setCapacity(Q_B + "." + B3, 0); final String Q_A = CapacitySchedulerConfiguration.ROOT + "." + A; csConf.setCapacity(Q_A, 60); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); try { CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); } catch (IllegalArgumentException e) { fail("Failed to create queues with 0 capacity: " + e); } assertTrue("Failed to create queues with 0 capacity", true); } @Test public void testOffSwitchScheduling() throws Exception { // Setup queue configs setupSingleLevelQueues(csConf); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CSQueue root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); // Setup some nodes final int memoryPerNode = 10; final int coresPerNode = 16; final int numNodes = 2; FiCaSchedulerNode node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, memoryPerNode*GB); FiCaSchedulerNode node_1 = TestUtils.getMockNode("host_1", DEFAULT_RACK, 0, memoryPerNode*GB); final Resource clusterResource = Resources.createResource(numNodes * (memoryPerNode*GB), numNodes * coresPerNode); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Start testing LeafQueue a = (LeafQueue)queues.get(A); LeafQueue b = (LeafQueue)queues.get(B); a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() .incPending(Resources.createResource(1 * GB)); // Simulate B returning a container on node_0 stubQueueAllocation(a, clusterResource, node_0, 0*GB, NodeType.OFF_SWITCH); stubQueueAllocation(b, clusterResource, node_0, 1*GB, NodeType.OFF_SWITCH); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(a, 0*GB, clusterResource); verifyQueueMetrics(b, 1*GB, clusterResource); // Now, A should get the scheduling opportunity since A=0G/6G, B=1G/14G // also, B gets a scheduling opportunity since A allocates RACK_LOCAL stubQueueAllocation(a, clusterResource, node_1, 2*GB, NodeType.RACK_LOCAL); stubQueueAllocation(b, clusterResource, node_1, 1*GB, NodeType.OFF_SWITCH); root.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); InOrder allocationOrder = inOrder(a, b); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 2*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); // Now, B should get the scheduling opportunity // since A has 2/6G while B has 2/14G, // However, since B returns off-switch, A won't get an opportunity stubQueueAllocation(a, clusterResource, node_0, 1*GB, NodeType.NODE_LOCAL); stubQueueAllocation(b, clusterResource, node_0, 2*GB, NodeType.OFF_SWITCH); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); allocationOrder = inOrder(b, a); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(a).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(a, 2*GB, clusterResource); verifyQueueMetrics(b, 4*GB, clusterResource); } @Test public void testOffSwitchSchedulingMultiLevelQueues() throws Exception { // Setup queue configs setupMultiLevelQueues(csConf); //B3 Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CSQueue root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); // Setup some nodes final int memoryPerNode = 10; final int coresPerNode = 10; final int numNodes = 2; FiCaSchedulerNode node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, memoryPerNode*GB); FiCaSchedulerNode node_1 = TestUtils.getMockNode("host_1", DEFAULT_RACK, 0, memoryPerNode*GB); final Resource clusterResource = Resources.createResource(numNodes * (memoryPerNode*GB), numNodes * coresPerNode); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Start testing LeafQueue b3 = (LeafQueue)queues.get(B3); LeafQueue b2 = (LeafQueue)queues.get(B2); b2.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); b3.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() .incPending(Resources.createResource(1 * GB)); CSQueue b = queues.get(B); b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); // Simulate B3 returning a container on node_0 stubQueueAllocation(b2, clusterResource, node_0, 0*GB, NodeType.OFF_SWITCH); stubQueueAllocation(b3, clusterResource, node_0, 1*GB, NodeType.OFF_SWITCH); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(b2, 0*GB, clusterResource); verifyQueueMetrics(b3, 1*GB, clusterResource); // Now, B2 should get the scheduling opportunity since B2=0G/2G, B3=1G/7G // also, B3 gets a scheduling opportunity since B2 allocates RACK_LOCAL stubQueueAllocation(b2, clusterResource, node_1, 1*GB, NodeType.RACK_LOCAL); stubQueueAllocation(b3, clusterResource, node_1, 1*GB, NodeType.OFF_SWITCH); root.assignContainers(clusterResource, node_1, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); InOrder allocationOrder = inOrder(b2, b3); allocationOrder.verify(b2).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(b3).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(b2, 1*GB, clusterResource); verifyQueueMetrics(b3, 2*GB, clusterResource); // Now, B3 should get the scheduling opportunity // since B2 has 1/2G while B3 has 2/7G, // However, since B3 returns off-switch, B2 won't get an opportunity stubQueueAllocation(b2, clusterResource, node_0, 1*GB, NodeType.NODE_LOCAL); stubQueueAllocation(b3, clusterResource, node_0, 1*GB, NodeType.OFF_SWITCH); root.assignContainers(clusterResource, node_0, new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); allocationOrder = inOrder(b3, b2); allocationOrder.verify(b3).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); allocationOrder.verify(b2).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); verifyQueueMetrics(b2, 1*GB, clusterResource); verifyQueueMetrics(b3, 3*GB, clusterResource); } public boolean hasQueueACL(List<QueueUserACLInfo> aclInfos, QueueACL acl, String qName) { for (QueueUserACLInfo aclInfo : aclInfos) { if (aclInfo.getQueueName().equals(qName)) { if (aclInfo.getUserAcls().contains(acl)) { return true; } } } return false; } @Test public void testQueueAcl() throws Exception { setupMultiLevelQueues(csConf); csConf.setAcl(CapacitySchedulerConfiguration.ROOT, QueueACL.SUBMIT_APPLICATIONS, " "); csConf.setAcl(CapacitySchedulerConfiguration.ROOT, QueueACL.ADMINISTER_QUEUE, " "); final String Q_C = CapacitySchedulerConfiguration.ROOT + "." + C; csConf.setAcl(Q_C, QueueACL.ADMINISTER_QUEUE, "*"); final String Q_C11= Q_C + "." + C1 + "." + C11; csConf.setAcl(Q_C11, QueueACL.SUBMIT_APPLICATIONS, "*"); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CSQueue root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); YarnAuthorizationProvider authorizer = YarnAuthorizationProvider.getInstance(conf); CapacityScheduler.setQueueAcls(authorizer, queues); UserGroupInformation user = UserGroupInformation.getCurrentUser(); // Setup queue configs ParentQueue c = (ParentQueue)queues.get(C); ParentQueue c1 = (ParentQueue)queues.get(C1); ParentQueue c11 = (ParentQueue)queues.get(C11); ParentQueue c111 = (ParentQueue)queues.get(C111); assertFalse(root.hasAccess(QueueACL.ADMINISTER_QUEUE, user)); List<QueueUserACLInfo> aclInfos = root.getQueueUserAclInfo(user); assertFalse(hasQueueACL(aclInfos, QueueACL.ADMINISTER_QUEUE, "root")); assertFalse(root.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertFalse(hasQueueACL(aclInfos, QueueACL.SUBMIT_APPLICATIONS, "root")); // c has no SA, but QA assertTrue(c.hasAccess(QueueACL.ADMINISTER_QUEUE, user)); assertTrue(hasQueueACL(aclInfos, QueueACL.ADMINISTER_QUEUE, "c")); assertFalse(c.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertFalse(hasQueueACL(aclInfos, QueueACL.SUBMIT_APPLICATIONS, "c")); //Queue c1 has QA, no SA (gotten perm from parent) assertTrue(c1.hasAccess(QueueACL.ADMINISTER_QUEUE, user)); assertTrue(hasQueueACL(aclInfos, QueueACL.ADMINISTER_QUEUE, "c1")); assertFalse(c1.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertFalse(hasQueueACL(aclInfos, QueueACL.SUBMIT_APPLICATIONS, "c1")); //Queue c11 has permissions from parent queue and SA assertTrue(c11.hasAccess(QueueACL.ADMINISTER_QUEUE, user)); assertTrue(hasQueueACL(aclInfos, QueueACL.ADMINISTER_QUEUE, "c11")); assertTrue(c11.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertTrue(hasQueueACL(aclInfos, QueueACL.SUBMIT_APPLICATIONS, "c11")); //Queue c111 has SA and AQ, both from parent assertTrue(c111.hasAccess(QueueACL.ADMINISTER_QUEUE, user)); assertTrue(hasQueueACL(aclInfos, QueueACL.ADMINISTER_QUEUE, "c111")); assertTrue(c111.hasAccess(QueueACL.SUBMIT_APPLICATIONS, user)); assertTrue(hasQueueACL(aclInfos, QueueACL.SUBMIT_APPLICATIONS, "c111")); reset(c); } @After public void tearDown() throws Exception { } private ResourceLimits anyResourceLimits() { return any(ResourceLimits.class); } }
36,510
42.362233
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacitySchedulerQueueACLs.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.scheduler.capacity; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.QueueACLsTestBase; public class TestCapacitySchedulerQueueACLs extends QueueACLsTestBase { @Override protected Configuration createConfiguration() { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] { QUEUEA, QUEUEB }); csConf.setCapacity(CapacitySchedulerConfiguration.ROOT + "." + QUEUEA, 50f); csConf.setCapacity(CapacitySchedulerConfiguration.ROOT + "." + QUEUEB, 50f); Map<QueueACL, AccessControlList> aclsOnQueueA = new HashMap<QueueACL, AccessControlList>(); AccessControlList submitACLonQueueA = new AccessControlList(QUEUE_A_USER); submitACLonQueueA.addUser(COMMON_USER); AccessControlList adminACLonQueueA = new AccessControlList(QUEUE_A_ADMIN); aclsOnQueueA.put(QueueACL.SUBMIT_APPLICATIONS, submitACLonQueueA); aclsOnQueueA.put(QueueACL.ADMINISTER_QUEUE, adminACLonQueueA); csConf.setAcls(CapacitySchedulerConfiguration.ROOT + "." + QUEUEA, aclsOnQueueA); Map<QueueACL, AccessControlList> aclsOnQueueB = new HashMap<QueueACL, AccessControlList>(); AccessControlList submitACLonQueueB = new AccessControlList(QUEUE_B_USER); submitACLonQueueB.addUser(COMMON_USER); AccessControlList adminACLonQueueB = new AccessControlList(QUEUE_B_ADMIN); aclsOnQueueB.put(QueueACL.SUBMIT_APPLICATIONS, submitACLonQueueB); aclsOnQueueB.put(QueueACL.ADMINISTER_QUEUE, adminACLonQueueB); csConf.setAcls(CapacitySchedulerConfiguration.ROOT + "." + QUEUEB, aclsOnQueueB); Map<QueueACL, AccessControlList> aclsOnRootQueue = new HashMap<QueueACL, AccessControlList>(); AccessControlList submitACLonRoot = new AccessControlList(""); AccessControlList adminACLonRoot = new AccessControlList(ROOT_ADMIN); aclsOnRootQueue.put(QueueACL.SUBMIT_APPLICATIONS, submitACLonRoot); aclsOnRootQueue.put(QueueACL.ADMINISTER_QUEUE, adminACLonRoot); csConf.setAcls(CapacitySchedulerConfiguration.ROOT, aclsOnRootQueue); csConf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); csConf.set("yarn.resourcemanager.scheduler.class", CapacityScheduler.class.getName()); return csConf; } }
3,408
45.067568
90
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestChildQueueOrder.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; 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.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerImpl; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestChildQueueOrder { private static final Log LOG = LogFactory.getLog(TestChildQueueOrder.class); RMContext rmContext; YarnConfiguration conf; CapacitySchedulerConfiguration csConf; CapacitySchedulerContext csContext; final static int GB = 1024; final static String DEFAULT_RACK = "/default"; private final ResourceCalculator resourceComparator = new DefaultResourceCalculator(); @Before public void setUp() throws Exception { rmContext = TestUtils.getMockRMContext(); conf = new YarnConfiguration(); csConf = new CapacitySchedulerConfiguration(); csContext = mock(CapacitySchedulerContext.class); when(csContext.getConf()).thenReturn(conf); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getMinimumResourceCapability()).thenReturn( Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(16*GB, 32)); when(csContext.getClusterResource()). thenReturn(Resources.createResource(100 * 16 * GB, 100 * 32)); when(csContext.getApplicationComparator()). thenReturn(CapacityScheduler.applicationComparator); when(csContext.getNonPartitionedQueueComparator()). thenReturn(CapacityScheduler.nonPartitionedQueueComparator); when(csContext.getResourceCalculator()). thenReturn(resourceComparator); when(csContext.getRMContext()).thenReturn(rmContext); } private FiCaSchedulerApp getMockApplication(int appId, String user) { FiCaSchedulerApp application = mock(FiCaSchedulerApp.class); doReturn(user).when(application).getUser(); doReturn(Resources.createResource(0, 0)).when(application).getHeadroom(); return application; } private void stubQueueAllocation(final CSQueue queue, final Resource clusterResource, final FiCaSchedulerNode node, final int allocation) { stubQueueAllocation(queue, clusterResource, node, allocation, NodeType.NODE_LOCAL); } private void stubQueueAllocation(final CSQueue queue, final Resource clusterResource, final FiCaSchedulerNode node, final int allocation, final NodeType type) { // Simulate the queue allocation doAnswer(new Answer<CSAssignment>() { @Override public CSAssignment answer(InvocationOnMock invocation) throws Throwable { try { throw new Exception(); } catch (Exception e) { LOG.info("FOOBAR q.assignContainers q=" + queue.getQueueName() + " alloc=" + allocation + " node=" + node.getNodeName()); } final Resource allocatedResource = Resources.createResource(allocation); if (queue instanceof ParentQueue) { ((ParentQueue)queue).allocateResource(clusterResource, allocatedResource, RMNodeLabelsManager.NO_LABEL); } else { FiCaSchedulerApp app1 = getMockApplication(0, ""); ((LeafQueue)queue).allocateResource(clusterResource, app1, allocatedResource, null, null); } // Next call - nothing if (allocation > 0) { doReturn(new CSAssignment(Resources.none(), type)). when(queue) .assignContainers(eq(clusterResource), eq(node), any(ResourceLimits.class), any(SchedulingMode.class)); // Mock the node's resource availability Resource available = node.getAvailableResource(); doReturn(Resources.subtractFrom(available, allocatedResource)). when(node).getAvailableResource(); } return new CSAssignment(allocatedResource, type); } }). when(queue).assignContainers(eq(clusterResource), eq(node), any(ResourceLimits.class), any(SchedulingMode.class)); doNothing().when(node).releaseContainer(any(Container.class)); } private float computeQueueAbsoluteUsedCapacity(CSQueue queue, int expectedMemory, Resource clusterResource) { return ( ((float)expectedMemory / (float)clusterResource.getMemory()) ); } private float computeQueueUsedCapacity(CSQueue queue, int expectedMemory, Resource clusterResource) { return (expectedMemory / (clusterResource.getMemory() * queue.getAbsoluteCapacity())); } final static float DELTA = 0.0001f; private void verifyQueueMetrics(CSQueue queue, int expectedMemory, Resource clusterResource) { assertEquals( computeQueueAbsoluteUsedCapacity(queue, expectedMemory, clusterResource), queue.getAbsoluteUsedCapacity(), DELTA); assertEquals( computeQueueUsedCapacity(queue, expectedMemory, clusterResource), queue.getUsedCapacity(), DELTA); } private static final String A = "a"; private static final String B = "b"; private static final String C = "c"; private static final String D = "d"; private void setupSortedQueues(CapacitySchedulerConfiguration conf) { // Define queues csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {A, B, C, D}); final String Q_A = CapacitySchedulerConfiguration.ROOT + "." + A; conf.setCapacity(Q_A, 25); final String Q_B = CapacitySchedulerConfiguration.ROOT + "." + B; conf.setCapacity(Q_B, 25); final String Q_C = CapacitySchedulerConfiguration.ROOT + "." + C; conf.setCapacity(Q_C, 25); final String Q_D = CapacitySchedulerConfiguration.ROOT + "." + D; conf.setCapacity(Q_D, 25); } @Test public void testSortedQueues() throws Exception { // Setup queue configs setupSortedQueues(csConf); Map<String, CSQueue> queues = new HashMap<String, CSQueue>(); CSQueue root = CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); // Setup some nodes final int memoryPerNode = 10; final int coresPerNode = 16; final int numNodes = 1; FiCaSchedulerNode node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, memoryPerNode*GB); doNothing().when(node_0).releaseContainer(any(Container.class)); final Resource clusterResource = Resources.createResource(numNodes * (memoryPerNode*GB), numNodes * coresPerNode); when(csContext.getNumClusterNodes()).thenReturn(numNodes); // Start testing CSQueue a = queues.get(A); CSQueue b = queues.get(B); CSQueue c = queues.get(C); CSQueue d = queues.get(D); // Make a/b/c/d has >0 pending resource, so that allocation will continue. queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() .incPending(Resources.createResource(1 * GB)); a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); c.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); d.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); final String user_0 = "user_0"; // Stub an App and its containerCompleted FiCaSchedulerApp app_0 = getMockApplication(0,user_0); doReturn(true).when(app_0).containerCompleted(any(RMContainer.class), any(ContainerStatus.class), any(RMContainerEventType.class), any(String.class)); Priority priority = TestUtils.createMockPriority(1); ContainerAllocationExpirer expirer = mock(ContainerAllocationExpirer.class); DrainDispatcher drainDispatcher = new DrainDispatcher(); RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class); SystemMetricsPublisher publisher = mock(SystemMetricsPublisher.class); RMContext rmContext = mock(RMContext.class); when(rmContext.getContainerAllocationExpirer()).thenReturn(expirer); when(rmContext.getDispatcher()).thenReturn(drainDispatcher); when(rmContext.getRMApplicationHistoryWriter()).thenReturn(writer); when(rmContext.getSystemMetricsPublisher()).thenReturn(publisher); when(rmContext.getYarnConfiguration()).thenReturn(new YarnConfiguration()); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId( app_0.getApplicationId(), 1); ContainerId containerId = BuilderUtils.newContainerId(appAttemptId, 1); Container container=TestUtils.getMockContainer(containerId, node_0.getNodeID(), Resources.createResource(1*GB), priority); RMContainer rmContainer = new RMContainerImpl(container, appAttemptId, node_0.getNodeID(), "user", rmContext); // Assign {1,2,3,4} 1GB containers respectively to queues stubQueueAllocation(a, clusterResource, node_0, 1*GB); stubQueueAllocation(b, clusterResource, node_0, 0*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); for(int i=0; i < 2; i++) { stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 1*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); } for(int i=0; i < 3; i++) { stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 0*GB); stubQueueAllocation(c, clusterResource, node_0, 1*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); } for(int i=0; i < 4; i++) { stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 0*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 1*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); } verifyQueueMetrics(a, 1*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 4*GB, clusterResource); LOG.info("status child-queues: " + ((ParentQueue)root). getChildQueuesToPrint()); //Release 3 x 1GB containers from D for(int i=0; i < 3;i++) { d.completedContainer(clusterResource, app_0, node_0, rmContainer, null, RMContainerEventType.KILL, null, true); } verifyQueueMetrics(a, 1*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 1*GB, clusterResource); //reset manually resources on node node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, (memoryPerNode-1-2-3-1)*GB); LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); // Assign 2 x 1GB Containers to A for(int i=0; i < 2; i++) { stubQueueAllocation(a, clusterResource, node_0, 1*GB); stubQueueAllocation(b, clusterResource, node_0, 0*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); } verifyQueueMetrics(a, 3*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 1*GB, clusterResource); LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); //Release 1GB Container from A a.completedContainer(clusterResource, app_0, node_0, rmContainer, null, RMContainerEventType.KILL, null, true); verifyQueueMetrics(a, 2*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 1*GB, clusterResource); //reset manually resources on node node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, (memoryPerNode-2-2-3-1)*GB); LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); // Assign 1GB container to B stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 1*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(a, 2*GB, clusterResource); verifyQueueMetrics(b, 3*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 1*GB, clusterResource); LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); //Release 1GB container resources from B b.completedContainer(clusterResource, app_0, node_0, rmContainer, null, RMContainerEventType.KILL, null, true); verifyQueueMetrics(a, 2*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 1*GB, clusterResource); //reset manually resources on node node_0 = TestUtils.getMockNode("host_0", DEFAULT_RACK, 0, (memoryPerNode-2-2-3-1)*GB); LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); // Assign 1GB container to A stubQueueAllocation(a, clusterResource, node_0, 1*GB); stubQueueAllocation(b, clusterResource, node_0, 0*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 0*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); verifyQueueMetrics(a, 3*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 1*GB, clusterResource); LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); // Now do the real test, where B and D request a 1GB container // D should should get the next container if the order is correct stubQueueAllocation(a, clusterResource, node_0, 0*GB); stubQueueAllocation(b, clusterResource, node_0, 1*GB); stubQueueAllocation(c, clusterResource, node_0, 0*GB); stubQueueAllocation(d, clusterResource, node_0, 1*GB); root.assignContainers(clusterResource, node_0, new ResourceLimits( clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); InOrder allocationOrder = inOrder(d,b); allocationOrder.verify(d).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), any(ResourceLimits.class), any(SchedulingMode.class)); allocationOrder.verify(b).assignContainers(eq(clusterResource), any(FiCaSchedulerNode.class), any(ResourceLimits.class), any(SchedulingMode.class)); verifyQueueMetrics(a, 3*GB, clusterResource); verifyQueueMetrics(b, 2*GB, clusterResource); verifyQueueMetrics(c, 3*GB, clusterResource); verifyQueueMetrics(d, 2*GB, clusterResource); //D got the container LOG.info("status child-queues: " + ((ParentQueue)root).getChildQueuesToPrint()); } @After public void tearDown() throws Exception { } }
19,165
42.757991
93
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestContainerAllocation.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.scheduler.capacity; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.SecurityUtilTestHelper; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.LogAggregationContext; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.api.ContainerType; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl; import org.apache.hadoop.yarn.server.resourcemanager.RMSecretManagerService; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; public class TestContainerAllocation { private static final Log LOG = LogFactory .getLog(TestContainerAllocation.class); private final int GB = 1024; private YarnConfiguration conf; RMNodeLabelsManager mgr; @Before public void setUp() throws Exception { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); mgr = new NullRMNodeLabelsManager(); mgr.init(conf); } @Test(timeout = 3000000) public void testExcessReservationThanNodeManagerCapacity() throws Exception { @SuppressWarnings("resource") MockRM rm = new MockRM(conf); rm.start(); // Register node1 MockNM nm1 = rm.registerNode("127.0.0.1:1234", 2 * GB, 4); MockNM nm2 = rm.registerNode("127.0.0.1:2234", 3 * GB, 4); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); // wait.. int waitCount = 20; int size = rm.getRMContext().getRMNodes().size(); while ((size = rm.getRMContext().getRMNodes().size()) != 2 && waitCount-- > 0) { LOG.info("Waiting for node managers to register : " + size); Thread.sleep(100); } Assert.assertEquals(2, rm.getRMContext().getRMNodes().size()); // Submit an application RMApp app1 = rm.submitApp(128); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); LOG.info("sending container requests "); am1.addRequests(new String[] {"*"}, 2 * GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); // send the request // kick the scheduler nm1.nodeHeartbeat(true); int waitCounter = 20; LOG.info("heartbeating nm1"); while (alloc1Response.getAllocatedContainers().size() < 1 && waitCounter-- > 0) { LOG.info("Waiting for containers to be created for app 1..."); Thread.sleep(500); alloc1Response = am1.schedule(); } LOG.info("received container : " + alloc1Response.getAllocatedContainers().size()); // No container should be allocated. // Internally it should not been reserved. Assert.assertTrue(alloc1Response.getAllocatedContainers().size() == 0); LOG.info("heartbeating nm2"); waitCounter = 20; nm2.nodeHeartbeat(true); while (alloc1Response.getAllocatedContainers().size() < 1 && waitCounter-- > 0) { LOG.info("Waiting for containers to be created for app 1..."); Thread.sleep(500); alloc1Response = am1.schedule(); } LOG.info("received container : " + alloc1Response.getAllocatedContainers().size()); Assert.assertTrue(alloc1Response.getAllocatedContainers().size() == 1); rm.stop(); } // This is to test container tokens are generated when the containers are // acquired by the AM, not when the containers are allocated @Test public void testContainerTokenGeneratedOnPullRequest() throws Exception { MockRM rm1 = new MockRM(conf); rm1.start(); MockNM nm1 = rm1.registerNode("127.0.0.1:1234", 8000); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // request a container. am1.allocate("127.0.0.1", 1024, 1, new ArrayList<ContainerId>()); ContainerId containerId2 = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); rm1.waitForState(nm1, containerId2, RMContainerState.ALLOCATED); RMContainer container = rm1.getResourceScheduler().getRMContainer(containerId2); // no container token is generated. Assert.assertEquals(containerId2, container.getContainerId()); Assert.assertNull(container.getContainer().getContainerToken()); // acquire the container. List<Container> containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); Assert.assertEquals(containerId2, containers.get(0).getId()); // container token is generated. Assert.assertNotNull(containers.get(0).getContainerToken()); rm1.stop(); } @Test public void testNormalContainerAllocationWhenDNSUnavailable() throws Exception{ MockRM rm1 = new MockRM(conf); rm1.start(); MockNM nm1 = rm1.registerNode("unknownhost:1234", 8000); RMApp app1 = rm1.submitApp(200); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // request a container. am1.allocate("127.0.0.1", 1024, 1, new ArrayList<ContainerId>()); ContainerId containerId2 = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); rm1.waitForState(nm1, containerId2, RMContainerState.ALLOCATED); // acquire the container. SecurityUtilTestHelper.setTokenServiceUseIp(true); List<Container> containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); // not able to fetch the container; Assert.assertEquals(0, containers.size()); SecurityUtilTestHelper.setTokenServiceUseIp(false); containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); // should be able to fetch the container; Assert.assertEquals(1, containers.size()); } // This is to test whether LogAggregationContext is passed into // container tokens correctly @Test public void testLogAggregationContextPassedIntoContainerToken() throws Exception { MockRM rm1 = new MockRM(conf); rm1.start(); MockNM nm1 = rm1.registerNode("127.0.0.1:1234", 8000); MockNM nm2 = rm1.registerNode("127.0.0.1:2345", 8000); // LogAggregationContext is set as null Assert .assertNull(getLogAggregationContextFromContainerToken(rm1, nm1, null)); // create a not-null LogAggregationContext LogAggregationContext logAggregationContext = LogAggregationContext.newInstance( "includePattern", "excludePattern", "rolledLogsIncludePattern", "rolledLogsExcludePattern"); LogAggregationContext returned = getLogAggregationContextFromContainerToken(rm1, nm2, logAggregationContext); Assert.assertEquals("includePattern", returned.getIncludePattern()); Assert.assertEquals("excludePattern", returned.getExcludePattern()); Assert.assertEquals("rolledLogsIncludePattern", returned.getRolledLogsIncludePattern()); Assert.assertEquals("rolledLogsExcludePattern", returned.getRolledLogsExcludePattern()); rm1.stop(); } private LogAggregationContext getLogAggregationContextFromContainerToken( MockRM rm1, MockNM nm1, LogAggregationContext logAggregationContext) throws Exception { RMApp app2 = rm1.submitApp(200, logAggregationContext); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1); nm1.nodeHeartbeat(true); // request a container. am2.allocate("127.0.0.1", 512, 1, new ArrayList<ContainerId>()); ContainerId containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); rm1.waitForState(nm1, containerId, RMContainerState.ALLOCATED); // acquire the container. List<Container> containers = am2.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); Assert.assertEquals(containerId, containers.get(0).getId()); // container token is generated. Assert.assertNotNull(containers.get(0).getContainerToken()); ContainerTokenIdentifier token = BuilderUtils.newContainerTokenIdentifier(containers.get(0) .getContainerToken()); return token.getLogAggregationContext(); } private volatile int numRetries = 0; private class TestRMSecretManagerService extends RMSecretManagerService { public TestRMSecretManagerService(Configuration conf, RMContextImpl rmContext) { super(conf, rmContext); } @Override protected RMContainerTokenSecretManager createContainerTokenSecretManager( Configuration conf) { return new RMContainerTokenSecretManager(conf) { @Override public Token createContainerToken(ContainerId containerId, NodeId nodeId, String appSubmitter, Resource capability, Priority priority, long createTime, LogAggregationContext logAggregationContext, String nodeLabelExp, ContainerType containerType) { numRetries++; return super.createContainerToken(containerId, nodeId, appSubmitter, capability, priority, createTime, logAggregationContext, nodeLabelExp, containerType); } }; } } // This is to test fetching AM container will be retried, if AM container is // not fetchable since DNS is unavailable causing container token/NMtoken // creation failure. @Test(timeout = 30000) public void testAMContainerAllocationWhenDNSUnavailable() throws Exception { MockRM rm1 = new MockRM(conf) { @Override protected RMSecretManagerService createRMSecretManagerService() { return new TestRMSecretManagerService(conf, rmContext); } }; rm1.start(); MockNM nm1 = rm1.registerNode("unknownhost:1234", 8000); SecurityUtilTestHelper.setTokenServiceUseIp(true); RMApp app1 = rm1.submitApp(200); RMAppAttempt attempt = app1.getCurrentAppAttempt(); nm1.nodeHeartbeat(true); // fetching am container will fail, keep retrying 5 times. while (numRetries <= 5) { nm1.nodeHeartbeat(true); Thread.sleep(1000); Assert.assertEquals(RMAppAttemptState.SCHEDULED, attempt.getAppAttemptState()); System.out.println("Waiting for am container to be allocated."); } SecurityUtilTestHelper.setTokenServiceUseIp(false); MockRM.launchAndRegisterAM(app1, rm1, nm1); } @Test(timeout = 60000) public void testExcessReservationWillBeUnreserved() throws Exception { /** * Test case: Submit two application (app1/app2) to a queue. And there's one * node with 8G resource in the cluster. App1 allocates a 6G container, Then * app2 asks for a 4G container. App2's request will be reserved on the * node. * * Before next node heartbeat, app2 cancels the reservation, we should found * the reserved resource is cancelled as well. */ // inject node label manager MockRM rm1 = new MockRM(); rm1.getRMContext().setNodeLabelManager(mgr); rm1.start(); MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB); MockNM nm2 = rm1.registerNode("h2:1234", 8 * GB); // launch an app to queue, AM container should be launched in nm1 RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "default"); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // launch another app to queue, AM container should be launched in nm1 RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "default"); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1); am1.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>()); am2.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>()); CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId()); // Do node heartbeats 2 times // First time will allocate container for app1, second time will reserve // container for app2 cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); // App2 will get preference to be allocated on node1, and node1 will be all // used by App2. FiCaSchedulerApp schedulerApp1 = cs.getApplicationAttempt(am1.getApplicationAttemptId()); FiCaSchedulerApp schedulerApp2 = cs.getApplicationAttempt(am2.getApplicationAttemptId()); // Check if a 4G contaienr allocated for app1, and nothing allocated for app2 Assert.assertEquals(2, schedulerApp1.getLiveContainers().size()); Assert.assertEquals(1, schedulerApp2.getLiveContainers().size()); Assert.assertTrue(schedulerApp2.getReservedContainers().size() > 0); // NM1 has available resource = 2G (8G - 2 * 1G - 4G) Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId()) .getAvailableResource().getMemory()); Assert.assertNotNull(cs.getNode(nm1.getNodeId()).getReservedContainer()); // Usage of queue = 4G + 2 * 1G + 4G (reserved) Assert.assertEquals(10 * GB, cs.getRootQueue().getQueueResourceUsage() .getUsed().getMemory()); // Cancel asks of app2 and re-kick RM am2.allocate("*", 4 * GB, 0, new ArrayList<ContainerId>()); cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); // App2's reservation will be cancelled Assert.assertTrue(schedulerApp2.getReservedContainers().size() == 0); Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId()) .getAvailableResource().getMemory()); Assert.assertNull(cs.getNode(nm1.getNodeId()).getReservedContainer()); Assert.assertEquals(6 * GB, cs.getRootQueue().getQueueResourceUsage() .getUsed().getMemory()); rm1.close(); } }
16,597
39.982716
108
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacityScheduler.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.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.LocalConfigurationProvider; import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.QueueState; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceOption; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.exceptions.YarnException; 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.ipc.YarnRPC; import org.apache.hadoop.yarn.nodelabels.RMNodeLabel; import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceRequest; import org.apache.hadoop.yarn.server.resourcemanager.AdminService; import org.apache.hadoop.yarn.server.resourcemanager.Application; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockNodes; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.NodeManager; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.Task; import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MockRMWithAMS; import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MyContainerManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppMetrics; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; 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.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNodeReport; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.TestSchedulerUtils; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; 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.scheduler.event.NodeAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.policy.FairOrderingPolicy; import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.CapacitySchedulerInfo; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.CapacitySchedulerLeafQueueInfo; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.CapacitySchedulerQueueInfo; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.CapacitySchedulerQueueInfoList; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; public class TestCapacityScheduler { private static final Log LOG = LogFactory.getLog(TestCapacityScheduler.class); private final int GB = 1024; private static final String A = CapacitySchedulerConfiguration.ROOT + ".a"; private static final String B = CapacitySchedulerConfiguration.ROOT + ".b"; private static final String A1 = A + ".a1"; private static final String A2 = A + ".a2"; private static final String B1 = B + ".b1"; private static final String B2 = B + ".b2"; private static final String B3 = B + ".b3"; private static float A_CAPACITY = 10.5f; private static float B_CAPACITY = 89.5f; private static float A1_CAPACITY = 30; private static float A2_CAPACITY = 70; private static float B1_CAPACITY = 79.2f; private static float B2_CAPACITY = 0.8f; private static float B3_CAPACITY = 20; private ResourceManager resourceManager = null; private RMContext mockContext; @Before public void setUp() throws Exception { resourceManager = new ResourceManager() { @Override protected RMNodeLabelsManager createNodeLabelManager() { RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); mgr.init(getConfig()); return mgr; } }; CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(csConf); YarnConfiguration conf = new YarnConfiguration(csConf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); resourceManager.init(conf); resourceManager.getRMContext().getContainerTokenSecretManager().rollMasterKey(); resourceManager.getRMContext().getNMTokenSecretManager().rollMasterKey(); ((AsyncDispatcher)resourceManager.getRMContext().getDispatcher()).start(); mockContext = mock(RMContext.class); when(mockContext.getConfigurationProvider()).thenReturn( new LocalConfigurationProvider()); } @After public void tearDown() throws Exception { if (resourceManager != null) { resourceManager.stop(); } } @Test (timeout = 30000) public void testConfValidation() throws Exception { ResourceScheduler scheduler = new CapacityScheduler(); scheduler.setRMContext(resourceManager.getRMContext()); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 2048); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 1024); try { scheduler.reinitialize(conf, mockContext); fail("Exception is expected because the min memory allocation is" + " larger than the max memory allocation."); } catch (YarnRuntimeException e) { // Exception is expected. assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler memory")); } conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, 2); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, 1); try { scheduler.reinitialize(conf, mockContext); fail("Exception is expected because the min vcores allocation is" + " larger than the max vcores allocation."); } catch (YarnRuntimeException e) { // Exception is expected. assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler vcores")); } } private org.apache.hadoop.yarn.server.resourcemanager.NodeManager registerNode(String hostName, int containerManagerPort, int httpPort, String rackName, Resource capability) throws IOException, YarnException { org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm = new org.apache.hadoop.yarn.server.resourcemanager.NodeManager( hostName, containerManagerPort, httpPort, rackName, capability, resourceManager); NodeAddedSchedulerEvent nodeAddEvent1 = new NodeAddedSchedulerEvent(resourceManager.getRMContext() .getRMNodes().get(nm.getNodeId())); resourceManager.getResourceScheduler().handle(nodeAddEvent1); return nm; } @Test public void testCapacityScheduler() throws Exception { LOG.info("--- START: testCapacityScheduler ---"); // Register node1 String host_0 = "host_0"; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(4 * GB, 1)); // Register node2 String host_1 = "host_1"; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_1 = registerNode(host_1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(2 * GB, 1)); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.create(1); // Submit an application Application application_0 = new Application("user_0", "a1", resourceManager); application_0.submit(); application_0.addNodeManager(host_0, 1234, nm_0); application_0.addNodeManager(host_1, 1234, nm_1); Resource capability_0_0 = Resources.createResource(1 * GB, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * GB, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] {host_0, host_1}); application_0.addTask(task_0_0); // Submit another application Application application_1 = new Application("user_1", "b2", resourceManager); application_1.submit(); application_1.addNodeManager(host_0, 1234, nm_0); application_1.addNodeManager(host_1, 1234, nm_1); Resource capability_1_0 = Resources.createResource(3 * GB, 1); application_1.addResourceRequestSpec(priority_1, capability_1_0); Resource capability_1_1 = Resources.createResource(2 * GB, 1); application_1.addResourceRequestSpec(priority_0, capability_1_1); Task task_1_0 = new Task(application_1, priority_1, new String[] {host_0, host_1}); application_1.addTask(task_1_0); // Send resource requests to the scheduler application_0.schedule(); application_1.schedule(); // Send a heartbeat to kick the tires on the Scheduler LOG.info("Kick!"); // task_0_0 and task_1_0 allocated, used=4G nodeUpdate(nm_0); // nothing allocated nodeUpdate(nm_1); // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(1 * GB, application_0); application_1.schedule(); // task_1_0 checkApplicationResourceUsage(3 * GB, application_1); checkNodeResourceUsage(4*GB, nm_0); // task_0_0 (1G) and task_1_0 (3G) checkNodeResourceUsage(0*GB, nm_1); // no tasks, 2G available LOG.info("Adding new tasks..."); Task task_1_1 = new Task(application_1, priority_0, new String[] {ResourceRequest.ANY}); application_1.addTask(task_1_1); application_1.schedule(); Task task_0_1 = new Task(application_0, priority_0, new String[] {host_0, host_1}); application_0.addTask(task_0_1); application_0.schedule(); // Send a heartbeat to kick the tires on the Scheduler LOG.info("Sending hb from " + nm_0.getHostName()); // nothing new, used=4G nodeUpdate(nm_0); LOG.info("Sending hb from " + nm_1.getHostName()); // task_0_1 is prefer as locality, used=2G nodeUpdate(nm_1); // Get allocations from the scheduler LOG.info("Trying to allocate..."); application_0.schedule(); checkApplicationResourceUsage(1 * GB, application_0); application_1.schedule(); checkApplicationResourceUsage(5 * GB, application_1); nodeUpdate(nm_0); nodeUpdate(nm_1); checkNodeResourceUsage(4*GB, nm_0); checkNodeResourceUsage(2*GB, nm_1); LOG.info("--- END: testCapacityScheduler ---"); } private void nodeUpdate( org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm) { RMNode node = resourceManager.getRMContext().getRMNodes().get(nm.getNodeId()); // Send a heartbeat to kick the tires on the Scheduler NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node); resourceManager.getResourceScheduler().handle(nodeUpdate); } private CapacitySchedulerConfiguration setupQueueConfiguration( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[] {"a1", "a2"}); conf.setCapacity(A1, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); conf.setQueues(B, new String[] {"b1", "b2", "b3"}); conf.setCapacity(B1, B1_CAPACITY); conf.setUserLimitFactor(B1, 100.0f); conf.setCapacity(B2, B2_CAPACITY); conf.setUserLimitFactor(B2, 100.0f); conf.setCapacity(B3, B3_CAPACITY); conf.setUserLimitFactor(B3, 100.0f); LOG.info("Setup top-level queues a and b"); return conf; } @Test public void testMaximumCapacitySetup() { float delta = 0.0000001f; CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); assertEquals(CapacitySchedulerConfiguration.MAXIMUM_CAPACITY_VALUE,conf.getNonLabeledQueueMaximumCapacity(A),delta); conf.setMaximumCapacity(A, 50.0f); assertEquals(50.0f, conf.getNonLabeledQueueMaximumCapacity(A),delta); conf.setMaximumCapacity(A, -1); assertEquals(CapacitySchedulerConfiguration.MAXIMUM_CAPACITY_VALUE,conf.getNonLabeledQueueMaximumCapacity(A),delta); } @Test public void testRefreshQueues() throws Exception { CapacityScheduler cs = new CapacityScheduler(); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); RMContextImpl rmContext = new RMContextImpl(null, null, null, null, null, null, new RMContainerTokenSecretManager(conf), new NMTokenSecretManagerInRM(conf), new ClientToAMTokenSecretManagerInRM(), null); setupQueueConfiguration(conf); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); cs.init(conf); cs.start(); cs.reinitialize(conf, rmContext); checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY); conf.setCapacity(A, 80f); conf.setCapacity(B, 20f); cs.reinitialize(conf, mockContext); checkQueueCapacities(cs, 80f, 20f); cs.stop(); } void checkQueueCapacities(CapacityScheduler cs, float capacityA, float capacityB) { CSQueue rootQueue = cs.getRootQueue(); CSQueue queueA = findQueue(rootQueue, A); CSQueue queueB = findQueue(rootQueue, B); CSQueue queueA1 = findQueue(queueA, A1); CSQueue queueA2 = findQueue(queueA, A2); CSQueue queueB1 = findQueue(queueB, B1); CSQueue queueB2 = findQueue(queueB, B2); CSQueue queueB3 = findQueue(queueB, B3); float capA = capacityA / 100.0f; float capB = capacityB / 100.0f; checkQueueCapacity(queueA, capA, capA, 1.0f, 1.0f); checkQueueCapacity(queueB, capB, capB, 1.0f, 1.0f); checkQueueCapacity(queueA1, A1_CAPACITY / 100.0f, (A1_CAPACITY/100.0f) * capA, 1.0f, 1.0f); checkQueueCapacity(queueA2, A2_CAPACITY / 100.0f, (A2_CAPACITY/100.0f) * capA, 1.0f, 1.0f); checkQueueCapacity(queueB1, B1_CAPACITY / 100.0f, (B1_CAPACITY/100.0f) * capB, 1.0f, 1.0f); checkQueueCapacity(queueB2, B2_CAPACITY / 100.0f, (B2_CAPACITY/100.0f) * capB, 1.0f, 1.0f); checkQueueCapacity(queueB3, B3_CAPACITY / 100.0f, (B3_CAPACITY/100.0f) * capB, 1.0f, 1.0f); } private void checkQueueCapacity(CSQueue q, float expectedCapacity, float expectedAbsCapacity, float expectedMaxCapacity, float expectedAbsMaxCapacity) { final float epsilon = 1e-5f; assertEquals("capacity", expectedCapacity, q.getCapacity(), epsilon); assertEquals("absolute capacity", expectedAbsCapacity, q.getAbsoluteCapacity(), epsilon); assertEquals("maximum capacity", expectedMaxCapacity, q.getMaximumCapacity(), epsilon); assertEquals("absolute maximum capacity", expectedAbsMaxCapacity, q.getAbsoluteMaximumCapacity(), epsilon); } private CSQueue findQueue(CSQueue root, String queuePath) { if (root.getQueuePath().equals(queuePath)) { return root; } List<CSQueue> childQueues = root.getChildQueues(); if (childQueues != null) { for (CSQueue q : childQueues) { if (queuePath.startsWith(q.getQueuePath())) { CSQueue result = findQueue(q, queuePath); if (result != null) { return result; } } } } return null; } private void checkApplicationResourceUsage(int expected, Application application) { Assert.assertEquals(expected, application.getUsedResources().getMemory()); } private void checkNodeResourceUsage(int expected, org.apache.hadoop.yarn.server.resourcemanager.NodeManager node) { Assert.assertEquals(expected, node.getUsed().getMemory()); node.checkResourceUsage(); } /** Test that parseQueue throws an exception when two leaf queues have the * same name * @throws IOException */ @Test(expected=IOException.class) public void testParseQueue() throws IOException { CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); cs.init(conf); cs.start(); conf.setQueues(CapacitySchedulerConfiguration.ROOT + ".a.a1", new String[] {"b1"} ); conf.setCapacity(CapacitySchedulerConfiguration.ROOT + ".a.a1.b1", 100.0f); conf.setUserLimitFactor(CapacitySchedulerConfiguration.ROOT + ".a.a1.b1", 100.0f); cs.reinitialize(conf, new RMContextImpl(null, null, null, null, null, null, new RMContainerTokenSecretManager(conf), new NMTokenSecretManagerInRM(conf), new ClientToAMTokenSecretManagerInRM(), null)); } @Test public void testReconnectedNode() throws Exception { CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(csConf); CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); cs.init(csConf); cs.start(); cs.reinitialize(csConf, new RMContextImpl(null, null, null, null, null, null, new RMContainerTokenSecretManager(csConf), new NMTokenSecretManagerInRM(csConf), new ClientToAMTokenSecretManagerInRM(), null)); RMNode n1 = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1); RMNode n2 = MockNodes.newNodeInfo(0, MockNodes.newResource(2 * GB), 2); cs.handle(new NodeAddedSchedulerEvent(n1)); cs.handle(new NodeAddedSchedulerEvent(n2)); Assert.assertEquals(6 * GB, cs.getClusterResource().getMemory()); // reconnect n1 with downgraded memory n1 = MockNodes.newNodeInfo(0, MockNodes.newResource(2 * GB), 1); cs.handle(new NodeRemovedSchedulerEvent(n1)); cs.handle(new NodeAddedSchedulerEvent(n1)); Assert.assertEquals(4 * GB, cs.getClusterResource().getMemory()); cs.stop(); } @Test public void testRefreshQueuesWithNewQueue() throws Exception { CapacityScheduler cs = new CapacityScheduler(); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); cs.init(conf); cs.start(); cs.reinitialize(conf, new RMContextImpl(null, null, null, null, null, null, new RMContainerTokenSecretManager(conf), new NMTokenSecretManagerInRM(conf), new ClientToAMTokenSecretManagerInRM(), null)); checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY); // Add a new queue b4 String B4 = B + ".b4"; float B4_CAPACITY = 10; B3_CAPACITY -= B4_CAPACITY; try { conf.setCapacity(A, 80f); conf.setCapacity(B, 20f); conf.setQueues(B, new String[] {"b1", "b2", "b3", "b4"}); conf.setCapacity(B1, B1_CAPACITY); conf.setCapacity(B2, B2_CAPACITY); conf.setCapacity(B3, B3_CAPACITY); conf.setCapacity(B4, B4_CAPACITY); cs.reinitialize(conf,mockContext); checkQueueCapacities(cs, 80f, 20f); // Verify parent for B4 CSQueue rootQueue = cs.getRootQueue(); CSQueue queueB = findQueue(rootQueue, B); CSQueue queueB4 = findQueue(queueB, B4); assertEquals(queueB, queueB4.getParent()); } finally { B3_CAPACITY += B4_CAPACITY; cs.stop(); } } @Test public void testCapacitySchedulerInfo() throws Exception { QueueInfo queueInfo = resourceManager.getResourceScheduler().getQueueInfo("a", true, true); Assert.assertEquals(queueInfo.getQueueName(), "a"); Assert.assertEquals(queueInfo.getChildQueues().size(), 2); List<QueueUserACLInfo> userACLInfo = resourceManager.getResourceScheduler().getQueueUserAclInfo(); Assert.assertNotNull(userACLInfo); for (QueueUserACLInfo queueUserACLInfo : userACLInfo) { Assert.assertEquals(getQueueCount(userACLInfo, queueUserACLInfo.getQueueName()), 1); } } private int getQueueCount(List<QueueUserACLInfo> queueInformation, String queueName) { int result = 0; for (QueueUserACLInfo queueUserACLInfo : queueInformation) { if (queueName.equals(queueUserACLInfo.getQueueName())) { result++; } } return result; } @Test public void testBlackListNodes() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); String host = "127.0.0.1"; RMNode node = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1, host); cs.handle(new NodeAddedSchedulerEvent(node)); ApplicationId appId = BuilderUtils.newApplicationId(100, 1); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId( appId, 1); RMAppAttemptMetrics attemptMetric = new RMAppAttemptMetrics(appAttemptId, rm.getRMContext()); RMAppImpl app = mock(RMAppImpl.class); when(app.getApplicationId()).thenReturn(appId); RMAppAttemptImpl attempt = mock(RMAppAttemptImpl.class); when(attempt.getAppAttemptId()).thenReturn(appAttemptId); when(attempt.getRMAppAttemptMetrics()).thenReturn(attemptMetric); when(app.getCurrentAppAttempt()).thenReturn(attempt); rm.getRMContext().getRMApps().put(appId, app); SchedulerEvent addAppEvent = new AppAddedSchedulerEvent(appId, "default", "user"); cs.handle(addAppEvent); SchedulerEvent addAttemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId, false); cs.handle(addAttemptEvent); // Verify the blacklist can be updated independent of requesting containers cs.allocate(appAttemptId, Collections.<ResourceRequest>emptyList(), Collections.<ContainerId>emptyList(), Collections.singletonList(host), null); Assert.assertTrue(cs.getApplicationAttempt(appAttemptId).isBlacklisted(host)); cs.allocate(appAttemptId, Collections.<ResourceRequest>emptyList(), Collections.<ContainerId>emptyList(), null, Collections.singletonList(host)); Assert.assertFalse(cs.getApplicationAttempt(appAttemptId).isBlacklisted(host)); rm.stop(); } @Test public void testAllocateReorder() throws Exception { //Confirm that allocation (resource request) alone will trigger a change in //application ordering where appropriate Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); LeafQueue q = (LeafQueue) cs.getQueue("default"); Assert.assertNotNull(q); FairOrderingPolicy fop = new FairOrderingPolicy(); fop.setSizeBasedWeight(true); q.setOrderingPolicy(fop); String host = "127.0.0.1"; RMNode node = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1, host); cs.handle(new NodeAddedSchedulerEvent(node)); //add app begin ApplicationId appId1 = BuilderUtils.newApplicationId(100, 1); ApplicationAttemptId appAttemptId1 = BuilderUtils.newApplicationAttemptId( appId1, 1); RMAppAttemptMetrics attemptMetric1 = new RMAppAttemptMetrics(appAttemptId1, rm.getRMContext()); RMAppImpl app1 = mock(RMAppImpl.class); when(app1.getApplicationId()).thenReturn(appId1); RMAppAttemptImpl attempt1 = mock(RMAppAttemptImpl.class); when(attempt1.getAppAttemptId()).thenReturn(appAttemptId1); when(attempt1.getRMAppAttemptMetrics()).thenReturn(attemptMetric1); when(app1.getCurrentAppAttempt()).thenReturn(attempt1); rm.getRMContext().getRMApps().put(appId1, app1); SchedulerEvent addAppEvent1 = new AppAddedSchedulerEvent(appId1, "default", "user"); cs.handle(addAppEvent1); SchedulerEvent addAttemptEvent1 = new AppAttemptAddedSchedulerEvent(appAttemptId1, false); cs.handle(addAttemptEvent1); //add app end //add app begin ApplicationId appId2 = BuilderUtils.newApplicationId(100, 2); ApplicationAttemptId appAttemptId2 = BuilderUtils.newApplicationAttemptId( appId2, 1); RMAppAttemptMetrics attemptMetric2 = new RMAppAttemptMetrics(appAttemptId2, rm.getRMContext()); RMAppImpl app2 = mock(RMAppImpl.class); when(app2.getApplicationId()).thenReturn(appId2); RMAppAttemptImpl attempt2 = mock(RMAppAttemptImpl.class); when(attempt2.getAppAttemptId()).thenReturn(appAttemptId2); when(attempt2.getRMAppAttemptMetrics()).thenReturn(attemptMetric2); when(app2.getCurrentAppAttempt()).thenReturn(attempt2); rm.getRMContext().getRMApps().put(appId2, app2); SchedulerEvent addAppEvent2 = new AppAddedSchedulerEvent(appId2, "default", "user"); cs.handle(addAppEvent2); SchedulerEvent addAttemptEvent2 = new AppAttemptAddedSchedulerEvent(appAttemptId2, false); cs.handle(addAttemptEvent2); //add app end RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); Priority priority = TestUtils.createMockPriority(1); ResourceRequest r1 = TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory); //This will allocate for app1 cs.allocate(appAttemptId1, Collections.<ResourceRequest>singletonList(r1), Collections.<ContainerId>emptyList(), null, null); //And this will result in container assignment for app1 CapacityScheduler.schedule(cs); //Verify that app1 is still first in assignment order //This happens because app2 has no demand/a magnitude of NaN, which //results in app1 and app2 being equal in the fairness comparison and //failling back to fifo (start) ordering assertEquals(q.getOrderingPolicy().getAssignmentIterator().next().getId(), appId1.toString()); //Now, allocate for app2 (this would be the first/AM allocation) ResourceRequest r2 = TestUtils.createResourceRequest(ResourceRequest.ANY, 1*GB, 1, true, priority, recordFactory); cs.allocate(appAttemptId2, Collections.<ResourceRequest>singletonList(r2), Collections.<ContainerId>emptyList(), null, null); //In this case we do not perform container assignment because we want to //verify re-ordering based on the allocation alone //Now, the first app for assignment is app2 assertEquals(q.getOrderingPolicy().getAssignmentIterator().next().getId(), appId2.toString()); rm.stop(); } @Test public void testResourceOverCommit() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 4 * GB); RMApp app1 = rm.submitApp(2048); // kick the scheduling, 2 GB given to AM1, remaining 2GB on nm1 nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport( nm1.getNodeId()); // check node report, 2 GB used and 2 GB available Assert.assertEquals(2 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(2 * GB, report_nm1.getAvailableResource().getMemory()); // add request for containers am1.addRequests(new String[] { "127.0.0.1", "127.0.0.2" }, 2 * GB, 1, 1); AllocateResponse alloc1Response = am1.schedule(); // send the request // kick the scheduler, 2 GB given to AM1, resource remaining 0 nm1.nodeHeartbeat(true); while (alloc1Response.getAllocatedContainers().size() < 1) { LOG.info("Waiting for containers to be created for app 1..."); Thread.sleep(100); alloc1Response = am1.schedule(); } List<Container> allocated1 = alloc1Response.getAllocatedContainers(); Assert.assertEquals(1, allocated1.size()); Assert.assertEquals(2 * GB, allocated1.get(0).getResource().getMemory()); Assert.assertEquals(nm1.getNodeId(), allocated1.get(0).getNodeId()); report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); // check node report, 4 GB used and 0 GB available Assert.assertEquals(0, report_nm1.getAvailableResource().getMemory()); Assert.assertEquals(4 * GB, report_nm1.getUsedResource().getMemory()); // check container is assigned with 2 GB. Container c1 = allocated1.get(0); Assert.assertEquals(2 * GB, c1.getResource().getMemory()); // update node resource to 2 GB, so resource is over-consumed. Map<NodeId, ResourceOption> nodeResourceMap = new HashMap<NodeId, ResourceOption>(); nodeResourceMap.put(nm1.getNodeId(), ResourceOption.newInstance(Resource.newInstance(2 * GB, 1), -1)); UpdateNodeResourceRequest request = UpdateNodeResourceRequest.newInstance(nodeResourceMap); AdminService as = ((MockRM)rm).getAdminService(); as.updateNodeResource(request); // Now, the used resource is still 4 GB, and available resource is minus value. report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(4 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(-2 * GB, report_nm1.getAvailableResource().getMemory()); // Check container can complete successfully in case of resource over-commitment. ContainerStatus containerStatus = BuilderUtils.newContainerStatus( c1.getId(), ContainerState.COMPLETE, "", 0); nm1.containerStatus(containerStatus); int waitCount = 0; while (attempt1.getJustFinishedContainers().size() < 1 && waitCount++ != 20) { LOG.info("Waiting for containers to be finished for app 1... Tried " + waitCount + " times already.."); Thread.sleep(100); } Assert.assertEquals(1, attempt1.getJustFinishedContainers().size()); Assert.assertEquals(1, am1.schedule().getCompletedContainersStatuses().size()); report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); Assert.assertEquals(2 * GB, report_nm1.getUsedResource().getMemory()); // As container return 2 GB back, the available resource becomes 0 again. Assert.assertEquals(0 * GB, report_nm1.getAvailableResource().getMemory()); // Verify no NPE is trigger in schedule after resource is updated. am1.addRequests(new String[] { "127.0.0.1", "127.0.0.2" }, 3 * GB, 1, 1); alloc1Response = am1.schedule(); Assert.assertEquals("Shouldn't have enough resource to allocate containers", 0, alloc1Response.getAllocatedContainers().size()); int times = 0; // try 10 times as scheduling is async process. while (alloc1Response.getAllocatedContainers().size() < 1 && times++ < 10) { LOG.info("Waiting for containers to be allocated for app 1... Tried " + times + " times already.."); Thread.sleep(100); } Assert.assertEquals("Shouldn't have enough resource to allocate containers", 0, alloc1Response.getAllocatedContainers().size()); rm.stop(); } @Test (timeout = 5000) public void testApplicationComparator() { CapacityScheduler cs = new CapacityScheduler(); Comparator<FiCaSchedulerApp> appComparator= cs.getApplicationComparator(); ApplicationId id1 = ApplicationId.newInstance(1, 1); ApplicationId id2 = ApplicationId.newInstance(1, 2); ApplicationId id3 = ApplicationId.newInstance(2, 1); Priority priority = Priority.newInstance(0); //same clusterId FiCaSchedulerApp app1 = Mockito.mock(FiCaSchedulerApp.class); when(app1.getApplicationId()).thenReturn(id1); when(app1.getPriority()).thenReturn(priority); FiCaSchedulerApp app2 = Mockito.mock(FiCaSchedulerApp.class); when(app2.getApplicationId()).thenReturn(id2); when(app2.getPriority()).thenReturn(priority); FiCaSchedulerApp app3 = Mockito.mock(FiCaSchedulerApp.class); when(app3.getApplicationId()).thenReturn(id3); when(app3.getPriority()).thenReturn(priority); assertTrue(appComparator.compare(app1, app2) < 0); //different clusterId assertTrue(appComparator.compare(app1, app3) < 0); assertTrue(appComparator.compare(app2, app3) < 0); } @Test public void testGetAppsInQueue() throws Exception { Application application_0 = new Application("user_0", "a1", resourceManager); application_0.submit(); Application application_1 = new Application("user_0", "a2", resourceManager); application_1.submit(); Application application_2 = new Application("user_0", "b2", resourceManager); application_2.submit(); ResourceScheduler scheduler = resourceManager.getResourceScheduler(); List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(application_0.getApplicationAttemptId())); assertTrue(appsInA.contains(application_1.getApplicationAttemptId())); assertEquals(2, appsInA.size()); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(application_0.getApplicationAttemptId())); assertTrue(appsInRoot.contains(application_1.getApplicationAttemptId())); assertTrue(appsInRoot.contains(application_2.getApplicationAttemptId())); assertEquals(3, appsInRoot.size()); Assert.assertNull(scheduler.getAppsInQueue("nonexistentqueue")); } @Test public void testAddAndRemoveAppFromCapacityScheduler() throws Exception { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); @SuppressWarnings("unchecked") AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode> cs = (AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode>) rm .getResourceScheduler(); SchedulerApplication<SchedulerApplicationAttempt> app = TestSchedulerUtils.verifyAppAddedAndRemovedFromScheduler( cs.getSchedulerApplications(), cs, "a1"); Assert.assertEquals("a1", app.getQueue().getQueueName()); } @Test public void testAsyncScheduling() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); final int NODES = 100; // Register nodes for (int i=0; i < NODES; ++i) { String host = "192.168.1." + i; RMNode node = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1, host); cs.handle(new NodeAddedSchedulerEvent(node)); } // Now directly exercise the scheduling loop for (int i=0; i < NODES; ++i) { CapacityScheduler.schedule(cs); } } private MockAM launchAM(RMApp app, MockRM rm, MockNM nm) throws Exception { RMAppAttempt attempt = app.getCurrentAppAttempt(); nm.nodeHeartbeat(true); MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); am.registerAppAttempt(); rm.waitForState(app.getApplicationId(), RMAppState.RUNNING); return am; } private void waitForAppPreemptionInfo(RMApp app, Resource preempted, int numAMPreempted, int numTaskPreempted, Resource currentAttemptPreempted, boolean currentAttemptAMPreempted, int numLatestAttemptTaskPreempted) throws InterruptedException { while (true) { RMAppMetrics appPM = app.getRMAppMetrics(); RMAppAttemptMetrics attemptPM = app.getCurrentAppAttempt().getRMAppAttemptMetrics(); if (appPM.getResourcePreempted().equals(preempted) && appPM.getNumAMContainersPreempted() == numAMPreempted && appPM.getNumNonAMContainersPreempted() == numTaskPreempted && attemptPM.getResourcePreempted().equals(currentAttemptPreempted) && app.getCurrentAppAttempt().getRMAppAttemptMetrics() .getIsPreempted() == currentAttemptAMPreempted && attemptPM.getNumNonAMContainersPreempted() == numLatestAttemptTaskPreempted) { return; } Thread.sleep(500); } } private void waitForNewAttemptCreated(RMApp app, ApplicationAttemptId previousAttemptId) throws InterruptedException { while (app.getCurrentAppAttempt().equals(previousAttemptId)) { Thread.sleep(500); } } @Test(timeout = 30000) public void testAllocateDoesNotBlockOnSchedulerLock() throws Exception { final YarnConfiguration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MyContainerManager containerManager = new MyContainerManager(); final MockRMWithAMS rm = new MockRMWithAMS(conf, containerManager); rm.start(); MockNM nm1 = rm.registerNode("localhost:1234", 5120); Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(2); acls.put(ApplicationAccessType.VIEW_APP, "*"); RMApp app = rm.submitApp(1024, "appname", "appuser", acls); nm1.nodeHeartbeat(true); RMAppAttempt attempt = app.getCurrentAppAttempt(); ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId(); int msecToWait = 10000; int msecToSleep = 100; while (attempt.getAppAttemptState() != RMAppAttemptState.LAUNCHED && msecToWait > 0) { LOG.info("Waiting for AppAttempt to reach LAUNCHED state. " + "Current state is " + attempt.getAppAttemptState()); Thread.sleep(msecToSleep); msecToWait -= msecToSleep; } Assert.assertEquals(attempt.getAppAttemptState(), RMAppAttemptState.LAUNCHED); // Create a client to the RM. final YarnRPC rpc = YarnRPC.create(conf); UserGroupInformation currentUser = UserGroupInformation.createRemoteUser(applicationAttemptId.toString()); Credentials credentials = containerManager.getContainerCredentials(); final InetSocketAddress rmBindAddress = rm.getApplicationMasterService().getBindAddress(); Token<? extends TokenIdentifier> amRMToken = MockRMWithAMS.setupAndReturnAMRMToken(rmBindAddress, credentials.getAllTokens()); currentUser.addToken(amRMToken); ApplicationMasterProtocol client = currentUser.doAs(new PrivilegedAction<ApplicationMasterProtocol>() { @Override public ApplicationMasterProtocol run() { return (ApplicationMasterProtocol) rpc.getProxy( ApplicationMasterProtocol.class, rmBindAddress, conf); } }); RegisterApplicationMasterRequest request = RegisterApplicationMasterRequest.newInstance("localhost", 12345, ""); client.registerApplicationMaster(request); // grab the scheduler lock from another thread // and verify an allocate call in this thread doesn't block on it final CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); final CyclicBarrier barrier = new CyclicBarrier(2); Thread otherThread = new Thread(new Runnable() { @Override public void run() { synchronized(cs) { try { barrier.await(); barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } }); otherThread.start(); barrier.await(); AllocateRequest allocateRequest = AllocateRequest.newInstance(0, 0.0f, null, null, null); client.allocate(allocateRequest); barrier.await(); otherThread.join(); rm.stop(); } @Test public void testNumClusterNodes() throws Exception { YarnConfiguration conf = new YarnConfiguration(); CapacityScheduler cs = new CapacityScheduler(); cs.setConf(conf); RMContext rmContext = TestUtils.getMockRMContext(); cs.setRMContext(rmContext); CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(csConf); cs.init(csConf); cs.start(); assertEquals(0, cs.getNumClusterNodes()); RMNode n1 = MockNodes.newNodeInfo(0, MockNodes.newResource(4 * GB), 1); RMNode n2 = MockNodes.newNodeInfo(0, MockNodes.newResource(2 * GB), 2); cs.handle(new NodeAddedSchedulerEvent(n1)); cs.handle(new NodeAddedSchedulerEvent(n2)); assertEquals(2, cs.getNumClusterNodes()); cs.handle(new NodeRemovedSchedulerEvent(n1)); assertEquals(1, cs.getNumClusterNodes()); cs.handle(new NodeAddedSchedulerEvent(n1)); assertEquals(2, cs.getNumClusterNodes()); cs.handle(new NodeRemovedSchedulerEvent(n2)); cs.handle(new NodeRemovedSchedulerEvent(n1)); assertEquals(0, cs.getNumClusterNodes()); cs.stop(); } @Test(timeout = 120000) public void testPreemptionInfo() throws Exception { Configuration conf = new Configuration(); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 3); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); int CONTAINER_MEMORY = 1024; // start RM MockRM rm1 = new MockRM(conf); rm1.start(); // get scheduler CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); // start NM MockNM nm1 = new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService()); nm1.registerNode(); // create app and launch the AM RMApp app0 = rm1.submitApp(CONTAINER_MEMORY); MockAM am0 = launchAM(app0, rm1, nm1); // get scheduler app FiCaSchedulerApp schedulerAppAttempt = cs.getSchedulerApplications().get(app0.getApplicationId()) .getCurrentAppAttempt(); // allocate some containers and launch them List<Container> allocatedContainers = am0.allocateAndWaitForContainers(3, CONTAINER_MEMORY, nm1); // kill the 3 containers for (Container c : allocatedContainers) { cs.killContainer(schedulerAppAttempt.getRMContainer(c.getId())); } // check values waitForAppPreemptionInfo(app0, Resource.newInstance(CONTAINER_MEMORY * 3, 3), 0, 3, Resource.newInstance(CONTAINER_MEMORY * 3, 3), false, 3); // kill app0-attempt0 AM container cs.killContainer(schedulerAppAttempt.getRMContainer(app0 .getCurrentAppAttempt().getMasterContainer().getId())); // wait for app0 failed waitForNewAttemptCreated(app0, am0.getApplicationAttemptId()); // check values waitForAppPreemptionInfo(app0, Resource.newInstance(CONTAINER_MEMORY * 4, 4), 1, 3, Resource.newInstance(0, 0), false, 0); // launch app0-attempt1 MockAM am1 = launchAM(app0, rm1, nm1); schedulerAppAttempt = cs.getSchedulerApplications().get(app0.getApplicationId()) .getCurrentAppAttempt(); // allocate some containers and launch them allocatedContainers = am1.allocateAndWaitForContainers(3, CONTAINER_MEMORY, nm1); for (Container c : allocatedContainers) { cs.killContainer(schedulerAppAttempt.getRMContainer(c.getId())); } // check values waitForAppPreemptionInfo(app0, Resource.newInstance(CONTAINER_MEMORY * 7, 7), 1, 6, Resource.newInstance(CONTAINER_MEMORY * 3, 3), false, 3); rm1.stop(); } @Test(timeout = 30000) public void testRecoverRequestAfterPreemption() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm1 = new MockRM(conf); rm1.start(); MockNM nm1 = rm1.registerNode("127.0.0.1:1234", 8000); RMApp app1 = rm1.submitApp(1024); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); // request a container. am1.allocate("127.0.0.1", 1024, 1, new ArrayList<ContainerId>()); ContainerId containerId1 = ContainerId.newContainerId( am1.getApplicationAttemptId(), 2); rm1.waitForState(nm1, containerId1, RMContainerState.ALLOCATED); RMContainer rmContainer = cs.getRMContainer(containerId1); List<ResourceRequest> requests = rmContainer.getResourceRequests(); FiCaSchedulerApp app = cs.getApplicationAttempt(am1 .getApplicationAttemptId()); FiCaSchedulerNode node = cs.getNode(rmContainer.getAllocatedNode()); for (ResourceRequest request : requests) { // Skip the OffRack and RackLocal resource requests. if (request.getResourceName().equals(node.getRackName()) || request.getResourceName().equals(ResourceRequest.ANY)) { continue; } // Already the node local resource request is cleared from RM after // allocation. Assert.assertNull(app.getResourceRequest(request.getPriority(), request.getResourceName())); } // Call killContainer to preempt the container cs.killContainer(rmContainer); Assert.assertEquals(3, requests.size()); for (ResourceRequest request : requests) { // Resource request must have added back in RM after preempt event // handling. Assert.assertEquals( 1, app.getResourceRequest(request.getPriority(), request.getResourceName()).getNumContainers()); } // New container will be allocated and will move to ALLOCATED state ContainerId containerId2 = ContainerId.newContainerId( am1.getApplicationAttemptId(), 3); rm1.waitForState(nm1, containerId2, RMContainerState.ALLOCATED); // allocate container List<Container> containers = am1.allocate(new ArrayList<ResourceRequest>(), new ArrayList<ContainerId>()).getAllocatedContainers(); // Now with updated ResourceRequest, a container is allocated for AM. Assert.assertTrue(containers.size() == 1); } private MockRM setUpMove() { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); return setUpMove(conf); } private MockRM setUpMove(Configuration config) { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(config); setupQueueConfiguration(conf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); return rm; } @Test public void testMoveAppBasic() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); String queue = scheduler.getApplicationAttempt(appsInA1.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("a1")); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); List<ApplicationAttemptId> appsInB1 = scheduler.getAppsInQueue("b1"); assertTrue(appsInB1.isEmpty()); List<ApplicationAttemptId> appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.isEmpty()); // now move the app scheduler.moveApplication(app.getApplicationId(), "b1"); // check postconditions appsInB1 = scheduler.getAppsInQueue("b1"); assertEquals(1, appsInB1.size()); queue = scheduler.getApplicationAttempt(appsInB1.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("b1")); appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.contains(appAttemptId)); assertEquals(1, appsInB.size()); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); appsInA1 = scheduler.getAppsInQueue("a1"); assertTrue(appsInA1.isEmpty()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.isEmpty()); rm.stop(); } @Test public void testMoveAppSameParent() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); String queue = scheduler.getApplicationAttempt(appsInA1.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("a1")); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); List<ApplicationAttemptId> appsInA2 = scheduler.getAppsInQueue("a2"); assertTrue(appsInA2.isEmpty()); // now move the app scheduler.moveApplication(app.getApplicationId(), "a2"); // check postconditions appsInA2 = scheduler.getAppsInQueue("a2"); assertEquals(1, appsInA2.size()); queue = scheduler.getApplicationAttempt(appsInA2.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("a2")); appsInA1 = scheduler.getAppsInQueue("a1"); assertTrue(appsInA1.isEmpty()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); rm.stop(); } @Test public void testMoveAppForMoveToQueueWithFreeCap() throws Exception { ResourceScheduler scheduler = resourceManager.getResourceScheduler(); // Register node1 String host_0 = "host_0"; NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(4 * GB, 1)); // Register node2 String host_1 = "host_1"; NodeManager nm_1 = registerNode(host_1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(2 * GB, 1)); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(1); // Submit application_0 Application application_0 = new Application("user_0", "a1", resourceManager); application_0.submit(); // app + app attempt event sent to scheduler application_0.addNodeManager(host_0, 1234, nm_0); application_0.addNodeManager(host_1, 1234, nm_1); Resource capability_0_0 = Resources.createResource(1 * GB, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * GB, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] { host_0, host_1 }); application_0.addTask(task_0_0); // Submit application_1 Application application_1 = new Application("user_1", "b2", resourceManager); application_1.submit(); // app + app attempt event sent to scheduler application_1.addNodeManager(host_0, 1234, nm_0); application_1.addNodeManager(host_1, 1234, nm_1); Resource capability_1_0 = Resources.createResource(1 * GB, 1); application_1.addResourceRequestSpec(priority_1, capability_1_0); Resource capability_1_1 = Resources.createResource(2 * GB, 1); application_1.addResourceRequestSpec(priority_0, capability_1_1); Task task_1_0 = new Task(application_1, priority_1, new String[] { host_0, host_1 }); application_1.addTask(task_1_0); // Send resource requests to the scheduler application_0.schedule(); // allocate application_1.schedule(); // allocate // task_0_0 task_1_0 allocated, used=2G nodeUpdate(nm_0); // nothing allocated nodeUpdate(nm_1); // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(1 * GB, application_0); application_1.schedule(); // task_1_0 checkApplicationResourceUsage(1 * GB, application_1); checkNodeResourceUsage(2 * GB, nm_0); // task_0_0 (1G) and task_1_0 (1G) 2G // available checkNodeResourceUsage(0 * GB, nm_1); // no tasks, 2G available // move app from a1(30% cap of total 10.5% cap) to b1(79,2% cap of 89,5% // total cap) scheduler.moveApplication(application_0.getApplicationId(), "b1"); // 2GB 1C Task task_1_1 = new Task(application_1, priority_0, new String[] { ResourceRequest.ANY }); application_1.addTask(task_1_1); application_1.schedule(); // 2GB 1C Task task_0_1 = new Task(application_0, priority_0, new String[] { host_0, host_1 }); application_0.addTask(task_0_1); application_0.schedule(); // prev 2G used free 2G nodeUpdate(nm_0); // prev 0G used free 2G nodeUpdate(nm_1); // Get allocations from the scheduler application_1.schedule(); checkApplicationResourceUsage(3 * GB, application_1); // Get allocations from the scheduler application_0.schedule(); checkApplicationResourceUsage(3 * GB, application_0); checkNodeResourceUsage(4 * GB, nm_0); checkNodeResourceUsage(2 * GB, nm_1); } @Test public void testMoveAppSuccess() throws Exception { ResourceScheduler scheduler = resourceManager.getResourceScheduler(); // Register node1 String host_0 = "host_0"; NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(5 * GB, 1)); // Register node2 String host_1 = "host_1"; NodeManager nm_1 = registerNode(host_1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(5 * GB, 1)); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(1); // Submit application_0 Application application_0 = new Application("user_0", "a1", resourceManager); application_0.submit(); // app + app attempt event sent to scheduler application_0.addNodeManager(host_0, 1234, nm_0); application_0.addNodeManager(host_1, 1234, nm_1); Resource capability_0_0 = Resources.createResource(3 * GB, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * GB, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] { host_0, host_1 }); application_0.addTask(task_0_0); // Submit application_1 Application application_1 = new Application("user_1", "b2", resourceManager); application_1.submit(); // app + app attempt event sent to scheduler application_1.addNodeManager(host_0, 1234, nm_0); application_1.addNodeManager(host_1, 1234, nm_1); Resource capability_1_0 = Resources.createResource(1 * GB, 1); application_1.addResourceRequestSpec(priority_1, capability_1_0); Resource capability_1_1 = Resources.createResource(2 * GB, 1); application_1.addResourceRequestSpec(priority_0, capability_1_1); Task task_1_0 = new Task(application_1, priority_1, new String[] { host_0, host_1 }); application_1.addTask(task_1_0); // Send resource requests to the scheduler application_0.schedule(); // allocate application_1.schedule(); // allocate // b2 can only run 1 app at a time scheduler.moveApplication(application_0.getApplicationId(), "b2"); nodeUpdate(nm_0); nodeUpdate(nm_1); // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(0 * GB, application_0); application_1.schedule(); // task_1_0 checkApplicationResourceUsage(1 * GB, application_1); // task_1_0 (1G) application_0 moved to b2 with max running app 1 so it is // not scheduled checkNodeResourceUsage(1 * GB, nm_0); checkNodeResourceUsage(0 * GB, nm_1); // lets move application_0 to a queue where it can run scheduler.moveApplication(application_0.getApplicationId(), "a2"); application_0.schedule(); nodeUpdate(nm_1); // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(3 * GB, application_0); checkNodeResourceUsage(1 * GB, nm_0); checkNodeResourceUsage(3 * GB, nm_1); } @Test(expected = YarnException.class) public void testMoveAppViolateQueueState() throws Exception { resourceManager = new ResourceManager() { @Override protected RMNodeLabelsManager createNodeLabelManager() { RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); mgr.init(getConfig()); return mgr; } }; CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(csConf); StringBuilder qState = new StringBuilder(); qState.append(CapacitySchedulerConfiguration.PREFIX).append(B) .append(CapacitySchedulerConfiguration.DOT) .append(CapacitySchedulerConfiguration.STATE); csConf.set(qState.toString(), QueueState.STOPPED.name()); YarnConfiguration conf = new YarnConfiguration(csConf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); resourceManager.init(conf); resourceManager.getRMContext().getContainerTokenSecretManager() .rollMasterKey(); resourceManager.getRMContext().getNMTokenSecretManager().rollMasterKey(); ((AsyncDispatcher) resourceManager.getRMContext().getDispatcher()).start(); mockContext = mock(RMContext.class); when(mockContext.getConfigurationProvider()).thenReturn( new LocalConfigurationProvider()); ResourceScheduler scheduler = resourceManager.getResourceScheduler(); // Register node1 String host_0 = "host_0"; NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(6 * GB, 1)); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(1); // Submit application_0 Application application_0 = new Application("user_0", "a1", resourceManager); application_0.submit(); // app + app attempt event sent to scheduler application_0.addNodeManager(host_0, 1234, nm_0); Resource capability_0_0 = Resources.createResource(3 * GB, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * GB, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] { host_0 }); application_0.addTask(task_0_0); // Send resource requests to the scheduler application_0.schedule(); // allocate // task_0_0 allocated nodeUpdate(nm_0); // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(3 * GB, application_0); checkNodeResourceUsage(3 * GB, nm_0); // b2 queue contains 3GB consumption app, // add another 3GB will hit max capacity limit on queue b scheduler.moveApplication(application_0.getApplicationId(), "b1"); } @Test public void testMoveAppQueueMetricsCheck() throws Exception { ResourceScheduler scheduler = resourceManager.getResourceScheduler(); // Register node1 String host_0 = "host_0"; NodeManager nm_0 = registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(5 * GB, 1)); // Register node2 String host_1 = "host_1"; NodeManager nm_1 = registerNode(host_1, 1234, 2345, NetworkTopology.DEFAULT_RACK, Resources.createResource(5 * GB, 1)); // ResourceRequest priorities Priority priority_0 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(0); Priority priority_1 = org.apache.hadoop.yarn.server.resourcemanager.resource.Priority .create(1); // Submit application_0 Application application_0 = new Application("user_0", "a1", resourceManager); application_0.submit(); // app + app attempt event sent to scheduler application_0.addNodeManager(host_0, 1234, nm_0); application_0.addNodeManager(host_1, 1234, nm_1); Resource capability_0_0 = Resources.createResource(3 * GB, 1); application_0.addResourceRequestSpec(priority_1, capability_0_0); Resource capability_0_1 = Resources.createResource(2 * GB, 1); application_0.addResourceRequestSpec(priority_0, capability_0_1); Task task_0_0 = new Task(application_0, priority_1, new String[] { host_0, host_1 }); application_0.addTask(task_0_0); // Submit application_1 Application application_1 = new Application("user_1", "b2", resourceManager); application_1.submit(); // app + app attempt event sent to scheduler application_1.addNodeManager(host_0, 1234, nm_0); application_1.addNodeManager(host_1, 1234, nm_1); Resource capability_1_0 = Resources.createResource(1 * GB, 1); application_1.addResourceRequestSpec(priority_1, capability_1_0); Resource capability_1_1 = Resources.createResource(2 * GB, 1); application_1.addResourceRequestSpec(priority_0, capability_1_1); Task task_1_0 = new Task(application_1, priority_1, new String[] { host_0, host_1 }); application_1.addTask(task_1_0); // Send resource requests to the scheduler application_0.schedule(); // allocate application_1.schedule(); // allocate nodeUpdate(nm_0); nodeUpdate(nm_1); CapacityScheduler cs = (CapacityScheduler) resourceManager.getResourceScheduler(); CSQueue origRootQ = cs.getRootQueue(); CapacitySchedulerInfo oldInfo = new CapacitySchedulerInfo(origRootQ, cs, new RMNodeLabel( RMNodeLabelsManager.NO_LABEL)); int origNumAppsA = getNumAppsInQueue("a", origRootQ.getChildQueues()); int origNumAppsRoot = origRootQ.getNumApplications(); scheduler.moveApplication(application_0.getApplicationId(), "a2"); CSQueue newRootQ = cs.getRootQueue(); int newNumAppsA = getNumAppsInQueue("a", newRootQ.getChildQueues()); int newNumAppsRoot = newRootQ.getNumApplications(); CapacitySchedulerInfo newInfo = new CapacitySchedulerInfo(newRootQ, cs, new RMNodeLabel( RMNodeLabelsManager.NO_LABEL)); CapacitySchedulerLeafQueueInfo origOldA1 = (CapacitySchedulerLeafQueueInfo) getQueueInfo("a1", oldInfo.getQueues()); CapacitySchedulerLeafQueueInfo origNewA1 = (CapacitySchedulerLeafQueueInfo) getQueueInfo("a1", newInfo.getQueues()); CapacitySchedulerLeafQueueInfo targetOldA2 = (CapacitySchedulerLeafQueueInfo) getQueueInfo("a2", oldInfo.getQueues()); CapacitySchedulerLeafQueueInfo targetNewA2 = (CapacitySchedulerLeafQueueInfo) getQueueInfo("a2", newInfo.getQueues()); // originally submitted here assertEquals(1, origOldA1.getNumApplications()); assertEquals(1, origNumAppsA); assertEquals(2, origNumAppsRoot); // after the move assertEquals(0, origNewA1.getNumApplications()); assertEquals(1, newNumAppsA); assertEquals(2, newNumAppsRoot); // original consumption on a1 assertEquals(3 * GB, origOldA1.getResourcesUsed().getMemory()); assertEquals(1, origOldA1.getResourcesUsed().getvCores()); assertEquals(0, origNewA1.getResourcesUsed().getMemory()); // after the move assertEquals(0, origNewA1.getResourcesUsed().getvCores()); // after the move // app moved here with live containers assertEquals(3 * GB, targetNewA2.getResourcesUsed().getMemory()); assertEquals(1, targetNewA2.getResourcesUsed().getvCores()); // it was empty before the move assertEquals(0, targetOldA2.getNumApplications()); assertEquals(0, targetOldA2.getResourcesUsed().getMemory()); assertEquals(0, targetOldA2.getResourcesUsed().getvCores()); // after the app moved here assertEquals(1, targetNewA2.getNumApplications()); // 1 container on original queue before move assertEquals(1, origOldA1.getNumContainers()); // after the move the resource released assertEquals(0, origNewA1.getNumContainers()); // and moved to the new queue assertEquals(1, targetNewA2.getNumContainers()); // which originally didn't have any assertEquals(0, targetOldA2.getNumContainers()); // 1 user with 3GB assertEquals(3 * GB, origOldA1.getUsers().getUsersList().get(0) .getResourcesUsed().getMemory()); // 1 user with 1 core assertEquals(1, origOldA1.getUsers().getUsersList().get(0) .getResourcesUsed().getvCores()); // user ha no more running app in the orig queue assertEquals(0, origNewA1.getUsers().getUsersList().size()); // 1 user with 3GB assertEquals(3 * GB, targetNewA2.getUsers().getUsersList().get(0) .getResourcesUsed().getMemory()); // 1 user with 1 core assertEquals(1, targetNewA2.getUsers().getUsersList().get(0) .getResourcesUsed().getvCores()); // Get allocations from the scheduler application_0.schedule(); // task_0_0 checkApplicationResourceUsage(3 * GB, application_0); application_1.schedule(); // task_1_0 checkApplicationResourceUsage(1 * GB, application_1); // task_1_0 (1G) application_0 moved to b2 with max running app 1 so it is // not scheduled checkNodeResourceUsage(4 * GB, nm_0); checkNodeResourceUsage(0 * GB, nm_1); } private int getNumAppsInQueue(String name, List<CSQueue> queues) { for (CSQueue queue : queues) { if (queue.getQueueName().equals(name)) { return queue.getNumApplications(); } } return -1; } private CapacitySchedulerQueueInfo getQueueInfo(String name, CapacitySchedulerQueueInfoList info) { if (info != null) { for (CapacitySchedulerQueueInfo queueInfo : info.getQueueInfoList()) { if (queueInfo.getQueueName().equals(name)) { return queueInfo; } else { CapacitySchedulerQueueInfo result = getQueueInfo(name, queueInfo.getQueues()); if (result == null) { continue; } return result; } } } return null; } @Test public void testMoveAllApps() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); String queue = scheduler.getApplicationAttempt(appsInA1.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("a1")); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); List<ApplicationAttemptId> appsInB1 = scheduler.getAppsInQueue("b1"); assertTrue(appsInB1.isEmpty()); List<ApplicationAttemptId> appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.isEmpty()); // now move the app scheduler.moveAllApps("a1", "b1"); // check postconditions Thread.sleep(1000); appsInB1 = scheduler.getAppsInQueue("b1"); assertEquals(1, appsInB1.size()); queue = scheduler.getApplicationAttempt(appsInB1.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("b1")); appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.contains(appAttemptId)); assertEquals(1, appsInB.size()); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); appsInA1 = scheduler.getAppsInQueue("a1"); assertTrue(appsInA1.isEmpty()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.isEmpty()); rm.stop(); } @Test public void testMoveAllAppsInvalidDestination() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); List<ApplicationAttemptId> appsInB1 = scheduler.getAppsInQueue("b1"); assertTrue(appsInB1.isEmpty()); List<ApplicationAttemptId> appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.isEmpty()); // now move the app try { scheduler.moveAllApps("a1", "DOES_NOT_EXIST"); Assert.fail(); } catch (YarnException e) { // expected } // check postconditions, app should still be in a1 appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); appsInB1 = scheduler.getAppsInQueue("b1"); assertTrue(appsInB1.isEmpty()); appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.isEmpty()); rm.stop(); } @Test public void testMoveAllAppsInvalidSource() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); List<ApplicationAttemptId> appsInB1 = scheduler.getAppsInQueue("b1"); assertTrue(appsInB1.isEmpty()); List<ApplicationAttemptId> appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.isEmpty()); // now move the app try { scheduler.moveAllApps("DOES_NOT_EXIST", "b1"); Assert.fail(); } catch (YarnException e) { // expected } // check postconditions, app should still be in a1 appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); appsInB1 = scheduler.getAppsInQueue("b1"); assertTrue(appsInB1.isEmpty()); appsInB = scheduler.getAppsInQueue("b"); assertTrue(appsInB.isEmpty()); rm.stop(); } @Test public void testKillAllAppsInQueue() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); String queue = scheduler.getApplicationAttempt(appsInA1.get(0)).getQueue() .getQueueName(); Assert.assertTrue(queue.equals("a1")); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); // now kill the app scheduler.killAllAppsInQueue("a1"); // check postconditions rm.waitForState(app.getApplicationId(), RMAppState.KILLED); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.isEmpty()); appsInA1 = scheduler.getAppsInQueue("a1"); assertTrue(appsInA1.isEmpty()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.isEmpty()); rm.stop(); } @Test public void testKillAllAppsInvalidSource() throws Exception { MockRM rm = setUpMove(); AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); // submit an app RMApp app = rm.submitApp(GB, "test-move-1", "user_0", null, "a1"); ApplicationAttemptId appAttemptId = rm.getApplicationReport(app.getApplicationId()) .getCurrentApplicationAttemptId(); // check preconditions List<ApplicationAttemptId> appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); List<ApplicationAttemptId> appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); List<ApplicationAttemptId> appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); // now kill the app try { scheduler.killAllAppsInQueue("DOES_NOT_EXIST"); Assert.fail(); } catch (YarnException e) { // expected } // check postconditions, app should still be in a1 appsInA1 = scheduler.getAppsInQueue("a1"); assertEquals(1, appsInA1.size()); appsInA = scheduler.getAppsInQueue("a"); assertTrue(appsInA.contains(appAttemptId)); assertEquals(1, appsInA.size()); appsInRoot = scheduler.getAppsInQueue("root"); assertTrue(appsInRoot.contains(appAttemptId)); assertEquals(1, appsInRoot.size()); rm.stop(); } // Test to ensure that we don't carry out reservation on nodes // that have no CPU available when using the DominantResourceCalculator @Test(timeout = 30000) public void testAppReservationWithDominantResourceCalculator() throws Exception { CapacitySchedulerConfiguration csconf = new CapacitySchedulerConfiguration(); csconf.setResourceComparator(DominantResourceCalculator.class); YarnConfiguration conf = new YarnConfiguration(csconf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 10 * GB, 1); // register extra nodes to bump up cluster resource MockNM nm2 = rm.registerNode("127.0.0.1:1235", 10 * GB, 4); rm.registerNode("127.0.0.1:1236", 10 * GB, 4); RMApp app1 = rm.submitApp(1024); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); SchedulerNodeReport report_nm1 = rm.getResourceScheduler().getNodeReport(nm1.getNodeId()); // check node report Assert.assertEquals(1 * GB, report_nm1.getUsedResource().getMemory()); Assert.assertEquals(9 * GB, report_nm1.getAvailableResource().getMemory()); // add request for containers am1.addRequests(new String[] { "127.0.0.1", "127.0.0.2" }, 1 * GB, 1, 1); am1.schedule(); // send the request // kick the scheduler, container reservation should not happen nm1.nodeHeartbeat(true); Thread.sleep(1000); AllocateResponse allocResponse = am1.schedule(); ApplicationResourceUsageReport report = rm.getResourceScheduler().getAppResourceUsageReport( attempt1.getAppAttemptId()); Assert.assertEquals(0, allocResponse.getAllocatedContainers().size()); Assert.assertEquals(0, report.getNumReservedContainers()); // container should get allocated on this node nm2.nodeHeartbeat(true); while (allocResponse.getAllocatedContainers().size() == 0) { Thread.sleep(100); allocResponse = am1.schedule(); } report = rm.getResourceScheduler().getAppResourceUsageReport( attempt1.getAppAttemptId()); Assert.assertEquals(1, allocResponse.getAllocatedContainers().size()); Assert.assertEquals(0, report.getNumReservedContainers()); rm.stop(); } @Test public void testPreemptionDisabled() throws Exception { CapacityScheduler cs = new CapacityScheduler(); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); conf.setBoolean(YarnConfiguration.RM_SCHEDULER_ENABLE_MONITORS, true); RMContextImpl rmContext = new RMContextImpl(null, null, null, null, null, null, new RMContainerTokenSecretManager(conf), new NMTokenSecretManagerInRM(conf), new ClientToAMTokenSecretManagerInRM(), null); setupQueueConfiguration(conf); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); cs.init(conf); cs.start(); cs.reinitialize(conf, rmContext); CSQueue rootQueue = cs.getRootQueue(); CSQueue queueB = findQueue(rootQueue, B); CSQueue queueB2 = findQueue(queueB, B2); // When preemption turned on for the whole system // (yarn.resourcemanager.scheduler.monitor.enable=true), and with no other // preemption properties set, queue root.b.b2 should be preemptable. assertFalse("queue " + B2 + " should default to preemptable", queueB2.getPreemptionDisabled()); // Disable preemption at the root queue level. // The preemption property should be inherited from root all the // way down so that root.b.b2 should NOT be preemptable. conf.setPreemptionDisabled(rootQueue.getQueuePath(), true); cs.reinitialize(conf, rmContext); assertTrue( "queue " + B2 + " should have inherited non-preemptability from root", queueB2.getPreemptionDisabled()); // Enable preemption for root (grandparent) but disable for root.b (parent). // root.b.b2 should inherit property from parent and NOT be preemptable conf.setPreemptionDisabled(rootQueue.getQueuePath(), false); conf.setPreemptionDisabled(queueB.getQueuePath(), true); cs.reinitialize(conf, rmContext); assertTrue( "queue " + B2 + " should have inherited non-preemptability from parent", queueB2.getPreemptionDisabled()); // When preemption is turned on for root.b.b2, it should be preemptable // even though preemption is disabled on root.b (parent). conf.setPreemptionDisabled(queueB2.getQueuePath(), false); cs.reinitialize(conf, rmContext); assertFalse("queue " + B2 + " should have been preemptable", queueB2.getPreemptionDisabled()); } @Test public void testRefreshQueuesMaxAllocationRefresh() throws Exception { // queue refresh should not allow changing the maximum allocation setting // per queue to be smaller than previous setting CapacityScheduler cs = new CapacityScheduler(); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); cs.init(conf); cs.start(); cs.reinitialize(conf, mockContext); checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY); assertEquals("max allocation in CS", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, cs.getMaximumResourceCapability().getMemory()); assertEquals("max allocation for A1", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, conf.getMaximumAllocationPerQueue(A1).getMemory()); assertEquals("max allocation", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, conf.getMaximumAllocation().getMemory()); CSQueue rootQueue = cs.getRootQueue(); CSQueue queueA = findQueue(rootQueue, A); CSQueue queueA1 = findQueue(queueA, A1); assertEquals("queue max allocation", ((LeafQueue) queueA1) .getMaximumAllocation().getMemory(), 8192); setMaxAllocMb(conf, A1, 4096); try { cs.reinitialize(conf, mockContext); fail("should have thrown exception"); } catch (IOException e) { assertTrue("max allocation exception", e.getCause().toString().contains("not be decreased")); } setMaxAllocMb(conf, A1, 8192); cs.reinitialize(conf, mockContext); setMaxAllocVcores(conf, A1, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES - 1); try { cs.reinitialize(conf, mockContext); fail("should have thrown exception"); } catch (IOException e) { assertTrue("max allocation exception", e.getCause().toString().contains("not be decreased")); } } @Test public void testRefreshQueuesMaxAllocationPerQueueLarge() throws Exception { // verify we can't set the allocation per queue larger then cluster setting CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); cs.init(conf); cs.start(); // change max allocation for B3 queue to be larger then cluster max setMaxAllocMb(conf, B3, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB + 2048); try { cs.reinitialize(conf, mockContext); fail("should have thrown exception"); } catch (IOException e) { assertTrue("maximum allocation exception", e.getCause().getMessage().contains("maximum allocation")); } setMaxAllocMb(conf, B3, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB); cs.reinitialize(conf, mockContext); setMaxAllocVcores(conf, B3, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES + 1); try { cs.reinitialize(conf, mockContext); fail("should have thrown exception"); } catch (IOException e) { assertTrue("maximum allocation exception", e.getCause().getMessage().contains("maximum allocation")); } } @Test public void testRefreshQueuesMaxAllocationRefreshLarger() throws Exception { // queue refresh should allow max allocation per queue to go larger CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); setMaxAllocMb(conf, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB); setMaxAllocVcores(conf, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); setMaxAllocMb(conf, A1, 4096); setMaxAllocVcores(conf, A1, 2); cs.init(conf); cs.start(); cs.reinitialize(conf, mockContext); checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY); assertEquals("max capability MB in CS", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, cs.getMaximumResourceCapability().getMemory()); assertEquals("max capability vcores in CS", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, cs.getMaximumResourceCapability().getVirtualCores()); assertEquals("max allocation MB A1", 4096, conf.getMaximumAllocationPerQueue(A1).getMemory()); assertEquals("max allocation vcores A1", 2, conf.getMaximumAllocationPerQueue(A1).getVirtualCores()); assertEquals("cluster max allocation MB", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, conf.getMaximumAllocation().getMemory()); assertEquals("cluster max allocation vcores", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, conf.getMaximumAllocation().getVirtualCores()); CSQueue rootQueue = cs.getRootQueue(); CSQueue queueA = findQueue(rootQueue, A); CSQueue queueA1 = findQueue(queueA, A1); assertEquals("queue max allocation", ((LeafQueue) queueA1) .getMaximumAllocation().getMemory(), 4096); setMaxAllocMb(conf, A1, 6144); setMaxAllocVcores(conf, A1, 3); cs.reinitialize(conf, null); // conf will have changed but we shouldn't be able to change max allocation // for the actual queue assertEquals("max allocation MB A1", 6144, conf.getMaximumAllocationPerQueue(A1).getMemory()); assertEquals("max allocation vcores A1", 3, conf.getMaximumAllocationPerQueue(A1).getVirtualCores()); assertEquals("max allocation MB cluster", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, conf.getMaximumAllocation().getMemory()); assertEquals("max allocation vcores cluster", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, conf.getMaximumAllocation().getVirtualCores()); assertEquals("queue max allocation MB", 6144, ((LeafQueue) queueA1).getMaximumAllocation().getMemory()); assertEquals("queue max allocation vcores", 3, ((LeafQueue) queueA1).getMaximumAllocation().getVirtualCores()); assertEquals("max capability MB cluster", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, cs.getMaximumResourceCapability().getMemory()); assertEquals("cluster max capability vcores", YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, cs.getMaximumResourceCapability().getVirtualCores()); } @Test public void testRefreshQueuesMaxAllocationCSError() throws Exception { // Try to refresh the cluster level max allocation size to be smaller // and it should error out CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); setMaxAllocMb(conf, 10240); setMaxAllocVcores(conf, 10); setMaxAllocMb(conf, A1, 4096); setMaxAllocVcores(conf, A1, 4); cs.init(conf); cs.start(); cs.reinitialize(conf, mockContext); checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY); assertEquals("max allocation MB in CS", 10240, cs.getMaximumResourceCapability().getMemory()); assertEquals("max allocation vcores in CS", 10, cs.getMaximumResourceCapability().getVirtualCores()); setMaxAllocMb(conf, 6144); try { cs.reinitialize(conf, mockContext); fail("should have thrown exception"); } catch (IOException e) { assertTrue("max allocation exception", e.getCause().toString().contains("not be decreased")); } setMaxAllocMb(conf, 10240); cs.reinitialize(conf, mockContext); setMaxAllocVcores(conf, 8); try { cs.reinitialize(conf, mockContext); fail("should have thrown exception"); } catch (IOException e) { assertTrue("max allocation exception", e.getCause().toString().contains("not be decreased")); } } @Test public void testRefreshQueuesMaxAllocationCSLarger() throws Exception { // Try to refresh the cluster level max allocation size to be larger // and verify that if there is no setting per queue it uses the // cluster level setting. CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); setMaxAllocMb(conf, 10240); setMaxAllocVcores(conf, 10); setMaxAllocMb(conf, A1, 4096); setMaxAllocVcores(conf, A1, 4); cs.init(conf); cs.start(); cs.reinitialize(conf, mockContext); checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY); assertEquals("max allocation MB in CS", 10240, cs.getMaximumResourceCapability().getMemory()); assertEquals("max allocation vcores in CS", 10, cs.getMaximumResourceCapability().getVirtualCores()); CSQueue rootQueue = cs.getRootQueue(); CSQueue queueA = findQueue(rootQueue, A); CSQueue queueB = findQueue(rootQueue, B); CSQueue queueA1 = findQueue(queueA, A1); CSQueue queueA2 = findQueue(queueA, A2); CSQueue queueB2 = findQueue(queueB, B2); assertEquals("queue A1 max allocation MB", 4096, ((LeafQueue) queueA1).getMaximumAllocation().getMemory()); assertEquals("queue A1 max allocation vcores", 4, ((LeafQueue) queueA1).getMaximumAllocation().getVirtualCores()); assertEquals("queue A2 max allocation MB", 10240, ((LeafQueue) queueA2).getMaximumAllocation().getMemory()); assertEquals("queue A2 max allocation vcores", 10, ((LeafQueue) queueA2).getMaximumAllocation().getVirtualCores()); assertEquals("queue B2 max allocation MB", 10240, ((LeafQueue) queueB2).getMaximumAllocation().getMemory()); assertEquals("queue B2 max allocation vcores", 10, ((LeafQueue) queueB2).getMaximumAllocation().getVirtualCores()); setMaxAllocMb(conf, 12288); setMaxAllocVcores(conf, 12); cs.reinitialize(conf, null); // cluster level setting should change and any queues without // per queue setting assertEquals("max allocation MB in CS", 12288, cs.getMaximumResourceCapability().getMemory()); assertEquals("max allocation vcores in CS", 12, cs.getMaximumResourceCapability().getVirtualCores()); assertEquals("queue A1 max MB allocation", 4096, ((LeafQueue) queueA1).getMaximumAllocation().getMemory()); assertEquals("queue A1 max vcores allocation", 4, ((LeafQueue) queueA1).getMaximumAllocation().getVirtualCores()); assertEquals("queue A2 max MB allocation", 12288, ((LeafQueue) queueA2).getMaximumAllocation().getMemory()); assertEquals("queue A2 max vcores allocation", 12, ((LeafQueue) queueA2).getMaximumAllocation().getVirtualCores()); assertEquals("queue B2 max MB allocation", 12288, ((LeafQueue) queueB2).getMaximumAllocation().getMemory()); assertEquals("queue B2 max vcores allocation", 12, ((LeafQueue) queueB2).getMaximumAllocation().getVirtualCores()); } private void waitContainerAllocated(MockAM am, int mem, int nContainer, int startContainerId, MockRM rm, MockNM nm) throws Exception { for (int cId = startContainerId; cId < startContainerId + nContainer; cId++) { am.allocate("*", mem, 1, new ArrayList<ContainerId>()); ContainerId containerId = ContainerId.newContainerId(am.getApplicationAttemptId(), cId); Assert.assertTrue(rm.waitForState(nm, containerId, RMContainerState.ALLOCATED, 10 * 1000)); } } @Test public void testHierarchyQueuesCurrentLimits() throws Exception { /* * Queue tree: * Root * / \ * A B * / \ / | \ * A1 A2 B1 B2 B3 */ YarnConfiguration conf = new YarnConfiguration( setupQueueConfiguration(new CapacitySchedulerConfiguration())); conf.setBoolean(CapacitySchedulerConfiguration.ENABLE_USER_METRICS, true); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 100 * GB, rm1.getResourceTrackerService()); nm1.registerNode(); RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "b1"); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); waitContainerAllocated(am1, 1 * GB, 1, 2, rm1, nm1); // Maximum resoure of b1 is 100 * 0.895 * 0.792 = 71 GB // 2 GBs used by am, so it's 71 - 2 = 69G. Assert.assertEquals(69 * GB, am1.doHeartbeat().getAvailableResources().getMemory()); RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "b2"); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1); // Allocate 5 containers, each one is 8 GB in am2 (40 GB in total) waitContainerAllocated(am2, 8 * GB, 5, 2, rm1, nm1); // Allocated one more container with 1 GB resource in b1 waitContainerAllocated(am1, 1 * GB, 1, 3, rm1, nm1); // Total is 100 GB, // B2 uses 41 GB (5 * 8GB containers and 1 AM container) // B1 uses 3 GB (2 * 1GB containers and 1 AM container) // Available is 100 - 41 - 3 = 56 GB Assert.assertEquals(56 * GB, am1.doHeartbeat().getAvailableResources().getMemory()); // Now we submit app3 to a1 (in higher level hierarchy), to see if headroom // of app1 (in queue b1) updated correctly RMApp app3 = rm1.submitApp(1 * GB, "app", "user", null, "a1"); MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm1); // Allocate 3 containers, each one is 8 GB in am3 (24 GB in total) waitContainerAllocated(am3, 8 * GB, 3, 2, rm1, nm1); // Allocated one more container with 4 GB resource in b1 waitContainerAllocated(am1, 1 * GB, 1, 4, rm1, nm1); // Total is 100 GB, // B2 uses 41 GB (5 * 8GB containers and 1 AM container) // B1 uses 4 GB (3 * 1GB containers and 1 AM container) // A1 uses 25 GB (3 * 8GB containers and 1 AM container) // Available is 100 - 41 - 4 - 25 = 30 GB Assert.assertEquals(30 * GB, am1.doHeartbeat().getAvailableResources().getMemory()); } @Test public void testParentQueueMaxCapsAreRespected() throws Exception { /* * Queue tree: * Root * / \ * A B * / \ * A1 A2 */ CapacitySchedulerConfiguration csConf = new CapacitySchedulerConfiguration(); csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {"a", "b"}); csConf.setCapacity(A, 50); csConf.setMaximumCapacity(A, 50); csConf.setCapacity(B, 50); // Define 2nd-level queues csConf.setQueues(A, new String[] {"a1", "a2"}); csConf.setCapacity(A1, 50); csConf.setUserLimitFactor(A1, 100.0f); csConf.setCapacity(A2, 50); csConf.setUserLimitFactor(A2, 100.0f); csConf.setCapacity(B1, B1_CAPACITY); csConf.setUserLimitFactor(B1, 100.0f); YarnConfiguration conf = new YarnConfiguration(csConf); conf.setBoolean(CapacitySchedulerConfiguration.ENABLE_USER_METRICS, true); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM("127.0.0.1:1234", 24 * GB, rm1.getResourceTrackerService()); nm1.registerNode(); // Launch app1 in a1, resource usage is 1GB (am) + 4GB * 2 = 9GB RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "a1"); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); waitContainerAllocated(am1, 4 * GB, 2, 2, rm1, nm1); // Try to launch app2 in a2, asked 2GB, should success RMApp app2 = rm1.submitApp(2 * GB, "app", "user", null, "a2"); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1); try { // Try to allocate a container, a's usage=11G/max=12 // a1's usage=9G/max=12 // a2's usage=2G/max=12 // In this case, if a2 asked 2G, should fail. waitContainerAllocated(am2, 2 * GB, 1, 2, rm1, nm1); } catch (AssertionError failure) { // Expected, return; return; } Assert.fail("Shouldn't successfully allocate containers for am2, " + "queue-a's max capacity will be violated if container allocated"); } @SuppressWarnings("unchecked") private <E> Set<E> toSet(E... elements) { Set<E> set = Sets.newHashSet(elements); return set; } @Test public void testQueueHierarchyPendingResourceUpdate() throws Exception { Configuration conf = TestUtils.getConfigurationWithQueueLabels(new Configuration(false)); conf.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true); final RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); mgr.init(conf); mgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("h1", 0), toSet("x"))); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); MockRM rm = new MockRM(conf, memStore) { protected RMNodeLabelsManager createNodeLabelManager() { return mgr; } }; rm.start(); MockNM nm1 = // label = x new MockNM("h1:1234", 200 * GB, rm.getResourceTrackerService()); nm1.registerNode(); MockNM nm2 = // label = "" new MockNM("h2:1234", 200 * GB, rm.getResourceTrackerService()); nm2.registerNode(); // Launch app1 in queue=a1 RMApp app1 = rm.submitApp(1 * GB, "app", "user", null, "a1"); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm, nm2); // Launch app2 in queue=b1 RMApp app2 = rm.submitApp(8 * GB, "app", "user", null, "b1"); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm, nm2); // am1 asks for 8 * 1GB container for no label am1.allocate(Arrays.asList(ResourceRequest.newInstance( Priority.newInstance(1), "*", Resources.createResource(1 * GB), 8)), null); checkPendingResource(rm, "a1", 8 * GB, null); checkPendingResource(rm, "a", 8 * GB, null); checkPendingResource(rm, "root", 8 * GB, null); // am2 asks for 8 * 1GB container for no label am2.allocate(Arrays.asList(ResourceRequest.newInstance( Priority.newInstance(1), "*", Resources.createResource(1 * GB), 8)), null); checkPendingResource(rm, "a1", 8 * GB, null); checkPendingResource(rm, "a", 8 * GB, null); checkPendingResource(rm, "b1", 8 * GB, null); checkPendingResource(rm, "b", 8 * GB, null); // root = a + b checkPendingResource(rm, "root", 16 * GB, null); // am2 asks for 8 * 1GB container in another priority for no label am2.allocate(Arrays.asList(ResourceRequest.newInstance( Priority.newInstance(2), "*", Resources.createResource(1 * GB), 8)), null); checkPendingResource(rm, "a1", 8 * GB, null); checkPendingResource(rm, "a", 8 * GB, null); checkPendingResource(rm, "b1", 16 * GB, null); checkPendingResource(rm, "b", 16 * GB, null); // root = a + b checkPendingResource(rm, "root", 24 * GB, null); // am1 asks 4 GB resource instead of 8 * GB for priority=1 am1.allocate(Arrays.asList(ResourceRequest.newInstance( Priority.newInstance(1), "*", Resources.createResource(4 * GB), 1)), null); checkPendingResource(rm, "a1", 4 * GB, null); checkPendingResource(rm, "a", 4 * GB, null); checkPendingResource(rm, "b1", 16 * GB, null); checkPendingResource(rm, "b", 16 * GB, null); // root = a + b checkPendingResource(rm, "root", 20 * GB, null); // am1 asks 8 * GB resource which label=x am1.allocate(Arrays.asList(ResourceRequest.newInstance( Priority.newInstance(2), "*", Resources.createResource(8 * GB), 1, true, "x")), null); checkPendingResource(rm, "a1", 4 * GB, null); checkPendingResource(rm, "a", 4 * GB, null); checkPendingResource(rm, "a1", 8 * GB, "x"); checkPendingResource(rm, "a", 8 * GB, "x"); checkPendingResource(rm, "b1", 16 * GB, null); checkPendingResource(rm, "b", 16 * GB, null); // root = a + b checkPendingResource(rm, "root", 20 * GB, null); checkPendingResource(rm, "root", 8 * GB, "x"); // some containers allocated for am1, pending resource should decrease ContainerId containerId = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); Assert.assertTrue(rm.waitForState(nm1, containerId, RMContainerState.ALLOCATED, 10 * 1000)); containerId = ContainerId.newContainerId(am1.getApplicationAttemptId(), 3); Assert.assertTrue(rm.waitForState(nm2, containerId, RMContainerState.ALLOCATED, 10 * 1000)); checkPendingResource(rm, "a1", 0 * GB, null); checkPendingResource(rm, "a", 0 * GB, null); checkPendingResource(rm, "a1", 0 * GB, "x"); checkPendingResource(rm, "a", 0 * GB, "x"); // some containers could be allocated for am2 when we allocating containers // for am1, just check if pending resource of b1/b/root > 0 checkPendingResourceGreaterThanZero(rm, "b1", null); checkPendingResourceGreaterThanZero(rm, "b", null); // root = a + b checkPendingResourceGreaterThanZero(rm, "root", null); checkPendingResource(rm, "root", 0 * GB, "x"); // complete am2, pending resource should be 0 now AppAttemptRemovedSchedulerEvent appRemovedEvent = new AppAttemptRemovedSchedulerEvent( am2.getApplicationAttemptId(), RMAppAttemptState.FINISHED, false); rm.getResourceScheduler().handle(appRemovedEvent); checkPendingResource(rm, "a1", 0 * GB, null); checkPendingResource(rm, "a", 0 * GB, null); checkPendingResource(rm, "a1", 0 * GB, "x"); checkPendingResource(rm, "a", 0 * GB, "x"); checkPendingResource(rm, "b1", 0 * GB, null); checkPendingResource(rm, "b", 0 * GB, null); checkPendingResource(rm, "root", 0 * GB, null); checkPendingResource(rm, "root", 0 * GB, "x"); } private void checkPendingResource(MockRM rm, String queueName, int memory, String label) { CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); CSQueue queue = cs.getQueue(queueName); Assert.assertEquals( memory, queue.getQueueResourceUsage() .getPending(label == null ? RMNodeLabelsManager.NO_LABEL : label) .getMemory()); } private void checkPendingResourceGreaterThanZero(MockRM rm, String queueName, String label) { CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); CSQueue queue = cs.getQueue(queueName); Assert.assertTrue(queue.getQueueResourceUsage() .getPending(label == null ? RMNodeLabelsManager.NO_LABEL : label) .getMemory() > 0); } // Test verifies AM Used resource for LeafQueue when AM ResourceRequest is // lesser than minimumAllocation @Test(timeout = 30000) public void testAMUsedResource() throws Exception { MockRM rm = setUpMove(); Configuration conf = rm.getConfig(); int minAllocMb = conf.getInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); int amMemory = 50; assertTrue("AM memory is greater than or equql to minAllocation", amMemory < minAllocMb); Resource minAllocResource = Resource.newInstance(minAllocMb, 1); String queueName = "a1"; RMApp rmApp = rm.submitApp(amMemory, "app-1", "user_0", null, queueName); assertEquals("RMApp does not containes minimum allocation", minAllocResource, rmApp.getAMResourceRequest().getCapability()); ResourceScheduler scheduler = rm.getRMContext().getScheduler(); LeafQueue queueA = (LeafQueue) ((CapacityScheduler) scheduler).getQueue(queueName); assertEquals("Minimum Resource for AM is incorrect", minAllocResource, queueA.getUser("user_0").getResourceUsage().getAMUsed()); rm.stop(); } // Verifies headroom passed to ApplicationMaster has been updated in // RMAppAttemptMetrics @Test public void testApplicationHeadRoom() throws Exception { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); rm.start(); CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); ApplicationId appId = BuilderUtils.newApplicationId(100, 1); ApplicationAttemptId appAttemptId = BuilderUtils.newApplicationAttemptId(appId, 1); RMAppAttemptMetrics attemptMetric = new RMAppAttemptMetrics(appAttemptId, rm.getRMContext()); RMAppImpl app = mock(RMAppImpl.class); when(app.getApplicationId()).thenReturn(appId); RMAppAttemptImpl attempt = mock(RMAppAttemptImpl.class); when(attempt.getAppAttemptId()).thenReturn(appAttemptId); when(attempt.getRMAppAttemptMetrics()).thenReturn(attemptMetric); when(app.getCurrentAppAttempt()).thenReturn(attempt); rm.getRMContext().getRMApps().put(appId, app); SchedulerEvent addAppEvent = new AppAddedSchedulerEvent(appId, "default", "user"); cs.handle(addAppEvent); SchedulerEvent addAttemptEvent = new AppAttemptAddedSchedulerEvent(appAttemptId, false); cs.handle(addAttemptEvent); Allocation allocate = cs.allocate(appAttemptId, Collections.<ResourceRequest> emptyList(), Collections.<ContainerId> emptyList(), null, null); Assert.assertNotNull(attempt); Assert .assertEquals(Resource.newInstance(0, 0), allocate.getResourceLimit()); Assert.assertEquals(Resource.newInstance(0, 0), attemptMetric.getApplicationAttemptHeadroom()); // Add a node to cluster Resource newResource = Resource.newInstance(4 * GB, 1); RMNode node = MockNodes.newNodeInfo(0, newResource, 1, "127.0.0.1"); cs.handle(new NodeAddedSchedulerEvent(node)); allocate = cs.allocate(appAttemptId, Collections.<ResourceRequest> emptyList(), Collections.<ContainerId> emptyList(), null, null); // All resources should be sent as headroom Assert.assertEquals(newResource, allocate.getResourceLimit()); Assert.assertEquals(newResource, attemptMetric.getApplicationAttemptHeadroom()); rm.stop(); } @Test public void testDefaultNodeLabelExpressionQueueConfig() throws Exception { CapacityScheduler cs = new CapacityScheduler(); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); conf.setDefaultNodeLabelExpression("root.a", " x"); conf.setDefaultNodeLabelExpression("root.b", " y "); cs.setConf(new YarnConfiguration()); cs.setRMContext(resourceManager.getRMContext()); cs.init(conf); cs.start(); QueueInfo queueInfoA = cs.getQueueInfo("a", true, false); Assert.assertEquals(queueInfoA.getQueueName(), "a"); Assert.assertEquals(queueInfoA.getDefaultNodeLabelExpression(), "x"); QueueInfo queueInfoB = cs.getQueueInfo("b", true, false); Assert.assertEquals(queueInfoB.getQueueName(), "b"); Assert.assertEquals(queueInfoB.getDefaultNodeLabelExpression(), "y"); } @Test(timeout = 30000) public void testAMLimitUsage() throws Exception { CapacitySchedulerConfiguration config = new CapacitySchedulerConfiguration(); config.set(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, DefaultResourceCalculator.class.getName()); verifyAMLimitForLeafQueue(config); config.set(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, DominantResourceCalculator.class.getName()); verifyAMLimitForLeafQueue(config); } private void verifyAMLimitForLeafQueue(CapacitySchedulerConfiguration config) throws Exception { MockRM rm = setUpMove(config); String queueName = "a1"; String userName = "user_0"; ResourceScheduler scheduler = rm.getRMContext().getScheduler(); LeafQueue queueA = (LeafQueue) ((CapacityScheduler) scheduler).getQueue(queueName); Resource amResourceLimit = queueA.getAMResourceLimit(); Resource amResource1 = Resource.newInstance(amResourceLimit.getMemory() + 1024, amResourceLimit.getVirtualCores() + 1); Resource amResource2 = Resource.newInstance(amResourceLimit.getMemory() + 2048, amResourceLimit.getVirtualCores() + 1); rm.submitApp(amResource1, "app-1", userName, null, queueName); rm.submitApp(amResource2, "app-2", userName, null, queueName); // When AM limit is exceeded, 1 applications will be activated.Rest all // applications will be in pending Assert.assertEquals("PendingApplications should be 1", 1, queueA.getNumPendingApplications()); Assert.assertEquals("Active applications should be 1", 1, queueA.getNumActiveApplications()); Assert.assertEquals("User PendingApplications should be 1", 1, queueA .getUser(userName).getPendingApplications()); Assert.assertEquals("User Active applications should be 1", 1, queueA .getUser(userName).getActiveApplications()); rm.stop(); } private void setMaxAllocMb(Configuration conf, int maxAllocMb) { conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, maxAllocMb); } private void setMaxAllocMb(CapacitySchedulerConfiguration conf, String queueName, int maxAllocMb) { String propName = CapacitySchedulerConfiguration.getQueuePrefix(queueName) + CapacitySchedulerConfiguration.MAXIMUM_ALLOCATION_MB; conf.setInt(propName, maxAllocMb); } private void setMaxAllocVcores(Configuration conf, int maxAllocVcores) { conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, maxAllocVcores); } private void setMaxAllocVcores(CapacitySchedulerConfiguration conf, String queueName, int maxAllocVcores) { String propName = CapacitySchedulerConfiguration.getQueuePrefix(queueName) + CapacitySchedulerConfiguration.MAXIMUM_ALLOCATION_VCORES; conf.setInt(propName, maxAllocVcores); } }
119,607
38.318869
120
java
hadoop
hadoop-master/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestWorkPreservingRMRestartForNodeLabel.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.scheduler.capacity; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; import org.apache.hadoop.yarn.server.resourcemanager.TestRMRestart; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; public class TestWorkPreservingRMRestartForNodeLabel { private Configuration conf; private static final int GB = 1024; // 1024 MB RMNodeLabelsManager mgr; @Before public void setUp() throws Exception { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); conf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); conf.setBoolean(YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_ENABLED, true); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); mgr = new NullRMNodeLabelsManager(); mgr.init(conf); } @SuppressWarnings("unchecked") private <E> Set<E> toSet(E... elements) { Set<E> set = Sets.newHashSet(elements); return set; } private void checkRMContainerLabelExpression(ContainerId containerId, MockRM rm, String labelExpression) { RMContainer container = rm.getRMContext().getScheduler().getRMContainer(containerId); Assert.assertNotNull("Cannot find RMContainer=" + containerId, container); Assert.assertEquals(labelExpression, container.getNodeLabelExpression()); } @SuppressWarnings("rawtypes") public static void waitForNumContainersToRecover(int num, MockRM rm, ApplicationAttemptId attemptId) throws Exception { AbstractYarnScheduler scheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); SchedulerApplicationAttempt attempt = scheduler.getApplicationAttempt(attemptId); while (attempt == null) { System.out.println("Wait for scheduler attempt " + attemptId + " to be created"); Thread.sleep(200); attempt = scheduler.getApplicationAttempt(attemptId); } while (attempt.getLiveContainers().size() < num) { System.out.println("Wait for " + num + " containers to recover. currently: " + attempt.getLiveContainers().size()); Thread.sleep(200); } } private void checkAppResourceUsage(String partition, ApplicationId appId, MockRM rm, int expectedMemUsage) { CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); FiCaSchedulerApp app = cs.getSchedulerApplications().get(appId).getCurrentAppAttempt(); Assert.assertEquals(expectedMemUsage, app.getAppAttemptResourceUsage() .getUsed(partition).getMemory()); } private void checkQueueResourceUsage(String partition, String queueName, MockRM rm, int expectedMemUsage) { CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler(); CSQueue queue = cs.getQueue(queueName); Assert.assertEquals(expectedMemUsage, queue.getQueueResourceUsage() .getUsed(partition).getMemory()); } @Test public void testWorkPreservingRestartForNodeLabel() throws Exception { // This test is pretty much similar to testContainerAllocateWithLabel. // Difference is, this test doesn't specify label expression in ResourceRequest, // instead, it uses default queue label expression // set node -> label mgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("h1", 0), toSet("x"), NodeId.newInstance("h2", 0), toSet("y"))); MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); conf = TestUtils.getConfigurationWithDefaultQueueLabels(conf); // inject node label manager MockRM rm1 = new MockRM(conf, memStore) { @Override public RMNodeLabelsManager createNodeLabelManager() { return mgr; } }; rm1.getRMContext().setNodeLabelManager(mgr); rm1.start(); MockNM nm1 = rm1.registerNode("h1:1234", 8000); // label = x MockNM nm2 = rm1.registerNode("h2:1234", 8000); // label = y MockNM nm3 = rm1.registerNode("h3:1234", 8000); // label = <empty> ContainerId containerId; // launch an app to queue a1 (label = x), and check all container will // be allocated in h1 RMApp app1 = rm1.submitApp(200, "app", "user", null, "a1"); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); // request a container. am1.allocate("*", 1024, 1, new ArrayList<ContainerId>()); containerId = ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); Assert.assertTrue(rm1.waitForState(nm1, containerId, RMContainerState.ALLOCATED, 10 * 1000)); checkRMContainerLabelExpression(ContainerId.newContainerId( am1.getApplicationAttemptId(), 1), rm1, "x"); checkRMContainerLabelExpression(ContainerId.newContainerId( am1.getApplicationAttemptId(), 2), rm1, "x"); // launch an app to queue b1 (label = y), and check all container will // be allocated in h2 RMApp app2 = rm1.submitApp(200, "app", "user", null, "b1"); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); // request a container. am2.allocate("*", 1024, 1, new ArrayList<ContainerId>()); containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); Assert.assertTrue(rm1.waitForState(nm2, containerId, RMContainerState.ALLOCATED, 10 * 1000)); checkRMContainerLabelExpression(ContainerId.newContainerId( am2.getApplicationAttemptId(), 1), rm1, "y"); checkRMContainerLabelExpression(ContainerId.newContainerId( am2.getApplicationAttemptId(), 2), rm1, "y"); // launch an app to queue c1 (label = ""), and check all container will // be allocated in h3 RMApp app3 = rm1.submitApp(200, "app", "user", null, "c1"); MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm3); // request a container. am3.allocate("*", 1024, 1, new ArrayList<ContainerId>()); containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); Assert.assertTrue(rm1.waitForState(nm3, containerId, RMContainerState.ALLOCATED, 10 * 1000)); checkRMContainerLabelExpression(ContainerId.newContainerId( am3.getApplicationAttemptId(), 1), rm1, ""); checkRMContainerLabelExpression(ContainerId.newContainerId( am3.getApplicationAttemptId(), 2), rm1, ""); // Re-start RM mgr = new NullRMNodeLabelsManager(); mgr.init(conf); mgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("h1", 0), toSet("x"), NodeId.newInstance("h2", 0), toSet("y"))); MockRM rm2 = new MockRM(conf, memStore) { @Override public RMNodeLabelsManager createNodeLabelManager() { return mgr; } }; rm2.start(); nm1.setResourceTrackerService(rm2.getResourceTrackerService()); nm2.setResourceTrackerService(rm2.getResourceTrackerService()); nm3.setResourceTrackerService(rm2.getResourceTrackerService()); // recover app NMContainerStatus app1c1 = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 1, ContainerState.RUNNING, "x"); NMContainerStatus app1c2 = TestRMRestart.createNMContainerStatus(am1.getApplicationAttemptId(), 2, ContainerState.RUNNING, "x"); nm1.registerNode(Arrays.asList(app1c1, app1c2), null); waitForNumContainersToRecover(2, rm2, am1.getApplicationAttemptId()); checkRMContainerLabelExpression(ContainerId.newContainerId( am1.getApplicationAttemptId(), 1), rm1, "x"); checkRMContainerLabelExpression(ContainerId.newContainerId( am1.getApplicationAttemptId(), 2), rm1, "x"); NMContainerStatus app2c1 = TestRMRestart.createNMContainerStatus(am2.getApplicationAttemptId(), 1, ContainerState.RUNNING, "y"); NMContainerStatus app2c2 = TestRMRestart.createNMContainerStatus(am2.getApplicationAttemptId(), 2, ContainerState.RUNNING, "y"); nm2.registerNode(Arrays.asList(app2c1, app2c2), null); waitForNumContainersToRecover(2, rm2, am2.getApplicationAttemptId()); checkRMContainerLabelExpression(ContainerId.newContainerId( am2.getApplicationAttemptId(), 1), rm1, "y"); checkRMContainerLabelExpression(ContainerId.newContainerId( am2.getApplicationAttemptId(), 2), rm1, "y"); NMContainerStatus app3c1 = TestRMRestart.createNMContainerStatus(am3.getApplicationAttemptId(), 1, ContainerState.RUNNING, ""); NMContainerStatus app3c2 = TestRMRestart.createNMContainerStatus(am3.getApplicationAttemptId(), 2, ContainerState.RUNNING, ""); nm3.registerNode(Arrays.asList(app3c1, app3c2), null); waitForNumContainersToRecover(2, rm2, am3.getApplicationAttemptId()); checkRMContainerLabelExpression(ContainerId.newContainerId( am3.getApplicationAttemptId(), 1), rm1, ""); checkRMContainerLabelExpression(ContainerId.newContainerId( am3.getApplicationAttemptId(), 2), rm1, ""); // Check recovered resource usage checkAppResourceUsage("x", app1.getApplicationId(), rm1, 2 * GB); checkAppResourceUsage("y", app2.getApplicationId(), rm1, 2 * GB); checkAppResourceUsage("", app3.getApplicationId(), rm1, 2 * GB); checkQueueResourceUsage("x", "a1", rm1, 2 * GB); checkQueueResourceUsage("y", "b1", rm1, 2 * GB); checkQueueResourceUsage("", "c1", rm1, 2 * GB); checkQueueResourceUsage("x", "a", rm1, 2 * GB); checkQueueResourceUsage("y", "b", rm1, 2 * GB); checkQueueResourceUsage("", "c", rm1, 2 * GB); checkQueueResourceUsage("x", "root", rm1, 2 * GB); checkQueueResourceUsage("y", "root", rm1, 2 * GB); checkQueueResourceUsage("", "root", rm1, 2 * GB); rm1.close(); rm2.close(); } }
12,447
43.141844
109
java