K8SServiceRegistry.java 11.5 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 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
/*
 * 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.skywalking.oap.server.receiver.envoy.als.k8s;

import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.kubernetes.client.informer.ResourceEventHandler;
import io.kubernetes.client.informer.SharedInformerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Endpoints;
import io.kubernetes.client.openapi.models.V1EndpointsList;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServiceList;
import io.kubernetes.client.util.Config;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.oap.server.receiver.envoy.EnvoyMetricReceiverConfig;
import org.apache.skywalking.oap.server.receiver.envoy.als.ServiceMetaInfo;

import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Objects.isNull;
51
import static java.util.Optional.ofNullable;
52 53

@Slf4j
54 55
public class K8SServiceRegistry {
    protected final Map<String/* ip */, ServiceMetaInfo> ipServiceMetaInfoMap;
56

57
    protected final Map<String/* namespace:serviceName */, V1Service> idServiceMap;
58

59
    protected final Map<String/* ip */, V1Pod> ipPodMap;
60

61
    protected final Map<String/* ip */, String/* namespace:serviceName */> ipServiceMap;
62

63
    protected final ExecutorService executor;
64

65
    protected final ServiceNameFormatter serviceNameFormatter;
66

67
    public K8SServiceRegistry(final EnvoyMetricReceiverConfig config) {
68 69 70 71 72 73 74 75 76 77 78 79 80
        serviceNameFormatter = new ServiceNameFormatter(config.getK8sServiceNameRule());
        ipServiceMetaInfoMap = new ConcurrentHashMap<>();
        idServiceMap = new ConcurrentHashMap<>();
        ipPodMap = new ConcurrentHashMap<>();
        ipServiceMap = new ConcurrentHashMap<>();
        executor = Executors.newCachedThreadPool(
            new ThreadFactoryBuilder()
                .setNameFormat("K8SServiceRegistry-%d")
                .setDaemon(true)
                .build()
        );
    }

81
    public void start() throws IOException {
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
        final ApiClient apiClient = Config.defaultClient();
        apiClient.setHttpClient(apiClient.getHttpClient()
                                         .newBuilder()
                                         .readTimeout(0, TimeUnit.SECONDS)
                                         .build());
        Configuration.setDefaultApiClient(apiClient);

        final CoreV1Api coreV1Api = new CoreV1Api();
        final SharedInformerFactory factory = new SharedInformerFactory(executor);

        // TODO: also listen to the EndpointSlice event after the client supports us to do so
        listenServiceEvents(coreV1Api, factory);
        listenEndpointsEvents(coreV1Api, factory);
        listenPodEvents(coreV1Api, factory);

        factory.startAllRegisteredInformers();
    }

    private void listenServiceEvents(final CoreV1Api coreV1Api, final SharedInformerFactory factory) {
        factory.sharedIndexInformerFor(
            params -> coreV1Api.listServiceForAllNamespacesCall(
                null,
                null,
                null,
                null,
                null,
                null,
                params.resourceVersion,
110
                300,
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
                params.watch,
                null
            ),
            V1Service.class,
            V1ServiceList.class
        ).addEventHandler(new ResourceEventHandler<V1Service>() {
            @Override
            public void onAdd(final V1Service service) {
                addService(service);
            }

            @Override
            public void onUpdate(final V1Service oldService, final V1Service newService) {
                addService(newService);
            }

            @Override
            public void onDelete(final V1Service service, final boolean deletedFinalStateUnknown) {
                removeService(service);
            }
        });
    }

    private void listenEndpointsEvents(final CoreV1Api coreV1Api, final SharedInformerFactory factory) {
        factory.sharedIndexInformerFor(
            params -> coreV1Api.listEndpointsForAllNamespacesCall(
                null,
                null,
                null,
                null,
                null,
                null,
                params.resourceVersion,
144
                300,
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
                params.watch,
                null
            ),
            V1Endpoints.class,
            V1EndpointsList.class
        ).addEventHandler(new ResourceEventHandler<V1Endpoints>() {
            @Override
            public void onAdd(final V1Endpoints endpoints) {
                addEndpoints(endpoints);
            }

            @Override
            public void onUpdate(final V1Endpoints oldEndpoints, final V1Endpoints newEndpoints) {
                addEndpoints(newEndpoints);
            }

            @Override
            public void onDelete(final V1Endpoints endpoints, final boolean deletedFinalStateUnknown) {
                removeEndpoints(endpoints);
            }
        });
    }

    private void listenPodEvents(final CoreV1Api coreV1Api, final SharedInformerFactory factory) {
        factory.sharedIndexInformerFor(
            params -> coreV1Api.listPodForAllNamespacesCall(
                null,
                null,
                null,
                null,
                null,
                null,
                params.resourceVersion,
178
                300,
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
                params.watch,
                null
            ),
            V1Pod.class,
            V1PodList.class
        ).addEventHandler(new ResourceEventHandler<V1Pod>() {
            @Override
            public void onAdd(final V1Pod pod) {
                addPod(pod);
            }

            @Override
            public void onUpdate(final V1Pod oldPod, final V1Pod newPod) {
                addPod(newPod);
            }

            @Override
            public void onDelete(final V1Pod pod, final boolean deletedFinalStateUnknown) {
                removePod(pod);
            }
        });
    }

202
    protected void addService(final V1Service service) {
203
        ofNullable(service.getMetadata()).ifPresent(
204 205 206 207 208 209
            metadata -> idServiceMap.put(metadata.getNamespace() + ":" + metadata.getName(), service)
        );

        recompose();
    }

210
    protected void removeService(final V1Service service) {
211
        ofNullable(service.getMetadata()).ifPresent(
212
            metadata -> idServiceMap.remove(metadata.getNamespace() + ":" + metadata.getName())
213 214 215
        );
    }

216
    protected void addPod(final V1Pod pod) {
217
        ofNullable(pod.getStatus()).ifPresent(
218 219 220 221 222 223
            status -> ipPodMap.put(status.getPodIP(), pod)
        );

        recompose();
    }

224
    protected void removePod(final V1Pod pod) {
225
        ofNullable(pod.getStatus()).ifPresent(
226 227 228 229
            status -> ipPodMap.remove(status.getPodIP())
        );
    }

230
    protected void addEndpoints(final V1Endpoints endpoints) {
231 232 233 234 235 236 237 238
        V1ObjectMeta endpointsMetadata = endpoints.getMetadata();
        if (isNull(endpointsMetadata)) {
            log.error("Endpoints metadata is null: {}", endpoints);
            return;
        }

        final String namespace = endpointsMetadata.getNamespace();
        final String name = endpointsMetadata.getName();
239

240 241
        ofNullable(endpoints.getSubsets()).ifPresent(subsets -> subsets.forEach(
            subset -> ofNullable(subset.getAddresses()).ifPresent(addresses -> addresses.forEach(
242
                address -> ipServiceMap.put(address.getIp(), namespace + ":" + name)
243 244
            ))
        ));
245 246 247 248

        recompose();
    }

249
    protected void removeEndpoints(final V1Endpoints endpoints) {
250 251
        ofNullable(endpoints.getSubsets()).ifPresent(subsets -> subsets.forEach(
            subset -> ofNullable(subset.getAddresses()).ifPresent(addresses -> addresses.forEach(
252
                address -> ipServiceMap.remove(address.getIp())
253 254
            ))
        ));
255 256
    }

257
    protected List<ServiceMetaInfo.KeyValue> transformLabelsToTags(final Map<String, String> labels) {
258 259 260 261 262 263 264 265 266
        if (isNull(labels)) {
            return Collections.emptyList();
        }
        return labels.entrySet()
                     .stream()
                     .map(each -> new ServiceMetaInfo.KeyValue(each.getKey(), each.getValue()))
                     .collect(Collectors.toList());
    }

267
    protected ServiceMetaInfo findService(final String ip) {
268 269 270 271 272 273 274 275
        final ServiceMetaInfo service = ipServiceMetaInfoMap.get(ip);
        if (isNull(service)) {
            log.debug("Unknown ip {}, ip -> service is null", ip);
            return ServiceMetaInfo.UNKNOWN;
        }
        return service;
    }

276
    protected void recompose() {
277 278 279 280 281 282 283 284
        ipPodMap.forEach((ip, pod) -> {
            final String namespaceService = ipServiceMap.get(ip);
            final V1Service service;
            if (isNullOrEmpty(namespaceService) || isNull(service = idServiceMap.get(namespaceService))) {
                return;
            }

            final Map<String, Object> context = ImmutableMap.of("service", service, "pod", pod);
285 286 287 288 289
            final V1ObjectMeta podMetadata = pod.getMetadata();
            if (isNull(podMetadata)) {
                log.warn("Pod metadata is null, {}", pod);
                return;
            }
290 291 292 293 294 295 296 297

            ipServiceMetaInfoMap.computeIfAbsent(ip, unused -> {
                final ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();

                try {
                    serviceMetaInfo.setServiceName(serviceNameFormatter.format(context));
                } catch (Exception e) {
                    log.error("Failed to evaluate service name.", e);
298 299 300 301 302 303
                    final V1ObjectMeta serviceMetadata = service.getMetadata();
                    if (isNull(serviceMetadata)) {
                        log.warn("Service metadata is null, {}", service);
                        return ServiceMetaInfo.UNKNOWN;
                    }
                    serviceMetaInfo.setServiceName(serviceMetadata.getName());
304
                }
305 306
                serviceMetaInfo.setServiceInstanceName(
                    String.format("%s.%s", podMetadata.getName(), podMetadata.getNamespace()));
307 308 309 310 311 312 313
                serviceMetaInfo.setTags(transformLabelsToTags(podMetadata.getLabels()));

                return serviceMetaInfo;
            });
        });
    }

314
    protected boolean isEmpty() {
315 316 317
        return ipServiceMetaInfoMap.isEmpty();
    }
}