Improve the default client loading code. (#251)

* Improve the default client loading code.

* Address comments.
This commit is contained in:
Brendan Burns
2019-03-06 01:26:04 -08:00
committed by Kubernetes Prow Robot
parent e0db2ae8bd
commit de99b2b6b4
3 changed files with 41 additions and 6 deletions

View File

@@ -6,23 +6,38 @@ namespace k8s
{
public partial class KubernetesClientConfiguration
{
private const string ServiceaccountPath = "/var/run/secrets/kubernetes.io/serviceaccount/";
private const string ServiceAccountPath = "/var/run/secrets/kubernetes.io/serviceaccount/";
private const string ServiceAccountTokenKeyFileName = "token";
private const string ServiceAccountRootCAKeyFileName = "ca.crt";
public static KubernetesClientConfiguration InClusterConfig()
public static Boolean IsInCluster()
{
var host = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
var port = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(port))
{
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()) {
throw new KubeConfigException(
"unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined");
}
var token = File.ReadAllText(Path.Combine(ServiceaccountPath, ServiceAccountTokenKeyFileName));
var rootCAFile = Path.Combine(ServiceaccountPath, ServiceAccountRootCAKeyFileName);
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");
return new KubernetesClientConfiguration
{