-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ProjectCacheService.cs
239 lines (203 loc) · 8.86 KB
/
ProjectCacheService.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Execution;
using Microsoft.Build.FileSystem;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
namespace Microsoft.Build.Experimental.ProjectCache
{
internal class ProjectCacheService
{
private readonly BuildManager _buildManager;
private readonly PluginLoggerBase _logger;
private readonly ProjectCacheDescriptor _projectCacheDescriptor;
private readonly CancellationToken _cancellationToken;
private readonly ProjectCachePluginBase _projectCachePlugin;
private ProjectCacheService(
ProjectCachePluginBase projectCachePlugin,
BuildManager buildManager,
PluginLoggerBase logger,
ProjectCacheDescriptor projectCacheDescriptor,
CancellationToken cancellationToken)
{
_projectCachePlugin = projectCachePlugin;
_buildManager = buildManager;
_logger = logger;
_projectCacheDescriptor = projectCacheDescriptor;
_cancellationToken = cancellationToken;
}
public static async Task<ProjectCacheService> FromDescriptorAsync(
ProjectCacheDescriptor pluginDescriptor,
BuildManager buildManager,
ILoggingService loggingService,
CancellationToken cancellationToken)
{
var plugin = await Task.Run(() => GetPluginInstance(pluginDescriptor), cancellationToken)
.ConfigureAwait(false);
// TODO: Detect and use the highest verbosity from all the user defined loggers. That's tricky because right now we can't discern between user set loggers and msbuild's internally added loggers.
var logger = new LoggingServiceToPluginLoggerAdapter(LoggerVerbosity.Normal, loggingService);
await plugin.BeginBuildAsync(
new CacheContext(
pluginDescriptor.PluginSettings,
new IFileSystemAdapter(FileSystems.Default),
pluginDescriptor.ProjectGraph,
pluginDescriptor.EntryPoints),
// TODO: Detect verbosity from logging service.
logger,
cancellationToken);
if (logger.HasLoggedErrors)
{
throw new Exception(
ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("ProjectCacheInitializationFailed"));
}
return new ProjectCacheService(plugin, buildManager, logger, pluginDescriptor, cancellationToken);
}
private static ProjectCachePluginBase GetPluginInstance(ProjectCacheDescriptor pluginDescriptor)
{
if (pluginDescriptor.PluginInstance != null)
{
return pluginDescriptor.PluginInstance;
}
if (pluginDescriptor.PluginAssemblyPath != null)
{
return GetPluginInstanceFromType(GetTypeFromAssemblyPath(pluginDescriptor.PluginAssemblyPath));
}
ErrorUtilities.ThrowInternalErrorUnreachable();
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
}
private static ProjectCachePluginBase GetPluginInstanceFromType(Type pluginType)
{
try
{
return (ProjectCachePluginBase) Activator.CreateInstance(pluginType)!;
}
catch (TargetInvocationException e) when (e.InnerException != null)
{
throw e.InnerException;
}
}
private static Type GetTypeFromAssemblyPath(string pluginAssemblyPath)
{
var assembly = LoadAssembly(pluginAssemblyPath);
var type = GetTypes<ProjectCachePluginBase>(assembly).FirstOrDefault();
ErrorUtilities.VerifyThrow(type != null, "NoProjectCachePluginFoundInAssembly", pluginAssemblyPath);
return type!;
Assembly LoadAssembly(string resolverPath)
{
#if !FEATURE_ASSEMBLYLOADCONTEXT
return Assembly.LoadFrom(resolverPath);
#else
return _loader.LoadFromPath(resolverPath);
#endif
}
IEnumerable<Type> GetTypes<T>(Assembly assembly)
{
return assembly.ExportedTypes
.Select(type => new {type, info = type.GetTypeInfo()})
.Where(
t => t.info.IsClass &&
t.info.IsPublic &&
!t.info.IsAbstract &&
typeof(T).IsAssignableFrom(t.type))
.Select(t => t.type);
}
}
#if FEATURE_ASSEMBLYLOADCONTEXT
private static readonly CoreClrAssemblyLoader _loader = new CoreClrAssemblyLoader();
#endif
public async Task<CacheResult> GetCacheResultAsync(BuildRequestData buildRequest)
{
// TODO: Parent these logs under the project build event so they appear nested under the project in the binlog viewer.
var queryDescription = $"{buildRequest.ProjectFullPath}" +
$"\n\tTargets:[{string.Join(", ", buildRequest.TargetNames)}]" +
$"\n\tGlobal Properties: {{{string.Join(",", buildRequest.GlobalProperties.Select(kvp => $"{kvp.Name}={kvp.EvaluatedValue}"))}}}";
_logger.LogMessage(
"\n====== Querying project cache for project " + queryDescription,
MessageImportance.High);
var cacheResult = await _projectCachePlugin.GetCacheResultAsync(buildRequest, _logger, _cancellationToken);
if (_logger.HasLoggedErrors || cacheResult.ResultType == CacheResultType.None)
{
throw new Exception(
ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("ProjectCacheQueryFailed", queryDescription));
}
var message = $"Plugin result: {cacheResult.ResultType}.";
switch (cacheResult.ResultType)
{
case CacheResultType.CacheHit:
message += " Skipping project.";
break;
case CacheResultType.CacheMiss:
case CacheResultType.CacheNotApplicable:
message += " Building project.";
break;
case CacheResultType.None:
break;
default:
throw new ArgumentOutOfRangeException();
}
_logger.LogMessage(
message,
MessageImportance.High);
return cacheResult;
}
public async Task ShutDown()
{
await _projectCachePlugin.EndBuildAsync(_logger, _cancellationToken);
if (_logger.HasLoggedErrors)
{
throw new Exception(
ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("ProjectCacheShutdownFailed"));
}
}
private class LoggingServiceToPluginLoggerAdapter : PluginLoggerBase
{
private readonly ILoggingService _loggingService;
public override bool HasLoggedErrors { get; protected set; }
public LoggingServiceToPluginLoggerAdapter(
LoggerVerbosity verbosity,
ILoggingService loggingService) : base(verbosity)
{
_loggingService = loggingService;
}
public override void LogMessage(string message, MessageImportance? messageImportance = null)
{
_loggingService.LogCommentFromText(
BuildEventContext.Invalid,
messageImportance ?? MessageImportance.Normal,
message);
}
public override void LogWarning(string warning)
{
_loggingService.LogWarningFromText(
BuildEventContext.Invalid,
null,
null,
null,
BuildEventFileInfo.Empty,
warning);
}
public override void LogError(string error)
{
HasLoggedErrors = true;
_loggingService.LogErrorFromText(
BuildEventContext.Invalid,
null,
null,
null,
BuildEventFileInfo.Empty,
error);
}
}
}
}