Browse Source

update host port on pull if changed

abhishek9686 2 weeks ago
parent
commit
def287ea10
2 changed files with 23 additions and 1 deletions
  1. 9 1
      controllers/hosts.go
  2. 14 0
      logic/hosts.go

+ 9 - 1
controllers/hosts.go

@@ -232,7 +232,15 @@ func pull(w http.ResponseWriter, r *http.Request) {
 		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
 		return
 	}
-	_ = logic.CheckHostPorts(host)
+
+	portChanged := logic.CheckHostPorts(host)
+	if portChanged {
+		// Save the port change to database immediately to prevent conflicts
+		if err := logic.UpsertHost(host); err != nil {
+			slog.Error("failed to save host port change", "host", host.Name, "error", err)
+		}
+	}
+
 	response := models.HostPull{
 		Host:              *host,
 		Nodes:             logic.GetHostNodes(host),

+ 14 - 0
logic/hosts.go

@@ -618,6 +618,9 @@ func GetRelatedHosts(hostID string) []models.Host {
 // with the same endpoint have different listen ports
 // in the case of 64535 hosts or more with same endpoint, ports will not be changed
 func CheckHostPorts(h *models.Host) (changed bool) {
+	if h.IsStaticPort {
+		return false
+	}
 	hostPortMutex.Lock()
 	defer hostPortMutex.Unlock()
 	utils.TraceCaller()
@@ -630,6 +633,17 @@ func CheckHostPorts(h *models.Host) (changed bool) {
 		return
 	}
 
+	// Get the current host from database to check if it already has a valid port assigned
+	currentHost, err := GetHost(h.ID.String())
+	if err == nil && currentHost.ListenPort > 0 {
+		// If the host already has a port in the database, use that instead of the incoming port
+		// This prevents the host from being reassigned when the client sends the old port
+		if currentHost.ListenPort != h.ListenPort {
+			fmt.Println("=======> Host has different port in DB, using DB port:", currentHost.ListenPort, "instead of incoming:", h.ListenPort)
+			h.ListenPort = currentHost.ListenPort
+		}
+	}
+
 	originalPort := h.ListenPort
 	defer func() {
 		if originalPort != h.ListenPort {