Package org.apache.storm.utils
Class Utils
java.lang.Object
org.apache.storm.utils.Utils
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
A thread that can answer if it is sleeping in the case of simulated time.static class
-
Field Summary
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
addShutdownHookWithDelayedForceKill
(Runnable func, int numSecs) Adds the user supplied function as a shutdown hook for cleanup.static void
Adds the user supplied function as a shutdown hook for cleanup.static StormTopology
addVersions
(StormTopology topology) Add version information to the given topology.static Utils.SmartThread
Convenience method used when only the function is given.static Utils.SmartThread
asyncLoop
(Callable afn, boolean isDaemon, Thread.UncaughtExceptionHandler eh, int priority, boolean isFactory, boolean startImmediately, String threadName) Creates a thread that calls the given code repeatedly, sleeping for an interval of seconds equal to the return value of the previous call.static Utils.SmartThread
asyncLoop
(Callable afn, String threadName, Thread.UncaughtExceptionHandler eh) Convenience method used when only the function and name suffix are given.static long
static long
bitXorVals
(List<Long> coll) static boolean
checkDirExists
(String dir) static boolean
checkFileExists
(String path) static <V> ArrayList<V>
convertToArray
(Map<Integer, V> srcMap, int start) static <T> T
deserialize
(byte[] serialized, Class<T> clazz) static <T> T
deserializeFromString
(String str, Class<T> clazz) Deserialize an object stored in a string.static boolean
exceptionCauseIsInstanceOf
(Class klass, Throwable throwable) Checks if a throwable is an instance of a particular class.static void
exitProcess
(int val, String msg) findAndReadConfigFile
(String name) findAndReadConfigFile
(String name, boolean mustExist) findComponentCycles
(StormTopology topology, String topoId) Find and return components cycles in the topology graph when starting from spout.static <T> T
findOne
(IPredicate<T> pred, Collection<T> coll) Find the first item of coll for which pred.test(...) returns true.static <T,
U> T findOne
(IPredicate<T> pred, Map<U, T> map) findResources
(String name) static void
forceDelete
(String path) Deletes a file or directory and its contents if it exists.protected void
forceDeleteImpl
(String path) fromCompressedJsonConf
(byte[] serialized) static <S,
T> T static NavigableMap<String,
IVersionInfo> getAlternativeVersionsMap
(Map<String, Object> conf) Get a mapping of the configured supported versions of storm to their actual versions.static int
Shortcut to callinggetAvailablePort(int)
with 0 as the preferred port.static int
getAvailablePort
(int preferredPort) Gets an available port.static ClientBlobStore
getClientBlobStore
(Map<String, Object> conf) static <T> T
getCompatibleVersion
(NavigableMap<SimpleVersion, T> versionedMap, SimpleVersion desiredVersion, String what, T defaultValue) static ComponentCommon
getComponentCommon
(StormTopology topology, String id) static Object
getConfiguredClass
(Map<String, Object> conf, Object configKey) Return a new instance of a pluggable specified in the conf.static NavigableMap<SimpleVersion,
List<String>> Get a map of version to classpath from the conf Config.SUPERVISOR_WORKER_VERSION_CLASSPATH_MAPstatic NavigableMap<SimpleVersion,
String> Get a map of version to worker log writer from the conf Config.SUPERVISOR_WORKER_VERSION_LOGWRITER_MAPstatic NavigableMap<SimpleVersion,
String> Get a map of version to worker main from the conf Config.SUPERVISOR_WORKER_VERSION_MAIN_MAPstatic GlobalStreamId
getGlobalStreamId
(String componentId, String streamId) static Object
static org.apache.storm.shade.org.apache.zookeeper.data.ACL
getSuperUserAcl
(Map<String, Object> conf) Get the ACL for nimbus/supervisor.static String
getTopologyId
(String name, Nimbus.Iface client) static TopologyInfo
static List<org.apache.storm.shade.org.apache.zookeeper.data.ACL>
getWorkerACL
(Map<String, Object> conf) Get the ZK ACLs that a worker should use when writing to ZK.static byte[]
gunzip
(byte[] data) static byte[]
gzip
(byte[] data) static void
static void
handleUncaughtException
(Throwable t, Set<Class<?>> allowedExceptions, boolean worker) Handles uncaught exceptions.static void
static String
hostname()
Gets the storm.local.hostname value, or tries to figure out the local hostname if it is not set in the config.protected String
integerDivided
(int sum, int numPieces) static boolean
isLocalhostAddress
(String address) static boolean
static boolean
isSystemId
(String id) static boolean
isValidConf
(Map<String, Object> topoConfIn) static boolean
isValidKey
(String key) Validates blob key.static boolean
Is the cluster configured to interact with ZooKeeper in a secure way?static boolean
Is the topology configured to have ZooKeeper authentication.static <T> T
javaDeserialize
(byte[] serialized, Class<T> clazz) static byte[]
javaSerialize
(Object obj) static <T> String
static String
protected String
static Utils.UptimeComputer
static String
static <K,
V> Map<K, V> static Runnable
static double
nullToZero
(Double v) static <V> V
OR
(V a, V b) a or b the first one that is not null.static Double
parseJvmHeapMemByChildOpts
(List<String> options, Double defaultValue) parses the arguments to extract jvm heap memory size in MB.static org.apache.storm.shade.org.apache.zookeeper.data.Id
partitionFixed
(int maxNumChunks, Collection<T> coll) Fills up chunks out of a collection (given a maximum amount of chunks).static String
Get process PID.static void
readAndLogStream
(String prefix, InputStream in) static Object
readYamlFile
(String yamlFile) redactValue
(Map<String, Object> m, String key) Creates a new map with a string value in the map replaced with an equivalently-lengthed string of '#'.static void
reverseMap
(List<List<Object>> listSeq) "[[:a 1] [:b 1] [:c 2]} -> {1 [:a :b] 2 :c}" Reverses an assoc-list style Map like reverseMap(Map...)reverseMap
(Map<K, V> map) "{:a 1 :b 1 :c 2} -> {1 [:a :b] 2 :c}"
.static long
static byte[]
static String
serializeToString
(Object obj) Serialize an object using the configured serialization and then base64 encode it into a string.static void
static Utils
setInstance
(Utils u) Provide an instance of this class for delegates to use.static void
static void
static void
sleep
(long millis) static void
sleepNoSimulation
(long millis) static String
Gets some information, including stack trace, for a running thread.static <T> T
thriftDeserialize
(Class<T> c, byte[] b) static <T> T
thriftDeserialize
(Class<T> c, byte[] b, int offset, int length) static byte[]
thriftSerialize
(org.apache.storm.thrift.TBase t) static byte[]
toByteArray
(ByteBuffer buffer) static byte[]
toCompressedJsonConf
(Map<String, Object> topoConf) static int
toPositive
(int number) A cheap way to deterministically convert a number to a positive value.static <T extends Throwable>
voidunwrapAndThrow
(Class<T> klass, Throwable t) static <T extends Throwable>
Tstatic String
URL decode the given string using the UTF-8 charset.static String
URL encode the given string using the UTF-8 charset.static String
uuid()
static void
validateCycleFree
(StormTopology topology, String name) Validate that the topology is cycle free.static void
validateTopologyBlobStoreMap
(Map<String, Object> topoConf) Validate topology blobstore map.static void
validateTopologyBlobStoreMap
(Map<String, Object> topoConf, BlobStore blobStore) Validate topology blobstore map.static void
validateTopologyBlobStoreMap
(Map<String, Object> topoConf, NimbusBlobStore client) Validate topology blobstore map.static void
validateTopologyName
(String name) Validates topology name.static RuntimeException
static double
zeroIfNaNOrInf
(double x)
-
Field Details
-
LOG
public static final org.slf4j.Logger LOG -
DEFAULT_STREAM_ID
- See Also:
-
BLOB_KEY_PATTERN
-
-
Constructor Details
-
Utils
public Utils()
-
-
Method Details
-
setInstance
Provide an instance of this class for delegates to use. To mock out delegated methods, provide an instance of a subclass that overrides the implementation of the delegated method.- Parameters:
u
- a Utils instance- Returns:
- the previously set instance
-
setClassLoaderForJavaDeSerialize
-
resetClassLoaderForJavaDeSerialize
public static void resetClassLoaderForJavaDeSerialize() -
findResources
-
findAndReadConfigFile
-
findAndReadConfigFile
-
readDefaultConfig
-
urlEncodeUtf8
URL encode the given string using the UTF-8 charset. Once Storm is baselined to Java 11, we can use URLEncoder.encode(String, Charset) instead, which obsoletes this method. -
urlDecodeUtf8
URL decode the given string using the UTF-8 charset. Once Storm is baselined to Java 11, we can use URLDecoder.decode(String, Charset) instead, which obsoletes this method. -
readCommandLineOpts
-
readStormConfig
-
bitXorVals
-
bitXor
-
addShutdownHookWithForceKillIn1Sec
Adds the user supplied function as a shutdown hook for cleanup. Also adds a function that sleeps for a second and then halts the runtime to avoid any zombie process in case cleanup function hangs. -
addShutdownHookWithDelayedForceKill
Adds the user supplied function as a shutdown hook for cleanup. Also adds a function that sleeps for numSecs and then halts the runtime to avoid any zombie process in case cleanup function hangs. -
isSystemId
-
asyncLoop
public static Utils.SmartThread asyncLoop(Callable afn, boolean isDaemon, Thread.UncaughtExceptionHandler eh, int priority, boolean isFactory, boolean startImmediately, String threadName) Creates a thread that calls the given code repeatedly, sleeping for an interval of seconds equal to the return value of the previous call.The given afn may be a callable that returns the number of seconds to sleep, or it may be a Callable that returns another Callable that in turn returns the number of seconds to sleep. In the latter case isFactory.
- Parameters:
afn
- the code to call on each iterationisDaemon
- whether the new thread should be a daemon threadeh
- code to call when afn throws an exceptionpriority
- the new thread's priorityisFactory
- whether afn returns a callable instead of sleep secondsstartImmediately
- whether to start the thread before returningthreadName
- a suffix to be appended to the thread name- Returns:
- the newly created thread
- See Also:
-
asyncLoop
public static Utils.SmartThread asyncLoop(Callable afn, String threadName, Thread.UncaughtExceptionHandler eh) Convenience method used when only the function and name suffix are given.- Parameters:
afn
- the code to call on each iterationthreadName
- a suffix to be appended to the thread name- Returns:
- the newly created thread
- See Also:
-
asyncLoop
Convenience method used when only the function is given.- Parameters:
afn
- the code to call on each iteration- Returns:
- the newly created thread
-
exceptionCauseIsInstanceOf
Checks if a throwable is an instance of a particular class.- Parameters:
klass
- The class you're expectingthrowable
- The throwable you expect to be an instance of klass- Returns:
- true if throwable is instance of klass, false otherwise.
-
unwrapTo
-
unwrapAndThrow
- Throws:
T extends Throwable
-
wrapInRuntime
-
secureRandomLong
public static long secureRandomLong() -
hostname
Gets the storm.local.hostname value, or tries to figure out the local hostname if it is not set in the config.- Returns:
- a string representation of the hostname.
- Throws:
UnknownHostException
-
localHostname
- Throws:
UnknownHostException
-
exitProcess
-
uuid
-
javaSerialize
-
javaDeserialize
-
get
-
zeroIfNaNOrInf
public static double zeroIfNaNOrInf(double x) -
join
-
parseZkId
-
getSuperUserAcl
public static org.apache.storm.shade.org.apache.zookeeper.data.ACL getSuperUserAcl(Map<String, Object> conf) Get the ACL for nimbus/supervisor. The Super User ACL. This assumes that security is enabled.- Parameters:
conf
- the config to get the super User ACL from- Returns:
- the super user ACL.
-
getWorkerACL
public static List<org.apache.storm.shade.org.apache.zookeeper.data.ACL> getWorkerACL(Map<String, Object> conf) Get the ZK ACLs that a worker should use when writing to ZK.- Parameters:
conf
- the config for the topology.- Returns:
- the ACLs
-
isZkAuthenticationConfiguredTopology
Is the topology configured to have ZooKeeper authentication.- Parameters:
conf
- the topology configuration- Returns:
- true if ZK is configured else false
-
handleUncaughtException
public static void handleUncaughtException(Throwable t, Set<Class<?>> allowedExceptions, boolean worker) Handles uncaught exceptions.- Parameters:
worker
- true if this is for handling worker exceptions
-
handleUncaughtException
-
handleWorkerUncaughtException
-
thriftSerialize
public static byte[] thriftSerialize(org.apache.storm.thrift.TBase t) -
thriftDeserialize
-
thriftDeserialize
-
sleepNoSimulation
public static void sleepNoSimulation(long millis) -
sleep
public static void sleep(long millis) -
makeUptimeComputer
-
reverseMap
"{:a 1 :b 1 :c 2} -> {1 [:a :b] 2 :c}"
.Example usage in java:
Map<Integer, String> tasks; Map<String, List<Integer>> componentTasks = Utils.reverse_map(tasks);
The order of he resulting list values depends on the ordering properties of the Map passed in. The caller is responsible for passing an ordered map if they expect the result to be consistently ordered as well.
- Parameters:
map
- to reverse- Returns:
- a reversed map
-
reverseMap
"[[:a 1] [:b 1] [:c 2]} -> {1 [:a :b] 2 :c}" Reverses an assoc-list style Map like reverseMap(Map...)- Parameters:
listSeq
- to reverse- Returns:
- a reversed map
-
isOnWindows
public static boolean isOnWindows() -
checkFileExists
-
forceDelete
Deletes a file or directory and its contents if it exists. Does not complain if the input is null or does not exist.- Parameters:
path
- the path to the file or directory- Throws:
IOException
-
serialize
-
deserialize
-
serializeToString
Serialize an object using the configured serialization and then base64 encode it into a string.- Parameters:
obj
- the object to encode- Returns:
- a string with the encoded object in it.
-
deserializeFromString
Deserialize an object stored in a string. The String is assumed to be a base64 encoded string containing the bytes to actually deserialize.- Parameters:
str
- the encoded string.clazz
- the thrift class we are expecting.- Returns:
- the decoded object
-
toByteArray
-
mkSuicideFn
-
readAndLogStream
-
getComponentCommon
-
tuple
-
gzip
public static byte[] gzip(byte[] data) -
gunzip
public static byte[] gunzip(byte[] data) -
getRepeat
-
getGlobalStreamId
-
getSetComponentObject
-
toPositive
public static int toPositive(int number) A cheap way to deterministically convert a number to a positive value. When the input is positive, the original value is returned. When the input number is negative, the returned positive value is the original value bit AND against Integer.MAX_VALUE(0x7fffffff) which is not its absolutely value.- Parameters:
number
- a given number- Returns:
- a positive number.
-
processPid
Get process PID.- Returns:
- the pid of this JVM, because Java doesn't provide a real way to do this.
-
fromCompressedJsonConf
-
redactValue
Creates a new map with a string value in the map replaced with an equivalently-lengthed string of '#'. (If the object is not a string to string will be called on it and replaced)- Parameters:
m
- The map that a value will be redacted fromkey
- The key pointing to the value to be redacted- Returns:
- a new map with the value redacted. The original map will not be modified.
-
createDefaultUncaughtExceptionHandler
-
createWorkerUncaughtExceptionHandler
-
setupDefaultUncaughtExceptionHandler
public static void setupDefaultUncaughtExceptionHandler() -
setupWorkerUncaughtExceptionHandler
public static void setupWorkerUncaughtExceptionHandler() -
parseJvmHeapMemByChildOpts
parses the arguments to extract jvm heap memory size in MB.- Returns:
- the value of the JVM heap memory setting (in MB) in a java command.
-
getClientBlobStore
-
isValidConf
-
getTopologyInfo
-
getTopologyId
-
validateTopologyBlobStoreMap
public static void validateTopologyBlobStoreMap(Map<String, Object> topoConf) throws InvalidTopologyException, AuthorizationExceptionValidate topology blobstore map.- Parameters:
topoConf
- Topology configuration- Throws:
InvalidTopologyException
AuthorizationException
-
validateTopologyBlobStoreMap
public static void validateTopologyBlobStoreMap(Map<String, Object> topoConf, NimbusBlobStore client) throws InvalidTopologyException, AuthorizationExceptionValidate topology blobstore map.- Parameters:
topoConf
- Topology configurationclient
- The NimbusBlobStore client. It must call prepare() before being used here.- Throws:
InvalidTopologyException
AuthorizationException
-
validateTopologyBlobStoreMap
public static void validateTopologyBlobStoreMap(Map<String, Object> topoConf, BlobStore blobStore) throws InvalidTopologyException, AuthorizationExceptionValidate topology blobstore map. -
threadDump
Gets some information, including stack trace, for a running thread.- Returns:
- A human-readable string of the dump.
-
checkDirExists
-
getConfiguredClass
Return a new instance of a pluggable specified in the conf.- Parameters:
conf
- The conf to read from.configKey
- The key pointing to the pluggable class- Returns:
- an instance of the class or null if it is not specified.
-
isZkAuthenticationConfiguredStormServer
Is the cluster configured to interact with ZooKeeper in a secure way? This only works when called from within Nimbus or a Supervisor process.- Parameters:
conf
- the storm configuration, not the topology configuration- Returns:
- true if it is configured else false.
-
toCompressedJsonConf
-
nullToZero
-
OR
public static <V> V OR(V a, V b) a or b the first one that is not null.- Parameters:
a
- somethingb
- something else- Returns:
- a or b the first one that is not null
-
integerDivided
-
partitionFixed
Fills up chunks out of a collection (given a maximum amount of chunks).i.e. partitionFixed(5, [1,2,3]) -> [[1,2,3]] partitionFixed(5, [1..9]) -> [[1,2], [3,4], [5,6], [7,8], [9]] partitionFixed(3, [1..10]) -> [[1,2,3,4], [5,6,7], [8,9,10]]
- Parameters:
maxNumChunks
- the maximum number of chunks to returncoll
- the collection to be chunked up- Returns:
- a list of the chunks, which are themselves lists.
-
readYamlFile
-
getAvailablePort
public static int getAvailablePort(int preferredPort) Gets an available port. Consider if it is possible to pass port 0 to the server instead of using this method, since there is no guarantee that the port returned by this method will remain free.- Returns:
- The preferred port if available, or a random available port
-
getAvailablePort
public static int getAvailablePort()Shortcut to callinggetAvailablePort(int)
with 0 as the preferred port.- Returns:
- A random available port
-
findOne
Find the first item of coll for which pred.test(...) returns true.- Parameters:
pred
- The IPredicate to test forcoll
- The Collection of items to search through.- Returns:
- The first matching value in coll, or null if nothing matches.
-
findOne
-
parseJson
-
memoizedLocalHostname
- Throws:
UnknownHostException
-
addVersions
Add version information to the given topology.- Parameters:
topology
- the topology being submitted (MIGHT BE MODIFIED)- Returns:
- topology
-
getConfiguredClasspathVersions
public static NavigableMap<SimpleVersion,List<String>> getConfiguredClasspathVersions(Map<String, Object> conf, List<String> currentClassPath) Get a map of version to classpath from the conf Config.SUPERVISOR_WORKER_VERSION_CLASSPATH_MAP- Parameters:
conf
- what to read it out ofcurrentClassPath
- the current classpath for this version of storm (not included in the conf, but returned by this)- Returns:
- the map
-
getAlternativeVersionsMap
Get a mapping of the configured supported versions of storm to their actual versions.- Parameters:
conf
- what to read the configuration out of.- Returns:
- the map.
-
getConfiguredWorkerMainVersions
public static NavigableMap<SimpleVersion,String> getConfiguredWorkerMainVersions(Map<String, Object> conf) Get a map of version to worker main from the conf Config.SUPERVISOR_WORKER_VERSION_MAIN_MAP- Parameters:
conf
- what to read it out of- Returns:
- the map
-
getConfiguredWorkerLogWriterVersions
public static NavigableMap<SimpleVersion,String> getConfiguredWorkerLogWriterVersions(Map<String, Object> conf) Get a map of version to worker log writer from the conf Config.SUPERVISOR_WORKER_VERSION_LOGWRITER_MAP- Parameters:
conf
- what to read it out of- Returns:
- the map
-
getConfigFromClasspath
public static Map<String,Object> getConfigFromClasspath(List<String> cp, Map<String, Object> conf) throws IOException- Throws:
IOException
-
isLocalhostAddress
-
merge
-
convertToArray
-
forceDeleteImpl
- Throws:
IOException
-
makeUptimeComputerImpl
-
localHostnameImpl
- Throws:
UnknownHostException
-
hostnameImpl
- Throws:
UnknownHostException
-
isValidKey
Validates blob key.- Parameters:
key
- Key for the blob.
-
validateTopologyName
Validates topology name.- Parameters:
name
- the topology name- Throws:
IllegalArgumentException
- if the topology name is not valid
-
findComponentCycles
Find and return components cycles in the topology graph when starting from spout. Return a list of cycles. Each cycle may consist of one or more components. Components that cannot be reached from any of the spouts are ignored.- Returns:
- a List of cycles. Each cycle has a list of component names.
-
validateCycleFree
public static void validateCycleFree(StormTopology topology, String name) throws InvalidTopologyException Validate that the topology is cycle free. If not, then throw an InvalidTopologyException describing the cycle(s).- Parameters:
topology
- StormTopology instance to examine.name
- Name of the topology, used in exception error message.- Throws:
InvalidTopologyException
- if there are cycles, with message describing the cycles encountered.
-