Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add working directory override #59

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions all.sln
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ControllerSample", "Control
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ControllerSample", "samples\AspNetCore\ControllerSample\ControllerSample\ControllerSample.csproj", "{FE082318-2993-42A3-B2DB-28EDA77F7136}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppConfigurationSample", "samples\AspNetCore\AppConfigurationSample\AppConfigurationSample\AppConfigurationSample.csproj", "{C6911A37-51F3-4E29-8E67-39B460EE7ABA}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AppConfigurationSample", "AppConfigurationSample", "{3AD6FEBE-37E9-436E-BE86-29668A9DDB3E}"
ProjectSection(SolutionItems) = preProject
samples\AspNetCore\AppConfigurationSample\README.md = samples\AspNetCore\AppConfigurationSample\README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -258,6 +265,18 @@ Global
{FE082318-2993-42A3-B2DB-28EDA77F7136}.Release|x64.Build.0 = Release|Any CPU
{FE082318-2993-42A3-B2DB-28EDA77F7136}.Release|x86.ActiveCfg = Release|Any CPU
{FE082318-2993-42A3-B2DB-28EDA77F7136}.Release|x86.Build.0 = Release|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Debug|x64.ActiveCfg = Debug|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Debug|x64.Build.0 = Debug|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Debug|x86.ActiveCfg = Debug|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Debug|x86.Build.0 = Debug|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Release|Any CPU.Build.0 = Release|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Release|x64.ActiveCfg = Release|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Release|x64.Build.0 = Release|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Release|x86.ActiveCfg = Release|Any CPU
{C6911A37-51F3-4E29-8E67-39B460EE7ABA}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -285,6 +304,8 @@ Global
{A3C52771-3B41-43F6-A4DD-7B3F7BAA598D} = {D625B898-1677-4DCA-B067-C7BFB07F1314}
{C5B72F44-C52D-471D-BE29-DB1C34699220} = {DA3D8137-F2DD-465D-81AA-3CA5C75087D2}
{FE082318-2993-42A3-B2DB-28EDA77F7136} = {C5B72F44-C52D-471D-BE29-DB1C34699220}
{3AD6FEBE-37E9-436E-BE86-29668A9DDB3E} = {DA3D8137-F2DD-465D-81AA-3CA5C75087D2}
{C6911A37-51F3-4E29-8E67-39B460EE7ABA} = {3AD6FEBE-37E9-436E-BE86-29668A9DDB3E}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E906E97D-7D56-4E02-A13F-1C48AEB47A88}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>10</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Dapr.Extensions.Configuration" Version="1.11.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
<PackageReference Include="Dapr.AspNetCore" Version="1.11.0" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Man.Dapr.Sidekick.AspNetCore\Man.Dapr.Sidekick.AspNetCore.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;

namespace AppConfigurationSample.Controllers;

[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
[HttpGet(Name = "GetSecret")]
public async Task<IActionResult> Get([FromServices] DaprClient daprClient, [FromServices] IConfiguration configuration)
{
// Can read secrets by using the client or IConfiguration through DI as well
var clientSecrets = await daprClient.GetSecretAsync("localsecretstore", "secret");
var clientSecret = string.Join(",", clientSecrets.Select(d => d.Value));

var configurationSecret = configuration.GetSection("secret").Value;

return Ok(new
{
SecretFromClient = clientSecret,
SecretFromConfiguration = configurationSecret
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: localsecretstore
namespace: default
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: "Dapr/secrets.json"

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"secret": "YourPasskeyHere"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using Dapr.Client;
using Dapr.Extensions.Configuration;
using Man.Dapr.Sidekick;
using Man.Dapr.Sidekick.Threading;
using Serilog;

// Add Serilog for enhanced console logging.
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

try
{
var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog();
var env = builder.Environment;

// Manage local dapr sidecar
if (env.IsDevelopment())
{
// Set options in code
var sidecarOptions = new DaprSidecarOptions
{
AppId = "AppConfigurationSample",
AppPort = 5000,
DaprGrpcPort = 50001,
ResourcesDirectory = Path.Combine(env.ContentRootPath, "Dapr/Components"),

// Set the working directory to our project to allow relative paths in component yaml files
WorkingDirectory = env.ContentRootPath
};

// Build the default Sidekick controller
var sidekick = new DaprSidekickBuilder().Build();

// Start the Dapr Sidecar early in the pipeline, this will come up in the background
sidekick.Sidecar.Start(() => new DaprOptions { Sidecar = sidecarOptions }, DaprCancellationToken.None);

// Add Dapr Sidekick
builder.Services.AddDaprSidekick(builder.Configuration, o =>
{
o.Sidecar = sidecarOptions;
});
}

// Add services to the container.

builder.Services
.AddControllers()
.AddDapr();
builder.Services.AddDaprClient();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

// Wait for the Dapr sidecar to report healthy before attempting to use any Dapr components.
var client = new DaprClientBuilder().Build();
using (var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
{
// use the await keyword in your service instead
await client.WaitForSidecarAsync(tokenSource.Token);
}

// Get secrets from store during startup
var secret = await client.GetSecretAsync("localsecretstore", "secret");

// Use secrets to setup your services
Log.Logger.Information("----- Secret from DaprClient: " + string.Join(",", secret.Select(d => d.Value)));

// or forward them in the ConfigurationManager

builder.Configuration.AddDaprSecretStore("localsecretstore", client);

Log.Logger.Information("----- Secret from ConfigurationManager: " + builder.Configuration.GetSection("secret").Value);

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
46 changes: 46 additions & 0 deletions samples/AspNetCore/AppConfigurationSample/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# ASP.NET Core Controller example

This sample shows using Dapr with ASP.NET Core controllers. This application is a simple Web API application.
The application uses a Dapr secret store to read secrets.
The sample is starting a Dapr Sidekick process very early in the execution of the `Program.cs`
and then waits for the sidecar components to be loaded so that we can read secrets from the secret store
and use them when we setup our services.
The Sidekick hosted service will then reuse the same daprd process instance and manage it as usual.

## How Dapr Sidekick was added

The main change to the ASPCore template is the following block of code at the beginning of the `Program.cs`:

```csharp
// Manage local dapr sidecar
if (env.IsDevelopment())
{
// Set options in code
var sidecarOptions = new DaprSidecarOptions
{
AppId = "AppConfigurationSample",
AppPort = 5000,
DaprGrpcPort = 50001,
ResourcesDirectory = Path.Combine(env.ContentRootPath, "Dapr/Components"),

// Set the working directory to our project to allow relative paths in component yaml files
WorkingDirectory = env.ContentRootPath
};

// Build the default Sidekick controller
var sidekick = new DaprSidekickBuilder().Build();

// Start the Dapr Sidecar early in the pipeline, this will come up in the background
sidekick.Sidecar.Start(() => new DaprOptions { Sidecar = sidecarOptions }, DaprCancellationToken.None);

// Add Dapr Sidekick
builder.Services.AddDaprSidekick(builder.Configuration, o =>
{
o.Sidecar = sidecarOptions;
});
}
```

## Running the sample

To run the sample simply set `AppConfigurationSample` as the startup project and run it in Visual Studio, it will launch the Dapr sidecar and connect to it.
25 changes: 25 additions & 0 deletions src/Man.Dapr.Sidekick/Options/DaprManagedProcessOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Collections.Specialized;

namespace Man.Dapr.Sidekick.Options
{
public class DaprManagedProcessOptions
{
/// <summary>
/// Gets or sets a working directory to be used by the managed process.
/// This is required by some components that use relevant directory paths to load local files from the project folders.
/// Defaults to %USERPROFILE%/.dapr ($HOME/.dapr on Linux) if not specified.
/// </summary>
public string WorkingDirectory { get; set; }

/// <summary>
/// Gets or sets optional command-line process arguments.
/// </summary>
public string Arguments { get; set; }

/// <summary>
/// Gets or sets an optional action for configuring any environment variables for the process.
/// </summary>
public Action<StringDictionary> ConfigureEnvironmentVariables { get; set; }
}
}
7 changes: 7 additions & 0 deletions src/Man.Dapr.Sidekick/Options/DaprProcessOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ public abstract class DaprProcessOptions
/// </summary>
public string InitialDirectory { get; set; }

/// <summary>
/// Gets or sets a working directory to be used by the managed process.
/// This is required by some components that use relevant directory paths to load local files from the project folders.
/// Defaults to %USERPROFILE%/.dapr ($HOME/.dapr on Linux) if not specified.
/// </summary>
public string WorkingDirectory { get; set; }

/// <summary>
/// Gets or sets the issuer certificate used for mTLS encryption.
/// </summary>
Expand Down
13 changes: 10 additions & 3 deletions src/Man.Dapr.Sidekick/Process/DaprProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.IO;
using System.Linq;
using Man.Dapr.Sidekick.Logging;
using Man.Dapr.Sidekick.Options;
using Man.Dapr.Sidekick.Security;
using Man.Dapr.Sidekick.Threading;

Expand All @@ -12,7 +13,6 @@ internal abstract class DaprProcess<TOptions> : IDaprProcess<TOptions>, IDaprPro
{
private readonly object _lock = new object();
private readonly string _defaultProcessName;
private readonly string _defaultExeName;
private Func<DaprOptions> _startOptionsAccessor; // Returns latest startup options
private TOptions _pendingOptions; // Options used to start process, stored temporarily until startup complete.
private DaprProcessLogger _daprLogger;
Expand All @@ -28,7 +28,6 @@ internal abstract class DaprProcess<TOptions> : IDaprProcess<TOptions>, IDaprPro
protected DaprProcess(string defaultProcessName)
{
_defaultProcessName = defaultProcessName;
_defaultExeName = _defaultProcessName + ".exe";
}

public TOptions LastSuccessfulOptions { get; private set; }
Expand Down Expand Up @@ -343,7 +342,15 @@ private IProcess StartManagedProcess(TOptions proposedOptions, DaprCancellationT
process.OutputDataReceived += (sender, args) => _daprLogger?.LogData(args.Data);

// Start the managed dapr process
process.Start(proposedOptions.ProcessFile, arguments, Logger, cancellationToken: cancellationToken);
process.Start(
proposedOptions.ProcessFile,
new DaprManagedProcessOptions
{
Arguments = arguments,
WorkingDirectory = proposedOptions.WorkingDirectory
},
Logger,
cancellationToken: cancellationToken);

// Handle unplanned exit
process.UnplannedExit += (sender, args) =>
Expand Down
Loading