index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dynein/dynein/src/test/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/test/java/com/airbnb/dynein/scheduler/NoOpScheduleManagerFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.airbnb.dynein.scheduler.metrics.NoOpMetricsImpl; import java.time.Clock; public class NoOpScheduleManagerFactory extends ScheduleManagerFactory { public NoOpScheduleManagerFactory( int maxShardId, TokenManager tokenManager, JobSpecTransformer jobSpecTransformer, Clock clock, Metrics metrics) { super(maxShardId, tokenManager, jobSpecTransformer, clock, metrics); } @Override public ScheduleManager get() { return new NoOpScheduleManager( maxShardId, tokenManager, jobSpecTransformer, clock, new NoOpMetricsImpl()); } }
5,600
0
Create_ds/dynein/dynein/src/test/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/test/java/com/airbnb/dynein/scheduler/dynamodb/DynamoDBTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.dynamodb; import static java.util.Arrays.asList; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.api.InvalidTokenException; import com.airbnb.dynein.api.JobSchedulePolicy; import com.airbnb.dynein.api.JobScheduleType; import com.airbnb.dynein.api.JobTokenPayload; import com.airbnb.dynein.common.job.JacksonJobSpecTransformer; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.JacksonTokenManager; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.common.utils.TimeUtils; import com.airbnb.dynein.scheduler.Schedule; import com.airbnb.dynein.scheduler.Schedule.JobStatus; import com.airbnb.dynein.scheduler.ScheduleManager; import com.airbnb.dynein.scheduler.ScheduleManager.SchedulesQueryResponse; import com.airbnb.dynein.scheduler.config.DynamoDBConfiguration; import com.airbnb.dynein.scheduler.dynamodb.DynamoDBUtils.Attribute; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.airbnb.dynein.scheduler.metrics.NoOpMetricsImpl; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; @RunWith(MockitoJUnitRunner.class) public class DynamoDBTest { private static final byte[] SERIALIZED_JOB_DATA = {0, 0, 0, 0}; @Mock private DynamoDbAsyncClient ddbClient; private JobSpecTransformer transformer; private TokenManager tokenManager; private ScheduleManager scheduleManager; private Clock clock; private String validToken; private String tableName; private int maxShardId; private Metrics metrics; private DynamoDBConfiguration ddbConfig; @Before public void setUp() { ddbConfig = new DynamoDBConfiguration(); maxShardId = 64; ObjectMapper mapper = new ObjectMapper(); transformer = new JacksonJobSpecTransformer(mapper); tokenManager = new JacksonTokenManager(mapper); tableName = ddbConfig.getSchedulesTableName(); clock = Clock.fixed(Instant.now(), ZoneId.of("UTC")); validToken = tokenManager.generateToken(2, "test-cluster", clock.millis() + 1000); metrics = spy(new NoOpMetricsImpl()); scheduleManager = new DynamoDBScheduleManager( maxShardId, tokenManager, transformer, clock, metrics, ddbClient, ddbConfig); } // lifted from original DyneinTest private DyneinJobSpec getTestJobSpec(String token, String queueName) { JobSchedulePolicy policy = JobSchedulePolicy.builder() .type(JobScheduleType.SCHEDULED) .epochMillis(Instant.now(clock).plusMillis(1000).toEpochMilli()) .build(); return DyneinJobSpec.builder() .jobToken(token) .name("AddJob") .queueType("PRODUCTION") .queueName(queueName) .createAtInMillis(Instant.now().minusMillis(10).toEpochMilli()) .schedulePolicy(policy) .serializedJob(SERIALIZED_JOB_DATA) .build(); } private String getToken(int id) { return tokenManager.generateToken(id, null, (long) 10); } private Schedule jobSpecToSchedule(DyneinJobSpec jobSpec) throws InvalidTokenException { String date = Long.toString(TimeUtils.getInstant(jobSpec.getSchedulePolicy(), clock).toEpochMilli()); JobTokenPayload token = tokenManager.decodeToken(jobSpec.getJobToken()); int shard = token.getLogicalShard(); String message = transformer.serializeJobSpec(jobSpec); return new Schedule( String.format("%s#%s", date, jobSpec.getJobToken()), Schedule.JobStatus.SCHEDULED, message, Integer.toString(shard % maxShardId)); } public <T> Throwable getException(CompletableFuture<T> future) { Throwable t = null; try { future.get(1000, TimeUnit.MILLISECONDS); } catch (ExecutionException ex) { t = ex.getCause(); } catch (Exception e) { throw new RuntimeException(e); } return t; } @Test public void testScheduleJob() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); Map<String, AttributeValue> item = DynamoDBUtils.toAttributeMap(schedule); PutItemRequest putItemRequest = PutItemRequest.builder().tableName(tableName).item(item).build(); when(ddbClient.putItem(putItemRequest)).thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Void> response = scheduleManager.addJob(schedule); response.get(1000, TimeUnit.MILLISECONDS); verify(ddbClient, times(1)).putItem(putItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testScheduleJob_Failure() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test2"); Schedule schedule = jobSpecToSchedule(jobSpec); Map<String, AttributeValue> item = DynamoDBUtils.toAttributeMap(schedule); CompletableFuture<PutItemResponse> ret = new CompletableFuture<>(); Exception putException = new Exception(); ret.completeExceptionally(putException); PutItemRequest putItemRequest = PutItemRequest.builder().tableName(tableName).item(item).build(); when(ddbClient.putItem(putItemRequest)).thenReturn(ret); CompletableFuture<Void> response = scheduleManager.addJob(schedule); assertSame(getException(response), putException); verify(ddbClient, times(1)).putItem(putItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testDeleteJob() throws Exception { String token = getToken(1); JobTokenPayload tokenPayload = tokenManager.decodeToken(token); Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKeyFromToken(token, tokenPayload, maxShardId); Map<String, String> attributeNames = new HashMap<>(); Map<String, AttributeValue> attributeValues = new HashMap<>(); attributeNames.put("#jobStatus", DynamoDBUtils.Attribute.JOB_STATUS.columnName); attributeValues.put( ":scheduled", AttributeValue.builder().s(Schedule.JobStatus.SCHEDULED.toString()).build()); DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder() .tableName(tableName) .conditionExpression("#jobStatus = :scheduled") .key(primaryKey) .expressionAttributeNames(attributeNames) .expressionAttributeValues(attributeValues) .build(); when(ddbClient.deleteItem(deleteItemRequest)) .thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Void> response = scheduleManager.deleteJob(token); response.get(1000, TimeUnit.MILLISECONDS); verify(ddbClient, times(1)).deleteItem(deleteItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testDeleteJob_Failure() throws Exception { String token = getToken(2); JobTokenPayload tokenPayload = tokenManager.decodeToken(token); Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKeyFromToken(token, tokenPayload, maxShardId); Map<String, String> attributeNames = new HashMap<>(); Map<String, AttributeValue> attributeValues = new HashMap<>(); attributeNames.put("#jobStatus", DynamoDBUtils.Attribute.JOB_STATUS.columnName); attributeValues.put( ":scheduled", AttributeValue.builder().s(Schedule.JobStatus.SCHEDULED.toString()).build()); DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder() .tableName(tableName) .conditionExpression("#jobStatus = :scheduled") .key(primaryKey) .expressionAttributeNames(attributeNames) .expressionAttributeValues(attributeValues) .build(); CompletableFuture<DeleteItemResponse> ret = new CompletableFuture<>(); Exception exception = new Exception(); ret.completeExceptionally(exception); when(ddbClient.deleteItem(deleteItemRequest)).thenReturn(ret); CompletableFuture<Void> response = scheduleManager.deleteJob(token); assertSame(getException(response), exception); verify(ddbClient, times(1)).deleteItem(deleteItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testGetJob() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); JobTokenPayload tokenPayload = tokenManager.decodeToken(validToken); Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKeyFromToken(validToken, tokenPayload, maxShardId); GetItemRequest getItemRequest = GetItemRequest.builder() .key(primaryKey) .tableName(tableName) .attributesToGet(Collections.singletonList(DynamoDBUtils.Attribute.JOB_SPEC.columnName)) .build(); when(ddbClient.getItem(getItemRequest)) .thenReturn( CompletableFuture.completedFuture( GetItemResponse.builder() .item( ImmutableMap.of( DynamoDBUtils.Attribute.JOB_SPEC.columnName, AttributeValue.builder().s(schedule.getJobSpec()).build())) .build())); CompletableFuture<Schedule> response = scheduleManager.getJob(validToken); Assert.assertEquals(response.get(1000, TimeUnit.MILLISECONDS), schedule); verify(ddbClient, times(1)).getItem(getItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testGetJob_Failure() throws Throwable { String token = getToken(4); JobTokenPayload tokenPayload = tokenManager.decodeToken(token); Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKeyFromToken(token, tokenPayload, maxShardId); GetItemRequest getItemRequest = GetItemRequest.builder() .key(primaryKey) .tableName(tableName) .attributesToGet(Collections.singletonList(DynamoDBUtils.Attribute.JOB_SPEC.columnName)) .build(); CompletableFuture<GetItemResponse> ret = new CompletableFuture<>(); Exception exception = new Exception(); ret.completeExceptionally(exception); when(ddbClient.getItem(getItemRequest)).thenReturn(ret); CompletableFuture<Schedule> response = scheduleManager.getJob(token); assertSame(getException(response), exception); verify(ddbClient, times(1)).getItem(getItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testGetOverdueJobs() throws Exception { String partition = "test-partition"; QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock)); DyneinJobSpec jobSpec1 = getTestJobSpec(validToken, "test1"); Schedule schedule1 = jobSpecToSchedule(jobSpec1); DyneinJobSpec jobSpec2 = getTestJobSpec(getToken(4), "test2"); Schedule schedule2 = jobSpecToSchedule(jobSpec2); QueryResponse queryResponse = QueryResponse.builder() .items( asList( DynamoDBUtils.toAttributeMap(schedule1), DynamoDBUtils.toAttributeMap(schedule2))) .count(2) .lastEvaluatedKey(ImmutableMap.of()) .build(); when(ddbClient.query(queryRequest)) .thenReturn(CompletableFuture.completedFuture(queryResponse)); CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition); Assert.assertEquals( response.get(1, TimeUnit.SECONDS), SchedulesQueryResponse.of(asList(schedule1, schedule2), false)); verify(ddbClient, times(1)).query(queryRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testGetOverdueJobs_queryLimit() throws Exception { String partition = "test-partition"; QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock)); DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); List<Schedule> queryLimitSchedules = new ArrayList<>(); for (int i = 0; i < ddbConfig.getQueryLimit(); i++) { queryLimitSchedules.add(schedule); } QueryResponse queryResponse = QueryResponse.builder() .items( queryLimitSchedules .stream() .map(DynamoDBUtils::toAttributeMap) .collect(Collectors.toList())) .count(ddbConfig.getQueryLimit()) .lastEvaluatedKey(ImmutableMap.of()) .build(); when(ddbClient.query(queryRequest)) .thenReturn(CompletableFuture.completedFuture(queryResponse)); CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition); Assert.assertEquals( response.get(1, TimeUnit.SECONDS), SchedulesQueryResponse.of(queryLimitSchedules, true)); verify(ddbClient, times(1)).query(queryRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testGetOverdueJobs_pagination() throws Exception { String partition = "test-partition"; QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock)); DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); List<Schedule> queryLimitSchedules = new ArrayList<>(); for (int i = 0; i < ddbConfig.getQueryLimit() - 1; i++) { queryLimitSchedules.add(schedule); } QueryResponse queryResponse = QueryResponse.builder() .items( queryLimitSchedules .stream() .map(DynamoDBUtils::toAttributeMap) .collect(Collectors.toList())) .count(ddbConfig.getQueryLimit() - 1) .lastEvaluatedKey( ImmutableMap.of("random", AttributeValue.builder().s("thing").build())) .build(); when(ddbClient.query(queryRequest)) .thenReturn(CompletableFuture.completedFuture(queryResponse)); CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition); Assert.assertEquals( response.get(1, TimeUnit.SECONDS), SchedulesQueryResponse.of(queryLimitSchedules, true)); verify(ddbClient, times(1)).query(queryRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testGetOverdueJobs_failure() { String partition = "test-partition"; QueryRequest queryRequest = getQueryRequest(partition, JobStatus.SCHEDULED, Instant.now(clock)); Exception exception = new Exception(); CompletableFuture<QueryResponse> fut = new CompletableFuture<>(); fut.completeExceptionally(exception); when(ddbClient.query(queryRequest)).thenReturn(fut); CompletableFuture<SchedulesQueryResponse> response = scheduleManager.getOverdueJobs(partition); assertSame(getException(response), exception); verify(ddbClient, times(1)).query(queryRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testUpdateStatus() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); UpdateItemRequest updateItemRequest = getUpdateItemReq(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); when(ddbClient.updateItem(updateItemRequest)) .thenReturn( CompletableFuture.completedFuture( UpdateItemResponse.builder() .attributes( ImmutableMap.of( Attribute.JOB_STATUS.columnName, AttributeValue.builder().s(JobStatus.ACQUIRED.name()).build())) .build())); CompletableFuture<Schedule> response = scheduleManager.updateStatus(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); Assert.assertEquals(response.get(1, TimeUnit.SECONDS), schedule.withStatus(JobStatus.ACQUIRED)); verify(ddbClient, times(1)).updateItem(updateItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testUpdateStatus_emptyResponse() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); UpdateItemRequest updateItemRequest = getUpdateItemReq(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); when(ddbClient.updateItem(updateItemRequest)) .thenReturn(CompletableFuture.completedFuture(UpdateItemResponse.builder().build())); CompletableFuture<Schedule> response = scheduleManager.updateStatus(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); Throwable exception = getException(response); assertTrue(exception instanceof IllegalStateException); assertEquals(exception.getMessage(), "Status update successful but status isn't returned."); verify(ddbClient, times(1)).updateItem(updateItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testUpdateStatus_unknownResponse() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); UpdateItemRequest updateItemRequest = getUpdateItemReq(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); when(ddbClient.updateItem(updateItemRequest)) .thenReturn( CompletableFuture.completedFuture( UpdateItemResponse.builder() .attributes( ImmutableMap.of( Attribute.JOB_STATUS.columnName, AttributeValue.builder().s("magic").build())) .build())); CompletableFuture<Schedule> response = scheduleManager.updateStatus(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); Throwable exception = getException(response); assertTrue(exception instanceof IllegalArgumentException); assertEquals( exception.getMessage(), "No enum constant com.airbnb.dynein.scheduler.Schedule.JobStatus.magic"); verify(ddbClient, times(1)).updateItem(updateItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testUpdateStatus_failure() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec); UpdateItemRequest updateItemRequest = getUpdateItemReq(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); Exception exception = new Exception(); CompletableFuture<UpdateItemResponse> response = new CompletableFuture<>(); response.completeExceptionally(exception); when(ddbClient.updateItem(updateItemRequest)).thenReturn(response); CompletableFuture<Schedule> ret = scheduleManager.updateStatus(schedule, JobStatus.SCHEDULED, JobStatus.ACQUIRED); assertSame(getException(ret), exception); verify(ddbClient, times(1)).updateItem(updateItemRequest); verifyNoMoreInteractions(ddbClient); } @Test public void testDeleteDispatchedJob() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec).withStatus(JobStatus.ACQUIRED); DeleteItemRequest request = getDeleteItemRequest(schedule); when(ddbClient.deleteItem(request)) .thenReturn(CompletableFuture.completedFuture(DeleteItemResponse.builder().build())); CompletableFuture<Void> ret = scheduleManager.deleteDispatchedJob(schedule); assertNull(ret.get(1, TimeUnit.SECONDS)); verify(ddbClient, times(1)).deleteItem(request); verifyNoMoreInteractions(ddbClient); } @Test public void testDeleteDispatchedJob_failure() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1"); Schedule schedule = jobSpecToSchedule(jobSpec).withStatus(JobStatus.ACQUIRED); DeleteItemRequest request = getDeleteItemRequest(schedule); Exception exception = new Exception(); CompletableFuture<DeleteItemResponse> response = new CompletableFuture<>(); response.completeExceptionally(exception); when(ddbClient.deleteItem(request)).thenReturn(response); CompletableFuture<Void> ret = scheduleManager.deleteDispatchedJob(schedule); assertSame(getException(ret), exception); verify(ddbClient, times(1)).deleteItem(request); verifyNoMoreInteractions(ddbClient); } private UpdateItemRequest getUpdateItemReq( Schedule schedule, Schedule.JobStatus oldStatus, Schedule.JobStatus newStatus) { Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKey(schedule); Map<String, String> attributeNames = new HashMap<>(); Map<String, AttributeValue> attributeValues = new HashMap<>(); attributeNames.put("#jobStatus", DynamoDBUtils.Attribute.JOB_STATUS.columnName); attributeValues.put(":oldStatus", AttributeValue.builder().s(oldStatus.name()).build()); attributeValues.put(":newStatus", AttributeValue.builder().s(newStatus.name()).build()); String updated = "SET #jobStatus = :newStatus"; return UpdateItemRequest.builder() .tableName(this.tableName) .key(primaryKey) .conditionExpression("#jobStatus = :oldStatus") .expressionAttributeNames(attributeNames) .expressionAttributeValues(attributeValues) .updateExpression(updated) .returnValues(ReturnValue.UPDATED_NEW) .build(); } private DeleteItemRequest getDeleteItemRequest(Schedule schedule) { Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKey(schedule); Map<String, String> attributeNames = new HashMap<>(); Map<String, AttributeValue> attributeValues = new HashMap<>(); attributeNames.put("#jobStatus", DynamoDBUtils.Attribute.JOB_STATUS.columnName); attributeValues.put( ":acquired", AttributeValue.builder().s(Schedule.JobStatus.ACQUIRED.toString()).build()); return DeleteItemRequest.builder() .tableName(tableName) .conditionExpression("#jobStatus = :acquired") .key(primaryKey) .expressionAttributeNames(attributeNames) .expressionAttributeValues(attributeValues) .build(); } private QueryRequest getQueryRequest(String partition, JobStatus jobStatus, Instant instant) { Map<String, AttributeValue> values = new HashMap<>(); Map<String, String> names = new HashMap<>(); String keyCondition = "#shardId = :shardId and #dateToken < :dateToken"; String filter = "#jobStatus = :jobStatus"; String now = Long.toString(instant.toEpochMilli()); values.put(":shardId", AttributeValue.builder().s(partition).build()); values.put(":dateToken", AttributeValue.builder().s(now).build()); values.put(":jobStatus", AttributeValue.builder().s(jobStatus.toString()).build()); names.put("#shardId", DynamoDBUtils.Attribute.SHARD_ID.columnName); names.put("#dateToken", DynamoDBUtils.Attribute.DATE_TOKEN.columnName); names.put("#jobStatus", DynamoDBUtils.Attribute.JOB_STATUS.columnName); return QueryRequest.builder() .tableName(tableName) .keyConditionExpression(keyCondition) .filterExpression(filter) .expressionAttributeValues(values) .expressionAttributeNames(names) .limit(ddbConfig.getQueryLimit()) .build(); } }
5,601
0
Create_ds/dynein/dynein/src/test/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/test/java/com/airbnb/dynein/scheduler/worker/PartitionWorkerTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.worker; import static java.util.Arrays.asList; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.dynein.api.*; import com.airbnb.dynein.common.job.JacksonJobSpecTransformer; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.JacksonTokenManager; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.scheduler.NoOpScheduleManager; import com.airbnb.dynein.scheduler.Schedule; import com.airbnb.dynein.scheduler.Schedule.JobStatus; import com.airbnb.dynein.scheduler.ScheduleManager; import com.airbnb.dynein.scheduler.ScheduleManager.SchedulesQueryResponse; import com.airbnb.dynein.scheduler.config.WorkersConfiguration; import com.airbnb.dynein.scheduler.metrics.NoOpMetricsImpl; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.eventbus.EventBus; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.util.List; import java.util.concurrent.*; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class PartitionWorkerTest { private static final byte[] SERIALIZED_JOB_DATA = {0, 0, 0, 0}; @Mock private AsyncSqsClient asyncClient; private TokenManager tokenManager; private Clock clock; private JobSpecTransformer transformer; private PartitionWorker worker; private String validToken; @Mock private ScheduleManager scheduleManager; @Before public void setUp() { clock = Clock.fixed(Instant.now(), ZoneId.of("UTC")); tokenManager = new JacksonTokenManager(new ObjectMapper()); validToken = tokenManager.generateToken(2, "test-cluster", clock.millis() + 1000); ObjectMapper mapper = new ObjectMapper(); transformer = new JacksonJobSpecTransformer(mapper); tokenManager = new JacksonTokenManager(mapper); scheduleManager = spy(new NoOpScheduleManager(64, tokenManager, transformer, clock, new NoOpMetricsImpl())); worker = new PartitionWorker( 1, asyncClient, new EventBus(), clock, scheduleManager, transformer, new WorkersConfiguration(1, 10, 1000), new NoOpMetricsImpl()); worker.startExecutor(); when(scheduleManager.updateStatus( any(Schedule.class), eq(JobStatus.SCHEDULED), eq(JobStatus.ACQUIRED))) .thenAnswer( invocation -> CompletableFuture.completedFuture( ((Schedule) invocation.getArguments()[0]).withStatus(JobStatus.ACQUIRED))); } // lifted from original DyneinTest private DyneinJobSpec getTestJobSpec(String token, String queueName) { JobSchedulePolicy policy; policy = JobSchedulePolicy.builder() .type(JobScheduleType.SCHEDULED) .epochMillis(Instant.now().plusMillis(1000).toEpochMilli()) .build(); return DyneinJobSpec.builder() .jobToken(token) .name("AddJob") .queueType("PRODUCTION") .queueName(queueName) .createAtInMillis(Instant.now().minusMillis(10).toEpochMilli()) .schedulePolicy(policy) .serializedJob(SERIALIZED_JOB_DATA) .build(); } private Schedule getSchedule(DyneinJobSpec jobSpec, boolean failure) throws Exception { JobTokenPayload payload = tokenManager.decodeToken(jobSpec.getJobToken()); int shard = !failure ? payload.getLogicalShard() : 1; String message = transformer.serializeJobSpec(jobSpec); return new Schedule( payload .getEpochMillisOptional() .orElseThrow( () -> new IllegalStateException("no tokens without epochMillis allowed")) + "-" + jobSpec.getJobToken(), Schedule.JobStatus.SCHEDULED, message, Integer.toString(shard)); } @Test public void testDispatchJob() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test3"); Schedule schedule = getSchedule(jobSpec, false); when(asyncClient.add(schedule.getJobSpec(), "test3")) .thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Void> ret = worker.dispatchToDestination(schedule); ret.get(1000, TimeUnit.MILLISECONDS); verify(asyncClient, times(1)).add(schedule.getJobSpec(), "test3"); verify(scheduleManager, times(1)).deleteDispatchedJob(eq(schedule)); verifyNoMoreInteractions(asyncClient, scheduleManager); } @Test public void testDispatch_EnqueueFail() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test4"); Schedule schedule = getSchedule(jobSpec, false); Exception addException = new Exception(); CompletableFuture<Void> error = new CompletableFuture<>(); error.completeExceptionally(addException); when(asyncClient.add(schedule.getJobSpec(), "test4")).thenReturn(error); CompletableFuture<Void> ret = worker.dispatchToDestination(schedule); try { ret.get(1000, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { assertSame(e.getCause(), addException); } verify(asyncClient, times(1)).add(schedule.getJobSpec(), "test4"); verify(scheduleManager, times(1)) .updateStatus(schedule, Schedule.JobStatus.ACQUIRED, Schedule.JobStatus.SCHEDULED); verifyNoMoreInteractions(scheduleManager, asyncClient); } public void testDispatch_ResetToScheduledFail() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test5"); Schedule schedule = getSchedule(jobSpec, false); CompletableFuture<Schedule> updateError = new CompletableFuture<>(); updateError.completeExceptionally(new Exception()); CompletableFuture<Void> queueError = new CompletableFuture<>(); queueError.completeExceptionally(new Exception()); when(asyncClient.add(schedule.getJobSpec(), "test5")).thenReturn(queueError); when(scheduleManager.updateStatus( schedule, Schedule.JobStatus.ACQUIRED, Schedule.JobStatus.SCHEDULED)) .thenReturn(updateError); CompletableFuture<Void> ret = worker.dispatchToDestination(schedule); Throwable caught = null; try { ret.get(1000, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { caught = e.getCause(); } assertSame(caught, updateError); verify(asyncClient, times(1)).add(schedule.getJobSpec(), "test5"); verify(scheduleManager, times(1)) .updateStatus(schedule, Schedule.JobStatus.ACQUIRED, Schedule.JobStatus.SCHEDULED); verifyNoMoreInteractions(scheduleManager, asyncClient); } @Test public void testDispatch_DeleteFromTableFail() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test6"); Schedule schedule = getSchedule(jobSpec, false); CompletableFuture<Void> response = new CompletableFuture<>(); Exception exception = new Exception(); response.completeExceptionally(exception); when(asyncClient.add(schedule.getJobSpec(), "test6")) .thenReturn(CompletableFuture.completedFuture(null)); when(scheduleManager.deleteDispatchedJob(schedule)).thenReturn(response); CompletableFuture<Void> ret = worker.dispatchToDestination(schedule); ret.get(1000, TimeUnit.MILLISECONDS); verify(asyncClient, times(1)).add(schedule.getJobSpec(), "test6"); verify(scheduleManager, times(1)).deleteDispatchedJob(schedule); verifyNoMoreInteractions(scheduleManager, asyncClient); } @Test public void testDispatchOverdue() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test7"); Schedule schedule = getSchedule(jobSpec, false); Schedule scheduleAcquired = schedule.withStatus(JobStatus.ACQUIRED); List<Schedule> items = asList(schedule, schedule); String partition = "1"; SchedulesQueryResponse response = SchedulesQueryResponse.of(items, false); when(scheduleManager.getOverdueJobs(partition)) .thenReturn(CompletableFuture.completedFuture(response)); when(asyncClient.add(schedule.getJobSpec(), "test7")) .thenReturn(CompletableFuture.completedFuture(null)); when(scheduleManager.deleteDispatchedJob(scheduleAcquired)) .thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Boolean> ret = worker.dispatchOverdue(partition); Assert.assertEquals( ret.get(1000, TimeUnit.MILLISECONDS), response.isShouldImmediatelyQueryAgain()); verify(scheduleManager, times(1)).getOverdueJobs(partition); verify(scheduleManager, times(2)) .updateStatus(schedule, Schedule.JobStatus.SCHEDULED, Schedule.JobStatus.ACQUIRED); verify(asyncClient, times(2)).add(schedule.getJobSpec(), "test7"); verify(scheduleManager, times(2)).deleteDispatchedJob(scheduleAcquired); verifyNoMoreInteractions(scheduleManager, asyncClient); } @Test public void testDispatchOverdue_scanForOverdueFailure() throws Exception { DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test8"); Schedule schedule = getSchedule(jobSpec, false); String partition = "failure1"; CompletableFuture<SchedulesQueryResponse> response = new CompletableFuture<>(); response.completeExceptionally(new Exception()); when(scheduleManager.getOverdueJobs(partition)).thenReturn(response); CompletableFuture<Boolean> ret = worker.dispatchOverdue(partition); ret.get(1000, TimeUnit.MILLISECONDS); verify(scheduleManager, times(1)).getOverdueJobs(partition); verifyNoMoreInteractions(scheduleManager, asyncClient); } @Test public void testDispatchOverdue_SetAcquiredPartialFailure() throws Exception { DyneinJobSpec jobSpec_1 = getTestJobSpec(validToken, "test9"); Schedule schedule_1 = getSchedule(jobSpec_1, false); DyneinJobSpec jobSpec_2 = getTestJobSpec(validToken, "test9"); Schedule schedule_2 = getSchedule(jobSpec_2, true); String partition = "failure2"; CompletableFuture<Schedule> updateResponse = new CompletableFuture<>(); updateResponse.completeExceptionally(new Exception()); when(scheduleManager.getOverdueJobs(partition)) .thenReturn( CompletableFuture.completedFuture( SchedulesQueryResponse.of(asList(schedule_1, schedule_2), false))); when(scheduleManager.updateStatus(schedule_2, JobStatus.SCHEDULED, JobStatus.ACQUIRED)) .thenReturn(updateResponse); when(asyncClient.add(schedule_1.getJobSpec(), "test9")) .thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Boolean> ret = worker.dispatchOverdue("failure2"); ret.get(1000, TimeUnit.MILLISECONDS); verify(scheduleManager, times(1)).getOverdueJobs(partition); verify(scheduleManager, times(1)) .updateStatus(schedule_1, JobStatus.SCHEDULED, JobStatus.ACQUIRED); verify(scheduleManager, times(1)) .updateStatus(schedule_2, JobStatus.SCHEDULED, JobStatus.ACQUIRED); verify(asyncClient, times(1)).add(schedule_1.getJobSpec(), "test9"); verify(scheduleManager, times(1)) .deleteDispatchedJob(schedule_1.withStatus(JobStatus.ACQUIRED)); verifyNoMoreInteractions(scheduleManager, asyncClient); } // test dispatched overdue w/ dispatch fail @Test public void testDispatchOverdue_dispatchPartialFailure() throws Exception { String partition = "failure3"; DyneinJobSpec jobSpec_1 = getTestJobSpec(validToken, "test10"); Schedule schedule_1 = getSchedule(jobSpec_1, false); DyneinJobSpec jobSpec_2 = getTestJobSpec(validToken, "test10.1"); Schedule schedule_2 = getSchedule(jobSpec_2, true); CompletableFuture<Void> dispatchResponse = new CompletableFuture<>(); dispatchResponse.completeExceptionally(new Exception()); when(scheduleManager.getOverdueJobs(partition)) .thenReturn( CompletableFuture.completedFuture( SchedulesQueryResponse.of(asList(schedule_1, schedule_2), false))); when(asyncClient.add(schedule_1.getJobSpec(), "test10")) .thenReturn(CompletableFuture.completedFuture(null)); when(asyncClient.add(schedule_2.getJobSpec(), "test10.1")).thenReturn(dispatchResponse); when(scheduleManager.updateStatus( schedule_2.withStatus(JobStatus.ACQUIRED), Schedule.JobStatus.ACQUIRED, Schedule.JobStatus.SCHEDULED)) .thenReturn(CompletableFuture.completedFuture(schedule_2)); CompletableFuture<Boolean> ret = worker.dispatchOverdue(partition); ret.get(1000, TimeUnit.MILLISECONDS); verify(scheduleManager, times(1)).getOverdueJobs(partition); verify(scheduleManager, times(1)) .updateStatus(schedule_1, JobStatus.SCHEDULED, JobStatus.ACQUIRED); verify(scheduleManager, times(1)) .updateStatus(schedule_2, JobStatus.SCHEDULED, JobStatus.ACQUIRED); verify(asyncClient, times(1)).add(schedule_1.getJobSpec(), "test10"); verify(asyncClient, times(1)).add(schedule_2.getJobSpec(), "test10.1"); verify(scheduleManager, times(1)) .deleteDispatchedJob(schedule_1.withStatus(JobStatus.ACQUIRED)); verify(scheduleManager, times(1)) .updateStatus( schedule_2.withStatus(JobStatus.ACQUIRED), JobStatus.ACQUIRED, JobStatus.SCHEDULED); verifyNoMoreInteractions(scheduleManager, asyncClient); } }
5,602
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/ManagedInboundJobQueueConsumer.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; import com.airbnb.conveyor.async.AsyncConsumer; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.dynein.api.InvalidTokenException; import com.airbnb.dynein.common.utils.ExecutorUtils; import io.dropwizard.lifecycle.Managed; import java.util.concurrent.ExecutorService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @AllArgsConstructor public class ManagedInboundJobQueueConsumer implements Managed { private static final long EXECUTOR_TIMEOUT_SECONDS = 15; private final AsyncSqsClient asyncClient; private final ExecutorService executorService; private final ScheduleManager scheduleManager; private final String inboundQueueName; @Override public void start() { log.info("Starting to consume from inbound job queue {}", inboundQueueName); executorService.execute(this::run); log.info("Started consuming from inbound job queue {}", inboundQueueName); } @Override public void stop() { log.info("Stopping consumption from inbound job queue {}", inboundQueueName); ExecutorUtils.twoPhaseExecutorShutdown(executorService, EXECUTOR_TIMEOUT_SECONDS); log.info("Stopped consumption from inbound job queue {}", inboundQueueName); } private void run() { while (!executorService.isShutdown()) { doRun(); } } private void doRun() { AsyncConsumer<String> consumer = (message, executor) -> { try { return scheduleManager.addJob(scheduleManager.makeSchedule(message)); } catch (InvalidTokenException e) { throw new RuntimeException(e); } }; asyncClient .consume(consumer, inboundQueueName) .whenComplete( (it, ex) -> { if (ex != null) { log.error("Error consuming from inbound queue {}", inboundQueueName, ex); } else if (!it) { log.debug("Inbound job queue {} is empty", inboundQueueName); } else { log.info("Successfully consumed job from inbound queue"); } }); } }
5,603
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/Schedule.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; import lombok.AllArgsConstructor; import lombok.Value; import lombok.experimental.Wither; import lombok.extern.slf4j.Slf4j; @Slf4j @Value @AllArgsConstructor @Wither public class Schedule { private final String dateToken; private final JobStatus status; private final String jobSpec; private final String shardId; public enum JobStatus { SCHEDULED, ACQUIRED } }
5,604
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/Scheduler.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.api.JobSchedulePolicy; import com.airbnb.dynein.api.PrepareJobRequest; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.common.utils.TimeUtils; import com.airbnb.dynein.scheduler.metrics.Metrics; import java.time.Clock; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Named; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class Scheduler { @NonNull @Named(Constants.SQS_PRODUCER) private final AsyncSqsClient asyncClient; @NonNull @Named(Constants.INBOUND_QUEUE_NAME) private final String inboundQueueName; @NonNull private final JobSpecTransformer jobSpecTransformer; @NonNull private final TokenManager tokenManager; @NonNull private final ScheduleManager scheduleManager; @NonNull private final Clock clock; @NonNull private final Metrics metrics; public String prepareJob(@NonNull PrepareJobRequest request) { return tokenManager.generateToken( request.getAssociatedId(), null, request .getSchedulePolicyOptional() .flatMap(JobSchedulePolicy::getEpochMillisOptional) .orElse(null)); } public CompletableFuture<Void> createJob(@NonNull DyneinJobSpec jobSpec) { CompletableFuture<Void> ret = new CompletableFuture<>(); log.info("Create new job {}", jobSpec); String serializedJobSpec = jobSpecTransformer.serializeJobSpec(jobSpec); switch (jobSpec.getSchedulePolicy().getType()) { case IMMEDIATE: { ret = asyncClient .add(serializedJobSpec, jobSpec.getQueueName()) .whenComplete( (it, ex) -> { if (ex == null) { log.info( "DyneinJob {} triggered, enqueue to queue {}, type: IMMEDIATE", jobSpec.getJobToken(), jobSpec.getQueueName()); metrics.dispatchJob(jobSpec.getQueueName()); } else { log.error( "Failed to trigger DyneinJob {} to queue {}, type: IMMEDIATE", jobSpec.getJobToken(), jobSpec.getQueueName(), ex); } }); break; } case SCHEDULED: { ret = asyncClient .add(serializedJobSpec, inboundQueueName) .whenComplete( (it, ex) -> { if (ex == null) { log.info( "Added job spec {} to inbound job queue {}, with token {}", jobSpec.getName(), inboundQueueName, jobSpec.getJobToken()); metrics.enqueueToInboundQueue(jobSpec); } else { log.error( "Exception when adding job spec {} to inbound job queue {}, with token {}", jobSpec.getName(), inboundQueueName, jobSpec.getJobToken(), ex); } }); break; } case SQS_DELAYED: { long delayMs = TimeUtils.getDelayMillis(jobSpec.getSchedulePolicy(), clock); if (delayMs > TimeUnit.MINUTES.toMillis(15)) { ret.completeExceptionally( new IllegalArgumentException( "Delay " + delayMs + "ms is longer than 15 minutes, cannot be scheduled with SQS_DELAYED")); } else { ret = asyncClient .add( serializedJobSpec, jobSpec.getQueueName(), (int) TimeUnit.MILLISECONDS.toSeconds(delayMs)) .whenComplete( (it, ex) -> { if (ex == null) { log.info( "DyneinJob {} triggered, enqueue to queue {}, type: SQS_DELAYED", jobSpec.getJobToken(), jobSpec.getQueueName()); metrics.dispatchJob(jobSpec.getQueueName()); } else { log.error( "Failed to trigger DyneinJob {} to queue {}, type: SQS_DELAYED", jobSpec.getJobToken(), jobSpec.getQueueName(), ex); } }); } break; } default: ret.completeExceptionally( new UnsupportedOperationException("Unsupported Job Schedule Policy Type")); } return ret; } public CompletableFuture<Void> deleteJob(String token) { return scheduleManager.deleteJob(token); } public CompletableFuture<DyneinJobSpec> getJob(String token) { return scheduleManager .getJob(token) .thenApply(schedule -> jobSpecTransformer.deserializeJobSpec(schedule.getJobSpec())); } }
5,605
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/ScheduleManagerFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.scheduler.metrics.Metrics; import java.time.Clock; import javax.inject.Provider; import lombok.AccessLevel; import lombok.AllArgsConstructor; @AllArgsConstructor(access = AccessLevel.PROTECTED) public abstract class ScheduleManagerFactory implements Provider<ScheduleManager> { protected final int maxShardId; protected final TokenManager tokenManager; protected final JobSpecTransformer jobSpecTransformer; protected final Clock clock; protected final Metrics metrics; @Override public abstract ScheduleManager get(); }
5,606
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/ScheduleManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.api.InvalidTokenException; import com.airbnb.dynein.api.JobTokenPayload; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.common.utils.TimeUtils; import com.airbnb.dynein.scheduler.metrics.Metrics; import java.io.Closeable; import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.concurrent.CompletableFuture; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Value; @AllArgsConstructor(access = AccessLevel.PROTECTED) public abstract class ScheduleManager implements Closeable { @Value @AllArgsConstructor(staticName = "of") public static class SchedulesQueryResponse { List<Schedule> schedules; boolean shouldImmediatelyQueryAgain; } protected final int maxShardId; protected final TokenManager tokenManager; protected final JobSpecTransformer jobSpecTransformer; protected final Clock clock; protected final Metrics metrics; public abstract CompletableFuture<Void> addJob(Schedule schedule); public abstract CompletableFuture<Schedule> getJob(String token); public abstract CompletableFuture<Void> deleteJob(String token); public abstract CompletableFuture<SchedulesQueryResponse> getOverdueJobs( String partition, Instant instant); public abstract CompletableFuture<Void> recoverStuckJobs(String partition, Instant instant); public final CompletableFuture<SchedulesQueryResponse> getOverdueJobs(String partition) { return getOverdueJobs(partition, Instant.now(clock)); } public abstract CompletableFuture<Schedule> updateStatus( Schedule schedule, Schedule.JobStatus oldStatus, Schedule.JobStatus newStatus); public abstract CompletableFuture<Void> deleteDispatchedJob(Schedule schedule); protected Schedule makeSchedule(String serializedJobSpec) throws InvalidTokenException { DyneinJobSpec jobSpec = jobSpecTransformer.deserializeJobSpec(serializedJobSpec); String date = Long.toString(TimeUtils.getInstant(jobSpec.getSchedulePolicy(), clock).toEpochMilli()); JobTokenPayload token = tokenManager.decodeToken(jobSpec.getJobToken()); int shard = token.getLogicalShard(); return new Schedule( String.format("%s#%s", date, jobSpec.getJobToken()), Schedule.JobStatus.SCHEDULED, serializedJobSpec, Integer.toString(Math.floorMod(shard, maxShardId))); } }
5,607
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/Constants.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler; public class Constants { public static final String MAX_PARTITIONS = "maxPartitions"; public static final String SQS_CONSUMER = "sqsConsumer"; public static final String SQS_PRODUCER = "sqsProducer"; public static final String INBOUND_QUEUE_NAME = "inboundQueueName"; }
5,608
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/metrics/NoOpMetricsImpl.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.metrics; public class NoOpMetricsImpl implements Metrics {}
5,609
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/metrics/Metrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.metrics; import com.airbnb.dynein.api.DyneinJobSpec; public interface Metrics { default void storeJob(final long elapsedTime, DyneinJobSpec jobSpec, String partition) {} default void storeJobError(Throwable throwable, String queueName) {} default void queryOverdue(String partition) {} default void queryOverdueError(Throwable throwable, String partition) {} default void updateJobStatus(String oldStatus, String newStatus) {} default void updateJobStatusError(Throwable throwable, String oldStatus, String newStatus) {} default void deleteDispatchedJob(String queueName) {} default void deleteDispatchedJobError(Throwable throwable, String queueName) {} default void dispatchJob(String queueName) {} default void dispatchScheduledJob(long timeNs, DyneinJobSpec jobSpec, String partition) {} default void dispatchJobError(Throwable t, String queueName) {} default void enqueueToInboundQueue(DyneinJobSpec jobSpec) {} default void dispatchOverdue(long timeNs, String partition) {} default void updatePartitions(long timeNs) {} default void updatePartitionsError(Throwable t) {} default void countPartitionWorkers(int count) {} default void restartWorker(int workerId) {} default void recoverStuckJob(String partition, int successCount, int totalCount) {} default void recoverStuckJobsError(String partition) {} }
5,610
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/config/SQSConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.config; import java.net.URI; import lombok.Value; @Value public class SQSConfiguration { private static final String DEFAULT_REGION = "us-east-1"; private String region = DEFAULT_REGION; private URI endpoint; private TimeoutRegistry timeouts = new TimeoutRegistry(); private String inboundQueueName; public URI getEndpoint() { return endpoint == null ? URI.create("https://sqs." + region + ".amazonaws.com") : endpoint; } }
5,611
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/config/WorkersConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.config; import java.util.List; import lombok.Value; @Value public class WorkersConfiguration { public enum PartitionPolicyChoice { K8S, STATIC; } private int numberOfWorkers; private int threadPoolSize; private long recoverStuckJobsLookAheadMs; private boolean recoverStuckJobsAtWorkerRotation = true; private PartitionPolicyChoice partitionPolicy = PartitionPolicyChoice.K8S; private List<Integer> staticPartitionList = null; }
5,612
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/config/DynamoDBConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.config; import java.net.URI; import java.util.Optional; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class DynamoDBConfiguration { public static final String DEFAULT_REGION = "us-east-1"; public static final String DEFAULT_TABLE_NAME = "job_schedules"; private String region = DEFAULT_REGION; private URI endpoint = null; private String schedulesTableName = DEFAULT_TABLE_NAME; private int queryLimit = 10; public URI getEndpoint() { return Optional.ofNullable(endpoint) .orElseGet(() -> URI.create("https://dynamodb." + region + ".amazonaws.com")); } }
5,613
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/config/TimeoutRegistry.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.config; import lombok.Data; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor public class TimeoutRegistry { // Execution timeout: total time allocated to the SQS client, include all of the retry attempts private int apiCallTimeout = 25 * 1000; // Request timeout: time allocated for each individual attempt private int apiCallAttemptTimeout = 2000; // Retry policy: scale factor for exponential backoff policy private int baseDelay = 100; // Retry policy: maximum backoff time for exponential backoff policy private int maxBackoffTime = 10 * 1000; }
5,614
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/config/SchedulerConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.config; import com.airbnb.dynein.scheduler.heartbeat.HeartbeatConfiguration; import javax.validation.constraints.NotNull; import lombok.Value; @Value public class SchedulerConfiguration { @NotNull private WorkersConfiguration workers; @NotNull private HeartbeatConfiguration heartbeat; @NotNull private SQSConfiguration sqs; @NotNull private DynamoDBConfiguration dynamoDb; private int maxPartitions; private boolean consumeInboundJobs; }
5,615
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/dynamodb/DynamoDBUtils.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.dynamodb; import static java.util.Arrays.asList; import com.airbnb.dynein.api.JobTokenPayload; import com.airbnb.dynein.scheduler.Schedule; import com.airbnb.dynein.scheduler.Schedule.JobStatus; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.experimental.UtilityClass; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @UtilityClass class DynamoDBUtils { @AllArgsConstructor @Getter public enum Attribute { SHARD_ID("shard_id", "#shardId"), DATE_TOKEN("date_token", "#dateToken"), JOB_STATUS("job_status", "#jobStatus"), JOB_SPEC("job_spec", "#jobSpec"); public final String columnName; public final String attributeName; } @AllArgsConstructor public enum Value { SHARD_ID(":shardId"), JOB_STATUS(":jobStatus"), DATE_TOKEN(":dateToken"), OLD_STATUS(":oldStatus"), NEW_STATUS(":newStatus"), SCHEDULED_STATUS(":scheduled"), ACQUIRED_STATUS(":acquired"); public final String name; } @AllArgsConstructor(staticName = "of") public class Condition { private Attribute attribute; private String operator; private Value value; public String toString() { return String.format("%s %s %s", attribute.attributeName, operator, value.name); } } Map<String, AttributeValue> attributeValuesMap(Map<Value, String> input) { return input .entrySet() .stream() .collect( Collectors.toMap( (Entry<Value, String> e) -> e.getKey().name, (Entry<Value, String> e) -> AttributeValue.builder().s(e.getValue()).build())); } @Getter(lazy = true) private final Map<String, String> jobStatusAttributeMap = initJobStatusAttributeMap(); @Getter(lazy = true) private final Map<String, String> getOverdueJobsAttributeMap = initGetOverdueJobsAttributeNameMap(); private Map<String, String> initAttributeNameMap(List<Attribute> attributes) { return ImmutableMap.copyOf( attributes .stream() .collect(Collectors.toMap(Attribute::getAttributeName, Attribute::getColumnName))); } private Map<String, String> initJobStatusAttributeMap() { return initAttributeNameMap(Collections.singletonList(Attribute.JOB_STATUS)); } private Map<String, String> initGetOverdueJobsAttributeNameMap() { return initAttributeNameMap( asList(Attribute.SHARD_ID, Attribute.JOB_STATUS, Attribute.DATE_TOKEN)); } Map<String, AttributeValue> getPrimaryKeyFromToken( String token, JobTokenPayload payload, int maxShardId) { Map<String, AttributeValue> primaryKey = new HashMap<>(); String date = String.valueOf(payload.getEpochMillis()); int shard = payload.getLogicalShard(); primaryKey.put( Attribute.SHARD_ID.columnName, AttributeValue.builder().s(Integer.toString(shard % maxShardId)).build()); primaryKey.put( Attribute.DATE_TOKEN.columnName, AttributeValue.builder().s(String.format("%s#%s", date, token)).build()); return primaryKey; } Schedule decodeSchedule(Map<String, AttributeValue> item) { return new Schedule( item.get(Attribute.DATE_TOKEN.columnName).s(), JobStatus.valueOf(item.get(Attribute.JOB_STATUS.columnName).s()), item.get(Attribute.JOB_SPEC.columnName).s(), item.get(Attribute.SHARD_ID.columnName).s()); } Map<String, AttributeValue> getPrimaryKey(Schedule schedule) { Map<String, AttributeValue> item = new HashMap<>(); item.put( Attribute.SHARD_ID.columnName, AttributeValue.builder().s(schedule.getShardId()).build()); item.put( Attribute.DATE_TOKEN.columnName, AttributeValue.builder().s(schedule.getDateToken()).build()); return item; } Map<String, AttributeValue> toAttributeMap(Schedule schedule) { Map<String, AttributeValue> item = new HashMap<>(); item.put( Attribute.SHARD_ID.columnName, AttributeValue.builder().s(schedule.getShardId()).build()); item.put( Attribute.DATE_TOKEN.columnName, AttributeValue.builder().s(schedule.getDateToken()).build()); item.put( Attribute.JOB_STATUS.columnName, AttributeValue.builder().s(schedule.getStatus().toString()).build()); item.put( Attribute.JOB_SPEC.columnName, AttributeValue.builder().s(schedule.getJobSpec()).build()); return item; } }
5,616
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/dynamodb/DynamoDBScheduleManagerFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.dynamodb; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.scheduler.Constants; import com.airbnb.dynein.scheduler.ScheduleManagerFactory; import com.airbnb.dynein.scheduler.config.DynamoDBConfiguration; import com.airbnb.dynein.scheduler.metrics.Metrics; import java.time.Clock; import javax.inject.Inject; import javax.inject.Named; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; public class DynamoDBScheduleManagerFactory extends ScheduleManagerFactory { private final DynamoDBConfiguration dynamoDBConfiguration; @Inject public DynamoDBScheduleManagerFactory( @Named(Constants.MAX_PARTITIONS) Integer maxShardId, TokenManager tokenManager, JobSpecTransformer jobSpecTransformer, Clock clock, Metrics metrics, DynamoDBConfiguration dynamoDBConfiguration) { super(maxShardId, tokenManager, jobSpecTransformer, clock, metrics); this.dynamoDBConfiguration = dynamoDBConfiguration; } private DynamoDbAsyncClient getDdbAsyncClient() { return DynamoDbAsyncClient.builder() .region(Region.of(dynamoDBConfiguration.getRegion())) .endpointOverride(dynamoDBConfiguration.getEndpoint()) .build(); } @Override public DynamoDBScheduleManager get() { return new DynamoDBScheduleManager( maxShardId, tokenManager, jobSpecTransformer, clock, metrics, getDdbAsyncClient(), dynamoDBConfiguration); } }
5,617
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/dynamodb/DynamoDBScheduleManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.dynamodb; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.api.InvalidTokenException; import com.airbnb.dynein.api.JobTokenPayload; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.scheduler.Schedule; import com.airbnb.dynein.scheduler.Schedule.JobStatus; import com.airbnb.dynein.scheduler.ScheduleManager; import com.airbnb.dynein.scheduler.config.DynamoDBConfiguration; import com.airbnb.dynein.scheduler.dynamodb.DynamoDBUtils.Attribute; import com.airbnb.dynein.scheduler.dynamodb.DynamoDBUtils.Condition; import com.airbnb.dynein.scheduler.dynamodb.DynamoDBUtils.Value; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableMap; import io.reactivex.Flowable; import java.time.Clock; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; @Slf4j public class DynamoDBScheduleManager extends ScheduleManager { private final DynamoDbAsyncClient ddbClient; private final DynamoDBConfiguration ddbConfig; DynamoDBScheduleManager( int maxShardId, TokenManager tokenManager, JobSpecTransformer jobSpecTransformer, Clock clock, Metrics metrics, DynamoDbAsyncClient ddbClient, DynamoDBConfiguration ddbConfig) { super(maxShardId, tokenManager, jobSpecTransformer, clock, metrics); this.ddbClient = ddbClient; this.ddbConfig = ddbConfig; } @Override public CompletableFuture<Void> addJob(Schedule schedule) { CompletableFuture<Void> ret = new CompletableFuture<>(); Stopwatch stopwatch = Stopwatch.createStarted(); DyneinJobSpec jobSpec = jobSpecTransformer.deserializeJobSpec(schedule.getJobSpec()); try { Map<String, AttributeValue> item = DynamoDBUtils.toAttributeMap(schedule); PutItemRequest putItemRequest = PutItemRequest.builder().tableName(ddbConfig.getSchedulesTableName()).item(item).build(); ddbClient .putItem(putItemRequest) .whenComplete( (it, ex) -> { if (ex != null) { stopwatch.stop(); log.error("Error scheduling job {}", jobSpec.getJobToken(), ex); metrics.storeJobError(ex, jobSpec.getQueueName()); ret.completeExceptionally(ex); } else { stopwatch.stop(); log.info("Scheduled job {}", jobSpec.getJobToken()); long time = stopwatch.elapsed(TimeUnit.NANOSECONDS); metrics.storeJob(time, jobSpec, schedule.getShardId()); ret.complete(null); } }); } catch (Exception ex) { log.error("Error scheduling job {}", jobSpec.getJobToken(), ex); metrics.storeJobError(ex, jobSpec.getQueueName()); ret.completeExceptionally(ex); } return ret; } private <T> CompletableFuture<Void> asyncForeach( Flowable<T> f, Function<T, CompletableFuture<Void>> function) { CompletableFuture<List<T>> fut = new CompletableFuture<>(); f.toList().doOnError(fut::completeExceptionally).subscribe(fut::complete); return fut.thenCompose( items -> CompletableFuture.allOf( items.stream().map(function).toArray(CompletableFuture[]::new))); } @Override public CompletableFuture<Void> recoverStuckJobs(String partition, Instant instant) { AtomicInteger totalCount = new AtomicInteger(0); AtomicInteger successCount = new AtomicInteger(0); log.info("Starting recoverStuckJobs for partition: {}, with lookAhead: {}", partition, instant); return asyncForeach( Flowable.fromPublisher( ddbClient.queryPaginator( makeQueryRequestForOverdueJobs(partition, instant, JobStatus.ACQUIRED))) .flatMap(queryResponse -> Flowable.fromIterable(queryResponse.items())) .map(DynamoDBUtils::decodeSchedule), schedule -> { log.info( "Recovering job {} in partition {} from ACQUIRED to SCHEDULED", schedule.getDateToken(), schedule.getShardId()); return updateStatus(schedule, JobStatus.ACQUIRED, JobStatus.SCHEDULED) .handle( (result, ex) -> { totalCount.incrementAndGet(); if (ex == null && result.getStatus().equals(JobStatus.SCHEDULED)) { successCount.incrementAndGet(); log.info( "Successfully recovered job {} in partition {} from ACQUIRED to SCHEDULED", schedule.getDateToken(), schedule.getShardId()); } else { log.warn( "Failed to recover job {} in partition {} from ACQUIRED to SCHEDULED", schedule.getDateToken(), schedule.getShardId()); } return null; }); }) .whenComplete( (result, ex) -> { log.info( "Recovered {} of {} jobs from ACQUIRED state back to SCHEDULED state in partition {}.", successCount.get(), totalCount.get(), partition); metrics.recoverStuckJob(partition, successCount.get(), totalCount.get()); }); } @Override public CompletableFuture<Schedule> getJob(String token) { try { JobTokenPayload tokenPayload = tokenManager.decodeToken(token); Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKeyFromToken(token, tokenPayload, maxShardId); GetItemRequest getItemRequest = GetItemRequest.builder() .key(primaryKey) .tableName(ddbConfig.getSchedulesTableName()) .attributesToGet(Collections.singletonList(Attribute.JOB_SPEC.columnName)) .build(); return ddbClient .getItem(getItemRequest) .thenApply( item -> { try { return makeSchedule(item.item().get(Attribute.JOB_SPEC.columnName).s()); } catch (InvalidTokenException e) { throw new RuntimeException(e); } }); } catch (InvalidTokenException ex) { CompletableFuture<Schedule> future = new CompletableFuture<>(); future.completeExceptionally(ex); return future; } } @Override public CompletableFuture<Void> deleteJob(String token) { try { JobTokenPayload tokenPayload = tokenManager.decodeToken(token); Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKeyFromToken(token, tokenPayload, maxShardId); Map<String, AttributeValue> attributeValues = DynamoDBUtils.attributeValuesMap( ImmutableMap.of(Value.SCHEDULED_STATUS, Schedule.JobStatus.SCHEDULED.toString())); DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder() .tableName(ddbConfig.getSchedulesTableName()) .conditionExpression( Condition.of(Attribute.JOB_STATUS, "=", Value.SCHEDULED_STATUS).toString()) .key(primaryKey) .expressionAttributeNames(DynamoDBUtils.getJobStatusAttributeMap()) .expressionAttributeValues(attributeValues) .build(); return ddbClient .deleteItem(deleteItemRequest) .whenComplete( (response, ex) -> { if (ex != null) { log.error( "Error deleting job {} from table {}", token, ddbConfig.getSchedulesTableName(), ex); } else { log.info( "Deleted job {} from table {}", token, ddbConfig.getSchedulesTableName()); } }) .thenApply(response -> null); } catch (InvalidTokenException ex) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(ex); return future; } } private QueryRequest makeQueryRequestForOverdueJobs( String partition, Instant instant, JobStatus jobStatus) { String keyCondition = Condition.of(Attribute.SHARD_ID, "=", Value.SHARD_ID) + " and " + Condition.of(Attribute.DATE_TOKEN, "<", Value.DATE_TOKEN); String filter = Condition.of(Attribute.JOB_STATUS, "=", Value.JOB_STATUS).toString(); String now = Long.toString(instant.toEpochMilli()); Map<String, AttributeValue> attributeValues = DynamoDBUtils.attributeValuesMap( ImmutableMap.of( Value.SHARD_ID, partition, Value.DATE_TOKEN, now, Value.JOB_STATUS, jobStatus.toString())); return QueryRequest.builder() .tableName(ddbConfig.getSchedulesTableName()) .keyConditionExpression(keyCondition) .filterExpression(filter) .expressionAttributeValues(attributeValues) .expressionAttributeNames(DynamoDBUtils.getGetOverdueJobsAttributeMap()) .limit(ddbConfig.getQueryLimit()) .build(); } @Override public CompletableFuture<SchedulesQueryResponse> getOverdueJobs( @NonNull String partition, Instant instant) { return ddbClient .query(makeQueryRequestForOverdueJobs(partition, instant, JobStatus.SCHEDULED)) .whenComplete( (res, ex) -> { if (ex == null) { log.info( "Query for overdue jobs in partition {} at time {} successful", partition, instant.toEpochMilli()); metrics.queryOverdue(partition); } else { log.error( "Query for overdue jobs in partition {} at time {} failed", partition, instant.toEpochMilli(), ex); metrics.queryOverdueError(ex, partition); } }) .thenApply( queryResponse -> SchedulesQueryResponse.of( queryResponse .items() .stream() .map(DynamoDBUtils::decodeSchedule) .collect(Collectors.toList()), queryResponse.count() == ddbConfig.getQueryLimit() || !queryResponse.lastEvaluatedKey().isEmpty())); } @Override public CompletableFuture<Schedule> updateStatus( Schedule schedule, JobStatus oldStatus, JobStatus newStatus) { Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKey(schedule); Map<String, AttributeValue> attributeValues = DynamoDBUtils.attributeValuesMap( ImmutableMap.of( Value.OLD_STATUS, oldStatus.toString(), Value.NEW_STATUS, newStatus.toString())); String updated = "SET " + Condition.of(Attribute.JOB_STATUS, "=", Value.NEW_STATUS); UpdateItemRequest updateItemRequest = UpdateItemRequest.builder() .tableName(ddbConfig.getSchedulesTableName()) .key(primaryKey) .conditionExpression( Condition.of(Attribute.JOB_STATUS, "=", Value.OLD_STATUS).toString()) .expressionAttributeNames(DynamoDBUtils.getJobStatusAttributeMap()) .expressionAttributeValues(attributeValues) .updateExpression(updated) .returnValues(ReturnValue.UPDATED_NEW) .build(); return ddbClient .updateItem(updateItemRequest) .whenComplete( (response, exception) -> { DyneinJobSpec jobSpec = jobSpecTransformer.deserializeJobSpec(schedule.getJobSpec()); if (exception != null) { log.error( "Failed to set job {} to {}", jobSpec.getJobToken(), newStatus.toString(), exception); metrics.updateJobStatusError(exception, oldStatus.toString(), newStatus.toString()); } else { log.info("Set job {} to {}", jobSpec.getJobToken(), newStatus.toString()); metrics.updateJobStatus(oldStatus.toString(), newStatus.toString()); } }) .thenApply( response -> { JobStatus updatedStatus = Optional.ofNullable(response.attributes().get(Attribute.JOB_STATUS.columnName)) .map(attr -> JobStatus.valueOf(attr.s())) .orElseThrow( () -> new IllegalStateException( "Status update successful but status isn't returned.")); return schedule.withStatus(updatedStatus); }); } @Override public CompletableFuture<Void> deleteDispatchedJob(Schedule schedule) { Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKey(schedule); Map<String, AttributeValue> attributeValues = DynamoDBUtils.attributeValuesMap( ImmutableMap.of(Value.ACQUIRED_STATUS, Schedule.JobStatus.ACQUIRED.toString())); DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder() .tableName(ddbConfig.getSchedulesTableName()) .conditionExpression( Condition.of(Attribute.JOB_STATUS, "=", Value.ACQUIRED_STATUS).toString()) .key(primaryKey) .expressionAttributeNames(DynamoDBUtils.getJobStatusAttributeMap()) .expressionAttributeValues(attributeValues) .build(); return ddbClient .deleteItem(deleteItemRequest) .whenComplete( (response, exception) -> { DyneinJobSpec jobSpec = jobSpecTransformer.deserializeJobSpec(schedule.getJobSpec()); if (exception != null) { log.error( "Error deleting job {} from table {}", jobSpec.getJobToken(), ddbConfig.getSchedulesTableName(), exception); metrics.deleteDispatchedJobError(exception, jobSpec.getQueueName()); } else { log.info( "Deleted job {} from table {}", jobSpec.getJobToken(), ddbConfig.getSchedulesTableName()); metrics.deleteDispatchedJob(jobSpec.getQueueName()); } }) .thenApply(response -> null); } @Override public void close() { ddbClient.close(); } }
5,618
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/heartbeat/HeartbeatManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.heartbeat; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import io.dropwizard.lifecycle.Managed; import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.inject.Inject; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @AllArgsConstructor(onConstructor = @__(@Inject)) public class HeartbeatManager implements Managed { private static final long EXECUTOR_TIMEOUT_SECONDS = 15; private final ConcurrentHashMap<Integer, Long> checkIns; private final ScheduledExecutorService executorService; private final EventBus eventBus; private final Clock clock; private final HeartbeatConfiguration heartbeatConfiguration; @Override public void start() { log.info("Attempting to start heartbeat"); executorService.scheduleWithFixedDelay( this::scanMap, 0, heartbeatConfiguration.getMonitorInterval(), TimeUnit.MILLISECONDS); log.info("Started heartbeat"); } @Override public void stop() { log.info("Stopping heartbeat"); executorService.shutdown(); eventBus.unregister(this); try { if (!executorService.awaitTermination(EXECUTOR_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException ex) { throw new RuntimeException(); } log.info("Stopped heartbeat"); } @Subscribe public void workerCheckIn(PartitionWorkerIterationEvent iterationEvent) { log.debug( "Checking in index {} at time {}", iterationEvent.getIndex(), iterationEvent.getTimestamp()); checkIns.put(iterationEvent.getIndex(), iterationEvent.getTimestamp()); } private void scanMap() { long now = Instant.now(clock).toEpochMilli(); List<Integer> stalled = checkIns .entrySet() .stream() .filter(entry -> entry.getValue() < now - heartbeatConfiguration.getStallTolerance()) .map(Entry::getKey) .collect(Collectors.toList()); if (stalled.size() > 0) { eventBus.post(new PartitionWorkerStalledEvent(stalled)); } log.debug("Completed scanning PartitionWorker check in times."); } }
5,619
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/heartbeat/HeartbeatConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.heartbeat; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class HeartbeatConfiguration { @JsonProperty("monitorInterval") private int monitorInterval = 1000; @JsonProperty("stallTolerance") private int stallTolerance = 60000; }
5,620
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/heartbeat/PartitionWorkerIterationEvent.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.heartbeat; import lombok.Value; @Value public class PartitionWorkerIterationEvent { private long timestamp; private int index; }
5,621
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/heartbeat/PartitionWorkerStalledEvent.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.heartbeat; import java.util.List; import lombok.Value; @Value public class PartitionWorkerStalledEvent { private List<Integer> stalledWorkers; }
5,622
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/partition/K8SConsecutiveAllocationPolicy.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.partition; import com.airbnb.dynein.scheduler.Constants; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.client.AppsAPIGroupClient; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable; import java.text.Collator; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import lombok.AllArgsConstructor; @AllArgsConstructor(onConstructor = @__(@Inject)) public class K8SConsecutiveAllocationPolicy implements PartitionPolicy { private static final String K8S_CONDITION_READY = "Ready"; private static final String K8S_CONDITION_TRUE = "True"; private final DefaultKubernetesClient kubernetesClient; private final AppsAPIGroupClient appsClient; @Named(Constants.MAX_PARTITIONS) private final Integer numPartitions; public List<Integer> getPartitions() { String podName = System.getenv("K8S_POD_NAME"); String namespace = System.getenv("K8S_NAMESPACE"); NamespacedKubernetesClient namespacedClient = kubernetesClient.inNamespace(namespace); ReplicaSet replicaSet; Pod pod = namespacedClient.pods().withName(podName).get(); String replicaSetName = pod.getMetadata().getOwnerReferences().get(0).getName(); replicaSet = appsClient.replicaSets().inNamespace(namespace).withName(replicaSetName).get(); FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> deploymentPods = namespacedClient.pods().withLabelSelector(replicaSet.getSpec().getSelector()); List<String> activePods = deploymentPods .list() .getItems() .stream() .filter( isActive -> isActive .getStatus() .getConditions() .stream() .anyMatch( condition -> condition.getType().equals(K8S_CONDITION_READY) && condition.getStatus().equals(K8S_CONDITION_TRUE))) .map(it -> it.getMetadata().getName()) .sorted(Collator.getInstance()) .collect(Collectors.toList()); int podIndex = activePods.indexOf(podName); int numPods = activePods.size(); if (numPods == 0 || podIndex == -1) { return new ArrayList<>(); } List<Integer> partitions = new ArrayList<>(); int split = numPartitions / numPods; int start = podIndex * split; int end = (podIndex == numPods - 1) ? numPartitions - 1 : ((podIndex + 1) * split) - 1; for (int i = start; i <= end; i++) { partitions.add(i); } return partitions; } }
5,623
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/partition/PartitionPolicy.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.partition; import java.util.List; public interface PartitionPolicy { List<Integer> getPartitions(); }
5,624
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/partition/StaticAllocationPolicy.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.partition; import java.util.List; import lombok.AllArgsConstructor; @AllArgsConstructor public class StaticAllocationPolicy implements PartitionPolicy { private final List<Integer> staticPartitions; @Override public List<Integer> getPartitions() { return staticPartitions; } }
5,625
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/worker/PartitionWorkerFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.worker; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.conveyor.async.AsyncSqsClientFactory; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.scheduler.Constants; import com.airbnb.dynein.scheduler.ScheduleManagerFactory; import com.airbnb.dynein.scheduler.config.WorkersConfiguration; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.google.common.eventbus.EventBus; import java.time.Clock; import javax.inject.Inject; import javax.inject.Named; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @AllArgsConstructor(onConstructor = @__(@Inject)) @Slf4j public class PartitionWorkerFactory { private final AsyncSqsClientFactory asyncSqsClientFactory; @Named(Constants.SQS_PRODUCER) private final AsyncSqsClientConfiguration asyncSqsClientConfiguration; private final ScheduleManagerFactory scheduleManagerFactory; private final Clock clock; private final JobSpecTransformer jobSpecTransformer; private final WorkersConfiguration workersConfiguration; private final EventBus eventBus; private final Metrics metrics; private AsyncSqsClient getAsyncClient() { return asyncSqsClientFactory.create(asyncSqsClientConfiguration); } public PartitionWorker get(int index) { return new PartitionWorker( index, getAsyncClient(), eventBus, clock, scheduleManagerFactory.get(), jobSpecTransformer, workersConfiguration, metrics); } }
5,626
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/worker/WorkerManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.worker; import com.airbnb.dynein.common.utils.ExecutorUtils; import com.airbnb.dynein.scheduler.heartbeat.PartitionWorkerStalledEvent; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.airbnb.dynein.scheduler.partition.PartitionPolicy; import com.google.common.base.Stopwatch; import com.google.common.eventbus.Subscribe; import io.dropwizard.lifecycle.Managed; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.*; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @AllArgsConstructor(onConstructor = @__(@javax.inject.Inject)) public class WorkerManager implements Managed { private static final long EXECUTOR_TIMEOUT_SECONDS = 15; private final List<PartitionWorker> partitionWorkers; private final PartitionWorkerFactory partitionWorkerFactory; private final ScheduledExecutorService executorService; private ConcurrentHashMap<Integer, List<Integer>> workerIndexToPartitions; private final PartitionPolicy partitionPolicy; private final Metrics metrics; @Override public void start() { log.info("Attempting to start worker"); executorService.scheduleWithFixedDelay(this::updatePartitions, 0, 30, TimeUnit.SECONDS); log.info("Started worker"); } @Override public void stop() { log.info("Stopping worker"); ExecutorUtils.twoPhaseExecutorShutdown(executorService, EXECUTOR_TIMEOUT_SECONDS); log.info("Stopped worker"); } private void updatePartitions() { try { List<Integer> partitions = partitionPolicy.getPartitions(); metrics.countPartitionWorkers(partitionWorkers.size()); Set<Integer> currentPartitions = workerIndexToPartitions .values() .stream() .flatMap(List::stream) .collect(Collectors.toSet()); boolean shouldRecreateWorkers = false; if (!currentPartitions.equals(new HashSet<>(partitions))) { log.info( "I'm working on: {}, previously I'm working on: {}", partitions, currentPartitions); shouldRecreateWorkers = true; } if (partitionWorkers.size() != workerIndexToPartitions.size()) { log.info( "Current number of workers: {} is different from the number of defined workers: {}", partitionWorkers.size(), workerIndexToPartitions.size()); shouldRecreateWorkers = true; } if (shouldRecreateWorkers) { recreateWorkers(partitions); } } catch (Exception exception) { log.error("Unable to update partitions.", exception); metrics.updatePartitionsError(exception); } } private void recreateWorkers(List<Integer> partitions) { log.info("Recreate workers."); Stopwatch stopwatch = Stopwatch.createStarted(); for (PartitionWorker partitionWorker : partitionWorkers) { partitionWorker.shutdownExecutor(); } workerIndexToPartitions = new ConcurrentHashMap<>(); for (int i = 0; i < partitionWorkers.size(); i++) { workerIndexToPartitions.put(i, new ArrayList<>()); } for (int i = 0; i < partitions.size(); i++) { int partitionWorkerIndex = i % partitionWorkers.size(); workerIndexToPartitions.get(partitionWorkerIndex).add(partitions.get(i)); } log.info("Starting partition workers."); for (int i = 0; i < partitionWorkers.size(); i++) { List<Integer> thisWorkerPartitions = workerIndexToPartitions.get(i); if (!thisWorkerPartitions.isEmpty()) { partitionWorkers.get(i).start(thisWorkerPartitions); } } log.info("Partitions successfully updated."); long time = stopwatch.elapsed(TimeUnit.NANOSECONDS); metrics.updatePartitions(time); metrics.countPartitionWorkers(partitionWorkers.size()); } @Subscribe public void restartStalledWorkers(PartitionWorkerStalledEvent stalledEvent) { stalledEvent .getStalledWorkers() .forEach( workerId -> { partitionWorkers.get(workerId).shutdownExecutor(); PartitionWorker newWorker = partitionWorkerFactory.get(workerId); partitionWorkers.set(workerId, newWorker); newWorker.start(workerIndexToPartitions.get(workerId)); log.info("Restarted PartitionWorker with index {}", workerId); metrics.restartWorker(workerId); }); metrics.countPartitionWorkers(partitionWorkers.size()); } }
5,627
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/worker/PartitionWorker.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.worker; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.utils.ExecutorUtils; import com.airbnb.dynein.scheduler.Constants; import com.airbnb.dynein.scheduler.Schedule; import com.airbnb.dynein.scheduler.ScheduleManager; import com.airbnb.dynein.scheduler.config.WorkersConfiguration; import com.airbnb.dynein.scheduler.heartbeat.PartitionWorkerIterationEvent; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.google.common.base.Stopwatch; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.concurrent.*; import javax.inject.Inject; import javax.inject.Named; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class PartitionWorker { private static final long EXECUTOR_TIMEOUT_SECONDS = 5; private final int index; @Named(Constants.SQS_PRODUCER) private final AsyncSqsClient asyncSqsClient; private final EventBus eventBus; private final Clock clock; private final ScheduleManager scheduleManager; private final JobSpecTransformer jobSpecTransformer; private final WorkersConfiguration workersConfiguration; private final Metrics metrics; private ScheduledExecutorService executorService = null; private ConcurrentHashMap<Integer, Long> scanTimes = null; CompletableFuture<Void> dispatchToDestination(Schedule schedule) { Stopwatch stopwatch = Stopwatch.createStarted(); CompletableFuture<Void> ret = new CompletableFuture<>(); DyneinJobSpec jobSpec = jobSpecTransformer.deserializeJobSpec(schedule.getJobSpec()); asyncSqsClient .add(schedule.getJobSpec(), jobSpec.getQueueName()) .whenCompleteAsync( (it, ex) -> { if (ex != null) { log.error( "Error dispatching job {} to destination queue {}", jobSpec.getJobToken(), jobSpec.getQueueName(), ex); metrics.dispatchJobError(ex, jobSpec.getQueueName()); scheduleManager .updateStatus( schedule, Schedule.JobStatus.ACQUIRED, Schedule.JobStatus.SCHEDULED) .whenComplete((response, exception) -> ret.completeExceptionally(ex)); } else { log.info( "Dispatched job {} to destination queue {}", jobSpec.getJobToken(), jobSpec.getQueueName()); long time = stopwatch.elapsed(TimeUnit.NANOSECONDS); metrics.dispatchScheduledJob(time, jobSpec, schedule.getShardId()); scheduleManager .deleteDispatchedJob(schedule) .whenComplete((response, exception) -> ret.complete(null)); } }, executorService); return ret; } /* * dispatchOverdue: queries the DynamoDB for any overdue jobs in partition partition * returns: true if the number of overdue jobs returned is equal to queryLimit (configurable) * or if the query response hit its memory limit (1MB), signifying the need to query for overdue jobs * again immediately. Otherwise returns false, meaning that it should be safe to resume querying * after a short delay. */ CompletableFuture<Boolean> dispatchOverdue(String partition) { Stopwatch stopwatch = Stopwatch.createStarted(); CompletableFuture<Boolean> ret = new CompletableFuture<>(); scheduleManager .getOverdueJobs(partition) .whenCompleteAsync( (res, ex) -> { if (ex != null) { log.error("Error querying overdue jobs for partition {}", partition, ex); metrics.queryOverdueError(ex, partition); ret.complete(true); } else { metrics.queryOverdue(partition); CompletableFuture.allOf( res.getSchedules() .stream() .map( schedule -> scheduleManager .updateStatus( schedule, Schedule.JobStatus.SCHEDULED, Schedule.JobStatus.ACQUIRED) .thenCompose(this::dispatchToDestination)) .toArray(CompletableFuture[]::new)) .whenCompleteAsync( (it, exception) -> { // explicitly don't handle any exceptions here because: // - acquire errors are harmless, // either CAS exception or will be picked up by the next iteration // - dispatch errors are harmless, // - dispatch to SQS failures will be set back to ACQUIRED // - set back to ACQUIRED failures will be picked up by fix stuck jobs ret.complete(res.isShouldImmediatelyQueryAgain()); long time = stopwatch.elapsed(TimeUnit.NANOSECONDS); log.debug("Dispatched overdue jobs for partition {}", partition); metrics.dispatchOverdue(time, partition); }, executorService); } }, executorService); return ret; } private void scanGroup(List<Integer> partitions) { if (executorService == null || executorService.isShutdown()) { log.info( "Partition worker has stopped scanning assigned partitions {}", partitions.toString()); return; } boolean noDelay = false; // Stopwatch stopwatch = Stopwatch.createStarted(); for (Integer partition : partitions) { Long now = Instant.now(clock).toEpochMilli(); if (scanTimes.get(partition) < now) { boolean thisNoDelay = dispatchOverdue(partition.toString()) .whenCompleteAsync( (scheduleImmediate, exception) -> { long nextScan = Instant.now(clock).toEpochMilli(); if (!scheduleImmediate) { nextScan += 1000L; log.debug( "Next scan of partition {} delayed by a minimum of 1s", partition); } scanTimes.put(partition, nextScan); }, executorService) .join(); noDelay = noDelay || thisNoDelay; } else { // if a partition was skipped this iteration, we shouldn't delay next call to scanGroup() noDelay = true; } } eventBus.post(new PartitionWorkerIterationEvent(Instant.now(clock).toEpochMilli(), index)); // long time = stopwatch.elapsed(TimeUnit.NANOSECONDS); log.debug("Iteration over partitions {} complete", partitions); // TODO(andy-fang): figure out what to do with this metric. // we likely still want to track this, but it currently causes datadog-agent OOM // metrics.iterationComplete(time); if (noDelay) { executorService.submit(() -> scanGroup(partitions)); } else { log.info("Next iteration of partitions {} delayed by 1s", partitions); executorService.schedule(() -> scanGroup(partitions), 1000L, TimeUnit.MILLISECONDS); } } CompletableFuture<Void> recoverStuckJobs(List<Integer> partitions, long lookAheadMs) { log.info( "Recovering stuck jobs for partitions {} with lookAheadMs: {}", partitions, lookAheadMs); CompletableFuture<Void> allDone = CompletableFuture.completedFuture(null); for (int partition : partitions) { allDone = allDone .thenRun( () -> scheduleManager.recoverStuckJobs( String.valueOf(partition), Instant.now(clock).plusMillis(lookAheadMs))) .exceptionally( e -> { log.error("Failed to recover stuck job for partition {}", partition, e); metrics.recoverStuckJobsError(String.valueOf(partition)); return null; // suppress exceptions to unblock future actions }); } return allDone; } CompletableFuture<Void> recoverStuckJobs(List<Integer> partitions) { return recoverStuckJobs(partitions, workersConfiguration.getRecoverStuckJobsLookAheadMs()); } void start(List<Integer> partitions) { long currentMillis = Instant.now(clock).toEpochMilli(); startExecutor(); partitions.forEach(partition -> scanTimes.put(partition, currentMillis)); executorService.submit( () -> { log.info("Recovering stuck jobs during initial boot"); recoverStuckJobs(partitions) .whenCompleteAsync((result, ex) -> scanGroup(partitions), executorService); }); executorService.scheduleAtFixedRate( () -> { log.info( "Recovering stuck jobs at least {} ms old for partitions: {}", workersConfiguration.getRecoverStuckJobsLookAheadMs(), partitions); recoverStuckJobs(partitions, -workersConfiguration.getRecoverStuckJobsLookAheadMs()) .join(); log.info("Regular stuck job recovery done."); }, workersConfiguration.getRecoverStuckJobsLookAheadMs(), workersConfiguration.getRecoverStuckJobsLookAheadMs(), TimeUnit.MILLISECONDS); } void shutdownExecutor() { if (executorService != null && !executorService.isShutdown()) { ExecutorUtils.twoPhaseExecutorShutdown(executorService, EXECUTOR_TIMEOUT_SECONDS); } } void startExecutor() { scanTimes = new ConcurrentHashMap<>(); executorService = MoreExecutors.getExitingScheduledExecutorService( (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool( workersConfiguration.getThreadPoolSize(), new ThreadFactoryBuilder() .setNameFormat("partition-worker-" + index + "-%s") .build())); log.info("New ExecutorService has been created."); } }
5,628
0
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler
Create_ds/dynein/dynein/src/main/java/com/airbnb/dynein/scheduler/modules/SchedulerModule.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.scheduler.modules; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.conveyor.async.AsyncSqsClientFactory; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.conveyor.async.config.OverrideConfiguration; import com.airbnb.conveyor.async.config.RetryPolicyConfiguration; import com.airbnb.conveyor.async.metrics.AsyncConveyorMetrics; import com.airbnb.conveyor.async.metrics.NoOpConveyorMetrics; import com.airbnb.dynein.common.job.JacksonJobSpecTransformer; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.token.JacksonTokenManager; import com.airbnb.dynein.common.token.TokenManager; import com.airbnb.dynein.scheduler.Constants; import com.airbnb.dynein.scheduler.ManagedInboundJobQueueConsumer; import com.airbnb.dynein.scheduler.ScheduleManager; import com.airbnb.dynein.scheduler.ScheduleManagerFactory; import com.airbnb.dynein.scheduler.config.DynamoDBConfiguration; import com.airbnb.dynein.scheduler.config.SQSConfiguration; import com.airbnb.dynein.scheduler.config.SchedulerConfiguration; import com.airbnb.dynein.scheduler.config.WorkersConfiguration; import com.airbnb.dynein.scheduler.dynamodb.DynamoDBScheduleManagerFactory; import com.airbnb.dynein.scheduler.heartbeat.HeartbeatConfiguration; import com.airbnb.dynein.scheduler.heartbeat.HeartbeatManager; import com.airbnb.dynein.scheduler.metrics.Metrics; import com.airbnb.dynein.scheduler.metrics.NoOpMetricsImpl; import com.airbnb.dynein.scheduler.partition.K8SConsecutiveAllocationPolicy; import com.airbnb.dynein.scheduler.partition.PartitionPolicy; import com.airbnb.dynein.scheduler.partition.StaticAllocationPolicy; import com.airbnb.dynein.scheduler.worker.PartitionWorker; import com.airbnb.dynein.scheduler.worker.PartitionWorkerFactory; import com.airbnb.dynein.scheduler.worker.WorkerManager; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.name.Names; import java.time.Clock; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import javax.inject.Named; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; @Slf4j public class SchedulerModule extends AbstractModule { private final SchedulerConfiguration schedulerConfiguration; private final DynamoDBConfiguration dynamoDBConfiguration; private final SQSConfiguration sqsConfiguration; private final HeartbeatConfiguration heartbeatConfiguration; private final WorkersConfiguration workersConfiguration; public SchedulerModule(SchedulerConfiguration schedulerConfiguration) { this.schedulerConfiguration = schedulerConfiguration; this.dynamoDBConfiguration = schedulerConfiguration.getDynamoDb(); this.sqsConfiguration = schedulerConfiguration.getSqs(); this.heartbeatConfiguration = schedulerConfiguration.getHeartbeat(); this.workersConfiguration = schedulerConfiguration.getWorkers(); } @Override protected void configure() { bind(Clock.class).toInstance(Clock.systemUTC()); bind(WorkersConfiguration.class).toInstance(workersConfiguration); bind(DynamoDBConfiguration.class).toInstance(dynamoDBConfiguration); bind(Integer.class) .annotatedWith(Names.named(Constants.MAX_PARTITIONS)) .toInstance(schedulerConfiguration.getMaxPartitions()); bind(String.class) .annotatedWith(Names.named(Constants.INBOUND_QUEUE_NAME)) .toInstance(sqsConfiguration.getInboundQueueName()); bind(DynamoDBScheduleManagerFactory.class).asEagerSingleton(); bind(ScheduleManagerFactory.class).to(DynamoDBScheduleManagerFactory.class).asEagerSingleton(); bind(ScheduleManager.class).toProvider(ScheduleManagerFactory.class).asEagerSingleton(); bind(EventBus.class).toInstance(new EventBus()); switch (workersConfiguration.getPartitionPolicy()) { case K8S: { bind(K8SConsecutiveAllocationPolicy.class).asEagerSingleton(); bind(PartitionPolicy.class).to(K8SConsecutiveAllocationPolicy.class); break; } case STATIC: { bind(PartitionPolicy.class) .toInstance( new StaticAllocationPolicy(workersConfiguration.getStaticPartitionList())); break; } } bind(Metrics.class).to(NoOpMetricsImpl.class).asEagerSingleton(); bind(AsyncConveyorMetrics.class).to(NoOpConveyorMetrics.class).asEagerSingleton(); bind(JobSpecTransformer.class).to(JacksonJobSpecTransformer.class).asEagerSingleton(); bind(TokenManager.class).to(JacksonTokenManager.class).asEagerSingleton(); } @Provides public DynamoDbAsyncClient providesDdbAsyncClient() { return DynamoDbAsyncClient.builder() .endpointOverride(dynamoDBConfiguration.getEndpoint()) .build(); } @Provides @Singleton public ManagedInboundJobQueueConsumer providesManagedInboundJobQueueConsumer( @Named(Constants.SQS_CONSUMER) AsyncSqsClient asyncClient, ScheduleManager scheduleManager) { return new ManagedInboundJobQueueConsumer( asyncClient, MoreExecutors.getExitingExecutorService( (ThreadPoolExecutor) Executors.newFixedThreadPool( 1, new ThreadFactoryBuilder().setNameFormat("inbound-consumer-%d").build())), scheduleManager, sqsConfiguration.getInboundQueueName()); } private AsyncSqsClientConfiguration buildBaseSqsConfig() { AsyncSqsClientConfiguration asyncSqsConfig = new AsyncSqsClientConfiguration(AsyncSqsClientConfiguration.Type.PRODUCTION); asyncSqsConfig.setRegion(sqsConfiguration.getRegion()); asyncSqsConfig.setEndpoint(sqsConfiguration.getEndpoint()); return asyncSqsConfig; } @Provides @Named(Constants.SQS_CONSUMER) AsyncSqsClientConfiguration provideConsumerSqsConfig() { return buildBaseSqsConfig(); } @Provides @Named(Constants.SQS_PRODUCER) AsyncSqsClientConfiguration provideProducerSqsConfig() { AsyncSqsClientConfiguration asyncSqsConfig = buildBaseSqsConfig(); RetryPolicyConfiguration retryConfig = new RetryPolicyConfiguration(); retryConfig.setPolicy(RetryPolicyConfiguration.Policy.CUSTOM); retryConfig.setCondition(RetryPolicyConfiguration.Condition.DEFAULT); retryConfig.setBackOff(RetryPolicyConfiguration.BackOff.EQUAL_JITTER); retryConfig.setMaximumBackoffTime(sqsConfiguration.getTimeouts().getMaxBackoffTime()); retryConfig.setBaseDelay(sqsConfiguration.getTimeouts().getBaseDelay()); OverrideConfiguration overrideConfig = new OverrideConfiguration(); overrideConfig.setApiCallAttemptTimeout( sqsConfiguration.getTimeouts().getApiCallAttemptTimeout()); overrideConfig.setApiCallTimeout(sqsConfiguration.getTimeouts().getApiCallTimeout()); overrideConfig.setRetryPolicyConfiguration(retryConfig); asyncSqsConfig.setOverrideConfiguration(overrideConfig); return asyncSqsConfig; } @Provides @Singleton @Named(Constants.SQS_CONSUMER) public AsyncSqsClient provideAsyncConsumer( AsyncSqsClientFactory asyncSqsClientFactory, @Named(Constants.SQS_CONSUMER) AsyncSqsClientConfiguration asyncSqsClientConfiguration) { return asyncSqsClientFactory.create(asyncSqsClientConfiguration); } @Provides @Singleton @Named(Constants.SQS_PRODUCER) public AsyncSqsClient provideAsyncProducer( AsyncSqsClientFactory asyncSqsClientFactory, @Named(Constants.SQS_PRODUCER) AsyncSqsClientConfiguration asyncSqsClientConfiguration) { return asyncSqsClientFactory.create(asyncSqsClientConfiguration); } @Provides @Singleton public HeartbeatManager provideHeartBeat(EventBus eventBus, Clock clock) { HeartbeatManager heartbeatManager = new HeartbeatManager( new ConcurrentHashMap<>(), MoreExecutors.getExitingScheduledExecutorService( (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool( 1, new ThreadFactoryBuilder().setNameFormat("heartbeat-manager-%d").build())), eventBus, clock, heartbeatConfiguration); eventBus.register(heartbeatManager); return heartbeatManager; } @Provides @Singleton public WorkerManager provideWorkerManager( PartitionWorkerFactory factory, EventBus eventBus, Metrics metrics, PartitionPolicy policy) { List<PartitionWorker> partitionWorkers = new ArrayList<>(); for (int i = 0; i < workersConfiguration.getNumberOfWorkers(); i++) { partitionWorkers.add(factory.get(i)); } WorkerManager manager = new WorkerManager( partitionWorkers, factory, MoreExecutors.getExitingScheduledExecutorService( (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool( 1, new ThreadFactoryBuilder().setNameFormat("worker-manager-%d").build())), new ConcurrentHashMap<>(), policy, metrics); eventBus.register(manager); return manager; } }
5,629
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/ExampleConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example; import com.airbnb.dynein.scheduler.config.SchedulerConfiguration; import io.dropwizard.Configuration; import lombok.Data; @Data public class ExampleConfiguration extends Configuration { SchedulerConfiguration scheduler; String jobQueue; }
5,630
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/DyneinExampleApplication.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example; import com.airbnb.dynein.example.worker.ManagedWorker; import com.airbnb.dynein.scheduler.ManagedInboundJobQueueConsumer; import com.airbnb.dynein.scheduler.modules.SchedulerModule; import com.airbnb.dynein.scheduler.worker.WorkerManager; import com.google.inject.Guice; import com.google.inject.Injector; import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; public class DyneinExampleApplication extends Application<ExampleConfiguration> { public static void main(String[] args) throws Exception { new DyneinExampleApplication().run(args); } @Override public String getName() { return "hello-world"; } @Override public void initialize(Bootstrap<ExampleConfiguration> bootstrap) {} @Override public void run(ExampleConfiguration configuration, Environment environment) { Injector injector = Guice.createInjector( new SchedulerModule(configuration.getScheduler()), new ExampleModule(configuration)); final ExampleResource resource = injector.getInstance(ExampleResource.class); environment.jersey().register(resource); // worker that executes the jobs environment.lifecycle().manage(injector.getInstance(ManagedWorker.class)); // worker that fetches jobs from inbound queue environment.lifecycle().manage(injector.getInstance(ManagedInboundJobQueueConsumer.class)); // worker that executes schedules from dynamodb environment.lifecycle().manage(injector.getInstance(WorkerManager.class)); } }
5,631
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/ExampleModule.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example; import com.google.inject.AbstractModule; import com.google.inject.name.Names; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class ExampleModule extends AbstractModule { private final ExampleConfiguration configuration; @Override protected void configure() { bind(String.class) .annotatedWith(Names.named("jobQueue")) .toInstance(configuration.getJobQueue()); bind(ExecutorService.class) .annotatedWith(Names.named("workerExecutor")) .toInstance(Executors.newSingleThreadExecutor()); } }
5,632
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/ExampleResource.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.api.JobSchedulePolicy; import com.airbnb.dynein.api.JobScheduleType; import com.airbnb.dynein.api.PrepareJobRequest; import com.airbnb.dynein.example.api.ScheduleJobResponse; import com.airbnb.dynein.scheduler.Scheduler; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Clock; import java.time.Instant; import java.util.Optional; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.MediaType; import lombok.RequiredArgsConstructor; import org.glassfish.jersey.server.ManagedAsync; @Path("/schedule") @Produces(MediaType.APPLICATION_JSON) @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class ExampleResource { private final Scheduler scheduler; private final Clock clock; private final ObjectMapper objectMapper; @Named("jobQueue") private final String jobQueue; private void scheduleJob( Optional<String> name, Optional<Integer> delaySeconds, JobScheduleType scheduleType, AsyncResponse asyncResponse) { try { Instant now = Instant.now(clock); JobSchedulePolicy policy = JobSchedulePolicy.builder() .type(scheduleType) .epochMillis(now.plusSeconds(delaySeconds.orElse(10)).toEpochMilli()) .build(); String token = scheduler.prepareJob(PrepareJobRequest.builder().schedulePolicy(policy).build()); scheduler .createJob( DyneinJobSpec.builder() .createAtInMillis(now.toEpochMilli()) .queueName(jobQueue) .jobToken(token) .name(ExampleJob.class.getName()) .serializedJob(objectMapper.writeValueAsBytes(name.orElse("default-name"))) .schedulePolicy(policy) .build()) .whenComplete( (response, e) -> { if (e != null) { asyncResponse.resume(e); } else { asyncResponse.resume(new ScheduleJobResponse(token)); } }); } catch (Exception e) { asyncResponse.resume(e); } } @GET @Path("/sqs-delayed") @Timed @ManagedAsync public void scheduleSqsDelayed( @QueryParam("name") Optional<String> name, @QueryParam("delaySeconds") Optional<Integer> delaySeconds, @Suspended final AsyncResponse asyncResponse) { scheduleJob(name, delaySeconds, JobScheduleType.SQS_DELAYED, asyncResponse); } @GET @Path("/immediate") @Timed @ManagedAsync public void scheduleImmediate( @QueryParam("name") Optional<String> name, @QueryParam("delaySeconds") Optional<Integer> delaySeconds, @Suspended final AsyncResponse asyncResponse) { scheduleJob(name, Optional.of(0), JobScheduleType.IMMEDIATE, asyncResponse); } @GET @Path("/scheduled") @Timed @ManagedAsync public void scheduleScheduled( @QueryParam("name") Optional<String> name, @QueryParam("delaySeconds") Optional<Integer> delaySeconds, @Suspended final AsyncResponse asyncResponse) { scheduleJob(name, delaySeconds, JobScheduleType.SCHEDULED, asyncResponse); } }
5,633
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/ExampleJob.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public class ExampleJob { private final String name; public void run() { log.info("Running job with name: {}", name); } }
5,634
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/api/ScheduleJobResponse.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example.api; import lombok.Value; @Value public class ScheduleJobResponse { String token; }
5,635
0
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example
Create_ds/dynein/example/src/main/java/com/airbnb/dynein/example/worker/ManagedWorker.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.example.worker; import com.airbnb.conveyor.async.AsyncConsumer; import com.airbnb.conveyor.async.AsyncSqsClient; import com.airbnb.dynein.common.job.JobSpecTransformer; import com.airbnb.dynein.common.utils.ExecutorUtils; import com.airbnb.dynein.example.ExampleJob; import com.airbnb.dynein.scheduler.Constants; import io.dropwizard.lifecycle.Managed; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import javax.inject.Inject; import javax.inject.Named; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RequiredArgsConstructor(onConstructor = @__(@Inject)) @Slf4j public class ManagedWorker implements Managed { private static final long EXECUTOR_TIMEOUT_SECONDS = 15; @Named(Constants.SQS_CONSUMER) private final AsyncSqsClient asyncClient; @Named("workerExecutor") private final ExecutorService executorService; private final JobSpecTransformer transformer; @Named("jobQueue") private final String queueName; @Override public void start() { log.info("Starting to consume from job queue {}", queueName); executorService.execute(this::run); log.info("Started consuming from job queue {}", queueName); } @Override public void stop() { log.info("Stopping consumption from job queue {}", queueName); ExecutorUtils.twoPhaseExecutorShutdown(executorService, EXECUTOR_TIMEOUT_SECONDS); log.info("Stopped consumption from job queue {}", queueName); } private void run() { while (!executorService.isShutdown()) { doRun(); } } private void doRun() { AsyncConsumer<String> consumer = (message, executor) -> CompletableFuture.runAsync( () -> new ExampleJob( new String(transformer.deserializeJobSpec(message).getSerializedJob())) .run(), executor); asyncClient .consume(consumer, queueName) .whenComplete( (it, ex) -> { if (ex != null) { log.error("Error consuming from queue {}", queueName, ex); } else if (!it) { log.debug("Job queue {} is empty", queueName); } else { log.info("Successfully consumed job from queue"); } }); } }
5,636
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/token/TokenManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.token; import com.airbnb.dynein.api.InvalidTokenException; import com.airbnb.dynein.api.JobTokenPayload; public interface TokenManager { short MAX_LOGICAL_SHARD = 1024; void validateToken(final String token) throws InvalidTokenException; JobTokenPayload decodeToken(String token) throws InvalidTokenException; String generateToken(final long associatedId, String logicalCluster, Long epochMillis); }
5,637
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/token/JacksonTokenManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.token; import com.airbnb.dynein.api.InvalidTokenException; import com.airbnb.dynein.api.JobTokenPayload; import com.airbnb.dynein.common.utils.UuidUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.util.UUID; import javax.inject.Inject; import lombok.AllArgsConstructor; @AllArgsConstructor(onConstructor = @__(@Inject)) public class JacksonTokenManager implements TokenManager { private ObjectMapper objectMapper; @Override public void validateToken(String token) throws InvalidTokenException { decodeToken(token); } @Override public JobTokenPayload decodeToken(String token) throws InvalidTokenException { try { return objectMapper.readValue(BaseEncoding.base64Url().decode(token), JobTokenPayload.class); } catch (IOException e) { throw new InvalidTokenException(e); } } @Override public String generateToken(long associatedId, String logicalCluster, Long epochMillis) { UUID uuid = UUID.randomUUID(); JobTokenPayload payload = JobTokenPayload.builder() .logicalShard((short) Math.floorMod(associatedId, MAX_LOGICAL_SHARD)) .logicalCluster(logicalCluster) .epochMillis(epochMillis) .uuid(UuidUtils.byteArrayFromUuid(uuid)) .build(); try { return BaseEncoding.base64Url().encode(objectMapper.writeValueAsBytes(payload)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
5,638
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/utils/UuidUtils.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.utils; import java.nio.ByteBuffer; import java.util.UUID; import lombok.experimental.UtilityClass; @UtilityClass public class UuidUtils { public byte[] byteArrayFromUuid(UUID uuid) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES * 2); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); return buffer.array(); } public UUID uuidFromByteArray(byte[] byteArray) { ByteBuffer buffer = ByteBuffer.wrap(byteArray); return new UUID(buffer.getLong(), buffer.getLong()); } }
5,639
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/utils/ExecutorUtils.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.utils; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; @Slf4j @UtilityClass public class ExecutorUtils { // adapted from the example in // https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html public void twoPhaseExecutorShutdown(ExecutorService executor, long timeoutSeconds) { log.info("attempting to shutdown executor {}", executor); executor.shutdown(); // reject new task submission try { if (!executor.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) { executor.shutdownNow(); // cancel currently running tasks if (!executor.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) { log.error("Executor did not terminate"); } } } catch (InterruptedException ex) { log.warn("interrupted while attempting to shutdown {}", executor); // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } log.info("successfully shutdown executor {}", executor); } }
5,640
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/utils/TimeUtils.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.utils; import com.airbnb.dynein.api.JobSchedulePolicy; import com.airbnb.dynein.api.JobScheduleType; import com.google.common.base.Preconditions; import java.time.Clock; import java.time.Duration; import java.time.Instant; import lombok.experimental.UtilityClass; @UtilityClass public class TimeUtils { private static IllegalStateException memberMissingException = new IllegalStateException("At least one of `epochMillis` or `delayMillis` must be present."); public long getDelayMillis(JobSchedulePolicy policy, Clock clock) { return policy .getDelayMillisOptional() .orElseGet( () -> policy .getEpochMillisOptional() .map(epoch -> epoch - Instant.now(clock).toEpochMilli()) .orElseThrow(() -> memberMissingException)); } public Instant getInstant(JobSchedulePolicy policy, Clock clock) { return policy .getEpochMillisOptional() .map(Instant::ofEpochMilli) .orElseGet( () -> policy .getDelayMillisOptional() .map(delay -> Instant.now(clock).plusMillis(delay)) .orElseThrow(() -> memberMissingException)); } public JobSchedulePolicy getPreferredSchedulePolicy(Duration delay, Clock clock) { Preconditions.checkArgument( !delay.isNegative(), "Scheduled Delay should be positive, got %s", delay); if (delay.equals(Duration.ZERO)) { return getSchedulePolicyWithEpochMillis(delay, JobScheduleType.IMMEDIATE, clock); } else if (delay.minus(Duration.ofMinutes(15)).isNegative()) { return getSchedulePolicyWithEpochMillis(delay, JobScheduleType.SQS_DELAYED, clock); } else { return getSchedulePolicyWithEpochMillis(delay, JobScheduleType.SCHEDULED, clock); } } public JobSchedulePolicy getSchedulePolicyWithEpochMillis( Duration delay, JobScheduleType scheduleType, Clock clock) { return JobSchedulePolicy.builder() .epochMillis(Instant.now(clock).plus(delay).toEpochMilli()) .type(scheduleType) .build(); } }
5,641
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/exceptions/DyneinClientException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.exceptions; import lombok.NonNull; abstract class DyneinClientException extends RuntimeException { private static final long serialVersionUID = 5899411497145720750L; DyneinClientException(@NonNull final String message, @NonNull final Throwable cause) { super(message, cause); } }
5,642
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/exceptions/JobSerializationException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.exceptions; import lombok.NonNull; public final class JobSerializationException extends DyneinClientException { private static final long serialVersionUID = -2698580362128340580L; public JobSerializationException(@NonNull final String message, @NonNull final Throwable cause) { super(message, cause); } }
5,643
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/exceptions/JobDeserializationException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.exceptions; import lombok.NonNull; public final class JobDeserializationException extends DyneinClientException { private static final long serialVersionUID = 6333070716140128729L; public JobDeserializationException( @NonNull final String message, @NonNull final Throwable cause) { super(message, cause); } }
5,644
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/job/JacksonJobSpecTransformer.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.job; import com.airbnb.dynein.api.DyneinJobSpec; import com.airbnb.dynein.common.exceptions.JobDeserializationException; import com.airbnb.dynein.common.exceptions.JobSerializationException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class JacksonJobSpecTransformer implements JobSpecTransformer { private final ObjectMapper objectMapper; public String serializeJobSpec(final DyneinJobSpec jobSpec) { try { log.debug("Serializing DyneinJobSpec {}.", jobSpec); return objectMapper.writeValueAsString(jobSpec); } catch (Exception ex) { log.error("Failed to serializeJobData job spec"); throw new JobSerializationException("Failed to serializeJobData job spec.", ex); } } public DyneinJobSpec deserializeJobSpec(final String data) { try { log.debug("Deserializing job data."); return objectMapper.readValue(data, DyneinJobSpec.class); } catch (Exception ex) { log.error("Failed to deserializeJobData job data.", ex); throw new JobDeserializationException("Failed to deserializeJobData job data.", ex); } } }
5,645
0
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common
Create_ds/dynein/dynein-common/src/main/java/com/airbnb/dynein/common/job/JobSpecTransformer.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.common.job; import com.airbnb.dynein.api.DyneinJobSpec; public interface JobSpecTransformer { String serializeJobSpec(final DyneinJobSpec jobSpec); DyneinJobSpec deserializeJobSpec(final String data); }
5,646
0
Create_ds/dynein/conveyor/src/test/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/test/java/com/airbnb/conveyor/async/MockAsyncSqsClientTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import static org.junit.Assert.*; import com.airbnb.conveyor.async.mock.MockAsyncSqsClient; import com.google.common.collect.ImmutableSet; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import org.junit.Test; public class MockAsyncSqsClientTest { private static final String QUEUE_NAME = "test"; @Test public void testAdd() { AsyncSqsClient queue = new MockAsyncSqsClient(); Set<String> messages = ImmutableSet.of("hello", "there"); messages.forEach((msg) -> queue.add(msg, QUEUE_NAME)); Set<String> receivedMessages = new HashSet<>(); queue.consume(receivedMessages::add, QUEUE_NAME).join(); queue.consume(receivedMessages::add, QUEUE_NAME).join(); assertEquals(messages, receivedMessages); } @Test public void testAddWithDelay() { AsyncSqsClient queue = new MockAsyncSqsClient(); Set<String> messages = ImmutableSet.of("hello"); queue.add("hello", QUEUE_NAME, 5).join(); Set<String> receivedMessages = new HashSet<>(); assertTrue(queue.consume(receivedMessages::add, QUEUE_NAME).join()); assertEquals(messages, receivedMessages); } @Test public void testAsyncConsume() { AsyncSqsClient queue = new MockAsyncSqsClient(); Set<String> messages = ImmutableSet.of("hello", "there"); messages.forEach((msg) -> queue.add(msg, QUEUE_NAME)); AsyncConsumer<String> function = (str, threadpool) -> CompletableFuture.completedFuture(null); CompletableFuture<Boolean> result = queue.consume(function, QUEUE_NAME); // testing final result assertTrue(result.join()); } @Test public void testConsumeWithEmptyQueue() { MockAsyncSqsClient emptyQueue = new MockAsyncSqsClient(); AsyncConsumer<String> function = (str, threadpool) -> CompletableFuture.completedFuture(null); CompletableFuture<Boolean> result = emptyQueue.consume(function, "empty"); // testing final result assertFalse(result.join()); } @Test(expected = Exception.class) public void testConsumeCompletion() { AsyncSqsClient queue = new MockAsyncSqsClient(); Set<String> messages = ImmutableSet.of("hello", "there"); messages.forEach((msg) -> queue.add(msg, QUEUE_NAME)); AsyncConsumer<String> function = (str, threadpool) -> { CompletableFuture<Void> ret = new CompletableFuture<>(); ret.completeExceptionally(new Exception()); return ret; }; CompletableFuture<Boolean> result = queue.consume(function, QUEUE_NAME); // testing final result result.join(); } }
5,647
0
Create_ds/dynein/conveyor/src/test/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/test/java/com/airbnb/conveyor/async/AsyncSqsClientImplTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.conveyor.async.metrics.AsyncConveyorMetrics; import com.airbnb.conveyor.async.metrics.NoOpConveyorMetrics; import io.github.resilience4j.bulkhead.BulkheadFullException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.services.sqs.model.*; public class AsyncSqsClientImplTest { private AsyncSqsClient asyncClient; private SqsAsyncClient awsAsyncSqsClient; private ArgumentCaptor<SendMessageRequest> sentRequest; private ThreadPoolExecutor executor; private AsyncConveyorMetrics metrics; @Before public void setUp() { this.awsAsyncSqsClient = Mockito.mock(SqsAsyncClient.class); metrics = new NoOpConveyorMetrics(); executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); asyncClient = new AsyncSqsClientImpl(awsAsyncSqsClient, metrics, executor); } // dummy add to queue private void queueAddSetup() { CompletableFuture<SendMessageResponse> messageResponse = CompletableFuture.completedFuture( SendMessageResponse.builder() .messageId("testId") .sequenceNumber("testSeqNumber") .build()); when(awsAsyncSqsClient.sendMessage(any(SendMessageRequest.class))).thenReturn(messageResponse); } // dummy get from queue private void receiveSetup() { Message message = Message.builder().body("testBody").receiptHandle("testHandle").build(); CompletableFuture<ReceiveMessageResponse> receiveMessage = CompletableFuture.completedFuture( ReceiveMessageResponse.builder() .messages(new ArrayList<>(Arrays.asList(message))) .build()); ReceiveMessageRequest testRequest = ReceiveMessageRequest.builder() .queueUrl("testUrl") .maxNumberOfMessages(1) .waitTimeSeconds(AsyncSqsClientConfiguration.DEFAULT_RECEIVE_WAIT_SECONDS) .build(); when(awsAsyncSqsClient.receiveMessage(testRequest)).thenReturn(receiveMessage); } // dummy queue URL set up private void urlSetup(String queueName, String url) { GetQueueUrlResponse response = GetQueueUrlResponse.builder().queueUrl(url).build(); CompletableFuture<GetQueueUrlResponse> queueUrl = CompletableFuture.completedFuture(response); GetQueueUrlRequest getUrl = GetQueueUrlRequest.builder().queueName(queueName).build(); when(awsAsyncSqsClient.getQueueUrl(getUrl)).thenReturn(queueUrl); } // dummy delete from queue private void deleteSetup() { DeleteMessageRequest deleteReq = DeleteMessageRequest.builder().queueUrl("testUrl").receiptHandle("testHandle").build(); CompletableFuture<DeleteMessageResponse> deleteResponse = CompletableFuture.completedFuture(DeleteMessageResponse.builder().build()); when(awsAsyncSqsClient.deleteMessage(deleteReq)).thenReturn(deleteResponse); } // dummy getQueueUrl failure private void urlFailureSetup(String queueName) { CompletableFuture<GetQueueUrlResponse> queueUrl = new CompletableFuture<>(); queueUrl.completeExceptionally(new Exception("Fake Exception returned by SQS")); GetQueueUrlRequest getUrl = GetQueueUrlRequest.builder().queueName(queueName).build(); when(awsAsyncSqsClient.getQueueUrl(getUrl)).thenReturn(queueUrl); } @Test public void testUrlRequest() { urlSetup("testQueue", "testUrl"); queueAddSetup(); ArgumentCaptor<GetQueueUrlRequest> urlReq = ArgumentCaptor.forClass(GetQueueUrlRequest.class); // add() will call getQueueUrl asyncClient.add("test", "testQueue"); // testing request verify(awsAsyncSqsClient).getQueueUrl(urlReq.capture()); assertEquals(urlReq.getValue().queueName(), "testQueue"); } @Test public void testAdd() { urlSetup("testQueue", "testUrl"); queueAddSetup(); sentRequest = ArgumentCaptor.forClass(SendMessageRequest.class); CompletableFuture<Void> noDelay = asyncClient.add("test", "testQueue"); verify(awsAsyncSqsClient).sendMessage(sentRequest.capture()); assertEquals(sentRequest.getValue().messageBody(), "test"); assertEquals(sentRequest.getValue().queueUrl(), "testUrl"); verify(awsAsyncSqsClient, times(1)).sendMessage(any(SendMessageRequest.class)); assertNull(noDelay.join()); } @Test public void testAddWithDelay() { urlSetup("testQueue", "testUrl"); queueAddSetup(); sentRequest = ArgumentCaptor.forClass(SendMessageRequest.class); CompletableFuture<Void> delay = asyncClient.add("test", "testQueue", 10); verify(awsAsyncSqsClient).sendMessage(sentRequest.capture()); assertEquals(sentRequest.getValue().messageBody(), "test"); assertEquals(sentRequest.getValue().queueUrl(), "testUrl"); assertEquals(sentRequest.getValue().delaySeconds(), new Integer(10)); verify(awsAsyncSqsClient, times(1)).sendMessage(any(SendMessageRequest.class)); assertNull(delay.join()); } @Test(expected = Exception.class) public void testConsumeInternalsFailure() { urlSetup("testQueue", "testUrl"); receiveSetup(); // dummy reset visibility ChangeMessageVisibilityRequest changeVisibilityReq = ChangeMessageVisibilityRequest.builder() .queueUrl("testUrl") .receiptHandle("testHandle") .visibilityTimeout(0) .build(); CompletableFuture<ChangeMessageVisibilityResponse> visibilityResponse = CompletableFuture.completedFuture(ChangeMessageVisibilityResponse.builder().build()); when(awsAsyncSqsClient.changeMessageVisibility(changeVisibilityReq)) .thenReturn(visibilityResponse); ArgumentCaptor<ChangeMessageVisibilityRequest> visibilityReq = ArgumentCaptor.forClass(ChangeMessageVisibilityRequest.class); CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new Exception("async consumer completing exceptionally")); AsyncConsumer<String> function = (str, threadpool) -> future; CompletableFuture<Boolean> result = asyncClient.consume(function, "testQueue"); // testing setMessageVisible verify(awsAsyncSqsClient).changeMessageVisibility(visibilityReq.capture()); assertEquals(visibilityReq.getValue().queueUrl(), "testUrl"); assertEquals(visibilityReq.getValue().receiptHandle(), "testHandle"); assertEquals(visibilityReq.getValue().visibilityTimeout(), new Integer(0)); verify(awsAsyncSqsClient, times(1)) .changeMessageVisibility(any(ChangeMessageVisibilityRequest.class)); // testing final result result.join(); } @Test public void testConsumeInternalsSuccess() { urlSetup("testQueue", "testUrl"); receiveSetup(); deleteSetup(); ArgumentCaptor<ReceiveMessageRequest> messageReq = ArgumentCaptor.forClass(ReceiveMessageRequest.class); ArgumentCaptor<DeleteMessageRequest> deleteMessageReq = ArgumentCaptor.forClass(DeleteMessageRequest.class); Consumer<String> function = str -> System.out.println(str); CompletableFuture<Boolean> result = asyncClient.consume(function, "testQueue"); assertTrue(result.join()); // testing getMessage verify(awsAsyncSqsClient).receiveMessage(messageReq.capture()); assertEquals(messageReq.getValue().queueUrl(), "testUrl"); assertEquals(messageReq.getValue().maxNumberOfMessages(), new Integer(1)); assertEquals( messageReq.getValue().waitTimeSeconds(), new Integer(AsyncSqsClientConfiguration.DEFAULT_RECEIVE_WAIT_SECONDS)); verify(awsAsyncSqsClient, times(1)).receiveMessage(any(ReceiveMessageRequest.class)); // testing deleteMessage verify(awsAsyncSqsClient).deleteMessage(deleteMessageReq.capture()); assertEquals(deleteMessageReq.getValue().queueUrl(), "testUrl"); assertEquals(deleteMessageReq.getValue().receiptHandle(), "testHandle"); verify(awsAsyncSqsClient, times(1)).deleteMessage(any(DeleteMessageRequest.class)); } @Test public void testConsumeEmptyQueue() { urlSetup("empty", "emptyUrl"); CompletableFuture<ReceiveMessageResponse> noMessages = CompletableFuture.completedFuture(ReceiveMessageResponse.builder().build()); ReceiveMessageRequest testEmptyRequest = ReceiveMessageRequest.builder() .queueUrl("emptyUrl") .waitTimeSeconds(AsyncSqsClientConfiguration.DEFAULT_RECEIVE_WAIT_SECONDS) .maxNumberOfMessages(1) .build(); when(awsAsyncSqsClient.receiveMessage(testEmptyRequest)).thenReturn(noMessages); Consumer<String> function = str -> System.out.println(str); CompletableFuture<Boolean> response = asyncClient.consume(function, "empty"); verify(awsAsyncSqsClient, times(1)).receiveMessage(any(ReceiveMessageRequest.class)); assertFalse(response.join()); } @Test public void testAsyncConsumeConsumption() { urlSetup("testQueue", "testUrl"); receiveSetup(); deleteSetup(); AsyncConsumer<String> function = (str, threadpool) -> CompletableFuture.completedFuture(null); CompletableFuture<Boolean> result = asyncClient.consume(function, "testQueue"); // testing final result assertTrue(result.join()); } @Test public void testConsumeCompletionWithReceiveFailure() { urlSetup("receiveFailure", "receiveFailureUrl"); CompletableFuture<ReceiveMessageResponse> receiveMessage = new CompletableFuture<>(); receiveMessage.completeExceptionally(new Exception()); ReceiveMessageRequest testRequest = ReceiveMessageRequest.builder() .queueUrl("receiveFailureUrl") .maxNumberOfMessages(1) .waitTimeSeconds(AsyncSqsClientConfiguration.DEFAULT_RECEIVE_WAIT_SECONDS) .build(); when(awsAsyncSqsClient.receiveMessage(testRequest)).thenReturn(receiveMessage); // ensure future is completed when exception in receiveMessage Consumer<String> function = System.out::println; CompletableFuture<Boolean> result = asyncClient.consume(function, "receiveFailure"); try { result.get(1000, TimeUnit.MICROSECONDS); } catch (TimeoutException timeout) { fail("Future does not seem to complete when failure in receiveMessage."); } catch (Exception ex) { } urlFailureSetup("receiveFailure"); // ensure future is completed when exception in get URL within getMessage result = asyncClient.consume(function, "receiveFailure"); try { result.get(1000, TimeUnit.MILLISECONDS); } catch (TimeoutException timeout) { fail("Future does not seem to complete when failure in getQueueUrl within receiveMessage."); } catch (Exception ex) { } } @Test public void testConsumeCompletionWithDeletionFailure() { urlSetup("deletionFailure", "deletionFailureUrl"); receiveSetup(); DeleteMessageRequest deleteReq = DeleteMessageRequest.builder() .queueUrl("deletionFailureUrl") .receiptHandle("deletionHandle") .build(); CompletableFuture<DeleteMessageResponse> deleteResponse = new CompletableFuture<>(); deleteResponse.completeExceptionally(new Exception()); when(awsAsyncSqsClient.deleteMessage(deleteReq)).thenReturn(deleteResponse); // ensure future is completed when exception in deleteMessage Consumer<String> function = System.out::println; CompletableFuture<Boolean> result = asyncClient.consume(function, "deletionFailure"); try { result.get(1000, TimeUnit.MICROSECONDS); } catch (TimeoutException timeout) { fail("Future does not seem to complete when failure in deleteMessage."); } catch (Exception ex) { } urlFailureSetup("deletionFailure"); // ensure future is completed when exception in get URL within deleteMessage result = asyncClient.consume(function, "deletionFailure"); try { result.get(1000, TimeUnit.MILLISECONDS); } catch (TimeoutException timeout) { fail("Future does not seem to complete when failure in getQueueUrl within deleteMessage."); } catch (Exception ex) { } } @Test public void testConsumeCompletionWithChangeVisibilityFailure() { urlSetup("visibilityFailure", "visibilityFailureUrl"); ChangeMessageVisibilityRequest changeVisibilityReq = ChangeMessageVisibilityRequest.builder() .queueUrl("visibilityFailureUrl") .receiptHandle("visibilityFailure") .visibilityTimeout(0) .build(); CompletableFuture<ChangeMessageVisibilityResponse> visibilityResponse = new CompletableFuture<>(); visibilityResponse.completeExceptionally(new Exception()); when(awsAsyncSqsClient.changeMessageVisibility(changeVisibilityReq)) .thenReturn(visibilityResponse); CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new Exception("async consumer completing exceptionally")); AsyncConsumer<String> function = (str, threadpool) -> future; // ensure future is completed when exception in changeMessageVisibility CompletableFuture<Boolean> result = asyncClient.consume(function, "visibilityFailure"); try { result.get(1000, TimeUnit.MICROSECONDS); } catch (TimeoutException timeout) { fail("Future does not seem to complete when failure in changeMessageVisibility."); } catch (Exception ex) { } urlFailureSetup("visibilityFailure"); // ensure future is completed when exception in get URL within changeMessageVisibility result = asyncClient.consume(function, "visibilityFailure"); try { result.get(1000, TimeUnit.MILLISECONDS); } catch (TimeoutException timeout) { fail( "Future does not seem to complete when failure in getQueueUrl within changeMessageVisibility."); } catch (Exception ex) { } } @Test public void testConsumerConcurrency() { asyncClient = new AsyncSqsClientImpl( awsAsyncSqsClient, metrics, executor, 1, AsyncSqsClientConfiguration.DEFAULT_RECEIVE_WAIT_SECONDS, 0, // immediately raise an exception if bulkhead is full 10); urlSetup("testQueue", "testUrl"); receiveSetup(); when(awsAsyncSqsClient.deleteMessage(any(DeleteMessageRequest.class))) .thenReturn(CompletableFuture.completedFuture(DeleteMessageResponse.builder().build())); List<CompletableFuture<Void>> futures = new ArrayList<>(); List<CompletableFuture<Boolean>> consumeFutures = new ArrayList<>(); // occupy all slots in the bulkhead for (int i = 0; i < 10; i++) { CompletableFuture<Void> future = new CompletableFuture<>(); futures.add(future); consumeFutures.add(asyncClient.consume((str, executor) -> future, "testQueue")); } // now, further consume attempts should cause a wait on the semaphore within the bulkhead // however, since we set the max wait ms to 0, calling consume will raise a // BulkheadFullException immediately BulkheadFullException bulkheadFullException = null; try { asyncClient.consume((str, executor) -> new CompletableFuture<>(), "testQueue"); } catch (BulkheadFullException e) { bulkheadFullException = e; } assertNotNull(bulkheadFullException); // free a slot in the bulkhead futures.get(0).complete(null); // now, it should be okay to further consume consumeFutures .get(0) .whenComplete( (r, t) -> asyncClient.consume((str, executor) -> new CompletableFuture<>(), "testQueue")) .join(); } }
5,648
0
Create_ds/dynein/conveyor/src/test/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/test/java/com/airbnb/conveyor/async/AsyncSqsClientFactoryTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.conveyor.async.config.OverrideConfiguration; import com.airbnb.conveyor.async.config.RetryPolicyConfiguration; import com.airbnb.conveyor.async.metrics.NoOpConveyorMetrics; import com.airbnb.conveyor.async.mock.MockAsyncSqsClient; import org.junit.Test; import software.amazon.awssdk.services.sqs.SqsAsyncClient; public class AsyncSqsClientFactoryTest { private static final AsyncSqsClientConfiguration ASYNC_CONFIG = new AsyncSqsClientConfiguration(AsyncSqsClientConfiguration.Type.PRODUCTION); private static final AsyncSqsClientConfiguration LOCAL_CONFIG = new AsyncSqsClientConfiguration(AsyncSqsClientConfiguration.Type.MOCK); private final AsyncSqsClientFactory factory = new AsyncSqsClientFactory(new NoOpConveyorMetrics()); @Test public void testLocal() throws Exception { AsyncSqsClient localQueue = factory.create(LOCAL_CONFIG); assertTrue(localQueue instanceof MockAsyncSqsClient); } @Test public void testAsync() throws Exception { AsyncSqsClient asyncClient = factory.create(ASYNC_CONFIG); assertTrue(asyncClient instanceof AsyncSqsClientImpl); SqsAsyncClient sqs = ((AsyncSqsClientImpl) asyncClient).getClient(); assertNotNull(sqs); } @Test public void testAsyncWithOverrideConfig() throws Exception { AsyncSqsClientConfiguration config = new AsyncSqsClientConfiguration(AsyncSqsClientConfiguration.Type.PRODUCTION); RetryPolicyConfiguration retryPolicyConfiguration = new RetryPolicyConfiguration(); retryPolicyConfiguration.setCondition(RetryPolicyConfiguration.Condition.DEFAULT); retryPolicyConfiguration.setBackOff(RetryPolicyConfiguration.BackOff.EQUAL_JITTER); OverrideConfiguration overrideConfiguration = new OverrideConfiguration(); overrideConfiguration.setApiCallAttemptTimeout(300); overrideConfiguration.setApiCallTimeout(25 * 1000); overrideConfiguration.setRetryPolicyConfiguration(retryPolicyConfiguration); config.setOverrideConfiguration(overrideConfiguration); AsyncSqsClient asyncClient = factory.create(config); assertTrue(asyncClient instanceof AsyncSqsClientImpl); SqsAsyncClient sqs = ((AsyncSqsClientImpl) asyncClient).getClient(); assertNotNull(sqs); } }
5,649
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/AsyncConsumer.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; public interface AsyncConsumer<T> { CompletableFuture<Void> accept(T t, Executor executor); }
5,650
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/AsyncSqsClientImpl.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.conveyor.async.metrics.AsyncConveyorMetrics; import com.github.benmanes.caffeine.cache.AsyncLoadingCache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import io.github.resilience4j.bulkhead.Bulkhead; import io.github.resilience4j.bulkhead.BulkheadConfig; import java.time.Duration; import java.util.concurrent.*; import java.util.function.BiFunction; import java.util.function.Consumer; import javax.annotation.concurrent.ThreadSafe; import javax.inject.Inject; import lombok.Getter; import lombok.NonNull; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.services.sqs.model.*; /** Represents queue responsible for asynchronously propagating serialized messages. */ @Slf4j @ThreadSafe @Accessors public class AsyncSqsClientImpl implements AsyncSqsClient { @Getter final SqsAsyncClient client; @Getter final AsyncConveyorMetrics metrics; private final AsyncLoadingCache<String, String> urlCache; private final ExecutorService executor; private final int receiveWaitTimeoutSeconds; private final Bulkhead bulkhead; @Inject AsyncSqsClientImpl( @NonNull final SqsAsyncClient client, @NonNull final AsyncConveyorMetrics metrics, @NonNull final ExecutorService executor) { this( client, metrics, executor, AsyncSqsClientConfiguration.DEFAULT_URL_CACHE_SIZE, AsyncSqsClientConfiguration.DEFAULT_RECEIVE_WAIT_SECONDS, AsyncSqsClientConfiguration.DEFAULT_BULKHEAD_MAX_WAIT_MS, AsyncSqsClientConfiguration.DEFAULT_CONSUMER_CONCURRENCY); } AsyncSqsClientImpl( @NonNull final SqsAsyncClient client, @NonNull final AsyncConveyorMetrics metrics, @NonNull final ExecutorService executor, long maxCacheSize, int receiveWaitTimeoutSeconds, int bulkheadMaxWaitMillis, int consumerConcurrency) { this.client = client; this.metrics = metrics; this.urlCache = initUrlCache(maxCacheSize); this.executor = executor; this.receiveWaitTimeoutSeconds = receiveWaitTimeoutSeconds; this.bulkhead = Bulkhead.of( "conveyor-async", BulkheadConfig.custom() .maxConcurrentCalls(consumerConcurrency) .maxWaitTimeDuration(Duration.ofMillis(bulkheadMaxWaitMillis)) .build()); this.bulkhead .getEventPublisher() .onCallPermitted(event -> metrics.consumePermitted()) .onCallFinished(event -> metrics.consumeFinished()) .onCallRejected(event -> metrics.consumeRejected()) .onEvent(event -> metrics.bulkheadMetrics(this.bulkhead.getMetrics())); } private CompletableFuture<String> getQueueUrl(@NonNull final String queueName) { GetQueueUrlRequest urlRequest = GetQueueUrlRequest.builder().queueName(queueName).build(); return client.getQueueUrl(urlRequest).thenApply(GetQueueUrlResponse::queueUrl); } private AsyncLoadingCache<String, String> initUrlCache(long maxCacheSize) { return Caffeine.newBuilder() .maximumSize(maxCacheSize) .buildAsync((key, executor) -> getQueueUrl(key)); } private CompletableFuture<ReceiveMessageResponse> getMessage(@NonNull final String queueName) { return urlCache .get(queueName) .thenCompose( url -> { ReceiveMessageRequest messageRequest = ReceiveMessageRequest.builder() .queueUrl(url) .maxNumberOfMessages(1) .waitTimeSeconds(receiveWaitTimeoutSeconds) .build(); return client.receiveMessage(messageRequest); }); } private CompletableFuture<DeleteMessageResponse> deleteMessage( @NonNull final String queueName, @NonNull final String messageReceipt) { return urlCache .get(queueName) .thenCompose( url -> { DeleteMessageRequest deleteMessageReq = DeleteMessageRequest.builder() .queueUrl(url) .receiptHandle(messageReceipt) .build(); return client.deleteMessage(deleteMessageReq); }); } private void setMessageVisibility( @NonNull final String queueName, @NonNull final String messageReceipt) { urlCache .get(queueName) .thenCompose( url -> { ChangeMessageVisibilityRequest messageVisibilityReq = ChangeMessageVisibilityRequest.builder() .queueUrl(url) .receiptHandle(messageReceipt) .visibilityTimeout(0) .build(); return client.changeMessageVisibility(messageVisibilityReq); }); } private void consumePostProcess( @NonNull final String queueName, @NonNull final String messageReceipt, @NonNull CompletableFuture<Boolean> ret, @NonNull CompletableFuture<Void> computation, Stopwatch stopwatch) { computation.whenComplete( (r, ex) -> { if (ex == null) { deleteMessage(queueName, messageReceipt) .whenComplete( (deleted, deleteException) -> { if (deleteException != null) { log.error( "Exception while deleting message from queue={}", queueName, deleteException); metrics.consumeFailure(deleteException, queueName); ret.completeExceptionally(deleteException); } else { log.debug("Deleted message. queue={}", queueName); long time = stopwatch.stop().elapsed(TimeUnit.NANOSECONDS); metrics.consume(time, queueName); log.debug("Consumed message in {} nanoseconds. queue={}.", time, queueName); ret.complete(true); } }); } else { metrics.consumeFailure(ex, queueName); log.error("Exception occurred while consuming message from queue.", ex); setMessageVisibility(queueName, messageReceipt); ret.completeExceptionally(ex); } }); } private CompletableFuture<Boolean> consumeInternal( BiFunction<String, Executor, CompletableFuture<Void>> compute, @NonNull final String queueName) { bulkhead.acquirePermission(); log.debug("Consuming message. queue={}.", queueName); Stopwatch stopwatch = Stopwatch.createStarted(); return getMessage(queueName) .thenCompose( response -> { CompletableFuture<Boolean> ret = new CompletableFuture<>(); Preconditions.checkState( response.messages().size() <= 1, "Retrieved more than 1 message from SQS"); if (response.messages().isEmpty()) { ret.complete(false); } else { Message message = response.messages().get(0); log.debug("Retrieved message. queue={}", queueName); CompletableFuture<Void> result = compute.apply(message.body(), executor); consumePostProcess(queueName, message.receiptHandle(), ret, result, stopwatch); log.info("Consumed message {} from queue {}", message.messageId(), queueName); } return ret; }) .whenComplete((r, t) -> bulkhead.onComplete()); } @Override public CompletableFuture<Void> add( @NonNull final String message, @NonNull final String queueName) { return add(message, queueName, 0); } @Override public CompletableFuture<Void> add( @NonNull final String message, @NonNull final String queueName, int delaySeconds) { log.debug("Adding message. queue={}", queueName); Stopwatch stopwatch = Stopwatch.createStarted(); return urlCache .get(queueName) .thenCompose( url -> { SendMessageRequest request = SendMessageRequest.builder() .messageBody(message) .queueUrl(url) .delaySeconds(delaySeconds) .build(); return client.sendMessage(request); }) .whenComplete( (response, ex) -> { if (response != null) { log.info( "Published the message to SQS, id: {}, SequenceNumber: {}, QueueName: {}", response.messageId(), response.sequenceNumber(), queueName); long time = stopwatch.stop().elapsed(TimeUnit.NANOSECONDS); metrics.add(time, queueName); log.debug("Added message in {} nanoseconds. queue={}.", time, queueName); } else { metrics.addFailure(ex, queueName); log.error("Failed to add message. queue={}.", queueName, ex); } }) .thenApply(it -> null); } @Override public CompletableFuture<Boolean> consume( @NonNull final Consumer<String> consumer, @NonNull final String queueName) { return consumeInternal( (body, executor) -> CompletableFuture.runAsync(() -> consumer.accept(body), executor), queueName); } @Override public CompletableFuture<Boolean> consume(AsyncConsumer<String> consumer, String queueName) { return consumeInternal(consumer::accept, queueName); } @Override public void close() { client.close(); } }
5,651
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/AsyncSqsClient.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import java.io.Closeable; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import lombok.NonNull; public interface AsyncSqsClient extends Closeable { CompletableFuture<Void> add(@NonNull final String message, @NonNull final String queueName); CompletableFuture<Void> add( @NonNull final String message, @NonNull final String queueName, int delaySeconds); CompletableFuture<Boolean> consume( @NonNull final Consumer<String> consumer, @NonNull final String queueName); CompletableFuture<Boolean> consume(AsyncConsumer<String> consumer, String queueName); }
5,652
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/AsyncSqsClientFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.conveyor.async.config.OverrideConfiguration; import com.airbnb.conveyor.async.config.RetryPolicyConfiguration; import com.airbnb.conveyor.async.metrics.AsyncConveyorMetrics; import com.airbnb.conveyor.async.mock.MockAsyncSqsClient; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.time.Duration; import java.util.concurrent.*; import javax.inject.Inject; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.EqualJitterBackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FullJitterBackoffStrategy; import software.amazon.awssdk.core.retry.conditions.MaxNumberOfRetriesCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.services.sqs.SqsAsyncClientBuilder; /** Responsible for creating {@code AsyncClient}s from configuration */ @Slf4j @AllArgsConstructor(onConstructor = @__(@Inject)) public class AsyncSqsClientFactory { @NonNull private final AsyncConveyorMetrics metrics; /** * Provides a {@code AsyncClient} given the specified configuration. * * @param configuration The {@code AsyncClientConfiguration}. * @return the corresponding {@code AsyncClient}. */ public AsyncSqsClient create(@NonNull final AsyncSqsClientConfiguration configuration) { return createClient(configuration); } private RetryPolicy buildRetryPolicy(RetryPolicyConfiguration config) { RetryPolicy retryPolicy; if (config == null) { retryPolicy = RetryPolicy.none(); } else { switch (config.getPolicy()) { case DEFAULT: retryPolicy = RetryPolicy.defaultRetryPolicy(); break; case NONE: retryPolicy = RetryPolicy.none(); break; default: RetryCondition condition; BackoffStrategy strategy; switch (config.getCondition()) { case DEFAULT: condition = RetryCondition.defaultRetryCondition(); break; case MAX_NUM: condition = MaxNumberOfRetriesCondition.create(config.getNumRetries()); break; default: condition = RetryCondition.none(); } switch (config.getBackOff()) { case FULL_JITTER: strategy = FullJitterBackoffStrategy.builder() .baseDelay(Duration.ofMillis(config.getBaseDelay())) .maxBackoffTime(Duration.ofMillis(config.getMaximumBackoffTime())) .build(); break; case EQUAL_JITTER: strategy = EqualJitterBackoffStrategy.builder() .baseDelay(Duration.ofMillis(config.getBaseDelay())) .maxBackoffTime(Duration.ofMillis(config.getMaximumBackoffTime())) .build(); break; case FIXED_DELAY: strategy = FixedDelayBackoffStrategy.create(Duration.ofMillis(config.getBaseDelay())); break; case DEFAULT: strategy = BackoffStrategy.defaultStrategy(); break; case DEFAULT_THROTTLE: strategy = BackoffStrategy.defaultThrottlingStrategy(); break; default: strategy = BackoffStrategy.none(); } retryPolicy = RetryPolicy.builder() .numRetries(config.getNumRetries()) .retryCondition(condition) .backoffStrategy(strategy) .build(); } } return retryPolicy; } private SqsAsyncClient getAsyncSQSClient(AsyncSqsClientConfiguration config) { if (config.getType().equals(AsyncSqsClientConfiguration.Type.PRODUCTION)) { SqsAsyncClientBuilder builder = SqsAsyncClient.builder() .region(Region.of(config.getRegion())) .endpointOverride(config.getEndpoint()); OverrideConfiguration overrideConfig = config.getOverrideConfiguration(); if (overrideConfig != null) { RetryPolicy retry = buildRetryPolicy(overrideConfig.getRetryPolicyConfiguration()); ClientOverrideConfiguration clientOverrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofMillis(overrideConfig.getApiCallAttemptTimeout())) .apiCallTimeout(Duration.ofMillis(overrideConfig.getApiCallTimeout())) .retryPolicy(retry) .build(); builder = builder.overrideConfiguration(clientOverrideConfiguration); } return builder.build(); } else { throw new IllegalArgumentException("Doesn't support this Type " + config.getType()); } } private AsyncSqsClient createClient(@NonNull final AsyncSqsClientConfiguration configuration) { if (configuration.getType().equals(AsyncSqsClientConfiguration.Type.MOCK)) { return new MockAsyncSqsClient(); } else { SqsAsyncClient asyncSqsClient = getAsyncSQSClient(configuration); return new AsyncSqsClientImpl( asyncSqsClient, metrics, MoreExecutors.getExitingExecutorService( new ThreadPoolExecutor( configuration.getConsumerConcurrency(), configuration.getConsumerConcurrency(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("conveyor-executor-%d").build())), configuration.getMaxUrlCacheSize(), configuration.getReceiveWaitSeconds(), configuration.getBulkheadMaxWaitMillis(), configuration.getConsumerConcurrency()); } } }
5,653
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/metrics/AsyncConveyorMetrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async.metrics; import io.github.resilience4j.bulkhead.Bulkhead; import lombok.NonNull; public interface AsyncConveyorMetrics { default void add(final long elapsedTime, String queueName) {} default void addFailure(@NonNull final Throwable error, String queueName) {} default void consume(final long elapsedTime, String queueName) {} default void consumePermitted() {} default void consumeRejected() {} default void consumeFinished() {} default void consumeFailure(@NonNull final Throwable error, String queueName) {} default void bulkheadMetrics(@NonNull final Bulkhead.Metrics metrics) {} }
5,654
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/metrics/NoOpConveyorMetrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async.metrics; public class NoOpConveyorMetrics implements AsyncConveyorMetrics {}
5,655
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/config/RetryPolicyConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async.config; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class RetryPolicyConfiguration { private static int DEFAULT_NUM_RETRIES = Integer.MAX_VALUE; private static int DEFAULT_BASE_DELAY = 100; private static int DEFAULT_MAX_BACKOFF_TIME = 10 * 1000; @JsonProperty("num_retries") private int numRetries = DEFAULT_NUM_RETRIES; @JsonProperty("base_delay") private int baseDelay = DEFAULT_BASE_DELAY; @JsonProperty("max_backoff_time") private int maximumBackoffTime = DEFAULT_MAX_BACKOFF_TIME; @JsonProperty("policy") private Policy policy = Policy.DEFAULT; @JsonProperty("condition") private Condition condition = Condition.DEFAULT; @JsonProperty("backoff") private BackOff backOff = BackOff.DEFAULT; public enum Policy { CUSTOM, DEFAULT, NONE; @JsonProperty public static Policy create(String policy) { return Policy.valueOf(policy.toUpperCase()); } } public enum Condition { DEFAULT, NONE, MAX_NUM; @JsonProperty public static Condition create(String condition) { return Condition.valueOf(condition.toUpperCase()); } } public enum BackOff { FULL_JITTER, EQUAL_JITTER, FIXED_DELAY, DEFAULT, DEFAULT_THROTTLE, NONE; @JsonProperty public static BackOff create(String strategy) { return BackOff.valueOf(strategy.toUpperCase()); } } }
5,656
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/config/AsyncSqsClientConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async.config; import com.fasterxml.jackson.annotation.JsonProperty; import java.net.URI; import javax.validation.constraints.Min; import lombok.Data; import lombok.NonNull; @Data public class AsyncSqsClientConfiguration { public static final long DEFAULT_URL_CACHE_SIZE = 128; public static final int DEFAULT_RECEIVE_WAIT_SECONDS = 5; public static final int DEFAULT_BULKHEAD_MAX_WAIT_MS = Integer.MAX_VALUE; public static final int DEFAULT_CONSUMER_CONCURRENCY = 10; public static final String DEFAULT_REGION = "us-east-1"; public static final URI DEFAULT_ENDPOINT = URI.create("https://sqs." + DEFAULT_REGION + ".amazonaws.com"); @JsonProperty(defaultValue = "production") @NonNull private final Type type; @JsonProperty("consumer_concurrency") @Min(1) private int consumerConcurrency = DEFAULT_CONSUMER_CONCURRENCY; @JsonProperty("bulkhead_max_wait_ms") @Min(0) private int bulkheadMaxWaitMillis = DEFAULT_BULKHEAD_MAX_WAIT_MS; @JsonProperty("receive_wait_seconds") @Min(0) private int receiveWaitSeconds = DEFAULT_RECEIVE_WAIT_SECONDS; @JsonProperty("max_url_cache_size") private long maxUrlCacheSize = DEFAULT_URL_CACHE_SIZE; @JsonProperty("region") private String region = DEFAULT_REGION; @JsonProperty("endpoint") private URI endpoint = DEFAULT_ENDPOINT; @JsonProperty("override_configuration") private OverrideConfiguration overrideConfiguration; public enum Type { PRODUCTION, MOCK; @JsonProperty public static Type create(String type) { return Type.valueOf(type.toUpperCase()); } } }
5,657
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/config/OverrideConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async.config; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class OverrideConfiguration { @JsonProperty("api_call_attempt_timeout") public int apiCallAttemptTimeout; @JsonProperty("api_call_timeout") public int apiCallTimeout; @JsonProperty("retry_policy_configuration") public RetryPolicyConfiguration retryPolicyConfiguration; }
5,658
0
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async
Create_ds/dynein/conveyor/src/main/java/com/airbnb/conveyor/async/mock/MockAsyncSqsClient.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async.mock; import com.airbnb.conveyor.async.AsyncConsumer; import com.airbnb.conveyor.async.AsyncSqsClient; import java.util.concurrent.*; import java.util.function.BiFunction; import java.util.function.Consumer; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; /** Represents an in-memory blocking {@code AsyncClient} implement. */ @Slf4j public final class MockAsyncSqsClient implements AsyncSqsClient { private final int DEFAULT_CAPACITY = 10_000; @NonNull private final BlockingQueue<String> queue; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); public MockAsyncSqsClient() { this.queue = new ArrayBlockingQueue<>(DEFAULT_CAPACITY, true); } private CompletableFuture<String> getMessage() { CompletableFuture<String> message = new CompletableFuture<>(); CompletableFuture.runAsync( () -> { try { final String body = queue.take(); message.complete(body); } catch (Exception ex) { message.completeExceptionally(ex); } }, executor); return message; } private CompletableFuture<Boolean> consumeInternal( BiFunction<String, Executor, CompletableFuture<Void>> compute) { CompletableFuture<Boolean> ret = new CompletableFuture<>(); if (queue.size() == 0) { ret.complete(false); } else { getMessage() .whenComplete( (res, exception) -> { if (exception != null) { ret.completeExceptionally(exception); } }) .thenCompose( message -> { CompletableFuture<Void> result = compute.apply(message, executor); return result.whenComplete( (it, ex) -> { if (ex == null) { ret.complete(true); } else { ret.completeExceptionally(ex); } }); }); } return ret; } @Override public CompletableFuture<Void> add(@NonNull String message, @NonNull String queueName) { queue.add(message); return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> add( @NonNull String message, @NonNull String queueName, int delaySeconds) { if (delaySeconds < 0 || delaySeconds > 900) { throw new IllegalArgumentException("Valid values for DelaySeconds is 0 to 900."); } CompletableFuture<Void> ret = new CompletableFuture<>(); scheduler.schedule( () -> { add(message, queueName); ret.complete(null); }, delaySeconds, TimeUnit.SECONDS); return ret; } @Override public CompletableFuture<Boolean> consume( @NonNull final Consumer<String> consumer, @NonNull final String queueName) { return consumeInternal( (body, executor) -> CompletableFuture.runAsync(() -> consumer.accept(body), executor)); } @Override public CompletableFuture<Boolean> consume(AsyncConsumer<String> consumer, String queueName) { return consumeInternal(consumer::accept); } @Override public void close() {} }
5,659
0
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein/api/JobSchedulePolicy.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.api; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Optional; import lombok.Builder; import lombok.Data; @Builder @Data public class JobSchedulePolicy { JobScheduleType type; @Builder.Default long delayMillis = -1L; @Builder.Default long epochMillis = -1L; @JsonIgnore public Optional<Long> getDelayMillisOptional() { return delayMillis == -1 ? Optional.empty() : Optional.of(delayMillis); } @JsonIgnore public Optional<Long> getEpochMillisOptional() { return epochMillis == -1 ? Optional.empty() : Optional.of(epochMillis); } }
5,660
0
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein/api/DyneinJobSpec.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.api; import lombok.Builder; import lombok.Data; @Data @Builder public class DyneinJobSpec { JobSchedulePolicy schedulePolicy; long createAtInMillis; String queueName; String queueType; String jobToken; String name; byte[] serializedJob; }
5,661
0
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein/api/JobTokenPayload.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.api; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Optional; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @Builder @Data public class JobTokenPayload { @AllArgsConstructor public enum JobTokenType { SCHEDULED_JOB(0); int type; } private byte[] uuid; private short logicalShard; private String logicalCluster; private JobTokenType tokenType; private long epochMillis; @JsonIgnore public Optional<Long> getEpochMillisOptional() { return epochMillis == -1 ? Optional.empty() : Optional.of(epochMillis); } }
5,662
0
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein/api/InvalidTokenException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.api; public class InvalidTokenException extends Exception { public InvalidTokenException(Throwable cause) { super(cause); } }
5,663
0
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein/api/PrepareJobRequest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.api; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Optional; import lombok.Builder; import lombok.Data; @Data @Builder public class PrepareJobRequest { JobSchedulePolicy schedulePolicy; @Builder.Default long associatedId = -1; @JsonIgnore public Optional<JobSchedulePolicy> getSchedulePolicyOptional() { return Optional.ofNullable(schedulePolicy); } }
5,664
0
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein
Create_ds/dynein/dynein-api/src/main/java/com/airbnb/dynein/api/JobScheduleType.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.dynein.api; import lombok.AllArgsConstructor; @AllArgsConstructor public enum JobScheduleType { IMMEDIATE(1), SCHEDULED(2), SQS_DELAYED(3); int type; }
5,665
0
Create_ds/coordinators/coordinators/src/main/java/com/squareup
Create_ds/coordinators/coordinators/src/main/java/com/squareup/coordinators/Coordinators.java
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators; import android.os.Build; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public final class Coordinators { private Coordinators() { } /** * Attempts to bind a view to a {@link Coordinator}. * * Immediately calls provider to obtain a Coordinator for the view. If a non-null Coordinator is * returned, that Coordinator is permanently bound to the View. */ public static void bind(@NonNull View view, @NonNull CoordinatorProvider provider) { final Coordinator coordinator = provider.provideCoordinator(view); if (coordinator == null) { return; } View.OnAttachStateChangeListener binding = new Binding(coordinator, view); view.addOnAttachStateChangeListener(binding); // Sometimes we missed the first attach because the child's already been added. // Sometimes we didn't. The binding keeps track to avoid double attachment of the Coordinator, // and to guard against attachment to two different views simultaneously. if (isAttachedToWindow(view)) { binding.onViewAttachedToWindow(view); } } /** * Installs a binder that calls {@link #bind(View, CoordinatorProvider)} for any child view added * to the group. */ public static void installBinder(@NonNull ViewGroup viewGroup, @NonNull final CoordinatorProvider provider) { int childCount = viewGroup.getChildCount(); for (int i = 0; i < childCount; i++) { bind(viewGroup.getChildAt(i), provider); } viewGroup.setOnHierarchyChangeListener(new Binder(provider)); } @Nullable public static Coordinator getCoordinator(@NonNull View view) { return (Coordinator) view.getTag(R.id.coordinator); } private static boolean isAttachedToWindow(View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return view.getWindowToken() != null; } else { return view.isAttachedToWindow(); } } }
5,666
0
Create_ds/coordinators/coordinators/src/main/java/com/squareup
Create_ds/coordinators/coordinators/src/main/java/com/squareup/coordinators/CoordinatorProvider.java
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public interface CoordinatorProvider { /** * Called to obtain a {@link Coordinator} for a View. * * Called from {@link Coordinators#bind}. Whether or not Coordinator instances are reused is up * to the implementer, but a Coordinator instance may only be bound to one View instance at a * time. * * @return null if the view has no associated coordinator */ @Nullable Coordinator provideCoordinator(@NonNull View view); }
5,667
0
Create_ds/coordinators/coordinators/src/main/java/com/squareup
Create_ds/coordinators/coordinators/src/main/java/com/squareup/coordinators/Binder.java
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; final class Binder implements ViewGroup.OnHierarchyChangeListener { private final CoordinatorProvider provider; Binder(@NonNull CoordinatorProvider provider) { this.provider = provider; } @Override public void onChildViewAdded(View parent, View child) { Coordinators.bind(child, provider); } @Override public void onChildViewRemoved(View parent, View child) { } }
5,668
0
Create_ds/coordinators/coordinators/src/main/java/com/squareup
Create_ds/coordinators/coordinators/src/main/java/com/squareup/coordinators/Coordinator.java
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators; import android.view.View; import androidx.annotation.NonNull; /** * A Coordinator is attached to one view at a time. * * What you do from there is up to you. * * @see CoordinatorProvider */ public class Coordinator { private boolean attached; final void setAttached(boolean attached) { this.attached = attached; } /** * Called when the view is attached to a Window. * * Default implementation does nothing. * * @see View#onAttachedToWindow() */ public void attach(@NonNull View view) { } /** * Called when the view is detached from a Window. * * Default implementation does nothing. * * @see View#onDetachedFromWindow() */ public void detach(@NonNull View view) { } /** * True from just before {@link #attach} until just before {@link #detach}. */ public final boolean isAttached() { return attached; } }
5,669
0
Create_ds/coordinators/coordinators/src/main/java/com/squareup
Create_ds/coordinators/coordinators/src/main/java/com/squareup/coordinators/Binding.java
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators; import android.view.View; import androidx.annotation.NonNull; final class Binding implements View.OnAttachStateChangeListener { private final Coordinator coordinator; private final View view; Binding(@NonNull Coordinator coordinator, @NonNull View view) { this.coordinator = coordinator; this.view = view; } @Override public void onViewAttachedToWindow(@NonNull View v) { if (v != view) { throw new AssertionError("Binding for view " + view + " notified of attachment of different view " + v); } if (coordinator.isAttached()) { throw new IllegalStateException( "Coordinator " + coordinator + " is already attached"); } coordinator.setAttached(true); coordinator.attach(view); view.setTag(R.id.coordinator, coordinator); } @Override public void onViewDetachedFromWindow(@NonNull View v) { if (v != view) { throw new AssertionError("Binding for view " + view + " notified of detachment of different view " + v); } if (!coordinator.isAttached()) { // Android tries not to make reentrant calls, but doesn't always succeed. // See https://github.com/square/coordinators/issues/28 return; } coordinator.setAttached(false); coordinator.detach(view); view.setTag(R.id.coordinator, null); } }
5,670
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/ContainerSampleActivity.java
/* * Copyright 2016 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators.sample.container; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.squareup.coordinators.Coordinator; import com.squareup.coordinators.CoordinatorProvider; import com.squareup.coordinators.Coordinators; public class ContainerSampleActivity extends Activity { private static final ObjectGraph OBJECT_GRAPH = new ObjectGraph(); private static @LayoutRes int currentScreen; private ViewGroup container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.root_layout); container = findViewById(R.id.container); // Make each button show the layout identified in its tag. See root_layout.xml ViewGroup buttons = findViewById(R.id.buttons); for (int i = 0; i < buttons.getChildCount(); i++) { View button = buttons.getChildAt(i); String layoutName = (String) button.getTag(R.id.layout_to_show_tag); layoutName = layoutName.substring("res/layout/".length()); layoutName = layoutName.substring(0, layoutName.length() - ".xml".length()); final int layout = getResources().getIdentifier(layoutName, "layout", getPackageName()); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showScreen(layout); } }); } // Install a binder that will be called as each child view is added to the container // layout. Our binder expects each view to have a tag with the classname of the coordinator // that knows how to drive it. Again, we're setting those tags in the layout files themselves, // BECAUSE WE CAN! Coordinators.installBinder(container, new CoordinatorProvider() { @Nullable @Override public Coordinator provideCoordinator(@NonNull View view) { String coordinatorName = (String) view.getTag(R.id.coordinator_class_tag); return OBJECT_GRAPH.get(coordinatorName); } }); refresh(); } private void showScreen(@LayoutRes int id) { currentScreen = id; refresh(); } private void refresh() { container.removeAllViews(); if (currentScreen != 0) { LayoutInflater.from(container.getContext()).inflate(currentScreen, container); } } }
5,671
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/ObjectGraph.java
package com.squareup.coordinators.sample.container; import com.squareup.coordinators.sample.container.counter.Counter; import com.squareup.coordinators.sample.container.counter.CounterCoordinator; import com.squareup.coordinators.sample.container.doubledetach.DoubleDetachCoordinator; import com.squareup.coordinators.sample.container.tictactoe.TicTacToeBoard; import com.squareup.coordinators.sample.container.tictactoe.TicTacToeCoordinator; /** * All the objects. In real life might be generated, e.g. by Dagger. */ class ObjectGraph { private final Counter counter = new Counter(); private final TicTacToeBoard ticTacToe = new TicTacToeBoard(); private CounterCoordinator counterCoordinator() { return new CounterCoordinator(counter); } private DoubleDetachCoordinator doubleDetachCoordinator() { return new DoubleDetachCoordinator(); } private TicTacToeCoordinator ticTacToeCoordinator() { return new TicTacToeCoordinator(ticTacToe); } @SuppressWarnings("unchecked") // <T> T get(String className) { if (TicTacToeCoordinator.class.getName().equals(className)) { return (T) ticTacToeCoordinator(); } if (DoubleDetachCoordinator.class.getName().equals(className)) { return (T) doubleDetachCoordinator(); } if (CounterCoordinator.class.getName().equals(className)) { return (T) counterCoordinator(); } throw new IllegalArgumentException("Unknown class: " + className); } }
5,672
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/tictactoe/TicTacToeCoordinator.java
package com.squareup.coordinators.sample.container.tictactoe; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.coordinators.Coordinator; import com.squareup.coordinators.sample.container.R; import com.squareup.coordinators.sample.container.tictactoe.TicTacToeBoard.Value; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; /** * Binds a {@link ViewGroup} with nine TextView children to a * {@link TicTacToeBoard}. */ public class TicTacToeCoordinator extends Coordinator { private final TicTacToeBoard board; private Disposable subscription; public TicTacToeCoordinator(TicTacToeBoard board) { this.board = board; } @Override public void attach(View view) { super.attach(view); final ViewGroup viewGroup = (ViewGroup) view; subscription = board.grid().subscribe(new Consumer<Value[][]>() { @Override public void accept(Value[][] values) throws Exception { refresh(viewGroup, values); } }); setCellClickListeners(viewGroup); } @Override public void detach(View view) { subscription.dispose(); subscription = null; super.detach(view); } private void setCellClickListeners(ViewGroup viewGroup) { for (int i = 0; i < 9; i++) { final int index = i; final View cell = viewGroup.getChildAt(i); cell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggle(cell, index); } }); } } private void refresh(ViewGroup viewGroup, Value[][] values) { for (int i = 0; i < 9; i++) { int row = i / 3; int col = i % 3; TextView cell = (TextView) (viewGroup).getChildAt(i); Value value = values[row][col]; cell.setText(value.text); cell.setTag(R.id.tic_tac_toe_cell_value_tag, value); } } private void toggle(View cell, int index) { Value oldValue = (Value) cell.getTag(R.id.tic_tac_toe_cell_value_tag); Value[] values = Value.values(); Value newValue = values[(oldValue.ordinal() + 1) % values.length]; int row = index / 3; int col = index % 3; board.set(row, col, newValue); } }
5,673
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/tictactoe/TicTacToeBoard.java
package com.squareup.coordinators.sample.container.tictactoe; import android.os.Looper; import com.jakewharton.rxrelay2.BehaviorRelay; import io.reactivex.Observable; import io.reactivex.functions.BiPredicate; import java.util.Arrays; import static com.squareup.coordinators.sample.container.tictactoe.TicTacToeBoard.Value.EMPTY; import static java.lang.String.format; public final class TicTacToeBoard { enum Value { EMPTY(""), X, O; final String text; Value() { this.text = name(); } Value(String text) { this.text = text; } } private BehaviorRelay<Value[][]> grid = BehaviorRelay.createDefault(new Value[][] { { EMPTY, EMPTY, EMPTY }, // { EMPTY, EMPTY, EMPTY }, // { EMPTY, EMPTY, EMPTY } }); /** * Returns an observable of the tic tac toe board. First value is provided immediately, * succeeding values are guaranteed to be distinct from previous values. Values are * always provided on the main thread. */ Observable<Value[][]> grid() { return grid.distinctUntilChanged(new BiPredicate<Value[][], Value[][]>() { @Override public boolean test(Value[][] a, Value[][] b) throws Exception { return Arrays.equals(a, b); } }); } /** * Change the value of a cell. Must be called from the main thread. */ void set(int row, int col, Value value) { assertOnMain(); assertIndex("row", row); assertIndex("col", col); Value[][] newGrid = new Value[3][]; for (int i = 0; i < 3; i++) { newGrid[i] = grid.getValue()[i].clone(); } newGrid[row][col] = value; grid.accept(newGrid); } private void assertIndex(String label, int index) { if (index < 0 || index > 2) { throw new IllegalArgumentException(format("%s must be 0, 1 or 2", label)); } } private void assertOnMain() { // https://speakerdeck.com/rjrjr/where-the-reactive-rubber-meets-the-road if (!(Looper.getMainLooper().getThread() == Thread.currentThread())) { throw new AssertionError("Model updates must come from main thread."); } } }
5,674
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/doubledetach/DoubleDetachCoordinator.java
package com.squareup.coordinators.sample.container.doubledetach; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import com.squareup.coordinators.Coordinator; import com.squareup.coordinators.sample.container.R; public class DoubleDetachCoordinator extends Coordinator { private int attachCount = 0; @Override public void attach(@NonNull View view) { attachCount++; super.attach(view); View button = view.findViewById(R.id.double_detach_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Activity activity = (Activity) v.getContext(); activity.finish(); } }); } @Override public void detach(@NonNull View view) { attachCount--; if (attachCount != 0) { // This would throw before https://github.com/square/coordinators/issues/28 was fixed. throw new AssertionError("Attach/detach imbalance! " + attachCount); } ViewGroup parent = (ViewGroup) view.getParent(); parent.removeAllViews(); super.detach(view); } }
5,675
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/counter/CounterCoordinator.java
package com.squareup.coordinators.sample.container.counter; import android.view.View; import android.widget.TextView; import com.squareup.coordinators.Coordinator; import com.squareup.coordinators.sample.container.R; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; public class CounterCoordinator extends Coordinator { private final Counter counter; private Disposable subscription = null; public CounterCoordinator(Counter counter) { this.counter = counter; } @Override public void attach(final View view) { super.attach(view); final TextView textView = (TextView) view.findViewById(R.id.counter_value); final View up = view.findViewById(R.id.count_up); final View down = view.findViewById(R.id.count_down); subscription = counter.count().subscribe(new Consumer<Integer>() { @Override public void accept(Integer count) throws Exception { textView.setText(String.format("%s", count)); } }); up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { counter.up(); } }); down.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { counter.down(); } }); } @Override public void detach(View view) { subscription.dispose(); super.detach(view); } }
5,676
0
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container
Create_ds/coordinators/coordinators-sample-container/src/main/java/com/squareup/coordinators/sample/container/counter/Counter.java
package com.squareup.coordinators.sample.container.counter; import com.jakewharton.rxrelay2.BehaviorRelay; import io.reactivex.Observable; public class Counter { private BehaviorRelay<Integer> count = BehaviorRelay.createDefault(0); public Observable<Integer> count() { return count; } public void up() { count.accept(count.getValue() + 1); } public void down() { count.accept(count.getValue() - 1); } }
5,677
0
Create_ds/coordinators/coordinators-sample-basic/src/main/java/com/squareup/coordinators/sample
Create_ds/coordinators/coordinators-sample-basic/src/main/java/com/squareup/coordinators/sample/basic/BasicSampleActivity.java
/* * Copyright 2016 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.coordinators.sample.basic; import android.app.Activity; import android.os.Bundle; import android.view.View; import androidx.annotation.Nullable; import com.squareup.coordinators.Coordinator; import com.squareup.coordinators.CoordinatorProvider; import com.squareup.coordinators.Coordinators; public class BasicSampleActivity extends Activity { private static final TicTacToeBoard MODEL = new TicTacToeBoard(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tic_tac_toe_view); Coordinators.bind(findViewById(R.id.board_view), new CoordinatorProvider() { @Nullable @Override public Coordinator provideCoordinator(View view) { // A more interesting app could inspect the given view and choose an // appropriate coordinator for it -- perhaps based on the type of the view, // on on meta information in a tag on the view, so many possibilities... return new TicTacToeCoordinator(MODEL); } }); } }
5,678
0
Create_ds/coordinators/coordinators-sample-basic/src/main/java/com/squareup/coordinators/sample
Create_ds/coordinators/coordinators-sample-basic/src/main/java/com/squareup/coordinators/sample/basic/TicTacToeCoordinator.java
package com.squareup.coordinators.sample.basic; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.coordinators.Coordinator; import com.squareup.coordinators.sample.basic.TicTacToeBoard.Value; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; /** * Binds a {@link ViewGroup} with nine TextView children to a * {@link TicTacToeBoard}. */ public class TicTacToeCoordinator extends Coordinator { private final TicTacToeBoard board; private Disposable subscription; public TicTacToeCoordinator(TicTacToeBoard board) { this.board = board; } @Override public void attach(View view) { super.attach(view); final ViewGroup viewGroup = (ViewGroup) view; subscription = board.grid().subscribe(new Consumer<Value[][]>() { @Override public void accept(Value[][] values) throws Exception { refresh(viewGroup, values); } }); setCellClickListeners(viewGroup); } @Override public void detach(View view) { subscription.dispose(); super.detach(view); } private void setCellClickListeners(ViewGroup viewGroup) { for (int i = 0; i < 9; i++) { final int index = i; final View cell = viewGroup.getChildAt(i); cell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggle(cell, index); } }); } } private void refresh(ViewGroup viewGroup, Value[][] values) { for (int i = 0; i < 9; i++) { int row = i / 3; int col = i % 3; TextView cell = (TextView) (viewGroup).getChildAt(i); Value value = values[row][col]; cell.setText(value.text); cell.setTag(R.id.tic_tac_toe_cell_value_tag, value); } } private void toggle(View cell, int index) { Value oldValue = (Value) cell.getTag(R.id.tic_tac_toe_cell_value_tag); Value[] values = Value.values(); Value newValue = values[(oldValue.ordinal() + 1) % values.length]; int row = index / 3; int col = index % 3; board.set(row, col, newValue); } }
5,679
0
Create_ds/coordinators/coordinators-sample-basic/src/main/java/com/squareup/coordinators/sample
Create_ds/coordinators/coordinators-sample-basic/src/main/java/com/squareup/coordinators/sample/basic/TicTacToeBoard.java
package com.squareup.coordinators.sample.basic; import android.os.Looper; import com.jakewharton.rxrelay2.BehaviorRelay; import io.reactivex.Observable; import io.reactivex.functions.BiPredicate; import java.util.Arrays; import static com.squareup.coordinators.sample.basic.TicTacToeBoard.Value.EMPTY; import static java.lang.String.format; final class TicTacToeBoard { enum Value { EMPTY(""), X, O; final String text; Value() { this.text = name(); } Value(String text) { this.text = text; } } private BehaviorRelay<Value[][]> grid = BehaviorRelay.createDefault(new Value[][] { { EMPTY, EMPTY, EMPTY }, // { EMPTY, EMPTY, EMPTY }, // { EMPTY, EMPTY, EMPTY } }); /** * Returns an observable of the tic tac toe board. First value is provided immediately, * succeeding values are guaranteed to be distinct from previous values. Values are * always provided on the main thread. */ public Observable<Value[][]> grid() { return grid.distinctUntilChanged(new BiPredicate<Value[][], Value[][]>() { @Override public boolean test(Value[][] a, Value[][] b) throws Exception { return Arrays.equals(a, b); } }); } /** * Change the value of a cell. Must be called from the main thread. */ public void set(int row, int col, Value value) { assertOnMain(); assertIndex("row", row); assertIndex("col", col); Value[][] newGrid = new Value[3][]; for (int i = 0; i < 3; i++) { newGrid[i] = grid.getValue()[i].clone(); } newGrid[row][col] = value; grid.accept(newGrid); } private void assertIndex(String label, int index) { if (index < 0 || index > 2) { throw new IllegalArgumentException(format("%s must be 0, 1 or 2", label)); } } private void assertOnMain() { // https://speakerdeck.com/rjrjr/where-the-reactive-rubber-meets-the-road if (!(Looper.getMainLooper().getThread() == Thread.currentThread())) { throw new AssertionError("Model updates must come from main thread."); } } }
5,680
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/TckSecurityService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Proxy; import java.security.Principal; import java.util.function.Supplier; import javax.enterprise.inject.spi.CDI; import javax.servlet.http.HttpServletRequest; import org.apache.webbeans.corespi.security.SimpleSecurityService; import org.eclipse.microprofile.jwt.JsonWebToken; // to drop upgrading MW public class TckSecurityService extends SimpleSecurityService { @Override public Principal getCurrentPrincipal() { return Principal.class.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{Principal.class, JsonWebToken.class}, (proxy, method, args) -> { try { return method.invoke(((Supplier<Principal>) CDI.current().select(HttpServletRequest.class).get() .getAttribute(Principal.class.getName() + ".supplier")).get(), args); } catch (final InvocationTargetException ite) { throw ite.getTargetException(); } })); } }
5,681
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/RunAsFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import static java.util.Collections.singleton; import java.io.IOException; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import org.eclipse.microprofile.jwt.JsonWebToken; @WebFilter("/inspector") public class RunAsFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { request.setAttribute(JsonWebToken.class.getName(), new JsonWebToken() { @Override public String getName() { return "run-as"; } @Override public Set<String> getClaimNames() { return singleton("name"); } @Override public <T> T getClaim(final String s) { return "name".equals(s) ? (T) "the-name" : null; } }); chain.doFilter(request, response); } }
5,682
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/AsyncEndpoint.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import static java.util.concurrent.TimeUnit.MINUTES; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.json.Json; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.apache.geronimo.microprofile.impl.jwtauth.cdi.GeronimoJwtAuthExtension; import org.eclipse.microprofile.jwt.JsonWebToken; @Path("test") @ApplicationScoped public class AsyncEndpoint { @Inject private JsonWebToken token; @Inject // not perfect but CDI doesn't have any real propagation here private GeronimoJwtAuthExtension extension; @GET @Path("async") @Produces(MediaType.APPLICATION_JSON) public void async(@Suspended final AsyncResponse response, @Context final HttpServletRequest request) { final CountDownLatch latchBefore = new CountDownLatch(1); final CountDownLatch latchResponse = new CountDownLatch(1); final AtomicReference<String> before = new AtomicReference<>(); new Thread(() -> extension.execute(request, () -> { try { final String after = capture("async"); latchBefore.countDown(); try { latchResponse.await(1, MINUTES); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } response.resume(Json.createObjectBuilder() .add("before", before.get()) .add("after", after).build()); } catch (final Exception e) { latchBefore.countDown(); response.resume(e); } })).start(); try { latchBefore.await(1, MINUTES); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } before.set(capture("sync")); latchResponse.countDown(); } private String capture(final String marker) { return marker + "=" + token.getRawToken(); } }
5,683
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/TokenInspector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.jwt.JsonWebToken; @Path("inspector") @ApplicationScoped public class TokenInspector { @Inject private JsonWebToken token; @GET @Produces(MediaType.TEXT_PLAIN) public String inspect(@QueryParam("claim") final String name) { return "name".equals(name) ? token.getName() : token.getClaim(name); } }
5,684
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/PreProvidedTokenTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; import static org.testng.Assert.assertEquals; import java.net.URL; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import org.eclipse.microprofile.jwt.tck.container.jaxrs.TCKApplication; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.testng.annotations.Test; // NOTE: reuses tck resources and token generation public class PreProvidedTokenTest extends Arquillian { @Deployment(testable = false) public static Archive<?> war() { return ShrinkWrap.create(WebArchive.class, PreProvidedTokenTest.class.getSimpleName() + ".war") .addClasses(TCKApplication.class, TokenInspector.class, RunAsFilter.class) .addAsResource(PreProvidedTokenTest.class.getResource("/publicKey.pem"), "/publicKey.pem"); } @ArquillianResource private URL base; @Test public void runAsync() { final Client client = ClientBuilder.newClient(); try { final String value = client.target(base.toExternalForm()) .path("inspector") .queryParam("claim", "name") .request(TEXT_PLAIN_TYPE) .get(String.class) .trim(); assertEquals("run-as", value); } finally { client.close(); } } }
5,685
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/CookieTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; import static org.testng.Assert.assertEquals; import java.net.URL; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.Cookie; import org.eclipse.microprofile.jwt.tck.container.jaxrs.TCKApplication; import org.eclipse.microprofile.jwt.tck.util.TokenUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.testng.annotations.Test; // NOTE: reuses tck resources and token generation public class CookieTest extends Arquillian { @Deployment(testable = false) public static Archive<?> war() { return ShrinkWrap.create(WebArchive.class, CookieTest.class.getSimpleName() + ".war") .addClasses(TCKApplication.class, PassthroughEndpoint.class) .addAsResource(CookieTest.class.getResource("/publicKey.pem"), "/publicKey.pem"); } @ArquillianResource private URL base; @Test public void test() throws Exception { final Client client = ClientBuilder.newClient(); try { final String token = TokenUtils.generateTokenString("/Token2.json"); final String serverToken = client.target(base.toExternalForm()) .path("passthrough") .request(TEXT_PLAIN_TYPE) .cookie(new Cookie("Bearer", token)) .get(String.class); assertEquals(serverToken, token); } finally { client.close(); } } }
5,686
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/PassthroughEndpoint.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.jwt.JsonWebToken; @Path("passthrough") @ApplicationScoped public class PassthroughEndpoint { @Inject private JsonWebToken token; @GET @Produces(MediaType.TEXT_PLAIN) public String passthrough() { return token.getRawToken(); } }
5,687
0
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck
Create_ds/geronimo-jwt-auth/src/test/java/org/apache/geronimo/microprofile/impl/jwtauth/tck/jaxrs/JaxRsAsyncTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.tck.jaxrs; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static org.testng.Assert.assertEquals; import java.net.URL; import javax.json.JsonObject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import org.eclipse.microprofile.jwt.tck.container.jaxrs.TCKApplication; import org.eclipse.microprofile.jwt.tck.util.TokenUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.testng.annotations.Test; // NOTE: reuses tck resources and token generation public class JaxRsAsyncTest extends Arquillian { @Deployment(testable = false) public static Archive<?> war() { return ShrinkWrap.create(WebArchive.class, JaxRsAsyncTest.class.getSimpleName() + ".war") .addClasses(TCKApplication.class, AsyncEndpoint.class) .addAsResource(JaxRsAsyncTest.class.getResource("/publicKey.pem"), "/publicKey.pem"); } @ArquillianResource private URL base; @Test(timeOut = 60000) public void runAsync() throws Exception { final Client client = ClientBuilder.newClient(); try { final String token = TokenUtils.generateTokenString("/Token2.json"); final JsonObject object = client.target(base.toExternalForm()) .path("test/async") .request(APPLICATION_JSON_TYPE) .header("Authorization", "bearer " + token) .get(JsonObject.class); assertEquals(object.toString(), "{\"before\":\"sync=" + token + "\",\"after\":\"async=" + token + "\"}"); } finally { client.close(); } } }
5,688
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/JwtException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth; public class JwtException extends RuntimeException { private final int status; public JwtException(final String msg, final int status) { super(msg); this.status = status; } public int getStatus() { return status; } }
5,689
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/jwt/KidMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.jwt; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.joining; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig; import org.apache.geronimo.microprofile.impl.jwtauth.io.PropertiesLoader; import org.eclipse.microprofile.jwt.config.Names; @ApplicationScoped public class KidMapper { @Inject private GeronimoJwtAuthConfig config; private final ConcurrentMap<String, String> keyMapping = new ConcurrentHashMap<>(); private final Map<String, Collection<String>> issuerMapping = new HashMap<>(); private String defaultKey; private Set<String> defaultIssuers; @PostConstruct private void init() { ofNullable(config.read("kids.key.mapping", null)) .map(String::trim) .filter(s -> !s.isEmpty()) .map(PropertiesLoader::load) .ifPresent(props -> props.stringPropertyNames() .forEach(k -> keyMapping.put(k, loadKey(props.getProperty(k))))); ofNullable(config.read("kids.issuer.mapping", null)) .map(String::trim) .filter(s -> !s.isEmpty()) .map(PropertiesLoader::load) .ifPresent(props -> props.stringPropertyNames() .forEach(k -> { issuerMapping.put(k, Stream.of(props.getProperty(k).split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.toSet())); })); defaultIssuers = ofNullable(config.read("org.eclipse.microprofile.authentication.JWT.issuers", null)) .map(s -> Stream.of(s.split(",")) .map(String::trim) .filter(it -> !it.isEmpty()) .collect(Collectors.toSet())) .orElseGet(HashSet::new); ofNullable(config.read("issuer.default", config.read(Names.ISSUER, null))).ifPresent(defaultIssuers::add); defaultKey = config.read("public-key.default", config.read(Names.VERIFIER_PUBLIC_KEY, null)); } public String loadKey(final String property) { String value = keyMapping.get(property); if (value == null) { value = tryLoad(property); if (value != null && !property.equals(value) /* else we can leak easily*/) { keyMapping.putIfAbsent(property, value); } else if (defaultKey != null) { value = defaultKey; } } return value; } public Collection<String> loadIssuers(final String property) { return issuerMapping.getOrDefault(property, defaultIssuers); } private String tryLoad(final String value) { // try external file final File file = new File(value); if (file.exists()) { try { return Files.readAllLines(file.toPath()).stream().collect(joining("\n")); } catch (final IOException e) { throw new IllegalArgumentException(e); } } // if not found try classpath resource try (final InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(value)) { if (stream != null) { return new BufferedReader(new InputStreamReader(stream)).lines().collect(joining("\n")); } } catch (final IOException e) { throw new IllegalArgumentException(e); } // else direct value return value; } }
5,690
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/jwt/ContextualJsonWebToken.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.jwt; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import javax.security.auth.Subject; import org.eclipse.microprofile.jwt.JsonWebToken; public class ContextualJsonWebToken implements JsonWebToken { private final Supplier<JsonWebToken> provider; public ContextualJsonWebToken(final Supplier<JsonWebToken> provider) { this.provider = provider; } @Override public String getName() { return provider.get().getName(); } @Override public String getRawToken() { return provider.get().getRawToken(); } @Override public String getIssuer() { return provider.get().getIssuer(); } @Override public Set<String> getAudience() { return provider.get().getAudience(); } @Override public String getSubject() { return provider.get().getSubject(); } @Override public String getTokenID() { return provider.get().getTokenID(); } @Override public long getExpirationTime() { return provider.get().getExpirationTime(); } @Override public long getIssuedAtTime() { return provider.get().getIssuedAtTime(); } @Override public Set<String> getGroups() { return provider.get().getGroups(); } @Override public Set<String> getClaimNames() { return provider.get().getClaimNames(); } @Override public boolean containsClaim(String claimName) { return provider.get().containsClaim(claimName); } @Override public <T> T getClaim(final String claimName) { return provider.get().getClaim(claimName); } @Override public <T> Optional<T> claim(String claimName) { return provider.get().claim(claimName); } @Override public boolean implies(final Subject subject) { return provider.get().implies(subject); } @Override public String toString() { return provider.get().toString(); } }
5,691
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/jwt/DateValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.jwt; import static java.util.Optional.ofNullable; import java.net.HttpURLConnection; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.json.JsonNumber; import javax.json.JsonObject; import org.apache.geronimo.microprofile.impl.jwtauth.JwtException; import org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig; import org.eclipse.microprofile.jwt.Claims; import org.eclipse.microprofile.jwt.config.Names; @ApplicationScoped public class DateValidator { @Inject private GeronimoJwtAuthConfig config; private boolean expirationMandatory; private boolean issuedAtTimeMandatory; private long tolerance; @PostConstruct private void init() { expirationMandatory = Boolean.parseBoolean(config.read("exp.required", "true")); issuedAtTimeMandatory = Boolean.parseBoolean(config.read("iat.required", "true")); tolerance = Long.parseLong(config.read("date.tolerance", Long.toString(ofNullable(config.read("org.eclipse.microprofile.authentication.JWT.clockSkew", null)) .map(Long::parseLong) .orElse(60L)))); } public void checkInterval(final JsonObject payload) { long now = -1; final JsonNumber exp = payload.getJsonNumber(Claims.exp.name()); if (exp == null) { if (expirationMandatory) { throw new JwtException("No exp in the JWT", HttpURLConnection.HTTP_UNAUTHORIZED); } } else { final long expValue = exp.longValue(); now = now(); if (expValue < now - tolerance) { throw new JwtException("Token expired", HttpURLConnection.HTTP_UNAUTHORIZED); } } final JsonNumber iat = payload.getJsonNumber(Claims.iat.name()); if (iat == null) { if (issuedAtTimeMandatory) { throw new JwtException("No iat in the JWT", HttpURLConnection.HTTP_UNAUTHORIZED); } } else { final long iatValue = iat.longValue(); if (now < 0) { now = now(); } if (iatValue > now + tolerance) { throw new JwtException("Token issued after current time", HttpURLConnection.HTTP_UNAUTHORIZED); } } } private long now() { return System.currentTimeMillis() / 1000; } }
5,692
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/jwt/SignatureValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.jwt; import static java.util.stream.Collectors.toSet; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Base64; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; import javax.annotation.PostConstruct; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.apache.geronimo.microprofile.impl.jwtauth.JwtException; import org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig; @ApplicationScoped public class SignatureValidator { @Inject private GeronimoJwtAuthConfig config; private Set<String> supportedAlgorithms; private String jcaProvider; private boolean useCache; private final ConcurrentMap<String, PublicKey> publicKeyCache = new ConcurrentHashMap<>(); @PostConstruct private void init() { useCache = Boolean.parseBoolean(config.read("public-key.cache.active", "true")); supportedAlgorithms = Stream.of(config.read("header.alg.supported", "RS256").split(",")) .map(String::trim) .map(s -> s.toLowerCase(Locale.ROOT)) .filter(s -> !s.isEmpty()) .collect(toSet()); jcaProvider = config.read("jca.provider", null); } public void verifySignature(final String alg, final String key, final String signingString, final String expected) { final String normalizedAlg = alg.toLowerCase(Locale.ROOT); if (!supportedAlgorithms.contains(normalizedAlg)) { throw new JwtException("Unsupported algorithm", HttpURLConnection.HTTP_UNAUTHORIZED); } switch (normalizedAlg) { case "rs256": verifySignature(toPublicKey(key, "RSA"), signingString, expected, "SHA256withRSA"); break; case "rs384": verifySignature(toPublicKey(key, "RSA"), signingString, expected, "SHA384withRSA"); break; case "rs512": verifySignature(toPublicKey(key, "RSA"), signingString, expected, "SHA512withRSA"); break; case "hs256": verifyMac(toSecretKey(key, "HmacSHA256"), signingString, expected); break; case "hs384": verifyMac(toSecretKey(key, "HmacSHA384"), signingString, expected); break; case "hs512": verifyMac(toSecretKey(key, "HmacSHA512"), signingString, expected); break; case "es256": verifySignature(toPublicKey(key, "EC"), signingString, expected, "SHA256withECDSA"); break; case "es384": verifySignature(toPublicKey(key, "EC"), signingString, expected, "SHA384withECDSA"); break; case "es512": verifySignature(toPublicKey(key, "EC"), signingString, expected, "SHA512withECDSA"); break; default: throw new IllegalArgumentException("Unsupported algorithm: " + normalizedAlg); } } private SecretKey toSecretKey(final String key, final String algo) { return new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algo); } private PublicKey toPublicKey(final String key, final String algo) { PublicKey publicKey = useCache ? publicKeyCache.get(key) : null; if (publicKey == null) { final byte[] decoded = Base64.getDecoder().decode(key .replace("-----BEGIN RSA KEY-----", "") .replace("-----END RSA KEY-----", "") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replace("-----BEGIN RSA PUBLIC KEY-----", "") .replace("-----END RSA PUBLIC KEY-----", "") .replace("\n", "") .trim()); try { switch (algo) { case "RSA": { final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded); final KeyFactory keyFactory = KeyFactory.getInstance(algo); publicKey = keyFactory.generatePublic(keySpec); if (useCache) { publicKeyCache.putIfAbsent(key, publicKey); } break; } case "EC": // TODO default: throw new JwtException("Invalid signing", HttpURLConnection.HTTP_UNAUTHORIZED); } } catch (final Exception e) { throw new JwtException("Invalid signing", HttpURLConnection.HTTP_UNAUTHORIZED); } } return publicKey; } private void verifyMac(final SecretKey key, final String signingString, final String expected) { try { final Mac signature = jcaProvider == null ? Mac.getInstance(key.getAlgorithm()) : Mac.getInstance(key.getAlgorithm(), jcaProvider); signature.init(key); signature.update(signingString.getBytes(StandardCharsets.UTF_8)); if (!Arrays.equals(signature.doFinal(), Base64.getUrlDecoder().decode(expected))) { invalidSignature(); } } catch (final Exception e) { invalidSignature(); } } private void verifySignature(final PublicKey publicKey, final String signingString, final String expected, final String algo) { try { final Signature signature = jcaProvider == null ? Signature.getInstance(algo) : Signature.getInstance(algo, jcaProvider); signature.initVerify(publicKey); signature.update(signingString.getBytes(StandardCharsets.UTF_8)); if (!signature.verify(Base64.getUrlDecoder().decode(expected))) { invalidSignature(); } } catch (final Exception e) { invalidSignature(); } } private void invalidSignature() { throw new JwtException("Invalid signature", HttpURLConnection.HTTP_UNAUTHORIZED); } }
5,693
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/jwt/JwtParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.jwt; import static java.util.Collections.emptyMap; import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; import java.util.Base64; import java.util.Collection; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReaderFactory; import javax.json.JsonString; import org.apache.geronimo.microprofile.impl.jwtauth.JwtException; import org.apache.geronimo.microprofile.impl.jwtauth.cdi.GeronimoJwtAuthExtension; import org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig; import org.eclipse.microprofile.jwt.Claims; import org.eclipse.microprofile.jwt.JsonWebToken; @ApplicationScoped public class JwtParser { @Inject private GeronimoJwtAuthConfig config; @Inject private KidMapper kidMapper; @Inject private DateValidator dateValidator; @Inject private SignatureValidator signatureValidator; @Inject private GeronimoJwtAuthExtension extension; private JsonReaderFactory readerFactory; private String defaultKid; private String defaultAlg; private String defaultTyp; private boolean validateTyp; @PostConstruct private void init() { readerFactory = Json.createReaderFactory(emptyMap()); defaultKid = config.read("jwt.header.kid.default", null); defaultAlg = config.read("jwt.header.alg.default", "RS256"); defaultTyp = config.read("jwt.header.typ.default", "JWT"); validateTyp = Boolean.parseBoolean(config.read("jwt.header.typ.validate", "true")); } public JsonWebToken parse(final String jwt) { final int firstDot = jwt.indexOf('.'); if (firstDot < 0) { throw new JwtException("JWT is not valid", HttpURLConnection.HTTP_BAD_REQUEST); } final int secondDot = jwt.indexOf('.', firstDot + 1); if (secondDot < 0 || jwt.indexOf('.', secondDot + 1) > 0 || jwt.length() <= secondDot) { throw new JwtException("JWT is not valid", HttpURLConnection.HTTP_BAD_REQUEST); } final String rawHeader = jwt.substring(0, firstDot); final JsonObject header = loadJson(rawHeader); if (validateTyp && !getAttribute(header, "typ", defaultTyp).equalsIgnoreCase("jwt")) { throw new JwtException("Invalid typ", HttpURLConnection.HTTP_UNAUTHORIZED); } final JsonObject payload = loadJson(jwt.substring(firstDot + 1, secondDot)); dateValidator.checkInterval(payload); final String alg = getAttribute(header, "alg", defaultAlg); final String kid = getAttribute(header, "kid", defaultKid); final Collection<String> issuers = kidMapper.loadIssuers(kid); if (!issuers.isEmpty() && issuers.stream().noneMatch(it -> it.equals(payload.getString(Claims.iss.name())))) { throw new JwtException("Invalid issuer", HttpURLConnection.HTTP_UNAUTHORIZED); } signatureValidator.verifySignature(alg, kidMapper.loadKey(kid), jwt.substring(0, secondDot), jwt.substring(secondDot + 1)); return createToken(jwt, payload); } public GeronimoJsonWebToken createToken(final String jwt, final JsonObject payload) { return new GeronimoJsonWebToken(jwt, payload); } private String getAttribute(final JsonObject payload, final String key, final String def) { final JsonString json = payload.getJsonString(key); final String value = json != null ? json.getString() : def; if (value == null) { throw new JwtException("No " + key + " in JWT", HttpURLConnection.HTTP_UNAUTHORIZED); } return value; } private JsonObject loadJson(final String src) { return readerFactory.createReader(new ByteArrayInputStream(Base64.getUrlDecoder().decode(src))).readObject(); } }
5,694
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/jwt/GeronimoJsonWebToken.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.jwt; import static java.util.stream.Collectors.toSet; import java.util.Set; import java.util.stream.Stream; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonString; import javax.json.JsonValue; import org.eclipse.microprofile.jwt.Claims; import org.eclipse.microprofile.jwt.JsonWebToken; class GeronimoJsonWebToken implements JsonWebToken { private final JsonObject delegate; private final String raw; GeronimoJsonWebToken(final String raw, final JsonObject delegate) { this.raw = raw; this.delegate = delegate; } @Override public String getName() { return getClaim(Claims.upn.name()); } @Override public Set<String> getClaimNames() { return delegate.keySet(); } @Override public <T> T getClaim(final String claimName) { try { final Claims claim = Claims.valueOf(claimName); if (claim == Claims.raw_token) { return (T) raw; } if (claim.getType() == String.class) { return (T) delegate.getString(claimName); } if (claim.getType() == Long.class) { return (T) Long.valueOf(delegate.getJsonNumber(claimName).longValue()); } if (claim.getType() == JsonObject.class) { return (T) delegate.getJsonObject(claimName); } if (claim.getType() == Set.class) { final JsonValue jsonValue = delegate.get(claimName); if (jsonValue == null) { return null; } if (jsonValue.getValueType() == JsonValue.ValueType.ARRAY) { return (T) JsonArray.class.cast(jsonValue).stream() .map(this::toString) .collect(toSet()); } if (jsonValue.getValueType() == JsonValue.ValueType.STRING) { return (T) Stream.of(JsonString.class.cast(jsonValue).getString().split(",")) .collect(toSet()); } return (T) jsonValue; } return (T) delegate.get(claimName); } catch (final IllegalArgumentException iae) { return (T) delegate.get(claimName); } } private String toString(final Object value) { if (JsonString.class.isInstance(value)) { return JsonString.class.cast(value).getString(); } if (JsonNumber.class.isInstance(value)) { return String.valueOf(JsonNumber.class.cast(value).doubleValue()); } return value.toString(); } @Override public String toString() { return delegate.toString(); } }
5,695
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/servlet/JwtRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.servlet; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toList; import java.security.Principal; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import java.util.concurrent.Callable; import java.util.function.Supplier; import java.util.stream.Stream; import javax.security.auth.Subject; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.apache.geronimo.microprofile.impl.jwtauth.JwtException; import org.apache.geronimo.microprofile.impl.jwtauth.jwt.JwtParser; import org.eclipse.microprofile.jwt.JsonWebToken; public class JwtRequest extends HttpServletRequestWrapper implements TokenAccessor { private final Supplier<JsonWebToken> tokenExtractor; private final String headerName; private volatile JsonWebToken token; // cache for perf reasons public JwtRequest(final JwtParser service, final String header, final String cookie, final String prefix, final HttpServletRequest request) { super(request); this.headerName = header; this.tokenExtractor = () -> { if (token != null) { return token; } synchronized (this) { if (token != null) { return token; } final Object existing = getAttribute(JsonWebToken.class.getName()); if (existing != null) { token = JsonWebToken.class.isInstance(existing) ? JsonWebToken.class.cast(existing) : service.parse(String.valueOf(existing)); return token; } boolean fromHeader = true; String auth = String.class.cast( getAttribute("org.apache.geronimo.microprofile.impl.jwtauth.jaxrs.JAXRSRequestForwarder.header")); if (auth == null) { auth = getHeader(header); } if (auth == null) { final Cookie[] cookies = getCookies(); if (cookies != null) { fromHeader = false; auth = Stream.of(cookies) .filter(it -> cookie.equalsIgnoreCase(it.getName())) .findFirst() .map(Cookie::getValue) .orElse(null); } } if (auth == null || auth.isEmpty()) { throw new JwtException("No " + header + " header", HttpServletResponse.SC_UNAUTHORIZED); } if (fromHeader) { if (!auth.toLowerCase(Locale.ROOT).startsWith(prefix)) { throw new JwtException("No prefix " + prefix + " in header " + header, HttpServletResponse.SC_UNAUTHORIZED); } token = service.parse(auth.substring(prefix.length())); } else { token = service.parse(auth.startsWith(prefix) ? auth.substring(prefix.length()) : auth); } setAttribute(JsonWebToken.class.getName(), token); return token; } }; // integration hook if needed setAttribute(JwtRequest.class.getName(), this); setAttribute(JsonWebToken.class.getName() + ".supplier", tokenExtractor); setAttribute(Principal.class.getName() + ".supplier", tokenExtractor); // not portable but used by some servers like tomee setAttribute("javax.security.auth.subject.callable", (Callable<Subject>) () -> { final Set<Principal> principals = new LinkedHashSet<>(); final JsonWebToken namePrincipal = tokenExtractor.get(); principals.add(namePrincipal); principals.addAll(namePrincipal.getGroups().stream().map(role -> (Principal) () -> role).collect(toList())); return new Subject(true, principals, emptySet(), emptySet()); }); } public String getHeaderName() { return headerName; } public TokenAccessor asTokenAccessor() { return this; } @Override public JsonWebToken getToken() { return tokenExtractor.get(); } @Override public Principal getUserPrincipal() { return tokenExtractor.get(); } @Override public boolean isUserInRole(final String role) { return tokenExtractor.get().getGroups().contains(role); } @Override public String getAuthType() { return "MP-JWT"; } }
5,696
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/servlet/TokenAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.servlet; import org.eclipse.microprofile.jwt.JsonWebToken; public interface TokenAccessor { JsonWebToken getToken(); }
5,697
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/servlet/GeronimoJwtAuthInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.servlet; import static java.util.Optional.ofNullable; import java.util.Comparator; import java.util.EnumSet; import java.util.Set; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.annotation.HandlesTypes; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig; import org.eclipse.microprofile.auth.LoginConfig; @HandlesTypes(LoginConfig.class) public class GeronimoJwtAuthInitializer implements ServletContainerInitializer { @Override public void onStartup(final Set<Class<?>> classes, final ServletContext ctx) { final GeronimoJwtAuthConfig config = GeronimoJwtAuthConfig.create(); final boolean forceSetup = "true".equalsIgnoreCase(config.read("filter.active", "false")); if (forceSetup) { doSetup(ctx, config, null); return; } ofNullable(classes).filter(c -> !c.isEmpty()) .flatMap(marked -> marked.stream() .filter(Application.class::isAssignableFrom) // needed? what's the issue dropping it? nothing normally .filter(app -> app.isAnnotationPresent(LoginConfig.class) && "MP-JWT".equalsIgnoreCase(app.getAnnotation(LoginConfig.class).authMethod())) .min(Comparator.comparing(Class::getName))) // to be deterministic .ifPresent(app -> doSetup(ctx, config, app)); } private void doSetup(final ServletContext ctx, final GeronimoJwtAuthConfig config, final Class<?> app) { final FilterRegistration.Dynamic filter = ctx.addFilter("geronimo-microprofile-jwt-auth-filter", GeronimoJwtAuthFilter.class); filter.setAsyncSupported(true); final String[] mappings = ofNullable(app).map(a -> a.getAnnotation(ApplicationPath.class)) .map(ApplicationPath::value) .map(v -> (!v.startsWith("/") ? "/" : "") + (v.contains("{") ? v.substring(0, v.indexOf("{")) : v) + (v.endsWith("/") ? "" : "/") + "*") .map(v -> new String[]{v}) .orElseGet(() -> { final ServletRegistration defaultServlet = ctx.getServletRegistration(Application.class.getName()); if (defaultServlet != null && !defaultServlet.getMappings().isEmpty()) { return defaultServlet.getMappings().toArray(new String[defaultServlet.getMappings().size()]); } final String[] servletMapping = ctx.getServletRegistrations().values().stream() .filter(r -> r.getInitParameter("javax.ws.rs.Application") != null) .flatMap(r -> r.getMappings().stream()) .toArray(String[]::new); if (servletMapping.length > 0) { return servletMapping; } // unlikely return new String[]{config.read("filter.mapping.default", "/*")}; }); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, mappings); } }
5,698
0
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth
Create_ds/geronimo-jwt-auth/src/main/java/org/apache/geronimo/microprofile/impl/jwtauth/servlet/GeronimoJwtAuthFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.microprofile.impl.jwtauth.servlet; import static java.util.stream.Collectors.toSet; import java.io.IOException; import java.util.Collection; import java.util.Optional; import java.util.stream.Stream; import javax.enterprise.inject.spi.CDI; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.geronimo.microprofile.impl.jwtauth.JwtException; import org.apache.geronimo.microprofile.impl.jwtauth.cdi.GeronimoJwtAuthExtension; import org.apache.geronimo.microprofile.impl.jwtauth.config.GeronimoJwtAuthConfig; import org.apache.geronimo.microprofile.impl.jwtauth.jwt.JwtParser; public class GeronimoJwtAuthFilter implements Filter { private String headerName; private String cookieName; private String prefix; private JwtParser service; private GeronimoJwtAuthExtension extension; private Collection<String> publicUrls; @Override public void init(final FilterConfig filterConfig) { final CDI<Object> current = CDI.current(); service = current.select(JwtParser.class).get(); extension = current.select(GeronimoJwtAuthExtension.class).get(); final GeronimoJwtAuthConfig config = current.select(GeronimoJwtAuthConfig.class).get(); headerName = config.read("header.name", "Authorization"); cookieName = config.read("cookie.name", "Bearer"); prefix = Optional.of(config.read("header.prefix", "bearer")) .filter(s -> !s.isEmpty()).map(s -> s + " ") .orElse(""); publicUrls = Stream.of(config.read("filter.publicUrls", "").split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(toSet()); } @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (!HttpServletRequest.class.isInstance(request)) { chain.doFilter(request, response); return; } final HttpServletRequest httpServletRequest = HttpServletRequest.class.cast(request); if (!publicUrls.isEmpty()) { final String current = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()); if (publicUrls.stream().anyMatch(current::startsWith)) { chain.doFilter(request, response); return; } } try { final JwtRequest req = new JwtRequest(service, headerName, cookieName, prefix, httpServletRequest); extension.execute(req.asTokenAccessor(), () -> chain.doFilter(req, response)); } catch (final Exception e) { // when not used with JAX-RS but directly Servlet final HttpServletResponse httpServletResponse = HttpServletResponse.class.cast(response); if (!httpServletResponse.isCommitted()) { Throwable current = e; while (current != null) { if (JwtException.class.isInstance(current)) { final JwtException ex = JwtException.class.cast(current); httpServletResponse.sendError(ex.getStatus(), ex.getMessage()); return; } if (current == current.getCause()) { break; } current = current.getCause(); } } throw e; } } @Override public void destroy() { // no-op } }
5,699