-
Notifications
You must be signed in to change notification settings - Fork 84
/
LambdaDotNetCLIWrapper.cs
426 lines (359 loc) · 16.4 KB
/
LambdaDotNetCLIWrapper.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Amazon.Common.DotNetCli.Tools;
namespace Amazon.Lambda.Tools
{
/// <summary>
/// Wrapper around the dotnet cli used to execute the publish command.
/// </summary>
public class LambdaDotNetCLIWrapper
{
string _workingDirectory;
IToolLogger _logger;
public LambdaDotNetCLIWrapper(IToolLogger logger, string workingDirectory)
{
this._logger = logger;
this._workingDirectory = workingDirectory;
}
/// <summary>
/// Execute the dotnet store command on the provided package manifest
/// </summary>
/// <param name="defaults"></param>
/// <param name="projectLocation"></param>
/// <param name="outputLocation"></param>
/// <param name="targetFramework"></param>
/// <param name="packageManifest"></param>
/// <param name="enableOptimization"></param>
/// <returns></returns>
public int Store(LambdaToolsDefaults defaults, string projectLocation, string outputLocation, string targetFramework, string packageManifest, bool enableOptimization)
{
if (outputLocation == null)
throw new ArgumentNullException(nameof(outputLocation));
if (Directory.Exists(outputLocation))
{
try
{
Directory.Delete(outputLocation, true);
_logger?.WriteLine("Deleted previous publish folder");
}
catch (Exception e)
{
_logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}");
}
}
var dotnetCLI = FindExecutableInPath("dotnet.exe");
if (dotnetCLI == null)
dotnetCLI = FindExecutableInPath("dotnet");
if (string.IsNullOrEmpty(dotnetCLI))
throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH.");
var fullProjectLocation = this._workingDirectory;
if (!string.IsNullOrEmpty(projectLocation))
{
fullProjectLocation = Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation);
}
var fullPackageManifest = Path.Combine(fullProjectLocation, packageManifest);
_logger?.WriteLine($"... invoking 'dotnet store' for manifest {fullPackageManifest} into output directory {outputLocation}");
StringBuilder arguments = new StringBuilder("store");
if (!string.IsNullOrEmpty(outputLocation))
{
arguments.Append($" --output \"{outputLocation}\"");
}
if (!string.IsNullOrEmpty(targetFramework))
{
arguments.Append($" --framework \"{targetFramework}\"");
}
arguments.Append($" --manifest \"{fullPackageManifest}\"");
arguments.Append($" --runtime {LambdaConstants.RUNTIME_HIERARCHY_STARTING_POINT}");
if(!enableOptimization)
{
arguments.Append(" --skip-optimization");
}
var psi = new ProcessStartInfo
{
FileName = dotnetCLI,
Arguments = arguments.ToString(),
WorkingDirectory = this._workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
var handler = (DataReceivedEventHandler)((o, e) =>
{
if (string.IsNullOrEmpty(e.Data))
return;
// Skip outputting this warning message as it adds a lot of noise to the output and is not actionable.
// Full warning message being skipped: message NETSDK1062:
// Unable to use package assets cache due to I/O error. This can occur when the same project is built
// more than once in parallel. Performance may be degraded, but the build result will not be impacted.
if (e.Data.Contains("message NETSDK1062"))
return;
_logger?.WriteLine("... store: " + e.Data);
});
int exitCode;
using (var proc = new Process())
{
proc.StartInfo = psi;
proc.Start();
proc.ErrorDataReceived += handler;
proc.OutputDataReceived += handler;
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.EnableRaisingEvents = true;
proc.WaitForExit();
exitCode = proc.ExitCode;
}
return exitCode;
}
/// <summary>
/// Executes the dotnet publish command for the provided project
/// </summary>
/// <param name="defaults"></param>
/// <param name="projectLocation"></param>
/// <param name="outputLocation"></param>
/// <param name="targetFramework"></param>
/// <param name="configuration"></param>
/// <param name="msbuildParameters"></param>
/// <param name="deploymentTargetPackageStoreManifestContent"></param>
public int Publish(LambdaToolsDefaults defaults, string projectLocation, string outputLocation, string targetFramework, string configuration, string msbuildParameters, IList<string> publishManifests)
{
if(outputLocation == null)
throw new ArgumentNullException(nameof(outputLocation));
if (Directory.Exists(outputLocation))
{
try
{
Directory.Delete(outputLocation, true);
_logger?.WriteLine("Deleted previous publish folder");
}
catch (Exception e)
{
_logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}");
}
}
_logger?.WriteLine($"... invoking 'dotnet publish', working folder '{outputLocation}'");
var dotnetCLI = FindExecutableInPath("dotnet.exe");
if (dotnetCLI == null)
dotnetCLI = FindExecutableInPath("dotnet");
if (string.IsNullOrEmpty(dotnetCLI))
throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH.");
var fullProjectLocation = this._workingDirectory;
if (!string.IsNullOrEmpty(projectLocation))
{
fullProjectLocation = Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation);
}
StringBuilder arguments = new StringBuilder("publish");
if (!string.IsNullOrEmpty(projectLocation))
{
arguments.Append($" \"{fullProjectLocation}\"");
}
if (!string.IsNullOrEmpty(outputLocation))
{
arguments.Append($" --output \"{outputLocation}\"");
}
if (!string.IsNullOrEmpty(configuration))
{
arguments.Append($" --configuration \"{configuration}\"");
}
if (!string.IsNullOrEmpty(targetFramework))
{
arguments.Append($" --framework \"{targetFramework}\"");
}
if (!string.IsNullOrEmpty(msbuildParameters))
{
arguments.Append($" {msbuildParameters}");
}
if (!string.Equals("netcoreapp1.0", targetFramework, StringComparison.OrdinalIgnoreCase))
{
arguments.Append(" /p:GenerateRuntimeConfigurationFiles=true");
// If you set the runtime to RUNTIME_HIERARCHY_STARTING_POINT it will trim out the Windows and Mac OS specific dependencies but Razor view precompilation
// will not run. So only do this packaging optimization if there are no Razor views.
if (Directory.GetFiles(fullProjectLocation, "*.cshtml", SearchOption.AllDirectories).Length == 0)
{
arguments.Append($" -r {LambdaConstants.RUNTIME_HIERARCHY_STARTING_POINT}");
if (msbuildParameters == null ||
msbuildParameters.IndexOf("--self-contained", StringComparison.InvariantCultureIgnoreCase) == -1)
{
arguments.Append(" --self-contained false ");
}
if (string.IsNullOrEmpty(msbuildParameters) ||
!msbuildParameters.Contains("PreserveCompilationContext"))
{
_logger?.WriteLine("... Disabling compilation context to reduce package size. If compilation context is needed pass in the \"/p:PreserveCompilationContext=false\" switch.");
arguments.Append(" /p:PreserveCompilationContext=false");
}
}
// If we have a manifest of packages already deploy in target deployment environment then write it to disk and add the
// command line switch
if(publishManifests != null && publishManifests.Count > 0)
{
foreach(var manifest in publishManifests)
{
arguments.Append($" --manifest \"{manifest}\"");
}
}
}
var psi = new ProcessStartInfo
{
FileName = dotnetCLI,
Arguments = arguments.ToString(),
WorkingDirectory = this._workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
var handler = (DataReceivedEventHandler)((o, e) =>
{
if (string.IsNullOrEmpty(e.Data))
return;
_logger?.WriteLine("... publish: " + e.Data);
});
int exitCode;
using (var proc = new Process())
{
proc.StartInfo = psi;
proc.Start();
proc.ErrorDataReceived += handler;
proc.OutputDataReceived += handler;
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.EnableRaisingEvents = true;
proc.WaitForExit();
exitCode = proc.ExitCode;
}
if (exitCode == 0)
{
ProcessAdditionalFiles(defaults, outputLocation);
var chmodPath = FindExecutableInPath("chmod");
if (!string.IsNullOrEmpty(chmodPath) && File.Exists(chmodPath))
{
// as we are not invoking through a shell, which would handle
// wildcard expansion for us, we need to invoke per-file
var files = Directory.GetFiles(outputLocation, "*", SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
var filename = Path.GetFileName(file);
var psiChmod = new ProcessStartInfo
{
FileName = chmodPath,
Arguments = "+rx \"" + filename + "\"",
WorkingDirectory = outputLocation,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var proc = new Process())
{
proc.StartInfo = psiChmod;
proc.Start();
proc.ErrorDataReceived += handler;
proc.OutputDataReceived += handler;
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.EnableRaisingEvents = true;
proc.WaitForExit();
if (proc.ExitCode == 0)
{
this._logger?.WriteLine($"Changed permissions on published file (chmod +rx {filename}).");
}
}
}
}
}
return exitCode;
}
private void ProcessAdditionalFiles(LambdaToolsDefaults defaults, string publishLocation)
{
var listOfDependencies = new List<string>();
var extraDependences = defaults["additional-files"] as string[];
if (extraDependences != null)
{
foreach (var item in extraDependences)
listOfDependencies.Add(item);
}
foreach (var relativePath in listOfDependencies)
{
var fileName = Path.GetFileName(relativePath);
string source;
if (Path.IsPathRooted(relativePath))
source = relativePath;
else
source = Path.Combine(publishLocation, relativePath);
var target = Path.Combine(publishLocation, fileName);
if (File.Exists(source) && !File.Exists(target))
{
File.Copy(source, target);
_logger?.WriteLine($"... publish: Adding additional file {relativePath}");
}
}
}
/// <summary>
/// A collection of known paths for common utilities that are usually not found in the path
/// </summary>
static readonly IDictionary<string, string> KNOWN_LOCATIONS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{"dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe" },
{"chmod", @"/bin/chmod" },
{"zip", @"/usr/bin/zip" }
};
/// <summary>
/// Search the path environment variable for the command given.
/// </summary>
/// <param name="command">The command to search for in the path</param>
/// <returns>The full path to the command if found otherwise it will return null</returns>
public static string FindExecutableInPath(string command)
{
if (File.Exists(command))
return Path.GetFullPath(command);
#if NETCORE
if (string.Equals(command, "dotnet.exe"))
{
if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
command = "dotnet";
}
var mainModule = Process.GetCurrentProcess().MainModule;
if (!string.IsNullOrEmpty(mainModule?.FileName)
&& Path.GetFileName(mainModule.FileName).Equals(command, StringComparison.OrdinalIgnoreCase))
{
return mainModule.FileName;
}
}
#endif
Func<string, string> quoteRemover = x =>
{
if (x.StartsWith("\""))
x = x.Substring(1);
if (x.EndsWith("\""))
x = x.Substring(0, x.Length - 1);
return x;
};
var envPath = Environment.GetEnvironmentVariable("PATH");
if (envPath != null)
{
foreach (var path in envPath.Split(Path.PathSeparator))
{
try
{
var fullPath = Path.Combine(quoteRemover(path), command);
if (File.Exists(fullPath))
return fullPath;
}
catch (Exception)
{
// Catch exceptions and continue if there are invalid characters in the user's path.
}
}
}
if (KNOWN_LOCATIONS.ContainsKey(command) && File.Exists(KNOWN_LOCATIONS[command]))
return KNOWN_LOCATIONS[command];
return null;
}
}
}