Canary Routing with Traefik in Nomad

23 Jun 2019

I wanted to implement canary routing for some HTTP services deployed via Nomad the other day, but rather than having the traffic split by weighting to the containers, I wanted to direct the traffic based on a header.

My first choice of tech was to use Fabio, but it only supports routing by URL prefix, and additionally with a route weight. While I was at JustDevOps in Poland, I heard about another router/loadbalancer which worked in a similar way to Fabio: Traefik.

While Traefik also doesn’t directly support canary routing, it is much more flexible than Fabio, also allowing request filtering based on HTTP headers. Traefik integrates with a number of container schedulers directly, but Nomad is not one of them. It does however also support using the Consul Service Catalog so that you can use it as an almost drop-in replacement for Fabio.

So let’s get to the setup. As usual, there is a complete repository on GitHub: Nomad Traefik Canary Routing.

Nomad

As usual, I am using my Hashibox Vagrant base image, and provisioning it as a single Nomad server and client node, using this script. I won’t dig into all the setup in that, as I’ve written it a few times now.

Consul

Consul is already running on the Hashibox base, so we have no further configuration to do.

Traefik

Traefik can be deployed as a Docker container, and either configured through a TOML file (yay, not yaml!) or with command line switches. As we only need a minimal configuration, I opted to use the command line.

The container exposes two ports we need to care about: 80 for incoming traffic to be routed, and 8080 for the UI, which are statically allocated to the host as 8000 and 8080 for this demo.

The command line configuration used is as follows:

  • --api - enable the UI.
  • --consulcatalog - Traefik has two ways to use Consul - --consul uses the KV store for service definitions, and --consulcatalog makes use Consul’s service catalogue.
  • --consulcatalog.endpoint=consul.service.consul:8500 as Consul is not running in the same container as Traefik, we need to tell it where Consul is listening, and as we have DNS Forwarding for *.consul domains, we use the address consul.service.consul. If DNS forwarding was not available, you could use the Nomad variable ${attr.unique.network.ip-address} to get the current task’s host’s IP.
  • --consulcatalog.frontEndRule disable the default rule - each service needs to specify traefik.frontend.rule.
  • --consulcatalog.exposedByDefault=false - lastly, we stop Traefik showing all services registered into consul, the will need to have the traefik.enable=true tag to be processed.

The entire job file is listed below:

job "traefik" {
  datacenters = ["dc1"]
  type = "service"

  group "loadbalancers" {
    count = 1

    task "traefik" {
      driver = "docker"

      config {
        image = "traefik:1.7.12"

        args = [
          "--api",
          "--consulcatalog",
          "--consulcatalog.endpoint=consul.service.consul:8500",
          "--consulcatalog.frontEndRule=''",
          "--consulcatalog.exposedByDefault=false"
        ]

        port_map {
          http = 80
          ui = 8080
        }
      }

      resources {
        network {
          port "http" { static = 8000 }
          port "ui" { static = 8080 }
        }

        memory = 50
      }

    }
  }
}

We register the job into Nomad, and then start on the backend services we will route to:

nomad job run jobs/traefik.nomad

The Backend Services

To demonstrate the services can be routed to correctly, we can use the containersol/k8s-deployment-strategies docker container. This image exposes an HTTP service which responds with the container’s hostname and the content of the VERSION environment variable, something like this:

$ curl http://echo.service.consul:8080
# Host: 23351e48dc98, Version: 1.0.0

We’ll start by making a standard nomad job for this container, and then update it to support canarying. The entire job is listed below:

job "echo" {
  datacenters = ["dc1"]
  type = "service"

  group "apis" {
    count = 3

    task "echo" {
      driver = "docker"

      config {
        image = "containersol/k8s-deployment-strategies"

        port_map {
          http = 8080
        }
      }

      env {
        VERSION = "1.0.0"
      }

      resources {
        network {
          port "http" { }
        }
      }

      service {
        name = "echo"
        port = "http"

        tags = [
          "traefik.enable=true",
          "traefik.frontend.rule=Host:api.localhost"
        ]

        check {
          type = "http"
          path = "/"
          interval = "5s"
          timeout = "1s"
        }
      }
    }
  }
}

The only part of interest in this version of the job is the service stanza, which is registering our echo service into consul, with a few tags to control how it is routed by Traefik:

service {
  name = "echo"
  port = "http"

  tags = [
    "traefik.enable=true",
    "traefik.frontend.rule=Host:api.localhost"
  ]

  check {
    type = "http"
    path = "/"
    interval = "5s"
    timeout = "1s"
  }
}

The traefik.enabled=true tag allows this service to be handled by Traefik (as we set exposedByDefault=false in Traefik), and traefik.frontend.rule=Host:api.localhost the rule means that any traffic with the Host header set to api.localhost will be routed to the service.

Which we can now run the job in Nomad:

nomad job run jobs/echo.nomad

Once it is up and running, we’ll get 3 instances of echo running which will be round-robin routed by Traefik:

$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost'
#Host: 1ac8a49cbaee, Version: 1.0.0
$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost'
#Host: 23351e48dc98, Version: 1.0.0
$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost'
#Host: c2f8a9dcab95, Version: 1.0.0

Now that we have working routing for the Echo service let’s make it canaryable.

Canaries

To show canary routing, we will create a second version of the service to respond to HTTP traffic with a Canary header.

The first change to make is to add in the update stanza, which controls how the containers get updated when Nomad pushes a new version. The canary parameter controls how many instances of the task will be created for canary purposes (and must be less than the total number of containers). Likewise, the max_parallel parameter controls how many containers will be replaced at a time when a deployment happens.

group "apis" {
  count = 3

+  update {
+    max_parallel = 1
+    canary = 1
+  }

  task "echo" {

Next, we need to modify the service stanza to write different tags to Consul when a task is a canary instance so that it does not get included in the “normal” backend routing group.

If we don’t specify at least 1 value in canary_tags, Nomad will use the tags even in the canary version - an empty canary_tags = [] declaration is not enough!

service {
  name = "echo"
  port = "http"
  tags = [
    "traefik.enable=true",
    "traefik.frontend.rule=Host:api.localhost"
  ]
+  canary_tags = [
+    "traefik.enable=false"
+  ]
  check {

Finally, we need to add a separate service stanza to create a second backend group which will contain the canary versions. Note how this group has a different name, and has no tags, but does have a set of canary_tags.

service {
  name = "echo-canary"
  port = "http"
  tags = []
  canary_tags = [
    "traefik.enable=true",
    "traefik.frontend.rule=Host:api.localhost;Headers: Canary,true"
  ]
  check {
    type = "http"
    path = "/"
    interval = "5s"
    timeout = "1s"
  }
}

The reason we need two service stanzas is that Traefik can only create backends based on the name of the service registered to Consul and not from a tag in that registration. If we just used one service stanza, then the canary version of the container would be added to both the canary backend and standard backend. I was hoping for traefik.backend=echo-canary to work, but alas no.

The entire updated jobfile is as follows:

job "echo" {
  datacenters = ["dc1"]
  type = "service"

  group "apis" {
    count = 3

    update {
      max_parallel = 1
      canary = 1
    }

    task "echo" {
      driver = "docker"

      config {
        image = "containersol/k8s-deployment-strategies"

        port_map {
          http = 8080
        }
      }

      env {
        VERSION = "1.0.0"
      }

      resources {
        network {
          port "http" { }
        }

        memory = 50
      }

      service {
        name = "echo-canary"
        port = "http"

        tags = []
        canary_tags = [
          "traefik.enable=true",
          "traefik.frontend.rule=Host:api.localhost;Headers: Canary,true"
        ]

        check {
          type = "http"
          path = "/"
          interval = "5s"
          timeout = "1s"
        }
      }

      service {
        name = "echo"
        port = "http"

        tags = [
          "traefik.enable=true",
          "traefik.frontend.rule=Host:api.localhost"
        ]
        canary_tags = [
          "traefik.enable=false"
        ]

        check {
          type = "http"
          path = "/"
          interval = "5s"
          timeout = "1s"
        }
      }
    }
  }
}

Testing

First, we will change the VERSION environment variable so that Nomad sees the job as changed, and we get a different response from HTTP calls to the canary:

env {
-  VERSION = "1.0.0"
+  VERSION = "2.0.0"
}

Now we will update the job in Nomad:

nomad job run jobs/echo.nomad

If we run the status command, we can see that the deployment has started, and there is one canary instance running. Nothing further will happen until we promote it:

$ nomad status echo
ID            = echo
Status        = running

Latest Deployment
ID          = 330216b9
Status      = running
Description = Deployment is running but requires promotion

Deployed
Task Group  Promoted  Desired  Canaries  Placed  Healthy  Unhealthy  Progress Deadline
apis        false     3        1         1       1        0          2019-06-19T11:19:31Z

Allocations
ID        Node ID   Task Group  Version  Desired  Status   Created    Modified
dcff2555  82f6ea8b  apis        1        run      running  18s ago    2s ago
5b2710ed  82f6ea8b  apis        0        run      running  6m52s ago  6m26s ago
698bd8a7  82f6ea8b  apis        0        run      running  6m52s ago  6m27s ago
b315bcd3  82f6ea8b  apis        0        run      running  6m52s ago  6m25s ago

We can now test that the original containers still work, and that the canary version works:

$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost'
#Host: 1ac8a49cbaee, Version: 1.0.0
$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost'
#Host: 23351e48dc98, Version: 1.0.0
$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost'
#Host: c2f8a9dcab95, Version: 1.0.0
$ curl http://traefik.service.consul:8080 -H 'Host: api.localhost' -H 'Canary: true'
#Host: 496840b438f2, Version: 2.0.0

Assuming we are happy with our new version, we can tell Nomad to promote the deployment, which will remove the canary and start a rolling update of the three tasks, one at a time:

nomad deployment promote 330216b9

End

My hope is that the next version of Traefik will have better support for canary by header, meaning I could simplify the Nomad jobs a little, but as it stands, this doesn’t add much complexity to the jobs, and can be easily put into an Architecture Decision Record (or documented in a wiki page, never to be seen or read from again!)

infrastructure, vagrant, nomad, consul, traefik

---

Feature Toggles: Reducing Coupling

11 Jun 2019

One of the points I make in my Feature Toggles talk is that you shouldn’t be querying a toggle’s status all over your codebase. Ideally, each toggle gets checked in as few places as possible - preferably only one place. The advantage of doing this is that very little of your codebase needs to be coupled to the toggles (either the toggle itself or the library/system for managing toggles itself).

This post will go over several situations when that seems hard to do, namely: multiple services, multiple distinct areas of a codebase, and multiple times in a complex class or method. As in the previous post on this, we will be using Branch By Abstraction to do most of the heavy lifting.

Multiple Services

Multiple services interacting with the same feature toggle is a problematic situation to deal with, especially if multiple teams own the different services.

One of the main issues with this is trying to coordinate the two (or more) services. For example, if one team needs to switch off their implementation due to a problem, should the other services also get turned off too? To compound on this problem, what happens if one system can react to the toggle change faster than the other?

Services changing configuration at different speeds can also cause issues with handling in-flight requests too: if the message format is different when the toggle is on, will the receiving system be able to process a message produced when the toggle was in one state but consumed in the other state?

We can solve some of this by using separate toggles for each service (and they are not allowed to query the other service’s toggle state), and by writing the services so that they can handle both old format and new format requests at the same time.

For example, if we had a sending system which when the toggle is off will send this DTO:

public class PurchaseOptions
{
    public Address Address { get; set; }
}

And when the toggle is enabled, it will send the following DTO instead:

public class PurchaseOptions
{
    public BillingAddress Address { get; set; }
    public DeliveryAddress Address { get; set; }
}

To make the receiving system handle this, we deserialize the request into a DTO which contains all possible versions of the address, and then use the best version based on our own toggle state:

public class PurchaseOptionsRequest
{
    public Address Address { get; set; }
    public BillingAddress Address { get; set; }
    public DeliveryAddress Address { get; set; }
}

public class PurchaseController
{
    public async Task<PurchaseOptionsResponse> Post(PurchaseOptionsRequest request)
    {
        if (separateAddresses.Enabled)
        {
            var deliveryAddress = request.DeliveryAddress ?? request.Address;
            var billingAddress = request.BillingAddress ?? request.Address;

            ConfigureDelivery(deliveryAddress);
            CreateInvoice(billingAddress, deliveryAddress);
        }
        else
        {
            var address = request.Address ?? request.DeliveryAddress ?? request.BillingAddress;

            ConfigureDelivery(address)
            CreateInvoice(address, address);
        }
    }
}

Note how both sides of the toggle check read all three possible address fields, but try to use different fields first. This means that no matter whether the sending service has it’s toggle on or not, we will use the correct address.

Multiple Areas of the Codebase

To continue using the address example, we might have a UI, Controller and Handler, which all need to act differently based on the same toggle:

  • The UI needs to display either one or two address editors
  • The controller needs to have different validation logic for multiple addresses
  • The Command Handler will need to dispatch different values

We can solve this all by utilising Branch By Abstraction and Dependency Injection to make most of the codebase unaware that a feature toggle exists. Even the implementations won’t need to know about the toggles.

public class Startup
{
    public void ConfigureContainer(ServiceRegistry services)
    {
        if (separateAddresses.Enabled) {
            services.Add<IAddressEditor, MultiAddressEditor>();
            services.Add<IRequestValidator, MultiAddressValidator>();
            services.Add<IDeliveryHandler, MultiAddressDeliveryHandler>();
        }
        else {
            services.Add<IAddressEditor, SingleAddressEditor>();
            services.Add<IRequestValidator, SingleAddressValidator>();
            services.Add<IDeliveryHandler, SingleAddressDeliveryHandler>();
        }
    }
}

Let’s look at how one of these might work. The IRequestValidator has a definition like so:

public interface IRequestValidator<TRequest>
{
    public IEnumerable<string> Validate(TRequest request);
}

There is a middleware in the API request pipeline which will pick the right validator out of the container, based on the request type being processed. We implement two validators, once for the single address, and one for multiaddress:

public class SingleAddressValidator : IRequestValidator<SingleAddressRequest>
{
    public IEnumerable<string> Validate(SingleAddressRequest request)
    {
        //complex validation logic..
        if (request.Address == null)
            yield return "No Address specified";

        if (PostCode.Validate(request.Address.PostCode) == false)
            yield return "Invalid Postcode";
    }
}

public class MultiAddressValidator : IRequestValidator<MultiAddressRequest>
{
    public IEnumerable<string> Validate(MultiAddressRequest request)
    {
        var billingMessages = ValidateAddress(request.BillingAddress);

        if (billingMessages.Any())
            return billingMessages;

        if (request.DifferentDeliveryAddress)
            return ValidateAddress(request.DeliveryAddress);
    }
}

The implementations themselves don’t need to know about the state of the toggle, as the container and middleware take care of picking the right implementation to use.

Multiple Places in a Class/Method

If you have a single method (or class) which needs to check the toggle state in multiple places, you can also use the same Branch by Abstraction technique as above, by creating a custom interface and pair of implementations, which contain all the functionality which changes.

For example, if we have a method for finding an offer for a customer’s basket, which has a few separate checks that the toggle is enabled in it:

public SuggestedBasket CreateOffer(CreateOfferCommand command)
{
    if (newFeature.Enabled) {
        ExtraPreValidation(command).Throw();
    } else {
        StandardPreValidation(command).Throw();
    }

    var offer = SelectBestOffer(command.Items);

    if (offer == null && newFeature.Enabled) {
        offer = FindAlternativeOffer(command.Customer, command.Items);
    }

    return SuggestedBasket
        .From(command)
        .With(offer);
}

We can extract an interface for this, and replace the toggle specific parts with calls to the interface instead:

public interface ICreateOfferStrategy
{
    IThrowable PreValidate(CreateOfferCommand command);
    Offer AlternativeOffer(CreateOfferCommand command, Offer existingOffer);
}

public class DefaultOfferStrategy : ICreateOfferStrategy
{
    public IThrowable PreValidate(CreateOfferCommand command)
    {
        return StandardPreValidation(command);
    }

    public Offer AlternativeOffer(CreateOfferCommand command, Offer existingOffer)
    {
        return existingOffer;
    }
}

public class DefaultOfferStrategy : ICreateOfferStrategy
{
    public IThrowable PreValidate(CreateOfferCommand command)
    {
        return ExtraPreValidation(command);
    }

    public Offer AlternativeOffer(CreateOfferCommand command, Offer existingOffer)
    {
        if (existingOffer != null)
            return existingOffer;

        return TryFindAlternativeOffer(command.Customer, command.Items, offer);
    }
}

public class OfferBuilder
{
    private readonly ICreateOfferStrategy _strategy;

    public OfferBuilder(ICreateOfferStrategy strategy)
    {
        _strategy = strategy;
    }

    public SuggestedBasket CreateOffer(CreateOfferCommand command)
    {
        _strategy.PreValidation(command).Throw();

        var offer = SelectBestOffer(command.Items);

        offer = _strategy.AlternativeOffer(command, offer);

        return SuggestedBasket
            .From(command)
            .With(offer);
    }
}

Now that we have done this, our CreateOffer method has shrunk dramatically and no longer needs to know about the toggle state, as like the rest of our DI examples, the toggle can be queried once in the startup of the service and the correct ICreateOfferStrategy implementation registered into the container.

End

Hopefully, this post will give a few insights into different ways of reducing the number of calls to your feature toggling library, and prevent you scattering lots of if statements around the codebase!

featuretoggles, c#, di, microservices

---

Feature Toggles: Branch by Abstraction

03 Jun 2019

Recently, I was asked if I could provide an example of Branch By Abstraction when dealing with feature toggles. As this has come up a few times, I thought a blog post would be a good idea so I can refer others to it later too.

The Context

As usual, this is some kind of backend (micro)service, and it will send email messages somehow. We will start with two implementations of message sending: the “current” version; which is synchronous, and a “new” version; which is async.

We’ll do a bit of setup to show how feature toggling can be done in three ways for this feature:

  1. Static: Configured on startup
  2. Dynamic: Check the toggle state on each send
  3. Dynamic: Check the toggle for a given message

Abstractions and Implementations

We have an interface called IMessageDispatcher which defines a single Send method, which returns a Task (or Promise, Future, etc. depending on your language.)

public interface IMessageDispatcher
{
    Task<SendResult> Send(Message message);
}

The two message sending implementations don’t matter, but we need the types to show the other code examples. Fill in the blanks if you want!

public class HttpMessageDispatcher : IMessageDispatcher
{
    // ...
}

public class QueueMessageDispatcher : IMessageDispatcher
{
    // ...
}

1. Static Configuration

The word static in this context means that we check the feature toggle’s state once on startup and pick an implementation. We don’t recheck the toggle state unless the service is restarted.

For instance, in an ASP.Net core application, you could change which service is registered into the container at startup like so:

public void ConfigureServices(IServiceCollection services)
{
    var toggleSource = new ToggleSource(/* ... */);

    if (toggleSource.IsActive(Toggles.AsyncMessageDispatch))
        services.AddTransient<IMessageDispatcher, QueueMessageDispatcher>();
    else
        services.AddTransient<IMessageDispatcher, HttpMessageDispatcher>();
}

Which means any class which takes in an instance of IMessageDispatcher doesn’t need to check the toggle state or worry about which implementation to use.

2. Dynamic Configuration

We can build on this abstraction to enable more flexibility, if we want to be able to change the toggle state while the service is running, without needing to restart it. To do this, we can implement another version of the IMessageDispatcher interface which will check the toggle state on each invocation of Send():

public class ToggleDispatcher : IMessageDispatcher
{
    private readonly Func<bool> _isToggleActive;
    private readonly IMessageDispatcher _queueSender;
    private readonly IMessageDispatcher _httpSender;

    public ToggleDispatcher(Func<bool> isToggleActive, IMessageDispatcher queueSender, IMessageDispatcher httpSender)
    {
        _isToggleActive = isToggleActive;
        _queueSender = queueSender;
        _httpSender = httpSender;
    }

    public Task<SendResult> Send(Message message)
    {
        var chosen = _isToggleActive()
            ? _queueSender
            : _httpSender;

        return chosen.Send(message);
    }
}

And in our startup class, we can change the service registration to use the new version. Note how we are now registering the two concrete versions into the container so that they can be resolved later by the ToggleDispatcher registration:

public void ConfigureServices(IServiceCollection services)
{
    var toggleSource = new ToggleSource(/* ... */);

    services.AddTransient<HttpMessageDispatcher>();
    services.AddTransient<QueueMessageDispatcher>();

    services.AddTransient<IMessageDispatcher>(context => new ToggleDispatcher(
        () => toggleSource.IsActive(Toggles.AsyncMessageDispatch),
        context.GetService<QueueMessageDispatcher>(),
        context.GetService<HttpMessageDispatcher>())
    );
}

3. Dynamic(er) Configuration

We can take this another step further too, if we want to be able to have a phased rollout of this new QueueMessageDispatcher, for example, based on the sender address. In this case, we can create another decorator which uses the individual message to make the decision. The only difference to the original ToggleDispatcher is that the first argument now also provides a Message object:

public class MessageBasedToggleDispatcher : IMessageDispatcher
{
    private readonly Func<Message, bool> _isToggleActive;
    private readonly IMessageDispatcher _queueSender;
    private readonly IMessageDispatcher _httpSender;

    public MessageBasedToggleDispatcher(Func<Message, bool> isToggleActive, IMessageDispatcher queueSender, IMessageDispatcher httpSender)
    {
        _isToggleActive = isToggleActive;
        _queueSender = queueSender;
        _httpSender = httpSender;
    }

    public Task<SendResult> Send(Message message)
    {
        var chosen = _isToggleActive(message)
            ? _queueSender
            : _httpSender;

        return chosen.Send(message);
    }
}

The startup registration is modified to pass the message property we care about to the ToggleSource, with the toggleSource.IsActive() call being responsible for what to do with the key we have passed in. Perhaps it does something like a consistent hash of the address, and if the value is above a certain threshold the toggle is active, or maybe it queries a whitelist of people who the toggle is enabled for.

public void ConfigureServices(IServiceCollection services)
{
    var toggleSource = new ToggleSource(/* ... */);

    services.AddTransient<HttpMessageDispatcher>();
    services.AddTransient<QueueMessageDispatcher>();

    services.AddTransient<IMessageDispatcher>(context => new MessageBasedToggleDispatcher(
        message => toggleSource.IsActive(Toggles.AsyncMessageDispatch, message.SenderAddress),
        context.GetService<QueueMessageDispatcher>(),
        context.GetService<HttpMessageDispatcher>())
    );
}

Conclusion

This method of branching is extremly flexible, as it allows us to use toggles to replace feature implementations, but also gives us lots of places where we can add other decorators to add functionality to the pipeline. For example, we could add an auditing decorator or one which implements the outbox pattern - and the calling code which depends only on IMessageDispatcher doesn’t need to care.

featuretoggles, c#, di, microservices

---

Configuring Consul DNS Forwarding in Alpine Linux

31 May 2019

Following on from the post the other day on setting up DNS forwarding to Consul with SystemD, I wanted also to show how to get Consul up and running under Alpine Linux, as it’s a little more awkward in some respects.

To start with, I am going to setup Consul as a service - I didn’t do this in the Ubuntu version, as there are plenty of useful articles about that already, but that is not the case with Alpine.

Run Consul

First, we need to get a version of Consul and install it into our system. This script downloads 1.5.1 from Hashicorp’s releases site, installs it to /usr/bin/consul, and creates a consul user and group to run the daemon with:

CONSUL_VERSION=1.5.1

curl -sSL https://releases.hashicorp.com/consul/${CONSUL_VERSION}/consul_${CONSUL_VERSION}_linux_amd64.zip -o /tmp/consul.zip

unzip /tmp/consul.zip
sudo install consul /usr/bin/consul

sudo addgroup -S consul
sudo adduser -S -D -h /var/consul -s /sbin/nologin -G consul -g consul consul

Next, we need to create the directories for the configuration and data to live in, and copy the init script and configuration file to those directories:

consul_dir=/etc/consul
data_dir=/srv/consul

sudo mkdir $consul_dir
sudo mkdir $data_dir
sudo chown consul:consul $data_dir

sudo mv /tmp/consul.sh /etc/init.d/consul
sudo chmod +x /etc/init.d/consul

sudo mv /tmp/consul.json $consul_dir/consul.json

The init script is pretty straight forward, but note that I am running the agent in this example in dev mode; don’t do this in production:

#!/sbin/openrc-run
CONSUL_LOG_FILE="/var/log/${SVCNAME}.log"

name=consul
description="A tool for service discovery, monitoring and configuration"
description_checkconfig="Verify configuration file"
daemon=/usr/bin/$name
daemon_user=$name
daemon_group=$name
consul_dir=/etc/consul
extra_commands="checkconfig"

start_pre() {
    checkpath -f -m 0644 -o ${SVCNAME}:${SVCNAME} "$CONSUL_LOG_FILE"
}

depend() {
    need net
    after firewall
}

checkconfig() {
    consul validate $consul_dir
}

start() {
    checkconfig || return 1

    ebegin "Starting ${name}"
        start-stop-daemon --start --quiet \
            -m --pidfile /var/run/${name}.pid \
            --user ${daemon_user} --group ${daemon_group} \
            -b --stdout $CONSUL_LOG_FILE --stderr $CONSUL_LOG_FILE \
            -k 027 --exec ${daemon} -- agent -dev -config-dir=$consul_dir
    eend $?
}

stop() {
    ebegin "Stopping ${name}"
        start-stop-daemon --stop --quiet \
            --pidfile /var/run/${name}.pid \
            --exec ${daemon}
    eend $?
}

Finally, a basic config file to launch consul is as follows:

{
    "data_dir": "/srv/consul/data",
    "client_addr": "0.0.0.0"
}

Now that all our scripts are in place, we can register Consul into the service manager, and start it:

sudo rc-update add consul
sudo rc-service consul start

You can check consul is up and running by using dig to get the address of the consul service itself:

dig @localhost -p 8600 consul.service.consul

Setup Local DNS with Unbound

Now that Consul is running, we need to configure a local DNS resolver to forward requests for the .consul domain to Consul. We will use Unbound as it works nicely on Alpine. It also has the wonderful feature of being able to send queries to a specific port, so no iptables rules needed this time!

The config file (/etc/unbound/unbound.conf) is all default values, with the exception of the last 5 lines, which let us forward DNS requests to a custom, and insecure, location:

#! /bin/bash

sudo apk add unbound

(
cat <<-EOF
server:
    verbosity: 1
    root-hints: /etc/unbound/root.hints
    trust-anchor-file: "/usr/share/dnssec-root/trusted-key.key"
    do-not-query-localhost: no
    domain-insecure: "consul"
stub-zone:
    name: "consul"
    stub-addr: [email protected]
EOF
) | sudo tee /etc/unbound/unbound.conf

sudo rc-update add unbound
sudo rc-service unbound start

We can validate this works again by using dig, but this time removing the port specification to hit 53 instead:

dig @localhost consul.service.consul

Configure DNS Resolution

Finally, we need to update /etc/resolv.conf so that other system tools such as ping and curl can resolve .consul addresses. This is a little more hassle on Alpine, as there are no head files we can push our nameserver entry into. Instead, we use dhclient which will let us prepend a custom nameserver (or multiple) when the interface is brought up, even when using DHCP:

#! /bin/bash

sudo apk add dhclient

(
cat <<-EOF
option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
send host-name = gethostname();
request subnet-mask, broadcast-address, time-offset, routers,
        domain-name, domain-name-servers, domain-search, host-name,
        dhcp6.name-servers, dhcp6.domain-search, dhcp6.fqdn, dhcp6.sntp-servers,
        netbios-name-servers, netbios-scope, interface-mtu,
        rfc3442-classless-static-routes, ntp-servers;
prepend domain-name-servers 127.0.0.1;
EOF
) | sudo tee /etc/dhcp/dhclient.conf

sudo rm /etc/resolv.conf # hack due to it dhclient making an invalid `chown` call.
sudo rc-service networking restart

The only thing of interest here is the little hack: we delete the /etc/resolv.conf before restarting the networking service, as if you don’t do this, you get errors about “chmod invalid option resource=…”.

We can varify everything works in the same way we did on Ubuntu; curl to both a .consul and a public address:

$ curl -s -o /dev/null -w "%{http_code}\n" http://consul.service.consul:8500/ui/
200

$ curl -s -o /dev/null -w "%{http_code}\n" http://google.com
301

End

This was a bit easier to get started with than the Ubuntu version as I knew what I was trying to accomplish this time - however making a good init.d script was a bit more hassle, and the error from chmod took some time to track down.

infrastructure, consul, alpine, dns

---

Configuring Consul DNS Forwarding in Ubuntu 16.04

29 May 2019

DEPRECATED - This doesn’t work properly

Please see this post for an updated version which works!


One of the advantages of using Consul for service discovery is that besides an HTTP API, you can also query it by DNS.

The DNS server is listening on port 8600 by default, and you can query both A records or SRV records from it. SRV records are useful as they contain additional properties (priority, weight and port), and you can get multiple records back from a single query, letting you do load balancing client side:

$ dig @localhost -p 8600 consul.service.consul SRV +short

1 10 8300 vagrant1.node.dc1.consul.
1 14 8300 vagrant2.node.dc1.consul.
2 100 8300 vagrant3.node.dc1.consul.

A Records are also useful, as it means we should be able to treat services registered to Consul like any other domain - but it doesn’t work:

$ curl http://consul.service.consul:8500
curl: (6) Could not resolve host: consul.service.consul

The reason for this is that the system’s built-in DNS resolver doesn’t know how to query Consul. We can, however, configure it to forward any *.consul requests to Consul.

Solution - Forward DNS queries to Consul

As I usually target Ubuntu based machines, this means configuring systemd-resolved to forward to Consul. However, we want to keep Consul listening on it’s default port (8600), and systemd-resolved can only forward requests to port 53, so we need also to configure iptables to redirect the requests.

The steps are as follows:

  1. Configure systemd-resolved to forward .consul TLD queries to the local consul agent
  2. Configure iptables to redirect 53 to 8600

So let’s get to it!

1. Make iptables persistent

IPTables configuration changes don’t persist through reboots, so the easiest way to solve this is with the iptables-persistent package.

Typically I am scripting machines (using [Packer] or [Vagrant]), so I configure the install to be non-interactive:

echo iptables-persistent iptables-persistent/autosave_v4 boolean false | sudo debconf-set-selections
echo iptables-persistent iptables-persistent/autosave_v6 boolean false | sudo debconf-set-selections

sudo DEBIAN_FRONTEND=noninteractive apt install -yq iptables-persistent

2. Update Systemd-Resolved

The file to change is /etc/systemd/resolved.conf. By default it looks like this:

[Resolve]
#DNS=
#FallbackDNS=8.8.8.8 8.8.4.4 2001:4860:4860::8888 2001:4860:4860::8844
#Domains=
#LLMNR=yes
#DNSSEC=no

We need to change the DNS and Domains lines - either editing the file by hand, or scripting a replacement with sed:

sudo sed -i 's/#DNS=/DNS=127.0.0.1/g; s/#Domains=/Domains=~consul/g' /etc/systemd/resolved.conf

The result of which is the file now reading like this:

[Resolve]
DNS=127.0.0.1
#FallbackDNS=8.8.8.8 8.8.4.4 2001:4860:4860::8888 2001:4860:4860::8844
Domains=~consul
#LLMNR=yes
#DNSSEC=no

By specifying the Domains as ~consul, we are telling resolvd to forward requests for the consul TLD to the server specified in the DNS line.

3. Configure Resolvconf too

For compatibility with some applications (e.g. curl and ping), we also need to update /etc/resolv.conf to specify our local nameserver. You do this not by editing the file directly!

Instead, we need to add nameserver 127.0.0.1 to /etc/resolvconf/resolv.conf.d/head. Again, I will script this, and as we need sudo to write to the file, the easiest way is to use tee to append the line and then run resolvconf -u to apply the change:

echo "nameserver 127.0.0.1" | sudo tee --append /etc/resolvconf/resolv.conf.d/head
sudo resolvconf -u

Configure iptables

Finally, we need to configure iptables so that when systemd-resolved sends a DNS query to localhost on port 53, it gets redirected to port 8600. We’ll do this for both TCP and UDP requests, and then use netfilter-persistent to make the rules persistent:

sudo iptables -t nat -A OUTPUT -d localhost -p udp -m udp --dport 53 -j REDIRECT --to-ports 8600
sudo iptables -t nat -A OUTPUT -d localhost -p tcp -m tcp --dport 53 -j REDIRECT --to-ports 8600

sudo netfilter-persistent save

Verification

First, we can test that both Consul and Systemd-Resolved return an address for a consul service:

$ dig @localhost -p 8600 consul.service.consul +short
10.0.2.15

$ dig @localhost consul.service.consul +short
10.0.2.15

And now we can try using curl to verify that we can resolve consul domains and normal domains still:

$ curl -s -o /dev/null -w "%{http_code}\n" http://consul.service.consul:8500/ui/
200

$ curl -s -o /dev/null -w "%{http_code}\n" http://google.com
301

End

There are also guides available on how to do this on Hashicorp’s website, covering other DNS resolvers too (such as BIND, Dnsmasq, Unbound).

infrastructure, dns, consul

---