This repository was archived by the owner on Dec 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3-k8s-restart-all-pods.linq
More file actions
280 lines (239 loc) · 9.9 KB
/
Copy path3-k8s-restart-all-pods.linq
File metadata and controls
280 lines (239 loc) · 9.9 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
110
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
144
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
<Query Kind="Program">
<NuGetReference>KubernetesClient</NuGetReference>
<Namespace>System.Threading.Tasks</Namespace>
<Namespace>k8s</Namespace>
<Namespace>k8s.Models</Namespace>
</Query>
#nullable enable
#load "1-docker-build-images.linq"
#load "2-k8s-generate-manifests.linq"
const ScriptAction programAction = ScriptAction.RestartAll;
enum ScriptAction
{
None,
StopAll,
RestartAll,
OpenTofuDestroyAll,
OpenTofuInit
}
sealed record OpenTofuProject(string name);
static class DeployScriptConstants
{
internal const bool DisableManifestGeneration = false;
internal static readonly string OpentofuBinary = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "OpenTofu", "tofu.exe");
internal static readonly OpenTofuProject DevDepsProject = new("dev-dependencies");
internal static readonly OpenTofuProject DemoProject = new(ManifestsScript.Options.GlobalAppName);
internal static readonly string DockerfileOriginalDirectoryPath = DockerScript.Options.AppSourcePath;
internal static readonly string OutputDirectoryPath = DockerScript.Options.OutputDirectoryPath;
internal static readonly string DemoK8sNamespace = ManifestsScript.Options.GlobalAppName;
}
sealed record OpenTofuInfo(string BinaryPath, string WorkspacePath, string BackendConfigPath, string SecretVariablesPath)
{
public static OpenTofuInfo Create(string binaryPath, OpenTofuProject project)
{
var workspacePath = Path.Combine(Path.GetDirectoryName(DeployScriptConstants.OutputDirectoryPath)!, "3-opentofu", project.name);
var backendFolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "OpenTofu", project.name);
var backendValuesConfigPath = Path.Combine(backendFolderPath, "state.config");
var secretVariablesPath = Path.Combine(backendFolderPath, "terraform.tfvars");
if (!File.Exists(backendValuesConfigPath))
throw new System.IO.FileNotFoundException($"Path not found: {backendValuesConfigPath}. This file must contain state configuration.");
if (!File.Exists(secretVariablesPath))
throw new System.IO.FileNotFoundException($"Path not found: {secretVariablesPath}. This file must contain some secrets we do not store near other opentofu files.");
return new OpenTofuInfo(binaryPath, workspacePath, backendValuesConfigPath, secretVariablesPath);
}
}
Task Main()
{
return new DeployProgram().Run(this.QueryCancelToken);
}
internal class DeployProgram
{
internal async Task Run(CancellationToken cancellationToken)
{
switch (programAction)
{
case ScriptAction.RestartAll:
if (!DeployScriptConstants.DisableManifestGeneration)
await ManifestsScript.Run(cancellationToken);
await OpenTofuApply(DeployScriptConstants.DevDepsProject, cancellationToken);
await OpenTofuApply(DeployScriptConstants.DemoProject, cancellationToken);
await RestartAllPods(cancellationToken);
break;
case ScriptAction.StopAll:
if (!DeployScriptConstants.DisableManifestGeneration)
await ManifestsScript.Run(cancellationToken);
await StopAllPods(cancellationToken);
break;
case ScriptAction.OpenTofuDestroyAll:
await OpenTofuDestroy(DeployScriptConstants.DemoProject, cancellationToken);
break;
case ScriptAction.OpenTofuInit:
await OpenTofuInit(DeployScriptConstants.DevDepsProject, cancellationToken);
await OpenTofuInit(DeployScriptConstants.DemoProject, cancellationToken);
break;
default:
break;
}
}
async Task RunCommand(ProcessStartInfo psi, CancellationToken cancellationToken)
{
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Console.WriteLine(psi.WorkingDirectory);
Console.WriteLine($"{psi.FileName} {psi.Arguments}");
using var p = new Process();
p.StartInfo = psi;
p.OutputDataReceived += ProcessOutputHandler;
p.ErrorDataReceived += ProcessOutputHandler;
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
await p.WaitForExitAsync(cancellationToken);
p.OutputDataReceived -= ProcessOutputHandler;
p.ErrorDataReceived -= ProcessOutputHandler;
if (p.ExitCode != 0)
{
throw new ArgumentException($"{psi.FileName} {psi.Arguments}: exit code = {p.ExitCode}");
}
}
async Task OpenTofuApply(OpenTofuProject project, CancellationToken cancellationToken)
{
var paths = OpenTofuInfo.Create(DeployScriptConstants.OpentofuBinary, project);
var psi = new ProcessStartInfo(paths.BinaryPath, $"apply -auto-approve -var-file \"{paths.SecretVariablesPath}\"");
psi.WorkingDirectory = paths.WorkspacePath;
await RunCommand(psi, cancellationToken);
}
async Task OpenTofuInit(OpenTofuProject project, CancellationToken cancellationToken)
{
var paths = OpenTofuInfo.Create(DeployScriptConstants.OpentofuBinary, project);
var psi = new ProcessStartInfo(paths.BinaryPath, $"init -backend-config \"{paths.BackendConfigPath}\"");
psi.WorkingDirectory = paths.WorkspacePath;
await RunCommand(psi, cancellationToken);
}
async Task OpenTofuDestroy(OpenTofuProject project, CancellationToken cancellationToken)
{
var paths = OpenTofuInfo.Create(DeployScriptConstants.OpentofuBinary, project);
var psi = new ProcessStartInfo(paths.BinaryPath, $"destroy -auto-approve -var-file \"{paths.SecretVariablesPath}\"");
psi.WorkingDirectory = paths.WorkspacePath;
await RunCommand(psi, cancellationToken);
}
async Task RestartAllPods(CancellationToken cancellationToken)
{
string[] statefullSetNames = await GetAllStatefullSetNames(cancellationToken);
using var client = CreateK8sClient();
bool needToWait = await ScaleTo(0, client, statefullSetNames, cancellationToken);
if (needToWait)
{
await WaitScaling(0, client, statefullSetNames, cancellationToken);
}
needToWait = await ScaleTo(1, client, statefullSetNames, cancellationToken);
if (needToWait)
{
await WaitScaling(1, client, statefullSetNames, cancellationToken);
}
}
async Task StopAllPods(CancellationToken cancellationToken)
{
string[] statefullSetNames = await GetAllStatefullSetNames(cancellationToken);
using var client = CreateK8sClient();
bool needToWait = await ScaleTo(0, client, statefullSetNames, cancellationToken);
}
async Task WaitScaling(int targetReplicaCount, Kubernetes client, string[] statefullSetNames, CancellationToken cancellationToken)
{
foreach (string name in statefullSetNames)
{
try
{
var scaleResult = await client.ReadNamespacedStatefulSetScaleAsync(name, DeployScriptConstants.DemoK8sNamespace, cancellationToken: cancellationToken);
while (scaleResult.Status.Replicas != targetReplicaCount)
{
Console.WriteLine($"Waiting for replica count {targetReplicaCount}...");
await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken);
scaleResult = await client.ReadNamespacedStatefulSetScaleAsync(name, DeployScriptConstants.DemoK8sNamespace, cancellationToken: cancellationToken);
}
var resourceStatus = await client.ReadNamespacedStatefulSetStatusAsync(name, DeployScriptConstants.DemoK8sNamespace, cancellationToken: cancellationToken);
while (resourceStatus.Status.ReadyReplicas != resourceStatus.Status.CurrentReplicas)
{
Console.WriteLine($"Waiting for ready state...");
await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken);
resourceStatus = await client.ReadNamespacedStatefulSetStatusAsync(name, DeployScriptConstants.DemoK8sNamespace, cancellationToken: cancellationToken);
}
}
catch (Exception ex)
{
throw new Exception($"Failed to status of probe {name}.", ex);
}
}
}
async Task<bool> ScaleTo(int newReplicaCount, Kubernetes client, string[] statefullSetNames, CancellationToken cancellationToken)
{
string pathString = @"{ ""spec"": { ""replicas"": " + newReplicaCount.ToString() + @" } }";
V1Patch patch = new(pathString, V1Patch.PatchType.MergePatch);
bool needToWait = false;
foreach (string name in statefullSetNames)
{
try
{
var result = await client.PatchNamespacedStatefulSetScaleAsync(patch, name, DeployScriptConstants.DemoK8sNamespace, cancellationToken: cancellationToken);
needToWait |= result.Status.Replicas != newReplicaCount;
Console.WriteLine($"{name}: scaling to {newReplicaCount} (from current {result.Status.Replicas})...");
}
catch (Exception ex)
{
throw new Exception($"Failed to patch {name}.", ex);
}
}
return needToWait;
}
async Task<string[]> GetAllStatefullSetNames(CancellationToken cancellationToken)
{
var result = new List<string>();
var yamlFiles = Directory.GetFiles(DeployScriptConstants.OutputDirectoryPath, "*.yaml", SearchOption.AllDirectories);
foreach (var item in yamlFiles)
{
var name = await GetStatefullSetNameIfAny(item, cancellationToken);
if (name != null)
result.Add(name);
}
return result.ToArray();
}
private async Task<string?> GetStatefullSetNameIfAny(string yamlManifestPath, CancellationToken cancellationToken)
{
var yamlLines = await File.ReadAllLinesAsync(yamlManifestPath, cancellationToken);
if (!yamlLines.Contains("kind: StatefulSet"))
return null;
var indexMetadata = Array.FindIndex(yamlLines, t => t == "metadata:");
if (indexMetadata != -1 && yamlLines.Length > indexMetadata + 1)
{
var nameLine = yamlLines[indexMetadata + 1];
var indexName = nameLine.IndexOf(" name: ");
if (indexName != -1)
{
string statefullSetName = nameLine.Substring(indexName + " name: ".Length).Trim();
return statefullSetName;
}
}
return null;
}
static Kubernetes CreateK8sClient()
{
KubernetesClientConfiguration config;
var kubeconfig = Environment.GetEnvironmentVariable("KUBECONFIG");
if (kubeconfig != null)
{
config = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeconfig);
}
else
{
config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
}
var client = new Kubernetes(config);
return client;
}
static void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
Console.WriteLine(outLine.Data);
}
}