2018-09-27 10:50:39 -07:00
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using k8s.Exceptions;
|
|
|
|
|
|
|
|
|
|
namespace k8s
|
|
|
|
|
{
|
|
|
|
|
public partial class KubernetesClientConfiguration
|
|
|
|
|
{
|
2019-12-19 16:45:32 -08:00
|
|
|
private static string ServiceAccountPath =
|
|
|
|
|
Path.Combine(new string[] {
|
2020-01-06 12:44:16 -08:00
|
|
|
$"{Path.DirectorySeparatorChar}var", "run", "secrets", "kubernetes.io", "serviceaccount"
|
2019-12-19 16:45:32 -08:00
|
|
|
});
|
2018-09-27 10:50:39 -07:00
|
|
|
private const string ServiceAccountTokenKeyFileName = "token";
|
|
|
|
|
private const string ServiceAccountRootCAKeyFileName = "ca.crt";
|
|
|
|
|
|
2019-03-06 01:26:04 -08:00
|
|
|
public static Boolean IsInCluster()
|
2018-09-27 10:50:39 -07:00
|
|
|
{
|
|
|
|
|
var host = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
|
|
|
|
|
var port = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");
|
|
|
|
|
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(port))
|
|
|
|
|
{
|
2019-03-06 01:26:04 -08:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
var tokenPath = Path.Combine(ServiceAccountPath, ServiceAccountTokenKeyFileName);
|
|
|
|
|
if (!File.Exists(tokenPath))
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
var certPath = Path.Combine(ServiceAccountPath, ServiceAccountRootCAKeyFileName);
|
|
|
|
|
return File.Exists(certPath);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static KubernetesClientConfiguration InClusterConfig()
|
|
|
|
|
{
|
|
|
|
|
if (!IsInCluster()) {
|
2018-09-27 10:50:39 -07:00
|
|
|
throw new KubeConfigException(
|
|
|
|
|
"unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined");
|
|
|
|
|
}
|
|
|
|
|
|
2019-03-06 01:26:04 -08:00
|
|
|
var token = File.ReadAllText(Path.Combine(ServiceAccountPath, ServiceAccountTokenKeyFileName));
|
|
|
|
|
var rootCAFile = Path.Combine(ServiceAccountPath, ServiceAccountRootCAKeyFileName);
|
|
|
|
|
var host = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
|
|
|
|
|
var port = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");
|
2018-09-27 10:50:39 -07:00
|
|
|
|
|
|
|
|
return new KubernetesClientConfiguration
|
|
|
|
|
{
|
|
|
|
|
Host = new UriBuilder("https", host, Convert.ToInt32(port)).ToString(),
|
|
|
|
|
AccessToken = token,
|
2019-03-11 06:39:28 -07:00
|
|
|
SslCaCerts = CertUtils.LoadPemFileCert(rootCAFile)
|
2018-09-27 10:50:39 -07:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-11-08 14:22:10 +08:00
|
|
|
}
|