sockets_linux.go 1.34 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// +build linux

package sockets

import (
	"net"
	"sync"

	activation "github.com/coreos/go-systemd/activation"
	logging "github.com/ipfs/go-log"
	manet "github.com/multiformats/go-multiaddr-net"
)

var log = logging.Logger("socket-activation")

Steven Allen's avatar
Steven Allen committed
16 17 18 19
var (
	socketsMu sync.Mutex
	sockets   map[string][]manet.Listener
)
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

func initSockets() {
	if sockets != nil {
		return
	}
	nlisteners, err := activation.ListenersWithNames()
	// Do this before checking the error. We need this to be non-nil so we
	// don't try again.
	sockets = make(map[string][]manet.Listener, len(nlisteners))
	if err != nil {
		log.Errorf("error parsing systemd sockets: %s", err)
		return
	}
	for name, nls := range nlisteners {
		mls := make([]manet.Listener, 0, len(nls))
		for _, nl := range nls {
			ml, err := manet.WrapNetListener(nl)
			if err != nil {
				log.Errorf("error converting a systemd-socket to a multiaddr listener: %s", err)
				nl.Close()
				continue
			}
			mls = append(mls, ml)
		}
		sockets[name] = mls
	}
}

func mapListeners(nls []net.Listener) ([]manet.Listener, error) {
	mls := make([]manet.Listener, len(nls))
	return mls, nil
}

// TakeSockets takes the sockets associated with the given name.
func TakeSockets(name string) ([]manet.Listener, error) {
	socketsMu.Lock()
	defer socketsMu.Unlock()
	initSockets()

	s := sockets[name]
	delete(sockets, name)

	return s, nil
}