-
Notifications
You must be signed in to change notification settings - Fork 117
/
ChartBase.cs
554 lines (484 loc) · 20.5 KB
/
ChartBase.cs
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
// Copyright 2016-2020, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// *** WARNING: this file was generated by pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.Json;
using Pulumi.Kubernetes.Yaml;
using Pulumi.Utilities;
namespace Pulumi.Kubernetes.Helm
{
public abstract class ChartBase : CollectionComponentResource
{
/// <summary>
/// Create an instance of the specified Helm chart.
/// </summary>
/// <param name="releaseName">Name of the Chart (e.g., nginx-ingress).</param>
/// <param name="args">Configuration options for the Chart.</param>
/// <param name="options">A bag of options that control this resource's behavior.</param>
protected ChartBase(string releaseName, Union<ChartArgs, LocalChartArgs> args, ComponentResourceOptions? options = null)
: base("kubernetes:helm.sh/v2:Chart", GetName(args, releaseName), options)
{
releaseName = GetName(args, releaseName);
var config = args.Unwrap();
var configDeps = Output.Create(OutputUtilities.GetDependenciesAsync(config));
OutputUtilities.GetIsKnownAsync(config).ContinueWith(isKnown =>
{
if (!isKnown.Result)
{
// Note that this can only happen during a preview.
Log.Info("[Can't preview] all chart values must be known ahead of time to generate an accurate preview.", this);
}
});
var resources = Output.Tuple(config, configDeps).Apply(values =>
{
var chartArgs = values.Item1;
var dependencies = values.Item2;
// Create temporary directories and files to hold chart data and override values.
var overrides = Path.GetTempFileName();
var chartDirectoryName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var chartDirectory = Directory.CreateDirectory(chartDirectoryName);
try
{
string chart;
string defaultValues;
BaseChartArgsUnwrap cfgBase;
if (chartArgs.IsT0)
{
var cfg = chartArgs.AsT0;
// Fetch chart.
if (cfg.Repo != null && cfg.Repo.Contains("http"))
{
throw new Exception(
$"`{nameof(cfg.Repo)}` specifies the name of the Helm chart repo. Use `{nameof(ChartArgs)}.{nameof(cfg.Repo)}` to specify a URL.");
}
var chartToFetch = !string.IsNullOrEmpty(cfg.Repo) ? $"{cfg.Repo}/{cfg.Chart}" : cfg.Chart;
var fetchOptions = cfg.FetchOptions ?? new ChartFetchArgsUnwrap();
fetchOptions.Destination = chartDirectoryName;
fetchOptions.Version = cfg.Version;
Fetch(chartToFetch, fetchOptions);
// Sort the directories into alphabetical order, and choose the first
var fetchedChart = chartDirectory.GetDirectories().OrderBy(x => x.Name).ToArray()[0];
var fetchedChartName = fetchedChart.Name;
chart = fetchedChart.FullName;
defaultValues = Path.Join(chartDirectoryName, fetchedChartName, "values.yaml");
cfgBase = cfg;
}
else
{
var cfg = chartArgs.AsT1;
chart = cfg.Path;
defaultValues = Path.Join(chart, "values.yaml");
cfgBase = cfg;
}
// Write overrides file.
var data = JsonSerializer.Serialize(cfgBase.Values);
File.WriteAllText(overrides, data);
// Does not require Tiller. From the `helm template` documentation:
//
// > Render chart templates locally and display the output.
// >
// > This does not require Tiller. However, any values that would normally be
// > looked up or retrieved in-cluster will be faked locally. Additionally, none
// > of the server-side testing of chart validity (e.g. whether an API is supported)
// > is done.
var flags = new List<string>(new[]
{
"template", chart,
"--name-template", releaseName,
"--values", defaultValues,
"--values", overrides
});
if (cfgBase.ApiVersions.Length > 0)
{
flags.Add("--api-versions");
flags.Add(string.Join(",", cfgBase.ApiVersions));
}
if (!string.IsNullOrEmpty(cfgBase.Namespace))
{
flags.Add("--namespace");
flags.Add(cfgBase.Namespace);
}
if (IsHelmV3())
{
flags.Add("--include-crds");
}
var yaml = ExecuteCommand("helm", flags.ToArray(), new Dictionary<string, string>());
return ParseTemplate(
yaml, cfgBase.Transformations, cfgBase.ResourcePrefix, dependencies, cfgBase.Namespace);
}
catch (Exception e)
{
// Shed stack trace, only emit the error.
throw new ResourceException(e.Message, this);
}
finally
{
chartDirectory.Delete(true);
}
});
RegisterResources(resources);
}
private static string GetName(Union<ChartArgs, LocalChartArgs> config, string releaseName)
{
var prefix = config.Match(v => v.ResourcePrefix, v => v.ResourcePrefix);
return string.IsNullOrEmpty(prefix) ? releaseName : $"{prefix}-{releaseName}";
}
private static bool IsHelmV3()
{
var env = new Dictionary<string, string>();
string[] flags = {"version", "--short"};
// Helm v2 returns version like this:
// Client: v2.16.7+g5f2584f
// Helm v3 returns a version like this:
// v3.1.2+gd878d4d
// --include-crds is available in helm v3.1+ so check for a regex matching that version
var version = ExecuteCommand("helm", flags, env);
Regex r = new Regex(@"^v3\.[1-9]");
return r.IsMatch(version);
}
private void Fetch(string chart, ChartFetchArgsUnwrap opts)
{
var flags = new List<string>(new[] { "fetch", chart });
// Untar by default.
if (opts.Untar != false)
{
flags.Add("--untar");
}
var env = new Dictionary<string, string>();
// Helm v3 removed the `--home` flag, so we must use an env var instead.
if (!string.IsNullOrEmpty(opts.Home))
{
env["HELM_HOME"] = opts.Home;
}
if (!string.IsNullOrEmpty(opts.Version))
{
flags.Add("--version");
flags.Add(opts.Version);
}
if (!string.IsNullOrEmpty(opts.CAFile))
{
flags.Add("--ca-file");
flags.Add(opts.CAFile);
}
if (!string.IsNullOrEmpty(opts.CertFile))
{
flags.Add("--cert-file");
flags.Add(opts.CertFile);
}
if (!string.IsNullOrEmpty(opts.KeyFile))
{
flags.Add("--key-file");
flags.Add(opts.KeyFile);
}
if (!string.IsNullOrEmpty(opts.Destination))
{
flags.Add("--destination");
flags.Add(opts.Destination);
}
if (!string.IsNullOrEmpty(opts.Keyring))
{
flags.Add("--keyring");
flags.Add(opts.Keyring);
}
if (!string.IsNullOrEmpty(opts.Password))
{
flags.Add("--password");
flags.Add(opts.Password);
}
if (!string.IsNullOrEmpty(opts.Repo))
{
flags.Add("--repo");
flags.Add(opts.Repo);
}
if (!string.IsNullOrEmpty(opts.UntarDir))
{
flags.Add("--untardir");
flags.Add(opts.UntarDir);
}
if (!string.IsNullOrEmpty(opts.Username))
{
flags.Add("--username");
flags.Add(opts.Username);
}
if (opts.Devel == true)
{
flags.Add("--devel");
}
if (opts.Prov == true)
{
flags.Add("--prov");
}
if (opts.Verify == true)
{
flags.Add("--verify");
}
ExecuteCommand("helm", flags.ToArray(), env);
}
private Output<ImmutableDictionary<string, KubernetesResource>> ParseTemplate(string text,
List<TransformationAction> transformations, string? resourcePrefix, ImmutableHashSet<Resource> dependsOn,
string? defaultNamespace)
{
return Invokes
.YamlDecode(new YamlDecodeArgs { Text = text, DefaultNamespace = defaultNamespace })
.Apply(objs =>
{
var args = new ConfigGroupArgs
{
ResourcePrefix = resourcePrefix,
Objs = objs,
Transformations = transformations
};
var opts = new ComponentResourceOptions { Parent = this, DependsOn = dependsOn.ToArray() };
return Parser.Parse(args, opts);
});
}
private static string ExecuteCommand(string command, string[] flags, IDictionary<string, string> env)
{
using var process = new Process
{
StartInfo =
{
FileName = command,
Arguments = EscapeArguments(flags),
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
foreach (KeyValuePair<string, string> value in env)
{
process.StartInfo.EnvironmentVariables[value.Key] = value.Value;
}
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (process.ExitCode > 0)
{
string error = process.StandardError.ReadToEnd();
throw new Exception(error);
}
return output;
}
/// <summary>
/// Convert an argument array to an argument string for using with Process.StartInfo.Arguments.
/// </summary>
private static string EscapeArguments(params string[] args)
=> string.Join(" ", args.Select(EscapeArguments));
/// <summary>
/// Convert an argument array to an argument string for using with Process.StartInfo.Arguments.
/// </summary>
private static string EscapeArguments(string argument)
{
var escapedArgument = new StringBuilder();
var backslashCount = 0;
var needsQuotes = false;
foreach (var character in argument)
{
switch (character)
{
case '\\':
// Backslashes are simply passed through, except when they need
// to be escaped when followed by a \", e.g. the argument string
// \", which would be encoded to \\\"
backslashCount++;
escapedArgument.Append('\\');
break;
case '\"':
// Escape any preceding backslashes
escapedArgument.Append(new string('\\', backslashCount));
// Append an escaped double quote.
escapedArgument.Append("\\\"");
// Reset the backslash counter.
backslashCount = 0;
break;
case ' ':
case '\t':
// White spaces are escaped by surrounding the entire string with
// double quotes, which should be done at the end to prevent
// multiple wrappings.
needsQuotes = true;
// Append the whitespace
escapedArgument.Append(character);
// Reset the backslash counter.
backslashCount = 0;
break;
default:
// Reset the backslash counter.
backslashCount = 0;
// Append the current character
escapedArgument.Append(character);
break;
}
}
// No need to wrap in quotes
if (!needsQuotes)
{
return escapedArgument.ToString();
}
// Prepend the "
escapedArgument.Insert(0, '"');
// Escape any preceding backslashes before appending the "
escapedArgument.Append(new string('\\', backslashCount));
// Append the final "
escapedArgument.Append('\"');
return escapedArgument.ToString();
}
}
public class BaseChartArgs : ResourceArgs
{
private InputList<string>? _apiVersions;
/// <summary>
/// The optional kubernetes api versions used for Capabilities.APIVersions.
/// </summary>
public InputList<string> ApiVersions
{
get => _apiVersions ??= new InputList<string>();
set => _apiVersions = value;
}
/// <summary>
/// The optional namespace to install chart resources into.
/// </summary>
public Input<string>? Namespace { get; set; }
private InputMap<object>? _values;
/// <summary>
/// Overrides for chart values.
/// </summary>
public InputMap<object> Values
{
get => _values ??= new InputMap<object>();
set => _values = value;
}
private List<TransformationAction>? _transformations;
/// <summary>
/// Optional array of transformations to apply to resources that will be created by this chart prior to
/// creation. Allows customization of the chart behaviour without directly modifying the chart itself.
/// </summary>
public List<TransformationAction> Transformations
{
get => _transformations ??= new List<TransformationAction>();
set => _transformations = value;
}
/// <summary>
/// An optional prefix for the auto-generated resource names.
/// Example: A resource created with resourcePrefix="foo" would produce a resource named "foo-resourceName".
/// </summary>
public string? ResourcePrefix { get; set; }
}
public class ChartArgs : BaseChartArgs
{
/// <summary>
/// The repository name of the chart to deploy.
/// Example: "stable"
/// </summary>
public Input<string>? Repo { get; set; }
/// <summary>
/// The name of the chart to deploy. If <see cref="Repo" /> is provided, this chart
/// name will be prefixed by the repo name.
/// Example: Repo: "stable", Chart: "nginx-ingress" -> "stable/nginx-ingress"
/// Example: Chart: "stable/nginx-ingress" -> "stable/nginx-ingress"
/// </summary>
public Input<string> Chart { get; set; } = null!;
/// <summary>
/// The version of the chart to deploy. If not provided, the latest version will be deployed.
/// </summary>
public Input<string>? Version { get; set; }
/// <summary>
/// Additional options to customize the fetching of the Helm chart.
/// </summary>
public Input<ChartFetchArgs>? FetchOptions { get; set; }
}
public class LocalChartArgs : BaseChartArgs
{
/// <summary>
/// The path to the chart directory which contains the `Chart.yaml` file.
/// </summary>
public string Path { get; set; } = null!;
}
/// <summary>
/// Additional options to customize the fetching of the Helm chart.
/// </summary>
public class ChartFetchArgs
{
/// <summary>
/// Specific version of a chart. Without this, the latest version is fetched.
/// </summary>
public Input<string>? Version { get; set; }
/// <summary>
/// Verify certificates of HTTPS-enabled servers using this CA bundle.
/// </summary>
public Input<string>? CAFile { get; set; }
/// <summary>
/// Identify HTTPS client using this SSL certificate file.
/// </summary>
public Input<string>? CertFile { get; set; }
/// <summary>
/// Identify HTTPS client using this SSL key file.
/// </summary>
public Input<string>? KeyFile { get; set; }
/// <summary>
/// Location to write the chart. If this and tardir are specified, tardir is appended to this
/// (default ".").
/// </summary>
public Input<string>? Destination { get; set; }
/// <summary>
/// Keyring containing public keys (default "/Users/alex/.gnupg/pubring.gpg").
/// </summary>
public Input<string>? Keyring { get; set; }
/// <summary>
/// Chart repository password.
/// </summary>
public Input<string>? Password { get; set; }
/// <summary>
/// Chart repository url where to locate the requested chart.
/// </summary>
public Input<string>? Repo { get; set; }
/// <summary>
/// If untar is specified, this flag specifies the name of the directory into which the chart is
/// expanded (default ".").
/// </summary>
public Input<string>? UntarDir { get; set; }
/// <summary>
/// Chart repository username.
/// </summary>
public Input<string>? Username { get; set; }
/// <summary>
/// Location of your Helm config. Overrides $HELM_HOME (default "/Users/alex/.helm").
/// </summary>
public Input<string>? Home { get; set; }
/// <summary>
/// Use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is
/// ignored.
/// </summary>
public Input<bool>? Devel { get; set; }
/// <summary>
/// Fetch the provenance file, but don't perform verification.
/// </summary>
public Input<bool>? Prov { get; set; }
/// <summary>
/// If set to false, will leave the chart as a tarball after downloading.
/// </summary>
public Input<bool>? Untar { get; set; }
/// <summary>
/// Verify the package against its signature.
/// </summary>
public Input<bool>? Verify { get; set; }
}
}