Skip to content
This repository has been archived by the owner on May 23, 2023. It is now read-only.

Dynamically load environment variables when using BootstrapFromDocker #60

Merged
merged 7 commits into from Dec 31, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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
23 changes: 22 additions & 1 deletion src/Akka.Bootstrap.Docker.Tests/DockerBootstrapSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ namespace Akka.Bootstrap.Docker.Tests
public class DockerBootstrapSpecs
{
[Theory]
[InlineData("[]")]
[InlineData("akka.tcp://MySys@localhost:9140")]
[InlineData("akka.tcp://MySys@localhost:9140, akka.tcp://MySys@localhost:9141")]
[InlineData("akka.tcp://MySys@localhost:9140, akka.tcp://MySys@localhost:9141, akka.tcp://MySys@localhost:9142")]
Expand Down Expand Up @@ -84,5 +83,27 @@ public void ShouldStartNormallyIfNotEnvironmentVariablesAreSupplied()
myConfig.GetString("akka.remote.dot-netty.tcp.public-hostname").Should().Be(Dns.GetHostName());
myConfig.HasPath("akka.remote.dot-netty.tcp.port").Should().BeFalse();
}

[Fact]
public void ShouldStartIfValidAkkaConfigurationSuppliedByEnvironmentVariables()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

{
Environment.SetEnvironmentVariable("AKKA__COORDINATED_SHUTDOWN__EXIT_CLR", "on", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__ACTOR__PROVIDER", "cluster", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__REMOTE__DOT_NETTY__TCP__HOSTNAME", "127.0.0.1", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__REMOTE__DOT_NETTY__TCP__PUBLIC_HOSTNAME", "example.local", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__REMOTE__DOT_NETTY__TCP__PORT", "2559", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__CLUSTER__ROLES__0", "demo", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__CLUSTER__ROLES__1", "test", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("AKKA__CLUSTER__ROLES__2", "backup", EnvironmentVariableTarget.Process);

var myConfig = ConfigurationFactory.Empty.BootstrapFromDocker();

myConfig.GetBoolean("akka.coordinated-shutdown.exit-clr").Should().BeTrue();
myConfig.GetString("akka.actor.provider").Should().Be("cluster");
myConfig.GetString("akka.remote.dot-netty.tcp.hostname").Should().Be("127.0.0.1");
myConfig.GetString("akka.remote.dot-netty.tcp.public-hostname").Should().Be("example.local");
myConfig.GetInt("akka.remote.dot-netty.tcp.port").Should().Be(2559);
myConfig.GetStringList("akka.cluster.roles").Should().BeEquivalentTo(new [] { "demo", "test", "backup" });
}
}
}
66 changes: 66 additions & 0 deletions src/Akka.Bootstrap.Docker/ConfigEntrySource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// -----------------------------------------------------------------------
// <copyright file="DockerBootstrap.cs" company="Petabridge, LLC">
// Copyright (C) 2018 - 2018 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;

namespace Akka.Bootstrap.Docker
{
/// <summary>
/// Defines a source of configuration to be evaluated and applied
/// against a HOCON key/value pair.
/// </summary>
public abstract class ConfigEntrySource
{
/// <summary>
/// Override to describe the implementation type
/// </summary>
/// <value></value>
public abstract string SourceName { get; }

/// <summary>
/// The series of key nodes which make up the path
/// </summary>
/// <value></value>
public string[] Nodes { get; }
/// <summary>
/// The full HOCON path for the given value (Derived from `Nodes`)
/// </summary>
/// <value></value>
public string Key { get; }
/// <summary>
/// The value for this given HOCON node
/// </summary>
/// <value></value>
public string Value { get; }
/// <summary>
/// Identifies if the source is a series of values
/// </summary>
public int Index { get; }
/// <summary>
/// Returns the depth of the hocon key (ie. number of nodes on the key)
/// </summary>
public int Depth => Nodes.Length;

/// <summary>
/// Creates a config entry source from a set of nodes, value and optional index
/// </summary>
/// <param name="nodes">Set of nodes which comprise the path</param>
/// <param name="value">Value stored in this entry</param>
/// <param name="index">Provided index to identify a set of hocon values stored
/// against a single key</param>
protected ConfigEntrySource(string[] nodes, string value, int index = 0)
{
Nodes = nodes;
Key = String.Join(".", Nodes);
Index = index;
Value = value;
}

}

}
62 changes: 20 additions & 42 deletions src/Akka.Bootstrap.Docker/DockerBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
// -----------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Text;
using Akka.Configuration;

namespace Akka.Bootstrap.Docker
Expand All @@ -32,48 +37,21 @@ public static class DockerBootstrap
/// </example>
public static Config BootstrapFromDocker(this Config input, bool assignDefaultHostName = true)
{
/*
* Trim any leading or trailing whitespace since that can cause problems
* with the URI / IP parsing that happens in the next stage
*/
var clusterIp = Environment.GetEnvironmentVariable("CLUSTER_IP")?.Trim();
var clusterPort = Environment.GetEnvironmentVariable("CLUSTER_PORT")?.Trim();
var clusterSeeds = Environment.GetEnvironmentVariable("CLUSTER_SEEDS")?.Trim();

if (string.IsNullOrEmpty(clusterIp) && assignDefaultHostName)
{
clusterIp = Dns.GetHostName();
Console.WriteLine($"[Docker-Bootstrap] Environment variable CLUSTER_IP was not set." +
$"Defaulting to local hostname [{clusterIp}] for remote addressing.");
}

// Don't have access to Akka.NET ILoggingAdapter yet, since ActorSystem isn't started.
Console.WriteLine($"[Docker-Bootstrap] IP={clusterIp}");
Console.WriteLine($"[Docker-Bootstrap] PORT={clusterPort}");
Console.WriteLine($"[Docker-Bootstrap] SEEDS={clusterSeeds}");


if (!string.IsNullOrEmpty(clusterIp))
input = ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.hostname=0.0.0.0" +
Environment.NewLine +
"akka.remote.dot-netty.tcp.public-hostname=" + clusterIp)
.WithFallback(input);

if (!string.IsNullOrEmpty(clusterPort) && int.TryParse(clusterPort, out var portNum))
input = ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port=" + portNum)
.WithFallback(input);

if (!string.IsNullOrEmpty(clusterSeeds))
{
var seeds = clusterSeeds.Split(',');
var injectedClusterConfigString = seeds.Aggregate("akka.cluster.seed-nodes = [",
(current, seed) => current + @"""" + seed + @""", ");
injectedClusterConfigString += "]";
input = ConfigurationFactory.ParseString(injectedClusterConfigString)
.WithFallback(input);
}

return input;
return ConfigurationFactory.Empty
.FromEnvironment()
.WithFallback(
ConfigurationFactory.ParseString(
$@"
akka.remote.dot-netty.tcp {{
hostname=0.0.0.0
public-hostname={Dns.GetHostName()}
}}
"
)
)
.WithFallback(
input
);
}
}
}
55 changes: 55 additions & 0 deletions src/Akka.Bootstrap.Docker/EnvironmentVariableConfigEntrySource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// -----------------------------------------------------------------------
// <copyright file="DockerBootstrap.cs" company="Petabridge, LLC">
// Copyright (C) 2018 - 2018 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace Akka.Bootstrap.Docker
{
/// <summary>
/// Configuration entry source from Environment Variables
/// </summary>
public class EnvironmentVariableConfigEntrySource : ConfigEntrySource
{
public override string SourceName { get; }= "environment-variable";

/// <summary>
/// Creates an instance of EnvironmentVariableConfigEntrySource
/// from a raw environment variable key/value pair
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// Will perform analysis on the key in the following way:
/// - Instances of '__' are treated as path delimiterrs
/// - Instances of '_' are treated as substitutions of '-'
/// - Terminal nodes which appear to be integers will be taken as indexes
/// to support multi-value keys
/// </remarks>
public static EnvironmentVariableConfigEntrySource Create(string key, string value)
{
var nodes = key.Split(new [] { "__" }, StringSplitOptions.None)
.Select(x => x.Replace("_", "-"))
.ToArray();
var index = 0;
var maybeIndex = nodes.Last();
if (Regex.IsMatch(maybeIndex, @"^\d+$")) {
nodes = nodes.Take(nodes.Length - 1).ToArray();
index = int.Parse(maybeIndex);
}
return new EnvironmentVariableConfigEntrySource(nodes, value, index);
}

EnvironmentVariableConfigEntrySource(string[] nodes, string value, int index = 0)
:base(nodes, value, index)
{

}
}

}
122 changes: 122 additions & 0 deletions src/Akka.Bootstrap.Docker/EnvironmentVariableConfigLoader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// -----------------------------------------------------------------------
// <copyright file="DockerBootstrap.cs" company="Petabridge, LLC">
// Copyright (C) 2018 - 2018 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Akka.Configuration;

namespace Akka.Bootstrap.Docker
{
/// <summary>
/// Extension and helper methods to support loading a Config instance from
/// the environment variables of the current process.
/// </summary>
public static class EnvironmentVariableConfigLoader
{
private static IEnumerable<EnvironmentVariableConfigEntrySource> GetEnvironmentVariables()
{
// Currently, exclude environment variables that do not start with "AKKA__"
// We can implement variable substitution at a later stage which would allow
// us to do something like: akka.some-setting=${?HOSTNAME} which can refer
// to other non "AKKA__" variables.
bool UseAllEnvironmentVariables = false;

// List of environment variable mappings that do not follow the "AKKA__" convention.
// We are currently supporting these out of convenience, and may choose to officially
// create a set of aliases in the future. Doing so would allow envvar configuration
// to be less verbose but might perpetuate confusion as to source of truth for keys.
Dictionary<string, string> ExistingMappings = new Dictionary<string, string>()
{
{ "CLUSTER_IP", "akka.remote.dot-netty.tcp.public-hostname" },
{ "CLUSTER_PORT", "akka.remote.dot-netty.tcp.port" },
{ "CLUSTER_SEEDS", "akka.cluster.seed-nodes" }
};

// Identify environment variable mappings that are expected to be lists
string[] ExistingMappingLists = new string[] { "CLUSTER_SEEDS" };

foreach (DictionaryEntry set in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process))
{
var key = set.Key.ToString();
var isList = false;

if (ExistingMappings.TryGetValue(key, out var mappedKey))
{
isList = ExistingMappingLists.Contains(key);

// Format the key to appear as if it were an environment variable
// in the "AKKA__" format
key = mappedKey.ToUpper().Replace(".", "__").Replace("-", "_");
}

if (!UseAllEnvironmentVariables)
if (!key.StartsWith("AKKA__", StringComparison.OrdinalIgnoreCase))
continue;

// Skip empty environment variables
var value = set.Value?.ToString()?.Trim();
if (string.IsNullOrEmpty(value))
continue;

// Ideally, lists should be passed through in an indexed format.
// However, we can allow for lists to be passed in as array format.
// Otherwise, we must format the string as an array.
if (isList)
{
if (value.First() != '[' || value.Last() != ']')
{
var values = value.Split(',').Select(x => x.Trim());
value = $"[\" {String.Join("\",\"", values)} \"]";
}
else if (String.IsNullOrEmpty(value.Substring(1, value.Length - 2).Trim()))
{
value = "[]";
}
}

yield return EnvironmentVariableConfigEntrySource.Create(
key.ToLower().ToString(),
value
);
}
}

/// <summary>
/// Load AKKA configuration from the environment variables that are
/// accessible from the current process.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static Config FromEnvironment(this Config input)
{
var entries = GetEnvironmentVariables()
.OrderByDescending(x => x.Depth)
.GroupBy(x => x.Key);

StringBuilder sb = new StringBuilder();
foreach (var set in entries)
{
sb.Append($"{set.Key}=");
if (set.Count() > 1)
{
sb.AppendLine($"[\n\t\"{String.Join("\",\n\t\"", set.OrderBy(y => y.Index).Select(y => y.Value.Trim()))}\"]");
}
else
{
sb.AppendLine($"{set.First().Value}");
}
}

var config = ConfigurationFactory.ParseString(sb.ToString());

return config;
}
}

}