NIFI-12751 [MiNiFi] Prefer IPv4 address when sending NetworkInfo to C2

Signed-off-by: Ferenc Erdei <erdei.ferenc90@gmail.com>
This closes #8370
This commit is contained in:
Ferenc Kis 2024-02-07 15:57:12 +01:00 committed by Ferenc Erdei
parent 43276acf55
commit 84878df61a
No known key found for this signature in database
GPG Key ID: 023D856C60E92F96
1 changed files with 19 additions and 5 deletions

View File

@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.c2.client.service;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
@ -21,6 +22,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
@ -169,14 +171,20 @@ public class C2HeartbeatFactory {
logger.debug("Instance has multiple interfaces. Generated information may be non-deterministic.");
}
boolean networkInfoUnset = true;
for (NetworkInterface networkInterface : operationIfaces) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
if (inetAddresses.hasMoreElements()) {
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
networkInfo.setDeviceId(networkInterface.getName());
networkInfo.setHostname(inetAddress.getHostName());
networkInfo.setIpAddress(inetAddress.getHostAddress());
break;
// IPv4 address is preferred over IPv6 as it provides more readable information for the user
if (inetAddress instanceof Inet4Address) {
updateNetworkInfo(networkInfo, networkInterface, inetAddress);
return networkInfo;
}
if (networkInfoUnset) {
updateNetworkInfo(networkInfo, networkInterface, inetAddress);
networkInfoUnset = false;
}
}
}
}
@ -186,6 +194,12 @@ public class C2HeartbeatFactory {
return networkInfo;
}
private void updateNetworkInfo(NetworkInfo networkInfo, NetworkInterface networkInterface, InetAddress inetAddress) {
networkInfo.setDeviceId(networkInterface.getName());
networkInfo.setHostname(inetAddress.getHostName());
networkInfo.setIpAddress(inetAddress.getHostAddress());
}
private String getDeviceIdentifier(NetworkInfo networkInfo) {
if (deviceId == null) {
if (networkInfo.getDeviceId() != null) {