From 8049fa9b723733f298abbe2e605b7a45241e4aa2 Mon Sep 17 00:00:00 2001 From: Brad Davidson Date: Tue, 26 Nov 2024 20:06:21 +0000 Subject: [PATCH] Revert "Remove special hostname behavior for aws cloud-provider" This reverts commit 89a8d81227fe12fb8ca7f4aecff22ac6834e0643. Signed-off-by: Brad Davidson (cherry picked from commit 6e701fc7d61248b17aad639c467cc2676dc6c436) Signed-off-by: Brad Davidson --- pkg/rke2/rke2_linux.go | 64 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/pkg/rke2/rke2_linux.go b/pkg/rke2/rke2_linux.go index f0902668c4..3bf5c9e3c9 100644 --- a/pkg/rke2/rke2_linux.go +++ b/pkg/rke2/rke2_linux.go @@ -4,10 +4,16 @@ package rke2 import ( + "bytes" + "context" "fmt" + "io/ioutil" + "net/http" + "os/exec" "path/filepath" "strconv" "strings" + "time" "github.com/k3s-io/k3s/pkg/agent/config" "github.com/k3s-io/k3s/pkg/cli/cmds" @@ -18,6 +24,7 @@ import ( "github.com/rancher/rke2/pkg/cli/defaults" "github.com/rancher/rke2/pkg/images" "github.com/rancher/rke2/pkg/podexecutor" + "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -89,6 +96,19 @@ func initExecutor(clx *cli.Context, cfg Config, isServer bool) (*podexecutor.Sta Name: cfg.CloudProviderName, Path: cfg.CloudProviderConfig, } + if clx.String("node-name") == "" && cfg.CloudProviderName == "aws" { + fqdn := hostnameFromMetadataEndpoint(context.Background()) + if fqdn == "" { + hostFQDN, err := hostnameFQDN() + if err != nil { + return nil, err + } + fqdn = hostFQDN + } + if err := clx.Set("node-name", fqdn); err != nil { + return nil, err + } + } } if cfg.KubeletPath == "" { @@ -469,3 +489,47 @@ func parseControlPlaneMounts(cfg Config) (*podexecutor.ControlPlaneMounts, error CloudControllerManager: cfg.ExtraMounts.CloudControllerManager.Value(), }, nil } + +func hostnameFQDN() (string, error) { + cmd := exec.Command("hostname", "-f") + + var b bytes.Buffer + cmd.Stdout = &b + + if err := cmd.Run(); err != nil { + return "", err + } + + return strings.TrimSpace(b.String()), nil +} + +func hostnameFromMetadataEndpoint(ctx context.Context) string { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://169.254.169.254/latest/meta-data/local-hostname", nil) + if err != nil { + logrus.Debugf("Failed to create request for metadata endpoint: %v", err) + return "" + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + logrus.Debugf("Failed to get local-hostname from metadata endpoint: %v", err) + return "" + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + logrus.Debugf("Metadata endpoint returned unacceptable status code %d", resp.StatusCode) + return "" + } + + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + logrus.Debugf("Failed to read response body from metadata endpoint: %v", err) + return "" + } + + return strings.TrimSpace(string(b)) +}