From 078bf6a5c44fc40fb68627e8066de50faa962569 Mon Sep 17 00:00:00 2001 From: Lucas Ritzdorf <42657792+LRitzdorf@users.noreply.github.com> Date: Fri, 19 Jul 2024 16:14:58 -0600 Subject: [PATCH] handlers: handle MAC-less requests via IP-based lookup --- cmd/cloud-init-server/handlers.go | 25 +++++++++++++++++++++++++ cmd/cloud-init-server/main.go | 3 +++ 2 files changed, 28 insertions(+) diff --git a/cmd/cloud-init-server/handlers.go b/cmd/cloud-init-server/handlers.go index b99710c..8348341 100644 --- a/cmd/cloud-init-server/handlers.go +++ b/cmd/cloud-init-server/handlers.go @@ -6,6 +6,7 @@ import ( "io" "log" "net/http" + "strings" "github.com/OpenCHAMI/cloud-init/internal/memstore" "github.com/OpenCHAMI/cloud-init/internal/smdclient" @@ -121,6 +122,30 @@ func (h CiHandler) GetDataByMAC(dataKind ciDataKind) func(w http.ResponseWriter, } } +func (h CiHandler) GetDataByIP(dataKind ciDataKind) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + // Strip port number from RemoteAddr to obtain raw IP + portIndex := strings.LastIndex(r.RemoteAddr, ":") + var ip string + if portIndex > 0 { + ip = r.RemoteAddr[:portIndex] + } else { + ip = r.RemoteAddr + } + // Retrieve the node's xname based on IP address + name, err := h.sm.IDfromIP(ip) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusUnprocessableEntity) + return + } else { + log.Printf("xname %s with ip %s found\n", name, ip) + } + // Actually respond with the data + h.getData(name, dataKind, w) + } +} + func (h CiHandler) getData(id string, dataKind ciDataKind, w http.ResponseWriter) { ci, err := h.store.Get(id, h.sm) if err != nil { diff --git a/cmd/cloud-init-server/main.go b/cmd/cloud-init-server/main.go index efa8a35..636d50f 100644 --- a/cmd/cloud-init-server/main.go +++ b/cmd/cloud-init-server/main.go @@ -83,6 +83,9 @@ func initCiRouter(router chi.Router, handler *CiHandler) { // Add cloud-init endpoints to router router.Get("/", handler.ListEntries) router.Post("/", handler.AddEntry) + router.Get("/user-data", handler.GetDataByIP(UserData)) + router.Get("/meta-data", handler.GetDataByIP(MetaData)) + router.Get("/vendor-data", handler.GetDataByIP(VendorData)) router.Get("/{id}", handler.GetEntry) router.Get("/{id}/user-data", handler.GetDataByMAC(UserData)) router.Get("/{id}/meta-data", handler.GetDataByMAC(MetaData))