cs-codex-dist-tests/KubernetesWorkflow/K8sController.cs

559 lines
20 KiB
C#
Raw Normal View History

using k8s;
using k8s.Models;
2023-04-25 09:31:15 +00:00
using Logging;
using Utils;
namespace KubernetesWorkflow
2023-04-12 11:53:55 +00:00
{
public class K8sController
{
2023-04-25 09:31:15 +00:00
private readonly BaseLog log;
2023-04-12 11:53:55 +00:00
private readonly K8sCluster cluster;
private readonly KnownK8sPods knownPods;
private readonly WorkflowNumberSource workflowNumberSource;
2023-05-04 06:25:48 +00:00
private readonly K8sClient client;
2023-04-12 11:53:55 +00:00
2023-05-03 12:18:37 +00:00
public K8sController(BaseLog log, K8sCluster cluster, KnownK8sPods knownPods, WorkflowNumberSource workflowNumberSource, string testNamespace)
2023-04-12 11:53:55 +00:00
{
2023-04-25 09:31:15 +00:00
this.log = log;
2023-04-12 11:53:55 +00:00
this.cluster = cluster;
this.knownPods = knownPods;
this.workflowNumberSource = workflowNumberSource;
2023-05-04 06:25:48 +00:00
client = new K8sClient(cluster.GetK8sClientConfig());
K8sTestNamespace = cluster.Configuration.K8sNamespacePrefix + testNamespace;
}
public void Dispose()
{
client.Dispose();
}
public RunningPod BringOnline(ContainerRecipe[] containerRecipes, Location location)
{
2023-04-25 09:31:15 +00:00
log.Debug();
EnsureTestNamespace();
2023-04-13 09:07:36 +00:00
var deploymentName = CreateDeployment(containerRecipes, location);
var (serviceName, servicePortsMap) = CreateService(containerRecipes);
var (podName, podIp) = FetchNewPod();
2023-04-13 09:07:36 +00:00
return new RunningPod(cluster, podName, podIp, deploymentName, serviceName, servicePortsMap);
}
public void Stop(RunningPod pod)
{
2023-04-25 09:31:15 +00:00
log.Debug();
2023-04-13 09:07:36 +00:00
if (!string.IsNullOrEmpty(pod.ServiceName)) DeleteService(pod.ServiceName);
DeleteDeployment(pod.DeploymentName);
WaitUntilDeploymentOffline(pod.DeploymentName);
WaitUntilPodOffline(pod.Name);
}
2023-04-13 09:30:19 +00:00
public void DownloadPodLog(RunningPod pod, ContainerRecipe recipe, ILogHandler logHandler)
{
2023-04-25 09:31:15 +00:00
log.Debug();
2023-05-04 06:25:48 +00:00
using var stream = client.Run(c => c.ReadNamespacedPodLog(pod.Name, K8sTestNamespace, recipe.Name));
2023-04-13 09:30:19 +00:00
logHandler.Log(stream);
}
2023-04-14 07:54:07 +00:00
public string ExecuteCommand(RunningPod pod, string containerName, string command, params string[] args)
{
var cmdAndArgs = $"{containerName}: {command} ({string.Join(",", args)})";
log.Debug(cmdAndArgs);
2023-05-03 12:18:37 +00:00
var runner = new CommandRunner(client, K8sTestNamespace, pod, containerName, command, args);
2023-04-14 07:54:07 +00:00
runner.Run();
var result = runner.GetStdOut();
log.Debug($"{cmdAndArgs} = '{result}'");
return result;
2023-04-14 07:54:07 +00:00
}
public void DeleteAllResources()
{
2023-04-25 09:31:15 +00:00
log.Debug();
2023-05-04 06:25:48 +00:00
var all = client.Run(c => c.ListNamespace().Items);
2023-05-03 12:18:37 +00:00
var namespaces = all.Select(n => n.Name()).Where(n => n.StartsWith(cluster.Configuration.K8sNamespacePrefix));
foreach (var ns in namespaces)
{
DeleteNamespace(ns);
}
foreach (var ns in namespaces)
{
WaitUntilNamespaceDeleted(ns);
}
}
public void DeleteTestNamespace()
{
log.Debug();
if (IsTestNamespaceOnline())
{
2023-05-04 06:25:48 +00:00
client.Run(c => c.DeleteNamespace(K8sTestNamespace, null, null, gracePeriodSeconds: 0));
2023-05-03 12:18:37 +00:00
}
WaitUntilNamespaceDeleted();
}
2023-05-03 12:18:37 +00:00
public void DeleteNamespace(string ns)
{
log.Debug();
if (IsNamespaceOnline(ns))
{
2023-05-04 06:25:48 +00:00
client.Run(c => c.DeleteNamespace(ns, null, null, gracePeriodSeconds: 0));
2023-05-03 12:18:37 +00:00
}
}
#region Namespace management
2023-05-04 06:25:48 +00:00
private string K8sTestNamespace { get; }
private void EnsureTestNamespace()
{
if (IsTestNamespaceOnline()) return;
var namespaceSpec = new V1Namespace
{
ApiVersion = "v1",
Metadata = new V1ObjectMeta
{
2023-05-03 12:18:37 +00:00
Name = K8sTestNamespace,
Labels = new Dictionary<string, string> { { "name", K8sTestNamespace } }
}
};
2023-05-04 06:25:48 +00:00
client.Run(c => c.CreateNamespace(namespaceSpec));
WaitUntilNamespaceCreated();
CreatePolicy();
}
2023-05-03 12:18:37 +00:00
private bool IsTestNamespaceOnline()
{
2023-05-03 12:18:37 +00:00
return IsNamespaceOnline(K8sTestNamespace);
}
2023-05-03 12:18:37 +00:00
private bool IsNamespaceOnline(string name)
{
2023-05-04 06:25:48 +00:00
return client.Run(c => c.ListNamespace().Items.Any(n => n.Metadata.Name == name));
}
private void CreatePolicy()
{
client.Run(c =>
{
var body = new V1NetworkPolicy
{
Metadata = new V1ObjectMeta
{
Name = "isolate-policy",
NamespaceProperty = K8sTestNamespace
},
Spec = new V1NetworkPolicySpec
{
2023-05-30 19:41:34 +00:00
PodSelector = new V1LabelSelector {},
PolicyTypes = new[]
{
"Ingress",
"Egress"
},
Ingress = new List<V1NetworkPolicyIngressRule>
{
new V1NetworkPolicyIngressRule
{
FromProperty = new List<V1NetworkPolicyPeer>
{
new V1NetworkPolicyPeer
{
2023-05-30 19:41:34 +00:00
PodSelector = new V1LabelSelector {}
}
}
},
new V1NetworkPolicyIngressRule
{
FromProperty = new List<V1NetworkPolicyPeer>
{
new V1NetworkPolicyPeer
{
NamespaceSelector = new V1LabelSelector
{
MatchLabels = GetRunnerNamespaceSelector()
}
}
}
}
},
Egress = new List<V1NetworkPolicyEgressRule>
{
2023-05-30 19:41:34 +00:00
new V1NetworkPolicyEgressRule
{
To = new List<V1NetworkPolicyPeer>
{
new V1NetworkPolicyPeer
{
PodSelector = new V1LabelSelector {}
}
}
},
new V1NetworkPolicyEgressRule
{
To = new List<V1NetworkPolicyPeer>
{
new V1NetworkPolicyPeer
{
NamespaceSelector = new V1LabelSelector
{
2023-05-30 19:41:34 +00:00
MatchLabels = new Dictionary<string, string> { { "kubernetes.io/metadata.name", "kube-system" } }
}
},
new V1NetworkPolicyPeer
{
PodSelector = new V1LabelSelector
{
MatchLabels = new Dictionary<string, string> { { "k8s-app", "kube-dns" } }
}
}
2023-05-30 19:41:34 +00:00
},
Ports = new List<V1NetworkPolicyPort>
{
new V1NetworkPolicyPort
{
Port = new IntstrIntOrString
{
Value = "53"
},
Protocol = "UDP"
}
}
},
new V1NetworkPolicyEgressRule
{
To = new List<V1NetworkPolicyPeer>
{
new V1NetworkPolicyPeer
{
IpBlock = new V1IPBlock
{
Cidr = "0.0.0.0/0"
}
}
},
Ports = new List<V1NetworkPolicyPort>
{
new V1NetworkPolicyPort
{
Port = new IntstrIntOrString
{
Value = "80"
},
Protocol = "TCP"
},
new V1NetworkPolicyPort
{
Port = new IntstrIntOrString
{
Value = "443"
},
Protocol = "TCP"
}
}
}
2023-05-30 19:41:34 +00:00
}
}
};
c.CreateNamespacedNetworkPolicy(body, K8sTestNamespace);
});
}
#endregion
#region Deployment management
2023-04-13 09:07:36 +00:00
private string CreateDeployment(ContainerRecipe[] containerRecipes, Location location)
{
var deploymentSpec = new V1Deployment
{
ApiVersion = "apps/v1",
Metadata = CreateDeploymentMetadata(),
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector
{
MatchLabels = GetSelector()
},
Template = new V1PodTemplateSpec
{
Metadata = new V1ObjectMeta
{
Labels = GetSelector()
},
Spec = new V1PodSpec
{
NodeSelector = CreateNodeSelector(location),
Containers = CreateDeploymentContainers(containerRecipes)
}
}
}
};
2023-05-04 06:25:48 +00:00
client.Run(c => c.CreateNamespacedDeployment(deploymentSpec, K8sTestNamespace));
2023-04-13 09:07:36 +00:00
WaitUntilDeploymentOnline(deploymentSpec.Metadata.Name);
return deploymentSpec.Metadata.Name;
}
private void DeleteDeployment(string deploymentName)
{
2023-05-04 06:25:48 +00:00
client.Run(c => c.DeleteNamespacedDeployment(deploymentName, K8sTestNamespace));
2023-04-13 09:07:36 +00:00
WaitUntilDeploymentOffline(deploymentName);
}
private IDictionary<string, string> CreateNodeSelector(Location location)
{
if (location == Location.Unspecified) return new Dictionary<string, string>();
return new Dictionary<string, string>
{
{ "codex-test-location", cluster.GetNodeLabelForLocation(location) }
};
}
private IDictionary<string, string> GetSelector()
{
return new Dictionary<string, string> { { "codex-test-node", "dist-test-" + workflowNumberSource.WorkflowNumber } };
}
private IDictionary<string, string> GetRunnerNamespaceSelector()
{
return new Dictionary<string, string> { { "kubernetes.io/metadata.name", "default" } };
}
private V1ObjectMeta CreateDeploymentMetadata()
{
return new V1ObjectMeta
{
Name = "deploy-" + workflowNumberSource.WorkflowNumber,
NamespaceProperty = K8sTestNamespace,
Labels = GetSelector()
};
}
private List<V1Container> CreateDeploymentContainers(ContainerRecipe[] containerRecipes)
{
return containerRecipes.Select(r => CreateDeploymentContainer(r)).ToList();
}
private V1Container CreateDeploymentContainer(ContainerRecipe recipe)
{
return new V1Container
{
Name = recipe.Name,
Image = recipe.Image,
Ports = CreateContainerPorts(recipe),
Env = CreateEnv(recipe)
};
2023-04-12 11:53:55 +00:00
}
private List<V1EnvVar> CreateEnv(ContainerRecipe recipe)
2023-04-12 11:53:55 +00:00
{
return recipe.EnvVars.Select(CreateEnvVar).ToList();
}
private V1EnvVar CreateEnvVar(EnvVar envVar)
{
return new V1EnvVar
{
Name = envVar.Name,
Value = envVar.Value,
};
}
private List<V1ContainerPort> CreateContainerPorts(ContainerRecipe recipe)
{
var exposedPorts = recipe.ExposedPorts.Select(p => CreateContainerPort(recipe, p));
var internalPorts = recipe.InternalPorts.Select(p => CreateContainerPort(recipe, p));
return exposedPorts.Concat(internalPorts).ToList();
}
private V1ContainerPort CreateContainerPort(ContainerRecipe recipe, Port port)
{
return new V1ContainerPort
{
Name = GetNameForPort(recipe, port),
ContainerPort = port.Number
};
}
private string GetNameForPort(ContainerRecipe recipe, Port port)
{
2023-04-13 07:33:10 +00:00
return $"p{workflowNumberSource.WorkflowNumber}-{recipe.Number}-{port.Number}";
}
#endregion
#region Service management
2023-04-13 09:07:36 +00:00
private (string, Dictionary<ContainerRecipe, Port[]>) CreateService(ContainerRecipe[] containerRecipes)
{
var result = new Dictionary<ContainerRecipe, Port[]>();
var ports = CreateServicePorts(result, containerRecipes);
if (!ports.Any())
{
2023-05-30 19:41:34 +00:00
// None of these container-recipes wish to expose anything via a service port.
// So, we don't have to create a service.
2023-04-13 09:07:36 +00:00
return (string.Empty, result);
}
var serviceSpec = new V1Service
{
ApiVersion = "v1",
Metadata = CreateServiceMetadata(),
Spec = new V1ServiceSpec
{
Type = "NodePort",
Selector = GetSelector(),
Ports = ports
}
};
2023-05-04 06:25:48 +00:00
client.Run(c => c.CreateNamespacedService(serviceSpec, K8sTestNamespace));
2023-04-13 09:07:36 +00:00
return (serviceSpec.Metadata.Name, result);
}
private void DeleteService(string serviceName)
{
2023-05-04 06:25:48 +00:00
client.Run(c => c.DeleteNamespacedService(serviceName, K8sTestNamespace));
}
private V1ObjectMeta CreateServiceMetadata()
{
return new V1ObjectMeta
{
2023-04-13 08:11:33 +00:00
Name = "service-" + workflowNumberSource.WorkflowNumber,
2023-05-03 12:18:37 +00:00
NamespaceProperty = K8sTestNamespace
};
}
private List<V1ServicePort> CreateServicePorts(Dictionary<ContainerRecipe, Port[]> servicePorts, ContainerRecipe[] recipes)
{
var result = new List<V1ServicePort>();
foreach (var recipe in recipes)
{
result.AddRange(CreateServicePorts(servicePorts, recipe));
}
return result;
}
private List<V1ServicePort> CreateServicePorts(Dictionary<ContainerRecipe, Port[]> servicePorts, ContainerRecipe recipe)
{
var result = new List<V1ServicePort>();
var usedPorts = new List<Port>();
foreach (var port in recipe.ExposedPorts)
{
var servicePort = workflowNumberSource.GetServicePort();
2023-04-13 12:36:17 +00:00
usedPorts.Add(new Port(servicePort, ""));
result.Add(new V1ServicePort
{
Name = GetNameForPort(recipe, port),
Protocol = "TCP",
Port = port.Number,
TargetPort = GetNameForPort(recipe, port),
NodePort = servicePort
});
}
servicePorts.Add(recipe, usedPorts.ToArray());
return result;
}
#endregion
#region Waiting
private void WaitUntilNamespaceCreated()
{
WaitUntil(() => IsTestNamespaceOnline());
}
private void WaitUntilNamespaceDeleted()
{
WaitUntil(() => !IsTestNamespaceOnline());
}
2023-05-03 12:18:37 +00:00
private void WaitUntilNamespaceDeleted(string name)
{
WaitUntil(() => !IsNamespaceOnline(name));
}
private void WaitUntilDeploymentOnline(string deploymentName)
{
WaitUntil(() =>
{
2023-05-04 06:25:48 +00:00
var deployment = client.Run(c => c.ReadNamespacedDeployment(deploymentName, K8sTestNamespace));
return deployment?.Status.AvailableReplicas != null && deployment.Status.AvailableReplicas > 0;
});
}
2023-04-13 09:07:36 +00:00
private void WaitUntilDeploymentOffline(string deploymentName)
{
WaitUntil(() =>
{
2023-05-04 06:25:48 +00:00
var deployments = client.Run(c => c.ListNamespacedDeployment(K8sTestNamespace));
2023-04-13 09:07:36 +00:00
var deployment = deployments.Items.SingleOrDefault(d => d.Metadata.Name == deploymentName);
return deployment == null || deployment.Status.AvailableReplicas == 0;
});
}
private void WaitUntilPodOffline(string podName)
{
WaitUntil(() =>
{
2023-05-04 06:25:48 +00:00
var pods = client.Run(c => c.ListNamespacedPod(K8sTestNamespace)).Items;
2023-04-13 09:07:36 +00:00
var pod = pods.SingleOrDefault(p => p.Metadata.Name == podName);
return pod == null;
});
}
private void WaitUntil(Func<bool> predicate)
{
2023-04-25 09:31:15 +00:00
var sw = Stopwatch.Begin(log, true);
try
{
Time.WaitUntil(predicate, cluster.K8sOperationTimeout(), cluster.WaitForK8sServiceDelay());
}
finally
{
sw.End("", 1);
}
}
#endregion
private (string, string) FetchNewPod()
{
2023-05-04 06:25:48 +00:00
var pods = client.Run(c => c.ListNamespacedPod(K8sTestNamespace)).Items;
var newPods = pods.Where(p => !knownPods.Contains(p.Name())).ToArray();
if (newPods.Length != 1) throw new InvalidOperationException("Expected only 1 pod to be created. Test infra failure.");
var newPod = newPods.Single();
var name = newPod.Name();
var ip = newPod.Status.PodIP;
2023-04-12 11:53:55 +00:00
if (string.IsNullOrEmpty(name)) throw new InvalidOperationException("Invalid pod name received. Test infra failure.");
if (string.IsNullOrEmpty(ip)) throw new InvalidOperationException("Invalid pod IP received. Test infra failure.");
2023-04-12 11:53:55 +00:00
knownPods.Add(name);
return (name, ip);
2023-04-12 11:53:55 +00:00
}
}
}