Package com.linkedin.venice.utils
Class Utils
java.lang.Object
com.linkedin.venice.utils.Utils
Helper functions
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classThis class encapsulates config entity information such as config name, default value, config document -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final ByteBufferstatic final Stringstatic final Stringstatic final Stringstatic final AtomicBooleanstatic final String -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic intstatic voidcloseQuietly(AutoCloseable closeable, Consumer<Exception> consumer) static voidcloseQuietlyWithErrorLogged(AutoCloseable... closeables) static StringcomposeRealTimeTopic(String storeName) This method should only be used for system stores.static StringcomposeRealTimeTopic(String storeName, int versionNumber) static <T> voidcomputeIfNotNull(T t, Consumer<T> function) Run "function" on "t" if "t" is not nullstatic PubSubTopicPartitioncreatePubSubTopicPartitionFromLeaderTopicPartition(String pubSubAddress, PubSubTopicPartition leaderTopicPartition) static booleandirectoryExists(String dataDirectory) static StringescapeFilePathComponent(String component) Method to escape file path component to make it a valid file path string/substring.static voidPrint an error and exit with error code 1static voidPrint an error and exit with the given error codeextractQueryParamsFromRequest(Map<String, String[]> sparkRequestParams, ControllerResponse response) getAllRealTimeTopicNames(Store store) getAllSchemasFromResources(AvroProtocolDefinition protocolDef) static StringgetCanonicalPath(String fileName) Get the full Path of the file.static Stringstatic Stringstatic Map<CharSequence,CharSequence> static StringgetHelixNodeIdentifier(String hostname, int port) static StringGet the node's host name.static intstatic longstatic StringgetPid()Note: this may fail in some JVM implementations.static StringgetRealTimeTopicName(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 StringgetRealTimeTopicName(StoreInfo storeInfo) static StringgetRealTimeTopicName(Version version) static StringgetRealTimeTopicNameFromSeparateRealTimeTopic(String separateRealTimeTopicName) static StringgetReplicaId(PubSubTopicPartition topicPartition) Standard logging format for TopicPartitionstatic StringgetReplicaId(PubSubTopic topic, int partition) static StringgetReplicaId(String topic, int partition) static StringgetReplicaId(String storeName, int version, int partition) getReplicasForInstance(RoutingDataRepository routingDataRepo, String instanceId) static StringLog4J's class name logging splits at the last "." and assumes it is the class name.static org.apache.avro.SchemagetSchemaFromResource(String resourcePath) Utility function to get schemas out of embedded resources.static StringgetSeparateRealTimeTopicName(StoreInfo storeInfo) static StringgetSeparateRealTimeTopicName(Version version) static StringgetSeparateRealTimeTopicName(String realTimeTopicName) static Filestatic FilegetTempDataDirectory(String prefix) static Stringstatic StringgetUniqueString(String prefix) static Stringstatic StringgetUniqueTempPath(String prefix) static Optional<CharSequence>getValueFromCharSequenceMapWithStringKey(Map<CharSequence, CharSequence> charSequenceMap, String stringKey) Given a key with typeStringand 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 StringThis might not work when application is running inside application server like Jettystatic booleanisCurrentVersion(String resourceName, ReadOnlyStoreRepository metadataRepo) static booleanisExtraReplica(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 booleanisFutureVersion(String resourceName, ReadOnlyStoreRepository metadataRepo) static booleanisFutureVersionReady(String resourceName, ReadOnlyStoreRepository metadataRepo) Checks if the future version is ready to serve.static booleanCheck if a directory exists and is readablestatic booleanisReadableDir(String dirName) Check if a directory exists and is readablestatic booleanCheck if a file exists and is readablestatic booleanisReadableFile(String fileName) Check if a file exists and is readablestatic booleanisRTVersioningApplicable(String storeName) static booleanisSeparateTopicRegion(String region) Check whether input region is for separate RT topic.static <K,V> Iterator<V> iterateOnMapOfLists(Map<K, List<V>> mapOfLists) static StringmakeLargeNumberPretty(long largeNumber) static StringmakeTimePretty(long nanoSecTime) static <T> Set<T>mutableSetOf(T... objs) static booleanparseBooleanOrFalse(String value, String fieldName) Parses a boolean from a string, ensuring that only null and valid boolean values ("true" or "false") are accepted.static booleanparseBooleanOrThrow(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 longparseDateTimeToEpoch(String dateTime, String dateTimeFormat, String timeZone) Parses a date-time string to epoch milliseconds using the default format and time zone.static Stringstatic intparseIntFromString(String value, String fieldName) static intparseIntOrDefault(String value, String fieldName, int defaultValue) Parses an integer from a string, ensuring that only null or valid integer values are accepted.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 longparseLongFromString(String value, String fieldName) static intstatic VenicePropertiesparseProperties(File propertyFile) Given a .property file, reads into a Venice Props objectstatic VenicePropertiesparseProperties(String configFileName) Given a filePath, reads into a Venice Props objectstatic VenicePropertiesparseProperties(String directory, String fileName, boolean isFileOptional) Generate VeniceProperties object from a given directory, file.static List<LifecycleHooksRecord>parseStoreLifecycleHooksListFromString(String value, String fieldName) For Store Lifecycle Hooks value, we expect the command-line interface users to use JSON format to represent it.static StringresolveKafkaUrlForSepTopic(String kafkaUrl) Check whether the given kafka url has "_sep" or not.static PubSubTopicresolveLeaderTopicFromPubSubTopic(PubSubTopicRepository pubSubTopicRepository, PubSubTopic pubSubTopic) Resolve leader topic from input topic.static doubleround(double value, int precision) static <T> Set<T>setOf(T... objs) static booleansleep(long millis) Sleep until number of milliseconds have passed, or the operation is interrupted.static voidThe ssl certificate we have for unit tests has the hostname "localhost".static booleanverifyTransition(ExecutionStatus newStatus, ExecutionStatus... allowed) Verify that is the new status allowed to be used.static StoreVersionInfowaitStoreVersionOrThrow(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:
-
EMPTY_BYTE_BUFFER
-
-
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
-
parseIntOrDefault
Parses an integer from a string, ensuring that only null or valid integer values are accepted. Returns defaultValue if the value is null. Throws an exception if the value is invalid.- Parameters:
value- the string to parsefieldName- the name of the field being validateddefaultValue- the default value to return if the input is null- Returns:
- the parsed int value
-
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. -
parseStoreLifecycleHooksListFromString
public static List<LifecycleHooksRecord> parseStoreLifecycleHooksListFromString(String value, String fieldName) For Store Lifecycle Hooks value, we expect the command-line interface users to use JSON format to represent it. This method deserialize it to List. -
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
Schemainstance 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)in source code. For tests, usecomposeRealTimeTopic(String, int) -
composeRealTimeTopic
-
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
-
isRTVersioningApplicable
-
getRealTimeTopicName
-
getAllRealTimeTopicNames
-
getRealTimeTopicNameFromSeparateRealTimeTopic
-
getSeparateRealTimeTopicName
-
getSeparateRealTimeTopicName
-
getSeparateRealTimeTopicName
-
calculateTopicHashCode
-
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 typeStringand 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> CharSequenceinterface might not beStringfor 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 theCharSequenceinterface has a different hash function than String's hash function.- Returns:
- a Value in the CharSequence map or {@link null}
-
setOf
-
mutableSetOf
-
closeQuietlyWithErrorLogged
-
closeQuietly
-
getReplicasForInstance
public static List<Replica> getReplicasForInstance(RoutingDataRepository routingDataRepo, String instanceId) -
isCurrentVersion
-
isFutureVersion
-
isFutureVersionReady
public static boolean isFutureVersionReady(String resourceName, ReadOnlyStoreRepository metadataRepo) Checks if the future version is ready to serve. A future version is considered ready to serve if the version status is either PUSHED or ONLINE- Parameters:
resourceName-metadataRepo-- Returns:
-
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 StoreVersionInfo 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
-
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. -
createPubSubTopicPartitionFromLeaderTopicPartition
public static PubSubTopicPartition createPubSubTopicPartitionFromLeaderTopicPartition(String pubSubAddress, PubSubTopicPartition leaderTopicPartition) -
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()
-