|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 NVIDIA CORPORATION. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "os" |
| 22 | + "path/filepath" |
| 23 | + "strings" |
| 24 | + "sync" |
| 25 | + |
| 26 | + "k8s.io/klog/v2" |
| 27 | + |
| 28 | + nvapi "github.com/NVIDIA/k8s-dra-driver-gpu/api/nvidia.com/resource/v1beta1" |
| 29 | +) |
| 30 | + |
| 31 | +const ( |
| 32 | + maxHostnames = 18 |
| 33 | + hostsFilePath = "/etc/hosts" |
| 34 | + hostnameFormat = "compute-domain-daemon-%d" |
| 35 | +) |
| 36 | + |
| 37 | +// HostnameManager manages the allocation of static hostnames to IP addresses. |
| 38 | +type HostnameManager struct { |
| 39 | + sync.Mutex |
| 40 | + ipToHostname map[string]string |
| 41 | + cliqueID string |
| 42 | + nodesConfigPath string |
| 43 | +} |
| 44 | + |
| 45 | +// NewHostnameManager creates a new hostname manager. |
| 46 | +func NewHostnameManager(cliqueID string, nodesConfigPath string) *HostnameManager { |
| 47 | + return &HostnameManager{ |
| 48 | + ipToHostname: make(map[string]string), |
| 49 | + cliqueID: cliqueID, |
| 50 | + nodesConfigPath: nodesConfigPath, |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// UpdateHostnameMappings updates the /etc/hosts file with IP to hostname mappings. |
| 55 | +func (m *HostnameManager) UpdateHostnameMappings(nodes []*nvapi.ComputeDomainNode) error { |
| 56 | + m.Lock() |
| 57 | + defer m.Unlock() |
| 58 | + |
| 59 | + // Prefilter nodes to only consider those with the matching cliqueID |
| 60 | + var cliqueNodes []*nvapi.ComputeDomainNode |
| 61 | + for _, node := range nodes { |
| 62 | + if node.CliqueID == m.cliqueID { |
| 63 | + cliqueNodes = append(cliqueNodes, node) |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Find and remove stale IPs from map |
| 68 | + currentIPs := make(map[string]bool) |
| 69 | + for _, node := range cliqueNodes { |
| 70 | + currentIPs[node.IPAddress] = true |
| 71 | + } |
| 72 | + |
| 73 | + for ip := range m.ipToHostname { |
| 74 | + if !currentIPs[ip] { |
| 75 | + delete(m.ipToHostname, ip) |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + // Add new IPs to map (filling in holes where others were removed) |
| 80 | + for _, node := range cliqueNodes { |
| 81 | + // If IP already has a hostname, skip it |
| 82 | + if _, exists := m.ipToHostname[node.IPAddress]; exists { |
| 83 | + continue |
| 84 | + } |
| 85 | + |
| 86 | + hostname, err := m.allocateHostname(node.IPAddress) |
| 87 | + if err != nil { |
| 88 | + return fmt.Errorf("failed to allocate hostname for IP %s: %w", node.IPAddress, err) |
| 89 | + } |
| 90 | + m.ipToHostname[node.IPAddress] = hostname |
| 91 | + } |
| 92 | + |
| 93 | + // Update the hosts file with current mappings |
| 94 | + return m.updateHostsFile() |
| 95 | +} |
| 96 | + |
| 97 | +// LogHostnameMappings logs the current compute-domain-daemon mappings from memory. |
| 98 | +func (m *HostnameManager) LogHostnameMappings() { |
| 99 | + m.Lock() |
| 100 | + defer m.Unlock() |
| 101 | + |
| 102 | + if len(m.ipToHostname) == 0 { |
| 103 | + klog.Infof("No compute-domain-daemon mappings found") |
| 104 | + return |
| 105 | + } |
| 106 | + |
| 107 | + klog.Infof("Current compute-domain-daemon mappings:") |
| 108 | + for ip, hostname := range m.ipToHostname { |
| 109 | + klog.Infof(" %s -> %s", ip, hostname) |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +// allocateHostname allocates a hostname for an IP address, reusing existing hostnames if possible. |
| 114 | +func (m *HostnameManager) allocateHostname(ip string) (string, error) { |
| 115 | + // If IP already has a hostname, return it |
| 116 | + if hostname, exists := m.ipToHostname[ip]; exists { |
| 117 | + return hostname, nil |
| 118 | + } |
| 119 | + |
| 120 | + // Find the next available hostname |
| 121 | + for i := 0; i < maxHostnames; i++ { |
| 122 | + hostname := fmt.Sprintf(hostnameFormat, i) |
| 123 | + // Check if this hostname is already in use |
| 124 | + inUse := false |
| 125 | + for _, existingHostname := range m.ipToHostname { |
| 126 | + if existingHostname == hostname { |
| 127 | + inUse = true |
| 128 | + break |
| 129 | + } |
| 130 | + } |
| 131 | + if !inUse { |
| 132 | + m.ipToHostname[ip] = hostname |
| 133 | + return hostname, nil |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + // If all hostnames are used, return an error |
| 138 | + return "", fmt.Errorf("no hostnames available (max: %d)", maxHostnames) |
| 139 | +} |
| 140 | + |
| 141 | +// updateHostsFile updates the /etc/hosts file with current IP to hostname mappings. |
| 142 | +func (m *HostnameManager) updateHostsFile() error { |
| 143 | + // Read hosts file |
| 144 | + hostsContent, err := os.ReadFile(hostsFilePath) |
| 145 | + if err != nil { |
| 146 | + return fmt.Errorf("failed to read %s: %w", hostsFilePath, err) |
| 147 | + } |
| 148 | + |
| 149 | + // Grab any lines to preserve, skipping existing hostname mappings |
| 150 | + var preservedLines []string |
| 151 | + for _, line := range strings.Split(string(hostsContent), "\n") { |
| 152 | + line = strings.TrimSpace(line) |
| 153 | + |
| 154 | + // Keep empty lines and comments |
| 155 | + if line == "" || strings.HasPrefix(line, "#") { |
| 156 | + preservedLines = append(preservedLines, line) |
| 157 | + continue |
| 158 | + } |
| 159 | + |
| 160 | + // Skip existing compute-domain-daemon mappings |
| 161 | + if strings.Contains(line, "compute-domain-daemon-") { |
| 162 | + continue |
| 163 | + } |
| 164 | + |
| 165 | + // Keep all other lines |
| 166 | + preservedLines = append(preservedLines, line) |
| 167 | + } |
| 168 | + |
| 169 | + // Add preserved lines |
| 170 | + var newHostsContent strings.Builder |
| 171 | + for _, line := range preservedLines { |
| 172 | + newHostsContent.WriteString(line) |
| 173 | + newHostsContent.WriteString("\n") |
| 174 | + } |
| 175 | + |
| 176 | + // Add a separator comment |
| 177 | + newHostsContent.WriteString("# Compute Domain Daemon mappings\n") |
| 178 | + |
| 179 | + // Add new hostname mappings |
| 180 | + for ip, hostname := range m.ipToHostname { |
| 181 | + newHostsContent.WriteString(fmt.Sprintf("%s\t%s\n", ip, hostname)) |
| 182 | + } |
| 183 | + |
| 184 | + // Write the updated hosts file |
| 185 | + if err := os.WriteFile(hostsFilePath, []byte(newHostsContent.String()), 0644); err != nil { |
| 186 | + return fmt.Errorf("failed to write %s: %w", hostsFilePath, err) |
| 187 | + } |
| 188 | + |
| 189 | + return nil |
| 190 | +} |
| 191 | + |
| 192 | +// WriteNodesConfig creates a static nodes config file with hostnames. |
| 193 | +func (m *HostnameManager) WriteNodesConfig() error { |
| 194 | + // Ensure the directory exists |
| 195 | + dir := filepath.Dir(m.nodesConfigPath) |
| 196 | + if err := os.MkdirAll(dir, 0755); err != nil { |
| 197 | + return fmt.Errorf("failed to create directory %s: %w", dir, err) |
| 198 | + } |
| 199 | + |
| 200 | + // Create or overwrite the nodesConfig file |
| 201 | + f, err := os.Create(m.nodesConfigPath) |
| 202 | + if err != nil { |
| 203 | + return fmt.Errorf("failed to create nodes config file: %w", err) |
| 204 | + } |
| 205 | + defer f.Close() |
| 206 | + |
| 207 | + // Write static hostnames |
| 208 | + for i := 0; i < maxHostnames; i++ { |
| 209 | + hostname := fmt.Sprintf(hostnameFormat, i) |
| 210 | + if _, err := fmt.Fprintf(f, "%s\n", hostname); err != nil { |
| 211 | + return fmt.Errorf("failed to write to nodes config file: %w", err) |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + klog.Infof("Created static nodes config file with %d hostnames using format %s", maxHostnames, hostnameFormat) |
| 216 | + return nil |
| 217 | +} |
0 commit comments