Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ccec5e0

Browse files
committedMay 6, 2023
chore: Dealing with Code Smells
1 parent 91252e6 commit ccec5e0

File tree

11 files changed

+200
-149
lines changed

11 files changed

+200
-149
lines changed
 

‎src/BuildingBlocks/Development/Masa.BuildingBlocks.Development.DaprStarter/Options/DaprOptionsBase.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public ushort? AppPort
2929
/// The protocol (gRPC or HTTP) Dapr uses to talk to the application. Valid values are: http or grpc
3030
/// default: HTTP
3131
/// </summary>
32-
public Protocol? AppProtocol { get; protected set; }
32+
public Protocol? AppProtocol { get; protected set; } = Protocol.Http;
3333

3434
/// <summary>
3535
/// Enable https when Dapr invokes the application

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter.AspNetCore/DaprBackgroundService.cs

+23-5
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,21 @@ public class DaprBackgroundService : BackgroundService
1111
private readonly DaprOptions _options;
1212
private readonly IHostApplicationLifetime _hostApplicationLifetime;
1313
private readonly ILogger<DaprBackgroundService>? _logger;
14+
private readonly IServiceProvider _serviceProvider;
1415

1516
public DaprBackgroundService(
1617
IAppPortProvider appPortProvider,
1718
IDaprProcess daprProcess,
1819
IOptionsMonitor<DaprOptions> options,
1920
IHostApplicationLifetime hostApplicationLifetime,
21+
IServiceProvider serviceProvider,
2022
ILogger<DaprBackgroundService>? logger)
2123
{
2224
_appPortProvider = appPortProvider;
2325
_daprProcess = daprProcess;
2426
_options = options.CurrentValue;
2527
_hostApplicationLifetime = hostApplicationLifetime;
28+
_serviceProvider = serviceProvider;
2629
_logger = logger;
2730
}
2831

@@ -41,21 +44,36 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
4144
{
4245
_logger?.LogInformation("{Name} is Starting ...", nameof(DaprBackgroundService));
4346

44-
CheckCompletionAppPort(_options);
47+
CheckCompletionAppPortAndEnableSSl(_options);
48+
PortUtils.CheckCompletionPort(_options, _serviceProvider);
4549

4650
_daprProcess.Start();
4751
}
4852
}
4953

50-
private void CheckCompletionAppPort(DaprOptions daprOptions)
54+
private void CheckCompletionAppPortAndEnableSSl(DaprOptions daprOptions)
5155
{
52-
if (daprOptions.AppPort == null)
56+
if (daprOptions.AppPort == null || daprOptions.EnableSsl == null)
5357
{
54-
CompletionAppPort(daprOptions);
58+
if (daprOptions.EnableSsl == null && daprOptions.AppPort != null)
59+
{
60+
daprOptions.EnableSsl = _appPortProvider.GetEnableSsl(daprOptions.AppPort.Value);
61+
}
62+
else
63+
{
64+
CompletionAppPortAndEnableSSl(daprOptions);
65+
}
66+
}
67+
else
68+
{
69+
if (daprOptions.EnableSsl != _appPortProvider.GetEnableSsl(daprOptions.AppPort.Value))
70+
{
71+
throw new UserFriendlyException($"The current AppPort: {daprOptions.AppPort.Value} is not an {(daprOptions.EnableSsl is true ? "Https" : "Http")} port, Dapr failed to start");
72+
}
5573
}
5674
}
5775

58-
private void CompletionAppPort(DaprOptions daprOptions)
76+
private void CompletionAppPortAndEnableSSl(DaprOptions daprOptions)
5977
{
6078
var item = _appPortProvider.GetAppPort(daprOptions.EnableSsl);
6179
if (daprOptions.EnableSsl == null)

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter.AspNetCore/DefaultAppPortProvider.cs

+32-12
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,36 @@ public class DefaultAppPortProvider : IAppPortProvider
99

1010
public DefaultAppPortProvider(IServer server) => _server = server;
1111

12+
public bool GetEnableSsl(ushort appPort)
13+
{
14+
var ports = GetPorts();
15+
if (ports.Any(p => p.Port == appPort))
16+
{
17+
var port = ports.First(p => p.Port == appPort);
18+
return port.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
19+
}
20+
21+
return false;
22+
}
23+
1224
public (bool EnableSsl, ushort AppPort) GetAppPort(bool? enableSsl)
25+
{
26+
var ports = GetPorts();
27+
28+
if (ports.Count == 1)
29+
{
30+
return new(ports[0].Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase), (ushort)ports[0].Item2);
31+
}
32+
33+
if (enableSsl is false && ports.Any(p => p.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)))
34+
{
35+
return new(false, GetAppPort(ports, false));
36+
}
37+
38+
return new(true, GetAppPort(ports, true));
39+
}
40+
41+
private List<(string Scheme, int Port)> GetPorts()
1342
{
1443
var addresses = _server.Features.Get<IServerAddressesFeature>()?.Addresses;
1544
if (addresses is { IsReadOnly: false, Count: 0 })
@@ -19,19 +48,9 @@ public class DefaultAppPortProvider : IAppPortProvider
1948
.Select(address => new Uri(address))
2049
.Where(address
2150
=> address.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)
22-
|| address.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
51+
|| address.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
2352
.Select(address => new ValueTuple<string, int>(address.Scheme, address.Port)).ToList();
24-
25-
if (ports.Count == 1)
26-
{
27-
return new(ports[0].Item1.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase), (ushort)ports[0].Item2);
28-
}
29-
30-
if (enableSsl is true && ports.Any(p => p.Item1.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)))
31-
{
32-
return new(true, GetAppPort(ports, true));
33-
}
34-
return new(false, GetAppPort(ports, false));
53+
return ports;
3554
}
3655

3756
public static ushort GetAppPort(List<ValueTuple<string, int>> ports, bool enableSsl)
@@ -43,6 +62,7 @@ public static ushort GetAppPort(List<ValueTuple<string, int>> ports, bool enable
4362
.Select(p => (ushort)p.Item2)
4463
.FirstOrDefault();
4564
}
65+
4666
return ports
4767
.Where(p => p.Item1.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
4868
.Select(p => (ushort)p.Item2)

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter.AspNetCore/IAppPortProvider.cs

+2
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,7 @@ namespace Masa.Contrib.Development.DaprStarter.AspNetCore;
55

66
public interface IAppPortProvider
77
{
8+
bool GetEnableSsl(ushort appPort);
9+
810
(bool EnableSsl, ushort AppPort) GetAppPort(bool? enableSsl);
911
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Copyright (c) MASA Stack All rights reserved.
2+
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
3+
4+
// ReSharper disable once CheckNamespace
5+
6+
namespace Masa.Contrib.Development.DaprStarter.AspNetCore;
7+
8+
internal static class PortUtils
9+
{
10+
public static void CheckCompletionPort(DaprOptions daprOptions, IServiceProvider serviceProvider)
11+
{
12+
var daprEnvironmentProvider = serviceProvider.GetRequiredService<IDaprEnvironmentProvider>();
13+
14+
daprOptions.DaprHttpPort ??= daprEnvironmentProvider.GetHttpPort();
15+
daprOptions.DaprGrpcPort ??= daprEnvironmentProvider.GetGrpcPort();
16+
17+
var reservedPorts = new List<int>();
18+
AddReservedPorts(daprOptions.DaprHttpPort);
19+
AddReservedPorts(daprOptions.DaprGrpcPort);
20+
AddReservedPorts(daprOptions.MetricsPort);
21+
AddReservedPorts(daprOptions.ProfilePort);
22+
AddReservedPorts(daprOptions.AppPort);
23+
24+
var availabilityPortProvider = serviceProvider.GetRequiredService<IAvailabilityPortProvider>();
25+
26+
daprEnvironmentProvider.TrySetHttpPort(GetPortAndAddReservedPortsByAvailability(daprOptions.DaprHttpPort, 3500));
27+
daprEnvironmentProvider.TrySetGrpcPort(GetPortAndAddReservedPortsByAvailability(daprOptions.DaprGrpcPort, 5001));
28+
daprEnvironmentProvider.TrySetMetricsPort(GetPortAndAddReservedPortsByAvailability(daprOptions.MetricsPort, 9090));
29+
30+
// Environment variables need to be improved
31+
bool IsAvailablePort([NotNullWhen(true)] ushort? port)
32+
{
33+
return port is > 0;
34+
}
35+
36+
void AddReservedPorts(ushort? port)
37+
{
38+
if (port is > 0) reservedPorts.Add(port.Value);
39+
}
40+
41+
ushort? GetPortAndAddReservedPortsByAvailability(ushort? port, ushort startingPort)
42+
{
43+
ushort? portByAvailability;
44+
if (IsAvailablePort(port))
45+
{
46+
portByAvailability = port.Value;
47+
}
48+
else
49+
{
50+
portByAvailability = availabilityPortProvider.GetAvailablePort(startingPort, reservedPorts);
51+
if (portByAvailability != null) reservedPorts.Add(portByAvailability.Value);
52+
}
53+
54+
return portByAvailability;
55+
}
56+
}
57+
}

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter.AspNetCore/ServiceCollectionExtensions.cs

+14-66
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ public static IServiceCollection AddDaprStarter(this IServiceCollection services
1111
string sectionName = nameof(DaprOptions),
1212
bool isDelay = true)
1313
{
14-
return services.AddDaprStarter(() => { services.AddDaprStarterCore(sectionName); }, isDelay);
14+
return services.AddDaprStarter(() =>
15+
{
16+
services.AddDaprStarterCore(sectionName);
17+
}, isDelay);
1518
}
1619

1720
public static IServiceCollection AddDaprStarter(
@@ -21,15 +24,21 @@ public static IServiceCollection AddDaprStarter(
2124
{
2225
ArgumentNullException.ThrowIfNull(daprOptionAction);
2326

24-
return services.AddDaprStarter(() => { services.AddDaprStarterCore(daprOptionAction); }, isDelay);
27+
return services.AddDaprStarter(() =>
28+
{
29+
services.AddDaprStarterCore(daprOptionAction);
30+
}, isDelay);
2531
}
2632

2733
public static IServiceCollection AddDaprStarter(
2834
this IServiceCollection services,
2935
IConfiguration configuration,
3036
bool isDelay = true)
3137
{
32-
return services.AddDaprStarter(() => { services.AddDaprStarterCore(configuration); }, isDelay);
38+
return services.AddDaprStarter(() =>
39+
{
40+
services.AddDaprStarterCore(configuration);
41+
}, isDelay);
3342
}
3443

3544
private static IServiceCollection AddDaprStarter(this IServiceCollection services, Action action, bool isDelay = true)
@@ -45,79 +54,18 @@ private static IServiceCollection AddDaprStarter(this IServiceCollection service
4554

4655
var serviceProvider = services.BuildServiceProvider();
4756
var options = serviceProvider.GetRequiredService<IOptionsMonitor<DaprOptions>>();
48-
CheckCompletionPort(options.CurrentValue, serviceProvider);
4957

5058
if (isDelay) return services.AddHostedService<DaprBackgroundService>();
5159

60+
PortUtils.CheckCompletionPort(options.CurrentValue, serviceProvider);
61+
5262
ArgumentNullException.ThrowIfNull(options.CurrentValue.AppPort);
5363
var daprProcess = serviceProvider.GetRequiredService<IDaprProcess>();
5464
daprProcess.Start();
5565
return services;
5666
}
5767

58-
private static void CheckCompletionPort(DaprOptions daprOptions, IServiceProvider serviceProvider)
59-
{
60-
var daprEnvironmentProvider = serviceProvider.GetRequiredService<IDaprEnvironmentProvider>();
61-
62-
daprOptions.DaprHttpPort ??= daprEnvironmentProvider.GetHttpPort();
63-
daprOptions.DaprGrpcPort ??= daprEnvironmentProvider.GetGrpcPort();
6468

65-
var httpPortStatus = IsAvailablePort(daprOptions.DaprHttpPort);
66-
var gRpcPortStatus = IsAvailablePort(daprOptions.DaprGrpcPort);
67-
var metricsStatus = IsAvailablePort(daprOptions.MetricsPort);
68-
69-
var httpPortByAvailability = daprOptions.DaprHttpPort;
70-
var gRpcPortByAvailability = daprOptions.DaprGrpcPort;
71-
var metricsPortByAvailability = daprOptions.MetricsPort;
72-
73-
if (!httpPortStatus || !gRpcPortStatus || !metricsStatus)
74-
{
75-
var reservedPorts = new List<int>();
76-
AddReservedPorts(httpPortByAvailability);
77-
AddReservedPorts(gRpcPortByAvailability);
78-
AddReservedPorts(metricsPortByAvailability);
79-
AddReservedPorts(daprOptions.ProfilePort);
80-
AddReservedPorts(daprOptions.AppPort);
81-
82-
var availabilityPortProvider = serviceProvider.GetRequiredService<IAvailabilityPortProvider>();
83-
84-
if (!httpPortStatus)
85-
{
86-
httpPortByAvailability = availabilityPortProvider.GetAvailablePort(3500, reservedPorts);
87-
if (httpPortByAvailability != null) reservedPorts.Add(httpPortByAvailability.Value);
88-
}
89-
90-
if (!gRpcPortStatus)
91-
{
92-
gRpcPortByAvailability = availabilityPortProvider.GetAvailablePort(50001, reservedPorts);
93-
if (gRpcPortByAvailability != null) reservedPorts.Add(gRpcPortByAvailability.Value);
94-
}
95-
96-
if (!metricsStatus)
97-
{
98-
metricsPortByAvailability = availabilityPortProvider.GetAvailablePort(9090, reservedPorts);
99-
if (metricsPortByAvailability != null) reservedPorts.Add(metricsPortByAvailability.Value);
100-
}
101-
102-
void AddReservedPorts(ushort? port)
103-
{
104-
if (port is > 0)
105-
{
106-
reservedPorts.Add(port.Value);
107-
}
108-
}
109-
}
110-
111-
daprEnvironmentProvider.TrySetHttpPort(httpPortByAvailability);
112-
daprEnvironmentProvider.TrySetGrpcPort(gRpcPortByAvailability);
113-
daprEnvironmentProvider.TrySetMetricsPort(metricsPortByAvailability);
114-
115-
// Environment variables need to be improved
116-
bool IsAvailablePort([NotNullWhen(true)] ushort? port)
117-
{
118-
return port is > 0;
119-
}
120-
}
12169

12270

12371
private sealed class DaprService

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter.AspNetCore/_Imports.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
33

44
global using Masa.BuildingBlocks.Development.DaprStarter;
5-
global using Masa.Contrib.Development.DaprStarter;
65
global using Masa.Contrib.Development.DaprStarter.AspNetCore;
76
global using Microsoft.AspNetCore.Hosting.Server;
87
global using Microsoft.AspNetCore.Hosting.Server.Features;
98
global using Microsoft.Extensions.Configuration;
9+
global using Microsoft.Extensions.DependencyInjection;
1010
global using Microsoft.Extensions.DependencyInjection.Extensions;
1111
global using Microsoft.Extensions.Hosting;
1212
global using Microsoft.Extensions.Logging;

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter/DaprProcess.cs

+12-13
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public void Start()
4848
lock (_lock)
4949
{
5050
_isStopByManually = false;
51-
var sidecarOptions = ConvertToSidecarOptions(_daprOptions.CurrentValue);
51+
var sidecarOptions = ConvertToSidecarOptions(DaprOptions.CurrentValue);
5252

5353
StartCore(sidecarOptions);
5454
}
@@ -60,15 +60,15 @@ private void StartCore(SidecarOptions options)
6060
var commandLineBuilder = CreateCommandLineBuilder(options);
6161

6262
_process = _daprProcessProvider.DaprStart(
63-
_defaultSidecarFileName!,
63+
GetDefaultSidecarFileName(),
6464
commandLineBuilder.ToString(),
6565
options.CreateNoWindow,
6666
(_, args) =>
6767
{
6868
if (args.Data == null)
6969
return;
7070

71-
if (_isFirst) CheckAndCompleteDaprEnvironment(args.Data);
71+
if (IsFirst) CheckAndCompleteDaprEnvironment(args.Data);
7272
}, () => UpdateStatus(DaprProcessStatus.Stopped));
7373

7474
_retryTime = 0;
@@ -90,6 +90,11 @@ private void StartCore(SidecarOptions options)
9090
// Register the child process to the job object to ensure that the child process terminates when the parent process terminates
9191
// Windows only
9292

93+
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
94+
{
95+
//Only supported on windows
96+
return;
97+
}
9398
ChildProcessTracker.AddProcess(_process);
9499
}
95100

@@ -109,7 +114,7 @@ private void CompleteDaprEnvironment()
109114
{
110115
DaprEnvironmentProvider.TrySetHttpPort(SuccessDaprOptions.DaprHttpPort);
111116
DaprEnvironmentProvider.TrySetGrpcPort(SuccessDaprOptions.DaprGrpcPort);
112-
_isFirst = false;
117+
IsFirst = false;
113118
_retryTime = 0;
114119
UpdateStatus(DaprProcessStatus.Started);
115120
}
@@ -152,7 +157,7 @@ private void StopCore()
152157
_process?.Kill();
153158
if (SuccessDaprOptions!.EnableSsl is not true)
154159
{
155-
_daprProcessProvider.DaprStop(_defaultSidecarFileName!, SuccessDaprOptions.AppId);
160+
_daprProcessProvider.DaprStop(GetDefaultDaprFileName(), SuccessDaprOptions.AppId);
156161
}
157162

158163
if (SuccessDaprOptions.DaprHttpPort != null)
@@ -194,7 +199,7 @@ private void Refresh(DaprOptions options)
194199
StopCore();
195200
}
196201

197-
_isFirst = true;
202+
IsFirst = true;
198203
SuccessDaprOptions = null;
199204
_logger?.LogDebug("Dapr sidecar configuration updated, Dapr AppId is {AppId}, restarting dapr, please wait...", options.AppId);
200205
StartCore(sidecarOptionsByRefresh);
@@ -226,13 +231,7 @@ private void HeartBeat()
226231
if (SuccessDaprOptions == null)
227232
return;
228233

229-
if (SuccessDaprOptions!.EnableSsl is true)
230-
{
231-
_logger?.LogDebug("The dapr status cannot be monitored in https mode, the check has been skipped");
232-
return;
233-
}
234-
235-
var daprList = _daprProcessProvider.GetDaprList(_defaultDaprFileName!, SuccessDaprOptions.AppId, out bool isException);
234+
var daprList = _daprProcessProvider.GetDaprList(GetDefaultDaprFileName(), SuccessDaprOptions.AppId, out bool isException);
236235
if (daprList.Count > 1)
237236
{
238237
_logger?.LogDebug("dapr sidecar appears more than 1 same appid, this may cause error");

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter/DaprProcessBase.cs

+22-14
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,14 @@ public abstract class DaprProcessBase
1515
private static readonly string UserFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
1616

1717
internal SidecarOptions? SuccessDaprOptions;
18-
protected readonly IOptionsMonitor<DaprOptions> _daprOptions;
19-
protected static string? _defaultDaprFileName;
20-
protected static string? _defaultSidecarFileName;
18+
protected readonly IOptionsMonitor<DaprOptions> DaprOptions;
19+
private static string? _defaultDaprFileName;
20+
private static string? _defaultSidecarFileName;
2121

2222
/// <summary>
2323
/// record whether dapr is initialized for the first time
2424
/// </summary>
25-
protected bool _isFirst = true;
26-
25+
protected bool IsFirst = true;
2726

2827
protected DaprProcessBase(
2928
IDaprEnvironmentProvider daprEnvironmentProvider,
@@ -32,7 +31,7 @@ protected DaprProcessBase(
3231
{
3332
DaprEnvironmentProvider = daprEnvironmentProvider;
3433
_daprProvider = daprProvider;
35-
_daprOptions = daprOptions;
34+
DaprOptions = daprOptions;
3635
}
3736

3837
internal SidecarOptions ConvertToSidecarOptions(DaprOptions options)
@@ -131,14 +130,13 @@ internal CommandLineBuilder CreateCommandLineBuilder(SidecarOptions options)
131130
.Add("enable-api-logging", () => "", options.EnableApiLogging is not true)
132131
.Add("enable-metrics", () => "", options.EnableMetrics is not true)
133132
.Add("mode", () => options.Mode, options.Mode.IsNullOrWhiteSpace())
134-
.Add(options.ExtendedParameter, () => "");
133+
.Add(options.ExtendedParameter, () => "", options.ExtendedParameter.IsNullOrWhiteSpace());
135134

136-
if (_isFirst)
137-
{
138-
_defaultDaprFileName = Path.Combine(options.DaprRootPath, GetFileName(DaprStarterConstant.DEFAULT_DAPR_FILE_NAME));
139-
_defaultSidecarFileName = Path.Combine(options.RootPath, "bin", GetFileName(DaprStarterConstant.DEFAULT_FILE_NAME));
140-
SuccessDaprOptions = options;
141-
}
135+
if (!IsFirst)
136+
return commandLineBuilder;
137+
138+
SetDefaultFileName(options.DaprRootPath, options.RootPath);
139+
SuccessDaprOptions = options;
142140

143141
return commandLineBuilder;
144142
}
@@ -166,7 +164,7 @@ internal CommandLineBuilder CreateCommandLineBuilder(SidecarOptions options)
166164
static ushort? GetPort(string data, string pattern)
167165
{
168166
ushort? port = null;
169-
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
167+
var regex = new Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
170168
var match = regex.Matches(data);
171169
if (match.Count > 0)
172170
{
@@ -197,4 +195,14 @@ internal CommandLineBuilder CreateCommandLineBuilder(SidecarOptions options)
197195
#endregion
198196

199197
static string GetFileName(string fileName) => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"{fileName}.exe" : fileName;
198+
199+
protected static string GetDefaultDaprFileName() => _defaultDaprFileName!;
200+
201+
protected static string GetDefaultSidecarFileName() => _defaultSidecarFileName!;
202+
203+
private static void SetDefaultFileName(string daprRootPath, string sidecarRootPath)
204+
{
205+
_defaultDaprFileName = Path.Combine(daprRootPath, GetFileName(DaprStarterConstant.DEFAULT_DAPR_FILE_NAME));
206+
_defaultSidecarFileName = Path.Combine(sidecarRootPath, "bin", GetFileName(DaprStarterConstant.DEFAULT_FILE_NAME));
207+
}
200208
}

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter/DaprProvider.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,13 @@ private static void DaprProcess_ErrorDataReceived(object? sender, DataReceivedEv
117117
public void DaprStop(string fileName, string appId)
118118
{
119119
var daprList = GetDaprList(fileName, appId, out _);
120-
var pid = 0;
121-
foreach (var dapr in daprList)
120+
121+
var pidList = daprList.Select(dapr => dapr.PId).ToList();
122+
foreach (var pid in pidList)
122123
{
123124
try
124125
{
125-
pid = dapr.PId;
126-
var process = Process.GetProcessById(dapr.PId);
126+
var process = Process.GetProcessById(pid);
127127
process.Kill();
128128
}
129129
catch (Exception ex)

‎src/Contrib/Development/Masa.Contrib.Development.DaprStarter/Internal/ChildProcessTracker.cs

+32-33
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,18 @@ public static class ChildProcessTracker
2121
/// <param name="process"></param>
2222
public static void AddProcess(Process? process)
2323
{
24-
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
25-
{
26-
//Only supported on windows
27-
return;
28-
}
29-
3024
if (process == null)
3125
return;
3226

33-
if (s_jobHandle != IntPtr.Zero)
27+
if (SJobHandle != IntPtr.Zero)
3428
{
35-
bool success = AssignProcessToJobObject(s_jobHandle, process.Handle);
29+
bool success = AssignProcessToJobObject(SJobHandle, process.Handle);
3630
if (!success && !process.HasExited)
3731
throw new System.ComponentModel.Win32Exception();
3832
}
3933
}
40-
34+
#pragma warning disable S3963
35+
#pragma warning disable S3877
4136
static ChildProcessTracker()
4237
{
4338
// This feature requires Windows 8 or later. To support Windows 7 requires
@@ -51,26 +46,29 @@ static ChildProcessTracker()
5146
// The job name is optional (and can be null) but it helps with diagnostics.
5247
// If it's not null, it has to be unique. Use SysInternals' Handle command-line
5348
// utility: handle -a ChildProcessTracker
54-
string jobName = "ChildProcessTracker" + Process.GetCurrentProcess().Id;
55-
s_jobHandle = CreateJobObject(IntPtr.Zero, jobName);
56-
57-
var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
49+
string jobName = "ChildProcessTracker" + Environment.ProcessId;
50+
SJobHandle = CreateJobObject(IntPtr.Zero, jobName);
5851

59-
// This is the key flag. When our process is killed, Windows will automatically
60-
// close the job handle, and when that happens, we want the child processes to
61-
// be killed, too.
62-
info.LimitFlags = JOBOBJECTLIMIT.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
52+
var info = new JobObjectBasicLimitInformation
53+
{
54+
// be killed, too.
55+
// close the job handle, and when that happens, we want the child processes to
56+
// This is the key flag. When our process is killed, Windows will automatically
57+
LimitFlags = JobObjectLimits.JobObjectLimitKillOnJobClose
58+
};
6359

64-
var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
65-
extendedInfo.BasicLimitInformation = info;
60+
var extendedInfo = new JobObjectExtendedLimitInformation
61+
{
62+
BasicLimitInformation = info
63+
};
6664

67-
int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
65+
int length = Marshal.SizeOf(typeof(JobObjectExtendedLimitInformation));
6866
IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
6967
try
7068
{
7169
Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
7270

73-
if (!SetInformationJobObject(s_jobHandle, JobObjectInfoType.ExtendedLimitInformation,
71+
if (!SetInformationJobObject(SJobHandle, JobObjectInfoType.ExtendedLimitInformation,
7472
extendedInfoPtr, (uint)length))
7573
{
7674
throw new System.ComponentModel.Win32Exception();
@@ -81,40 +79,41 @@ static ChildProcessTracker()
8179
Marshal.FreeHGlobal(extendedInfoPtr);
8280
}
8381
}
82+
#pragma warning restore S3877
83+
#pragma warning restore S3963
8484

8585
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
8686
static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string name);
8787

8888
[DllImport("kernel32.dll")]
89-
static extern bool SetInformationJobObject(IntPtr job, JobObjectInfoType infoType,
90-
IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);
89+
static extern bool SetInformationJobObject(IntPtr job, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);
9190

9291
[DllImport("kernel32.dll", SetLastError = true)]
9392
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
9493

9594
// Windows will automatically close any open job handles when our process terminates.
9695
// This can be verified by using SysInternals' Handle utility. When the job handle
9796
// is closed, the child processes will be killed.
98-
private static readonly IntPtr s_jobHandle;
97+
private static readonly IntPtr SJobHandle;
9998
}
10099

101100
public enum JobObjectInfoType
102101
{
103102
AssociateCompletionPortInformation = 7,
104103
BasicLimitInformation = 2,
105-
BasicUIRestrictions = 4,
104+
BasicUiRestrictions = 4,
106105
EndOfJobTimeInformation = 6,
107106
ExtendedLimitInformation = 9,
108107
SecurityLimitInformation = 5,
109108
GroupInformation = 11
110109
}
111110

112111
[StructLayout(LayoutKind.Sequential)]
113-
public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
112+
public struct JobObjectBasicLimitInformation
114113
{
115114
public Int64 PerProcessUserTimeLimit;
116115
public Int64 PerJobUserTimeLimit;
117-
public JOBOBJECTLIMIT LimitFlags;
116+
public JobObjectLimits LimitFlags;
118117
public UIntPtr MinimumWorkingSetSize;
119118
public UIntPtr MaximumWorkingSetSize;
120119
public UInt32 ActiveProcessLimit;
@@ -124,13 +123,13 @@ public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
124123
}
125124

126125
[Flags]
127-
public enum JOBOBJECTLIMIT : uint
126+
public enum JobObjectLimits : uint
128127
{
129-
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
128+
JobObjectLimitKillOnJobClose = 0x2000
130129
}
131130

132131
[StructLayout(LayoutKind.Sequential)]
133-
public struct IO_COUNTERS
132+
public struct IoCounters
134133
{
135134
public UInt64 ReadOperationCount;
136135
public UInt64 WriteOperationCount;
@@ -141,10 +140,10 @@ public struct IO_COUNTERS
141140
}
142141

143142
[StructLayout(LayoutKind.Sequential)]
144-
public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
143+
public struct JobObjectExtendedLimitInformation
145144
{
146-
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
147-
public IO_COUNTERS IoInfo;
145+
public JobObjectBasicLimitInformation BasicLimitInformation;
146+
public IoCounters IoInfo;
148147
public UIntPtr ProcessMemoryLimit;
149148
public UIntPtr JobMemoryLimit;
150149
public UIntPtr PeakProcessMemoryUsed;

0 commit comments

Comments
 (0)
Please sign in to comment.