-
Notifications
You must be signed in to change notification settings - Fork 90
/
IgniteUtils.java
1263 lines (1101 loc) · 42.7 KB
/
IgniteUtils.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.ignite.internal.util;
import static java.util.Arrays.copyOfRange;
import static java.util.concurrent.CompletableFuture.allOf;
import static java.util.concurrent.CompletableFuture.failedFuture;
import static org.apache.ignite.lang.ErrorGroups.Common.NODE_STOPPING_ERR;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.ignite.internal.close.ManuallyCloseable;
import org.apache.ignite.internal.lang.IgniteInternalException;
import org.apache.ignite.internal.lang.IgniteStringFormatter;
import org.apache.ignite.internal.lang.NodeStoppingException;
import org.apache.ignite.internal.logger.IgniteLogger;
import org.apache.ignite.internal.manager.ComponentContext;
import org.apache.ignite.internal.manager.IgniteComponent;
import org.apache.ignite.internal.util.worker.IgniteWorker;
import org.jetbrains.annotations.Nullable;
/**
* Collection of utility methods used throughout the system.
*/
public class IgniteUtils {
/** The moment will be used as a start monotonic time. */
private static final long BEGINNING_OF_TIME = System.nanoTime();
/** Version of the JDK. */
private static final String jdkVer = System.getProperty("java.specification.version");
/** Class loader used to load Ignite. */
private static final ClassLoader igniteClassLoader = IgniteUtils.class.getClassLoader();
/** Indicates that assertions are enabled. */
private static final boolean assertionsEnabled = IgniteUtils.class.desiredAssertionStatus();
/**
* Gets the current monotonic time in milliseconds. This is the amount of milliseconds which passed from an arbitrary moment in the
* past.
*/
public static long monotonicMs() {
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - BEGINNING_OF_TIME);
}
/** Primitive class map. */
private static final Map<String, Class<?>> primitiveMap = Map.of(
"byte", byte.class,
"short", short.class,
"int", int.class,
"long", long.class,
"float", float.class,
"double", double.class,
"char", char.class,
"boolean", boolean.class,
"void", void.class
);
/** Class cache. */
private static final ConcurrentMap<ClassLoader, ConcurrentMap<String, Class<?>>> classCache = new ConcurrentHashMap<>();
/**
* Root package for JMX MBeans.
*/
private static final String JMX_MBEAN_PACKAGE = "org.apache";
/**
* Get JDK version.
*
* @return JDK version.
*/
public static String jdkVersion() {
return jdkVer;
}
/**
* Get major Java version from a string.
*
* @param verStr Version string.
* @return Major version or zero if failed to resolve.
*/
public static int majorJavaVersion(String verStr) {
if (verStr == null || verStr.isEmpty()) {
return 0;
}
try {
String[] parts = verStr.split("\\.");
int major = Integer.parseInt(parts[0]);
if (parts.length == 1) {
return major;
}
int minor = Integer.parseInt(parts[1]);
return major == 1 ? minor : major;
} catch (Exception e) {
return 0;
}
}
/**
* Returns the amount of RAM memory available on this machine.
*
* @return Total amount of memory in bytes or {@code -1} if any exception happened.
*/
public static long getTotalMemoryAvailable() {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
Object attr;
try {
attr = mbeanServer.getAttribute(
ObjectName.getInstance("java.lang", "type", "OperatingSystem"),
"TotalPhysicalMemorySize"
);
} catch (Exception e) {
return -1;
}
return (attr instanceof Long) ? (Long) attr : -1;
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as long as it grows no larger than expSize and the load
* factor is >= its default (0.75).
*
* <p>Copy pasted from guava. See com.google.common.collect.Maps#capacity(int)
*
* @param expSize Expected size of the created map.
* @return Capacity.
*/
public static int capacity(int expSize) {
if (expSize < 3) {
return expSize + 1;
}
if (expSize < (1 << 30)) {
return expSize + expSize / 3;
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates new {@link HashMap} with expected size.
*
* @param expSize Expected size of the created map.
* @param <K> Type of the map's keys.
* @param <V> Type of the map's values.
* @return New map.
*/
public static <K, V> HashMap<K, V> newHashMap(int expSize) {
return new HashMap<>(capacity(expSize));
}
/**
* Creates new {@link LinkedHashMap} with expected size.
*
* @param expSize Expected size of created map.
* @param <K> Type of the map's keys.
* @param <V> Type of the map's values.
* @return New map.
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int expSize) {
return new LinkedHashMap<>(capacity(expSize));
}
/**
* Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical
* because ConcurrentHashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ
* in lower or upper bits.
*
* <p>This function has been taken from Java 8 ConcurrentHashMap with slightly modifications.
*
* @param h Value to hash.
* @return Hash value.
*/
public static int hash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical
* because ConcurrentHashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ
* in lower or upper bits.
*
* <p>This function has been taken from Java 8 ConcurrentHashMap with slightly modifications.
*
* @param obj Value to hash.
* @return Hash value.
*/
public static int hash(Object obj) {
return hash(obj.hashCode());
}
/**
* A primitive override of {@link #hash(Object)} to avoid unnecessary boxing.
*
* @param key Value to hash.
* @return Hash value.
*/
public static int hash(long key) {
int val = (int) (key ^ (key >>> 32));
return hash(val);
}
/**
* Returns size in human-readable format.
*
* @param bytes Number of bytes to display.
* @param si If {@code true}, then unit base is 1000, otherwise unit base is 1024.
* @return Formatted size.
*/
public static String readableSize(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);
}
/**
* Gets absolute value for integer. If integer is {@link Integer#MIN_VALUE}, then {@code 0} is returned.
*
* @param i Integer.
* @return Absolute value.
*/
public static int safeAbs(int i) {
return Math.max(Math.abs(i), 0);
}
/**
* Gets absolute value for long. If long is {@link Long#MIN_VALUE}, then {@code 0} is returned.
*
* @param i Long value.
* @return Absolute value.
*/
public static long safeAbs(long i) {
return Math.max(Math.abs(i), 0);
}
/**
* Returns a first non-null value in a given array, if such is present.
*
* @param vals Input array.
* @return First non-null value, or {@code null}, if array is empty or contains only nulls.
*/
@SafeVarargs
@Nullable
public static <T> T firstNotNull(@Nullable T... vals) {
if (vals == null) {
return null;
}
for (T val : vals) {
if (val != null) {
return val;
}
}
return null;
}
/**
* Returns class loader used to load Ignite itself.
*
* @return Class loader used to load Ignite itself.
*/
public static ClassLoader igniteClassLoader() {
return igniteClassLoader;
}
/**
* Gets class for provided name. Accepts primitive types names.
*
* @param clsName Class name.
* @param ldr Class loader.
* @return Class.
* @throws ClassNotFoundException If class not found.
*/
public static Class<?> forName(String clsName, @Nullable ClassLoader ldr) throws ClassNotFoundException {
return forName(clsName, ldr, null);
}
/**
* Gets class for provided name. Accepts primitive types names.
*
* @param clsName Class name.
* @param ldr Class loader.
* @param clsFilter Predicate to filter class names.
* @return Class.
* @throws ClassNotFoundException If class not found.
*/
public static Class<?> forName(
String clsName,
@Nullable ClassLoader ldr,
@Nullable Predicate<String> clsFilter
) throws ClassNotFoundException {
assert clsName != null;
Class<?> cls = primitiveMap.get(clsName);
if (cls != null) {
return cls;
}
if (ldr == null) {
ldr = igniteClassLoader;
}
ConcurrentMap<String, Class<?>> ldrMap = classCache.get(ldr);
if (ldrMap == null) {
ConcurrentMap<String, Class<?>> old = classCache.putIfAbsent(ldr, ldrMap = new ConcurrentHashMap<>());
if (old != null) {
ldrMap = old;
}
}
cls = ldrMap.get(clsName);
if (cls == null) {
if (clsFilter != null && !clsFilter.test(clsName)) {
throw new ClassNotFoundException("Deserialization of class " + clsName + " is disallowed.");
}
cls = Class.forName(clsName, true, ldr);
Class<?> old = ldrMap.putIfAbsent(clsName, cls);
if (old != null) {
cls = old;
}
}
return cls;
}
/**
* Deletes a file or a directory with all sub-directories and files.
*
* @param path File or directory to delete.
* @return {@code true} if the file or directory is successfully deleted or does not exist, {@code false} otherwise
*/
public static boolean deleteIfExists(Path path) {
try {
deleteIfExistsThrowable(path);
return true;
} catch (NoSuchFileException e) {
return true;
} catch (IOException e) {
return false;
}
}
/**
* Deletes a file or a directory with all sub-directories and files.
*
* @param path File or directory to delete.
* @throws IOException if an I/O error is thrown by a visitor method
*/
public static void deleteIfExistsThrowable(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Calls fsync on a directory.
*
* @param dir Path to the directory.
* @throws IOException If an I/O error occurs.
*/
public static void fsyncDir(Path dir) throws IOException {
assert Files.isDirectory(dir) : dir;
// Fsync for directories doesn't work on Windows.
if (OperatingSystem.current() == OperatingSystem.WINDOWS) {
return;
}
try (FileChannel fc = FileChannel.open(dir, StandardOpenOption.READ)) {
fc.force(true);
}
}
/**
* Calls fsync on a file.
*
* @param file Path to the file.
* @throws IOException If an I/O error occurs.
*/
public static void fsyncFile(Path file) throws IOException {
assert Files.isRegularFile(file) : file;
try (FileChannel fc = FileChannel.open(file, StandardOpenOption.WRITE)) {
fc.force(true);
}
}
/**
* Checks if assertions enabled.
*
* @return {@code true} if assertions enabled.
*/
public static boolean assertionsEnabled() {
return assertionsEnabled;
}
/**
* Shuts down the given executor service gradually, first disabling new submissions and later, if necessary, cancelling remaining
* tasks.
*
* <p>The method takes the following steps:
*
* <ol>
* <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks.
* <li>awaits executor service termination for half of the specified timeout.
* <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling
* pending tasks and interrupting running tasks.
* <li>awaits executor service termination for the other half of the specified timeout.
* </ol>
*
* <p>If, at any step of the process, the calling thread is interrupted, the method calls {@link
* ExecutorService#shutdownNow()} and returns.
*
* @param service the {@code ExecutorService} to shut down
* @param timeout the maximum time to wait for the {@code ExecutorService} to terminate
* @param unit the time unit of the timeout argument
*/
public static void shutdownAndAwaitTermination(@Nullable ExecutorService service, long timeout, TimeUnit unit) {
if (service == null) {
return;
}
long halfTimeoutNanos = unit.toNanos(timeout) / 2;
// Disable new tasks from being submitted
service.shutdown();
try {
// Wait for half the duration of the timeout for existing tasks to terminate
if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) {
// Cancel currently executing tasks
service.shutdownNow();
// Wait the other half of the timeout for tasks to respond to being cancelled
service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS);
}
} catch (InterruptedException ie) {
// Preserve interrupt status
Thread.currentThread().interrupt();
// (Re-)Cancel if current thread also interrupted
service.shutdownNow();
}
}
/**
* Closes all provided objects. If any of the {@link AutoCloseable#close} methods throw an exception, only the first thrown exception
* will be propagated to the caller, after all other objects are closed, similar to the try-with-resources block.
*
* @param closeables Stream of objects to close.
* @throws Exception If failed to close.
*/
public static void closeAll(Stream<? extends AutoCloseable> closeables) throws Exception {
AtomicReference<Throwable> ex = new AtomicReference<>();
closeables.filter(Objects::nonNull).forEach(closeable -> {
try {
closeable.close();
} catch (Throwable e) {
if (!ex.compareAndSet(null, e)) {
ex.get().addSuppressed(e);
}
}
});
if (ex.get() != null) {
throw ExceptionUtils.sneakyThrow(ex.get());
}
}
/**
* Closes all provided objects. If any of the {@link AutoCloseable#close} methods throw an exception, only the first thrown exception
* will be propagated to the caller, after all other objects are closed, similar to the try-with-resources block.
*
* @param closeables Collection of objects to close.
* @throws Exception If failed to close.
*/
public static void closeAll(Collection<? extends AutoCloseable> closeables) throws Exception {
closeAll(closeables.stream());
}
/**
* Closes all provided objects.
*
* @param closeables Array of closeable objects to close.
* @throws Exception If failed to close.
* @see #closeAll(Collection)
*/
public static void closeAll(AutoCloseable... closeables) throws Exception {
closeAll(Arrays.stream(closeables));
}
/**
* Closes all provided objects. If any of the {@link ManuallyCloseable#close} methods throw an exception, only the first thrown
* exception will be propagated to the caller, after all other objects are closed, similar to the try-with-resources block.
*
* @param closeables Stream of objects to close.
* @throws Exception If failed to close.
*/
public static void closeAllManually(Stream<? extends ManuallyCloseable> closeables) throws Exception {
AtomicReference<Throwable> ex = new AtomicReference<>();
closeables.filter(Objects::nonNull).forEach(closeable -> {
try {
closeable.close();
} catch (Throwable e) {
if (!ex.compareAndSet(null, e)) {
ex.get().addSuppressed(e);
}
}
});
if (ex.get() != null) {
throw ExceptionUtils.sneakyThrow(ex.get());
}
}
/**
* Closes all provided objects.
*
* @param closeables Collection of closeable objects to close.
* @throws Exception If failed to close.
* @see #closeAll(Collection)
*/
public static void closeAllManually(Collection<? extends ManuallyCloseable> closeables) throws Exception {
closeAllManually(closeables.stream());
}
/**
* Closes all provided objects.
*
* @param closeables Array of closeable objects to close.
* @throws Exception If failed to close.
* @see #closeAll(Collection)
*/
public static void closeAllManually(ManuallyCloseable... closeables) throws Exception {
closeAllManually(Arrays.stream(closeables));
}
/**
* Short date format pattern for log messages in "quiet" mode. Only time is included since we don't expect "quiet" mode to be used for
* longer runs.
*/
private static final DateTimeFormatter SHORT_DATE_FMT = DateTimeFormatter.ofPattern("HH:mm:ss");
/**
* Prints stack trace of the current thread to provided logger.
*
* @param log Logger.
* @param msg Message to print with the stack.
* @deprecated Calls to this method should never be committed to master.
*/
@Deprecated
public static void dumpStack(IgniteLogger log, String msg, Object... params) {
String reason = "Dumping stack";
var err = new Exception(IgniteStringFormatter.format(msg, params));
if (log != null) {
log.warn(reason, err);
} else {
System.err.println("[" + LocalDateTime.now().format(SHORT_DATE_FMT) + "] (err) " + reason);
err.printStackTrace(System.err);
}
}
/**
* Atomically moves or renames a file to a target file.
*
* @param sourcePath The path to the file to move.
* @param targetPath The path to the target file.
* @param log Optional logger.
* @return The path to the target file.
* @throws IOException If the source file cannot be moved to the target.
*/
public static Path atomicMoveFile(Path sourcePath, Path targetPath, @Nullable IgniteLogger log) throws IOException {
// Move temp file to target path atomically.
// The code comes from
// https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/util/AtomicFileWriter.java#L187
Objects.requireNonNull(sourcePath, "sourcePath");
Objects.requireNonNull(targetPath, "targetPath");
Path success;
try {
success = Files.move(sourcePath, targetPath, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
// If it falls here that can mean many things. Either that the atomic move is not supported,
// or something wrong happened. Anyway, let's try to be over-diagnosing
if (log != null) {
if (e instanceof AtomicMoveNotSupportedException) {
log.info("Atomic move not supported. Falling back to non-atomic move [reason={}]", e.getMessage());
} else {
log.info("Unable to move atomically. Falling back to non-atomic move [reason={}]", e.getMessage());
}
if (targetPath.toFile().exists() && log.isInfoEnabled()) {
log.info("The target file already exists [path={}]", targetPath);
}
}
try {
success = Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e1) {
e1.addSuppressed(e);
if (log != null) {
log.warn("Unable to move file. Going to delete source [sourcePath={}, targetPath={}]",
sourcePath,
targetPath
);
}
try {
Files.deleteIfExists(sourcePath);
} catch (IOException e2) {
e2.addSuppressed(e1);
if (log != null) {
log.warn("Unable to delete file [path={}]", sourcePath);
}
throw e2;
}
throw e1;
}
}
return success;
}
/**
* Return {@code obj} if not null, otherwise {@code defaultObj}.
*
* @param obj Object.
* @param defaultObj Default object.
* @param <O> Object type.
* @return Object or default object.
*/
public static <O> O nonNullOrElse(@Nullable O obj, O defaultObj) {
return (obj != null) ? obj : defaultObj;
}
/**
* Returns {@code true} If the given value is power of 2 (0 is not power of 2).
*
* @param i Value.
*/
public static boolean isPow2(int i) {
return i > 0 && (i & (i - 1)) == 0;
}
/**
* Returns {@code true} If the given value is power of 2 (0 is not power of 2).
*
* @param i Value.
*/
public static boolean isPow2(long i) {
return i > 0 && (i & (i - 1)) == 0;
}
/**
* Waits if necessary for this future to complete, and then returns its result ignoring interrupts.
*
* @return Result value.
* @throws CancellationException If this future was cancelled.
* @throws ExecutionException If this future completed exceptionally.
*/
public static <T> T getUninterruptibly(CompletableFuture<T> future) throws ExecutionException {
boolean interrupted = false;
try {
while (true) {
try {
return future.get();
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Stops workers from given collection and waits for their completion.
*
* @param workers Workers collection.
* @param cancel Whether it should cancel workers.
* @param log Logger.
*/
public static void awaitForWorkersStop(Collection<IgniteWorker> workers, boolean cancel, @Nullable IgniteLogger log) {
if (cancel) {
workers.forEach(IgniteWorker::cancel);
}
for (IgniteWorker worker : workers) {
try {
worker.join();
} catch (Exception e) {
if (log != null && log.isWarnEnabled()) {
log.debug("Unable to cancel ignite worker [worker={}, reason={}]", worker.toString(), e.getMessage());
}
}
}
}
/**
* Method that runs the provided {@code fn} in {@code busyLock}.
*
* @param busyLock Component's busy lock.
* @param fn Function to run.
* @param <T> Type of returned value from {@code fn}.
* @return Result of the provided function.
* @throws IgniteInternalException with cause {@link NodeStoppingException} if {@link IgniteSpinBusyLock#enterBusy()} failed.
*/
public static <T> T inBusyLock(IgniteSpinBusyLock busyLock, Supplier<T> fn) {
if (!busyLock.enterBusy()) {
throw new IgniteInternalException(NODE_STOPPING_ERR, new NodeStoppingException());
}
try {
return fn.get();
} finally {
busyLock.leaveBusy();
}
}
/**
* Method that runs the provided {@code fn} in {@code busyLock}.
*
* @param busyLock Component's busy lock.
* @param fn Function to run.
* @return Result of the provided function.
* @throws IgniteInternalException with cause {@link NodeStoppingException} if {@link IgniteSpinBusyLock#enterBusy()} failed.
*/
public static int inBusyLock(IgniteSpinBusyLock busyLock, IntSupplier fn) {
if (!busyLock.enterBusy()) {
throw new IgniteInternalException(NODE_STOPPING_ERR, new NodeStoppingException());
}
try {
return fn.getAsInt();
} finally {
busyLock.leaveBusy();
}
}
/**
* Method that runs the provided {@code fn} in {@code busyLock}.
*
* @param busyLock Component's busy lock.
* @param fn Runnable to run.
* @throws IgniteInternalException with cause {@link NodeStoppingException} if {@link IgniteSpinBusyLock#enterBusy()} failed.
*/
public static void inBusyLock(IgniteSpinBusyLock busyLock, Runnable fn) {
if (!busyLock.enterBusy()) {
throw new IgniteInternalException(NODE_STOPPING_ERR, new NodeStoppingException());
}
try {
fn.run();
} finally {
busyLock.leaveBusy();
}
}
/**
* Method that runs the provided {@code fn} in {@code busyLock}.
*
* @param <T> Type of returned value from {@code fn}.
* @param busyLock Component's busy lock.
* @param fn Function to run.
* @return Future returned from the {@code fn}, or future with the {@link NodeStoppingException} if
* {@link IgniteSpinBusyLock#enterBusy()} failed or with runtime exception/error while executing the {@code fn}.
*/
public static <T> CompletableFuture<T> inBusyLockAsync(IgniteSpinBusyLock busyLock, Supplier<CompletableFuture<T>> fn) {
if (!busyLock.enterBusy()) {
return failedFuture(new NodeStoppingException());
}
try {
return fn.get();
} catch (Throwable t) {
return failedFuture(t);
} finally {
busyLock.leaveBusy();
}
}
/**
* Method that runs the provided {@code fn} in {@code busyLock} if {@link IgniteSpinBusyLock#enterBusy()} succeed. Otherwise it just
* silently returns.
*
* @param busyLock Component's busy lock.
* @param fn Runnable to run.
*/
public static void inBusyLockSafe(IgniteSpinBusyLock busyLock, Runnable fn) {
if (!busyLock.enterBusy()) {
return;
}
try {
fn.run();
} finally {
busyLock.leaveBusy();
}
}
/**
* Collects all the fields of given class which are defined as a public static within the specified class.
*
* @param sourceCls The class to lookup fields in.
* @param targetCls Type of the fields of interest.
* @return A mapping name to property itself.
*/
public static <T> List<T> collectStaticFields(Class<?> sourceCls, Class<? extends T> targetCls) {
List<T> result = new ArrayList<>();
for (Field f : sourceCls.getDeclaredFields()) {
if (!targetCls.equals(f.getType())
|| !Modifier.isStatic(f.getModifiers())
|| !Modifier.isPublic(f.getModifiers())) {
continue;
}
try {
T value = targetCls.cast(f.get(sourceCls));
result.add(value);
} catch (IllegalAccessException e) {
// should not happen
throw new AssertionError(e);
}
}
return result;
}
/**
* Cancels the future and runs a consumer on future's result if it was completed before the cancellation. Does nothing if future is
* cancelled or completed exceptionally.
*
* @param future Future.
* @param consumer Consumer that accepts future's result.
* @param <T> Future's result type.
*/
public static <T> void cancelOrConsume(CompletableFuture<T> future, Consumer<T> consumer) {
future.cancel(true);
if (future.isCancelled() || future.isCompletedExceptionally()) {
return;
}
assert future.isDone();
T res = future.join();
assert res != null;
consumer.accept(res);
}
/**
* Produce new MBean name according to received group and name.
*
* @param group pkg:group=value part of MBean name.
* @param name pkg:name=value part of MBean name.
* @return new ObjectName.
* @throws MalformedObjectNameException if MBean name can't be formed from the received arguments.
*/
public static ObjectName makeMbeanName(String group, String name) throws MalformedObjectNameException {
return new ObjectName(String.format("%s:group=%s,name=%s", JMX_MBEAN_PACKAGE, group, name));
}
/**
* Filter the collection using the given predicate.
*
* @param collection Collection.
* @param predicate Predicate.
* @return Filtered list.
*/
public static <T> List<T> filter(Collection<T> collection, Predicate<T> predicate) {
List<T> result = new ArrayList<>();
for (T e : collection) {
if (predicate.test(e)) {
result.add(e);
}
}
return result;
}