mdsvc: use Unix socket for registration

Using allows Unix socket allows for limiting who can
register/unregister containers by setting proper
permissions on the socket.

Fixes #437
This commit is contained in:
Eugene Yakubovich
2015-03-26 11:39:19 -07:00
parent d06e5eb6f6
commit f030f05f02
4 changed files with 130 additions and 125 deletions
+1 -5
View File
@@ -37,6 +37,7 @@ const (
MetadataServiceIP = "169.254.169.255"
MetadataServicePubPort = 80
MetadataServicePrvPort = 2375
MetadataServiceRegSock = "/run/rkt/metadata-svc.sock"
)
// Stage1ImagePath returns the path where the stage1 app image (unpacked ACI) is rooted,
@@ -95,11 +96,6 @@ func ImageManifestPath(root string, imageID types.Hash) string {
return filepath.Join(AppImagePath(root, imageID), aci.ManifestFile)
}
// MetadataServicePrivateURL returns the private URL used to host the metadata service
func MetadataServicePrivateURL() string {
return fmt.Sprintf("http://127.0.0.1:%v", MetadataServicePrvPort)
}
// MetadataServicePublicURL returns the public URL used to host the metadata service
func MetadataServicePublicURL() string {
return fmt.Sprintf("http://%v:%v", MetadataServiceIP, MetadataServicePubPort)
+84 -84
View File
@@ -27,8 +27,11 @@ import (
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
@@ -61,7 +64,7 @@ var (
flagSrcAddrs string
flagNoIdle bool
exitCh chan bool
exitCh = make(chan os.Signal, 1)
)
const (
@@ -75,7 +78,7 @@ func init() {
cmdMetadataService.Flags.BoolVar(&flagNoIdle, "no-idle", false, "exit when last container is unregistered")
}
func modifyIPTables(action, port string) error {
func modifyIPTables(action string) error {
return exec.Command(
"iptables",
"-t", "nat",
@@ -84,7 +87,7 @@ func modifyIPTables(action, port string) error {
"-d", common.MetadataServiceIP,
"--dport", strconv.Itoa(common.MetadataServicePubPort),
"-j", "REDIRECT",
"--to-port", port,
"--to-port", strconv.Itoa(flagListenPort),
).Run()
}
@@ -99,13 +102,6 @@ func queryValue(u *url.URL, key string) string {
func handleRegisterContainer(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
remoteIP := strings.Split(r.RemoteAddr, ":")[0]
if _, ok := containerByIP[remoteIP]; ok {
// not allowed from container IP
w.WriteHeader(http.StatusForbidden)
return
}
uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
if err != nil {
w.WriteHeader(http.StatusNotFound)
@@ -159,20 +155,23 @@ func handleUnregisterContainer(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
if flagNoIdle && len(containerByUID) == 0 {
exitCh <- true
// TODO(eyakubovich): this is very racy
// It's possible for last container to get unregistered
// and svc gets flagged to shutdown. Then another container
// starts to launch, sees that port is in use and doesn't
// start metadata svc only for this one to exit a moment later.
// However, --no-idle is meant for demos and having a single
// container spawn up (via --spawn-metadata-svc). The design
// of metadata svc is also likely to change as we convert it
// to be backed by persistent storage.
// wait for signal and exit
close(exitCh)
}
}
func handleRegisterApp(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
remoteIP := strings.Split(r.RemoteAddr, ":")[0]
if _, ok := containerByIP[remoteIP]; ok {
// not allowed from container IP
w.WriteHeader(http.StatusForbidden)
return
}
uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
if err != nil {
w.WriteHeader(http.StatusNotFound)
@@ -358,7 +357,7 @@ func handleAppID(w http.ResponseWriter, r *http.Request, c *mdsContainer, im *sc
func initCrypto() error {
if n, err := rand.Reader.Read(hmacKey[:]); err != nil || n != len(hmacKey) {
return fmt.Errorf("failed to generate HMAC Key")
return fmt.Errorf("Failed to generate HMAC Key")
}
return nil
}
@@ -455,34 +454,8 @@ func logReq(h func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
}
}
func makeHandlers() http.Handler {
r := mux.NewRouter()
r.HandleFunc("/pods/{uuid}", logReq(handleRegisterContainer)).Methods("PUT")
r.HandleFunc("/pods/{uuid}", logReq(handleUnregisterContainer)).Methods("DELETE")
r.HandleFunc("/pods/{uuid}/{app:.*}", logReq(handleRegisterApp)).Methods("PUT")
acRtr := r.Headers("Metadata-Flavor", "AppContainer").
PathPrefix("/acMetadata/v1").Subrouter()
mr := acRtr.Methods("GET").Subrouter()
mr.HandleFunc("/pod/annotations/", logReq(containerGet(handleContainerAnnotations)))
mr.HandleFunc("/pod/annotations/{name}", logReq(containerGet(handleContainerAnnotation)))
mr.HandleFunc("/pod/manifest", logReq(containerGet(handlePodManifest)))
mr.HandleFunc("/pod/uuid", logReq(containerGet(handleContainerUUID)))
mr.HandleFunc("/apps/{app:.*}/annotations/", logReq(appGet(handleAppAnnotations)))
mr.HandleFunc("/apps/{app:.*}/annotations/{name}", logReq(appGet(handleAppAnnotation)))
mr.HandleFunc("/apps/{app:.*}/image/manifest", logReq(appGet(handleImageManifest)))
mr.HandleFunc("/apps/{app:.*}/image/id", logReq(appGet(handleAppID)))
acRtr.HandleFunc("/pod/hmac/sign", logReq(handleContainerSign)).Methods("POST")
acRtr.HandleFunc("/pod/hmac/verify", logReq(handleContainerVerify)).Methods("POST")
return r
}
func getListener() (net.Listener, error) {
// unixListener returns the listener used for registrations (over unix sock)
func unixListener() (net.Listener, error) {
s := os.Getenv("LISTEN_FDS")
if s != "" {
// socket activated
@@ -496,65 +469,92 @@ func getListener() (net.Listener, error) {
return net.FileListener(os.NewFile(uintptr(listenFdsStart), "listen"))
} else {
return net.Listen("tcp4", fmt.Sprintf(":%v", flagListenPort))
dir := filepath.Dir(common.MetadataServiceRegSock)
err := os.MkdirAll(dir, 0755)
if err != nil {
return nil, fmt.Errorf("Failed to create %v: %v", dir, err)
}
return net.ListenUnix("unix", &net.UnixAddr{
Net: "unix",
Name: common.MetadataServiceRegSock,
})
}
}
func cleanup(port string) {
if err := modifyIPTables("-D", port); err != nil {
log.Printf("Error cleaning up iptables: %v", err)
func runRegistrationServer(l net.Listener) {
r := mux.NewRouter()
r.HandleFunc("/pods/{uuid}", logReq(handleRegisterContainer)).Methods("PUT")
r.HandleFunc("/pods/{uuid}", logReq(handleUnregisterContainer)).Methods("DELETE")
r.HandleFunc("/pods/{uuid}/{app:.*}", logReq(handleRegisterApp)).Methods("PUT")
if err := http.Serve(l, r); err != nil {
stderr("Error serving registration HTTP: %v", err)
}
close(exitCh)
}
func runPublicServer(l net.Listener) {
r := mux.NewRouter().Headers("Metadata-Flavor", "AppContainer").
PathPrefix("/acMetadata/v1").Subrouter()
mr := r.Methods("GET").Subrouter()
mr.HandleFunc("/pod/annotations/", logReq(containerGet(handleContainerAnnotations)))
mr.HandleFunc("/pod/annotations/{name}", logReq(containerGet(handleContainerAnnotation)))
mr.HandleFunc("/pod/manifest", logReq(containerGet(handlePodManifest)))
mr.HandleFunc("/pod/uuid", logReq(containerGet(handleContainerUUID)))
mr.HandleFunc("/apps/{app:.*}/annotations/", logReq(appGet(handleAppAnnotations)))
mr.HandleFunc("/apps/{app:.*}/annotations/{name}", logReq(appGet(handleAppAnnotation)))
mr.HandleFunc("/apps/{app:.*}/image/manifest", logReq(appGet(handleImageManifest)))
mr.HandleFunc("/apps/{app:.*}/image/id", logReq(appGet(handleAppID)))
r.HandleFunc("/pod/hmac/sign", logReq(handleContainerSign)).Methods("POST")
r.HandleFunc("/pod/hmac/verify", logReq(handleContainerVerify)).Methods("POST")
if err := http.Serve(l, r); err != nil {
stderr("Error serving container HTTP: %v", err)
}
close(exitCh)
}
func runMetadataService(args []string) (exit int) {
log.Print("Metadata service starting...")
l, err := getListener()
unixl, err := unixListener()
if err != nil {
log.Printf("Error getting listener: %v", err)
return
stderr(err.Error())
return 1
}
defer unixl.Close()
initCrypto()
port := strings.Split(l.Addr().String(), ":")[1]
if flagNoIdle {
// TODO(eyakubovich): this is very racy
// It's possible for last container to get unregistered
// and svc gets flagged to shutdown. Then another container
// starts to launch, sees that port is in use and doesn't
// start metadata svc only for this one to exit a moment later.
// However, --no-idle is meant for demos and having a single
// container spawn up (via --spawn-metadata-svc). The design
// of metadata svc is also likely to change as we convert it
// to be backed by persistent storage.
exitCh = make(chan bool, 1)
// wait for signal and exit
go func() {
<-exitCh
cleanup(port)
os.Exit(0)
}()
tcpl, err := net.ListenTCP("tcp4", &net.TCPAddr{Port: flagListenPort})
if err != nil {
stderr("Error listening on port %v: %v", flagListenPort, err)
return 1
}
defer tcpl.Close()
if err := modifyIPTables("-A", port); err != nil {
log.Printf("Error setting up iptables: %v", err)
if err := initCrypto(); err != nil {
stderr(err.Error())
return 1
}
srv := http.Server{
Handler: makeHandlers(),
if err := modifyIPTables("-A"); err != nil {
stderr("Error setting up iptables: %v", err)
return 1
}
defer modifyIPTables("-D")
go runRegistrationServer(unixl)
go runPublicServer(tcpl)
log.Print("Metadata service running...")
if err = srv.Serve(l); err != nil {
log.Printf("Error serving HTTP: %v", err)
exit = 1
}
signal.Notify(exitCh, syscall.SIGINT, syscall.SIGTERM)
<-exitCh
cleanup(port)
log.Print("Metadata service exiting...")
return
+8 -23
View File
@@ -29,7 +29,6 @@ import (
"fmt"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path"
@@ -464,37 +463,23 @@ func overlayRender(cfg RunConfig, img types.Hash, cdir string, dest string) erro
}
func launchMetadataService(debug bool) error {
// use socket activation protocol to avoid race-condition of
// service becoming ready
l, err := net.ListenTCP("tcp4", &net.TCPAddr{Port: common.MetadataServicePrvPort})
// readlink so arg[0] displays useful info
exe, err := os.Readlink("/proc/self/exe")
if err != nil {
if err.(*net.OpError).Err.(*os.SyscallError).Err == syscall.EADDRINUSE {
// assume metadata-service is already running
return nil
}
return err
return fmt.Errorf("error reading /proc/self/exe link: %v", err)
}
defer l.Close()
lf, err := l.File()
if err != nil {
return err
}
args := []string{"/proc/self/exe"}
args := []string{exe}
if debug {
args = append(args, "--debug")
}
args = append(args, "metadata-service", "--no-idle")
cmd := exec.Cmd{
Path: args[0],
Args: args,
Env: append(os.Environ(), "LISTEN_FDS=1"),
ExtraFiles: []*os.File{lf},
Stdout: os.Stdout,
Stderr: os.Stderr,
Path: exe,
Args: args,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
return cmd.Start()
+37 -13
View File
@@ -17,14 +17,20 @@ package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path"
"time"
"github.com/coreos/rocket/common"
)
const retryCount = 3
var retryPause = time.Second
func registerContainer(c *Container, ip net.IP) error {
uuid := c.UUID.String()
@@ -66,23 +72,41 @@ func registerApp(uuid, app string, r io.Reader) error {
}
func httpRequest(method, pth string, body io.Reader) error {
uri := common.MetadataServicePrivateURL() + pth
req, err := http.NewRequest(method, uri, body)
if err != nil {
return err
uri := "http://unixsock" + pth
t := &http.Transport{
Dial: func(_, _ string) (net.Conn, error) {
return net.Dial("unix", common.MetadataServiceRegSock)
},
}
cli := http.Client{}
var err error
for i := 0; i < retryCount; i++ {
var req *http.Request
req, err = http.NewRequest(method, uri, body)
if err != nil {
return err
}
resp, err := cli.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
cli := http.Client{Transport: t}
if resp.StatusCode != 200 {
return fmt.Errorf("%v %v returned %v", method, pth, resp.StatusCode)
var resp *http.Response
resp, err = cli.Do(req)
switch {
case err == nil:
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("%v %v returned %v", method, pth, resp.StatusCode)
}
return nil
default:
log.Print(err)
time.Sleep(retryPause)
}
}
return nil
return err
}