-
Notifications
You must be signed in to change notification settings - Fork 66
/
FunctionJsonConverter.cs
348 lines (312 loc) · 14.9 KB
/
FunctionJsonConverter.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Mono.Cecil;
using Newtonsoft.Json;
namespace MakeFunctionJson
{
internal class FunctionJsonConverter
{
private string _assemblyPath;
private string _outputPath;
private bool _functionsInDependencies;
private readonly HashSet<string> _excludedFunctionNames;
private readonly ILogger _logger;
private readonly IDictionary<string, MethodDefinition> _functionNamesSet;
private static readonly IEnumerable<string> _functionsArtifacts = new[]
{
"local.settings.json",
"host.json"
};
private static readonly IEnumerable<string> _triggersWithoutStorage = new[]
{
"httptrigger",
"kafkatrigger",
// Durable Functions triggers can also support non-Azure Storage backends
"orchestrationTrigger",
"activityTrigger",
"entityTrigger",
};
internal FunctionJsonConverter(ILogger logger, string assemblyPath, string outputPath, bool functionsInDependencies, IEnumerable<string> excludedFunctionNames = null)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (string.IsNullOrEmpty(assemblyPath))
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (string.IsNullOrEmpty(outputPath))
{
throw new ArgumentNullException(nameof(outputPath));
}
_logger = logger;
_assemblyPath = assemblyPath;
_outputPath = outputPath.Trim('"');
_functionsInDependencies = functionsInDependencies;
_excludedFunctionNames = new HashSet<string>(excludedFunctionNames ?? Enumerable.Empty<string>(), StringComparer.OrdinalIgnoreCase);
if (!Path.IsPathRooted(_outputPath))
{
_outputPath = Path.Combine(Directory.GetCurrentDirectory(), _outputPath);
}
_functionNamesSet = new Dictionary<string, MethodDefinition>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Run loads assembly in <see cref="_assemblyPath"/> then:
/// |> GetExportedTypes
/// |> GetMethods
/// |> Where method is SDK method
/// |> Convert that to function.json
/// |> Create folder \{functionName}\
/// |> Write \{functionName}\function.json
///
/// This means that every <see cref="MethodInfo"/> will be N binding objects on <see cref="FunctionJsonSchema"/>
/// Where N == total number of SDK attributes on the method parameters.
/// </summary>
internal bool TryRun()
{
try
{
this._functionNamesSet.Clear();
CleanOutputPath();
CopyFunctionArtifacts();
return TryGenerateFunctionJsons();
}
catch (Exception e)
{
_logger.LogErrorFromException(e);
return false;
}
}
private void CopyFunctionArtifacts()
{
var sourceFile = string.Empty;
var targetFile = string.Empty;
var assemblyDir = Path.GetDirectoryName(_assemblyPath);
foreach (var file in _functionsArtifacts)
{
sourceFile = Path.Combine(assemblyDir, file);
targetFile = Path.Combine(_outputPath, file);
if (File.Exists(sourceFile) && !sourceFile.Equals(targetFile, StringComparison.OrdinalIgnoreCase))
{
try
{
File.Copy(sourceFile, targetFile, overwrite: true);
}
catch (Exception e)
{
_logger.LogWarning($"Unable to copy '{sourceFile}' to '{targetFile}'");
_logger.LogWarningFromException(e);
}
}
}
}
public IEnumerable<(FunctionJsonSchema schema, FileInfo outputFile)?> GenerateFunctions(IEnumerable<TypeDefinition> types)
{
foreach (var type in types)
{
foreach (var method in type.Methods)
{
if (method.HasFunctionNameAttribute())
{
if (method.HasUnsuportedAttributes(out string error))
{
_logger.LogError(error);
yield return null;
}
else if (method.IsWebJobsSdkMethod())
{
var functionName = method.GetSdkFunctionName();
var artifactName = Path.Combine(functionName, "function.json");
var path = Path.Combine(_outputPath, artifactName);
var relativeAssemblyPath = PathUtility.MakeRelativePath(Path.Combine(_outputPath, "dummyFunctionName"), type.Module.FileName);
var functionJson = method.ToFunctionJson(relativeAssemblyPath);
if (CheckAppSettingsAndFunctionName(functionJson, method))
{
yield return (functionJson, new FileInfo(path));
}
else
{
yield return null;
}
}
else if (method.HasFunctionNameAttribute())
{
if (method.HasNoAutomaticTriggerAttribute() && method.HasTriggerAttribute())
{
_logger.LogWarning($"Method {method.DeclaringType.GetReflectionFullName()}.{method.Name} has both a 'NoAutomaticTrigger' attribute and a trigger attribute. Both can't be used together for an Azure function definition.");
}
else
{
_logger.LogWarning($"Method {method.DeclaringType.GetReflectionFullName()}.{method.Name} is missing a trigger attribute. Both a trigger attribute and FunctionName attribute are required for an Azure function definition.");
}
}
else if (method.HasValidWebJobSdkTriggerAttribute())
{
_logger.LogWarning($"Method {method.DeclaringType.GetReflectionFullName()}.{method.Name} is missing the 'FunctionName' attribute. Both a trigger attribute and 'FunctionName' are required for an Azure function definition.");
}
}
}
}
}
private bool TryGenerateFunctionJsons()
{
var loadContext = new AssemblyLoadContext(Path.GetFileName(_assemblyPath), isCollectible: true);
var assemblyRoot = Path.GetDirectoryName(_assemblyPath);
var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(assemblyRoot);
var readerParams = new ReaderParameters
{
AssemblyResolver = resolver
};
loadContext.Resolving += ResolveAssembly;
bool ret;
using (var scope = loadContext.EnterContextualReflection())
{
var module = ModuleDefinition.ReadModule(_assemblyPath, readerParams);
IEnumerable<TypeDefinition> exportedTypes = module.Types;
if (_functionsInDependencies)
{
foreach (var referencedAssembly in module.AssemblyReferences)
{
var tryPath = Path.Combine(assemblyRoot, $"{referencedAssembly.Name}.dll");
if (File.Exists(tryPath))
{
try
{
var loadedModule = ModuleDefinition.ReadModule(tryPath, readerParams);
exportedTypes = exportedTypes.Concat(loadedModule.Types);
}
catch (Exception ex)
{
_logger.LogWarning($"Could not evaluate '{referencedAssembly.Name}' for function types. Exception message: {ex.Message}");
}
}
}
}
var functions = GenerateFunctions(exportedTypes).ToList();
foreach (var function in functions.Where(f => f.HasValue && !f.Value.outputFile.Exists).Select(f => f.Value))
{
function.schema.Serialize(function.outputFile.FullName);
}
ret = functions.All(f => f.HasValue);
}
loadContext.Unload();
return ret;
Assembly ResolveAssembly(AssemblyLoadContext context, AssemblyName assemblyName)
{
Assembly result = null;
// First, check the assembly root dir. Assemblies copied with the app always wins.
var path = Path.Combine(assemblyRoot, assemblyName.Name + ".dll");
if (File.Exists(path))
{
result = context.LoadFromAssemblyPath(path);
if (result != null)
{
return result;
}
}
// Then, check if the assembly is already loaded into the default context.
// This is typically the case for framework assemblies like System.Private.Corelib.dll.
if (AssemblyLoadContext.Default.Assemblies.FirstOrDefault(a => a.GetName().Equals(assemblyName)) is Assembly existing)
{
return existing;
}
// Lastly, try the resolution logic used by cecil. This can produce assemblies with
// different versions, which may cause issues. But not doing this fails in more cases.
var resolved = resolver.Resolve(AssemblyNameReference.Parse(assemblyName.FullName));
path = resolved?.MainModule.FileName;
if (path != null)
{
result = context.LoadFromAssemblyPath(path);
}
return result;
}
}
private bool CheckAppSettingsAndFunctionName(FunctionJsonSchema functionJson, MethodDefinition method)
{
try
{
var functionName = method.GetSdkFunctionName();
if (this._functionNamesSet.ContainsKey(functionName))
{
var dupMethod = this._functionNamesSet[functionName];
_logger.LogError($"Function {method.DeclaringType.FullName}.{method.Name} and {dupMethod.DeclaringType.FullName}.{dupMethod.Name} have the same value for FunctionNameAttribute. Each function must have a unique name.");
return false;
}
else
{
this._functionNamesSet.Add(functionName, method);
}
const string settingsFileName = "local.settings.json";
var settingsFile = Path.Combine(_outputPath, settingsFileName);
if (!File.Exists(settingsFile))
{
return true; // no file to check.
}
var settings = JsonConvert.DeserializeObject<LocalSettingsJson>(File.ReadAllText(settingsFile));
var values = settings?.Values;
if (values != null)
{
// FirstOrDefault returns a KeyValuePair<string, string> which is a struct so it can't be null.
var azureWebJobsStorage = values.FirstOrDefault(pair => pair.Key.Equals("AzureWebJobsStorage", StringComparison.OrdinalIgnoreCase)).Value;
var allWithoutStorageTriggers = functionJson
.Bindings
.Where(b => b["type"] != null)
.Select(b => b["type"].ToString())
.Where(b => b.IndexOf("Trigger", StringComparison.OrdinalIgnoreCase) != -1)
.All(t => _triggersWithoutStorage.Any(tws => tws.Equals(t, StringComparison.OrdinalIgnoreCase)));
if (string.IsNullOrWhiteSpace(azureWebJobsStorage) && !allWithoutStorageTriggers)
{
_logger.LogWarning($"Function [{functionName}]: Missing value for AzureWebJobsStorage in {settingsFileName}. " +
$"This is required for all triggers other than {string.Join(", ", _triggersWithoutStorage)}.");
}
foreach (var binding in functionJson.Bindings)
{
foreach (var token in binding)
{
if (token.Key == "connection" || token.Key == "apiKey" || token.Key == "accountSid" || token.Key == "authToken")
{
var appSettingName = token.Value.ToString();
if (!values.Any(v => v.Key.Equals(appSettingName, StringComparison.OrdinalIgnoreCase)))
{
_logger.LogWarning($"Function [{functionName}]: cannot find value named '{appSettingName}' in {settingsFileName} that matches '{token.Key}' property set on '{binding["type"]?.ToString()}'");
}
}
}
}
}
}
catch (Exception e)
{
_logger.LogWarningFromException(e);
}
// We only return false on an error, not a warning.
return true;
}
private void CleanOutputPath()
{
Directory.GetDirectories(_outputPath)
.Select(d => Path.Combine(d, "function.json"))
.Where(File.Exists)
.Select(Path.GetDirectoryName)
.Where(d => !_excludedFunctionNames.Contains(new DirectoryInfo(d).Name))
.ToList()
.ForEach(directory =>
{
try
{
Directory.Delete(directory, recursive: true);
}
catch
{
_logger.LogWarning($"Unable to clean directory {directory}.");
}
});
}
}
}