-
Notifications
You must be signed in to change notification settings - Fork 11.5k
/
MixAll.java
502 lines (442 loc) · 18.9 KB
/
MixAll.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
* 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.rocketmq.common;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.rocketmq.common.annotation.ImportantField;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.help.FAQUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MixAll {
private static final Logger log = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);
public static final String ROCKETMQ_HOME_ENV = "ROCKETMQ_HOME";
public static final String ROCKETMQ_HOME_PROPERTY = "rocketmq.home.dir";
public static final String NAMESRV_ADDR_ENV = "NAMESRV_ADDR";
public static final String NAMESRV_ADDR_PROPERTY = "rocketmq.namesrv.addr";
public static final String MESSAGE_COMPRESS_LEVEL = "rocketmq.message.compressLevel";
public static final String DEFAULT_NAMESRV_ADDR_LOOKUP = "jmenv.tbsite.net";
public static final String WS_DOMAIN_NAME = System.getProperty("rocketmq.namesrv.domain", DEFAULT_NAMESRV_ADDR_LOOKUP);
public static final String WS_DOMAIN_SUBGROUP = System.getProperty("rocketmq.namesrv.domain.subgroup", "nsaddr");
// // http://jmenv.tbsite.net:8080/rocketmq/nsaddr
// public static final String WS_ADDR = "http://" + WS_DOMAIN_NAME + ":8080/rocketmq/" + WS_DOMAIN_SUBGROUP;
public static final String DEFAULT_TOPIC = "TBW102";
public static final String BENCHMARK_TOPIC = "BenchmarkTest";
public static final String DEFAULT_PRODUCER_GROUP = "DEFAULT_PRODUCER";
public static final String DEFAULT_CONSUMER_GROUP = "DEFAULT_CONSUMER";
public static final String TOOLS_CONSUMER_GROUP = "TOOLS_CONSUMER";
public static final String FILTERSRV_CONSUMER_GROUP = "FILTERSRV_CONSUMER";
public static final String MONITOR_CONSUMER_GROUP = "__MONITOR_CONSUMER";
public static final String CLIENT_INNER_PRODUCER_GROUP = "CLIENT_INNER_PRODUCER";
public static final String SELF_TEST_PRODUCER_GROUP = "SELF_TEST_P_GROUP";
public static final String SELF_TEST_CONSUMER_GROUP = "SELF_TEST_C_GROUP";
public static final String SELF_TEST_TOPIC = "SELF_TEST_TOPIC";
public static final String OFFSET_MOVED_EVENT = "OFFSET_MOVED_EVENT";
public static final String ONS_HTTP_PROXY_GROUP = "CID_ONS-HTTP-PROXY";
public static final String CID_ONSAPI_PERMISSION_GROUP = "CID_ONSAPI_PERMISSION";
public static final String CID_ONSAPI_OWNER_GROUP = "CID_ONSAPI_OWNER";
public static final String CID_ONSAPI_PULL_GROUP = "CID_ONSAPI_PULL";
public static final String CID_RMQ_SYS_PREFIX = "CID_RMQ_SYS_";
public static final List<String> LOCAL_INET_ADDRESS = getLocalInetAddress();
public static final String LOCALHOST = localhost();
public static final String DEFAULT_CHARSET = "UTF-8";
public static final long MASTER_ID = 0L;
public static final long CURRENT_JVM_PID = getPID();
public static final String RETRY_GROUP_TOPIC_PREFIX = "%RETRY%";
public static final String DLQ_GROUP_TOPIC_PREFIX = "%DLQ%";
public static final String SYSTEM_TOPIC_PREFIX = "rmq_sys_";
public static final String UNIQUE_MSG_QUERY_FLAG = "_UNIQUE_KEY_QUERY";
public static final String DEFAULT_TRACE_REGION_ID = "DefaultRegion";
public static final String CONSUME_CONTEXT_TYPE = "ConsumeContextType";
public static String getWSAddr() {
String wsDomainName = System.getProperty("rocketmq.namesrv.domain", DEFAULT_NAMESRV_ADDR_LOOKUP);
String wsDomainSubgroup = System.getProperty("rocketmq.namesrv.domain.subgroup", "nsaddr");
String wsAddr = "http://" + wsDomainName + ":8080/rocketmq/" + wsDomainSubgroup;
if (wsDomainName.indexOf(":") > 0) {
wsAddr = "http://" + wsDomainName + "/rocketmq/" + wsDomainSubgroup;
}
return wsAddr;
}
public static String getRetryTopic(final String consumerGroup) {
return RETRY_GROUP_TOPIC_PREFIX + consumerGroup;
}
public static boolean isSysConsumerGroup(final String consumerGroup) {
return consumerGroup.startsWith(CID_RMQ_SYS_PREFIX);
}
public static boolean isSystemTopic(final String topic) {
return topic.startsWith(SYSTEM_TOPIC_PREFIX);
}
public static String getDLQTopic(final String consumerGroup) {
return DLQ_GROUP_TOPIC_PREFIX + consumerGroup;
}
public static String brokerVIPChannel(final boolean isChange, final String brokerAddr) {
if (isChange) {
String[] ipAndPort = brokerAddr.split(":");
String brokerAddrNew = ipAndPort[0] + ":" + (Integer.parseInt(ipAndPort[1]) - 2);
return brokerAddrNew;
} else {
return brokerAddr;
}
}
public static long getPID() {
String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
if (processName != null && processName.length() > 0) {
try {
return Long.parseLong(processName.split("@")[0]);
} catch (Exception e) {
return 0;
}
}
return 0;
}
public static long createBrokerId(final String ip, final int port) {
InetSocketAddress isa = new InetSocketAddress(ip, port);
byte[] ipArray = isa.getAddress().getAddress();
ByteBuffer bb = ByteBuffer.allocate(8);
bb.put(ipArray);
bb.putInt(port);
long value = bb.getLong(0);
return Math.abs(value);
}
public static void string2File(final String str, final String fileName) throws IOException {
String tmpFile = fileName + ".tmp";
string2FileNotSafe(str, tmpFile);
String bakFile = fileName + ".bak";
String prevContent = file2String(fileName);
if (prevContent != null) {
string2FileNotSafe(prevContent, bakFile);
}
File file = new File(fileName);
file.delete();
file = new File(tmpFile);
file.renameTo(new File(fileName));
}
public static void string2FileNotSafe(final String str, final String fileName) throws IOException {
File file = new File(fileName);
File fileParent = file.getParentFile();
if (fileParent != null) {
fileParent.mkdirs();
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
fileWriter.write(str);
} catch (IOException e) {
throw e;
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
}
public static String file2String(final String fileName) throws IOException {
File file = new File(fileName);
return file2String(file);
}
public static String file2String(final File file) throws IOException {
if (file.exists()) {
byte[] data = new byte[(int) file.length()];
boolean result;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
int len = inputStream.read(data);
result = len == data.length;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
if (result) {
return new String(data);
}
}
return null;
}
public static String file2String(final URL url) {
InputStream in = null;
try {
URLConnection urlConnection = url.openConnection();
urlConnection.setUseCaches(false);
in = urlConnection.getInputStream();
int len = in.available();
byte[] data = new byte[len];
in.read(data, 0, len);
return new String(data, "UTF-8");
} catch (Exception ignored) {
} finally {
if (null != in) {
try {
in.close();
} catch (IOException ignored) {
}
}
}
return null;
}
public static String findClassPath(Class<?> c) {
URL url = c.getProtectionDomain().getCodeSource().getLocation();
return url.getPath();
}
public static void printObjectProperties(final Logger logger, final Object object) {
printObjectProperties(logger, object, false);
}
public static void printObjectProperties(final Logger logger, final Object object, final boolean onlyImportantField) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
if (!name.startsWith("this")) {
Object value = null;
try {
field.setAccessible(true);
value = field.get(object);
if (null == value) {
value = "";
}
} catch (IllegalAccessException e) {
log.error("Failed to obtain object properties", e);
}
if (onlyImportantField) {
Annotation annotation = field.getAnnotation(ImportantField.class);
if (null == annotation) {
continue;
}
}
if (logger != null) {
logger.info(name + "=" + value);
} else {
}
}
}
}
}
public static String properties2String(final Properties properties) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
if (entry.getValue() != null) {
sb.append(entry.getKey().toString() + "=" + entry.getValue().toString() + "\n");
}
}
return sb.toString();
}
public static Properties string2Properties(final String str) {
Properties properties = new Properties();
try {
InputStream in = new ByteArrayInputStream(str.getBytes(DEFAULT_CHARSET));
properties.load(in);
} catch (Exception e) {
log.error("Failed to handle properties", e);
return null;
}
return properties;
}
public static Properties object2Properties(final Object object) {
Properties properties = new Properties();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
if (!name.startsWith("this")) {
Object value = null;
try {
field.setAccessible(true);
value = field.get(object);
} catch (IllegalAccessException e) {
log.error("Failed to handle properties", e);
}
if (value != null) {
properties.setProperty(name, value.toString());
}
}
}
}
return properties;
}
public static void properties2Object(final Properties p, final Object object) {
Method[] methods = object.getClass().getMethods();
for (Method method : methods) {
String mn = method.getName();
if (mn.startsWith("set")) {
try {
String tmp = mn.substring(4);
String first = mn.substring(3, 4);
String key = first.toLowerCase() + tmp;
String property = p.getProperty(key);
if (property != null) {
Class<?>[] pt = method.getParameterTypes();
if (pt != null && pt.length > 0) {
String cn = pt[0].getSimpleName();
Object arg = null;
if (cn.equals("int") || cn.equals("Integer")) {
arg = Integer.parseInt(property);
} else if (cn.equals("long") || cn.equals("Long")) {
arg = Long.parseLong(property);
} else if (cn.equals("double") || cn.equals("Double")) {
arg = Double.parseDouble(property);
} else if (cn.equals("boolean") || cn.equals("Boolean")) {
arg = Boolean.parseBoolean(property);
} else if (cn.equals("float") || cn.equals("Float")) {
arg = Float.parseFloat(property);
} else if (cn.equals("String")) {
arg = property;
} else {
continue;
}
method.invoke(object, arg);
}
}
} catch (Throwable ignored) {
}
}
}
}
public static boolean isPropertiesEqual(final Properties p1, final Properties p2) {
return p1.equals(p2);
}
public static List<String> getLocalInetAddress() {
List<String> inetAddressList = new ArrayList<String>();
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = enumeration.nextElement();
Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
while (addrs.hasMoreElements()) {
inetAddressList.add(addrs.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
throw new RuntimeException("get local inet address fail", e);
}
return inetAddressList;
}
public static boolean isLocalAddr(String address) {
for (String addr : LOCAL_INET_ADDRESS) {
if (address.contains(addr))
return true;
}
return false;
}
private static String localhost() {
try {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostAddress();
} catch (Throwable e) {
try {
String candidatesHost = getLocalhostByNetworkInterface();
if (candidatesHost != null)
return candidatesHost;
} catch (Exception ignored) {
}
throw new RuntimeException("InetAddress java.net.InetAddress.getLocalHost() throws UnknownHostException"
+ FAQUrl.suggestTodo(FAQUrl.UNKNOWN_HOST_EXCEPTION),
e);
}
}
private static String getLocalhostByNetworkInterface() throws SocketException {
List<String> candidatesHost = new ArrayList<String>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = enumeration.nextElement();
if ("docker0".equals(networkInterface.getName()) || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress address = addrs.nextElement();
if (address.isLoopbackAddress()) {
continue;
}
//ip4 highter priority
if (address instanceof Inet6Address) {
candidatesHost.add(address.getHostAddress());
continue;
}
return address.getHostAddress();
}
}
if (!candidatesHost.isEmpty()) {
return candidatesHost.get(0);
}
return null;
}
public static boolean compareAndIncreaseOnly(final AtomicLong target, final long value) {
long prev = target.get();
while (value > prev) {
boolean updated = target.compareAndSet(prev, value);
if (updated)
return true;
prev = target.get();
}
return false;
}
public static String localhostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (Throwable e) {
throw new RuntimeException("InetAddress java.net.InetAddress.getLocalHost() throws UnknownHostException"
+ FAQUrl.suggestTodo(FAQUrl.UNKNOWN_HOST_EXCEPTION),
e);
}
}
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit)
return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
public Set<String> list2Set(List<String> values) {
Set<String> result = new HashSet<String>();
for (String v : values) {
result.add(v);
}
return result;
}
public List<String> set2List(Set<String> values) {
List<String> result = new ArrayList<String>();
for (String v : values) {
result.add(v);
}
return result;
}
}