MashrafeeAryan commented on code in PR #14551:
URL: https://github.com/apache/cloudstack/pull/14551#discussion_r4788608553


##########
utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java:
##########
@@ -0,0 +1,108 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.utils.identity;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.util.function.LongSupplier;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.MacAddress;
+
+// Keeps the management server ID the same across restarts
+final class ManagementServerId {
+
+    private ManagementServerId() {
+    }
+
+    // Find the ID file and load the ID
+    static long get() {
+        Path path = Paths.get(System.getProperty("management.server.id.file",
+                Paths.get(System.getProperty("user.home"), ".cloudstack", 
"management-server.id").toString()));
+        try {
+            // Use the ID from management.server.id if it is set
+            // Otherwise, read the saved ID from the file at path
+            // If the file does not exist, create an ID from the MAC address 
and save it
+            return load(path, System.getProperty("management.server.id"), () 
-> MacAddress.getMacAddress().toLong());
+        } catch (IOException | IllegalArgumentException e) {
+            // Stop with a clear error instead of silently choosing a 
different identity
+            throw new CloudRuntimeException("Unable to load the management 
server ID from " + path, e);
+        }
+    }
+
+    static long load(Path path, String configuredId, LongSupplier initialId) 
throws IOException {
+        // An operator-provided ID takes priority without overwriting the 
saved file
+        if (configuredId != null) {
+            return parse(configuredId);
+        }
+
+        // Ensure the directory exists, then lock the neighboring .lock file so
+        // two processes cannot initialize the same identity file at the same 
time
+        Files.createDirectories(path.toAbsolutePath().getParent());
+        try (FileChannel lockChannel = 
FileChannel.open(path.resolveSibling(path.getFileName() + ".lock"),
+                StandardOpenOption.CREATE, StandardOpenOption.WRITE);
+                FileLock lock = lockChannel.lock()) {
+            // Reuse the saved ID without checking network interfaces again
+            if (Files.exists(path)) {
+                // An ID is a short number; reject an unexpectedly large file
+                if (Files.size(path) > 64) {
+                    throw new IllegalArgumentException("Invalid management 
server ID file");
+                }
+                return parse(new String(Files.readAllBytes(path), 
StandardCharsets.UTF_8));
+            }
+
+            // First startup: obtain the initial MAC-derived ID and validate it
+            long id = parse(Long.toString(initialId.getAsLong()));

Review Comment:
   Hi @Damans227 , you are right it would save the wrong id forver. I added a 
database check before creating the ID file. 
   - If an ID file already exists, we used the saved ID. 
   - If there is no ID file, we look in mshost to see if we can find records 
matching the server's configured IP address and save it in the ID file.
   - if no records exist, we just create an ID from the network card and save 
it in the ID file.



##########
utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java:
##########
@@ -25,27 +25,32 @@
 import com.cloud.utils.component.ComponentLifecycle;
 import com.cloud.utils.component.SystemIntegrityChecker;
 import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.net.MacAddress;
 
+// Holds the management server ID and shares it with other CloudStack 
components
 public class ManagementServerNode extends AdapterBase implements 
SystemIntegrityChecker {
 
-    private static final long s_nodeId = MacAddress.getMacAddress().toLong();
+    // Load the ID once and keep the same value for the life of this process
+    private static final long s_nodeId = ManagementServerId.get();

Review Comment:
   Thanks for the suggestion Daman! I made the change. It makes sense to have 
it at the start() instead.



##########
utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java:
##########
@@ -0,0 +1,108 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.utils.identity;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.util.function.LongSupplier;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.MacAddress;
+
+// Keeps the management server ID the same across restarts
+final class ManagementServerId {
+
+    private ManagementServerId() {
+    }
+
+    // Find the ID file and load the ID
+    static long get() {
+        Path path = Paths.get(System.getProperty("management.server.id.file",
+                Paths.get(System.getProperty("user.home"), ".cloudstack", 
"management-server.id").toString()));
+        try {
+            // Use the ID from management.server.id if it is set
+            // Otherwise, read the saved ID from the file at path
+            // If the file does not exist, create an ID from the MAC address 
and save it
+            return load(path, System.getProperty("management.server.id"), () 
-> MacAddress.getMacAddress().toLong());
+        } catch (IOException | IllegalArgumentException e) {
+            // Stop with a clear error instead of silently choosing a 
different identity
+            throw new CloudRuntimeException("Unable to load the management 
server ID from " + path, e);
+        }
+    }
+
+    static long load(Path path, String configuredId, LongSupplier initialId) 
throws IOException {
+        // An operator-provided ID takes priority without overwriting the 
saved file
+        if (configuredId != null) {
+            return parse(configuredId);
+        }
+
+        // Ensure the directory exists, then lock the neighboring .lock file so
+        // two processes cannot initialize the same identity file at the same 
time
+        Files.createDirectories(path.toAbsolutePath().getParent());
+        try (FileChannel lockChannel = 
FileChannel.open(path.resolveSibling(path.getFileName() + ".lock"),
+                StandardOpenOption.CREATE, StandardOpenOption.WRITE);
+                FileLock lock = lockChannel.lock()) {
+            // Reuse the saved ID without checking network interfaces again
+            if (Files.exists(path)) {

Review Comment:
   You are right Daman! I have been struggling with a way to implement it. I 
implemented the following:
   
   So, CloudStack reads the saved ID in the ID file and looks up that ID in 
mshost. It compares the IP in the mshost with the IP configured on the server 
that’s starting. If they are the same, we keep the saved ID file.. 
   
   If the IPs are different, CloudStack stops startup and logs two options. If 
this is a separate clone, the admin can go ahead and request a new ID. If this 
is the same server moving to a new IP, the admin can confirm it so CloudStack 
keeps the saved ID file.
   
   Based on the error message I wrote, user would see something like this
   ```
   Management server ID 111 is recorded at 10.0.0.10, but this server is 
configured for 10.0.0.20. CloudStack stopped to avoid using the same ID on two 
servers if this VM is a clone.
   
   For a new cloned server with a copied ID file, set
   -Dmanagement.server.id.reset.from=111.
   
   For the same server moved to a new IP, stop the old instance and set
   -Dmanagement.server.id.previous.ip=10.0.0.10. See INSTALL.md.
   ```
   
   The simpler solution I can think probably:
   If we know it is a clone, we can just update the ID file with new mac 
address. So, if we already know that the clone will be a sepearte managemenet 
server, we can calculate its new MAC adress. (like the code originally does) 
and update the ID file.
   
   However, I wouldn't find a reliable way for the code to know that this clone 
will run as a seperate management server. 
   
   Would you please guide me on which approach I should take?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to