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

import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
23
import org.apache.flink.kubernetes.kubeclient.decorators.ExternalServiceDecorator;
24 25 26
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMapWatcher;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesException;
27
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesPod;
28
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesPodsWatcher;
29
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesService;
30
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesWatch;
31
import org.apache.flink.kubernetes.utils.Constants;
32
import org.apache.flink.kubernetes.utils.KubernetesUtils;
33 34
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.util.ExceptionUtils;
35

36
import io.fabric8.kubernetes.api.model.ConfigMap;
37
import io.fabric8.kubernetes.api.model.HasMetadata;
38
import io.fabric8.kubernetes.api.model.LoadBalancerStatus;
39 40
import io.fabric8.kubernetes.api.model.OwnerReference;
import io.fabric8.kubernetes.api.model.OwnerReferenceBuilder;
41 42 43
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
44
import io.fabric8.kubernetes.api.model.apps.Deployment;
45
import io.fabric8.kubernetes.client.KubernetesClient;
46
import io.fabric8.kubernetes.client.KubernetesClientException;
47 48 49 50 51 52 53
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
54 55
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
56
import java.util.concurrent.CompletionException;
57
import java.util.concurrent.Executor;
58
import java.util.function.Function;
59
import java.util.function.Supplier;
60 61 62 63 64 65 66 67 68 69 70 71 72
import java.util.stream.Collectors;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * The implementation of {@link FlinkKubeClient}.
 */
public class Fabric8FlinkKubeClient implements FlinkKubeClient {

	private static final Logger LOG = LoggerFactory.getLogger(Fabric8FlinkKubeClient.class);

	private final KubernetesClient internalClient;
	private final String clusterId;
73
	private final String namespace;
74
	private final int maxRetryAttempts;
75

76
	private final Executor kubeClientExecutorService;
77 78 79 80

	public Fabric8FlinkKubeClient(
			Configuration flinkConfig,
			KubernetesClient client,
81
			Supplier<Executor> asyncExecutorFactory) {
82 83 84
		this.internalClient = checkNotNull(client);
		this.clusterId = checkNotNull(flinkConfig.getString(KubernetesConfigOptions.CLUSTER_ID));

85
		this.namespace = flinkConfig.getString(KubernetesConfigOptions.NAMESPACE);
86

87 88 89
		this.maxRetryAttempts = flinkConfig.getInteger(
			KubernetesConfigOptions.KUBERNETES_TRANSACTIONAL_OPERATION_MAX_RETRIES);

90
		this.kubeClientExecutorService = asyncExecutorFactory.get();
91 92 93
	}

	@Override
94 95 96 97 98 99 100 101 102
	public void createJobManagerComponent(KubernetesJobManagerSpecification kubernetesJMSpec) {
		final Deployment deployment = kubernetesJMSpec.getDeployment();
		final List<HasMetadata> accompanyingResources = kubernetesJMSpec.getAccompanyingResources();

		// create Deployment
		LOG.debug("Start to create deployment with spec {}", deployment.getSpec().toString());
		final Deployment createdDeployment = this.internalClient
			.apps()
			.deployments()
103
			.inNamespace(this.namespace)
104 105 106 107 108 109 110
			.create(deployment);

		// Note that we should use the uid of the created Deployment for the OwnerReference.
		setOwnerReference(createdDeployment, accompanyingResources);

		this.internalClient
			.resourceList(accompanyingResources)
111
			.inNamespace(this.namespace)
112 113 114 115
			.createOrReplace();
	}

	@Override
116 117 118 119 120 121
	public CompletableFuture<Void> createTaskManagerPod(KubernetesPod kubernetesPod) {
		return CompletableFuture.runAsync(
			() -> {
				final Deployment masterDeployment = this.internalClient
					.apps()
					.deployments()
122
					.inNamespace(this.namespace)
123 124 125 126 127
					.withName(KubernetesUtils.getDeploymentName(clusterId))
					.get();

				if (masterDeployment == null) {
					throw new RuntimeException(
128
						"Failed to find Deployment named " + clusterId + " in namespace " + this.namespace);
129
				}
130

131 132
				// Note that we should use the uid of the master Deployment for the OwnerReference.
				setOwnerReference(masterDeployment, Collections.singletonList(kubernetesPod.getInternalResource()));
133

134 135 136
				LOG.debug("Start to create pod with metadata {}, spec {}",
					kubernetesPod.getInternalResource().getMetadata(),
					kubernetesPod.getInternalResource().getSpec());
137

138 139
				this.internalClient
					.pods()
140
					.inNamespace(this.namespace)
141 142 143
					.create(kubernetesPod.getInternalResource());
				},
			kubeClientExecutorService);
144 145 146
	}

	@Override
147 148 149 150
	public CompletableFuture<Void> stopPod(String podName) {
		return CompletableFuture.runAsync(
			() -> this.internalClient.pods().withName(podName).delete(),
			kubeClientExecutorService);
151 152 153
	}

	@Override
154 155 156 157
	public Optional<Endpoint> getRestEndpoint(String clusterId) {
		Optional<KubernetesService> restService = getRestService(clusterId);
		if (!restService.isPresent()) {
			return Optional.empty();
158
		}
159
		final Service service = restService.get().getInternalResource();
160 161 162 163
		final int restPort = getRestPortFromExternalService(service);

		final KubernetesConfigOptions.ServiceExposedType serviceExposedType =
			KubernetesConfigOptions.ServiceExposedType.valueOf(service.getSpec().getType());
164

165
		// Return the external service.namespace directly when using ClusterIP.
166
		if (serviceExposedType == KubernetesConfigOptions.ServiceExposedType.ClusterIP) {
167
			return Optional.of(
168
				new Endpoint(ExternalServiceDecorator.getNamespacedExternalServiceName(clusterId, namespace), restPort));
169 170
		}

171
		return getRestEndPointFromService(service, restPort);
172 173 174 175 176 177
	}

	@Override
	public List<KubernetesPod> getPodsWithLabels(Map<String, String> labels) {
		final List<Pod> podList = this.internalClient.pods().withLabels(labels).list().getItems();

178
		if (podList == null || podList.isEmpty()) {
179 180 181 182 183
			return new ArrayList<>();
		}

		return podList
			.stream()
184
			.map(KubernetesPod::new)
185 186 187 188 189
			.collect(Collectors.toList());
	}

	@Override
	public void stopAndCleanupCluster(String clusterId) {
190 191 192
		this.internalClient
			.apps()
			.deployments()
193
			.inNamespace(this.namespace)
194 195 196
			.withName(KubernetesUtils.getDeploymentName(clusterId))
			.cascading(true)
			.delete();
197 198 199 200
	}

	@Override
	public void handleException(Exception e) {
201
		LOG.error("A Kubernetes exception occurred.", e);
202 203 204
	}

	@Override
205
	public Optional<KubernetesService> getRestService(String clusterId) {
206
		final String serviceName = ExternalServiceDecorator.getExternalServiceName(clusterId);
207 208 209

		final Service service = this.internalClient
			.services()
210
			.inNamespace(namespace)
211 212 213 214 215 216
			.withName(serviceName)
			.fromServer()
			.get();

		if (service == null) {
			LOG.debug("Service {} does not exist", serviceName);
217
			return Optional.empty();
218 219
		}

220
		return Optional.of(new KubernetesService(service));
221 222 223
	}

	@Override
224 225 226
	public KubernetesWatch watchPodsAndDoCallback(
			Map<String, String> labels,
			WatchCallbackHandler<KubernetesPod> podCallbackHandler) {
227 228 229 230
		return new KubernetesWatch(
			this.internalClient.pods()
				.withLabels(labels)
				.watch(new KubernetesPodsWatcher(podCallbackHandler)));
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
	@Override
	public CompletableFuture<Void> createConfigMap(KubernetesConfigMap configMap) {
		final String configMapName = configMap.getName();
		return CompletableFuture.runAsync(
			() -> this.internalClient.configMaps().inNamespace(namespace).create(configMap.getInternalResource()),
			kubeClientExecutorService)
			.exceptionally(
				throwable -> {
					throw new CompletionException(
						new KubernetesException("Failed to create ConfigMap " + configMapName, throwable));
				});
	}

	@Override
	public Optional<KubernetesConfigMap> getConfigMap(String name) {
		final ConfigMap configMap = this.internalClient.configMaps().inNamespace(namespace).withName(name).get();
		return configMap == null ? Optional.empty() : Optional.of(new KubernetesConfigMap(configMap));
	}

	@Override
	public CompletableFuture<Boolean> checkAndUpdateConfigMap(
			String configMapName,
			Function<KubernetesConfigMap, Optional<KubernetesConfigMap>> function) {
		return FutureUtils.retry(
			() -> CompletableFuture.supplyAsync(
				() -> getConfigMap(configMapName)
					.map(
						configMap -> function.apply(configMap).map(
							updatedConfigMap -> {
								try {
									this.internalClient.configMaps()
										.inNamespace(namespace)
										.withName(configMapName)
										.lockResourceVersion(updatedConfigMap.getResourceVersion())
										.replace(updatedConfigMap.getInternalResource());
								} catch (Throwable throwable) {
									LOG.debug("Failed to update ConfigMap {} with data {} because of concurrent " +
										"modifications. Trying again.", configMap.getName(), configMap.getData());
									throw throwable;
								}
								return true;
							}).orElse(false))
					.orElseThrow(() -> new CompletionException(
						new KubernetesException("Cannot retry checkAndUpdateConfigMap with configMap "
							+ configMapName + " because it does not exist."))),
				kubeClientExecutorService),
			maxRetryAttempts,
			// Only KubernetesClientException is retryable
			throwable -> ExceptionUtils.findThrowable(throwable, KubernetesClientException.class).isPresent(),
			kubeClientExecutorService);
	}

	@Override
	public KubernetesWatch watchConfigMaps(
			String name,
			WatchCallbackHandler<KubernetesConfigMap> callbackHandler) {
		return new KubernetesWatch(
			this.internalClient.configMaps().withName(name).watch(new KubernetesConfigMapWatcher(callbackHandler)));
	}

	@Override
	public CompletableFuture<Void> deleteConfigMapsByLabels(Map<String, String> labels) {
		return CompletableFuture.runAsync(
			() -> this.internalClient.configMaps().inNamespace(namespace).withLabels(labels).delete(),
			kubeClientExecutorService);
	}

	@Override
	public CompletableFuture<Void> deleteConfigMap(String configMapName) {
		return CompletableFuture.runAsync(
			() -> this.internalClient.configMaps().inNamespace(namespace).withName(configMapName).delete(),
			kubeClientExecutorService);
	}

307 308 309 310 311
	@Override
	public void close() {
		this.internalClient.close();
	}

312 313 314 315 316 317 318 319 320 321 322 323 324
	private void setOwnerReference(Deployment deployment, List<HasMetadata> resources) {
		final OwnerReference deploymentOwnerReference = new OwnerReferenceBuilder()
			.withName(deployment.getMetadata().getName())
			.withApiVersion(deployment.getApiVersion())
			.withUid(deployment.getMetadata().getUid())
			.withKind(deployment.getKind())
			.withController(true)
			.withBlockOwnerDeletion(true)
			.build();
		resources.forEach(resource ->
			resource.getMetadata().setOwnerReferences(Collections.singletonList(deploymentOwnerReference)));
	}

325
	/**
326
	 * Get rest port from the external Service.
327
	 */
328 329 330 331 332 333 334 335
	private int getRestPortFromExternalService(Service externalService) {
		final List<ServicePort> servicePortCandidates = externalService.getSpec().getPorts()
			.stream()
			.filter(x -> x.getName().equals(Constants.REST_PORT_NAME))
			.collect(Collectors.toList());

		if (servicePortCandidates.isEmpty()) {
			throw new RuntimeException("Failed to find port \"" + Constants.REST_PORT_NAME + "\" in Service \"" +
336
				ExternalServiceDecorator.getExternalServiceName(this.clusterId) + "\"");
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
		}

		final ServicePort externalServicePort = servicePortCandidates.get(0);

		final KubernetesConfigOptions.ServiceExposedType externalServiceType =
			KubernetesConfigOptions.ServiceExposedType.valueOf(externalService.getSpec().getType());

		switch (externalServiceType) {
			case ClusterIP:
			case LoadBalancer:
				return externalServicePort.getPort();
			case NodePort:
				return externalServicePort.getNodePort();
			default:
				throw new RuntimeException("Unrecognized Service type: " + externalServiceType);
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

	private Optional<Endpoint> getRestEndPointFromService(Service service, int restPort) {
		if (service.getStatus() == null) {
			return Optional.empty();
		}

		LoadBalancerStatus loadBalancer = service.getStatus().getLoadBalancer();
		boolean hasExternalIP = service.getSpec() != null &&
			service.getSpec().getExternalIPs() != null && !service.getSpec().getExternalIPs().isEmpty();

		if (loadBalancer != null) {
			return getLoadBalancerRestEndpoint(loadBalancer, restPort);
		} else if (hasExternalIP) {
			final String address = service.getSpec().getExternalIPs().get(0);
			if (address != null && !address.isEmpty()) {
				return Optional.of(new Endpoint(address, restPort));
			}
		}
		return Optional.empty();
	}

	private Optional<Endpoint> getLoadBalancerRestEndpoint(LoadBalancerStatus loadBalancer, int restPort) {
		boolean hasIngress = loadBalancer.getIngress() != null && !loadBalancer.getIngress().isEmpty();
		String address;
		if (hasIngress) {
			address = loadBalancer.getIngress().get(0).getIp();
			// Use hostname when the ip address is null
			if (address == null || address.isEmpty()) {
				address = loadBalancer.getIngress().get(0).getHostname();
			}
		} else {
			// Use node port
			address = this.internalClient.getMasterUrl().getHost();
		}
		boolean noAddress = address == null || address.isEmpty();
		return noAddress ? Optional.empty() : Optional.of(new Endpoint(address, restPort));
	}
391
}