Fabric8FlinkKubeClientTest.java 16.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * 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.kubernetes.kubeclient;

21 22 23 24
import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.configuration.BlobServerOptions;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.configuration.RestOptions;
25
import org.apache.flink.core.testutils.FlinkMatchers;
26
import org.apache.flink.kubernetes.KubernetesClientTestBase;
27 28 29 30
import org.apache.flink.kubernetes.KubernetesTestUtils;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptionsInternal;
import org.apache.flink.kubernetes.entrypoint.KubernetesSessionClusterEntrypoint;
31
import org.apache.flink.kubernetes.kubeclient.decorators.ExternalServiceDecorator;
32 33
import org.apache.flink.kubernetes.kubeclient.factory.KubernetesJobManagerFactory;
import org.apache.flink.kubernetes.kubeclient.parameters.KubernetesJobManagerParameters;
34
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
35
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesPod;
36

37
import io.fabric8.kubernetes.api.model.ConfigMap;
38
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
39 40 41 42 43 44
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.OwnerReference;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apps.Deployment;
45 46
import org.junit.Test;

47
import java.util.HashMap;
48
import java.util.List;
49
import java.util.Map;
50
import java.util.Optional;
51
import java.util.concurrent.CompletableFuture;
52
import java.util.concurrent.ExecutionException;
53
import java.util.concurrent.atomic.AtomicInteger;
54

55 56
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOG4J_NAME;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOGBACK_NAME;
57
import static org.hamcrest.Matchers.is;
58 59 60
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
61
import static org.junit.Assert.assertThat;
62
import static org.junit.Assert.assertTrue;
63
import static org.junit.Assert.fail;
64

65 66 67
/**
 * Tests for Fabric implementation of {@link FlinkKubeClient}.
 */
68
public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
69 70 71 72 73 74 75 76
	private static final int RPC_PORT = 7123;
	private static final int BLOB_SERVER_PORT = 8346;

	private static final double JOB_MANAGER_CPU = 2.0;
	private static final int JOB_MANAGER_MEMORY = 768;

	private static final String SERVICE_ACCOUNT_NAME = "service-test";

77 78
	private static final String TASKMANAGER_POD_NAME = "mock-task-manager-pod";

79 80 81 82 83 84 85 86 87 88 89 90
	private static final String TESTING_CONFIG_MAP_NAME = "test-config-map";
	private static final String TESTING_CONFIG_MAP_KEY = "test-config-map-key";
	private static final String TESTING_CONFIG_MAP_VALUE = "test-config-map-value";
	private static final String TESTING_CONFIG_MAP_NEW_VALUE = "test-config-map-new-value";

	private static final Map<String, String> TESTING_LABELS = new HashMap<String, String>() {
		{
			put("label1", "value1");
			put("label2", "value2");
		}
	};

91 92 93
	private static final String ENTRY_POINT_CLASS = KubernetesSessionClusterEntrypoint.class.getCanonicalName();

	private KubernetesJobManagerSpecification kubernetesJobManagerSpecification;
94

95 96 97
	@Override
	protected void setupFlinkConfig() {
		super.setupFlinkConfig();
98 99 100 101 102 103 104 105

		flinkConfig.set(KubernetesConfigOptions.CONTAINER_IMAGE_PULL_POLICY, CONTAINER_IMAGE_PULL_POLICY);
		flinkConfig.set(KubernetesConfigOptionsInternal.ENTRY_POINT_CLASS, ENTRY_POINT_CLASS);
		flinkConfig.set(RestOptions.PORT, REST_PORT);
		flinkConfig.set(JobManagerOptions.PORT, RPC_PORT);
		flinkConfig.set(BlobServerOptions.PORT, Integer.toString(BLOB_SERVER_PORT));
		flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_CPU, JOB_MANAGER_CPU);
		flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT, SERVICE_ACCOUNT_NAME);
106 107
	}

108 109 110
	@Override
	protected void onSetup() throws Exception {
		super.onSetup();
111

112 113
		KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOGBACK_NAME);
		KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOG4J_NAME);
114 115 116 117 118 119 120 121 122 123

		final ClusterSpecification clusterSpecification = new ClusterSpecification.ClusterSpecificationBuilder()
			.setMasterMemoryMB(JOB_MANAGER_MEMORY)
			.setTaskManagerMemoryMB(1000)
			.setSlotsPerTaskManager(3)
			.createClusterSpecification();

		final KubernetesJobManagerParameters kubernetesJobManagerParameters =
			new KubernetesJobManagerParameters(flinkConfig, clusterSpecification);
		this.kubernetesJobManagerSpecification =
124
			KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(kubernetesJobManagerParameters);
125 126 127
	}

	@Test
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
	public void testCreateFlinkMasterComponent() throws Exception {
		flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);

		final List<Deployment> resultedDeployments = kubeClient.apps().deployments()
			.inNamespace(NAMESPACE)
			.list()
			.getItems();
		assertEquals(1, resultedDeployments.size());

		final List<ConfigMap> resultedConfigMaps = kubeClient.configMaps()
			.inNamespace(NAMESPACE)
			.list()
			.getItems();
		assertEquals(1, resultedConfigMaps.size());

		final List<Service> resultedServices = kubeClient.services()
			.inNamespace(NAMESPACE)
			.list()
			.getItems();
		assertEquals(2, resultedServices.size());

		testOwnerReferenceSetting(resultedDeployments.get(0), resultedConfigMaps);
		testOwnerReferenceSetting(resultedDeployments.get(0), resultedServices);
	}

	private <T extends HasMetadata> void testOwnerReferenceSetting(
		HasMetadata ownerReference,
		List<T> resources) {
		resources.forEach(resource -> {
			List<OwnerReference> ownerReferences = resource.getMetadata().getOwnerReferences();
			assertEquals(1, ownerReferences.size());
			assertEquals(ownerReference.getMetadata().getUid(), ownerReferences.get(0).getUid());
		});
	}

	@Test
	public void testCreateFlinkTaskManagerPod() throws Exception {
		this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);

		final KubernetesPod kubernetesPod = new KubernetesPod(new PodBuilder()
			.editOrNewMetadata()
			.withName("mock-task-manager-pod")
			.endMetadata()
			.editOrNewSpec()
			.endSpec()
			.build());
174
		this.flinkKubeClient.createTaskManagerPod(kubernetesPod).get();
175 176

		final Pod resultTaskManagerPod =
177
			this.kubeClient.pods().inNamespace(NAMESPACE).withName(TASKMANAGER_POD_NAME).get();
178 179 180 181

		assertEquals(
			this.kubeClient.apps().deployments().inNamespace(NAMESPACE).list().getItems().get(0).getMetadata().getUid(),
			resultTaskManagerPod.getMetadata().getOwnerReferences().get(0).getUid());
182
	}
183 184

	@Test
185
	public void testStopPod() throws ExecutionException, InterruptedException {
186 187 188 189 190 191 192 193 194 195 196 197
		final String podName = "pod-for-delete";
		final Pod pod = new PodBuilder()
			.editOrNewMetadata()
			.withName(podName)
			.endMetadata()
			.editOrNewSpec()
			.endSpec()
			.build();

		this.kubeClient.pods().inNamespace(NAMESPACE).create(pod);
		assertNotNull(this.kubeClient.pods().inNamespace(NAMESPACE).withName(podName).get());

198
		this.flinkKubeClient.stopPod(podName).get();
199
		assertNull(this.kubeClient.pods().inNamespace(NAMESPACE).withName(podName).get());
200 201 202
	}

	@Test
203 204
	public void testServiceLoadBalancerWithNoIP() {
		final String hostName = "test-host-name";
205
		mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer(hostName, ""));
206

207
		final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
208

209 210 211
		assertThat(resultEndpoint.isPresent(), is(true));
		assertThat(resultEndpoint.get().getAddress(), is(hostName));
		assertThat(resultEndpoint.get().getPort(), is(REST_PORT));
212 213 214 215
	}

	@Test
	public void testServiceLoadBalancerEmptyHostAndIP() {
216
		mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer("", ""));
217

218 219
		final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
		assertThat(resultEndpoint.isPresent(), is(false));
220 221 222 223
	}

	@Test
	public void testServiceLoadBalancerNullHostAndIP() {
224
		mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer(null, null));
225

226 227
		final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
		assertThat(resultEndpoint.isPresent(), is(false));
228 229
	}

230 231 232 233
	@Test
	public void testNodePortService() {
		mockExpectedServiceFromServerSide(buildExternalServiceWithNodePort());

234 235 236
		final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
		assertThat(resultEndpoint.isPresent(), is(true));
		assertThat(resultEndpoint.get().getPort(), is(NODE_PORT));
237 238 239 240 241 242
	}

	@Test
	public void testClusterIPService() {
		mockExpectedServiceFromServerSide(buildExternalServiceWithClusterIP());

243 244
		final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
		assertThat(resultEndpoint.isPresent(), is(true));
245 246 247
		assertThat(
			resultEndpoint.get().getAddress(),
			is(ExternalServiceDecorator.getNamespacedExternalServiceName(CLUSTER_ID, NAMESPACE)));
248
		assertThat(resultEndpoint.get().getPort(), is(REST_PORT));
249 250
	}

251 252 253 254 255 256
	@Test
	public void testStopAndCleanupCluster() throws Exception {
		this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);

		final KubernetesPod kubernetesPod = new KubernetesPod(new PodBuilder()
			.editOrNewMetadata()
257
			.withName(TASKMANAGER_POD_NAME)
258 259 260 261
			.endMetadata()
			.editOrNewSpec()
			.endSpec()
			.build());
262
		this.flinkKubeClient.createTaskManagerPod(kubernetesPod).get();
263 264 265 266 267 268 269 270 271

		assertEquals(1, this.kubeClient.apps().deployments().inNamespace(NAMESPACE).list().getItems().size());
		assertEquals(1, this.kubeClient.configMaps().inNamespace(NAMESPACE).list().getItems().size());
		assertEquals(2, this.kubeClient.services().inNamespace(NAMESPACE).list().getItems().size());
		assertEquals(1, this.kubeClient.pods().inNamespace(NAMESPACE).list().getItems().size());

		this.flinkKubeClient.stopAndCleanupCluster(CLUSTER_ID);
		assertTrue(this.kubeClient.apps().deployments().inNamespace(NAMESPACE).list().getItems().isEmpty());
	}
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

	@Test
	public void testCreateConfigMap() throws Exception {
		final KubernetesConfigMap configMap = buildTestingConfigMap();
		this.flinkKubeClient.createConfigMap(configMap).get();
		final Optional<KubernetesConfigMap> currentOpt = this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
		assertThat(currentOpt.isPresent(), is(true));
		assertThat(currentOpt.get().getData().get(TESTING_CONFIG_MAP_KEY), is(TESTING_CONFIG_MAP_VALUE));
	}

	@Test
	public void testCreateConfigMapAlreadyExisting() throws Exception {
		final KubernetesConfigMap configMap = buildTestingConfigMap();
		this.flinkKubeClient.createConfigMap(configMap).get();

		mockCreateConfigMapAlreadyExisting(configMap.getInternalResource());
		configMap.getData().put(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_NEW_VALUE);
		try {
			this.flinkKubeClient.createConfigMap(configMap).get();
			fail("Overwrite an already existing config map should fail with an exception.");
		} catch (Exception ex) {
			final String errorMsg = "Failed to create ConfigMap " + TESTING_CONFIG_MAP_NAME;
			assertThat(ex, FlinkMatchers.containsMessage(errorMsg));
		}
		// Create failed we should still get the old value
		final Optional<KubernetesConfigMap> currentOpt = this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
		assertThat(currentOpt.isPresent(), is(true));
		assertThat(currentOpt.get().getData().get(TESTING_CONFIG_MAP_KEY), is(TESTING_CONFIG_MAP_VALUE));
	}

	@Test
	public void testDeleteConfigMapByLabels() throws Exception {
		this.flinkKubeClient.createConfigMap(buildTestingConfigMap()).get();
		assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(true));
		this.flinkKubeClient.deleteConfigMapsByLabels(TESTING_LABELS).get();
		assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
	}

	@Test
	public void testDeleteConfigMapByName() throws Exception {
		this.flinkKubeClient.createConfigMap(buildTestingConfigMap()).get();
		assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(true));
		this.flinkKubeClient.deleteConfigMap(TESTING_CONFIG_MAP_NAME).get();
		assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
	}

	@Test
	public void testCheckAndUpdateConfigMap() throws Exception {
		this.flinkKubeClient.createConfigMap(buildTestingConfigMap());

		// Checker pass
		final boolean updated = this.flinkKubeClient.checkAndUpdateConfigMap(
			TESTING_CONFIG_MAP_NAME,
			c -> {
				c.getData().put(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_NEW_VALUE);
				return Optional.of(c);
			}).get();
		assertThat(updated, is(true));

		final Optional<KubernetesConfigMap> configMapOpt = this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
		assertThat(configMapOpt.isPresent(), is(true));
		assertThat(configMapOpt.get().getData().get(TESTING_CONFIG_MAP_KEY), is(TESTING_CONFIG_MAP_NEW_VALUE));
	}

	@Test
	public void testCheckAndUpdateConfigMapWithEmptyResult() throws Exception {
		this.flinkKubeClient.createConfigMap(buildTestingConfigMap());

		// Checker not pass and return empty result
		final boolean updated = this.flinkKubeClient.checkAndUpdateConfigMap(
			TESTING_CONFIG_MAP_NAME, c -> Optional.empty()).get();
		assertThat(updated, is(false));

		final Optional<KubernetesConfigMap> configMapOpt = this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
		assertThat(configMapOpt.isPresent(), is(true));
		assertThat(configMapOpt.get().getData().get(TESTING_CONFIG_MAP_KEY), is(TESTING_CONFIG_MAP_VALUE));
	}

	@Test
	public void testCheckAndUpdateConfigMapWhenConfigMapNotExist() {
		try {
			final CompletableFuture<Boolean> future = this.flinkKubeClient.checkAndUpdateConfigMap(
				TESTING_CONFIG_MAP_NAME,
				c -> Optional.empty());
			future.get();
			fail("CheckAndUpdateConfigMap should fail with an exception when the ConfigMap does not exist.");
		} catch (Exception ex) {
			final String errMsg = "Cannot retry checkAndUpdateConfigMap with configMap "
				+ TESTING_CONFIG_MAP_NAME + " because it does not exist.";
			assertThat(ex, FlinkMatchers.containsMessage(errMsg));
			// Should not retry when ConfigMap does not exist.
			assertThat(ex, FlinkMatchers.containsMessage(
				"Stopped retrying the operation because the error is not retryable."));
		}
	}

	@Test
	public void testCheckAndUpdateConfigMapWhenReplaceConfigMapFailed() throws Exception {
		final int configuredRetries =
			flinkConfig.getInteger(KubernetesConfigOptions.KUBERNETES_TRANSACTIONAL_OPERATION_MAX_RETRIES);
		final KubernetesConfigMap configMap = buildTestingConfigMap();
		this.flinkKubeClient.createConfigMap(configMap).get();

		mockReplaceConfigMapFailed(configMap.getInternalResource());

		final AtomicInteger retries = new AtomicInteger(0);
		try {
			this.flinkKubeClient.checkAndUpdateConfigMap(TESTING_CONFIG_MAP_NAME, c -> {
				retries.incrementAndGet();
				return Optional.of(configMap);
			}).get();
			fail("CheckAndUpdateConfigMap should fail with exception when number of retries has been exhausted.");
		} catch (Exception ex) {
			assertThat(ex, FlinkMatchers.containsMessage("Could not complete the " +
				"operation. Number of retries has been exhausted."));
			assertThat(retries.get(), is(configuredRetries + 1));
		}
	}

	private KubernetesConfigMap buildTestingConfigMap() {
		final Map<String, String> data = new HashMap<>();
		data.put(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_VALUE);
		return new KubernetesConfigMap(new ConfigMapBuilder()
			.withNewMetadata()
			.withName(TESTING_CONFIG_MAP_NAME)
			.withLabels(TESTING_LABELS)
			.endMetadata()
			.withData(data).build());
	}
401
}