Skip to content

Commit

Permalink
feat:dapr (masastack#6)
Browse files Browse the repository at this point in the history
* chore: add MASA.Utils.Development.Dapr

* chore: dapr init

* chore: Stop dapr process after project is stopped

* chore: Increase get pid based on port

* chore: add dapr daemon, restart dapr after dapr is shut down abnormally, Added OSX system port handling

* chore: dapr supports the default AppPort obtained from ApplicationUrl by default, automatically assigns the grpc and http ports of dapr and automatically supplements environment variables

Supports automatic restart after the dapr process is closed, and the configuration after restart is consistent with the last successful startup configuration

Supports automatic restart of the dapr process after configuration update. Currently, there are no restrictions on HttpPort and GrpcPort. However, if the configuration update changes HttpPort and GrpcPort, the port obtained by DaprClient will be inconsistent with the actual running one. It needs to be adjusted later here.

* chore: remove redundant code

* chore: remove bad code

* fix: Fix AddDapr method enable dapr slidecar error

* feature: add dapr background options

* feature: add dapr background options

* feature: add dapr background options

* chore: Modify log

Co-authored-by: zhenlei520 <[email protected]>
  • Loading branch information
zhenlei520 and zhenlei520 authored Feb 21, 2022
1 parent bb2e838 commit 1ee722e
Show file tree
Hide file tree
Showing 32 changed files with 1,491 additions and 1 deletion.
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) MASA Stack

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
17 changes: 17 additions & 0 deletions MASA.Utils.sln
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MASA.Utils.Security.Cryptog
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MASA.Utils.Security.Cryptography.Tests", "test\MASA.Utils.Security.Cryptography.Tests\MASA.Utils.Security.Cryptography.Tests.csproj", "{BBC2C38F-D758-468F-95E6-DC4688A2D1C0}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Development", "Development", "{598A7DA7-898E-429B-992A-B0E586DADA35}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MASA.Utils.Development.Dapr", "src\Development\MASA.Utils.Development.Dapr\MASA.Utils.Development.Dapr.csproj", "{BA436D03-972D-4B6A-B526-9C44D0FE5E48}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MASA.Utils.Development.Dapr.AspNetCore", "src\Development\MASA.Utils.Development.Dapr.AspNetCore\MASA.Utils.Development.Dapr.AspNetCore.csproj", "{C91175C6-68E8-4EC8-8C92-BC6087F53EF1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -171,6 +177,14 @@ Global
{BBC2C38F-D758-468F-95E6-DC4688A2D1C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BBC2C38F-D758-468F-95E6-DC4688A2D1C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BBC2C38F-D758-468F-95E6-DC4688A2D1C0}.Release|Any CPU.Build.0 = Release|Any CPU
{BA436D03-972D-4B6A-B526-9C44D0FE5E48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BA436D03-972D-4B6A-B526-9C44D0FE5E48}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BA436D03-972D-4B6A-B526-9C44D0FE5E48}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BA436D03-972D-4B6A-B526-9C44D0FE5E48}.Release|Any CPU.Build.0 = Release|Any CPU
{C91175C6-68E8-4EC8-8C92-BC6087F53EF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C91175C6-68E8-4EC8-8C92-BC6087F53EF1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C91175C6-68E8-4EC8-8C92-BC6087F53EF1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C91175C6-68E8-4EC8-8C92-BC6087F53EF1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -206,6 +220,9 @@ Global
{64E3BA98-199D-46AD-BEE1-113FDB03238B} = {4FB3BD6D-D4C1-4BEF-AD62-8FD6EAEEB4DF}
{B59A8DF4-6591-42CE-A9F8-BD0806B4A4C4} = {4FB3BD6D-D4C1-4BEF-AD62-8FD6EAEEB4DF}
{BBC2C38F-D758-468F-95E6-DC4688A2D1C0} = {4F908878-0EB8-43E4-96E4-8B1F32E9B635}
{598A7DA7-898E-429B-992A-B0E586DADA35} = {D956582F-4071-47E6-A8E7-4C5A83770045}
{BA436D03-972D-4B6A-B526-9C44D0FE5E48} = {598A7DA7-898E-429B-992A-B0E586DADA35}
{C91175C6-68E8-4EC8-8C92-BC6087F53EF1} = {598A7DA7-898E-429B-992A-B0E586DADA35}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D7DAA0E6-098F-4B18-8775-64FDA96F1FF0}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
namespace MASA.Utils.Development.Dapr.AspNetCore;

public class DaprBackgroundOptions
{
private int _maxRetryTimes = 5;

/// <summary>
/// default: 5
/// </summary>
public int MaxRetryTimes
{
get => _maxRetryTimes;
set
{
if (value <= 0)
throw new ArgumentException($"{nameof(MaxRetryTimes)} Must be greater than 0");

_maxRetryTimes = value;
}
}

private int _defaultTime = 3000;

/// <summary>
/// default: 3000ms
/// </summary>
public int Time
{
get => _defaultTime;
set
{
if (value <= 0)
throw new ArgumentException($"{nameof(MaxRetryTimes)} Must be greater than 0");

_defaultTime = value;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
namespace MASA.Utils.Development.Dapr.AspNetCore;

public class DaprBackgroundService : IHostedService
{
private readonly IServiceProvider _serviceProvider;
private readonly IDaprProcess _daprProcess;
private readonly DaprOptions _options;
private readonly DaprBackgroundOptions _daprBackgroundOptions;
private readonly ILogger<DaprBackgroundService>? _logger;

public DaprBackgroundService(
IServiceProvider serviceProvider,
IDaprProcess daprProcess,
IOptionsMonitor<DaprOptions> options,
IOptions<DaprBackgroundOptions> daprBackgroundOptions,
ILogger<DaprBackgroundService>? logger)
{
_serviceProvider = serviceProvider;
_daprProcess = daprProcess;
_options = options.CurrentValue;
options.OnChange(daprOptions =>
{
daprOptions.AppPort ??= GetAppPort(daprOptions);
_daprProcess.Refresh(daprOptions);
});
_daprBackgroundOptions = daprBackgroundOptions.Value;
_logger = logger;
}

private ushort GetAppPort(DaprOptions options)
{
int retry = 0;
again:
var server = _serviceProvider.GetRequiredService<IServer>();
var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses;
if (addresses is { IsReadOnly: false, Count: 0 })
{
if (retry < _daprBackgroundOptions.MaxRetryTimes)
{
_logger?.LogWarning("dapr: failed to get app running port, retrying, please wait...");
retry++;
goto again;
}
throw new Exception("Failed to get the startup port, please specify the port manually");
}

return addresses!
.Select(address => new Uri(address))
.Where(address
=> (options.EnableSsl is true && address.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
|| address.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
.Select(address => (ushort)address.Port).FirstOrDefault();
}

public Task StartAsync(CancellationToken cancellationToken)
{
_logger?.LogInformation("{Name} is Starting ...", nameof(DaprBackgroundService));
System.Timers.Timer timer = new System.Timers.Timer(_daprBackgroundOptions.Time);
timer.Elapsed += delegate
{
_options.AppPort ??= GetAppPort(_options);
_daprProcess.Start(_options, cancellationToken);
};
timer.AutoReset = false;
timer.Enabled = true;
timer.Start();
return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
_logger?.LogInformation("{Name} is Stopping...", nameof(DaprBackgroundService));
_daprProcess.Stop(cancellationToken);
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MASA.Utils.Development.Dapr\MASA.Utils.Development.Dapr.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
namespace MASA.Utils.Development.Dapr.AspNetCore;

public static class ServiceCollectionExtensions
{
public static IServiceCollection AddDapr(
this IServiceCollection services,
Action<DaprOptions>? action = null,
Action<DaprBackgroundOptions>? daprBackgroundOptionsAction = null)
{
DaprOptions daprOptions = new();
action?.Invoke(daprOptions);
return services.AddDapr(() => daprOptions, daprBackgroundOptionsAction);
}

public static IServiceCollection AddDapr(this IServiceCollection services,
Func<DaprOptions> func,
Action<DaprBackgroundOptions>? action = null)
{
if (services.Any(service => service.ImplementationType == typeof(DaprService)))
{
return services;
}
services.AddSingleton<DaprService>();

if (action != null)
services.Configure(action);

services.AddHostedService<DaprBackgroundService>();
services.Configure<HostOptions>(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(15));
return services.AddDaprCore(func);
}

public static IServiceCollection AddDapr(this IServiceCollection services, IConfiguration configuration)
{
if (services.Any(service => service.ImplementationType == typeof(DaprService)))
{
return services;
}
services.AddSingleton<DaprService>();
services.AddHostedService<DaprBackgroundService>();
services.Configure<DaprBackgroundOptions>(configuration);
return services.AddDaprCore(configuration);
}

private class DaprService
{

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
global using Microsoft.AspNetCore.Hosting.Server;
global using Microsoft.AspNetCore.Hosting.Server.Features;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Options;
26 changes: 26 additions & 0 deletions src/Development/MASA.Utils.Development.Dapr/CommandLineBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace MASA.Utils.Development.Dapr;

public class CommandLineBuilder
{
public string Prefix { get; }

public List<string> Arguments { get; set; }

public CommandLineBuilder(string prefix)
{
Prefix = prefix;
Arguments = new();
}

public CommandLineBuilder Add(string name, string value, bool isSkip = false)
{
if (!isSkip)
{
Arguments.Add($"{Prefix}{name} {value}");
}

return this;
}

public override string ToString() => string.Join(' ', Arguments);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace MASA.Utils.Development.Dapr.Configurations;

public class DaprRuntimeOptions
{
[JsonPropertyName("appId")]
public string AppId { get; set; } = default!;

[JsonPropertyName("httpPort")]
public ushort HttpPort { get; set; } = default!;

[JsonPropertyName("grpcPort")]
public ushort GrpcPort { get; set; } = default!;

[JsonPropertyName("appPort")]
public ushort AppPort { get; set; } = default!;

[JsonPropertyName("metricsEnabled")]
public bool MetricsEnabled { get; set; } = default!;

[JsonPropertyName("command")]
public string Command { get; set; } = default!;

[JsonPropertyName("pid")]
public int PId { get; set; } = default!;
}
Loading

0 comments on commit 1ee722e

Please sign in to comment.