1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.channel;
18
19 import io.netty.util.internal.EmptyArrays;
20 import io.netty.util.internal.MacAddressUtil;
21 import io.netty.util.internal.PlatformDependent;
22 import io.netty.util.internal.SystemPropertyUtil;
23 import io.netty.util.internal.logging.InternalLogger;
24 import io.netty.util.internal.logging.InternalLoggerFactory;
25
26 import java.lang.reflect.Method;
27 import java.util.Arrays;
28 import java.util.concurrent.ThreadLocalRandom;
29 import java.util.concurrent.atomic.AtomicInteger;
30
31 import static io.netty.util.internal.MacAddressUtil.defaultMachineId;
32 import static io.netty.util.internal.MacAddressUtil.parseMAC;
33
34
35
36
37 public final class DefaultChannelId implements ChannelId {
38
39 private static final long serialVersionUID = 809640043754842613L;
40
41 private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelId.class);
42 private static final byte[] MACHINE_ID;
43 private static final int PROCESS_ID_LEN = 4;
44 private static final int PROCESS_ID;
45 private static final int SEQUENCE_LEN = 4;
46 private static final int TIMESTAMP_LEN = 8;
47 private static final int RANDOM_LEN = 4;
48
49 private static final AtomicInteger nextSequence = new AtomicInteger();
50
51 private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
52
53
54
55
56 public static DefaultChannelId newInstance() {
57 return new DefaultChannelId(MACHINE_ID,
58 PROCESS_ID,
59 nextSequence.getAndIncrement(),
60 Long.reverse(System.nanoTime()) ^ System.currentTimeMillis(),
61 ThreadLocalRandom.current().nextInt());
62 }
63
64 static {
65 int processId = -1;
66 String customProcessId = SystemPropertyUtil.get("io.netty.processId");
67 if (customProcessId != null) {
68 try {
69 processId = Integer.parseInt(customProcessId);
70 } catch (NumberFormatException e) {
71
72 }
73
74 if (processId < 0) {
75 processId = -1;
76 logger.warn("-Dio.netty.processId: {} (malformed)", customProcessId);
77 } else if (logger.isDebugEnabled()) {
78 logger.debug("-Dio.netty.processId: {} (user-set)", processId);
79 }
80 }
81
82 if (processId < 0) {
83 processId = defaultProcessId();
84 if (logger.isDebugEnabled()) {
85 logger.debug("-Dio.netty.processId: {} (auto-detected)", processId);
86 }
87 }
88
89 PROCESS_ID = processId;
90
91 byte[] machineId = null;
92 String customMachineId = SystemPropertyUtil.get("io.netty.machineId");
93 if (customMachineId != null) {
94 try {
95 machineId = parseMAC(customMachineId);
96 } catch (Exception e) {
97 logger.warn("-Dio.netty.machineId: {} (malformed)", customMachineId, e);
98 }
99 if (machineId != null) {
100 logger.debug("-Dio.netty.machineId: {} (user-set)", customMachineId);
101 }
102 }
103
104 if (machineId == null) {
105 machineId = defaultMachineId();
106 if (logger.isDebugEnabled()) {
107 logger.debug("-Dio.netty.machineId: {} (auto-detected)", MacAddressUtil.formatAddress(machineId));
108 }
109 }
110
111 MACHINE_ID = machineId;
112 }
113
114 static int processHandlePid() {
115 if (PlatformDependent.javaVersion() < 9) {
116 return -1;
117 }
118
119
120 final long pid;
121 try {
122 pid = ProcessHandlePid.get();
123 } catch (Exception e) {
124 logger.debug("Could not invoke ProcessHandle.current().pid();", e);
125 return -1;
126 }
127 if (pid > Integer.MAX_VALUE || pid < Integer.MIN_VALUE) {
128 throw new IllegalStateException("Current process ID exceeds int range: " + pid);
129 }
130 return (int) pid;
131 }
132
133 private static final class ProcessHandlePid {
134 static long get() {
135 return ProcessHandle.current().pid();
136 }
137 }
138
139 static int jmxPid(ClassLoader loader) {
140 String value;
141 try {
142
143 Class<?> mgmtFactoryType = Class.forName("java.lang.management.ManagementFactory", true, loader);
144 Class<?> runtimeMxBeanType = Class.forName("java.lang.management.RuntimeMXBean", true, loader);
145
146 Method getRuntimeMXBean = mgmtFactoryType.getMethod("getRuntimeMXBean", EmptyArrays.EMPTY_CLASSES);
147 Object bean = getRuntimeMXBean.invoke(null, EmptyArrays.EMPTY_OBJECTS);
148 Method getName = runtimeMxBeanType.getMethod("getName", EmptyArrays.EMPTY_CLASSES);
149 value = (String) getName.invoke(bean, EmptyArrays.EMPTY_OBJECTS);
150 } catch (Throwable t) {
151 logger.debug("Could not invoke ManagementFactory.getRuntimeMXBean().getName(); Android?", t);
152 try {
153
154 Class<?> processType = Class.forName("android.os.Process", true, loader);
155 Method myPid = processType.getMethod("myPid", EmptyArrays.EMPTY_CLASSES);
156 value = myPid.invoke(null, EmptyArrays.EMPTY_OBJECTS).toString();
157 } catch (Throwable t2) {
158 logger.debug("Could not invoke Process.myPid(); not Android?", t2);
159 value = "";
160 }
161 }
162
163 int atIndex = value.indexOf('@');
164 if (atIndex >= 0) {
165 value = value.substring(0, atIndex);
166 }
167
168 int pid;
169 try {
170 pid = Integer.parseInt(value);
171 } catch (NumberFormatException e) {
172
173 pid = -1;
174 }
175
176 if (pid < 0) {
177 pid = ThreadLocalRandom.current().nextInt();
178 logger.warn("Failed to find the current process ID from '{}'; using a random value: {}", value, pid);
179 }
180
181 return pid;
182 }
183
184 static int defaultProcessId() {
185 ClassLoader loader = PlatformDependent.getClassLoader(DefaultChannelId.class);
186 int processId = processHandlePid();
187 if (processId != -1) {
188 return processId;
189 }
190 return jmxPid(loader);
191 }
192
193 private final byte[] machineId;
194 private final int processId;
195 private final int sequence;
196 private final long timestamp;
197 private final int random;
198 private final int hashCode;
199
200 private transient String shortValue;
201 private transient String longValue;
202
203
204
205
206 DefaultChannelId(final byte[] machineId, final int processId, final int sequence,
207 final long timestamp, final int random) {
208 this.machineId = machineId;
209 this.processId = processId;
210 this.sequence = sequence;
211 this.timestamp = timestamp;
212 this.random = random;
213 hashCode = computeHashCode();
214 }
215
216 private int computeHashCode() {
217 int h = Arrays.hashCode(machineId);
218 h = 31 * h + processId;
219 h = 31 * h + sequence;
220 h = 31 * h + Long.hashCode(timestamp);
221 h = 31 * h + random;
222 return h;
223 }
224
225 @Override
226 public String asShortText() {
227 String shortValue = this.shortValue;
228 if (shortValue == null) {
229 final StringBuilder buf = new StringBuilder(RANDOM_LEN * 2);
230 appendHexInt(buf, random);
231 this.shortValue = shortValue = buf.toString();
232 }
233 return shortValue;
234 }
235
236 @Override
237 public String asLongText() {
238 String longValue = this.longValue;
239 if (longValue == null) {
240 this.longValue = longValue = newLongValue();
241 }
242 return longValue;
243 }
244
245 private String newLongValue() {
246 final int machineIdLen = machineId.length;
247 final StringBuilder buf = new StringBuilder(
248 2 * (machineIdLen + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN) + 4);
249 appendHexBytes(buf, machineId);
250 buf.append('-');
251 appendHexInt(buf, processId);
252 buf.append('-');
253 appendHexInt(buf, sequence);
254 buf.append('-');
255 appendHexLong(buf, timestamp);
256 buf.append('-');
257 appendHexInt(buf, random);
258 return buf.toString();
259 }
260
261 private static void appendHexBytes(StringBuilder buf, byte[] bytes) {
262 for (byte b : bytes) {
263 buf.append(HEX_CHARS[(b & 0xFF) >>> 4]);
264 buf.append(HEX_CHARS[b & 0xF]);
265 }
266 }
267
268 private static void appendHexInt(StringBuilder buf, int value) {
269 for (int i = 28; i >= 0; i -= 4) {
270 buf.append(HEX_CHARS[(value >>> i) & 0xF]);
271 }
272 }
273
274 private static void appendHexLong(StringBuilder buf, long value) {
275 for (int i = 60; i >= 0; i -= 4) {
276 buf.append(HEX_CHARS[(int) ((value >>> i) & 0xF)]);
277 }
278 }
279
280 @Override
281 public int hashCode() {
282 return hashCode;
283 }
284
285 @Override
286 public int compareTo(final ChannelId o) {
287 if (this == o) {
288
289 return 0;
290 }
291 if (o instanceof DefaultChannelId) {
292 final DefaultChannelId other = (DefaultChannelId) o;
293 int cmp = compareBytes(machineId, other.machineId);
294 if (cmp != 0) {
295 return cmp;
296 }
297 cmp = Integer.compareUnsigned(processId, other.processId);
298 if (cmp != 0) {
299 return cmp;
300 }
301 cmp = Integer.compareUnsigned(sequence, other.sequence);
302 if (cmp != 0) {
303 return cmp;
304 }
305 cmp = Long.compareUnsigned(timestamp, other.timestamp);
306 if (cmp != 0) {
307 return cmp;
308 }
309 return Integer.compareUnsigned(random, other.random);
310 }
311
312 return asLongText().compareTo(o.asLongText());
313 }
314
315 private static int compareBytes(byte[] a, byte[] b) {
316 int len1 = a.length;
317 int len2 = b.length;
318 int len = Math.min(len1, len2);
319 for (int k = 0; k < len; k++) {
320 int cmp = (a[k] & 0xFF) - (b[k] & 0xFF);
321 if (cmp != 0) {
322 return cmp;
323 }
324 }
325 return len1 - len2;
326 }
327
328 @Override
329 public boolean equals(Object obj) {
330 if (this == obj) {
331 return true;
332 }
333 if (!(obj instanceof DefaultChannelId)) {
334 return false;
335 }
336 DefaultChannelId other = (DefaultChannelId) obj;
337 return hashCode == other.hashCode
338 && random == other.random
339 && processId == other.processId
340 && sequence == other.sequence
341 && timestamp == other.timestamp
342 && Arrays.equals(machineId, other.machineId);
343 }
344
345 @Override
346 public String toString() {
347 return asShortText();
348 }
349 }