-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Startup.cs
318 lines (273 loc) · 14.1 KB
/
Startup.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
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using Elasticsearch.Net;
using Fluid;
using GraphQL;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nest;
using OrchardCore.Admin;
using OrchardCore.BackgroundTasks;
using OrchardCore.ContentManagement;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.Deployment;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.Environment.Shell.Builders;
using OrchardCore.Environment.Shell.Configuration;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;
using OrchardCore.Navigation;
using OrchardCore.Queries;
using OrchardCore.Search.Abstractions;
using OrchardCore.Search.Elasticsearch.Core.Deployment;
using OrchardCore.Search.Elasticsearch.Core.Models;
using OrchardCore.Search.Elasticsearch.Core.Providers;
using OrchardCore.Search.Elasticsearch.Core.Services;
using OrchardCore.Search.Elasticsearch.Drivers;
using OrchardCore.Search.Elasticsearch.Services;
using OrchardCore.Search.Lucene.Handler;
using OrchardCore.Search.ViewModels;
using OrchardCore.Security.Permissions;
using OrchardCore.Settings;
namespace OrchardCore.Search.Elasticsearch
{
public class Startup : StartupBase
{
private const string ConfigSectionName = "OrchardCore_Elasticsearch";
private readonly AdminOptions _adminOptions;
private readonly IShellConfiguration _shellConfiguration;
private readonly ILogger<Startup> _logger;
public Startup(IOptions<AdminOptions> adminOptions,
IShellConfiguration shellConfiguration,
ILogger<Startup> logger)
{
_adminOptions = adminOptions.Value;
_shellConfiguration = shellConfiguration;
_logger = logger;
}
public override void ConfigureServices(IServiceCollection services)
{
var configuration = _shellConfiguration.GetSection(ConfigSectionName);
var elasticConfiguration = configuration.Get<ElasticConnectionOptions>();
if (CheckOptions(elasticConfiguration, _logger))
{
services.Configure<ElasticConnectionOptions>(o => o.ConfigurationExists = true);
IConnectionPool pool = null;
var uris = elasticConfiguration.Ports.Select(port => new Uri($"{elasticConfiguration.Url}:{port}")).Distinct();
switch (elasticConfiguration.ConnectionType)
{
case "SingleNodeConnectionPool":
pool = new SingleNodeConnectionPool(uris.First());
break;
case "CloudConnectionPool":
BasicAuthenticationCredentials credentials = null;
if (!string.IsNullOrWhiteSpace(elasticConfiguration.Username) && !string.IsNullOrWhiteSpace(elasticConfiguration.Password) && !string.IsNullOrWhiteSpace(elasticConfiguration.CloudId))
{
credentials = new BasicAuthenticationCredentials(elasticConfiguration.Username, elasticConfiguration.Password);
pool = new CloudConnectionPool(elasticConfiguration.CloudId, credentials);
}
break;
case "StaticConnectionPool":
pool = new StaticConnectionPool(uris);
break;
case "SniffingConnectionPool":
pool = new SniffingConnectionPool(uris);
break;
case "StickyConnectionPool":
pool = new StickyConnectionPool(uris);
break;
default:
pool = new SingleNodeConnectionPool(uris.First());
break;
}
var settings = new ConnectionSettings(pool).ThrowExceptions();
if (elasticConfiguration.ConnectionType != "CloudConnectionPool" && !string.IsNullOrWhiteSpace(elasticConfiguration.Username) && !string.IsNullOrWhiteSpace(elasticConfiguration.Password))
{
settings.BasicAuthentication(elasticConfiguration.Username, elasticConfiguration.Password);
}
if (!string.IsNullOrWhiteSpace(elasticConfiguration.CertificateFingerprint))
{
settings.CertificateFingerprint(elasticConfiguration.CertificateFingerprint);
}
if (elasticConfiguration.EnableApiVersioningHeader)
{
settings.EnableApiVersioningHeader();
}
var client = new ElasticClient(settings);
services.AddSingleton<IElasticClient>(client);
services.Configure<ElasticsearchOptions>(o =>
{
o.IndexPrefix = configuration.GetValue<string>(nameof(o.IndexPrefix));
var jsonNode = configuration.GetSection(nameof(o.Analyzers)).AsJsonNode();
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonNode);
var analyzersObject = JsonObject.Create(jsonElement, new JsonNodeOptions()
{
PropertyNameCaseInsensitive = true,
});
if (analyzersObject != null)
{
foreach (var analyzer in analyzersObject)
{
if (analyzer.Value == null)
{
continue;
}
o.Analyzers.Add(analyzer.Key, analyzer.Value.AsObject());
}
}
if (o.Analyzers.Count == 0)
{
// When no analyzers are configured, we'll define a default analyzer.
o.Analyzers.Add(ElasticsearchConstants.DefaultAnalyzer, new JsonObject
{
["type"] = "standard",
});
}
});
try
{
var response = client.Ping();
services.Configure<TemplateOptions>(o =>
{
o.MemberAccessStrategy.Register<SearchIndexViewModel>();
o.MemberAccessStrategy.Register<SearchFormViewModel>();
o.MemberAccessStrategy.Register<SearchResultsViewModel>();
});
services.AddElasticServices();
services.AddScoped<IPermissionProvider, Permissions>();
services.AddScoped<INavigationProvider, AdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, ElasticSettingsDisplayDriver>();
services.AddScoped<IDisplayDriver<Query>, ElasticQueryDisplayDriver>();
services.AddScoped<IContentTypePartDefinitionDisplayDriver, ContentTypePartIndexSettingsDisplayDriver>();
services.AddScoped<IContentPartFieldDefinitionDisplayDriver, ContentPartFieldIndexSettingsDisplayDriver>();
services.AddScoped<ElasticsearchService>();
services.AddScoped<ISearchService>(sp => sp.GetRequiredService<ElasticsearchService>());
services.AddScoped<IAuthorizationHandler, ElasticsearchAuthorizationHandler>();
}
catch (Exception ex)
{
_logger.LogError(ex, "Elasticsearch is enabled but not active because the connection failed.");
}
}
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
var options = serviceProvider.GetRequiredService<IOptions<ElasticConnectionOptions>>().Value;
if (!options.ConfigurationExists)
{
return;
}
var adminControllerName = typeof(AdminController).ControllerName();
routes.MapAreaControllerRoute(
name: "Elasticsearch.Index",
areaName: "OrchardCore.Search.Elasticsearch",
pattern: _adminOptions.AdminUrlPrefix + "/elasticsearch/Index",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Index) }
);
routes.MapAreaControllerRoute(
name: "Elasticsearch.Delete",
areaName: "OrchardCore.Search.Elasticsearch",
pattern: _adminOptions.AdminUrlPrefix + "/elasticsearch/Delete/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Delete) }
);
routes.MapAreaControllerRoute(
name: "Elasticsearch.Query",
areaName: "OrchardCore.Search.Elasticsearch",
pattern: _adminOptions.AdminUrlPrefix + "/elasticsearch/Query",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Query) }
);
routes.MapAreaControllerRoute(
name: "Elasticsearch.Rebuild",
areaName: "OrchardCore.Search.Elasticsearch",
pattern: _adminOptions.AdminUrlPrefix + "/elasticsearch/Rebuild/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Rebuild) }
);
routes.MapAreaControllerRoute(
name: "Elasticsearch.Reset",
areaName: "OrchardCore.Search.Elasticsearch",
pattern: _adminOptions.AdminUrlPrefix + "/elasticsearch/Reset/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Reset) }
);
routes.MapAreaControllerRoute(
name: "Elasticsearch.SyncSettings",
areaName: "OrchardCore.Search.Elasticsearch",
pattern: _adminOptions.AdminUrlPrefix + "/elasticsearch/SyncSettings",
defaults: new { controller = adminControllerName, action = nameof(AdminController.SyncSettings) }
);
}
private static bool CheckOptions(ElasticConnectionOptions elasticConnectionOptions, ILogger logger)
{
var optionsAreValid = true;
if (elasticConnectionOptions == null)
{
logger.LogError("Elasticsearch is enabled but not active because the configuration is missing.");
return false;
}
if (string.IsNullOrWhiteSpace(elasticConnectionOptions.Url))
{
logger.LogError("Elasticsearch is enabled but not active because the 'Url' is missing or empty in application configuration.");
optionsAreValid = false;
}
if (elasticConnectionOptions.Ports.Length == 0)
{
logger.LogError("Elasticsearch is enabled but not active because a port is missing in application configuration.");
optionsAreValid = false;
}
return optionsAreValid;
}
}
[RequireFeatures("OrchardCore.Deployment")]
public class DeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
if (services.Any(d => d.GetImplementationType() == typeof(ElasticsearchService)))
{
services.AddTransient<IDeploymentSource, ElasticIndexDeploymentSource>();
services.AddSingleton<IDeploymentStepFactory>(new DeploymentStepFactory<ElasticIndexDeploymentStep>());
services.AddScoped<IDisplayDriver<DeploymentStep>, ElasticIndexDeploymentStepDriver>();
services.AddTransient<IDeploymentSource, ElasticSettingsDeploymentSource>();
services.AddSingleton<IDeploymentStepFactory>(new DeploymentStepFactory<ElasticSettingsDeploymentStep>());
services.AddScoped<IDisplayDriver<DeploymentStep>, ElasticSettingsDeploymentStepDriver>();
services.AddTransient<IDeploymentSource, ElasticIndexRebuildDeploymentSource>();
services.AddSingleton<IDeploymentStepFactory>(new DeploymentStepFactory<ElasticIndexRebuildDeploymentStep>());
services.AddScoped<IDisplayDriver<DeploymentStep>, ElasticIndexRebuildDeploymentStepDriver>();
services.AddTransient<IDeploymentSource, ElasticIndexResetDeploymentSource>();
services.AddSingleton<IDeploymentStepFactory>(new DeploymentStepFactory<ElasticIndexResetDeploymentStep>());
services.AddScoped<IDisplayDriver<DeploymentStep>, ElasticIndexResetDeploymentStepDriver>();
}
}
}
[Feature("OrchardCore.Search.Elasticsearch.Worker")]
public class ElasticWorkerStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
if (services.Any(d => d.GetImplementationType() == typeof(ElasticsearchService)))
{
services.AddSingleton<IBackgroundTask, IndexingBackgroundTask>();
}
}
}
[Feature("OrchardCore.Search.Elasticsearch.ContentPicker")]
public class ElasticContentPickerStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
if (services.Any(d => d.GetImplementationType() == typeof(ElasticsearchService)))
{
services.AddScoped<IContentPickerResultProvider, ElasticContentPickerResultProvider>();
services.AddScoped<IContentPartFieldDefinitionDisplayDriver, ContentPickerFieldElasticEditorSettingsDriver>();
services.AddShapeAttributes<ElasticContentPickerShapeProvider>();
}
}
}
}