17
17
package com .dragonflyoss .dragonfly .supernode .config ;
18
18
19
19
import javax .annotation .PostConstruct ;
20
+ import java .net .Inet4Address ;
21
+ import java .net .InetAddress ;
22
+ import java .net .NetworkInterface ;
20
23
import java .nio .file .Files ;
21
24
import java .nio .file .Paths ;
22
25
import java .util .ArrayList ;
26
+ import java .util .Enumeration ;
23
27
import java .util .List ;
24
28
25
- import com .dragonflyoss .dragonfly .supernode .common .Constants ;
26
29
import com .alibaba .fastjson .JSON ;
27
30
31
+ import com .dragonflyoss .dragonfly .supernode .common .Constants ;
28
32
import lombok .Data ;
29
33
import lombok .extern .slf4j .Slf4j ;
34
+ import org .apache .commons .lang3 .StringUtils ;
30
35
import org .springframework .boot .context .properties .ConfigurationProperties ;
31
36
32
37
/**
@@ -68,6 +73,12 @@ public class SupernodeProperties {
68
73
*/
69
74
private String dfgetPath = Constants .DFGET_PATH ;
70
75
76
+ /**
77
+ * The advertise ip is used to set the ip that we advertise to other peer in the p2p-network.
78
+ * By default, the first non-loop address is advertised.
79
+ */
80
+ private String advertiseIp ;
81
+
71
82
@ PostConstruct
72
83
public void init () {
73
84
String cdnHome = baseHome + "/repo" ;
@@ -82,6 +93,48 @@ public void init() {
82
93
log .error ("create repo dir error" , e );
83
94
System .exit (1 );
84
95
}
96
+
97
+ setLocalIp ();
98
+
85
99
log .info ("cluster members: {}" , JSON .toJSONString (cluster ));
86
100
}
101
+
102
+ private void setLocalIp () {
103
+ if (StringUtils .isNotBlank (advertiseIp )) {
104
+ Constants .localIp = advertiseIp ;
105
+ Constants .generateNodeCid ();
106
+ log .info ("init local ip of supernode, use ip:{}" , Constants .localIp );
107
+ } else {
108
+ List <String > ips = getAllIps ();
109
+ if (!ips .isEmpty ()) {
110
+ Constants .localIp = ips .get (0 );
111
+ Constants .generateNodeCid ();
112
+ }
113
+ log .info ("init local ip of supernode, ip list:{}, use ip:{}" ,
114
+ JSON .toJSONString (ips ), Constants .localIp );
115
+ }
116
+ }
117
+
118
+ private List <String > getAllIps () {
119
+ List <String > ips = new ArrayList <String >();
120
+ try {
121
+ Enumeration <NetworkInterface > allNetInterfaces = NetworkInterface
122
+ .getNetworkInterfaces ();
123
+ while (allNetInterfaces .hasMoreElements ()) {
124
+ NetworkInterface netInterface = allNetInterfaces .nextElement ();
125
+ Enumeration <InetAddress > addresses = netInterface
126
+ .getInetAddresses ();
127
+ while (addresses .hasMoreElements ()) {
128
+ InetAddress ip = addresses .nextElement ();
129
+ if (ip instanceof Inet4Address && !ip .isAnyLocalAddress ()
130
+ && !ip .isLoopbackAddress ()) {
131
+ ips .add (ip .getHostAddress ());
132
+ }
133
+ }
134
+ }
135
+ } catch (Exception e ) {
136
+ log .error ("getAllIps error:{}" , e .getMessage (), e );
137
+ }
138
+ return ips ;
139
+ }
87
140
}
0 commit comments