constellation/hack/qemu-metadata-api/server/server.go

207 lines
5.8 KiB
Go
Raw Normal View History

/*
Copyright (c) Edgeless Systems GmbH
SPDX-License-Identifier: AGPL-3.0-only
*/
package server
import (
"encoding/json"
"fmt"
2024-02-08 09:20:01 -05:00
"log/slog"
"net"
"net/http"
"strings"
2022-09-21 07:47:57 -04:00
"github.com/edgelesssys/constellation/v2/hack/qemu-metadata-api/virtwrapper"
"github.com/edgelesssys/constellation/v2/internal/cloud/metadata"
"github.com/edgelesssys/constellation/v2/internal/role"
)
// Server that provides QEMU metadata.
type Server struct {
2024-02-08 09:20:01 -05:00
log *slog.Logger
2022-11-26 13:44:34 -05:00
virt virConnect
network string
initSecretHashVal []byte
}
// New creates a new Server.
2024-02-08 09:20:01 -05:00
func New(log *slog.Logger, network, initSecretHash string, conn virConnect) *Server {
return &Server{
2022-11-26 13:44:34 -05:00
log: log,
virt: conn,
network: network,
initSecretHashVal: []byte(initSecretHash),
}
}
// ListenAndServe on a given port.
func (s *Server) ListenAndServe(port string) error {
mux := http.NewServeMux()
mux.Handle("/self", http.HandlerFunc(s.listSelf))
mux.Handle("/peers", http.HandlerFunc(s.listPeers))
mux.Handle("/endpoint", http.HandlerFunc(s.getEndpoint))
2022-11-26 13:44:34 -05:00
mux.Handle("/initsecrethash", http.HandlerFunc(s.initSecretHash))
server := http.Server{
Handler: mux,
}
lis, err := net.Listen("tcp", net.JoinHostPort("", port))
if err != nil {
return err
}
2024-02-08 09:20:01 -05:00
s.log.Info(fmt.Sprintf("Starting QEMU metadata API on %s", lis.Addr()))
return server.Serve(lis)
}
// listSelf returns peer information about the instance issuing the request.
func (s *Server) listSelf(w http.ResponseWriter, r *http.Request) {
2024-02-08 09:20:01 -05:00
log := s.log.With(slog.String("peer", r.RemoteAddr))
log.Info("Serving GET request for /self")
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
2024-02-08 09:20:01 -05:00
log.With(slog.Any("error", err)).Error("Failed to parse remote address")
http.Error(w, fmt.Sprintf("Failed to parse remote address: %s\n", err), http.StatusInternalServerError)
return
}
peers, err := s.listAll()
if err != nil {
2024-02-08 09:20:01 -05:00
log.With(slog.Any("error", err)).Error("Failed to list peer metadata")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, peer := range peers {
if peer.VPCIP == remoteIP {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(peer); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-02-08 09:20:01 -05:00
log.Info("Request successful")
return
}
}
2024-02-08 09:20:01 -05:00
log.Error("Failed to find peer in active leases")
http.Error(w, "No matching peer found", http.StatusNotFound)
}
// listPeers returns a list of all active peers.
func (s *Server) listPeers(w http.ResponseWriter, r *http.Request) {
2024-02-08 09:20:01 -05:00
log := s.log.With(slog.String("peer", r.RemoteAddr))
log.Info("Serving GET request for /peers")
peers, err := s.listAll()
if err != nil {
2024-02-08 09:20:01 -05:00
log.With(slog.Any("error", err)).Error("Failed to list peer metadata")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(peers); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-02-08 09:20:01 -05:00
log.Info("Request successful")
}
2022-11-26 13:44:34 -05:00
// initSecretHash returns the hash of the init secret.
func (s *Server) initSecretHash(w http.ResponseWriter, r *http.Request) {
2024-02-08 09:20:01 -05:00
log := s.log.With(slog.String("initSecretHash", r.RemoteAddr))
2022-11-26 13:44:34 -05:00
if r.Method != http.MethodGet {
2024-02-08 09:20:01 -05:00
log.With(slog.String("method", r.Method)).Error("Invalid method for /initSecretHash")
2022-11-26 13:44:34 -05:00
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
2024-02-08 09:20:01 -05:00
log.Info("Serving GET request for /initsecrethash")
2022-11-26 13:44:34 -05:00
w.Header().Set("Content-Type", "text/plain")
_, err := w.Write(s.initSecretHashVal)
if err != nil {
2024-02-08 09:20:01 -05:00
log.With(slog.Any("error", err)).Error("Failed to write init secret hash")
2022-11-26 13:44:34 -05:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-02-08 09:20:01 -05:00
log.Info("Request successful")
2022-11-26 13:44:34 -05:00
}
// getEndpoint returns the IP address of the first control-plane instance.
// This allows us to fake a load balancer for QEMU instances.
func (s *Server) getEndpoint(w http.ResponseWriter, r *http.Request) {
2024-02-08 09:20:01 -05:00
log := s.log.With(slog.String("peer", r.RemoteAddr))
log.Info("Serving GET request for /endpoint")
net, err := s.virt.LookupNetworkByName(s.network)
if err != nil {
2024-02-08 09:20:01 -05:00
log.With(slog.Any("error", err)).Error("Failed to lookup network")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer net.Free()
leases, err := net.GetDHCPLeases()
if err != nil {
2024-02-08 09:20:01 -05:00
log.With(slog.Any("error", err)).Error("Failed to get DHCP leases")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
for _, lease := range leases {
if strings.HasPrefix(lease.Hostname, "control-plane") &&
strings.HasSuffix(lease.Hostname, "0") {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(lease.IPaddr); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-02-08 09:20:01 -05:00
log.Info("Request successful")
return
}
}
2024-02-08 09:20:01 -05:00
log.Error("Failed to find control-plane peer in active leases")
http.Error(w, "No matching peer found", http.StatusNotFound)
}
// listAll returns a list of all active peers.
2022-07-05 08:14:11 -04:00
func (s *Server) listAll() ([]metadata.InstanceMetadata, error) {
net, err := s.virt.LookupNetworkByName(s.network)
if err != nil {
return nil, err
}
defer net.Free()
leases, err := net.GetDHCPLeases()
if err != nil {
return nil, err
}
2022-07-05 08:14:11 -04:00
var peers []metadata.InstanceMetadata
for _, lease := range leases {
2022-07-05 08:14:11 -04:00
instanceRole := role.Worker
if strings.HasPrefix(lease.Hostname, "control-plane") {
2022-07-05 08:14:11 -04:00
instanceRole = role.ControlPlane
}
2022-07-05 08:14:11 -04:00
peers = append(peers, metadata.InstanceMetadata{
Name: lease.Hostname,
Role: instanceRole,
VPCIP: lease.IPaddr,
ProviderID: "qemu:///hostname/" + lease.Hostname,
})
}
return peers, nil
}
type virConnect interface {
LookupNetworkByName(name string) (*virtwrapper.Network, error)
}