mirror of
https://github.com/nsnail/Ocelot.git
synced 2025-04-25 06:22:49 +08:00
60 lines
2.0 KiB
C#
60 lines
2.0 KiB
C#
using KubeClient;
|
|
using KubeClient.Models;
|
|
using Ocelot.Logging;
|
|
using Ocelot.ServiceDiscovery.Providers;
|
|
using Ocelot.Values;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Ocelot.Provider.Kubernetes
|
|
{
|
|
public class Kube : IServiceDiscoveryProvider
|
|
{
|
|
private KubeRegistryConfiguration kubeRegistryConfiguration;
|
|
private IOcelotLogger logger;
|
|
private IKubeApiClient kubeApi;
|
|
|
|
public Kube(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClientFactory kubeClientFactory)
|
|
{
|
|
this.kubeRegistryConfiguration = kubeRegistryConfiguration;
|
|
this.logger = factory.CreateLogger<Kube>();
|
|
this.kubeApi = kubeClientFactory.Get(kubeRegistryConfiguration);
|
|
}
|
|
|
|
public async Task<List<Service>> Get()
|
|
{
|
|
logger.LogDebug($"namespace:{kubeRegistryConfiguration.KubeNamespace } service:{kubeRegistryConfiguration.KeyOfServiceInK8s}");
|
|
var service = await kubeApi.ServicesV1().Get(kubeRegistryConfiguration.KeyOfServiceInK8s, kubeRegistryConfiguration.KubeNamespace);
|
|
var services = new List<Service>();
|
|
if (IsValid(service))
|
|
{
|
|
services.Add(BuildService(service));
|
|
}
|
|
return services;
|
|
}
|
|
|
|
private bool IsValid(ServiceV1 service)
|
|
{
|
|
if (string.IsNullOrEmpty(service.Spec.ClusterIP) || service.Spec.Ports.Count <= 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private Service BuildService(ServiceV1 serviceEntry)
|
|
{
|
|
var servicePort = serviceEntry.Spec.Ports.FirstOrDefault();
|
|
return new Service(
|
|
serviceEntry.Metadata.Name,
|
|
new ServiceHostAndPort(serviceEntry.Spec.ClusterIP, servicePort.Port),
|
|
serviceEntry.Metadata.Uid,
|
|
string.Empty,
|
|
Enumerable.Empty<string>());
|
|
}
|
|
}
|
|
}
|