tableflip: github.com/cloudflare/tableflip Index | Examples | Files

package tableflip

import "github.com/cloudflare/tableflip"

Package tableflip implements zero downtime upgrades.

An upgrade spawns a new copy of argv[0] and passes file descriptors of used listening sockets to the new process. The old process exits once the new process signals readiness. Thus new code can use sockets allocated in the old process. This is similar to the approach used by nginx, but as a library.

At any point in time there are one or two processes, with at most one of them in non-ready state. A successful upgrade fully replaces all old configuration and code.

To use this library with systemd you need to use the PIDFile option in the service file.

[Unit]
Description=Service using tableflip

[Service]
ExecStart=/path/to/binary -some-flag /path/to/pid-file
ExecReload=/bin/kill -HUP $MAINPID
PIDFile=/path/to/pid-file

Then pass /path/to/pid-file to New. You can use systemd-run to test your implementation:

systemd-run --user -p PIDFile=/path/to/pid-file /path/to/binary

systemd-run will print a unit name, which you can use with systemctl to inspect the service.

NOTES:

Requires at least Go 1.9, since there is a race condition on the pipes used for communication between parent and child.

If you're seeing "can't start process: no such file or directory", you're probably using "go run main.go", for graceful reloads to work, you'll need use "go build main.go".

This shows how to use the upgrader with the graceful shutdown facilities of net/http.

Code:

var (
    listenAddr = flag.String("listen", "localhost:8080", "`Address` to listen on")
    pidFile    = flag.String("pid-file", "", "`Path` to pid file")
)

flag.Parse()
log.SetPrefix(fmt.Sprintf("%d ", os.Getpid()))

upg, err := tableflip.New(tableflip.Options{
    PIDFile: *pidFile,
})
if err != nil {
    panic(err)
}
defer upg.Stop()

// Do an upgrade on SIGHUP
go func() {
    sig := make(chan os.Signal, 1)
    signal.Notify(sig, syscall.SIGHUP)
    for range sig {
        err := upg.Upgrade()
        if err != nil {
            log.Println("Upgrade failed:", err)
        }
    }
}()

ln, err := upg.Fds.Listen("tcp", *listenAddr)
if err != nil {
    log.Fatalln("Can't listen:", err)
}

server := http.Server{
    // Set timeouts, etc.
}

go func() {
    err := server.Serve(ln)
    if err != http.ErrServerClosed {
        log.Println("HTTP server:", err)
    }
}()

log.Printf("ready")
if err := upg.Ready(); err != nil {
    panic(err)
}
<-upg.Exit()

// Make sure to set a deadline on exiting the process
// after upg.Exit() is closed. No new upgrades can be
// performed if the parent doesn't exit.
time.AfterFunc(30*time.Second, func() {
    log.Println("Graceful shutdown timed out")
    os.Exit(1)
})

// Wait for connections to drain.
server.Shutdown(context.Background())

This shows how to use the Upgrader with a listener based service.

Code:

var (
    listenAddr = flag.String("listen", "localhost:8080", "`Address` to listen on")
    pidFile    = flag.String("pid-file", "", "`Path` to pid file")
)

flag.Parse()
log.SetPrefix(fmt.Sprintf("%d ", os.Getpid()))

upg, err := tableflip.New(tableflip.Options{
    PIDFile: *pidFile,
})
if err != nil {
    panic(err)
}
defer upg.Stop()

// Do an upgrade on SIGHUP
go func() {
    sig := make(chan os.Signal, 1)
    signal.Notify(sig, syscall.SIGHUP)
    for range sig {
        err := upg.Upgrade()
        if err != nil {
            log.Println("upgrade failed:", err)
        }
    }
}()

ln, err := upg.Fds.Listen("tcp", *listenAddr)
if err != nil {
    log.Fatalln("Can't listen:", err)
}

go func() {
    defer ln.Close()

    log.Printf("listening on %s", ln.Addr())

    for {
        c, err := ln.Accept()
        if err != nil {
            return
        }

        go func() {
            c.SetDeadline(time.Now().Add(time.Second))
            c.Write([]byte("It is a mistake to think you can solve any major problems just with potatoes.\n"))
            c.Close()
        }()
    }
}()

log.Printf("ready")
if err := upg.Ready(); err != nil {
    panic(err)
}
<-upg.Exit()

Index

Examples

Package Files

child.go doc.go env.go fds.go parent.go process.go upgrader.go

Constants

const DefaultUpgradeTimeout time.Duration = time.Minute

DefaultUpgradeTimeout is the duration before the Upgrader kills the new process if no readiness notification was received.

type Conn Uses

type Conn interface {
    net.Conn
    syscall.Conn
}

Conn can be shared between processes.

type Fds Uses

type Fds struct {
    // contains filtered or unexported fields
}

Fds holds all file descriptors inherited from the parent process.

func (*Fds) AddConn Uses

func (f *Fds) AddConn(network, addr string, conn Conn) error

AddConn adds a connection.

It is safe to close conn after calling this method.

func (*Fds) AddFile Uses

func (f *Fds) AddFile(name string, file *os.File) error

AddFile adds a file.

As of Go 1.11, file will be in blocking mode after this call.

func (*Fds) AddListener Uses

func (f *Fds) AddListener(network, addr string, ln Listener) error

AddListener adds a listener.

It is safe to close ln after calling the method. Any existing listener with the same address is overwitten.

func (*Fds) Conn Uses

func (f *Fds) Conn(network, addr string) (net.Conn, error)

Conn returns an inherited connection or nil.

It is safe to close the returned Conn.

func (*Fds) File Uses

func (f *Fds) File(name string) (*os.File, error)

File returns an inherited file or nil.

The descriptor may be in blocking mode.

func (*Fds) Listen Uses

func (f *Fds) Listen(network, addr string) (net.Listener, error)

Listen returns a listener inherited from the parent process, or creates a new one.

func (*Fds) Listener Uses

func (f *Fds) Listener(network, addr string) (net.Listener, error)

Listener returns an inherited listener or nil.

It is safe to close the returned listener.

type Listener Uses

type Listener interface {
    net.Listener
    syscall.Conn
}

Listener can be shared between processes.

type Options Uses

type Options struct {
    // Time after which an upgrade is considered failed. Defaults to
    // DefaultUpgradeTimeout.
    UpgradeTimeout time.Duration
    // The PID of a ready process is written to this file.
    PIDFile string
}

Options control the behaviour of the Upgrader.

type Upgrader Uses

type Upgrader struct {
    Fds *Fds
    // contains filtered or unexported fields
}

Upgrader handles zero downtime upgrades and passing files between processes.

func New Uses

func New(opts Options) (upg *Upgrader, err error)

New creates a new Upgrader. Files are passed from the parent and may be empty.

Only the first call to this function will succeed.

func (*Upgrader) Exit Uses

func (u *Upgrader) Exit() <-chan struct{}

Exit returns a channel which is closed when the process should exit.

func (*Upgrader) Ready Uses

func (u *Upgrader) Ready() error

Ready signals that the current process is ready to accept connections. It must be called to finish the upgrade.

All fds which were inherited but not used are closed after the call to Ready.

func (*Upgrader) Stop Uses

func (u *Upgrader) Stop()

Stop prevents any more upgrades from happening, and closes the exit channel.

func (*Upgrader) Upgrade Uses

func (u *Upgrader) Upgrade() error

Upgrade triggers an upgrade.

Package tableflip imports 14 packages (graph). Updated 2018-10-25. Refresh now. Tools for package owners.