code
stringlengths
25
201k
docstring
stringlengths
19
96.2k
func_name
stringlengths
0
235
language
stringclasses
1 value
repo
stringlengths
8
51
path
stringlengths
11
314
url
stringlengths
62
377
license
stringclasses
7 values
@Test public void testSupportedPipeCharWithoutRegex() { String[] expectedTextTokenValue = new String[]{"thread", "|", "grep", "xxx"}; List<CliToken> actualTokens = CliTokenImpl.tokenize("thread| grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("thread | grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("thread |grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); }
supported: <p> case1: thread| grep xxx [thread|, grep, xxx] -> [thread, |, grep, xxx] case:2 thread | grep xxx [thread, |, grep, xxx] -> [thread, |, grep, xxx] case3: thread |grep xxx [thread, |grep] -> [thread, |, grep, xxx]
testSupportedPipeCharWithoutRegex
java
alibaba/arthas
core/src/test/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImplTest.java
https://github.com/alibaba/arthas/blob/master/core/src/test/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImplTest.java
Apache-2.0
@Test public void testSupportedPipeCharWithRegex() { String[] expectedTextTokenValue = new String[]{"trace", "-E", "classA|classB", "methodA|methodB", "|", "grep", "classA"}; List<CliToken> actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB| grep classA"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB | grep classA"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB |grep classA"); assertEquals(expectedTextTokenValue, actualTokens); }
supported: <p> case1: trace -E classA|classB methodA|methodB| grep classA [trace, -E, classA|classB, methodA|methodB|, grep, classA] -> [trace, -E, classA|classB, methodA|methodB, |, grep, classA] case2: trace -E classA|classB methodA|methodB | grep classA [trace, -E, classA|classB, methodA|methodB, |, grep, classA] -> [trace, -E, classA|classB, methodA|methodB, |, grep, classA] case3: trace -E classA|classB methodA|methodB |grep classA [trace, -E, classA|classB, methodA|methodB, |grep, classA] -> [trace, -E, classA|classB, methodA|methodB, |, grep, classA]
testSupportedPipeCharWithRegex
java
alibaba/arthas
core/src/test/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImplTest.java
https://github.com/alibaba/arthas/blob/master/core/src/test/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImplTest.java
Apache-2.0
@Override public void draw(ArthasStreamObserver arthasStreamObserver, EnhancerModel result) { if (result.getEffect() != null) { String msg = ViewRenderUtil.renderEnhancerAffect(result.getEffect()); ResponseBody responseBody = ResponseBody.newBuilder() .setJobId(result.getJobId()) .setType(result.getType()) .setStringValue(msg) .build(); arthasStreamObserver.onNext(responseBody); } }
Term grpc view for EnhancerModel @author xuyang 2023/8/15
draw
java
alibaba/arthas
labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/grpc/view/GrpcEnhancerView.java
https://github.com/alibaba/arthas/blob/master/labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/grpc/view/GrpcEnhancerView.java
Apache-2.0
@Override public void draw(ArthasStreamObserver arthasStreamObserver, WatchResponseModel model) { ObjectVO objectVO = model.getValue(); // Object obj = objectVO.needExpand() ? new ObjectView(model.getSizeLimit(), objectVO).draw() : objectVO.getObject(); JavaObject javaObject = toJavaObjectWithExpand(objectVO.getObject(), objectVO.getExpand()); WatchResponse watchResponse = WatchResponse.newBuilder() .setAccessPoint(model.getAccessPoint()) .setClassName(model.getClassName()) .setCost(model.getCost()) .setMethodName(model.getMethodName()) .setSizeLimit(model.getSizeLimit()) .setTs(DateUtils.formatDateTime(model.getTs())) .setValue(javaObject) .build(); ResponseBody responseBody = ResponseBody.newBuilder() .setJobId(model.getJobId()) .setResultId(model.getResultId()) .setType(model.getType()) .setWatchResponse(watchResponse) .build(); arthasStreamObserver.onNext(responseBody); }
Term view for WatchModel @author xuyang 2023/8/15
draw
java
alibaba/arthas
labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/grpc/view/GrpcWatchView.java
https://github.com/alibaba/arthas/blob/master/labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/grpc/view/GrpcWatchView.java
Apache-2.0
public boolean processInput(InputStream in, MessageUtils.ContentType contentType) { byte[] inBytes; try { InputStream inStream = (contentType == ContentType.GRPC_WEB_TEXT) ? Base64.getDecoder().wrap(in) : in; inBytes = IOUtils.getBytes(inStream); } catch (IOException e) { e.printStackTrace(); logger.warn("invalid input"); return false; } if (inBytes.length < 5) { logger.debug("invalid input. Expected minimum of 5 bytes"); return false; } while (getNextFrameBytes(inBytes)) { } mNumFrames = mFrames.size(); // common case is only one frame. if (mNumFrames == 1) { mMsg = mFrames.get(0); } else { // concatenate all frames into one byte array // TODO: this is inefficient. mMsg = new byte[mLength]; int offset = 0; for (byte[] f : mFrames) { System.arraycopy(f, 0, mMsg, offset, f.length); offset += f.length; } mFrames = null; } return true; }
Reads the bytes from the given InputStream and populates bytes in {@link #mMsg}
processInput
java
alibaba/arthas
labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageDeframer.java
https://github.com/alibaba/arthas/blob/master/labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageDeframer.java
Apache-2.0
private boolean getNextFrameBytes(byte[] inBytes) { // Firstbyte should be 0x00 (for this to be a DATA frame) int firstByteValue = inBytes[mReadSoFar] | DATA_BYTE; if (firstByteValue != 0) { logger.debug("done with DATA bytes"); return false; } // Next 4 bytes = length of the bytes array starting after the 4 bytes. int offset = mReadSoFar + 1; int len = ByteBuffer.wrap(inBytes, offset, 4).getInt(); // Empty message is special case. // TODO: Can this is special handling be removed? if (len == 0) { mFrames.add(new byte[0]); return false; } // Make sure we have enough bytes in the inputstream int expectedNumBytes = len + 5 + mReadSoFar; if (inBytes.length < expectedNumBytes) { logger.warn(String.format("input doesn't have enough bytes. expected: %d, found %d", expectedNumBytes, inBytes.length)); return false; } // Read "len" bytes into message mLength += len; offset += 4; byte[] inputBytes = Arrays.copyOfRange(inBytes, offset, len + offset); mFrames.add(inputBytes); mReadSoFar += (len + 5); // we have more frames to process, if there are bytes unprocessed return inBytes.length > mReadSoFar; }
returns true if the next frame is a DATA frame
getNextFrameBytes
java
alibaba/arthas
labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageDeframer.java
https://github.com/alibaba/arthas/blob/master/labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageDeframer.java
Apache-2.0
public byte[] getPrefix(byte[] in, Type type) { int len = in.length; return new byte[] { type.value, (byte) ((len >> 24) & 0xff), (byte) ((len >> 16) & 0xff), (byte) ((len >> 8) & 0xff), (byte) ((len >> 0) & 0xff), }; }
Creates frames from the input bytes.
getPrefix
java
alibaba/arthas
labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageFramer.java
https://github.com/alibaba/arthas/blob/master/labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageFramer.java
Apache-2.0
static Object getInputProtobufObj(Method rpcMethod, byte[] in) { Class[] inputArgs = rpcMethod.getParameterTypes(); Class inputArgClass = inputArgs[0]; // use the inputArg classtype to create a protobuf object Method parseFromObj; try { parseFromObj = inputArgClass.getMethod("parseFrom", byte[].class); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Couldn't find method in 'parseFrom' in " + inputArgClass.getName()); } Object inputObj; try { inputObj = parseFromObj.invoke(null, in); } catch (InvocationTargetException | IllegalAccessException e) { throw new IllegalArgumentException(e); } if (inputObj == null || !inputArgClass.isInstance(inputObj)) { throw new IllegalArgumentException("Input obj is **not** instance of the correct input class type"); } return inputObj; }
Find the input arg protobuf class for the given rpc-method. Convert the given bytes to the input protobuf. return that.
getInputProtobufObj
java
alibaba/arthas
labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageUtils.java
https://github.com/alibaba/arthas/blob/master/labs/arthas-grpc-web-proxy/src/main/java/com/taobao/arthas/grpcweb/proxy/MessageUtils.java
Apache-2.0
@Override public int getStart() { return this.start; }
Returns the starting offset into the text for this interval. @return A number between 0 (start of text) and the text length.
getStart
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/interval/Interval.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/interval/Interval.java
Apache-2.0
@Override public int getEnd() { return this.end; }
Returns the ending offset into the text for this interval. @return A number between getStart() + 1 and the text length.
getEnd
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/interval/Interval.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/interval/Interval.java
Apache-2.0
@Override public int size() { return end - start + 1; }
Returns the length of the interval. @return The end position less the start position, plus one.
size
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/interval/Interval.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/interval/Interval.java
Apache-2.0
@Override public String toString() { return this.start + ":" + this.end; }
Returns the starting offset and ending offset separated by a full colon (:). @return A non-null String, never empty.
toString
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/interval/Interval.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/interval/Interval.java
Apache-2.0
public boolean containsMatch(final CharSequence text) { return firstMatch(text) != null; }
Returns true if the text contains one of the search terms; otherwise, returns false. @param text Specified text. @return true if the text contains one of the search terms. Else, returns false.
containsMatch
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/PayloadTrie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/PayloadTrie.java
Apache-2.0
public PayloadTrieBuilder<T> addKeyword(final String keyword) { this.trie.addKeyword(keyword); return this; }
Adds a keyword to the {@link Trie}'s list of text search keywords. No {@link Payload} is supplied. @param keyword The keyword to add to the list. @return This builder. @throws NullPointerException if the keyword is null.
addKeyword
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/PayloadTrie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/PayloadTrie.java
Apache-2.0
public PayloadTrieBuilder<T> addKeyword(final String keyword, final T payload) { this.trie.addKeyword(keyword, payload); return this; }
Adds a keyword and a payload to the {@link Trie}'s list of text search keywords. @param keyword The keyword to add to the list. @param payload the payload to add @return This builder. @throws NullPointerException if the keyword is null.
addKeyword
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/PayloadTrie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/PayloadTrie.java
Apache-2.0
public PayloadTrieBuilder<T> addKeywords(final Collection<Payload<T>> keywords) { for (Payload<T> payload : keywords) { this.trie.addKeyword(payload.getKeyword(), payload.getData()); } return this; }
Adds a list of keywords and payloads to the {@link Trie}'s list of text search keywords. @param keywords The keywords to add to the list. @return This builder.
addKeywords
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/PayloadTrie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/PayloadTrie.java
Apache-2.0
public PayloadTrie<T> build() { this.trie.constructFailureStates(); return this.trie; }
Configure the PayloadTrie based on the builder settings. @return The configured PayloadTrie.
build
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/PayloadTrie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/PayloadTrie.java
Apache-2.0
public static TrieBuilder builder() { return new TrieBuilder(); }
Provides a fluent interface for constructing Trie instances. @return The builder used to configure its Trie.
builder
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/Trie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/Trie.java
Apache-2.0
public TrieBuilder addKeyword(final String keyword) { delegate.addKeyword(keyword, null); return this; }
Adds a keyword to the Trie's list of text search keywords. @param keyword The keyword to add to the list. @return This builder. @throws NullPointerException if the keyword is null.
addKeyword
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/Trie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/Trie.java
Apache-2.0
public Trie build() { PayloadTrie<String> payloadTrie = this.delegate.build(); return new Trie(payloadTrie); }
Configure the Trie based on the builder settings. @return The configured Trie.
build
java
robert-bor/aho-corasick
src/main/java/org/ahocorasick/trie/Trie.java
https://github.com/robert-bor/aho-corasick/blob/master/src/main/java/org/ahocorasick/trie/Trie.java
Apache-2.0
@SuppressWarnings( "SameParameterValue" ) static void injectKeyword( final StringBuilder source, final String keyword, final int interval ) { final int length = source.length(); for( int i = 0; i < length; i += interval ) { source.replace( i, i + keyword.length(), keyword ); } }
Injects keywords into a string builder. @param source Should contain a bunch of random data that cannot match any keyword. @param keyword A keyword to inject repeatedly in the text. @param interval How often to inject the keyword.
injectKeyword
java
robert-bor/aho-corasick
src/test/java/org/ahocorasick/trie/TestHelper.java
https://github.com/robert-bor/aho-corasick/blob/master/src/test/java/org/ahocorasick/trie/TestHelper.java
Apache-2.0
@SuppressWarnings( "SameParameterValue" ) public static StringBuilder randomNumbers( int count ) { final StringBuilder sb = new StringBuilder( count ); while( --count > 0 ) { sb.append( current().nextInt( 0, 10 ) ); } return sb; }
Generates a random sequence of ASCII numbers. @param count The number of numbers to generate. @return A character sequence filled with random digits.
randomNumbers
java
robert-bor/aho-corasick
src/test/java/org/ahocorasick/trie/TestHelper.java
https://github.com/robert-bor/aho-corasick/blob/master/src/test/java/org/ahocorasick/trie/TestHelper.java
Apache-2.0
@Test public void test_TokenizeTokensInSequence() { final Trie trie = trie( GREEK_LETTERS ); final Collection<Token> tokens = trie.tokenize( "Alpha Beta Gamma" ); assertEquals( 5, tokens.size() ); }
Test boundary check with case-insensitive matches with whole words.
test_TokenizeTokensInSequence
java
robert-bor/aho-corasick
src/test/java/org/ahocorasick/trie/TrieTest.java
https://github.com/robert-bor/aho-corasick/blob/master/src/test/java/org/ahocorasick/trie/TrieTest.java
Apache-2.0
public Collection<LogFilePath> getPaths(TopicPartition topicPartition) { return getPaths(new TopicPartitionGroup(topicPartition)); }
Get paths in a given topic partition. @param topicPartition The topic partition to retrieve paths for. @return Collection of file paths in the given topic partition.
getPaths
java
pinterest/secor
src/main/java/com/pinterest/secor/common/FileRegistry.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/FileRegistry.java
Apache-2.0
public Collection<LogFilePath> getPaths(TopicPartitionGroup topicPartitionGroup) { HashSet<LogFilePath> logFilePaths = mFiles.get(topicPartitionGroup); if (logFilePaths == null) { return new HashSet<LogFilePath>(); } return new HashSet<LogFilePath>(logFilePaths); }
Get paths in a given topic partition. @param topicPartitionGroup The topic partition to retrieve paths for. @return Collection of file paths in the given topic partition.
getPaths
java
pinterest/secor
src/main/java/com/pinterest/secor/common/FileRegistry.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/FileRegistry.java
Apache-2.0
public FileWriter getWriter(LogFilePath path) throws Exception { return mWriters.get(path); }
Retrieve an existing writer for a given path. @param path The path to retrieve writer for. @return Writer for a given path or null if no writer has been created yet. @throws Exception on error
getWriter
java
pinterest/secor
src/main/java/com/pinterest/secor/common/FileRegistry.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/FileRegistry.java
Apache-2.0
public FileWriter getOrCreateWriter(LogFilePath path, CompressionCodec codec) throws Exception { FileWriter writer = mWriters.get(path); if (writer == null) { // Just in case. FileUtil.delete(path.getLogFilePath()); FileUtil.delete(path.getLogFileCrcPath()); TopicPartitionGroup topicPartition = new TopicPartitionGroup(path.getTopic(), path.getKafkaPartitions()); HashSet<LogFilePath> files = mFiles.get(topicPartition); if (files == null) { files = new HashSet<LogFilePath>(); mFiles.put(topicPartition, files); } if (!files.contains(path)) { files.add(path); } writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), path, codec, mConfig); mWriters.put(path, writer); mCreationTimes.put(path, System.currentTimeMillis() / 1000L); LOG.debug("created writer for path {}", path.getLogFilePath()); } return writer; }
Retrieve a writer for a given path or create a new one if it does not exist. @param path The path to retrieve writer for. @param codec Optional compression codec. @return Writer for a given path. @throws Exception on error
getOrCreateWriter
java
pinterest/secor
src/main/java/com/pinterest/secor/common/FileRegistry.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/FileRegistry.java
Apache-2.0
public void deletePath(LogFilePath path) throws IOException { TopicPartitionGroup topicPartition = new TopicPartitionGroup(path.getTopic(), path.getKafkaPartitions()); HashSet<LogFilePath> paths = mFiles.get(topicPartition); paths.remove(path); if (paths.isEmpty()) { mFiles.remove(topicPartition); StatsUtil.clearLabel("secor.size." + topicPartition.getTopic() + "." + topicPartition.getPartitions()[0]); StatsUtil.clearLabel("secor.modification_age_sec." + topicPartition.getTopic() + "." + topicPartition.getPartitions()[0]); } deleteWriter(path); FileUtil.delete(path.getLogFilePath()); FileUtil.delete(path.getLogFileCrcPath()); }
Delete a given path, the underlying file, and the corresponding writer. @param path The path to delete. @throws IOException on error
deletePath
java
pinterest/secor
src/main/java/com/pinterest/secor/common/FileRegistry.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/FileRegistry.java
Apache-2.0
public void deleteWriter(LogFilePath path) throws IOException { FileWriter writer = mWriters.get(path); if (writer == null) { LOG.warn("No writer found for path {}", path.getLogFilePath()); } else { LOG.info("Deleting writer for path {}", path.getLogFilePath()); writer.close(); mWriters.remove(path); mCreationTimes.remove(path); } }
Delete writer for a given topic partition. Underlying file is not removed. @param path The path to remove the writer for. @throws IOException on error
deleteWriter
java
pinterest/secor
src/main/java/com/pinterest/secor/common/FileRegistry.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/FileRegistry.java
Apache-2.0
public void start() { Duration[] defaultLatchIntervals = {Duration.apply(1, TimeUnit.MINUTES)}; Map<String, CustomHttpHandler> handlers = mPrometheusEnabled ? new Map.Map1<>("/prometheus", new PrometheusHandler()) : Map$.MODULE$.empty(); @SuppressWarnings("deprecation") AdminServiceFactory adminServiceFactory = new AdminServiceFactory( this.mPort, 20, List$.MODULE$.<StatsFactory>empty(), Option.<String>empty(), List$.MODULE$.<Regex>empty(), handlers, JavaConversions .asScalaBuffer(Arrays.asList(defaultLatchIntervals)).toList() ); RuntimeEnvironment runtimeEnvironment = new RuntimeEnvironment(this); adminServiceFactory.apply(runtimeEnvironment); try { Properties properties = new Properties(); properties.load(this.getClass().getResource("build.properties").openStream()); String buildRevision = properties.getProperty("build_revision", "unknown"); LOG.info("build.properties build_revision: {}", properties.getProperty("build_revision", "unknown")); StatsUtil.setLabel("secor.build_revision", buildRevision); } catch (Throwable t) { LOG.error("Failed to load properties from build.properties", t); } }
OstrichAdminService initializes export of metrics to Ostrich. @author Pawel Garbacki (pawel@pinterest.com)
start
java
pinterest/secor
src/main/java/com/pinterest/secor/common/monitoring/OstrichAdminService.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/monitoring/OstrichAdminService.java
Apache-2.0
@Override public void handle(HttpExchange exchange) { Optional<PrometheusMeterRegistry> registry = Metrics.globalRegistry.getRegistries().stream() .filter(meterRegistry -> meterRegistry instanceof PrometheusMeterRegistry) .map(meterRegistry -> (PrometheusMeterRegistry) meterRegistry) .findFirst(); if (registry.isPresent()) { this.render(registry.get().scrape(), exchange, HttpStatus.SC_OK); } else { LOG.warn("Trying to scrape prometheus, while it is disabled, " + "set \"secor.monitoring.metrics.collector.micrometer.prometheus.enabled\" to \"true\""); this.render("Not Found", exchange, HttpStatus.SC_NOT_FOUND); } }
Initializes Http Endpoint for Prometheus @author Paulius Dambrauskas (p.dambrauskas@gmail.com)
handle
java
pinterest/secor
src/main/java/com/pinterest/secor/common/monitoring/PrometheusHandler.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/common/monitoring/PrometheusHandler.java
Apache-2.0
@Override public void run() { try { FileUtils.deleteDirectory(this.mStagingDir); } catch (IOException e) { LOG.error("Failed deleting file", e); } }
Runnable used to delete staging folder content. Deletes folders content, while keeping folder itself. @author Paulius Dambrauskas (p.dambrauskas@gmail.com)
run
java
pinterest/secor
src/main/java/com/pinterest/secor/io/StagingDirectoryCleaner.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/io/StagingDirectoryCleaner.java
Apache-2.0
private CompressionKind resolveCompression(CompressionCodec codec) { if (codec instanceof Lz4Codec) return CompressionKind.LZ4; else if (codec instanceof SnappyCodec) return CompressionKind.SNAPPY; // although GZip and ZLIB are not same thing // there is no better named codec for this case, // use hadoop Gzip codec to enable ORC ZLIB compression else if (codec instanceof GzipCodec) return CompressionKind.ZLIB; else return CompressionKind.NONE; }
Used for returning the compression kind used in ORC @param codec @return
resolveCompression
java
pinterest/secor
src/main/java/com/pinterest/secor/io/impl/JsonORCFileReaderWriterFactory.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/io/impl/JsonORCFileReaderWriterFactory.java
Apache-2.0
public static void main(String[] args) { if (args.length != 0) { System.err.println("Usage: java -Dconfig=<secor_properties> " + "-Dlog4j.configuration=<log4j_properties> ConsumerMain"); return; } try { SecorConfig config = SecorConfig.load(); String stagingDirectoryPath = config.getLocalPath() + '/' + IdUtil.getLocalMessageDir(); ShutdownHookRegistry.registerHook(10, new StagingDirectoryCleaner(stagingDirectoryPath)); MetricCollector metricCollector = ReflectionUtil.createMetricCollector(config.getMetricsCollectorClass()); metricCollector.initialize(config); OstrichAdminService ostrichService = new OstrichAdminService(config); ostrichService.start(); FileUtil.configure(config); LogFileDeleter logFileDeleter = new LogFileDeleter(config); logFileDeleter.deleteOldLogs(); RateLimitUtil.configure(config); LOG.info("starting {} consumer threads", config.getConsumerThreads()); LinkedList<Consumer> consumers = new LinkedList<Consumer>(); for (int i = 0; i < config.getConsumerThreads(); ++i) { Consumer consumer = new Consumer(config, metricCollector); consumers.add(consumer); consumer.start(); } for (Consumer consumer : consumers) { consumer.join(); } } catch (Throwable t) { LOG.error("Consumer failed", t); System.exit(1); } }
Secor consumer. See https://docs.google.com/a/pinterest.com/document/d/1RHeH79O0e1WzsxumE24MIYqJFnRoRzQ3c74Wq3Q4R40/edit for detailed design. Run: $ cd optimus/secor $ mvn package $ cd target $ java -ea -Dlog4j.configuration=log4j.dev.properties -Dconfig=secor.dev.backup.properties \ -cp "secor-0.1-SNAPSHOT.jar:lib/*" com.pinterest.secor.main.ConsumerMain @author Pawel Garbacki (pawel@pinterest.com)
main
java
pinterest/secor
src/main/java/com/pinterest/secor/main/ConsumerMain.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/main/ConsumerMain.java
Apache-2.0
public static void main(String[] args) { try { SecorConfig config = SecorConfig.load(); FileUtil.configure(config); PartitionFinalizer partitionFinalizer = new PartitionFinalizer(config); partitionFinalizer.finalizePartitions(); } catch (Throwable t) { LOG.error("Partition finalizer failed", t); System.exit(1); } }
Partition finalizer main. Run: $ cd optimus/secor $ mvn package $ cd target $ java -ea -Dlog4j.configuration=log4j.dev.properties -Dconfig=secor.dev.backup.properties \ -cp "secor-0.1-SNAPSHOT.jar:lib/*" com.pinterest.secor.main.PartitionFinalizerMain @author Pawel Garbacki (pawel@pinterest.com)
main
java
pinterest/secor
src/main/java/com/pinterest/secor/main/PartitionFinalizerMain.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/main/PartitionFinalizerMain.java
Apache-2.0
@Override public long extractTimestampMillis(final Message message) { try { GenericRecord record = schemaRegistry.deserialize(message.getTopic(), message.getPayload()); if (record != null) { Object fieldValue = record.get(mConfig.getMessageTimestampName()); if (fieldValue != null) { Date dateFormat = DatatypeConverter.parseDateTime(fieldValue.toString()).getTime(); return dateFormat.getTime(); } else if (m_timestampRequired) { throw new RuntimeException("Missing timestamp field for message: " + message); } } else { throw new RuntimeException("Record is empty: " + message); } } catch (SerializationException e) { LOG.error("Failed to parse record", e); } return 0; }
AvroMessageParser extracts timestamp field (specified by 'message.timestamp.name') from AVRO data and partitions data by date. with support for ISO8601 date format
extractTimestampMillis
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/AvroIso8601MessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/AvroIso8601MessageParser.java
Apache-2.0
@Override public long extractTimestampMillis(final Message message) { try { GenericRecord record = schemaRegistry.deserialize(message.getTopic(), message.getPayload()); if (record != null) { Object fieldValue = record.get(mConfig.getMessageTimestampName()); if (fieldValue != null) { return toMillis(Double.valueOf(fieldValue.toString()).longValue()); } } else if (m_timestampRequired) { throw new RuntimeException("Missing timestamp field for message: " + message); } } catch (Exception e) { LOG.error("Failed to parse record", e); } return 0; }
AvroMessageParser extracts timestamp field (specified by 'message.timestamp.name') from AVRO data and partitions data by date.
extractTimestampMillis
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/AvroMessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/AvroMessageParser.java
Apache-2.0
@Override public String[] extractPartitions(Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); String result[] = { defaultDate }; if (jsonObject != null) { Object fieldValue = getJsonFieldValue(jsonObject); if (fieldValue != null && inputPattern != null) { try { Date dateFormat = inputFormatter.parse(fieldValue.toString()); result[0] = mDtPrefix + outputFormatter.format(dateFormat); } catch (Exception e) { LOG.warn("Impossible to convert date = {} with the input pattern = {}. Using date default = {}", fieldValue.toString(), inputPattern.toString(), result[0]); } } } return result; }
DateMessageParser extracts the timestamp field (specified by 'message.timestamp.name') and the date pattern (specified by 'message.timestamp.input.pattern') @see java.text.SimpleDateFormat @author Lucas Zago (lucaszago@gmail.com)
extractPartitions
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/DateMessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/DateMessageParser.java
Apache-2.0
@Override public long extractTimestampMillis(final Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); Object fieldValue = jsonObject != null ? getJsonFieldValue(jsonObject) : null; if (m_timestampRequired && fieldValue == null) { throw new RuntimeException("Missing timestamp field for message: " + message); } if (fieldValue != null) { try { Date dateFormat = DatatypeConverter.parseDateTime(fieldValue.toString()).getTime(); return dateFormat.getTime(); } catch (IllegalArgumentException ex) { if (m_timestampRequired){ throw new RuntimeException("Bad timestamp field for message: " + message); } } } return 0; }
Iso8601MessageParser extracts timestamp field (specified by 'message.timestamp.name') @author Jurriaan Pruis (email@jurriaanpruis.nl)
extractTimestampMillis
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/Iso8601MessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/Iso8601MessageParser.java
Apache-2.0
@Override public long extractTimestampMillis(final Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); if (jsonObject != null) { Object fieldValue = getJsonFieldValue(jsonObject); if (fieldValue != null) { return toMillis(Double.valueOf(fieldValue.toString()).longValue()); } } else if (m_timestampRequired) { throw new RuntimeException("Missing timestamp field for message: " + message); } return 0; }
JsonMessageParser extracts timestamp field (specified by 'message.timestamp.name') from JSON data and partitions data by date.
extractTimestampMillis
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/JsonMessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/JsonMessageParser.java
Apache-2.0
@Override public long extractTimestampMillis(Message message) throws Exception { HashMap<String, Object> msgHash = (HashMap<String,Object>)mMessagePackObjectMapper.readValue( message.getPayload(), mTypeReference); Object timestampValue = msgHash.get(mConfig.getMessageTimestampName()); if (timestampValue instanceof Number) { return toMillis(((Number) timestampValue).longValue()); } else if (timestampValue instanceof String) { return toMillis(Long.parseLong((String) timestampValue)); } else { return toMillis((Long) timestampValue); } }
MessagePack timestamped message parser. Requires a second or ms timestamp. Does not support message.timestamp.input.pattern. @author Zack Dever (zack@rd.io)
extractTimestampMillis
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/MessagePackParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/MessagePackParser.java
Apache-2.0
@Override public String[] extractPartitions(Message message) throws Exception { long offset = message.getOffset(); long offsetsPerPartition = mConfig.getOffsetsPerPartition(); long partition = (offset / offsetsPerPartition) * offsetsPerPartition; String[] result = {offsetPrefix + partition}; return result; }
Offset message parser groups messages based on the offset ranges. @author Pawel Garbacki (pawel@pinterest.com)
extractPartitions
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/OffsetMessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/OffsetMessageParser.java
Apache-2.0
@Override public long extractTimestampMillis(final Message message) { String line = new String(message.getPayload()); Matcher m = mTsPattern.matcher(line); if (m.find()) { String tsValue = m.group(1); if (tsValue != null) { return toMillis(Long.parseLong(tsValue)); } } throw new NumberFormatException("Cannot find timestamp field in: " + line); }
RegexMessageParser extracts timestamp field (specified by 'message.timestamp.input.pattern') The pattern specifies the regular exp to extract the timestamp field from a free-text line. * @author Henry Cai (hcai@pinterest.com)
extractTimestampMillis
java
pinterest/secor
src/main/java/com/pinterest/secor/parser/RegexMessageParser.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/parser/RegexMessageParser.java
Apache-2.0
public void deleteOldLogs() throws Exception { if (mConfig.getLocalLogDeleteAgeHours() <= 0) { return; } String[] consumerDirs = FileUtil.list(mConfig.getLocalPath()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); format.setTimeZone(mConfig.getTimeZone()); for (String consumerDir : consumerDirs) { long modificationTime = FileUtil.getModificationTimeMsRecursive(consumerDir); String modificationTimeStr = format.format(modificationTime); LOG.info("Consumer log dir {} last modified at {}", consumerDir , modificationTimeStr); final long localLogDeleteAgeMs = mConfig.getLocalLogDeleteAgeHours() * 60L * 60L * 1000L; if (System.currentTimeMillis() - modificationTime > localLogDeleteAgeMs) { LOG.info("Deleting directory {} last modified at {}", consumerDir, modificationTimeStr); FileUtil.delete(consumerDir); } } }
Log file deleter removes message old log files stored locally. @author Pawel Garbacki (pawel@pinterest.com)
deleteOldLogs
java
pinterest/secor
src/main/java/com/pinterest/secor/tools/LogFileDeleter.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/LogFileDeleter.java
Apache-2.0
public void printFile(String path) throws Exception { FileSystem fileSystem = FileUtil.getFileSystem(path); Path fsPath = new Path(path); SequenceFile.Reader reader = new SequenceFile.Reader(fileSystem, fsPath, new Configuration()); LongWritable key = (LongWritable) reader.getKeyClass().newInstance(); BytesWritable value = (BytesWritable) reader.getValueClass().newInstance(); System.out.println("reading file " + path); while (reader.next(key, value)) { if (mPrintOffsetsOnly) { System.out.println(Long.toString(key.get())); } else { byte[] nonPaddedBytes = new byte[value.getLength()]; System.arraycopy(value.getBytes(), 0, nonPaddedBytes, 0, value.getLength()); System.out.println(Long.toString(key.get()) + ": " + new String(nonPaddedBytes)); } } }
Log file printer displays the content of a log file. @author Pawel Garbacki (pawel@pinterest.com)
printFile
java
pinterest/secor
src/main/java/com/pinterest/secor/tools/LogFilePrinter.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/LogFilePrinter.java
Apache-2.0
private FileReader createFileReader(LogFilePath logFilePath) throws Exception { CompressionCodec codec = null; if (mConfig.getCompressionCodec() != null && !mConfig.getCompressionCodec().isEmpty()) { codec = CompressionUtil.createCompressionCodec(mConfig.getCompressionCodec()); } FileReader fileReader = ReflectionUtil.createFileReader( mConfig.getFileReaderWriterFactory(), logFilePath, codec, mConfig ); return fileReader; }
Helper to create a file reader writer from config @param logFilePath @return @throws Exception
createFileReader
java
pinterest/secor
src/main/java/com/pinterest/secor/tools/LogFileVerifier.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/LogFileVerifier.java
Apache-2.0
public T get() throws Exception { return mFuture.get(); }
Wraps a Future. `get` blocks until the underlying Future completes. @author Liam Stewart (liam.stewart@gmail.com)
get
java
pinterest/secor
src/main/java/com/pinterest/secor/uploader/FutureHandle.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/FutureHandle.java
Apache-2.0
public UploadResult get() throws Exception { return mUpload.waitForUploadResult(); }
Wraps an Upload being managed by the AWS SDK TransferManager. `get` blocks until the upload completes. @author Liam Stewart (liam.stewart@gmail.com)
get
java
pinterest/secor
src/main/java/com/pinterest/secor/uploader/S3UploadHandle.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/S3UploadHandle.java
Apache-2.0
public void applyPolicy(boolean forceUpload) throws Exception { Collection<TopicPartition> topicPartitions = mFileRegistry.getTopicPartitions(); for (TopicPartition topicPartition : topicPartitions) { checkTopicPartition(topicPartition, forceUpload); } }
Apply the Uploader policy for pushing partition files to the underlying storage. For each of the partitions of the file registry, apply the policy for flushing them to the underlying storage. This method could be subclassed to provide an alternate policy. The custom uploader class name would need to be specified in the secor.upload.class. @param forceUpload forceUpload @throws Exception if any error occurs while appying the policy
applyPolicy
java
pinterest/secor
src/main/java/com/pinterest/secor/uploader/Uploader.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/Uploader.java
Apache-2.0
public static CompressionCodec createCompressionCodec(String className) throws Exception { Configuration configuration = new Configuration(); CompressionCodecFactory.setCodecClasses(configuration,new LinkedList<Class>(Collections.singletonList(Class.forName(className)))); CompressionCodecFactory ccf = new CompressionCodecFactory( configuration); return ccf.getCodecByClassName(className); }
Compression Codec related helper methods @author Praveen Murugesan (praveen@uber.com)
createCompressionCodec
java
pinterest/secor
src/main/java/com/pinterest/secor/util/CompressionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/CompressionUtil.java
Apache-2.0
public boolean isConfigured() { return allTopics || !messageClassByTopic.isEmpty(); }
@return whether there was a protobuf class configuration
isConfigured
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ProtobufUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ProtobufUtil.java
Apache-2.0
public Class<? extends Message> getMessageClass(String topic) { return allTopics ? messageClassForAll : messageClassByTopic.get(topic); }
Returns configured protobuf message class for the given Kafka topic @param topic Kafka topic @return protobuf message class used by this utility instance, or <code>null</code> in case valid class couldn't be found in the configuration.
getMessageClass
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ProtobufUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ProtobufUtil.java
Apache-2.0
public Message decodeJsonMessage(String topic, byte[] payload) throws InvalidProtocolBufferException { try { Method builderGetter = allTopics ? messageClassForAll.getDeclaredMethod("newBuilder") : messageClassByTopic.get(topic).getDeclaredMethod("newBuilder"); com.google.protobuf.GeneratedMessageV3.Builder builder = (com.google.protobuf.GeneratedMessageV3.Builder) builderGetter.invoke(null); jsonParser.merge(new InputStreamReader(new ByteArrayInputStream(payload)), builder); return builder.build(); } catch (InvalidProtocolBufferException e){ throw e; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Error parsing JSON message", e); } catch (IOException e) { throw new RuntimeException("Error creating read stream for JSON message", e); } }
Decodes protobuf message @param topic Kafka topic name @param payload Byte array containing encoded json message @return protobuf message instance @throws RuntimeException when there's problem decoding protobuf message
decodeJsonMessage
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ProtobufUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ProtobufUtil.java
Apache-2.0
public Message decodeProtobufMessage(String topic, byte[] payload){ Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic.get(topic); try { return (Message) parseMethod.invoke(null, payload); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not callable. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e); } catch (IllegalAccessException e) { throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not accessible. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e); } catch (InvocationTargetException e) { throw new RuntimeException("Error parsing protobuf message", e); } }
Decodes protobuf message @param topic Kafka topic name @param payload Byte array containing encoded protobuf @return protobuf message instance @throws RuntimeException when there's problem decoding protobuf
decodeProtobufMessage
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ProtobufUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ProtobufUtil.java
Apache-2.0
public static UploadManager createUploadManager(String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!UploadManager.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, UploadManager.class.getName())); } // Assume that subclass of UploadManager has a constructor with the same signature as UploadManager return (UploadManager) clazz.getConstructor(SecorConfig.class).newInstance(config); }
Create an UploadManager from its fully qualified class name. The class passed in by name must be assignable to UploadManager and have 1-parameter constructor accepting a SecorConfig. See the secor.upload.manager.class config option. @param className The class name of a subclass of UploadManager @param config The SecorCondig to initialize the UploadManager with @return an UploadManager instance with the runtime type of the class passed by name @throws Exception on error
createUploadManager
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
public static Uploader createUploader(String className) throws Exception { Class<?> clazz = Class.forName(className); if (!Uploader.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, Uploader.class.getName())); } return (Uploader) clazz.newInstance(); }
Create an Uploader from its fully qualified class name. The class passed in by name must be assignable to Uploader. See the secor.upload.class config option. @param className The class name of a subclass of Uploader @return an UploadManager instance with the runtime type of the class passed by name @throws Exception on error
createUploader
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
public static MessageParser createMessageParser(String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!MessageParser.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, MessageParser.class.getName())); } // Assume that subclass of MessageParser has a constructor with the same signature as MessageParser return (MessageParser) clazz.getConstructor(SecorConfig.class).newInstance(config); }
Create a MessageParser from it's fully qualified class name. The class passed in by name must be assignable to MessageParser and have 1-parameter constructor accepting a SecorConfig. Allows the MessageParser to be pluggable by providing the class name of a desired MessageParser in config. See the secor.message.parser.class config option. @param className The class name of a subclass of MessageParser @param config The SecorCondig to initialize the MessageParser with @return a MessageParser instance with the runtime type of the class passed by name @throws Exception on error
createMessageParser
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
private static FileReaderWriterFactory createFileReaderWriterFactory(String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, FileReaderWriterFactory.class.getName())); } try { // Try to load constructor that accepts single parameter - secor // configuration instance return (FileReaderWriterFactory) clazz.getConstructor(SecorConfig.class).newInstance(config); } catch (NoSuchMethodException e) { // Fallback to parameterless constructor return (FileReaderWriterFactory) clazz.newInstance(); } }
Create a FileReaderWriterFactory that is able to read and write a specific type of output log file. The class passed in by name must be assignable to FileReaderWriterFactory. Allows for pluggable FileReader and FileWriter instances to be constructed for a particular type of log file. See the secor.file.reader.writer.factory config option. @param className the class name of a subclass of FileReaderWriterFactory @param config The SecorCondig to initialize the FileReaderWriterFactory with @return a FileReaderWriterFactory with the runtime type of the class passed by name @throws Exception
createFileReaderWriterFactory
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
public static FileWriter createFileWriter(String className, LogFilePath logFilePath, CompressionCodec codec, SecorConfig config) throws Exception { return createFileReaderWriterFactory(className, config).BuildFileWriter(logFilePath, codec); }
Use the FileReaderWriterFactory specified by className to build a FileWriter @param className the class name of a subclass of FileReaderWriterFactory to create a FileWriter from @param logFilePath the LogFilePath that the returned FileWriter should write to @param codec an instance CompressionCodec to compress the file written with, or null for no compression @param config The SecorCondig to initialize the FileWriter with @return a FileWriter specialised to write the type of files supported by the FileReaderWriterFactory @throws Exception on error
createFileWriter
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
public static FileReader createFileReader(String className, LogFilePath logFilePath, CompressionCodec codec, SecorConfig config) throws Exception { return createFileReaderWriterFactory(className, config).BuildFileReader(logFilePath, codec); }
Use the FileReaderWriterFactory specified by className to build a FileReader @param className the class name of a subclass of FileReaderWriterFactory to create a FileReader from @param logFilePath the LogFilePath that the returned FileReader should read from @param codec an instance CompressionCodec to decompress the file being read, or null for no compression @param config The SecorCondig to initialize the FileReader with @return a FileReader specialised to read the type of files supported by the FileReaderWriterFactory @throws Exception on error
createFileReader
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
public static MessageTransformer createMessageTransformer( String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!MessageTransformer.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format( "The class '%s' is not assignable to '%s'.", className, MessageTransformer.class.getName())); } return (MessageTransformer) clazz.getConstructor(SecorConfig.class) .newInstance(config); }
Create a MessageTransformer from it's fully qualified class name. The class passed in by name must be assignable to MessageTransformers and have 1-parameter constructor accepting a SecorConfig. Allows the MessageTransformers to be pluggable by providing the class name of a desired MessageTransformers in config. See the secor.message.transformer.class config option. @param className class name @param config secor config @return MessageTransformer @throws Exception on error
createMessageTransformer
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
public static ORCSchemaProvider createORCSchemaProvider( String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!ORCSchemaProvider.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format( "The class '%s' is not assignable to '%s'.", className, ORCSchemaProvider.class.getName())); } return (ORCSchemaProvider) clazz.getConstructor(SecorConfig.class) .newInstance(config); }
Create a ORCSchemaProvider from it's fully qualified class name. The class passed in by name must be assignable to ORCSchemaProvider and have 1-parameter constructor accepting a SecorConfig. Allows the ORCSchemaProvider to be pluggable by providing the class name of a desired ORCSchemaProvider in config. See the secor.orc.schema.provider config option. @param className class name @param config secor config @return ORCSchemaProvider @throws Exception on error
createORCSchemaProvider
java
pinterest/secor
src/main/java/com/pinterest/secor/util/ReflectionUtil.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ReflectionUtil.java
Apache-2.0
private static void setUnion(JSONWriter writer, UnionColumnVector vector, TypeDescription schema, int row) throws JSONException { int tag = vector.tags[row]; List<TypeDescription> schemaChildren = schema.getChildren(); ColumnVector columnVector = vector.fields[tag]; setValue(writer, columnVector, schemaChildren.get(tag), row); }
Writes a single row of union type as a JSON object. @throws JSONException
setUnion
java
pinterest/secor
src/main/java/com/pinterest/secor/util/orc/JsonFieldFiller.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/JsonFieldFiller.java
Apache-2.0
@Override public TypeDescription getSchema(String topic, LogFilePath logFilePath) { TypeDescription topicSpecificTD = topicToSchemaMap.get(topic); if (null != topicSpecificTD) { return topicSpecificTD; } return schemaForAlltopic; }
Default implementation for ORC schema provider. It fetches ORC schemas from configuration. User has to specify one schema per kafka topic or can have same schema for all the topics. @author Ashish (ashu.impetus@gmail.com)
getSchema
java
pinterest/secor
src/main/java/com/pinterest/secor/util/orc/schema/DefaultORCSchemaProvider.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/schema/DefaultORCSchemaProvider.java
Apache-2.0
private void setSchemas(SecorConfig config) { Map<String, String> schemaPerTopic = config.getORCMessageSchema(); for (Entry<String, String> entry : schemaPerTopic.entrySet()) { String topic = entry.getKey(); TypeDescription schema = TypeDescription.fromString(entry .getValue()); topicToSchemaMap.put(topic, schema); // If common schema is given if ("*".equals(topic)) { schemaForAlltopic = schema; } } }
This method is used for fetching all ORC schemas from config @param config
setSchemas
java
pinterest/secor
src/main/java/com/pinterest/secor/util/orc/schema/DefaultORCSchemaProvider.java
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/schema/DefaultORCSchemaProvider.java
Apache-2.0
public static String decompressToStringForZlib(byte[] bytesToDecompress, String charsetName) { byte[] bytesDecompressed = decompressForZlib(bytesToDecompress); String returnValue = null; try { returnValue = new String(bytesDecompressed, 0, bytesDecompressed.length, charsetName); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } return returnValue; }
zlib decompress 2 String @param bytesToDecompress byte[] @param charsetName String @return String
decompressToStringForZlib
java
xiaobailong24/MVVMArms
repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
Apache-2.0
public static byte[] decompressForZlib(byte[] bytesToDecompress) { byte[] returnValues = null; Inflater inflater = new Inflater(); int numberOfBytesToDecompress = bytesToDecompress.length; inflater.setInput(bytesToDecompress, 0, numberOfBytesToDecompress); int numberOfBytesDecompressedSoFar = 0; List<Byte> bytesDecompressedSoFar = new ArrayList<>(); try { while (!inflater.needsInput()) { byte[] bytesDecompressedBuffer = new byte[numberOfBytesToDecompress]; int numberOfBytesDecompressedThisTime = inflater.inflate(bytesDecompressedBuffer); numberOfBytesDecompressedSoFar += numberOfBytesDecompressedThisTime; for (int b = 0; b < numberOfBytesDecompressedThisTime; b++) { bytesDecompressedSoFar.add(bytesDecompressedBuffer[b]); } } returnValues = new byte[bytesDecompressedSoFar.size()]; for (int b = 0; b < returnValues.length; b++) { returnValues[b] = (byte) (bytesDecompressedSoFar.get(b)); } } catch (DataFormatException dfe) { dfe.printStackTrace(); } inflater.end(); return returnValues; }
zlib decompress 2 byte @param bytesToDecompress byte[] @return byte[]
decompressForZlib
java
xiaobailong24/MVVMArms
repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
Apache-2.0
public static byte[] compressForZlib(byte[] bytesToCompress) { Deflater deflater = new Deflater(); deflater.setInput(bytesToCompress); deflater.finish(); byte[] bytesCompressed = new byte[Short.MAX_VALUE]; int numberOfBytesAfterCompression = deflater.deflate(bytesCompressed); byte[] returnValues = new byte[numberOfBytesAfterCompression]; System.arraycopy(bytesCompressed, 0, returnValues, 0, numberOfBytesAfterCompression); return returnValues; }
zlib compress 2 byte @param bytesToCompress byte[] @return byte[]
compressForZlib
java
xiaobailong24/MVVMArms
repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
Apache-2.0
public static byte[] compressForZlib(String stringToCompress) { byte[] returnValues = null; try { returnValues = compressForZlib(stringToCompress.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } return returnValues; }
zlib compress 2 byte @param stringToCompress String @return byte[]
compressForZlib
java
xiaobailong24/MVVMArms
repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
Apache-2.0
public static byte[] compressForGzip(String string) { ByteArrayOutputStream os = null; GZIPOutputStream gos = null; try { os = new ByteArrayOutputStream(string.length()); gos = new GZIPOutputStream(os); gos.write(string.getBytes("UTF-8")); return os.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { closeQuietly(gos); closeQuietly(os); } return null; }
gzip compress 2 byte @param string String @return byte[]
compressForGzip
java
xiaobailong24/MVVMArms
repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/me/xiaobailong24/mvvmarms/repository/utils/ZipHelper.java
Apache-2.0
@Override public void execute() { MesosCluster cluster = repository.loadCluster(new MesosClusterContainersFactory()); if (cluster != null) { Marathon marathon = cluster.getMarathon(); if (marathon == null) { throw new MinimesosException("Marathon container is not found in cluster " + cluster.getClusterId()); } String marathonJson; try { marathonJson = getMarathonJson(); } catch (IOException e) { throw new MinimesosException("Failed to read JSON file from path, URL or stdin", e); } if (update) { marathon.updateApp(marathonJson); } else if (isNotBlank(app) || isNotBlank(marathonFile)) { marathon.deployApp(marathonJson); } else if (isNotBlank(group)) { marathon.deployGroup(marathonJson); } else { throw new MinimesosException("Neither app, group, --stdinApp or --stdinGroup is provided"); } } else { throw new MinimesosException("Running cluster is not found"); } }
Installs an Marathon application or application group.
execute
java
ContainerSolutions/minimesos
cli/src/main/java/com/containersol/minimesos/main/CommandInstall.java
https://github.com/ContainerSolutions/minimesos/blob/master/cli/src/main/java/com/containersol/minimesos/main/CommandInstall.java
Apache-2.0
public ClusterConfig readClusterConfigFromMinimesosFile() { InputStream clusterConfigFile = MesosCluster.getInputStream(getClusterConfigPath()); if (clusterConfigFile != null) { ConfigParser configParser = new ConfigParser(); try { return configParser.parse(IOUtils.toString(clusterConfigFile, "UTF-8")); } catch (Exception e) { String msg = String.format("Failed to load cluster configuration from %s: %s", getClusterConfigPath(), e.getMessage()); throw new MinimesosException(msg, e); } } throw new MinimesosException("No minimesosFile found in current directory. Please generate one with 'minimesos init'"); }
Reads ClusterConfig from minimesosFile. @return configuration of the cluster from the minimesosFile @throws MinimesosException if minimesosFile is not found or malformed
readClusterConfigFromMinimesosFile
java
ContainerSolutions/minimesos
cli/src/main/java/com/containersol/minimesos/main/CommandUp.java
https://github.com/ContainerSolutions/minimesos/blob/master/cli/src/main/java/com/containersol/minimesos/main/CommandUp.java
Apache-2.0
public MesosCluster loadCluster(MesosClusterFactory factory) { String clusterId = readClusterId(); if (clusterId != null) { try { return MesosCluster.loadCluster(clusterId, factory); } catch (MinimesosException e) { deleteMinimesosFile(); } } return null; }
Loads representation of the running cluster @return representation of the cluster, which ID is found in the file
loadCluster
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterRepository.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterRepository.java
Apache-2.0
public void saveClusterFile(MesosCluster cluster) { String clusterId = cluster.getClusterId(); File dotMinimesosDir = getMinimesosDir(); try { FileUtils.forceMkdir(dotMinimesosDir); String clusterIdPath = dotMinimesosDir.getAbsolutePath() + "/" + MINIMESOS_FILE_PROPERTY; Files.write(Paths.get(clusterIdPath), clusterId.getBytes()); LOGGER.debug("Writing cluster ID " + clusterId + " to " + clusterIdPath); } catch (IOException ie) { LOGGER.error("Could not write .minimesos folder", ie); throw new RuntimeException(ie); } }
Writes cluster id to file @param cluster cluster to store ID
saveClusterFile
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterRepository.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterRepository.java
Apache-2.0
public File getMinimesosFile() { return new File(getMinimesosDir(), MINIMESOS_FILE_PROPERTY); }
@return file, possibly non-existing, where cluster information is stored
getMinimesosFile
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterRepository.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterRepository.java
Apache-2.0
public static List<ClusterProcess> getDistinctRoleProcesses(List<ClusterProcess> processes) { List<ClusterProcess> distinct = new ArrayList<>(); Map<String, Integer> roles = new HashMap<>(); // count processes per role for (ClusterProcess process : processes) { Integer prev = roles.get(process.getRole()); int count = (prev != null) ? prev : 0; roles.put(process.getRole(), count+1 ); } for (Map.Entry<String, Integer> role : roles.entrySet() ) { if (role.getValue() == 1) { Optional<ClusterProcess> process = processes.stream().filter(withRole(role.getKey())).findFirst(); distinct.add(process.get()); } } return distinct; }
Filters given list of processes and returns only those with distinct roles @param processes complete list of processes @return processes with distinct roles
getDistinctRoleProcesses
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/ClusterUtil.java
Apache-2.0
public static MesosCluster loadCluster(String clusterId, MesosClusterFactory factory) { return new MesosCluster(clusterId, factory); }
Recreate a MesosCluster object based on an existing cluster ID. @param clusterId the cluster ID of the cluster that is already running
loadCluster
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public void start(int timeoutSeconds) { if (running) { throw new IllegalStateException("Cluster " + clusterId + " is already running"); } if (Environment.isRunningInJvmOnMacOsX() || Environment.isRunningInDockerOnMac()) { LOGGER.info("Detected Mac Environment X, running with '--mapPortsToHost' so master and marathon ports are mapped to localhost"); clusterConfig.setMapPortsToHost(true); } LOGGER.debug("Cluster " + getClusterId() + " - start"); this.memberProcesses.forEach((container) -> container.start(timeoutSeconds)); // wait until the given number of agents are registered getMaster().waitFor(); Marathon marathon = getMarathon(); if (marathon != null) { marathon.installMarathonApps(); } running = true; }
Starts the Mesos cluster and its containers with given timeout. @param timeoutSeconds seconds to wait until timeout
start
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public void state(PrintStream out) { JSONObject stateInfo = getClusterStateInfo(); if (stateInfo != null) { out.println(stateInfo.toString(2)); } else { throw new MinimesosException("Could not retrieve the state from the cluster at " + getMaster().getServiceUrl() + ". Is it running?"); } }
Prints the state of the Mesos master or agent
state
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public void destroy(MesosClusterFactory factory) { LOGGER.debug("Cluster " + getClusterId() + " - destroy"); Marathon marathon = getMarathon(); if (marathon != null) { marathon.killAllApps(); } if (memberProcesses.size() > 0) { for (int i = memberProcesses.size() - 1; i >= 0; i--) { ClusterProcess container = memberProcesses.get(i); LOGGER.debug("Removing container [" + container.getContainerId() + "]"); try { container.remove(); } catch (NotFoundException e) { LOGGER.error(String.format("Cannot remove container %s, maybe it's already dead?", container.getContainerId())); } } } this.running = false; this.memberProcesses.clear(); if (clusterId != null) { factory.destroyRunningCluster(clusterId); File sandboxLocation = new File(MesosCluster.getClusterHostDir(), ".minimesos/sandbox-" + clusterId); if (sandboxLocation.exists()) { try { FileUtils.forceDelete(sandboxLocation); } catch (IOException e) { String msg = String.format("Failed to force delete the cluster sandbox at %s", sandboxLocation.getAbsolutePath()); throw new MinimesosException(msg, e); } } } else { LOGGER.info("Minimesos cluster is not running"); } repository.deleteClusterFile(); this.running = false; }
Destroys the Mesos cluster and its containers
destroy
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public String addAndStartProcess(ClusterProcess process, int timeout) { process.setCluster(this); memberProcesses.add(process); LOGGER.debug(String.format("Starting %s (%s) container", process.getName(), process.getContainerId())); try { process.start(timeout); } catch (Exception exc) { String msg = String.format("Failed to start %s (%s) container", process.getName(), process.getContainerId()); LOGGER.error(msg, exc); throw new MinimesosException(msg, exc); } return process.getContainerId(); }
Starts a container. This container will be removed when the Mesos cluster is shut down. @param process container to be started @param timeout in seconds @return container ID
addAndStartProcess
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public String addAndStartProcess(ClusterProcess clusterProcess) { return addAndStartProcess(clusterProcess, clusterConfig.getTimeout()); }
Starts a container. This container will be removed when the Mesos cluster is shut down. The method is used by frameworks @param clusterProcess container to be started @return container ID
addAndStartProcess
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public JSONObject getClusterStateInfo() { try { return getMaster().getStateInfoJSON(); } catch (UnirestException e) { throw new MinimesosException("Failed to retrieve state from Mesos Master", e); } }
Retrieves JSON with Mesos Cluster master state @return stage JSON
getClusterStateInfo
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public static File getClusterHostDir() { String sp = System.getProperty(MINIMESOS_HOST_DIR_PROPERTY); if (sp == null) { sp = System.getProperty("user.dir"); } return new File(sp); }
Returns the directory on the host from which the cluster was created. @return directory
getClusterHostDir
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public static InputStream getInputStream(String location) { InputStream is = null; if (location != null) { URI uri; try { uri = URI.create(location); if (!uri.isAbsolute()) { uri = null; } } catch (IllegalArgumentException ignored) { //NOSONAR // means this is not a valid URI, could be filepath uri = null; } if (uri != null) { try { is = uri.toURL().openStream(); } catch (IOException e) { throw new MinimesosException("Failed to open URL " + location + ". Check URL syntax, your network connectivity or DNS settings.", e); } } else { // location is not an absolute URI, therefore treat it as relative or absolute path File file = new File(location); if (!file.exists()) { file = new File(getClusterHostDir(), location); } if (file.exists()) { try { is = new FileInputStream(file); } catch (FileNotFoundException e) { throw new MinimesosException("Failed to open " + file.getAbsolutePath() + " file", e); } } } } return is; }
Taking either URI or path to a file, returns string with its content @param location either absolute URI or path to a file @return input stream with location content or null
getInputStream
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public String getLoggingLevel() { return clusterConfig.getLoggingLevel(); }
@return configured or default logging level of all Mesos containers in the cluster
getLoggingLevel
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public String getConfiguredMesosVersion() { return clusterConfig.getMesosVersion(); }
@return Mesos version that is configured
getConfiguredMesosVersion
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public String getMesosVersion() { return getMaster().getState().getVersion(); }
@return Mesos version of running cluster
getMesosVersion
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/cluster/MesosCluster.java
Apache-2.0
public List<Container> getContainers() { return containers; }
Use this getter if you need to iterate over docker objects @return set of docker containers
getContainers
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public DockerContainersUtil filterByName(String pattern) { if (this.containers == null) { return this; } List<Container> matched = new ArrayList<>(); for (Container container : containers) { String[] names = container.getNames(); for (String name : names) { // all names start with '/' if (name.substring(1).matches(pattern)) { matched.add(container); } } } return new DockerContainersUtil(matched); }
Filters the set based on the container name @param pattern regular expression pattern of the container name @return filtered set
filterByName
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public DockerContainersUtil filterByImage(String pattern) { if (this.containers == null) { return this; } List<Container> matched = new ArrayList<>(); for (Container container : containers) { if (container.getImage().matches(pattern)) { matched.add(container); } } return new DockerContainersUtil(matched); }
Filters the set based on the constainer name @param pattern regular expression pattern of the container name @return filtered set
filterByImage
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public DockerContainersUtil kill(boolean ignoreFailure) { if (containers != null) { for (Container container : containers) { try { DockerClientFactory.build().killContainerCmd(container.getId()).exec(); } catch (DockerException failure) { if (!ignoreFailure) { throw failure; } } } } return this; }
Removes all containers in the util object @param ignoreFailure - use <code>true</code> if you expect containers might be stopped by this time
kill
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public static String getIpAddress(String containerId) { InspectContainerResponse response = DockerClientFactory.build().inspectContainerCmd(containerId).exec(); return response.getNetworkSettings().getIpAddress(); }
@param containerId id of the container to inspect @return IP Address of the container
getIpAddress
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public static void pullImage(String imageName, String imageVersion, long timeoutSecs) { try { final CompletableFuture<Void> result = new CompletableFuture<>(); DockerClientFactory.build().pullImageCmd(imageName).withTag(imageVersion).exec(new PullImageResultCallback()).awaitCompletion(); } catch (InterruptedException | RuntimeException e) { throw new MinimesosException("Error pulling image or image not found in registry: " + imageName + ":" + imageVersion, e); } }
Pulls a Docker image with given name and version. Throws exception when it times out after given timeout. @param imageName image to pull @param imageVersion image version to pull @param timeoutSecs pulling timeout in seconds
pullImage
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public static String getGatewayIpAddress(String containerId) { InspectContainerResponse response = DockerClientFactory.build().inspectContainerCmd(containerId).exec(); return response.getNetworkSettings().getGateway(); }
@return IP Address of the container's gateway (which would be docker0)
getGatewayIpAddress
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public static Container getContainer(String containerId) { List<Container> containers = DockerClientFactory.build().listContainersCmd().withShowAll(true).exec(); Container container = null; if (containers != null && !containers.isEmpty()) { Optional<Container> optional = containers.stream().filter(c -> c.getId().equals(containerId)).findFirst(); if (optional.isPresent()) { container = optional.get(); } } return container; }
@param containerId id of the container to retrieve @return container or null
getContainer
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/docker/DockerContainersUtil.java
Apache-2.0
public void pullImage() { pullImage(getImageName(), getImageTag()); }
Implement this method to pull your image. This will be called before the container is run.
pullImage
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
Apache-2.0
public String getImageName() { return config.getImageName(); }
@return name of the container to use
getImageName
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
Apache-2.0
public String getImageTag() { return config.getImageTag(); }
@return verstion of the container to use
getImageTag
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
Apache-2.0
@Override public void start(int timeout) { if (containerId != null) { return; } pullImage(); CreateContainerCmd createCommand = dockerCommand(); LOGGER.debug("Creating container [" + createCommand.getName() + "]"); containerId = createCommand.exec().getId(); DockerClientFactory.build().startContainerCmd(containerId).exec(); try { await("Container did not start within " + timeout + " seconds").atMost(timeout, TimeUnit.SECONDS).pollDelay(1, TimeUnit.SECONDS).until(() -> { List<Container> containers = DockerClientFactory.build().listContainersCmd().withShowAll(true).exec(); for (Container container : containers) { if (container.getId().equals(containerId)) { return true; } } return false; }); } catch (ConditionTimeoutException cte) { String errorMessage = String.format("Container [%s] did not start within %d seconds.", createCommand.getName(), timeout); LOGGER.error(errorMessage); try { for (String logLine : DockerContainersUtil.getDockerLogs(containerId)) { LOGGER.error(logLine); } } catch (Exception e) { LOGGER.error("Could not print container logs", e); } throw new MinimesosException(errorMessage + " See container logs above"); } LOGGER.debug(String.format("Container %s is up and running", containerId)); }
Starts the container and waits until is started @param timeout in seconds
start
java
ContainerSolutions/minimesos
minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
https://github.com/ContainerSolutions/minimesos/blob/master/minimesos/src/main/java/com/containersol/minimesos/integrationtest/container/AbstractContainer.java
Apache-2.0