Integration of a Go service with systemd: socket activation

Vincent Bernat

In a pre­vi­ous post, I high­lighted some use­ful fea­tures of sys­temd when writ­ing a ser­vice in Go, no­tably to sig­nal readi­ness and prove live­ness. An­other in­ter­est­ing bit is socket ac­ti­va­tion: sys­temd lis­tens on be­half of the ap­pli­ca­tion and, on in­com­ing traf­fic, starts the ser­vice with a copy of the lis­ten­ing socket. Lennart Po­et­ter­ing de­tails in a blog post:

If a ser­vice dies, its lis­ten­ing socket stays around, not los­ing a sin­gle mes­sage. Af­ter a restart of the crashed ser­vice it can con­tinue right where it left off. If a ser­vice is up­graded we can restart the ser­vice while keep­ing around its sock­ets, thus en­sur­ing the ser­vice is con­tin­u­ously re­spon­sive. Not a sin­gle con­nec­tion is lost dur­ing the upgrade.

This is one so­lu­tion to get zero-down­time de­ploy­ment for your ap­pli­ca­tion. An­other up­side is you can run your dae­mon with less priv­i­leges—los­ing rights is a dif­fi­cult task in Go.1

The basics#

Let’s take back our nifty 404-only web server:

package main

import (
    "log"
    "net"
    "net/http"
)

func main() {
    listener, err := net.Listen("tcp", ":8081")
    if err != nil {
        log.Panicf("cannot listen: %s", err)
    }
    http.Serve(listener, nil)
}

Here is the socket-ac­ti­vated ver­sion, us­ing go-systemd:

package main

import (
    "log"
    "net/http"

    "github.com/coreos/go-systemd/activation"
)

func main() {
    listeners, err := activation.Listeners(true) // ❶
    if err != nil {
        log.Panicf("cannot retrieve listeners: %s", err)
    }
    if len(listeners) != 1 {
        log.Panicf("unexpected number of socket activation (%d != 1)",
            len(listeners))
    }
    http.Serve(listeners[0], nil) // ❷
}

In ❶, we re­trieve the lis­ten­ing sock­ets pro­vided by sys­temd. In ❷, we use the first one to serve HTTP re­quests. Let’s test the re­sult with systemd-socket-activate:2

$ go build 404.go
$ systemd-socket-activate -l 8000 ./404
Listening on [::]:8000 as 3.

In an­other ter­mi­nal, we can make some re­quests to the service:

$ curl '[::1]':8000
404 page not found
$ curl '[::1]':8000
404 page not found

For a proper in­te­gra­tion with sys­temd, you need two files:

  • a socket unit for the lis­ten­ing socket; and
  • a ser­vice unit for the as­so­ci­ated service.

We can use the fol­low­ing socket unit, 404.socket:

[Socket]
ListenStream = 8000
BindIPv6Only = both

[Install]
WantedBy = sockets.target

The systemd.​socket(5) man­ual page de­scribes the avail­able op­tions. BindIPv6Only = both is ex­plic­itly spec­i­fied be­cause the de­fault value is dis­tri­bu­tion-de­pen­dent. As for the ser­vice unit, we can use the fol­low­ing one, 404.​service:

[Unit]
Description = 404 micro-service

[Service]
ExecStart = /usr/bin/404

sys­temd knows the two files work to­gether be­cause they share the same pre­fix. Once the files are in /etc/​systemd/​system, ex­e­cute systemctl daemon-reload and systemctl start 404.​socket. Your ser­vice is ready to ac­cept con­nections!

Handling of existing connections#

Our 404 ser­vice has a ma­jor short­com­ing: ex­ist­ing con­nec­tions are abruptly killed when the dae­mon is stopped or restarted. Let’s fix that!

Waiting a few seconds for existing connections#

We can in­clude a short grace pe­riod for con­nec­tions to ter­mi­nate, then kill re­main­ing ones:

// On signal, gracefully shut down the server and wait 5
// seconds for current connections to stop.
done := make(chan struct{})
quit := make(chan os.Signal, 1)
server := &http.Server{}
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

go func() {
    <-quit
    log.Println("server is shutting down")
    ctx, cancel := context.WithTimeout(context.Background(),
        5*time.Second)
    defer cancel()
    server.SetKeepAlivesEnabled(false)
    if err := server.Shutdown(ctx); err != nil {
        log.Panicf("cannot gracefully shut down the server: %s", err)
    }
    close(done)
}()

// Start accepting connections.
server.Serve(listeners[0])

// Wait for existing connections before exiting.
<-done

Upon re­cep­tion of a ter­mi­na­tion sig­nal, the gor­ou­tine would re­sume and sched­ule a shut­down of the service:

Shutdown() grace­fully shuts down the server with­out in­ter­rupt­ing any ac­tive con­nec­tions. Shutdown() works by first clos­ing all open lis­ten­ers, then clos­ing all idle con­nec­tions, and then wait­ing in­def­i­nitely for con­nec­tions to re­turn to idle and then shut down.

While restart­ing, new con­nec­tions are not ac­cepted: they sit in the lis­ten queue as­so­ci­ated with the socket. This queue is bounded and its size can be con­fig­ured with the Backlog di­rec­tive in the socket unit. Its de­fault value is 128. You may keep this value, even when your ser­vice is ex­pect­ing to re­ceive many con­nec­tions per sec­ond. When this value is ex­ceeded, in­com­ing con­nec­tions are silently dropped. The client should au­to­mat­i­cally retry to con­nect. On Linux, by de­fault, it will retry 5 times (tcp_​syn_​retries) in about 3 min­utes. This is a nice way to avoid the herd ef­fect you would ex­pe­ri­ence on restart if you in­creased the lis­ten queue to some high value.

Waiting longer for existing connections#

If you want to wait for a very long time for ex­ist­ing con­nec­tions to stop, you do not want to ig­nore new con­nec­tions for sev­eral min­utes. There is a very sim­ple trick: ask sys­temd to not kill any process on stop. With KillMode = none, only the stop com­mand is ex­e­cuted and all ex­ist­ing pro­cesses are left undisturbed:

[Unit]
Description = slow 404 micro-service

[Service]
ExecStart = /usr/bin/404
ExecStop  = /bin/kill $MAINPID
KillMode  = none

If you restart the ser­vice, the cur­rent process grace­fully shuts down for as long as needed and sys­temd spawns im­me­di­ately a new in­stance ready to serve in­com­ing re­quests with its own copy of the lis­ten­ing socket. On the other hand, we lose the abil­ity to wait for the ser­vice to come to a full stop—ei­ther by it­self or force­fully af­ter a time­out with SIGKILL.

Up­date (2021-01)

KillMode=​none is now dep­re­cated. In ad­di­tion to the be­low al­ter­na­tive, it is pos­si­ble to pass the cur­rently ac­tive con­nec­tions to sys­temd with the sd_​pid_​notify_​with_​fds() func­tion. Then, the new process needs some logic to han­dle them. Un­for­tu­nately, this is not an easy task as you also need to se­ri­al­ize the as­so­ci­ated state. More­over, the func­tion is not im­ple­mented in go-systemd.

Waiting longer for existing connections (alternative)#

An al­ter­na­tive to the pre­vi­ous so­lu­tion is to make sys­temd be­lieve your ser­vice died dur­ing reload.

done := make(chan struct{})
quit := make(chan os.Signal, 1)
server := &http.Server{}
signal.Notify(quit,
    // for reload:
    syscall.SIGHUP,
    // for stop or full restart:
    syscall.SIGINT, syscall.SIGTERM)
go func() {
    sig := <-quit
    switch sig {
    case syscall.SIGINT, syscall.SIGTERM:
        // Shutdown with a time limit.
        log.Println("server is shutting down")
        ctx, cancel := context.WithTimeout(context.Background(),
            15*time.Second)
        defer cancel()
        server.SetKeepAlivesEnabled(false)
        if err := server.Shutdown(ctx); err != nil {
            log.Panicf("cannot gracefully shut down the server: %s", err)
        }
    case syscall.SIGHUP: // ❶
        // Execute a short-lived process and asks systemd to
        // track it instead of us.
        log.Println("server is reloading")
        pid := detachedSleep()
        daemon.SdNotify(false, fmt.Sprintf("MAINPID=%d", pid))
        time.Sleep(time.Second) // Wait a bit for systemd to check the PID

        // Wait without a limit for current connections to stop.
        server.SetKeepAlivesEnabled(false)
        if err := server.Shutdown(context.Background()); err != nil {
            log.Panicf("cannot gracefully shut down the server: %s", err)
        }
    }
    close(done)
}()

// Serve requests with a slow handler.
server.Handler = http.HandlerFunc(
    func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(10 * time.Second)
        http.Error(w, "404 not found", http.StatusNotFound)
    })
server.Serve(listeners[0])

// Wait for all connections to terminate.
<-done
log.Println("server terminated")

The main dif­fer­ence is the han­dling of the SIGHUP sig­nal in ❶: a short-lived de­coy process is spawned and sys­temd is told to track it. When it dies, sys­temd will start a new in­stance. This method is a bit hacky: sys­temd needs the de­coy process to be a child of PID 1 but Go can­not eas­ily de­tach on its own. There­fore, we lever­age a short Python helper, wrapped in a detachedSleep() function:3

// detachedSleep spawns a detached process sleeping
// one second and returns its PID.
func detachedSleep() uint64 {
    py := `
import os
import time

pid = os.fork()
if pid == 0:
    for fd in {0, 1, 2}:
        os.close(fd)
    time.sleep(1)
else:
    print(pid)
`
    cmd := exec.Command("/usr/bin/python3", "-c", py)
    out, err := cmd.Output()
    if err != nil {
        log.Panicf("cannot execute sleep command: %s", err)
    }
    pid, err := strconv.ParseUint(strings.TrimSpace(string(out)), 10, 64)
    if err != nil {
        log.Panicf("cannot parse PID of sleep command: %s", err)
    }
    return pid
}

Dur­ing reload, there may be a small pe­riod dur­ing which both the new and the old pro­cesses ac­cept in­com­ing re­quests. If you do not want that, you can move the cre­ation of the short-lived process out­side the gor­ou­tine, af­ter server.​Serve(), or im­ple­ment some syn­chro­niza­tion mech­a­nism. There is also a pos­si­ble race-con­di­tion when we tell sys­temd to track an­other PID—see PR #7816.

The 404.​service unit needs an update:

[Unit]
Description = slow 404 micro-service

[Service]
ExecStart    = /usr/bin/404
ExecReload   = /bin/kill -HUP $MAINPID
Restart      = always
NotifyAccess = main
KillMode     = process

Each ad­di­tional di­rec­tive is sig­nificant:

  • ExecReload tells how to reload the process—by send­ing SIGHUP.
  • Restart tells to restart the process if it stops “un­ex­pect­edly,” no­tably on reload.4
  • NotifyAccess spec­i­fies which process can send no­ti­fi­ca­tions, like a PID change.
  • KillMode tells to only kill the main iden­ti­fied process—oth­ers are left un­touched.

Zero-downtime deployment?#

Zero-down­time de­ploy­ment is a dif­fi­cult en­deavor on Linux. For ex­am­ple, HAProxy had a long list of hacks un­til a proper—and com­plex—so­lu­tion was im­ple­mented in HAproxy 1.8. How do we fare with our sim­ple im­ple­mentation?

From the ker­nel point of view, there is only one socket with a unique lis­ten queue. This socket is as­so­ci­ated to sev­eral file de­scrip­tors: one in sys­temd and one in the cur­rent process. The socket stays alive as long as there is at least one file de­scrip­tor. An in­com­ing con­nec­tion is put by the ker­nel in the lis­ten queue and can be de­queued from any file de­scrip­tor with the accept() syscall. There­fore, this ap­proach ac­tu­ally achieves zero-down­time de­ploy­ment: no in­com­ing con­nec­tion is rejected.

By con­trast, HAProxy was us­ing sev­eral dif­fer­ent sock­ets lis­ten­ing to the same ad­dresses, thanks to the SO_​REUSEPORT op­tion.5 Each socket gets its own lis­ten­ing queue and the ker­nel bal­ances in­com­ing con­nec­tions be­tween each queue. When a socket gets closed, the con­tent of its queue is lost. If an in­com­ing con­nec­tion was sit­ting here, it would re­ceive a re­set. An el­e­gant patch for Linux to sig­nal a socket should not re­ceive new con­nec­tions was re­jected. HAProxy 1.8 is now re­cy­cling ex­ist­ing sock­ets by send­ing them to the new pro­cesses through a Unix socket.

I hope this post and the pre­vi­ous one show how sys­temd is a good side­kick for a Go ser­vice: readi­ness, live­ness and socket ac­ti­va­tion are some of the use­ful fea­tures you can get to build a more re­li­able ap­plication.

Addendum: decoy process using Go#

Up­date (2018-03)

On /r/golang, it was pointed out to me that, in the ver­sion where sys­temd is track­ing a de­coy, the helper can be re­placed by in­vok­ing the main ex­e­cutable. By re­ly­ing on a change of en­vi­ron­ment, it as­sumes the role of the de­coy. Here is such an im­ple­men­ta­tion re­plac­ing the detachedSleep() function:

func init() {
    // As early as possible, check if we should be the decoy.
    state := os.Getenv("__SLEEPY")
    os.Unsetenv("__SLEEPY")
    switch state {
    case "1":
        // First step, fork again.
        execPath := self()
        child, err := os.StartProcess(
            execPath,
            []string{execPath},
            &os.ProcAttr{
                Env: append(os.Environ(), "__SLEEPY=2"),
            })
        if err != nil {
            log.Panicf("cannot execute sleep command: %s", err)
        }

        // Advertise child's PID and exit. Child will be
        // orphaned and adopted by PID 1.
        fmt.Printf("%d", child.Pid)
        os.Exit(0)
    case "2":
        // Sleep and exit.
        time.Sleep(time.Second)
        os.Exit(0)
    }
    // Not the sleepy helper. Business as usual.
}

// self returns the absolute path to ourselves. This relies on
// /proc/self/exe which may be a symlink to a deleted path (for
// example, during an upgrade).
func self() string {
    execPath, err := os.Readlink("/proc/self/exe")
    if err != nil {
        log.Panicf("cannot get self path: %s", err)
    }
    execPath = strings.TrimSuffix(execPath, " (deleted)")
    return execpath
}

// detachedSleep spawns a detached process sleeping one second and
// returns its PID. A full daemonization is not needed as the process
// is short-lived.
func detachedSleep() uint64 {
    cmd := exec.Command(self())
    cmd.Env = append(os.Environ(), "__SLEEPY=1")
    out, err := cmd.Output()
    if err != nil {
        log.Panicf("cannot execute sleep command: %s", err)
    }
    pid, err := strconv.ParseUint(strings.TrimSpace(string(out)), 10, 64)
    if err != nil {
        log.Panicf("cannot parse PID of sleep command: %s", err)
    }
    return pid
}

Addendum: identifying sockets by name#

For a given ser­vice, sys­temd can pro­vide sev­eral sock­ets. To iden­tify them, it is pos­si­ble to name them. Let’s sup­pose we also want to re­turn 403 er­ror codes from the same ser­vice but on a dif­fer­ent port. We add an ad­di­tional socket unit def­i­ni­tion, 403.​socket, linked to the same 404.​service job:

[Socket]
ListenStream = 8001
BindIPv6Only = both
Service      = 404.service

[Install]
WantedBy=sockets.target

Un­less over­rid­den with FileDescriptorName, the name of the socket is the name of the unit: 403.​socket. go-sys­temd pro­vides the ListenersWithNames() func­tion to fetch a map from names to lis­ten­ing sockets:

package main

import (
    "log"
    "net/http"
    "sync"

    "github.com/coreos/go-systemd/activation"
)

func main() {
    var wg sync.WaitGroup

    // Map socket names to handlers.
    handlers := map[string]http.HandlerFunc{
        "404.socket": http.NotFound,
        "403.socket": func(w http.ResponseWriter, r *http.Request) {
            http.Error(w, "403 forbidden",
                http.StatusForbidden)
        },
    }

    // Get listening sockets.
    listeners, err := activation.ListenersWithNames(true)
    if err != nil {
        log.Panicf("cannot retrieve listeners: %s", err)
    }

    // For each listening socket, spawn a goroutine
    // with the appropriate handler.
    for name := range listeners {
        for idx := range listeners[name] {
            wg.Add(1)
            go func(name string, idx int) {
                defer wg.Done()
                http.Serve(
                    listeners[name][idx],
                    handlers[name])
            }(name, idx)
        }
    }

    // Wait for all goroutines to terminate.
    wg.Wait()
}

Let’s build the ser­vice and run it with systemd-socket-activate:

$ go build 404.go
$ systemd-socket-activate -l 8000 -l 8001 \
>                         --fdname=404.socket:403.socket \
>                         ./404
Listening on [::]:8000 as 3.
Listening on [::]:8001 as 4.

In an­other con­sole, we can make a re­quest for each endpoint:

$ curl '[::1]':8000
404 page not found
$ curl '[::1]':8001
403 forbidden