-
Notifications
You must be signed in to change notification settings - Fork 13k
/
YarnResourceManagerTest.java
585 lines (490 loc) · 19.3 KB
/
YarnResourceManagerTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*
* 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.flink.yarn;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ResourceManagerOptions;
import org.apache.flink.runtime.clusterframework.ApplicationStatus;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.concurrent.ScheduledExecutor;
import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.entrypoint.ClusterInformation;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.heartbeat.TestingHeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.TestingHighAvailabilityServices;
import org.apache.flink.runtime.instance.HardwareDescription;
import org.apache.flink.runtime.leaderelection.TestingLeaderElectionService;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.metrics.NoOpMetricRegistry;
import org.apache.flink.runtime.registration.RegistrationResponse;
import org.apache.flink.runtime.resourcemanager.JobLeaderIdService;
import org.apache.flink.runtime.resourcemanager.ResourceManagerGateway;
import org.apache.flink.runtime.resourcemanager.SlotRequest;
import org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.TestingRpcService;
import org.apache.flink.runtime.taskexecutor.SlotReport;
import org.apache.flink.runtime.taskexecutor.SlotStatus;
import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway;
import org.apache.flink.runtime.taskexecutor.TaskExecutorRegistrationSuccess;
import org.apache.flink.runtime.testutils.DirectScheduledExecutorService;
import org.apache.flink.runtime.util.TestingFatalErrorHandler;
import org.apache.flink.util.TestLogger;
import org.apache.flink.shaded.guava18.com.google.common.collect.ImmutableList;
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.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.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.client.api.AMRMClient;
import org.apache.hadoop.yarn.client.api.NMClient;
import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static org.apache.flink.yarn.YarnConfigKeys.ENV_APP_ID;
import static org.apache.flink.yarn.YarnConfigKeys.ENV_CLIENT_HOME_DIR;
import static org.apache.flink.yarn.YarnConfigKeys.ENV_CLIENT_SHIP_FILES;
import static org.apache.flink.yarn.YarnConfigKeys.ENV_FLINK_CLASSPATH;
import static org.apache.flink.yarn.YarnConfigKeys.ENV_HADOOP_USER_NAME;
import static org.apache.flink.yarn.YarnConfigKeys.FLINK_JAR_PATH;
import static org.apache.flink.yarn.YarnConfigKeys.FLINK_YARN_FILES;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* General tests for the YARN resource manager component.
*/
public class YarnResourceManagerTest extends TestLogger {
private static final Time TIMEOUT = Time.seconds(10L);
private Configuration flinkConfig = new Configuration();
private Map<String, String> env = new HashMap<>();
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before
public void setup() {
flinkConfig.setInteger(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN, 100);
File root = folder.getRoot();
File home = new File(root, "home");
boolean created = home.mkdir();
assertTrue(created);
env.put(ENV_APP_ID, "foo");
env.put(ENV_CLIENT_HOME_DIR, home.getAbsolutePath());
env.put(ENV_CLIENT_SHIP_FILES, "");
env.put(ENV_FLINK_CLASSPATH, "");
env.put(ENV_HADOOP_USER_NAME, "foo");
env.put(FLINK_JAR_PATH, root.toURI().toString());
}
@After
public void teardown() {
env.clear();
}
static class TestingYarnResourceManager extends YarnResourceManager {
AMRMClientAsync<AMRMClient.ContainerRequest> mockResourceManagerClient;
NMClient mockNMClient;
TestingYarnResourceManager(
RpcService rpcService,
String resourceManagerEndpointId,
ResourceID resourceId,
Configuration flinkConfig,
Map<String, String> env,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
SlotManager slotManager,
MetricRegistry metricRegistry,
JobLeaderIdService jobLeaderIdService,
ClusterInformation clusterInformation,
FatalErrorHandler fatalErrorHandler,
@Nullable String webInterfaceUrl,
AMRMClientAsync<AMRMClient.ContainerRequest> mockResourceManagerClient,
NMClient mockNMClient) {
super(
rpcService,
resourceManagerEndpointId,
resourceId,
flinkConfig,
env,
highAvailabilityServices,
heartbeatServices,
slotManager,
metricRegistry,
jobLeaderIdService,
clusterInformation,
fatalErrorHandler,
webInterfaceUrl);
this.mockNMClient = mockNMClient;
this.mockResourceManagerClient = mockResourceManagerClient;
}
<T> CompletableFuture<T> runInMainThread(Callable<T> callable) {
return callAsync(callable, TIMEOUT);
}
MainThreadExecutor getMainThreadExecutorForTesting() {
return super.getMainThreadExecutor();
}
@Override
protected AMRMClientAsync<AMRMClient.ContainerRequest> createAndStartResourceManagerClient(
YarnConfiguration yarnConfiguration,
int yarnHeartbeatIntervalMillis,
@Nullable String webInteraceUrl) {
return mockResourceManagerClient;
}
@Override
protected NMClient createAndStartNodeManagerClient(YarnConfiguration yarnConfiguration) {
return mockNMClient;
}
@Override
protected void runAsync(final Runnable runnable) {
runnable.run();
}
}
class Context {
// services
final TestingRpcService rpcService;
final TestingFatalErrorHandler fatalErrorHandler;
final MockResourceManagerRuntimeServices rmServices;
// RM
final ResourceID rmResourceID;
static final String RM_ADDRESS = "resourceManager";
final TestingYarnResourceManager resourceManager;
final int dataPort = 1234;
final HardwareDescription hardwareDescription = new HardwareDescription(1, 2L, 3L, 4L);
// domain objects for test purposes
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 200);
public ContainerId task = ContainerId.newInstance(
ApplicationAttemptId.newInstance(ApplicationId.newInstance(1L, 0), 0), 1);
public String taskHost = "host1";
public NMClient mockNMClient = mock(NMClient.class);
public AMRMClientAsync<AMRMClient.ContainerRequest> mockResourceManagerClient =
mock(AMRMClientAsync.class);
/**
* Create mock RM dependencies.
*/
Context() throws Exception {
rpcService = new TestingRpcService();
fatalErrorHandler = new TestingFatalErrorHandler();
rmServices = new MockResourceManagerRuntimeServices();
// resource manager
rmResourceID = ResourceID.generate();
resourceManager =
new TestingYarnResourceManager(
rpcService,
RM_ADDRESS,
rmResourceID,
flinkConfig,
env,
rmServices.highAvailabilityServices,
rmServices.heartbeatServices,
rmServices.slotManager,
rmServices.metricRegistry,
rmServices.jobLeaderIdService,
new ClusterInformation("localhost", 1234),
fatalErrorHandler,
null,
mockResourceManagerClient,
mockNMClient);
}
/**
* Mock services needed by the resource manager.
*/
class MockResourceManagerRuntimeServices {
private final ScheduledExecutor scheduledExecutor;
private final TestingHighAvailabilityServices highAvailabilityServices;
private final HeartbeatServices heartbeatServices;
private final MetricRegistry metricRegistry;
private final TestingLeaderElectionService rmLeaderElectionService;
private final JobLeaderIdService jobLeaderIdService;
private final SlotManager slotManager;
private UUID rmLeaderSessionId;
MockResourceManagerRuntimeServices() throws Exception {
scheduledExecutor = mock(ScheduledExecutor.class);
highAvailabilityServices = new TestingHighAvailabilityServices();
rmLeaderElectionService = new TestingLeaderElectionService();
highAvailabilityServices.setResourceManagerLeaderElectionService(rmLeaderElectionService);
heartbeatServices = new TestingHeartbeatServices(5L, 5L, scheduledExecutor);
metricRegistry = NoOpMetricRegistry.INSTANCE;
slotManager = new SlotManager(
new ScheduledExecutorServiceAdapter(new DirectScheduledExecutorService()),
Time.seconds(10), Time.seconds(10), Time.minutes(1));
jobLeaderIdService = new JobLeaderIdService(
highAvailabilityServices,
rpcService.getScheduledExecutor(),
Time.minutes(5L));
}
void grantLeadership() throws Exception {
rmLeaderSessionId = UUID.randomUUID();
rmLeaderElectionService.isLeader(rmLeaderSessionId).get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
}
}
/**
* Start the resource manager and grant leadership to it.
*/
void startResourceManager() throws Exception {
resourceManager.start();
rmServices.grantLeadership();
}
/**
* Stop the Akka actor system.
*/
void stopResourceManager() throws Exception {
rpcService.stopService().get();
}
}
static class TestingContainer extends Container {
private final NodeId nodeId;
private final ContainerId containerId;
private Resource resource;
private Priority priority;
TestingContainer(String host, int port, int containerId) {
this.nodeId = NodeId.newInstance(host, port);
this.containerId = ContainerId.newInstance(
ApplicationAttemptId.newInstance(
ApplicationId.newInstance(System.currentTimeMillis(), 1),
1
),
containerId
);
}
@Override
public ContainerId getId() {
return containerId;
}
@Override
public void setId(ContainerId containerId) {
}
@Override
public NodeId getNodeId() {
return nodeId;
}
@Override
public void setNodeId(NodeId nodeId) {
}
@Override
public Resource getResource() {
return resource;
}
@Override
public void setResource(Resource resource) {
this.resource = resource;
}
@Override
public Priority getPriority() {
return priority;
}
@Override
public void setPriority(Priority priority) {
this.priority = priority;
}
@Override
public Token getContainerToken() {
return null;
}
@Override
public void setContainerToken(Token token) {
}
@Override
public void setNodeHttpAddress(String s) {
}
@Override
public String getNodeHttpAddress() {
return null;
}
@Override public int compareTo(@Nonnull Container other) {
return 0;
}
}
static class TestingContainerStatus extends ContainerStatus {
private ContainerId containerId;
TestingContainerStatus() {
}
@Override
public ContainerId getContainerId() {
return containerId;
}
@Override
public void setContainerId(ContainerId containerId) {
this.containerId = containerId;
}
@Override
public ContainerState getState() {
return ContainerState.COMPLETE;
}
@Override
public void setState(ContainerState containerState) {
}
@Override
public int getExitStatus() {
return -1;
}
@Override
public void setExitStatus(int exitStatus) {
}
@Override
public String getDiagnostics() {
return "Test exit";
}
@Override
public void setDiagnostics(String diagnostics) {
}
}
@Test
public void testStopWorker() throws Exception {
new Context() {{
startResourceManager();
// Request slot from SlotManager.
CompletableFuture<?> registerSlotRequestFuture = resourceManager.runInMainThread(() -> {
rmServices.slotManager.registerSlotRequest(
new SlotRequest(new JobID(), new AllocationID(), resourceProfile1, taskHost));
return null;
});
// wait for the registerSlotRequest completion
registerSlotRequestFuture.get();
// Callback from YARN when container is allocated.
Container testingContainer = new TestingContainer("container", 1234, 1);
testingContainer.setResource(Resource.newInstance(200, 1));
testingContainer.setPriority(Priority.UNDEFINED);
resourceManager.onContainersAllocated(ImmutableList.of(testingContainer));
verify(mockResourceManagerClient).addContainerRequest(any(AMRMClient.ContainerRequest.class));
verify(mockNMClient).startContainer(eq(testingContainer), any(ContainerLaunchContext.class));
// Remote task executor registers with YarnResourceManager.
TaskExecutorGateway mockTaskExecutorGateway = mock(TaskExecutorGateway.class);
rpcService.registerGateway(taskHost, mockTaskExecutorGateway);
final ResourceManagerGateway rmGateway = resourceManager.getSelfGateway(ResourceManagerGateway.class);
final ResourceID taskManagerResourceId = new ResourceID(testingContainer.getId().toString());
final SlotReport slotReport = new SlotReport(
new SlotStatus(
new SlotID(taskManagerResourceId, 1),
new ResourceProfile(10, 1, 1, 1, 0, Collections.emptyMap())));
CompletableFuture<Integer> numberRegisteredSlotsFuture = rmGateway
.registerTaskExecutor(
taskHost,
taskManagerResourceId,
dataPort,
hardwareDescription,
Time.seconds(10L))
.thenCompose(
(RegistrationResponse response) -> {
assertThat(response, instanceOf(TaskExecutorRegistrationSuccess.class));
final TaskExecutorRegistrationSuccess success = (TaskExecutorRegistrationSuccess) response;
return rmGateway.sendSlotReport(
taskManagerResourceId,
success.getRegistrationId(),
slotReport,
Time.seconds(10L));
})
.handleAsync(
(Acknowledge ignored, Throwable throwable) -> rmServices.slotManager.getNumberRegisteredSlots(),
resourceManager.getMainThreadExecutorForTesting());
final int numberRegisteredSlots = numberRegisteredSlotsFuture.get();
assertEquals(1, numberRegisteredSlots);
// Unregister all task executors and release all containers.
CompletableFuture<?> unregisterAndReleaseFuture = resourceManager.runInMainThread(() -> {
rmServices.slotManager.unregisterTaskManagersAndReleaseResources();
return null;
});
unregisterAndReleaseFuture.get();
verify(mockNMClient).stopContainer(any(ContainerId.class), any(NodeId.class));
verify(mockResourceManagerClient).releaseAssignedContainer(any(ContainerId.class));
stopResourceManager();
// It's now safe to access the SlotManager state since the ResourceManager has been stopped.
assertThat(rmServices.slotManager.getNumberRegisteredSlots(), Matchers.equalTo(0));
assertThat(resourceManager.getNumberOfRegisteredTaskManagers().get(), Matchers.equalTo(0));
}};
}
/**
* Tests that application files are deleted when the YARN application master is de-registered.
*/
@Test
public void testDeleteApplicationFiles() throws Exception {
new Context() {{
final File applicationDir = folder.newFolder(".flink");
env.put(FLINK_YARN_FILES, applicationDir.getCanonicalPath());
startResourceManager();
resourceManager.deregisterApplication(ApplicationStatus.SUCCEEDED, null);
assertFalse("YARN application directory was not removed", Files.exists(applicationDir.toPath()));
}};
}
/**
* Tests that YarnResourceManager will not request more containers than needs during
* callback from Yarn when container is Completed.
*/
@Test
public void testOnContainerCompleted() throws Exception {
new Context() {{
startResourceManager();
CompletableFuture<?> registerSlotRequestFuture = resourceManager.runInMainThread(() -> {
rmServices.slotManager.registerSlotRequest(
new SlotRequest(new JobID(), new AllocationID(), resourceProfile1, taskHost));
return null;
});
// wait for the registerSlotRequest completion
registerSlotRequestFuture.get();
// Callback from YARN when container is allocated.
Container testingContainer = new TestingContainer("container", 1234, 1);
testingContainer.setResource(Resource.newInstance(200, 1));
testingContainer.setPriority(Priority.UNDEFINED);
resourceManager.onContainersAllocated(ImmutableList.of(testingContainer));
verify(mockResourceManagerClient).addContainerRequest(any(AMRMClient.ContainerRequest.class));
verify(mockNMClient).startContainer(eq(testingContainer), any(ContainerLaunchContext.class));
// Callback from YARN when container is Completed, pending request can not be fulfilled by pending
// containers, need to request new container.
ContainerStatus testingContainerStatus = new TestingContainerStatus();
testingContainerStatus.setContainerId(testingContainer.getId());
resourceManager.onContainersCompleted(ImmutableList.of(testingContainerStatus));
verify(mockResourceManagerClient, times(2)).addContainerRequest(any(AMRMClient.ContainerRequest.class));
// Callback from YARN when container is Completed happened before global fail, pending request
// slot is already fulfilled by pending containers, no need to request new container.
resourceManager.onContainersCompleted(ImmutableList.of(testingContainerStatus));
verify(mockResourceManagerClient, times(2)).addContainerRequest(any(AMRMClient.ContainerRequest.class));
}};
}
}