code
stringlengths 23
201k
| docstring
stringlengths 17
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
72
| path
stringlengths 11
317
| url
stringlengths 57
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
private List<Stat> getStats() throws Exception {
List<String> topics = mZookeeperConnector.getCommittedOffsetTopics();
List<Stat> stats = Lists.newArrayList();
for (String topic : topics) {
if (topic.matches(mConfig.getMonitoringBlacklistTopics()) ||
!topic.matches(mConfig.getKafkaTopicFilter())) {
LOG.info("skipping topic {}", topic);
continue;
}
List<Integer> partitions = mZookeeperConnector.getCommittedOffsetPartitions(topic);
for (Integer partition : partitions) {
try {
TopicPartition topicPartition = new TopicPartition(topic, partition);
Message committedMessage = mKafkaClient.getCommittedMessage(topicPartition);
long committedOffset = -1;
long committedTimestampMillis = -1;
if (committedMessage == null) {
LOG.warn("no committed message found in topic {} partition {}", topic, partition);
continue;
} else {
committedOffset = committedMessage.getOffset();
committedTimestampMillis = getTimestamp(committedMessage);
}
Message lastMessage = mKafkaClient.getLastMessage(topicPartition);
if (lastMessage == null) {
LOG.warn("no message found in topic {} partition {}", topic, partition);
} else {
long lastOffset = lastMessage.getOffset();
long lastTimestampMillis = getTimestamp(lastMessage);
assert committedOffset <= lastOffset: Long.toString(committedOffset) + " <= " +
lastOffset;
long offsetLag = lastOffset - committedOffset;
long timestampMillisLag = lastTimestampMillis - committedTimestampMillis;
Map<String, String> tags = ImmutableMap.of(
Stat.STAT_KEYS.TOPIC.getName(), topic,
Stat.STAT_KEYS.PARTITION.getName(), Integer.toString(partition),
Stat.STAT_KEYS.GROUP.getName(), mConfig.getKafkaGroup()
);
long timestamp = System.currentTimeMillis() / 1000;
stats.add(Stat.createInstance(metricName("lag.offsets"), tags, Long.toString(offsetLag), timestamp));
stats.add(Stat.createInstance(metricName("lag.seconds"), tags, Long.toString(timestampMillisLag / 1000), timestamp));
LOG.debug("topic {} partition {} committed offset {} last offset {} committed timestamp {} last timestamp {}",
topic, partition, committedOffset, lastOffset,
(committedTimestampMillis / 1000), (lastTimestampMillis / 1000));
}
} catch (RuntimeException e) {
LOG.warn(e.getMessage(), e);
}
}
}
return stats;
}
|
Helper to publish stats to statsD client
|
getStats
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
Apache-2.0
|
private String metricName(String key) {
return Joiner.on(".").join(mPrefix, key);
}
|
Helper to publish stats to statsD client
|
metricName
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
Apache-2.0
|
private long getTimestamp(Message message) throws Exception {
if (mMessageParser instanceof TimestampedMessageParser) {
return ((TimestampedMessageParser)mMessageParser).getTimestampMillis(message);
} else {
return -1;
}
}
|
Helper to publish stats to statsD client
|
getTimestamp
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
Apache-2.0
|
public String getName() {
return this.mName;
}
|
JSON hash map extension to store statistics
|
getName
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
Apache-2.0
|
public static Stat createInstance(String metric, Map<String, String> tags, String value, long timestamp) {
return new Stat(ImmutableMap.of(
STAT_KEYS.METRIC.getName(), metric,
STAT_KEYS.TAGS.getName(), tags,
STAT_KEYS.VALUE.getName(), value,
STAT_KEYS.TIMESTAMP.getName(), timestamp
));
}
|
JSON hash map extension to store statistics
|
createInstance
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/tools/ProgressMonitor.java
|
Apache-2.0
|
@java.lang.Override
public Handle<?> upload(LogFilePath localPath) throws Exception {
final String azureContainer = mConfig.getAzureContainer();
final String azureKey = localPath.withPrefix(mConfig.getAzurePath()).getLogFilePath();
final File localFile = new File(localPath.getLogFilePath());
LOG.info("uploading file {} to azure://{}/{}", localFile, azureContainer, azureKey);
final Future<?> f = executor.submit(new Runnable() {
@Override
public void run() {
try {
CloudBlobContainer container = blobClient.getContainerReference(azureContainer);
container.createIfNotExists();
CloudBlockBlob blob = container.getBlockBlobReference(azureKey);
blob.upload(new java.io.FileInputStream(localFile), localFile.length());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (StorageException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return new FutureHandle(f);
}
|
Manages uploads to Microsoft Azure blob storage using Azure Storage SDK for java
https://github.com/azure/azure-storage-java
@author Taichi Nakashima (nsd22843@gmail.com)
|
upload
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/AzureUploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/AzureUploadManager.java
|
Apache-2.0
|
@Override
public void run() {
try {
CloudBlobContainer container = blobClient.getContainerReference(azureContainer);
container.createIfNotExists();
CloudBlockBlob blob = container.getBlockBlobReference(azureKey);
blob.upload(new java.io.FileInputStream(localFile), localFile.length());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (StorageException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
Manages uploads to Microsoft Azure blob storage using Azure Storage SDK for java
https://github.com/azure/azure-storage-java
@author Taichi Nakashima (nsd22843@gmail.com)
|
run
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/AzureUploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/AzureUploadManager.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
|
@Override
public Handle<?> upload(LogFilePath localPath) throws Exception {
final String gsBucket = mConfig.getGsBucket();
final String gsKey = localPath.withPrefix(mConfig.getGsPath()).getLogFilePath();
final File localFile = new File(localPath.getLogFilePath());
final boolean directUpload = mConfig.getGsDirectUpload();
LOG.info("uploading file {} to gs://{}/{}", localFile, gsBucket, gsKey);
final BlobInfo sourceBlob = BlobInfo
.newBuilder(BlobId.of(gsBucket, gsKey))
.setContentType(Files.probeContentType(localFile.toPath()))
.build();
rateLimiter.acquire();
final Future<?> f = executor.submit(new Runnable() {
@Override
public void run() {
try {
if (directUpload) {
byte[] content = Files.readAllBytes(localFile.toPath());
Blob result = mClient.create(sourceBlob, content);
LOG.debug("Upload file {} to gs://{}/{}", localFile, gsBucket, gsKey);
LOG.trace("Upload file {}, Blob: {}", result);
} else {
long startTime = System.nanoTime();
try (WriteChannel out = mClient.writer(sourceBlob);
FileChannel in = new FileInputStream(localFile).getChannel();
) {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 5); // 5 MiB buffer (remember this is pr. thread)
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
}
long elapsedTime = System.nanoTime() - startTime;
LOG.debug("Upload file {} to gs://{}/{} in {} msec", localFile, gsBucket, gsKey, (elapsedTime / 1000000.0));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return new FutureHandle(f);
}
|
Global instance of the Storage. The best practice is to make it a single
globally shared instance across your application.
|
upload
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/GsUploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/GsUploadManager.java
|
Apache-2.0
|
@Override
public void run() {
try {
if (directUpload) {
byte[] content = Files.readAllBytes(localFile.toPath());
Blob result = mClient.create(sourceBlob, content);
LOG.debug("Upload file {} to gs://{}/{}", localFile, gsBucket, gsKey);
LOG.trace("Upload file {}, Blob: {}", result);
} else {
long startTime = System.nanoTime();
try (WriteChannel out = mClient.writer(sourceBlob);
FileChannel in = new FileInputStream(localFile).getChannel();
) {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 5); // 5 MiB buffer (remember this is pr. thread)
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
}
long elapsedTime = System.nanoTime() - startTime;
LOG.debug("Upload file {} to gs://{}/{} in {} msec", localFile, gsBucket, gsKey, (elapsedTime / 1000000.0));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
Global instance of the Storage. The best practice is to make it a single
globally shared instance across your application.
|
run
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/GsUploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/GsUploadManager.java
|
Apache-2.0
|
private static Storage getService(String credentialsPath, int connectTimeoutMs, int readTimeoutMs) throws Exception {
if (mStorageService == null) {
StorageOptions.Builder builder;
if (credentialsPath != null && !credentialsPath.isEmpty()) {
try (FileInputStream fis = new FileInputStream(credentialsPath)) {
GoogleCredentials credential = GoogleCredentials
.fromStream(new FileInputStream(credentialsPath))
.createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM));
// Depending on the environment that provides the default credentials (e.g. Compute Engine, App
// Engine), the credentials may require us to specify the scopes we need explicitly.
// Check for this case, and inject the scope if required.
if (credential.createScopedRequired()) {
credential = credential.createScoped(StorageScopes.all());
}
builder = StorageOptions.newBuilder().setCredentials(credential);
} catch (IOException e) {
throw new RuntimeException("Failed to load Google credentials : " + credentialsPath, e);
}
} else {
builder = StorageOptions.getDefaultInstance().toBuilder();
}
// These retrySettings are copied from default com.google.cloud.ServiceOptions#getDefaultRetrySettingsBuilder
// and changed initial retry delay to 5 seconds from 1 seconds.
// Changed max attempts from 6 to 12.
builder.setRetrySettings(RetrySettings.newBuilder()
.setMaxAttempts(12)
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setMaxRetryDelay(Duration.ofMillis(32_000L))
.setRetryDelayMultiplier(2.0)
.setTotalTimeout(Duration.ofMillis(50_000L))
.setInitialRpcTimeout(Duration.ofMillis(50_000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(50_000L))
.build());
mStorageService = builder
.build()
.getService();
}
return mStorageService;
}
|
Global instance of the Storage. The best practice is to make it a single
globally shared instance across your application.
|
getService
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/GsUploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/GsUploadManager.java
|
Apache-2.0
|
public Handle<?> upload(LogFilePath localPath) throws Exception {
String prefix = FileUtil.getPrefix(localPath.getTopic(), mConfig);
LogFilePath path = localPath.withPrefix(prefix);
final String localLogFilename = localPath.getLogFilePath();
final String logFileName;
if (FileUtil.s3PathPrefixIsAltered(path.getLogFilePath(), mConfig)) {
logFileName = localPath.withPrefix(FileUtil.getS3AlternativePrefix(mConfig)).getLogFilePath();
LOG.info("Will upload file to alternative s3 prefix path {}", logFileName);
}
else {
logFileName = path.getLogFilePath();
}
LOG.info("uploading file {} to {}", localLogFilename, logFileName);
final Future<?> f = executor.submit(new Runnable() {
@Override
public void run() {
try {
FileUtil.moveToCloud(localLogFilename, logFileName);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return new FutureHandle(f);
}
|
Manages uploads to S3 using the Hadoop API.
@author Pawel Garbacki (pawel@pinterest.com)
|
upload
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/HadoopS3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/HadoopS3UploadManager.java
|
Apache-2.0
|
@Override
public void run() {
try {
FileUtil.moveToCloud(localLogFilename, logFileName);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
Manages uploads to S3 using the Hadoop API.
@author Pawel Garbacki (pawel@pinterest.com)
|
run
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/HadoopS3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/HadoopS3UploadManager.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 AWSCredentials getCredentials() {
if (sessionToken.isEmpty()) {
return new BasicAWSCredentials(accessKey, secretKey);
} else {
return new BasicSessionCredentials(accessKey, secretKey, sessionToken);
}
}
|
Manages uploads to S3 using the TransferManager class from the AWS
SDK.
<p>
Set the <code>aws.sse.type</code> property to specify the type of
encryption to use. Supported options are:
<code>S3</code>, <code>KMS</code> and <code>customer</code>. See AWS
documentation for Server-Side Encryption (SSE) for details on these
options.<br>
Leave blank to use unencrypted uploads.<br>
If set to <code>KMS</code>, the <code>aws.sse.kms.key</code> property
specifies the id of the key to use. Leave unset to use the default AWS
key.<br>
If set to <code>customer</code>, the <code>aws.sse.customer.key</code>
property must be set to the base64 encoded customer key to use.
</p>
@author Liam Stewart (liam.stewart@gmail.com)
|
getCredentials
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
Apache-2.0
|
public Handle<?> upload(LogFilePath localPath) throws Exception {
String s3Bucket = mConfig.getS3Bucket();
String curS3Path = s3Path;
String s3Key;
File localFile = new File(localPath.getLogFilePath());
if (FileUtil.s3PathPrefixIsAltered(localPath.withPrefix(curS3Path).getLogFilePath(), mConfig)) {
curS3Path = FileUtil.getS3AlternativePathPrefix(mConfig);
LOG.info("Will upload file {} to alternative s3 path s3://{}/{}", localFile, s3Bucket, curS3Path);
}
if (mConfig.getS3MD5HashPrefix()) {
// add MD5 hash to the prefix to have proper partitioning of the secor logs on s3
String md5Hash = FileUtil.getMd5Hash(localPath.getTopic(), localPath.getPartitions());
s3Key = localPath.withPrefix(md5Hash + "/" + curS3Path).getLogFilePath();
}
else {
s3Key = localPath.withPrefix(curS3Path).getLogFilePath();
}
// make upload request, taking into account configured options for encryption
PutObjectRequest uploadRequest = new PutObjectRequest(s3Bucket, s3Key, localFile);
if (!mConfig.getAwsSseType().isEmpty()) {
if (S3.equals(mConfig.getAwsSseType())) {
LOG.info("uploading file {} to s3://{}/{} with S3-managed encryption", localFile, s3Bucket, s3Key);
enableS3Encryption(uploadRequest);
} else if (KMS.equals(mConfig.getAwsSseType())) {
LOG.info("uploading file {} to s3://{}/{} using KMS based encryption", localFile, s3Bucket, s3Key);
enableKmsEncryption(uploadRequest);
} else if (CUSTOMER.equals(mConfig.getAwsSseType())) {
LOG.info("uploading file {} to s3://{}/{} using customer key encryption", localFile, s3Bucket, s3Key);
enableCustomerEncryption(uploadRequest);
} else {
// bad option
throw new IllegalArgumentException(mConfig.getAwsSseType() + "is not a suitable type for AWS SSE encryption");
}
} else {
LOG.info("uploading file {} to s3://{}/{} with no encryption", localFile, s3Bucket, s3Key);
}
Upload upload = mManager.upload(uploadRequest);
return new S3UploadHandle(upload);
}
|
Manages uploads to S3 using the TransferManager class from the AWS
SDK.
<p>
Set the <code>aws.sse.type</code> property to specify the type of
encryption to use. Supported options are:
<code>S3</code>, <code>KMS</code> and <code>customer</code>. See AWS
documentation for Server-Side Encryption (SSE) for details on these
options.<br>
Leave blank to use unencrypted uploads.<br>
If set to <code>KMS</code>, the <code>aws.sse.kms.key</code> property
specifies the id of the key to use. Leave unset to use the default AWS
key.<br>
If set to <code>customer</code>, the <code>aws.sse.customer.key</code>
property must be set to the base64 encoded customer key to use.
</p>
@author Liam Stewart (liam.stewart@gmail.com)
|
upload
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
Apache-2.0
|
private void enableCustomerEncryption(PutObjectRequest uploadRequest) {
SSECustomerKey sseKey = new SSECustomerKey(mConfig.getAwsSseCustomerKey());
uploadRequest.withSSECustomerKey(sseKey);
}
|
Manages uploads to S3 using the TransferManager class from the AWS
SDK.
<p>
Set the <code>aws.sse.type</code> property to specify the type of
encryption to use. Supported options are:
<code>S3</code>, <code>KMS</code> and <code>customer</code>. See AWS
documentation for Server-Side Encryption (SSE) for details on these
options.<br>
Leave blank to use unencrypted uploads.<br>
If set to <code>KMS</code>, the <code>aws.sse.kms.key</code> property
specifies the id of the key to use. Leave unset to use the default AWS
key.<br>
If set to <code>customer</code>, the <code>aws.sse.customer.key</code>
property must be set to the base64 encoded customer key to use.
</p>
@author Liam Stewart (liam.stewart@gmail.com)
|
enableCustomerEncryption
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
Apache-2.0
|
private void enableKmsEncryption(PutObjectRequest uploadRequest) {
String keyId = mConfig.getAwsSseKmsKey();
if (!keyId.isEmpty()) {
uploadRequest.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(keyId));
} else {
uploadRequest.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams());
}
}
|
Manages uploads to S3 using the TransferManager class from the AWS
SDK.
<p>
Set the <code>aws.sse.type</code> property to specify the type of
encryption to use. Supported options are:
<code>S3</code>, <code>KMS</code> and <code>customer</code>. See AWS
documentation for Server-Side Encryption (SSE) for details on these
options.<br>
Leave blank to use unencrypted uploads.<br>
If set to <code>KMS</code>, the <code>aws.sse.kms.key</code> property
specifies the id of the key to use. Leave unset to use the default AWS
key.<br>
If set to <code>customer</code>, the <code>aws.sse.customer.key</code>
property must be set to the base64 encoded customer key to use.
</p>
@author Liam Stewart (liam.stewart@gmail.com)
|
enableKmsEncryption
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
Apache-2.0
|
private void enableS3Encryption(PutObjectRequest uploadRequest) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
uploadRequest.setMetadata(objectMetadata);
}
|
Manages uploads to S3 using the TransferManager class from the AWS
SDK.
<p>
Set the <code>aws.sse.type</code> property to specify the type of
encryption to use. Supported options are:
<code>S3</code>, <code>KMS</code> and <code>customer</code>. See AWS
documentation for Server-Side Encryption (SSE) for details on these
options.<br>
Leave blank to use unencrypted uploads.<br>
If set to <code>KMS</code>, the <code>aws.sse.kms.key</code> property
specifies the id of the key to use. Leave unset to use the default AWS
key.<br>
If set to <code>customer</code>, the <code>aws.sse.customer.key</code>
property must be set to the base64 encoded customer key to use.
</p>
@author Liam Stewart (liam.stewart@gmail.com)
|
enableS3Encryption
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/uploader/S3UploadManager.java
|
Apache-2.0
|
public void init(SecorConfig config, OffsetTracker offsetTracker, FileRegistry fileRegistry,
UploadManager uploadManager, MessageReader messageReader, MetricCollector metricCollector,
DeterministicUploadPolicyTracker deterministicUploadPolicyTracker) {
init(config, offsetTracker, fileRegistry, uploadManager, messageReader,
new ZookeeperConnector(config), metricCollector, deterministicUploadPolicyTracker);
}
|
Init the Uploader with its dependent objects.
@param config Secor configuration
@param offsetTracker Tracker of the current offset of topics partitions
@param fileRegistry Registry of log files on a per-topic and per-partition basis
@param uploadManager Manager of the physical upload of log files to the remote repository
@param messageReader messageReader
@param metricCollector component that ingest metrics into monitoring system
@param deterministicUploadPolicyTracker deterministicUploadPolicyTracker
|
init
|
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 void init(SecorConfig config, OffsetTracker offsetTracker, FileRegistry fileRegistry,
UploadManager uploadManager, MessageReader messageReader,
ZookeeperConnector zookeeperConnector, MetricCollector metricCollector,
DeterministicUploadPolicyTracker deterministicUploadPolicyTracker) {
mConfig = config;
mOffsetTracker = offsetTracker;
mFileRegistry = fileRegistry;
mUploadManager = uploadManager;
mMessageReader = messageReader;
mZookeeperConnector = zookeeperConnector;
mTopicFilter = mConfig.getKafkaTopicUploadAtMinuteMarkFilter();
mMetricCollector = metricCollector;
mDeterministicUploadPolicyTracker = deterministicUploadPolicyTracker;
if (mConfig.getOffsetsStorage().equals(SecorConstants.KAFKA_OFFSETS_STORAGE_KAFKA)) {
isOffsetsStorageKafka = true;
}
mUploadLastSeenOffset = mConfig.getUploadLastSeenOffset();
if (mConfig.getOffsetsStorage().equals(SecorConstants.KAFKA_OFFSETS_STORAGE_ZK) || mConfig.getDualCommitEnabled().equals("true")) {
isOffsetsStorageZookeeper = true;
}
}
|
Init the Uploader with its dependent objects.
@param config Secor configuration
@param offsetTracker Tracker of the current offset of topics partitions
@param fileRegistry Registry of log files on a per-topic and per-partition basis
@param uploadManager Manager of the physical upload of log files to the remote repository
@param messageReader messageReader
@param metricCollector component that ingest metrics into monitoring system
@param deterministicUploadPolicyTracker deterministicUploadPolicyTracker
|
init
|
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
|
protected void uploadFiles(TopicPartition topicPartition) throws Exception {
LOG.debug("Uploading for: " + topicPartition);
long committedOffsetCount = mOffsetTracker.getTrueCommittedOffsetCount(topicPartition);
long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition);
String stripped = StringUtils.strip(mConfig.getZookeeperPath(), "/");
final String lockPath = Joiner.on("/").skipNulls().join(
"",
stripped.isEmpty() ? null : stripped,
"secor",
"locks",
topicPartition.getTopic(),
topicPartition.getPartition());
mZookeeperConnector.lock(lockPath);
try {
// Check if the committed offset has changed.
long remoteComittedOffsetCount = getRemoteComittedOffsetCount(topicPartition);
if (remoteComittedOffsetCount == committedOffsetCount) {
//This is probably not possible in Kafka without zookeeper
if (mUploadLastSeenOffset && isOffsetsStorageZookeeper) {
long zkLastSeenOffset = mZookeeperConnector.getLastSeenOffsetCount(topicPartition);
// If the in-memory lastSeenOffset is less than ZK's, this means there was a failed
// attempt uploading for this topic partition and we already have some files uploaded
// on S3, e.g.
// s3n://topic/partition/day/hour=0/offset1
// s3n://topic/partition/day/hour=1/offset1
// Since our in-memory accumulated files (offsets) is less than what's on ZK, we
// might have less files to upload, e.g.
// localfs://topic/partition/day/hour=0/offset1
// If we continue uploading, we will upload this file:
// s3n://topic/partition/day/hour=0/offset1
// But the next file to be uploaded will become:
// s3n://topic/partition/day/hour=1/offset2
// So we will end up with 2 different files for hour=1/
// We should wait a bit longer to have at least getting to the same offset as ZK's
//
// Note We use offset + 1 throughout secor when we persist to ZK
if (lastSeenOffset + 1 < zkLastSeenOffset) {
LOG.warn("TP {}, ZK lastSeenOffset {}, in-memory lastSeenOffset {}, skip uploading this time",
topicPartition, zkLastSeenOffset, lastSeenOffset + 1);
mMetricCollector.increment("uploader.offset_delays", topicPartition.getTopic());
}
LOG.info("Setting lastSeenOffset for {} with {}", topicPartition, lastSeenOffset + 1);
mZookeeperConnector.setLastSeenOffsetCount(topicPartition, lastSeenOffset + 1);
}
LOG.info("uploading topic {} partition {}", topicPartition.getTopic(), topicPartition.getPartition());
// Deleting writers closes their streams flushing all pending data to the disk.
mFileRegistry.deleteWriters(topicPartition);
Collection<LogFilePath> paths = mFileRegistry.getPaths(topicPartition);
List<Handle<?>> uploadHandles = new ArrayList<Handle<?>>();
for (LogFilePath path : paths) {
uploadHandles.add(mUploadManager.upload(path));
}
for (Handle<?> uploadHandle : uploadHandles) {
try {
uploadHandle.get();
} catch (Exception ex) {
mMetricCollector.increment("uploader.upload.failures", topicPartition.getTopic());
throw ex;
}
}
mFileRegistry.deleteTopicPartition(topicPartition);
if (mDeterministicUploadPolicyTracker != null) {
mDeterministicUploadPolicyTracker.reset(topicPartition);
}
mOffsetTracker.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1);
if (isOffsetsStorageKafka) {
mMessageReader.commit(topicPartition, lastSeenOffset + 1);
}
if (isOffsetsStorageZookeeper) {
mZookeeperConnector.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1);
}
mMetricCollector.increment("uploader.file_uploads.count", paths.size(), topicPartition.getTopic());
} else {
LOG.warn("Zookeeper committed offset didn't match for topic {} partition {}: {} vs {}",
topicPartition.getTopic(), topicPartition.getTopic(), remoteComittedOffsetCount,
committedOffsetCount);
mMetricCollector.increment("uploader.offset_mismatches", topicPartition.getTopic());
}
} finally {
mZookeeperConnector.unlock(lockPath);
}
}
|
Init the Uploader with its dependent objects.
@param config Secor configuration
@param offsetTracker Tracker of the current offset of topics partitions
@param fileRegistry Registry of log files on a per-topic and per-partition basis
@param uploadManager Manager of the physical upload of log files to the remote repository
@param messageReader messageReader
@param metricCollector component that ingest metrics into monitoring system
@param deterministicUploadPolicyTracker deterministicUploadPolicyTracker
|
uploadFiles
|
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
|
protected FileReader createReader(LogFilePath srcPath, CompressionCodec codec) throws Exception {
return ReflectionUtil.createFileReader(
mConfig.getFileReaderWriterFactory(),
srcPath,
codec,
mConfig
);
}
|
This method is intended to be overwritten in tests.
@param srcPath source Path
@param codec compression codec
@return FileReader created file reader
@throws Exception on error
|
createReader
|
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
|
private void trim(LogFilePath srcPath, long startOffset) throws Exception {
final TopicPartition topicPartition = new TopicPartition(srcPath.getTopic(), srcPath.getKafkaPartition());
if (startOffset == srcPath.getOffset()) {
// If *all* the files had the right offset already, trimFiles would have returned
// before resetting the tracker. If just some do, we don't want to rewrite files in place
// (it's probably safe but let's not stress it), but this shouldn't happen anyway.
throw new RuntimeException("Some LogFilePath has unchanged offset, but they don't all? " + srcPath);
}
FileReader reader = null;
FileWriter writer = null;
LogFilePath dstPath = null;
int copiedMessages = 0;
// Deleting the writer closes its stream flushing all pending data to the disk.
mFileRegistry.deleteWriter(srcPath);
try {
CompressionCodec codec = null;
if (mConfig.getCompressionCodec() != null && !mConfig.getCompressionCodec().isEmpty()) {
codec = CompressionUtil.createCompressionCodec(mConfig.getCompressionCodec());
}
reader = createReader(srcPath, codec);
KeyValue keyVal;
while ((keyVal = reader.next()) != null) {
if (keyVal.getOffset() >= startOffset) {
if (writer == null) {
String localPrefix = mConfig.getLocalPath() + '/' +
IdUtil.getLocalMessageDir();
dstPath = new LogFilePath(localPrefix, srcPath.getTopic(),
srcPath.getPartitions(), srcPath.getGeneration(),
srcPath.getKafkaPartition(), startOffset,
srcPath.getExtension());
writer = mFileRegistry.getOrCreateWriter(dstPath,
codec);
}
writer.write(keyVal);
if (mDeterministicUploadPolicyTracker != null) {
mDeterministicUploadPolicyTracker.track(topicPartition, keyVal);
}
copiedMessages++;
}
}
} finally {
if (reader != null) {
reader.close();
}
}
mFileRegistry.deletePath(srcPath);
if (dstPath == null) {
LOG.info("removed file {}", srcPath.getLogFilePath());
} else {
LOG.info("trimmed {} messages from {} to {} with start offset {}",
copiedMessages, srcPath.getLogFilePath(), dstPath.getLogFilePath(), startOffset);
}
}
|
This method is intended to be overwritten in tests.
@param srcPath source Path
@param codec compression codec
@return FileReader created file reader
@throws Exception on error
|
trim
|
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
|
protected void trimFiles(TopicPartition topicPartition, long startOffset) throws Exception {
Collection<LogFilePath> paths = mFileRegistry.getPaths(topicPartition);
if (paths.stream().allMatch(srcPath -> srcPath.getOffset() == startOffset)) {
// We thought we needed to trim, but we were wrong: we already had started at the right offset.
// (Probably because we don't initialize the offset from ZK on startup.)
return;
}
if (mDeterministicUploadPolicyTracker != null) {
mDeterministicUploadPolicyTracker.reset(topicPartition);
}
for (LogFilePath path : paths) {
trim(path, startOffset);
}
}
|
This method is intended to be overwritten in tests.
@param srcPath source Path
@param codec compression codec
@return FileReader created file reader
@throws Exception on error
|
trimFiles
|
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
|
private boolean isRequiredToUploadAtTime(TopicPartition topicPartition) throws Exception{
final String topic = topicPartition.getTopic();
if (mTopicFilter == null || mTopicFilter.isEmpty()){
return false;
}
if (topic.matches(mTopicFilter)){
if (DateTime.now().minuteOfHour().get() == mConfig.getUploadMinuteMark()){
return true;
}
}
return false;
}
|
If the topic is in the list of topics to upload at a specific time. For example at a minute mark.
@param topicPartition
@return
@throws Exception
|
isRequiredToUploadAtTime
|
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
|
protected void checkTopicPartition(TopicPartition topicPartition, boolean forceUpload) throws Exception {
boolean shouldUpload;
if (mDeterministicUploadPolicyTracker != null) {
shouldUpload = mDeterministicUploadPolicyTracker.shouldUpload(topicPartition);
} else {
final long size = mFileRegistry.getSize(topicPartition);
final long modificationAgeSec = mFileRegistry.getModificationAgeSec(topicPartition);
final int fileCount = mFileRegistry.getActiveFileCount();
LOG.debug("size: " + size + " modificationAge: " + modificationAgeSec);
shouldUpload = forceUpload ||
activeFileCountExceeded(fileCount) ||
size >= mConfig.getMaxFileSizeBytes() ||
modificationAgeSec >= mConfig.getMaxFileAgeSeconds() ||
isRequiredToUploadAtTime(topicPartition);
}
if (shouldUpload) {
long newOffsetCount = getRemoteComittedOffsetCount(topicPartition);
long oldOffsetCount = mOffsetTracker.setCommittedOffsetCount(topicPartition,
newOffsetCount);
long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition);
if (oldOffsetCount == newOffsetCount) {
uploadFiles(topicPartition);
} else if (newOffsetCount > lastSeenOffset) { // && oldOffset < newOffset
LOG.debug("last seen offset {} is lower than committed offset count {}. Deleting files in topic {} partition {}",
lastSeenOffset, newOffsetCount, topicPartition.getTopic(), topicPartition.getPartition());
mMetricCollector.increment("uploader.partition_deletes", topicPartition.getTopic());
// There was a rebalancing event and someone committed an offset beyond that of the
// current message. We need to delete the local file.
mFileRegistry.deleteTopicPartition(topicPartition);
if (mDeterministicUploadPolicyTracker != null) {
mDeterministicUploadPolicyTracker.reset(topicPartition);
}
} else { // oldOffsetCount < newOffsetCount <= lastSeenOffset
LOG.debug("previous committed offset count {} is lower than committed offset {} is lower than or equal to last seen offset {}. " +
"Trimming files in topic {} partition {}",
oldOffsetCount, newOffsetCount, lastSeenOffset, topicPartition.getTopic(), topicPartition.getPartition());
mMetricCollector.increment("uploader.partition_trims", topicPartition.getTopic());
// There was a rebalancing event and someone committed an offset lower than that
// of the current message. We need to trim local files.
trimFiles(topicPartition, newOffsetCount);
// We might still be at the right place to upload. (In fact, we always trim the first time
// we hit the upload condition because oldOffsetCount starts at -1, but this is usually a no-op trim.)
// Check again! This is especially important if this was an "upload in graceful shutdown".
checkTopicPartition(topicPartition, forceUpload);
}
}
}
|
If the topic is in the list of topics to upload at a specific time. For example at a minute mark.
@param topicPartition
@return
@throws Exception
|
checkTopicPartition
|
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
|
private boolean activeFileCountExceeded(int fileCount) {
return mConfig.getMaxActiveFiles() > -1 && fileCount > mConfig.getMaxActiveFiles();
}
|
If the topic is in the list of topics to upload at a specific time. For example at a minute mark.
@param topicPartition
@return
@throws Exception
|
activeFileCountExceeded
|
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
|
private long getRemoteComittedOffsetCount(TopicPartition topicPartition) throws Exception {
//If storing offsets in Zookeeper is enabled we are going to always use those offsets.
if (isOffsetsStorageZookeeper) {
return mZookeeperConnector.getCommittedOffsetCount(topicPartition);
} else {
return mMessageReader.getCommitedOffsetCount(topicPartition);
}
}
|
If the topic is in the list of topics to upload at a specific time. For example at a minute mark.
@param topicPartition
@return
@throws Exception
|
getRemoteComittedOffsetCount
|
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 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 int getCount() {
return count;
}
|
@author Luke Sun (luke.skywalker.sun@gmail.com)
|
getCount
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
Apache-2.0
|
public long getLastBackOff() {
return lastBackOff;
}
|
@author Luke Sun (luke.skywalker.sun@gmail.com)
|
getLastBackOff
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
Apache-2.0
|
public boolean isBackOff() {
count++;
if (count > lastBackOff) {
try {
lastBackOff = backOff.nextBackOffMillis();
} catch (IOException e) {
// we don't care IOException here
}
return false;
} else {
return true;
}
}
|
@author Luke Sun (luke.skywalker.sun@gmail.com)
|
isBackOff
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
Apache-2.0
|
@Override
public void reset() {
interval = 0;
}
|
@author Luke Sun (luke.skywalker.sun@gmail.com)
|
reset
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
Apache-2.0
|
@Override
public long nextBackOffMillis() {
if (interval < max) {
interval += inc;
if (interval < 0) {
interval = max;
}
return interval;
} else {
return max;
}
}
|
@author Luke Sun (luke.skywalker.sun@gmail.com)
|
nextBackOffMillis
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/BackOffUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/BackOffUtil.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 static void configure(SecorConfig config) {
if (config != null) {
if (config.getCloudService().equals("Swift")) {
mConf.set("fs.swift.impl", "org.apache.hadoop.fs.swift.snative.SwiftNativeFileSystem");
mConf.set("fs.swift.service.GENERICPROJECT.auth.url", config.getSwiftAuthUrl());
mConf.set("fs.swift.service.GENERICPROJECT.username", config.getSwiftUsername());
mConf.set("fs.swift.service.GENERICPROJECT.tenant", config.getSwiftTenant());
mConf.set("fs.swift.service.GENERICPROJECT.region", config.getSwiftRegion());
mConf.set("fs.swift.service.GENERICPROJECT.http.port", config.getSwiftPort());
mConf.set("fs.swift.service.GENERICPROJECT.use.get.auth", config.getSwiftGetAuth());
mConf.set("fs.swift.service.GENERICPROJECT.public", config.getSwiftPublic());
if (config.getSwiftGetAuth().equals("true")) {
mConf.set("fs.swift.service.GENERICPROJECT.apikey", config.getSwiftApiKey());
} else {
mConf.set("fs.swift.service.GENERICPROJECT.password", config.getSwiftPassword());
}
} else if (config.getCloudService().equals("S3")) {
if (config.getAwsAccessKey().isEmpty() != config.getAwsSecretKey().isEmpty()) {
throw new IllegalArgumentException(
"Must specify both aws.access.key and aws.secret.key or neither.");
}
if (!config.getAwsAccessKey().isEmpty()) {
mConf.set(Constants.ACCESS_KEY, config.getAwsAccessKey());
mConf.set(Constants.SECRET_KEY, config.getAwsSecretKey());
mConf.set("fs.s3n.awsAccessKeyId", config.getAwsAccessKey());
mConf.set("fs.s3n.awsSecretAccessKey", config.getAwsSecretKey());
}
}
}
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
configure
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static FileSystem getFileSystem(String path) throws IOException {
return FileSystem.get(URI.create(path), mConf);
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
getFileSystem
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static boolean s3PathPrefixIsAltered(String logFileName, SecorConfig config)
throws Exception {
Date logDate = null;
if (config.getS3AlterPathDate() != null && !config.getS3AlterPathDate().isEmpty()) {
Date s3AlterPathDate = new SimpleDateFormat("yyyy-MM-dd").parse(config.getS3AlterPathDate());
// logFileName contains the log path, e.g. raw_logs/secor_topic/dt=2016-04-20/3_0_0000000000000292564
Matcher dateMatcher = datePattern.matcher(logFileName);
if (dateMatcher.find()) {
logDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateMatcher.group(1));
}
if (logDate == null) {
throw new Exception("Did not find a date in the format yyyy-MM-dd in " + logFileName);
}
if (!s3AlterPathDate.after(logDate)) {
return true;
}
}
return false;
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
s3PathPrefixIsAltered
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String getS3AlternativePathPrefix(SecorConfig config) {
return config.getS3AlternativePath();
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
getS3AlternativePathPrefix
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String getS3AlternativePrefix(SecorConfig config) {
return config.getS3FileSystem() + "://" + config.getS3Bucket() + "/" + config.getS3AlternativePath();
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
getS3AlternativePrefix
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String getPrefix(String topic, SecorConfig config) throws IOException {
String prefix = null;
if (config.getCloudService().equals("Swift")) {
String container = null;
if (config.getSeparateContainersForTopics()) {
if (!exists("swift://" + topic + ".GENERICPROJECT")){
String containerUrl = "swift://" + topic + ".GENERICPROJECT";
Path containerPath = new Path(containerUrl);
getFileSystem(containerUrl).create(containerPath).close();
}
container = topic;
} else {
container = config.getSwiftContainer();
}
prefix = "swift://" + container + ".GENERICPROJECT/" + config.getSwiftPath();
} else if (config.getCloudService().equals("S3")) {
prefix = config.getS3Prefix();
} else if (config.getCloudService().equals("GS")) {
prefix = "gs://" + config.getGsBucket() + "/" + config.getGsPath();
} else if (config.getCloudService().equals("Azure")) {
prefix = "azure://" + config.getAzureContainer() + "/" + config.getAzurePath();
}
return prefix;
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
getPrefix
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String[] list(String path) throws IOException {
FileSystem fs = getFileSystem(path);
Path fsPath = new Path(path);
ArrayList<String> paths = new ArrayList<String>();
FileStatus[] statuses = fs.listStatus(fsPath);
if (statuses != null) {
for (FileStatus status : statuses) {
Path statusPath = status.getPath();
if (path.startsWith("s3://") || path.startsWith("s3n://") || path.startsWith("s3a://") ||
path.startsWith("swift://") || path.startsWith("gs://")) {
paths.add(statusPath.toUri().toString());
} else {
paths.add(statusPath.toUri().getPath());
}
}
}
return paths.toArray(new String[] {});
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
list
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String[] listRecursively(String path) throws IOException {
ArrayList<String> paths = new ArrayList<String>();
String[] directPaths = list(path);
for (String directPath : directPaths) {
if (directPath.equals(path)) {
assert directPaths.length == 1: Integer.toString(directPaths.length) + " == 1";
paths.add(directPath);
} else {
String[] recursivePaths = listRecursively(directPath);
paths.addAll(Arrays.asList(recursivePaths));
}
}
return paths.toArray(new String[] {});
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
listRecursively
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static boolean exists(String path) throws IOException {
FileSystem fs = getFileSystem(path);
Path fsPath = new Path(path);
return fs.exists(fsPath);
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
exists
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static void delete(String path) throws IOException {
if (exists(path)) {
Path fsPath = new Path(path);
boolean success = getFileSystem(path).delete(fsPath, true); // recursive
if (!success) {
throw new IOException("Failed to delete " + path);
}
}
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
delete
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static void moveToCloud(String srcLocalPath, String dstCloudPath) throws IOException {
Path srcPath = new Path(srcLocalPath);
Path dstPath = new Path(dstCloudPath);
getFileSystem(dstCloudPath).moveFromLocalFile(srcPath, dstPath);
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
moveToCloud
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static void touch(String path) throws IOException {
FileSystem fs = getFileSystem(path);
Path fsPath = new Path(path);
fs.create(fsPath).close();
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
touch
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static long getModificationTimeMsRecursive(String path) throws IOException {
FileSystem fs = getFileSystem(path);
Path fsPath = new Path(path);
FileStatus status = fs.getFileStatus(fsPath);
long modificationTime = status.getModificationTime();
FileStatus[] statuses = fs.listStatus(fsPath);
if (statuses != null) {
for (FileStatus fileStatus : statuses) {
Path statusPath = fileStatus.getPath();
String stringPath;
if (path.startsWith("s3://") || path.startsWith("s3n://") || path.startsWith("s3a://") ||
path.startsWith("swift://") || path.startsWith("gs://")) {
stringPath = statusPath.toUri().toString();
} else {
stringPath = statusPath.toUri().getPath();
}
if (!stringPath.equals(path)) {
modificationTime = Math.max(modificationTime,
getModificationTimeMsRecursive(stringPath));
}
}
}
return modificationTime;
}
|
File util implements utilities for interactions with the file system.
@author Pawel Garbacki (pawel@pinterest.com)
|
getModificationTimeMsRecursive
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String getMd5Hash(String topic, String[] partitions) {
ArrayList<String> elements = new ArrayList<String>();
elements.add(topic);
for (String partition : partitions) {
elements.add(partition);
}
String pathPrefix = StringUtils.join(elements, "/");
try {
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] md5Bytes = messageDigest.digest(pathPrefix.getBytes("UTF-8"));
return getHexEncode(md5Bytes).substring(0, 4);
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
LOG.error(e.getMessage());
}
return "";
}
|
Generate MD5 hash of topic and partitions. And extract first 4 characters of the MD5 hash.
@param topic topic name
@param partitions partitions
@return md5 hash
|
getMd5Hash
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
private static String getHexEncode(byte[] bytes) {
final char[] chars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; ++i) {
final int cx = i * 2;
final byte b = bytes[i];
chars[cx] = m_digits[(b & 0xf0) >> 4];
chars[cx + 1] = m_digits[(b & 0x0f)];
}
return new String(chars);
}
|
Generate MD5 hash of topic and partitions. And extract first 4 characters of the MD5 hash.
@param topic topic name
@param partitions partitions
@return md5 hash
|
getHexEncode
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/FileUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/FileUtil.java
|
Apache-2.0
|
public static String getConsumerId() throws UnknownHostException {
String hostname = InetAddress.getLocalHost().getHostName();
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
long threadId = Thread.currentThread().getId();
return hostname + "_" + pid + "_" + threadId;
}
|
Utilities related to identifiers.
@author Pawel Garbacki (pawel@pinterest.com)
|
getConsumerId
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/IdUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/IdUtil.java
|
Apache-2.0
|
public static String getLocalMessageDir() throws UnknownHostException {
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
long threadId = Thread.currentThread().getId();
return pid + "_" + threadId;
}
|
Utilities related to identifiers.
@author Pawel Garbacki (pawel@pinterest.com)
|
getLocalMessageDir
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/IdUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/IdUtil.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 Message decodeProtobufOrJsonMessage(String topic, byte[] payload) {
try {
if (shouldDecodeFromJsonMessage(topic)) {
return decodeJsonMessage(topic, payload);
}
} catch (InvalidProtocolBufferException e) {
//When trimming files, the Uploader will read and then decode messages in protobuf format
LOG.debug("Unable to translate JSON string {} to protobuf message", new String(payload, Charsets.UTF_8));
}
return decodeProtobufMessage(topic, payload);
}
|
Decodes protobuf message
If the secor.topic.message.format property is set to "JSON" for "topic" assume "payload" is JSON
@param topic
Kafka topic name
@param payload
Byte array containing encoded protobuf or JSON message
@return protobuf message instance
@throws RuntimeException
when there's problem decoding protobuf or JSON message
|
decodeProtobufOrJsonMessage
|
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
|
private boolean shouldDecodeFromJsonMessage(String topic){
if (StringUtils.isNotEmpty(messageFormatForAll) && StringUtils.equalsIgnoreCase(messageFormatForAll, JSON)) {
return true;
} else if (StringUtils.equalsIgnoreCase(messageFormatByTopic.getOrDefault(topic, ""), JSON)) {
return true;
}
return false;
}
|
Decodes protobuf message
If the secor.topic.message.format property is set to "JSON" for "topic" assume "payload" is JSON
@param topic
Kafka topic name
@param payload
Byte array containing encoded protobuf or JSON message
@return protobuf message instance
@throws RuntimeException
when there's problem decoding protobuf or JSON message
|
shouldDecodeFromJsonMessage
|
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
|
public static void setLabel(String name, String value) {
long threadId = Thread.currentThread().getId();
name += "." + threadId;
Stats.setLabel(name, value);
}
|
Utilities to interact with Ostrich stats exporter.
@author Pawel Garbacki (pawel@pinterest.com)
|
setLabel
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/StatsUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/StatsUtil.java
|
Apache-2.0
|
public static void clearLabel(String name) {
long threadId = Thread.currentThread().getId();
name += "." + threadId;
Stats.clearLabel(name);
}
|
Utilities to interact with Ostrich stats exporter.
@author Pawel Garbacki (pawel@pinterest.com)
|
clearLabel
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/StatsUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/StatsUtil.java
|
Apache-2.0
|
@SuppressWarnings("rawtypes")
public Class<? extends TBase> getMessageClass(String topic) {
return allTopics ? messageClassForAll : messageClassByTopic.get(topic);
}
|
Returns configured thrift message class for the given Kafka topic
@param topic
Kafka topic
@return thrift 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/ThriftUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ThriftUtil.java
|
Apache-2.0
|
@SuppressWarnings("rawtypes")
public TBase decodeMessage(String topic, byte[] payload)
throws InstantiationException, IllegalAccessException, TException {
TDeserializer serializer = new TDeserializer(messageProtocolFactory);
TBase result = this.getMessageClass(topic).newInstance();
serializer.deserialize(result, payload);
return result;
}
|
Returns configured thrift message class for the given Kafka topic
@param topic
Kafka topic
@return thrift message class used by this utility instance, or
<code>null</code> in case valid class couldn't be found in the
configuration.
|
decodeMessage
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/ThriftUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ThriftUtil.java
|
Apache-2.0
|
@SuppressWarnings("rawtypes")
public byte[] encodeMessage(TBase object) throws InstantiationException,
IllegalAccessException, TException {
TSerializer serializer = new TSerializer(messageProtocolFactory);
return serializer.serialize(object);
}
|
Returns configured thrift message class for the given Kafka topic
@param topic
Kafka topic
@return thrift message class used by this utility instance, or
<code>null</code> in case valid class couldn't be found in the
configuration.
|
encodeMessage
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/ThriftUtil.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/ThriftUtil.java
|
Apache-2.0
|
public static void processRow(JSONWriter writer, VectorizedRowBatch batch,
TypeDescription schema, int row) throws JSONException {
if (schema.getCategory() == TypeDescription.Category.STRUCT) {
List<TypeDescription> fieldTypes = schema.getChildren();
List<String> fieldNames = schema.getFieldNames();
writer.object();
for (int c = 0; c < batch.cols.length; ++c) {
writer.key(fieldNames.get(c));
setValue(writer, batch.cols[c], fieldTypes.get(c), row);
}
writer.endObject();
} else {
setValue(writer, batch.cols[0], schema, row);
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
processRow
|
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
|
static void setValue(JSONWriter writer, ColumnVector vector,
TypeDescription schema, int row) throws JSONException {
if (vector.isRepeating) {
row = 0;
}
if (vector.noNulls || !vector.isNull[row]) {
switch (schema.getCategory()) {
case BOOLEAN:
writer.value(((LongColumnVector) vector).vector[row] != 0);
break;
case BYTE:
case SHORT:
case INT:
case LONG:
writer.value(((LongColumnVector) vector).vector[row]);
break;
case FLOAT:
case DOUBLE:
writer.value(((DoubleColumnVector) vector).vector[row]);
break;
case STRING:
case CHAR:
case VARCHAR:
writer.value(((BytesColumnVector) vector).toString(row));
break;
case DECIMAL:
writer.value(((DecimalColumnVector) vector).vector[row]
.toString());
break;
case DATE:
writer.value(new DateWritable(
(int) ((LongColumnVector) vector).vector[row])
.toString());
break;
case TIMESTAMP:
writer.value(((TimestampColumnVector) vector)
.asScratchTimestamp(row).toString());
break;
case LIST:
setList(writer, (ListColumnVector) vector, schema, row);
break;
case STRUCT:
setStruct(writer, (StructColumnVector) vector, schema, row);
break;
case UNION:
setUnion(writer, (UnionColumnVector) vector, schema, row);
break;
case BINARY:
// To prevent similar mistakes like the one described in https://github.com/pinterest/secor/pull/1018,
// it would be better to explicitly throw an exception here rather than ignore the incoming values,
// which causes silent failures in a later stage.
throw new UnsupportedOperationException();
case MAP:
setMap(writer, (MapColumnVector) vector, schema, row);
break;
default:
throw new IllegalArgumentException("Unknown type "
+ schema.toString());
}
} else {
writer.value(null);
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
setValue
|
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
|
private static void setList(JSONWriter writer, ListColumnVector vector,
TypeDescription schema, int row) throws JSONException {
writer.array();
int offset = (int) vector.offsets[row];
TypeDescription childType = schema.getChildren().get(0);
for (int i = 0; i < vector.lengths[row]; ++i) {
setValue(writer, vector.child, childType, offset + i);
}
writer.endArray();
}
|
@author Ashish (ashu.impetus@gmail.com)
|
setList
|
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
|
private static void setStruct(JSONWriter writer, StructColumnVector batch,
TypeDescription schema, int row) throws JSONException {
writer.object();
List<String> fieldNames = schema.getFieldNames();
List<TypeDescription> fieldTypes = schema.getChildren();
for (int i = 0; i < fieldTypes.size(); ++i) {
writer.key(fieldNames.get(i));
setValue(writer, batch.fields[i], fieldTypes.get(i), row);
}
writer.endObject();
}
|
@author Ashish (ashu.impetus@gmail.com)
|
setStruct
|
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
|
private static void setMap(JSONWriter writer, MapColumnVector vector,
TypeDescription schema, int row) throws JSONException {
writer.object();
List<TypeDescription> schemaChildren = schema.getChildren();
BytesColumnVector keyVector = (BytesColumnVector) vector.keys;
long length = vector.lengths[row];
long offset = vector.offsets[row];
for (int i = 0; i < length; i++) {
writer.key(keyVector.toString((int) offset + i));
setValue(writer, vector.values, schemaChildren.get(1), (int) offset + i);
}
writer.endObject();
}
|
@author Ashish (ashu.impetus@gmail.com)
|
setMap
|
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
|
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
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
LongColumnVector vector = (LongColumnVector) vect;
vector.vector[row] = value.getAsBoolean() ? 1 : 0;
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
LongColumnVector vector = (LongColumnVector) vect;
vector.vector[row] = value.getAsLong();
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
DoubleColumnVector vector = (DoubleColumnVector) vect;
vector.vector[row] = value.getAsDouble();
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
BytesColumnVector vector = (BytesColumnVector) vect;
byte[] bytes = value.getAsString().getBytes(
StandardCharsets.UTF_8);
vector.setRef(row, bytes, 0, bytes.length);
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
BytesColumnVector vector = (BytesColumnVector) vect;
String binStr = value.getAsString();
byte[] bytes = new byte[binStr.length() / 2];
for (int i = 0; i < bytes.length; ++i) {
bytes[i] = (byte) Integer.parseInt(
binStr.substring(i * 2, i * 2 + 2), 16);
}
vector.setRef(row, bytes, 0, bytes.length);
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
if (value.getAsJsonPrimitive().isString()) {
TimestampColumnVector vector = (TimestampColumnVector) vect;
vector.set(
row,
Timestamp.valueOf(value.getAsString().replaceAll(
"[TZ]", " ")));
} else if (value.getAsJsonPrimitive().isNumber()) {
TimestampColumnVector vector = (TimestampColumnVector) vect;
vector.set(
row,
new Timestamp(value.getAsLong()));
} else {
if (!back.isBackOff()) {
LOG.warn("Timestamp is neither string nor number: {}", value);
}
vect.noNulls = false;
vect.isNull[row] = true;
}
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
DecimalColumnVector vector = (DecimalColumnVector) vect;
vector.vector[row].set(HiveDecimal.create(value.getAsString()));
}
}
|
@author Ashish (ashu.impetus@gmail.com)
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
private JsonType getJsonType(TypeDescription.Category category) {
switch (category) {
case BOOLEAN:
return JsonType.BOOLEAN;
case BYTE:
case SHORT:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case DECIMAL:
return JsonType.NUMBER;
case CHAR:
case VARCHAR:
case STRING:
return JsonType.STRING;
default:
throw new UnsupportedOperationException();
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
getJsonType
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
private JsonType getJsonType(JsonPrimitive value) {
if (value.isBoolean()) {
return JsonType.BOOLEAN;
} else if (value.isNumber()) {
return JsonType.NUMBER;
} else if (value.isString()) {
return JsonType.STRING;
} else {
throw new UnsupportedOperationException();
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
getJsonType
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else if (value.isJsonPrimitive()) {
UnionColumnVector vector = (UnionColumnVector) vect;
JsonPrimitive primitive = value.getAsJsonPrimitive();
JsonType jsonType = getJsonType(primitive);
ConverterInfo converterInfo = childConverters.get(jsonType);
if (converterInfo == null) {
String message = String.format("Unable to infer type for '%s'", primitive);
throw new IllegalArgumentException(message);
}
int vectorIndex = converterInfo.getVectorIndex();
JsonConverter converter = converterInfo.getConverter();
vector.tags[row] = vectorIndex;
converter.convert(value, vector.fields[vectorIndex], row);
} else {
// It would be great to support non-primitive types in union type.
// Let's leave this for another PR in the future.
throw new UnsupportedOperationException();
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
StructColumnVector vector = (StructColumnVector) vect;
JsonObject obj = value.getAsJsonObject();
for (int c = 0; c < childrenConverters.length; ++c) {
JsonElement elem = obj.get(fieldNames.get(c));
childrenConverters[c].convert(elem, vector.fields[c], row);
}
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public void convert(JsonElement value, ColumnVector vect, int row) {
if (value == null || value.isJsonNull()) {
vect.noNulls = false;
vect.isNull[row] = true;
} else {
ListColumnVector vector = (ListColumnVector) vect;
JsonArray obj = value.getAsJsonArray();
vector.lengths[row] = obj.size();
vector.offsets[row] = vector.childCount;
vector.childCount += vector.lengths[row];
vector.child.ensureSize(vector.childCount, true);
for (int c = 0; c < obj.size(); ++c) {
childrenConverter.convert(obj.get(c), vector.child,
(int) vector.offsets[row] + c);
}
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
convert
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public static JsonConverter createConverter(TypeDescription schema) {
switch (schema.getCategory()) {
case BYTE:
case SHORT:
case INT:
case LONG:
return new LongColumnConverter();
case FLOAT:
case DOUBLE:
return new DoubleColumnConverter();
case CHAR:
case VARCHAR:
case STRING:
return new StringColumnConverter();
case DECIMAL:
return new DecimalColumnConverter();
case TIMESTAMP:
return new TimestampColumnConverter();
case BINARY:
return new BinaryColumnConverter();
case BOOLEAN:
return new BooleanColumnConverter();
case STRUCT:
return new StructColumnConverter(schema);
case LIST:
return new ListColumnConverter(schema);
case MAP:
return new MapColumnConverter(schema);
case UNION:
return new UnionColumnConverter(schema);
default:
throw new IllegalArgumentException("Unhandled type " + schema);
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
createConverter
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
Apache-2.0
|
public static void fillRow(int rowIndex, JsonConverter[] converters,
TypeDescription schema, VectorizedRowBatch batch, JsonObject data) {
List<String> fieldNames = schema.getFieldNames();
for (int c = 0; c < converters.length; ++c) {
JsonElement field = data.get(fieldNames.get(c));
if (field == null) {
batch.cols[c].noNulls = false;
batch.cols[c].isNull[rowIndex] = true;
} else {
converters[c].convert(field, batch.cols[c], rowIndex);
}
}
}
|
Union type in ORC is essentially a collection of two or more non-compatible types,
and it is represented by multiple child columns under UnionColumnVector.
Thus we need converters for each type.
|
fillRow
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/util/orc/VectorColumnFiller.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 void adjustOffset(Message message, boolean isLegacyConsumer) throws IOException {
TopicPartition topicPartition = new TopicPartition(message.getTopic(),
message.getKafkaPartition());
long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition);
//this validation logic is for duplicates removing as no rebalancing callbacks is incompatible with LegacyKafkaMessageIterator
if (isLegacyConsumer && message.getOffset() != lastSeenOffset + 1) {
StatsUtil.incr("secor.consumer_rebalance_count." + topicPartition.getTopic());
// There was a rebalancing event since we read the last message.
LOG.info("offset of message {} does not follow sequentially the last seen offset {}. " +
"Deleting files in topic {} partition {}",
message, lastSeenOffset, topicPartition.getTopic(), topicPartition.getPartition());
mFileRegistry.deleteTopicPartition(topicPartition);
if (mDeterministicUploadPolicyTracker != null) {
mDeterministicUploadPolicyTracker.reset(topicPartition);
}
}
mOffsetTracker.setLastSeenOffset(topicPartition, message.getOffset());
}
|
Message writer appends Kafka messages to local log files.
@author Pawel Garbacki (pawel@pinterest.com)
|
adjustOffset
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/writer/MessageWriter.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/writer/MessageWriter.java
|
Apache-2.0
|
public void write(ParsedMessage message) throws Exception {
TopicPartition topicPartition = new TopicPartition(message.getTopic(),
message.getKafkaPartition());
long offset = mOffsetTracker.getAdjustedCommittedOffsetCount(topicPartition);
LogFilePath path = new LogFilePath(mLocalPrefix, mGeneration, offset, message,
mFileExtension);
FileWriter writer = mFileRegistry.getOrCreateWriter(path, mCodec);
writer.write(new KeyValue(message.getOffset(), message.getKafkaKey(), message.getPayload(), message.getTimestamp(), message.getHeaders()));
LOG.debug("appended message {} to file {}. File length {}",
message, path, writer.getLength());
}
|
Message writer appends Kafka messages to local log files.
@author Pawel Garbacki (pawel@pinterest.com)
|
write
|
java
|
pinterest/secor
|
src/main/java/com/pinterest/secor/writer/MessageWriter.java
|
https://github.com/pinterest/secor/blob/master/src/main/java/com/pinterest/secor/writer/MessageWriter.java
|
Apache-2.0
|
public void setUp() throws Exception {
super.setUp();
PropertiesConfiguration properties = new PropertiesConfiguration();
properties.addProperty("secor.file.reader.writer.factory",
"com.pinterest.secor.io.impl.SequenceFileReaderWriterFactory");
properties.addProperty("secor.file.age.youngest", true);
SecorConfig secorConfig = new SecorConfig(properties);
mRegistry = new FileRegistry(secorConfig);
mLogFilePath = new LogFilePath("/some_parent_dir", PATH);
mTopicPartition = new TopicPartition("some_topic", 0);
mLogFilePathGz = new LogFilePath("/some_parent_dir", PATH_GZ);
}
|
FileRegistryTest tests the file registry logic.
@author Pawel Garbacki (pawel@pinterest.com)
|
setUp
|
java
|
pinterest/secor
|
src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
https://github.com/pinterest/secor/blob/master/src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
Apache-2.0
|
private FileWriter createWriter() throws Exception {
PowerMockito.mockStatic(FileUtil.class);
PowerMockito.mockStatic(ReflectionUtil.class);
FileWriter writer = Mockito.mock(FileWriter.class);
Mockito.when(
ReflectionUtil.createFileWriter(
Mockito.any(String.class),
Mockito.any(LogFilePath.class),
Mockito.any(CompressionCodec.class),
Mockito.any(SecorConfig.class)
))
.thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(123L);
FileWriter createdWriter = mRegistry.getOrCreateWriter(
mLogFilePath, new DefaultCodec());
assertTrue(createdWriter == writer);
return writer;
}
|
FileRegistryTest tests the file registry logic.
@author Pawel Garbacki (pawel@pinterest.com)
|
createWriter
|
java
|
pinterest/secor
|
src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
https://github.com/pinterest/secor/blob/master/src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
Apache-2.0
|
public void testGetOrCreateWriter() throws Exception {
createWriter();
// Call the method again. This time it should return an existing writer.
mRegistry.getOrCreateWriter(mLogFilePath, null);
// Verify that the method has been called exactly once (the default).
PowerMockito.verifyStatic(ReflectionUtil.class);
ReflectionUtil.createFileWriter(Mockito.any(String.class),
Mockito.any(LogFilePath.class),
Mockito.any(CompressionCodec.class),
Mockito.any(SecorConfig.class)
);
PowerMockito.verifyStatic(FileUtil.class);
FileUtil.delete(PATH);
PowerMockito.verifyStatic(FileUtil.class);
FileUtil.delete(CRC_PATH);
TopicPartition topicPartition = new TopicPartition("some_topic", 0);
Collection<TopicPartition> topicPartitions = mRegistry
.getTopicPartitions();
assertEquals(1, topicPartitions.size());
assertTrue(topicPartitions.contains(topicPartition));
Collection<LogFilePath> logFilePaths = mRegistry
.getPaths(topicPartition);
assertEquals(1, logFilePaths.size());
assertTrue(logFilePaths.contains(mLogFilePath));
}
|
FileRegistryTest tests the file registry logic.
@author Pawel Garbacki (pawel@pinterest.com)
|
testGetOrCreateWriter
|
java
|
pinterest/secor
|
src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
https://github.com/pinterest/secor/blob/master/src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
Apache-2.0
|
public void testGetWriterShowBeNotNull() throws Exception {
FileWriter createdWriter = createWriter();
FileWriter writer = mRegistry.getWriter(mLogFilePath);
assertNotNull(writer);
assertEquals(createdWriter, writer);
}
|
FileRegistryTest tests the file registry logic.
@author Pawel Garbacki (pawel@pinterest.com)
|
testGetWriterShowBeNotNull
|
java
|
pinterest/secor
|
src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
https://github.com/pinterest/secor/blob/master/src/test/java/com/pinterest/secor/common/FileRegistryTest.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.