about summary refs log tree commit diff stats
path: root/internal/listenfd/listenfd.go
blob: 7d020b05d4e7913d087e8a385b305e52f03a3a64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package listenfd

import (
	"net"
	"os"
	"strconv"

	"github.com/pkg/errors"
)

const fdStart = 3

func GetListener(i uint64) (net.Listener, error) {
	lfds, present := os.LookupEnv("LISTEN_FDS")
	if !present {
		return nil, nil
	}

	fds, err := strconv.ParseUint(lfds, 10, 32)
	if err != nil {
		return nil, errors.Wrap(err, "could not parse LISTEN_FDS")
	}
	if i >= fds {
		return nil, errors.Errorf("only %d fds available, requested index %d", fds, i)
	}

	l, err := net.FileListener(os.NewFile(uintptr(i+fdStart), ""))
	if err != nil {
		return nil, errors.Wrap(err, "could not create listener")
	}

	return l, nil
}