Package com.linkedin.venice.utils
Class Utils
java.lang.Object
com.linkedin.venice.utils.Utils
Helper functions
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
This class encapsulates config entity information such as config name, default value, config document -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final String
static final String
static final String
static final AtomicBoolean
static final String
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic void
closeQuietlyWithErrorLogged
(Closeable... closeables) static String
composeRealTimeTopic
(String storeName) This method should only be used for system stores.static <T> void
computeIfNotNull
(T t, Consumer<T> function) Run "function" on "t" if "t" is not nullstatic String
createNewRealTimeTopicName
(String oldRealTimeTopicName) static boolean
directoryExists
(String dataDirectory) static String
escapeFilePathComponent
(String component) Method to escape file path component to make it a valid file path string/substring.static void
Print an error and exit with error code 1static void
Print an error and exit with the given error codeextractQueryParamsFromRequest
(Map<String, String[]> sparkRequestParams, ControllerResponse response) getAllSchemasFromResources
(AvroProtocolDefinition protocolDef) static String
getCanonicalPath
(String fileName) Get the full Path of the file.static String
static String
static Map<CharSequence,
CharSequence> static String
getHelixNodeIdentifier
(String hostname, int port) static String
Get the node's host name.static int
static long
static String
getPid()
Note: this may fail in some JVM implementations.static String
getRealTimeTopicName
(Store store) It follows the following order to search for real time topic name, i) current store-version config, ii) store config, iii) other store-version configs, iv) default namestatic String
getRealTimeTopicName
(StoreInfo storeInfo) static String
getRealTimeTopicName
(Version version) static String
static String
getReplicaId
(PubSubTopicPartition topicPartition) Standard logging format for TopicPartitionstatic String
getReplicaId
(PubSubTopic topic, int partition) static String
getReplicaId
(String topic, int partition) getReplicasForInstance
(RoutingDataRepository routingDataRepo, String instanceId) static String
Log4J's class name logging splits at the last "." and assumes it is the class name.static org.apache.avro.Schema
getSchemaFromResource
(String resourcePath) Utility function to get schemas out of embedded resources.static File
static File
getTempDataDirectory
(String prefix) static String
static String
getUniqueString
(String prefix) static String
static String
getUniqueTempPath
(String prefix) static Optional<CharSequence>
getValueFromCharSequenceMapWithStringKey
(Map<CharSequence, CharSequence> charSequenceMap, String stringKey) Given a key with typeString
and get a value (if there is one) from a map of typeMap<CharSequence,
which has one of key's toString value equals to the given String key.CharSequence> static String
This might not work when application is running inside application server like Jettystatic boolean
isCurrentVersion
(String resourceName, ReadOnlyStoreRepository metadataRepo) static boolean
isExtraReplica
(ReadOnlyStoreRepository metadataRepo, Replica replica, List<Instance> readyInstances) When Helix thinks some host is overloaded or a new host joins the cluster, it might move some replicas from one host to another.static boolean
isFutureVersion
(String resourceName, ReadOnlyStoreRepository metadataRepo) static boolean
Check if a directory exists and is readablestatic boolean
isReadableDir
(String dirName) Check if a directory exists and is readablestatic boolean
Check if a file exists and is readablestatic boolean
isReadableFile
(String fileName) Check if a file exists and is readablestatic boolean
isSeparateTopicRegion
(String region) Check whether input region is for separate RT topic.static <K,
V> Iterator<V> iterateOnMapOfLists
(Map<K, List<V>> mapOfLists) static String
makeLargeNumberPretty
(long largeNumber) static String
makeTimePretty
(long nanoSecTime) static <T> Set<T>
mutableSetOf
(T... objs) static boolean
parseBooleanOrFalse
(String value, String fieldName) Parses a boolean from a string, ensuring that only null and valid boolean values ("true" or "false") are accepted.static boolean
parseBooleanOrThrow
(String value, String fieldName) Parses a boolean from a string, ensuring that only valid boolean values ("true" or "false") are accepted.parseCommaSeparatedStringToList
(String rawString) parseCommaSeparatedStringToSet
(String rawString) static long
parseDateTimeToEpoch
(String dateTime, String dateTimeFormat, String timeZone) Parses a date-time string to epoch milliseconds using the default format and time zone.static String
static int
parseIntFromString
(String value, String fieldName) parseJsonMapFromString
(String value, String fieldName) For String-String key-value map config, we expect the command-line interface users to use JSON format to represent it.static long
parseLongFromString
(String value, String fieldName) static int
static VeniceProperties
parseProperties
(File propertyFile) Given a .property file, reads into a Venice Props objectstatic VeniceProperties
parseProperties
(String configFileName) Given a filePath, reads into a Venice Props objectstatic VeniceProperties
parseProperties
(String directory, String fileName, boolean isFileOptional) Generate VeniceProperties object from a given directory, file.static String
resolveKafkaUrlForSepTopic
(String kafkaUrl) Check whether the given kafka url has "_sep" or not.static PubSubTopic
resolveLeaderTopicFromPubSubTopic
(PubSubTopicRepository pubSubTopicRepository, PubSubTopic pubSubTopic) Resolve leader topic from input topic.static double
round
(double value, int precision) static <T> Set<T>
setOf
(T... objs) static boolean
sleep
(long millis) Sleep until number of milliseconds have passed, or the operation is interrupted.static void
The ssl certificate we have for unit tests has the hostname "localhost".static boolean
verifyTransition
(ExecutionStatus newStatus, ExecutionStatus... allowed) Verify that is the new status allowed to be used.waitStoreVersionOrThrow
(String storeVersionName, ReadOnlyStoreRepository metadataRepo)
-
Field Details
-
WILDCARD_MATCH_ANY
- See Also:
-
NEW_LINE_CHAR
-
SUPPRESS_SYSTEM_EXIT
-
SEPARATE_TOPIC_SUFFIX
- See Also:
-
FATAL_DATA_VALIDATION_ERROR
- See Also:
-
-
Constructor Details
-
Utils
public Utils()
-
-
Method Details
-
exit
Print an error and exit with error code 1- Parameters:
message
- The error to print
-
exit
Print an error and exit with the given error code- Parameters:
message
- The error to printexitCode
- The error code to exit with
-
computeIfNotNull
Run "function" on "t" if "t" is not null -
parseProperties
Given a filePath, reads into a Venice Props object- Parameters:
configFileName
- - String path to a properties file- Returns:
- A @Props object with the given configurations
- Throws:
IOException
-
parseProperties
public static VeniceProperties parseProperties(String directory, String fileName, boolean isFileOptional) throws IOException Generate VeniceProperties object from a given directory, file.- Parameters:
directory
- directory that contains the Property filefileName
- fileName of the Property fileisFileOptional
- set this to true if the file is optional. If file is missing and set to true, empty property will be returned. If file is missing and set to false, this will throw an exception.- Throws:
IOException
-
parseProperties
Given a .property file, reads into a Venice Props object- Parameters:
propertyFile
- The .property file- Returns:
- A @Props object with the given properties
- Throws:
IOException
- if File not found or not accessible
-
isReadableDir
Check if a directory exists and is readable- Parameters:
d
- The directory- Returns:
- true iff the argument is a readable directory
-
isReadableDir
Check if a directory exists and is readable- Parameters:
dirName
- The directory name- Returns:
- true iff the argument is the name of a readable directory
-
isReadableFile
Check if a file exists and is readable- Returns:
- true iff the argument is the name of a readable file
-
isReadableFile
Check if a file exists and is readable- Parameters:
f
- The file- Returns:
- true iff the argument is a readable file
-
getCanonicalPath
Get the full Path of the file. Useful in logging/error output- Returns:
- canonicalPath of the file.
-
directoryExists
-
thisIsLocalhost
public static void thisIsLocalhost()The ssl certificate we have for unit tests has the hostname "localhost". Any tests that rely on this certificate require that the hostname of the machine match the hostname of the certificate. This method lets us globally assert that the hostname for the machine should resolve to "localhost". We can call this method at the start of any tests that require hostnames to resolve to "localhost" It's not ideal to put this as state in a Utils class, we can revisit if we come up with a better way to do it -
getHostName
Get the node's host name.- Returns:
- current node's host name.
-
sleep
public static boolean sleep(long millis) Sleep until number of milliseconds have passed, or the operation is interrupted. This method will swallow the InterruptedException and terminate, if this is used in a loop it may become difficult to cleanly break out of the loop.- Returns:
- true on success and false if sleep was interrupted
-
parseIntFromString
-
parseLongFromString
-
parseBooleanOrThrow
Parses a boolean from a string, ensuring that only valid boolean values ("true" or "false") are accepted. Throws an exception if the value is null or invalid.- Parameters:
value
- the string to parsefieldName
- the name of the field being validated- Returns:
- the parsed boolean value
- Throws:
VeniceHttpException
- if the value is null or not "true" or "false"
-
parseBooleanOrFalse
Parses a boolean from a string, ensuring that only null and valid boolean values ("true" or "false") are accepted. Returns false if the value is null.- Parameters:
value
- the string to parsefieldName
- the name of the field being validated- Returns:
- the parsed boolean value, or false if the input is null
- Throws:
VeniceHttpException
- if the value is not "true" or "false"
-
parseJsonMapFromString
For String-String key-value map config, we expect the command-line interface users to use JSON format to represent it. This method deserialize it to String-String map. -
getHelixNodeIdentifier
-
parseHostFromHelixNodeIdentifier
-
parsePortFromHelixNodeIdentifier
-
getSchemaFromResource
Utility function to get schemas out of embedded resources.- Parameters:
resourcePath
- The path of the file under the src/main/resources directory- Returns:
- the
Schema
instance corresponding to the file at - Throws:
IOException
- if the resourcePath does not exist
-
getAllSchemasFromResources
public static Map<Integer,org.apache.avro.Schema> getAllSchemasFromResources(AvroProtocolDefinition protocolDef) -
verifyTransition
Verify that is the new status allowed to be used. -
parseCommaSeparatedStringToSet
-
parseCommaSeparatedStringToList
-
round
public static double round(double value, int precision) - Parameters:
value
- the double value to be roundedprecision
- the number of decimal places by which to round- Returns:
- rounded by decimal places
-
makeLargeNumberPretty
-
getUniqueString
-
getUniqueString
-
getUniqueTempPath
-
getUniqueTempPath
-
getTempDataDirectory
-
getTempDataDirectory
-
composeRealTimeTopic
This method should only be used for system stores. For other stores, usegetRealTimeTopicName(Store)
,getRealTimeTopicName(StoreInfo)
orgetRealTimeTopicName(Version)
-
getRealTimeTopicNameFromStoreConfig
-
getRealTimeTopicName
It follows the following order to search for real time topic name, i) current store-version config, ii) store config, iii) other store-version configs, iv) default name -
getRealTimeTopicName
-
getRealTimeTopicName
-
createNewRealTimeTopicName
-
makeTimePretty
-
getCurrentWorkingDirectory
-
getPid
Note: this may fail in some JVM implementations. Lifted from: https://stackoverflow.com/a/7690178- Returns:
- the pid of the current Java process, or null if unavailable
-
getVeniceVersionFromClassPath
This might not work when application is running inside application server like Jetty- Returns:
- the version of the venice-common jar on the classpath, if available, or null otherwise.
-
getCurrentUser
-
getJavaMajorVersion
public static int getJavaMajorVersion() -
getDebugInfo
-
getValueFromCharSequenceMapWithStringKey
public static Optional<CharSequence> getValueFromCharSequenceMapWithStringKey(Map<CharSequence, CharSequence> charSequenceMap, String stringKey) Given a key with typeString
and get a value (if there is one) from a map of typeMap<CharSequence,
which has one of key's toString value equals to the given String key. Note that the worst case runtime of this function is O(n) since the given map is iterated to find the value. The reason why this function exists is that the specific implementation of theCharSequence> CharSequence
interface might not beString
for the map key type. So, when users try to get a value from such a map with a String key, they might not get the value even when the value of the key which has the same toString representation as the user-given String key since the specific implementation of theCharSequence
interface has a different hash function than String's hash function.- Returns:
- a Value in the CharSequence map or {@link null}
-
setOf
-
mutableSetOf
-
closeQuietlyWithErrorLogged
-
getReplicasForInstance
public static List<Replica> getReplicasForInstance(RoutingDataRepository routingDataRepo, String instanceId) -
isCurrentVersion
-
isFutureVersion
-
isExtraReplica
public static boolean isExtraReplica(ReadOnlyStoreRepository metadataRepo, Replica replica, List<Instance> readyInstances) When Helix thinks some host is overloaded or a new host joins the cluster, it might move some replicas from one host to another. The partition to be moved is usually in a healthy state, i.e. 3/3 running replicas. We will now build an extra replica in the new host before dropping one replica in an old host. i.e. replica changes 3 -> 4 -> 3. In this scenario, we may see an extra replica appear. This function determines if a replica is an extra replica.- Returns:
- true, if the input replica is an extra one. false, otherwise.
-
extractQueryParamsFromRequest
-
waitStoreVersionOrThrow
public static Pair<Store,Version> waitStoreVersionOrThrow(String storeVersionName, ReadOnlyStoreRepository metadataRepo) -
iterateOnMapOfLists
-
getSanitizedStringForLogger
Log4J's class name logging splits at the last "." and assumes it is the class name. In case where custom strings (e.g. URLs, server addresses, etc.) are added to the logger names, Log4J logs an incomplete string. This function replaces "." with "_" in the string when setting as the input for the logger.- Parameters:
orig
- The string to sanitize- Returns:
- A sanitized string that won't get mutated by Log4J
-
getReplicaId
Standard logging format for TopicPartition -
getReplicaId
-
getReplicaId
-
escapeFilePathComponent
Method to escape file path component to make it a valid file path string/substring.- Parameters:
component
- file path component string- Returns:
- Escaped file path component string
-
resolveKafkaUrlForSepTopic
Check whether the given kafka url has "_sep" or not. If it has, return the kafka url without "_sep". Otherwise, return the original kafka url.- Parameters:
kafkaUrl
-- Returns:
-
isSeparateTopicRegion
Check whether input region is for separate RT topic. -
resolveLeaderTopicFromPubSubTopic
public static PubSubTopic resolveLeaderTopicFromPubSubTopic(PubSubTopicRepository pubSubTopicRepository, PubSubTopic pubSubTopic) Resolve leader topic from input topic. If input topic is separate RT topic, return the corresponding RT topic. Otherwise, return the original input topic. -
parseDateTimeToEpoch
public static long parseDateTimeToEpoch(String dateTime, String dateTimeFormat, String timeZone) throws ParseException Parses a date-time string to epoch milliseconds using the default format and time zone.- Parameters:
dateTime
- the date-time string in the format "yyyy-MM-dd hh:mm:ss"- Returns:
- the epoch time in milliseconds
- Throws:
ParseException
- if the date-time string cannot be parsed
-
getOSMemorySize
public static long getOSMemorySize()
-