From 8362e7cc103e5f53c2b3658df646f1bbd2f65b7b Mon Sep 17 00:00:00 2001 From: Brandon Philips Date: Fri, 3 Jan 2014 18:06:34 -0800 Subject: [PATCH] Move listenfd to utility package Docker-DCO-1.1-Signed-off-by: Brandon Philips (github: philips) --- systemd/listendfd.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 systemd/listendfd.go diff --git a/systemd/listendfd.go b/systemd/listendfd.go new file mode 100644 index 0000000..a8fdb09 --- /dev/null +++ b/systemd/listendfd.go @@ -0,0 +1,41 @@ +package systemd + +import ( + "errors" + "fmt" + "net" + "strconv" + + "github.com/coreos/go-systemd/activation" +) + +// ListenFD returns the specified socket activated files as a slice of +// net.Listeners or all of the activated files if "*" is given. +func ListenFD(addr string) ([]net.Listener, error) { + files := activation.Files(false) + if files == nil || len(files) == 0 { + return nil, errors.New("No sockets found") + } + + fdNum, _ := strconv.Atoi(addr) + fdOffset := fdNum - 3 + if (addr != "*") && (len(files) < int(fdOffset)+1) { + return nil, errors.New("Too few socket activated files passed in") + } + + // socket activation + listeners := make([]net.Listener, len(files)) + for i, f := range files { + var err error + listeners[i], err = net.FileListener(f) + if err != nil { + return nil, fmt.Errorf("Error setting up FileListener for fd %d: %s", f.Fd(), err.Error()) + } + } + + if addr == "*" { + return listeners, nil + } + + return []net.Listener{listeners[fdOffset]}, nil +}