index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3/rest/LoadBalancerSpringResourceTest.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import java.util.Optional;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.grpc.protogen.AddLoadBalancerRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.LoadBalancerId;
import com.netflix.titus.grpc.protogen.RemoveLoadBalancerRequest;
import com.netflix.titus.runtime.service.LoadBalancerService;
import com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil.JUNIT_REST_CALL_METADATA;
import static com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil.NEXT_PAGE_OF_1;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebMvcTest
@ContextConfiguration(classes = {LoadBalancerSpringResource.class, ProtobufHttpMessageConverter.class})
public class LoadBalancerSpringResourceTest {
private static final String JOB_ID = "myJobId";
private static final String LOAD_BALANCER_ID = "lb1";
private static final GetJobLoadBalancersResult GET_JOB_LOAD_BALANCERS_RESULT = GetJobLoadBalancersResult.newBuilder()
.setJobId(JOB_ID)
.addLoadBalancers(LoadBalancerId.newBuilder().setId(LOAD_BALANCER_ID).build())
.build();
@MockBean
private LoadBalancerService serviceMock;
@MockBean
private SystemLogService systemLogService;
@Autowired
private MockMvc mockMvc;
@Test
public void testGetJobLoadBalancers() throws Exception {
JobId jobIdWrapper = JobId.newBuilder().setId(JOB_ID).build();
when(serviceMock.getLoadBalancers(jobIdWrapper, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(GET_JOB_LOAD_BALANCERS_RESULT));
GetJobLoadBalancersResult entity = SpringMockMvcUtil.doGet(mockMvc, String.format("/api/v3/loadBalancers/%s", JOB_ID), GetJobLoadBalancersResult.class);
assertThat(entity).isEqualTo(GET_JOB_LOAD_BALANCERS_RESULT);
verify(serviceMock, times(1)).getLoadBalancers(jobIdWrapper, JUNIT_REST_CALL_METADATA);
}
@Test
public void testGetAllLoadBalancers() throws Exception {
GetAllLoadBalancersRequest request = GetAllLoadBalancersRequest.newBuilder().setPage(NEXT_PAGE_OF_1).build();
GetAllLoadBalancersResult response = GetAllLoadBalancersResult.newBuilder()
.setPagination(SpringMockMvcUtil.paginationOf(NEXT_PAGE_OF_1))
.addJobLoadBalancers(GET_JOB_LOAD_BALANCERS_RESULT)
.build();
when(serviceMock.getAllLoadBalancers(request, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(response));
GetAllLoadBalancersResult entity = SpringMockMvcUtil.doPaginatedGet(mockMvc, "/api/v3/loadBalancers", GetAllLoadBalancersResult.class, NEXT_PAGE_OF_1);
assertThat(entity).isEqualTo(response);
verify(serviceMock, times(1)).getAllLoadBalancers(request, JUNIT_REST_CALL_METADATA);
}
@Test
public void testAddLoadBalancer() throws Exception {
AddLoadBalancerRequest forwardedRequest = AddLoadBalancerRequest.newBuilder()
.setJobId(JOB_ID)
.setLoadBalancerId(LoadBalancerId.newBuilder().setId(LOAD_BALANCER_ID).build())
.build();
when(serviceMock.addLoadBalancer(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPost(
mockMvc,
"/api/v3/loadBalancers",
Optional.empty(),
Optional.empty(),
Optional.of(new String[]{"jobId", JOB_ID, "loadBalancerId", LOAD_BALANCER_ID})
);
verify(serviceMock, times(1)).addLoadBalancer(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testRemoveLoadBalancer() throws Exception {
RemoveLoadBalancerRequest forwardedRequest = RemoveLoadBalancerRequest.newBuilder()
.setJobId(JOB_ID)
.setLoadBalancerId(LoadBalancerId.newBuilder().setId(LOAD_BALANCER_ID).build())
.build();
when(serviceMock.removeLoadBalancer(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doDelete(
mockMvc,
"/api/v3/loadBalancers",
"jobId", JOB_ID, "loadBalancerId", LOAD_BALANCER_ID
);
verify(serviceMock, times(1)).removeLoadBalancer(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
} | 300 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3/rest/JobManagementSpringResourceTest.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import java.util.Optional;
import com.google.protobuf.UInt32Value;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.grpc.protogen.Capacity;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobCapacityWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudget;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.ServiceJobSpec;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import com.netflix.titus.runtime.endpoint.common.EmptyLogStorageInfo;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.jobmanager.gateway.JobServiceGateway;
import com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil;
import com.netflix.titus.testkit.model.eviction.DisruptionBudgetGenerator;
import com.netflix.titus.testkit.model.job.JobDescriptorGenerator;
import com.netflix.titus.testkit.model.job.JobGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters.toGrpcDisruptionBudget;
import static com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters.toGrpcJob;
import static com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters.toGrpcJobDescriptor;
import static com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters.toGrpcTask;
import static com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil.JUNIT_REST_CALL_METADATA;
import static com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil.NEXT_PAGE_OF_2;
import static com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil.paginationOf;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebMvcTest()
@ContextConfiguration(classes = {JobManagementSpringResource.class, ProtobufHttpMessageConverter.class})
public class JobManagementSpringResourceTest {
private static final Job JOB_1 = toGrpcJob(JobGenerator.oneBatchJob()).toBuilder().setId("myJob1").build();
private static final Job JOB_2 = toGrpcJob(JobGenerator.oneBatchJob()).toBuilder().setId("myJob2").build();
private static final String JOB_ID_1 = JOB_1.getId();
private static final JobDescriptor JOB_DESCRIPTOR_1 = toGrpcJobDescriptor(JobDescriptorGenerator.oneTaskBatchJobDescriptor());
private static final Task TASK_1 = toGrpcTask(JobGenerator.oneBatchTask(), EmptyLogStorageInfo.empty()).toBuilder().setId("myTask1").build();
private static final Task TASK_2 = toGrpcTask(JobGenerator.oneBatchTask(), EmptyLogStorageInfo.empty()).toBuilder().setId("myTask2").build();
private static final String TASK_ID_1 = TASK_1.getId();
@MockBean
public JobServiceGateway jobServiceGatewayMock;
@MockBean
public SystemLogService systemLog;
@Autowired
private MockMvc mockMvc;
@Before
public void setUp() {
}
@Test
public void testCreateJob() throws Exception {
when(jobServiceGatewayMock.createJob(JOB_DESCRIPTOR_1, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(JOB_ID_1));
JobId entity = SpringMockMvcUtil.doPost(mockMvc, "/api/v3/jobs", JOB_DESCRIPTOR_1, JobId.class);
assertThat(entity.getId()).isEqualTo(JOB_ID_1);
verify(jobServiceGatewayMock, times(1)).createJob(JOB_DESCRIPTOR_1, JUNIT_REST_CALL_METADATA);
}
@Test
public void testSetInstances() throws Exception {
Capacity capacity = Capacity.newBuilder().setMin(1).setDesired(2).setMax(3).build();
JobCapacityUpdate forwardedRequest = JobCapacityUpdate.newBuilder().setJobId(JOB_ID_1).setCapacity(capacity).build();
when(jobServiceGatewayMock.updateJobCapacity(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/jobs/%s/instances", JOB_ID_1), capacity);
verify(jobServiceGatewayMock, times(1)).updateJobCapacity(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testSetCapacityWithOptionalAttributes() throws Exception {
JobCapacityWithOptionalAttributes restRequest = JobCapacityWithOptionalAttributes.newBuilder()
.setMin(UInt32Value.newBuilder().setValue(1).build())
.setDesired(UInt32Value.newBuilder().setValue(2).build())
.setMax(UInt32Value.newBuilder().setValue(3).build())
.build();
JobCapacityUpdateWithOptionalAttributes forwardedRequest = JobCapacityUpdateWithOptionalAttributes.newBuilder()
.setJobId(JOB_ID_1)
.setJobCapacityWithOptionalAttributes(restRequest)
.build();
when(jobServiceGatewayMock.updateJobCapacityWithOptionalAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/jobs/%s/capacityAttributes", JOB_ID_1), restRequest);
verify(jobServiceGatewayMock, times(1)).updateJobCapacityWithOptionalAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testSetJobProcesses() throws Exception {
ServiceJobSpec.ServiceJobProcesses restRequest = ServiceJobSpec.ServiceJobProcesses.newBuilder()
.setDisableDecreaseDesired(true)
.setDisableIncreaseDesired(true)
.build();
JobProcessesUpdate forwardedRequest = JobProcessesUpdate.newBuilder()
.setJobId(JOB_ID_1)
.setServiceJobProcesses(restRequest)
.build();
when(jobServiceGatewayMock.updateJobProcesses(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/jobs/%s/jobprocesses", JOB_ID_1), restRequest);
verify(jobServiceGatewayMock, times(1)).updateJobProcesses(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testSetJobDisruptionBudget() throws Exception {
JobDisruptionBudget restRequest = toGrpcDisruptionBudget(DisruptionBudgetGenerator.budgetSelfManagedBasic());
JobDisruptionBudgetUpdate forwardedRequest = JobDisruptionBudgetUpdate.newBuilder()
.setJobId(JOB_ID_1)
.setDisruptionBudget(restRequest)
.build();
when(jobServiceGatewayMock.updateJobDisruptionBudget(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Mono.empty());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/jobs/%s/disruptionBudget", JOB_ID_1), restRequest);
verify(jobServiceGatewayMock, times(1)).updateJobDisruptionBudget(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testUpdateJobAttributes() throws Exception {
JobAttributesUpdate restRequest = JobAttributesUpdate.newBuilder()
.setJobId(JOB_ID_1)
.putAttributes("keyA", "valueA")
.build();
when(jobServiceGatewayMock.updateJobAttributes(restRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Mono.empty());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/jobs/%s/attributes", JOB_ID_1), restRequest);
verify(jobServiceGatewayMock, times(1)).updateJobAttributes(restRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testDeleteJobAttributes() throws Exception {
JobAttributesDeleteRequest forwardedRequest = JobAttributesDeleteRequest.newBuilder()
.setJobId(JOB_ID_1)
.addKeys("keyA")
.build();
when(jobServiceGatewayMock.deleteJobAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Mono.empty());
SpringMockMvcUtil.doDelete(mockMvc, String.format("/api/v3/jobs/%s/attributes", JOB_ID_1), "keys", "keyA");
verify(jobServiceGatewayMock, times(1)).deleteJobAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testEnableJob() throws Exception {
JobStatusUpdate forwardedRequest = JobStatusUpdate.newBuilder()
.setId(JOB_ID_1)
.setEnableStatus(true)
.build();
when(jobServiceGatewayMock.updateJobStatus(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPost(mockMvc, String.format("/api/v3/jobs/%s/enable", JOB_ID_1));
verify(jobServiceGatewayMock, times(1)).updateJobStatus(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testDisableJob() throws Exception {
JobStatusUpdate forwardedRequest = JobStatusUpdate.newBuilder()
.setId(JOB_ID_1)
.setEnableStatus(false)
.build();
when(jobServiceGatewayMock.updateJobStatus(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPost(mockMvc, String.format("/api/v3/jobs/%s/disable", JOB_ID_1));
verify(jobServiceGatewayMock, times(1)).updateJobStatus(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testFindJob() throws Exception {
when(jobServiceGatewayMock.findJob(JOB_ID_1, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(JOB_1));
Job entity = SpringMockMvcUtil.doGet(mockMvc, String.format("/api/v3/jobs/%s", JOB_ID_1), Job.class);
assertThat(entity).isEqualTo(JOB_1);
verify(jobServiceGatewayMock, times(1)).findJob(JOB_ID_1, JUNIT_REST_CALL_METADATA);
}
@Test
public void testFindJobs() throws Exception {
JobQuery forwardedRequest = JobQuery.newBuilder()
.putFilteringCriteria("filter1", "value1")
.setPage(NEXT_PAGE_OF_2)
.build();
JobQueryResult expectedResult = JobQueryResult.newBuilder()
.setPagination(paginationOf(NEXT_PAGE_OF_2))
.addAllItems(asList(JOB_1, JOB_2))
.build();
when(jobServiceGatewayMock.findJobs(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(expectedResult));
JobQueryResult entity = SpringMockMvcUtil.doPaginatedGet(mockMvc, "/api/v3/jobs", JobQueryResult.class, NEXT_PAGE_OF_2, "filter1", "value1");
assertThat(entity).isEqualTo(expectedResult);
verify(jobServiceGatewayMock, times(1)).findJobs(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testKillJob() throws Exception {
when(jobServiceGatewayMock.killJob(JOB_ID_1, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doDelete(mockMvc, String.format("/api/v3/jobs/%s", JOB_ID_1));
verify(jobServiceGatewayMock, times(1)).killJob(JOB_ID_1, JUNIT_REST_CALL_METADATA);
}
@Test
public void testFindTask() throws Exception {
when(jobServiceGatewayMock.findTask(TASK_ID_1, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(TASK_1));
Task entity = SpringMockMvcUtil.doGet(mockMvc, String.format("/api/v3/tasks/%s", TASK_ID_1), Task.class);
assertThat(entity).isEqualTo(TASK_1);
verify(jobServiceGatewayMock, times(1)).findTask(TASK_ID_1, JUNIT_REST_CALL_METADATA);
}
@Test
public void testFindTasks() throws Exception {
TaskQuery forwardedRequest = TaskQuery.newBuilder()
.putFilteringCriteria("filter1", "value1")
.setPage(NEXT_PAGE_OF_2)
.build();
TaskQueryResult expectedResult = TaskQueryResult.newBuilder()
.setPagination(paginationOf(NEXT_PAGE_OF_2))
.addAllItems(asList(TASK_1, TASK_2))
.build();
when(jobServiceGatewayMock.findTasks(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(expectedResult));
TaskQueryResult entity = SpringMockMvcUtil.doPaginatedGet(mockMvc, "/api/v3/tasks", TaskQueryResult.class, NEXT_PAGE_OF_2, "filter1", "value1");
assertThat(entity).isEqualTo(expectedResult);
verify(jobServiceGatewayMock, times(1)).findTasks(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void taskKillTask() throws Exception {
TaskKillRequest forwardedRequest = TaskKillRequest.newBuilder()
.setTaskId(TASK_ID_1)
.setShrink(true)
.setPreventMinSizeUpdate(true)
.build();
when(jobServiceGatewayMock.killTask(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doDelete(mockMvc, String.format("/api/v3/tasks/%s", TASK_ID_1), "shrink", "true", "preventMinSizeUpdate", "true");
verify(jobServiceGatewayMock, times(1)).killTask(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testUpdateTaskAttributes() throws Exception {
TaskAttributesUpdate restRequest = TaskAttributesUpdate.newBuilder()
.setTaskId(TASK_ID_1)
.putAttributes("keyA", "valueA")
.build();
when(jobServiceGatewayMock.updateTaskAttributes(restRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/tasks/%s/attributes", TASK_ID_1), restRequest);
verify(jobServiceGatewayMock, times(1)).updateTaskAttributes(restRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testDeleteTaskAttributes() throws Exception {
TaskAttributesDeleteRequest forwardedRequest = TaskAttributesDeleteRequest.newBuilder()
.setTaskId(TASK_ID_1)
.addKeys("keyA")
.build();
when(jobServiceGatewayMock.deleteTaskAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doDelete(mockMvc, String.format("/api/v3/tasks/%s/attributes", TASK_ID_1), "keys", "keyA");
verify(jobServiceGatewayMock, times(1)).deleteTaskAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Test
public void testMoveTask() throws Exception {
TaskMoveRequest request = TaskMoveRequest.newBuilder()
.setSourceJobId(JOB_ID_1)
.setTargetJobId(JOB_2.getId())
.setTaskId(TASK_ID_1)
.build();
when(jobServiceGatewayMock.moveTask(request, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPost(mockMvc, "/api/v3/tasks/move", request);
verify(jobServiceGatewayMock, times(1)).moveTask(request, JUNIT_REST_CALL_METADATA);
}
}
| 301 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3/rest/LoadBalancerResourceTest.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.service.LoadBalancerService;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.CURSOR_QUERY_KEY;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.PAGE_QUERY_KEY;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.PAGE_SIZE_QUERY_KEY;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/**
* Tests the {@link LoadBalancerResource} class.
*/
public class LoadBalancerResourceTest {
@Mock
private LoadBalancerService loadBalancerService;
@Mock
private UriInfo uriInfo;
@Mock
private SystemLogService systemLog;
@Mock
private CallMetadataResolver callMetadataResolver;
private LoadBalancerResource loadBalancerResource;
private static final String TEST_JOB_ID = "job-id";
private static final String TEST_LOAD_BALANCER_ID = "load-balancer_id";
@Before
public void beforeAll() {
MockitoAnnotations.initMocks(this);
this.loadBalancerResource = new LoadBalancerResource(loadBalancerService, systemLog, callMetadataResolver);
}
@Test
public void getJobLoadBalancersTest() {
GetJobLoadBalancersResult expectedResult = GetJobLoadBalancersResult.newBuilder().build();
when(loadBalancerService.getLoadBalancers(any(), any())).thenReturn(Observable.just(expectedResult));
GetJobLoadBalancersResult actualResult = loadBalancerResource.getJobLoadBalancers(TEST_JOB_ID);
assertEquals(expectedResult, actualResult);
}
@Test
public void getAllJobsTest() {
GetAllLoadBalancersResult expectedResult = GetAllLoadBalancersResult.newBuilder().build();
when(uriInfo.getQueryParameters()).thenReturn(getDefaultPageParameters());
when(loadBalancerService.getAllLoadBalancers(any(), any())).thenReturn(Observable.just(expectedResult));
GetAllLoadBalancersResult actualResult = loadBalancerResource.getAllLoadBalancers(uriInfo);
assertEquals(expectedResult, actualResult);
}
@Test
public void addLoadBalancerSucceededTest() {
when(loadBalancerService.addLoadBalancer(any(), any())).thenReturn(Completable.complete());
Response response = loadBalancerResource.addLoadBalancer(TEST_JOB_ID, TEST_LOAD_BALANCER_ID);
assertEquals(200, response.getStatus());
}
@Test(expected = TitusServiceException.class)
public void addLoadBalancerFailedTest() {
TitusServiceException exception = TitusServiceException.jobNotFound(TEST_JOB_ID);
when(loadBalancerService.addLoadBalancer(any(), any())).thenReturn(Completable.error(exception));
loadBalancerResource.addLoadBalancer(TEST_JOB_ID, TEST_LOAD_BALANCER_ID);
}
@Test
public void removeLoadBalancerSucceededTest() {
when(loadBalancerService.removeLoadBalancer(any(), any())).thenReturn(Completable.complete());
Response response = loadBalancerResource.removeLoadBalancer(TEST_JOB_ID, TEST_LOAD_BALANCER_ID);
assertEquals(200, response.getStatus());
}
@Test(expected = TitusServiceException.class)
public void removeLoadBalancerFailedTest() {
TitusServiceException exception = TitusServiceException.jobNotFound(TEST_JOB_ID);
when(loadBalancerService.removeLoadBalancer(any(), any())).thenReturn(Completable.error(exception));
loadBalancerResource.removeLoadBalancer(TEST_JOB_ID, TEST_LOAD_BALANCER_ID);
}
private static MultivaluedMap<String, String> getDefaultPageParameters() {
MultivaluedMap queryParameters = new MultivaluedMapImpl();
queryParameters.add(PAGE_QUERY_KEY, "0");
queryParameters.add(PAGE_SIZE_QUERY_KEY, "1");
queryParameters.add(CURSOR_QUERY_KEY, "");
return queryParameters;
}
}
| 302 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3/rest/AutoScalingSpringResourceTest.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import com.netflix.titus.grpc.protogen.DeletePolicyRequest;
import com.netflix.titus.grpc.protogen.GetPolicyResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.PutPolicyRequest;
import com.netflix.titus.grpc.protogen.ScalingPolicyID;
import com.netflix.titus.grpc.protogen.UpdatePolicyRequest;
import com.netflix.titus.runtime.service.AutoScalingService;
import com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.testkit.junit.spring.SpringMockMvcUtil.JUNIT_REST_CALL_METADATA;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebMvcTest()
@ContextConfiguration(classes = {AutoScalingSpringResource.class, ProtobufHttpMessageConverter.class})
public class AutoScalingSpringResourceTest {
private static final GetPolicyResult GET_POLICY_RESULT = GetPolicyResult.newBuilder().build();
private static final ScalingPolicyID SCALING_POLICY_ID = ScalingPolicyID.newBuilder().setId("myPolicyId").build();
@MockBean
private AutoScalingService serviceMock;
@Autowired
private MockMvc mockMvc;
@Test
public void testGetAllScalingPolicies() throws Exception {
when(serviceMock.getAllScalingPolicies(JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(GET_POLICY_RESULT));
GetPolicyResult entity = SpringMockMvcUtil.doGet(mockMvc, "/api/v3/autoscaling/scalingPolicies", GetPolicyResult.class);
assertThat(entity).isEqualTo(GET_POLICY_RESULT);
verify(serviceMock, times(1)).getAllScalingPolicies(JUNIT_REST_CALL_METADATA);
}
@Test
public void testGetScalingPolicyForJob() throws Exception {
JobId jobId = JobId.newBuilder().setId("myJobId").build();
when(serviceMock.getJobScalingPolicies(jobId, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(GET_POLICY_RESULT));
GetPolicyResult entity = SpringMockMvcUtil.doGet(mockMvc, String.format("/api/v3/autoscaling/scalingPolicies/%s", jobId.getId()), GetPolicyResult.class);
assertThat(entity).isEqualTo(GET_POLICY_RESULT);
verify(serviceMock, times(1)).getJobScalingPolicies(jobId, JUNIT_REST_CALL_METADATA);
}
@Test
public void testSetScalingPolicy() throws Exception {
PutPolicyRequest request = PutPolicyRequest.newBuilder().build();
when(serviceMock.setAutoScalingPolicy(request, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(SCALING_POLICY_ID));
ScalingPolicyID entity = SpringMockMvcUtil.doPost(mockMvc, "/api/v3/autoscaling/scalingPolicy", request, ScalingPolicyID.class);
assertThat(entity).isEqualTo(SCALING_POLICY_ID);
verify(serviceMock, times(1)).setAutoScalingPolicy(request, JUNIT_REST_CALL_METADATA);
}
@Test
public void testGetScalingPolicy() throws Exception {
when(serviceMock.getScalingPolicy(SCALING_POLICY_ID, JUNIT_REST_CALL_METADATA)).thenReturn(Observable.just(GET_POLICY_RESULT));
GetPolicyResult entity = SpringMockMvcUtil.doGet(mockMvc, String.format("/api/v3/autoscaling/scalingPolicy/%s", SCALING_POLICY_ID.getId()), GetPolicyResult.class);
assertThat(entity).isEqualTo(GET_POLICY_RESULT);
verify(serviceMock, times(1)).getScalingPolicy(SCALING_POLICY_ID, JUNIT_REST_CALL_METADATA);
}
@Test
public void testRemovePolicy() throws Exception {
DeletePolicyRequest request = DeletePolicyRequest.newBuilder().setId(SCALING_POLICY_ID).build();
when(serviceMock.deleteAutoScalingPolicy(request, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doDelete(mockMvc, String.format("/api/v3/autoscaling/scalingPolicy/%s", SCALING_POLICY_ID.getId()));
verify(serviceMock, times(1)).deleteAutoScalingPolicy(request, JUNIT_REST_CALL_METADATA);
}
@Test
public void testUpdateScalingPolicy() throws Exception {
UpdatePolicyRequest request = UpdatePolicyRequest.newBuilder().build();
when(serviceMock.updateAutoScalingPolicy(request, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPut(mockMvc, "/api/v3/autoscaling/scalingPolicy", request);
verify(serviceMock, times(1)).updateAutoScalingPolicy(request, JUNIT_REST_CALL_METADATA);
}
} | 303 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/connector/prediction/JobRuntimePredictionsTest.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.connector.prediction;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class JobRuntimePredictionsTest {
@Test
public void testOneLineRepresentation() {
SortedSet<JobRuntimePrediction> predictions = new TreeSet<>();
predictions.add(new JobRuntimePrediction(0.95, 26.2));
predictions.add(new JobRuntimePrediction(0.1, 10.0));
predictions.add(new JobRuntimePrediction(0.2, 15.0));
JobRuntimePredictions jobRuntimePredictions = new JobRuntimePredictions("1", "some-id", predictions);
Optional<String> asString = jobRuntimePredictions.toSimpleString();
assertThat(asString).isPresent();
assertThat(asString.get()).isEqualTo("0.1=10.0;0.2=15.0;0.95=26.2");
}
@Test
public void testOneLineRepresentationForEmptyPredictions() {
JobRuntimePredictions predictions = new JobRuntimePredictions("1", "some-id", new TreeSet<>());
assertThat(predictions.toSimpleString()).isEmpty();
}
}
| 304 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/connector/registry/RegistryClientTest.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.registry;
import java.time.Duration;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Header;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
public class RegistryClientTest {
private static final Duration TIMEOUT = Duration.ofSeconds(10);
private final TitusRuntime titusRuntime = TitusRuntimes.internal();
private ClientAndServer mockServer;
private final TitusRegistryClientConfiguration configuration = mock(TitusRegistryClientConfiguration.class);
private RegistryClient registryClient;
@Before
public void setUp() {
mockServer = startClientAndServer(0);
when(configuration.getRegistryUri()).thenReturn("http://localhost:" + mockServer.getPort());
when(configuration.isSecure()).thenReturn(false);
when(configuration.getRegistryTimeoutMs()).thenReturn(2_000);
when(configuration.getRegistryRetryCount()).thenReturn(2);
when(configuration.getRegistryRetryDelayMs()).thenReturn(5);
registryClient = new DefaultDockerRegistryClient(configuration, titusRuntime);
}
@After
public void tearDown() {
mockServer.stop();
}
@Test
public void getDigestTest() {
final String repo = "titusops/alpine";
final String tag = "latest";
final String digest = "sha256:f9f5bb506406b80454a4255b33ed2e4383b9e4a32fb94d6f7e51922704e818fa";
mockServer
.when(
HttpRequest.request()
.withMethod("GET")
.withPath("/v2/" + repo + "/manifests/" + tag)
)
.respond(
HttpResponse.response()
.withStatusCode(HttpResponseStatus.OK.code())
.withHeader(
new Header("Docker-Content-Digest", digest)
)
.withBody("{\"schemaVersion\": 2}")
);
String retrievedDigest = registryClient.getImageDigest(repo, tag).timeout(TIMEOUT).block();
assertThat(retrievedDigest).isEqualTo(digest);
}
@Test
public void missingImageTest() {
final String repo = "titusops/alpine";
final String tag = "doesnotexist";
mockServer
.when(
HttpRequest.request().withPath("/v2/" + repo + "/manifests/" + tag)
).respond(HttpResponse.response()
.withStatusCode(HttpResponseStatus.NOT_FOUND.code()));
try {
registryClient.getImageDigest(repo, tag).timeout(TIMEOUT).block();
} catch (TitusRegistryException e) {
assertThat(e.getErrorCode()).isEqualTo(TitusRegistryException.ErrorCode.IMAGE_NOT_FOUND);
}
}
}
| 305 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/TitusEntitySanitizerComponent.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime;
import java.time.Duration;
import javax.inject.Named;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.CustomJobConfiguration;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobAssertions;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobConfiguration;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder;
import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerSanitizerBuilder;
import com.netflix.titus.api.model.ResourceDimension;
import com.netflix.titus.common.environment.MyEnvironments;
import com.netflix.titus.common.model.sanitizer.EntitySanitizer;
import com.netflix.titus.common.model.sanitizer.VerifierMode;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import com.netflix.titus.common.util.archaius2.ObjectConfigurationResolver;
import com.netflix.titus.common.util.closeable.CloseableDependency;
import com.netflix.titus.common.util.closeable.CloseableReference;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import reactor.core.publisher.Flux;
import static com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder.JOB_PERMISSIVE_SANITIZER;
import static com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder.JOB_STRICT_SANITIZER;
import static com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerSanitizerBuilder.LOAD_BALANCER_SANITIZER;
@Configuration
public class TitusEntitySanitizerComponent {
public static final String CUSTOM_JOB_CONFIGURATION_ROOT = "titusMaster.job.customConfiguration";
public static final String DEFAULT_CUSTOM_JOB_CONFIGURATION_ROOT = "titusMaster.job.defaultCustomConfiguration";
public static final String JOB_CONFIGURATION_RESOLVER = "jobConfigurationResolver";
@Bean
public JobConfiguration getJobConfiguration(TitusRuntime titusRuntime) {
return Archaius2Ext.newConfiguration(JobConfiguration.class, titusRuntime.getMyEnvironment());
}
@Bean
public JobAssertions getJobAssertions(JobConfiguration jobConfiguration) {
return new JobAssertions(
jobConfiguration,
capacityGroup -> ResourceDimension.newBuilder()
.withCpus(jobConfiguration.getCpuMax())
.withGpu(jobConfiguration.getGpuMax())
.withMemoryMB(jobConfiguration.getMemoryMegabytesMax())
.withDiskMB(jobConfiguration.getDiskMegabytesMax())
.withNetworkMbs(jobConfiguration.getNetworkMbpsMax())
.build()
);
}
@Bean
@Named(JOB_STRICT_SANITIZER)
public EntitySanitizer getJobEntityStrictSanitizer(JobConfiguration jobConfiguration, JobAssertions jobAssertions) {
return getJobEntitySanitizer(jobConfiguration, jobAssertions, VerifierMode.Strict);
}
@Bean
@Named(JOB_PERMISSIVE_SANITIZER)
public EntitySanitizer getJobEntityPermissiveSanitizer(JobConfiguration jobConfiguration, JobAssertions jobAssertions) {
return getJobEntitySanitizer(jobConfiguration, jobAssertions, VerifierMode.Permissive);
}
private EntitySanitizer getJobEntitySanitizer(JobConfiguration jobConfiguration, JobAssertions jobAssertions, VerifierMode verifierMode) {
return new JobSanitizerBuilder()
.withVerifierMode(verifierMode)
.withJobConstraintConfiguration(jobConfiguration)
.withJobAsserts(jobAssertions)
.build();
}
@Bean
@Named(LOAD_BALANCER_SANITIZER)
public EntitySanitizer getLoadBalancerEntitySanitizer() {
return new LoadBalancerSanitizerBuilder().build();
}
@Bean
@Named(JOB_CONFIGURATION_RESOLVER)
public CloseableDependency<ObjectConfigurationResolver<JobDescriptor, CustomJobConfiguration>> getJobObjectConfigurationResolverCloseable(Environment environment) {
CloseableReference<ObjectConfigurationResolver<JobDescriptor, CustomJobConfiguration>> ref = Archaius2Ext.newObjectConfigurationResolver(
CUSTOM_JOB_CONFIGURATION_ROOT,
environment,
JobDescriptor::getApplicationName,
CustomJobConfiguration.class,
Archaius2Ext.newConfiguration(CustomJobConfiguration.class, DEFAULT_CUSTOM_JOB_CONFIGURATION_ROOT, MyEnvironments.newSpring(environment)),
Flux.interval(Duration.ofSeconds(1))
);
return CloseableDependency.of(ref);
}
@Bean
public ObjectConfigurationResolver<JobDescriptor, CustomJobConfiguration> getJobObjectConfigurationResolver(
@Named(JOB_CONFIGURATION_RESOLVER) CloseableDependency<ObjectConfigurationResolver<JobDescriptor, CustomJobConfiguration>> closeableDependency) {
return closeableDependency.get();
}
}
| 306 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/TitusEntitySanitizerModule.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime;
import javax.inject.Named;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.archaius.api.Config;
import com.netflix.titus.api.appscale.model.sanitizer.ScalingPolicySanitizerBuilder;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.CustomJobConfiguration;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobAssertions;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobConfiguration;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder;
import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerSanitizerBuilder;
import com.netflix.titus.api.model.ResourceDimension;
import com.netflix.titus.common.model.sanitizer.EntitySanitizer;
import com.netflix.titus.common.model.sanitizer.VerifierMode;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import com.netflix.titus.common.util.archaius2.ObjectConfigurationResolver;
import static com.netflix.titus.api.appscale.model.sanitizer.ScalingPolicySanitizerBuilder.SCALING_POLICY_SANITIZER;
import static com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder.JOB_PERMISSIVE_SANITIZER;
import static com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder.JOB_STRICT_SANITIZER;
import static com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerSanitizerBuilder.LOAD_BALANCER_SANITIZER;
/**
*
*/
public class TitusEntitySanitizerModule extends AbstractModule {
public static final String CUSTOM_JOB_CONFIGURATION_ROOT = "titusMaster.job.customConfiguration";
public static final String DEFAULT_CUSTOM_JOB_CONFIGURATION_ROOT = "titusMaster.job.defaultCustomConfiguration";
@Override
protected void configure() {
}
@Provides
@Singleton
public JobAssertions getJobAssertions(JobConfiguration jobConfiguration) {
return new JobAssertions(
jobConfiguration,
capacityGroup -> ResourceDimension.newBuilder()
.withCpus(jobConfiguration.getCpuMax())
.withGpu(jobConfiguration.getGpuMax())
.withMemoryMB(jobConfiguration.getMemoryMegabytesMax())
.withDiskMB(jobConfiguration.getDiskMegabytesMax())
.withNetworkMbs(jobConfiguration.getNetworkMbpsMax())
.build()
);
}
@Provides
@Singleton
@Named(SCALING_POLICY_SANITIZER)
public EntitySanitizer getScalingPolicySanitizer() {
return new ScalingPolicySanitizerBuilder().build();
}
@Provides
@Singleton
@Named(JOB_STRICT_SANITIZER)
public EntitySanitizer getJobEntityStrictSanitizer(JobConfiguration jobConfiguration, JobAssertions jobAssertions) {
return getJobEntitySanitizer(jobConfiguration, jobAssertions, VerifierMode.Strict);
}
@Provides
@Singleton
@Named(JOB_PERMISSIVE_SANITIZER)
public EntitySanitizer getJobEntityPermissiveSanitizer(JobConfiguration jobConfiguration, JobAssertions jobAssertions) {
return getJobEntitySanitizer(jobConfiguration, jobAssertions, VerifierMode.Permissive);
}
private EntitySanitizer getJobEntitySanitizer(JobConfiguration jobConfiguration, JobAssertions jobAssertions, VerifierMode verifierMode) {
return new JobSanitizerBuilder()
.withVerifierMode(verifierMode)
.withJobConstraintConfiguration(jobConfiguration)
.withJobAsserts(jobAssertions)
.build();
}
@Provides
@Singleton
@Named(LOAD_BALANCER_SANITIZER)
public EntitySanitizer getLoadBalancerEntitySanitizer() {
return new LoadBalancerSanitizerBuilder().build();
}
@Provides
@Singleton
public JobConfiguration getJobConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(JobConfiguration.class);
}
@Provides
@Singleton
public ObjectConfigurationResolver<JobDescriptor, CustomJobConfiguration> getJobObjectConfigurationResolver(Config configuration,
ConfigProxyFactory factory) {
return Archaius2Ext.newObjectConfigurationResolver(
configuration.getPrefixedView(CUSTOM_JOB_CONFIGURATION_ROOT),
JobDescriptor::getApplicationName,
CustomJobConfiguration.class,
factory.newProxy(CustomJobConfiguration.class, DEFAULT_CUSTOM_JOB_CONFIGURATION_ROOT)
);
}
}
| 307 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/RelocationAttributes.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime;
/**
* Collection of task relocation related attributes that can be associated with agent instance groups, agent instances,
* jobs or tasks. These attributes when set, affect the relocation process of the tagged object.
*/
public final class RelocationAttributes {
/**
* If set to true, marks an object as needing migration. Applicable to an agent instance and a task.
*/
public static final String RELOCATION_REQUIRED = "titus.relocation.required";
/**
* Like {@link #RELOCATION_REQUIRED}, but the safeguards (system eviction limits, job disruption budget)
* for the object termination are ignored.
*/
public static final String RELOCATION_REQUIRED_IMMEDIATELY = "titus.relocation.requiredImmediately";
/**
* If set to true, marks an object as needing immediate migration if its creation time happened before the time set as
* an attribute value. The timestamp value is an epoch.
* Settable on a job, and applied to all tasks belonging to the given job.
*/
public static final String RELOCATION_REQUIRED_BY = "titus.relocation.requiredBy";
/**
* Like {@link #RELOCATION_REQUIRED_BY}, but the safeguards (system eviction limits, job disruption budget)
* for the object termination are ignored.
*/
public static final String RELOCATION_REQUIRED_BY_IMMEDIATELY = "titus.relocation.requiredByImmediately";
/**
* If set to true, turns off the relocation process for an object. Applicable to an agent, a job and a task.
*/
public static final String RELOCATION_NOT_ALLOWED = "titus.relocation.notAllowed";
}
| 308 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/FeatureFlagModule.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime;
import java.util.function.Predicate;
import javax.inject.Named;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.titus.api.FeatureActivationConfiguration;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.common.util.feature.FeatureGuardWhiteListConfiguration;
import com.netflix.titus.common.util.feature.FeatureGuards;
import static com.netflix.titus.api.FeatureRolloutPlans.ENVIRONMENT_VARIABLE_NAMES_STRICT_VALIDATION_FEATURE;
import static com.netflix.titus.api.FeatureRolloutPlans.JOB_AUTHORIZATION_FEATURE;
import static com.netflix.titus.api.FeatureRolloutPlans.SECURITY_GROUPS_REQUIRED_FEATURE;
public class FeatureFlagModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
public FeatureActivationConfiguration getFeatureActivationConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(FeatureActivationConfiguration.class);
}
/* *************************************************************************************************************
* Security groups/IAM role required.
*/
@Provides
@Singleton
@Named(SECURITY_GROUPS_REQUIRED_FEATURE)
public Predicate<JobDescriptor> getSecurityGroupRequiredPredicate(@Named(SECURITY_GROUPS_REQUIRED_FEATURE) FeatureGuardWhiteListConfiguration configuration) {
return FeatureGuards.toPredicate(
FeatureGuards.fromField(
JobDescriptor::getApplicationName,
FeatureGuards.newWhiteListFromConfiguration(configuration).build()
)
);
}
@Provides
@Singleton
@Named(SECURITY_GROUPS_REQUIRED_FEATURE)
public FeatureGuardWhiteListConfiguration getSecurityGroupRequiredFeatureGuardConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(FeatureGuardWhiteListConfiguration.class, "titus.features.jobManager." + SECURITY_GROUPS_REQUIRED_FEATURE);
}
/* *************************************************************************************************************
* Environment variables.
*
* Environment variable names set in {@link JobDescriptor} must conform to the rules defined in this spec:
* http://pubs.opengroup.org/onlinepubs/9699919799/.
*
* This change was introduced in Q1/2019. The strict validation should be enforced on all clients by the end of Q2/2019.
*/
@Provides
@Singleton
@Named(ENVIRONMENT_VARIABLE_NAMES_STRICT_VALIDATION_FEATURE)
public Predicate<JobDescriptor> getEnvironmentVariableStrictValidationPredicate(@Named(ENVIRONMENT_VARIABLE_NAMES_STRICT_VALIDATION_FEATURE) FeatureGuardWhiteListConfiguration configuration) {
return FeatureGuards.toPredicate(
FeatureGuards.fromField(
JobDescriptor::getApplicationName,
FeatureGuards.newWhiteListFromConfiguration(configuration).build()
)
);
}
@Provides
@Singleton
@Named(ENVIRONMENT_VARIABLE_NAMES_STRICT_VALIDATION_FEATURE)
public FeatureGuardWhiteListConfiguration getEnvironmentVariableStrictValidationConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(FeatureGuardWhiteListConfiguration.class, "titus.features.jobManager." + ENVIRONMENT_VARIABLE_NAMES_STRICT_VALIDATION_FEATURE);
}
/* *************************************************************************************************************
* Job authorization
*
* This change was introduced in Q1/2019.
*/
@Provides
@Singleton
@Named(JOB_AUTHORIZATION_FEATURE)
public Predicate<String> getJobAuthorizationPredicate(@Named(JOB_AUTHORIZATION_FEATURE) FeatureGuardWhiteListConfiguration configuration) {
return FeatureGuards.toPredicate(FeatureGuards.newWhiteListFromConfiguration(configuration).build());
}
@Provides
@Singleton
@Named(JOB_AUTHORIZATION_FEATURE)
public FeatureGuardWhiteListConfiguration getJobAuthorizationFeatureGuardConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(FeatureGuardWhiteListConfiguration.class, "titus.features.jobManager." + JOB_AUTHORIZATION_FEATURE);
}
}
| 309 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/JobManagerCursors.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.jobmanager;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.titus.api.jobmanager.model.job.BatchJobTask;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.model.PaginationEvaluator;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobStatus;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A collection of functions for dealing with the pagination cursors.
*/
public final class JobManagerCursors {
private static final Logger logger = LoggerFactory.getLogger(JobManagerCursors.class);
private static final Pattern CURSOR_RE = Pattern.compile("(.*)@(\\d+)");
private static final PaginationEvaluator<com.netflix.titus.api.jobmanager.model.job.Job> JOB_PAGINATION_EVALUATOR = new PaginationEvaluator<>(
com.netflix.titus.api.jobmanager.model.job.Job::getId,
task -> JobFunctions.findJobStatus(task, JobState.Accepted).orElse(task.getStatus()).getTimestamp()
);
private static final PaginationEvaluator<com.netflix.titus.api.jobmanager.model.job.Task> TASK_PAGINATION_EVALUATOR = new PaginationEvaluator<>(
com.netflix.titus.api.jobmanager.model.job.Task::getId,
task -> JobFunctions.findTaskStatus(task, TaskState.Accepted).orElse(task.getStatus()).getTimestamp()
);
private JobManagerCursors() {
}
public static PaginationEvaluator<com.netflix.titus.api.jobmanager.model.job.Job> newCoreJobPaginationEvaluator() {
return JOB_PAGINATION_EVALUATOR;
}
public static PaginationEvaluator<com.netflix.titus.api.jobmanager.model.job.Task> newCoreTaskPaginationEvaluator() {
return TASK_PAGINATION_EVALUATOR;
}
/**
* Compare two job entities by the creation time (first), and a job id (second).
*
* @deprecated Use core model entities.
*/
@Deprecated
public static Comparator<Job> jobCursorOrderComparator() {
return (first, second) -> {
int cmp = Long.compare(getCursorTimestamp(first), getCursorTimestamp(second));
if (cmp != 0) {
return cmp;
}
return first.getId().compareTo(second.getId());
};
}
/**
* Compare two job entities by the creation time (first), and a job id (second).
*/
public static Comparator<com.netflix.titus.api.jobmanager.model.job.Job<?>> coreJobCursorOrderComparator() {
return (first, second) -> {
int cmp = Long.compare(getCoreCursorTimestamp(first), getCoreCursorTimestamp(second));
if (cmp != 0) {
return cmp;
}
return first.getId().compareTo(second.getId());
};
}
/**
* Compare two task entities by the creation time (first), and a task id (second).
*
* @deprecated Use core model entities.
*/
@Deprecated
public static Comparator<Task> taskCursorOrderComparator() {
return (first, second) -> {
int cmp = Long.compare(getCursorTimestamp(first), getCursorTimestamp(second));
if (cmp != 0) {
return cmp;
}
return first.getId().compareTo(second.getId());
};
}
/**
* Find an index of the element pointed to by the cursor, or if not found, the element immediately preceding it.
* <p>
* If the element pointed to by the cursor would be the first element in the list (index=0) this returns -1.
*
* @deprecated Use core model entities.
*/
@Deprecated
public static Optional<Integer> jobIndexOf(List<Job> jobs, String cursor) {
return decode(cursor).map(cursorValues -> {
String jobId = cursorValues.getLeft();
long timestamp = cursorValues.getRight();
Job referenceJob = Job.newBuilder()
.setId(jobId)
.setStatus(JobStatus.newBuilder().setState(JobStatus.JobState.Accepted).setTimestamp(timestamp))
.build();
int idx = Collections.binarySearch(jobs, referenceJob, jobCursorOrderComparator());
if (idx >= 0) {
return idx;
}
return Math.max(-1, -idx - 2);
});
}
/**
* Find an index of the element pointed to by the cursor, or if not found, the element immediately preceding it.
* <p>
* If the element pointed to by the cursor would be the first element in the list (index=0) this returns -1.
*/
public static Optional<Integer> coreJobIndexOf(List<com.netflix.titus.api.jobmanager.model.job.Job<?>> jobs, String cursor) {
return decode(cursor).map(cursorValues -> {
String jobId = cursorValues.getLeft();
long timestamp = cursorValues.getRight();
com.netflix.titus.api.jobmanager.model.job.Job<?> referenceJob = com.netflix.titus.api.jobmanager.model.job.Job.newBuilder()
.withId(jobId)
.withStatus(com.netflix.titus.api.jobmanager.model.job.JobStatus.newBuilder().withState(JobState.Accepted).withTimestamp(timestamp).build())
.build();
int idx = Collections.binarySearch(jobs, referenceJob, coreJobCursorOrderComparator());
if (idx >= 0) {
return idx;
}
return Math.max(-1, -idx - 2);
});
}
/**
* Find an index of the element pointed to by the cursor, or if not found, the element immediately preceding it.
* <p>
* If the element pointed to by the cursor would be the first element in the list (index=0) this returns -1.
*
* @deprecated Use core model entities.
*/
@Deprecated
public static Optional<Integer> taskIndexOf(List<Task> tasks, String cursor) {
return decode(cursor).map(cursorValues -> {
String taskId = cursorValues.getLeft();
long timestamp = cursorValues.getRight();
Task referenceTask = Task.newBuilder()
.setId(taskId)
.setStatus(TaskStatus.newBuilder().setState(TaskStatus.TaskState.Accepted).setTimestamp(timestamp))
.build();
int idx = Collections.binarySearch(tasks, referenceTask, taskCursorOrderComparator());
if (idx >= 0) {
return idx;
}
return Math.max(-1, -idx - 2);
});
}
/**
* Find an index of the element pointed to by the cursor, or if not found, the element immediately preceding it.
* <p>
* If the element pointed to by the cursor would be the first element in the list (index=0) this returns -1.
*/
public static Optional<Integer> coreTaskIndexOf(List<com.netflix.titus.api.jobmanager.model.job.Task> tasks, String cursor) {
return decode(cursor).map(cursorValues -> {
String taskId = cursorValues.getLeft();
long timestamp = cursorValues.getRight();
BatchJobTask referenceTask = BatchJobTask.newBuilder()
.withId(taskId)
.withStatus(com.netflix.titus.api.jobmanager.model.job.TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(timestamp).build())
.build();
int idx = Collections.binarySearch(tasks, referenceTask, JobComparators.getTaskTimestampComparator());
if (idx >= 0) {
return idx;
}
return Math.max(-1, -idx - 2);
});
}
public static String newCursorFrom(Job job) {
return encode(job.getId(), getCursorTimestamp(job));
}
public static String newJobCoreCursorFrom(com.netflix.titus.api.jobmanager.model.job.Job<?> job) {
return encode(job.getId(), getCoreCursorTimestamp(job));
}
public static String newTaskCursorFrom(Task task) {
return encode(task.getId(), getCursorTimestamp(task));
}
public static String newTaskCoreCursorFrom(com.netflix.titus.api.jobmanager.model.job.Task task) {
return encode(task.getId(), JobComparators.getTaskCreateTimestamp(task));
}
private static long getCursorTimestamp(Job job) {
if (job.getStatus().getState() == JobStatus.JobState.Accepted) {
return job.getStatus().getTimestamp();
}
for (JobStatus next : job.getStatusHistoryList()) {
if (next.getState() == JobStatus.JobState.Accepted) {
return next.getTimestamp();
}
}
// Fallback, in case Accepted state is not found which should never happen.
return job.getStatus().getTimestamp();
}
private static long getCoreCursorTimestamp(com.netflix.titus.api.jobmanager.model.job.Job<?> job) {
return JobFunctions.findJobStatus(job, JobState.Accepted).orElse(job.getStatus()).getTimestamp();
}
private static long getCursorTimestamp(Task task) {
if (task.getStatus().getState() == TaskStatus.TaskState.Accepted) {
return task.getStatus().getTimestamp();
}
for (TaskStatus next : task.getStatusHistoryList()) {
if (next.getState() == TaskStatus.TaskState.Accepted) {
return next.getTimestamp();
}
}
// Fallback, in case Accepted state is not found which should never happen.
return task.getStatus().getTimestamp();
}
private static String encode(String id, long timestamp) {
String value = id + '@' + timestamp;
return Base64.getEncoder().encodeToString(value.getBytes());
}
public static Optional<Pair<String, Long>> decode(String encodedValue) {
String decoded;
try {
decoded = new String(Base64.getDecoder().decode(encodedValue.getBytes()));
} catch (Exception e) {
logger.debug("Cannot decode value: {}", encodedValue, e);
return Optional.empty();
}
Matcher matcher = CURSOR_RE.matcher(decoded);
if (!matcher.matches()) {
logger.debug("Not valid cursor value: {}", decoded);
return Optional.empty();
}
String id = matcher.group(1);
long timestamp = Long.parseLong(matcher.group(2));
return Optional.of(Pair.of(id, timestamp));
}
}
| 310 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/JobComparators.java | /*
* Copyright 2021 Netflix, 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.netflix.titus.runtime.jobmanager;
import java.util.Comparator;
import java.util.List;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.JobStatus;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.TaskStatus;
import com.netflix.titus.api.model.IdAndTimestampKey;
public class JobComparators {
private static final JobTimestampComparator JOB_TIMESTAMP_COMPARATOR = new JobTimestampComparator();
private static final TaskTimestampComparator TASK_TIMESTAMP_COMPARATOR = new TaskTimestampComparator();
/**
* Compare two job entities by the creation time (first), and a job id (second).
*/
public static Comparator<Job<?>> getJobTimestampComparator() {
return JOB_TIMESTAMP_COMPARATOR;
}
/**
* Compare two task entities by the creation time (first), and a task id (second).
*/
public static Comparator<Task> getTaskTimestampComparator() {
return TASK_TIMESTAMP_COMPARATOR;
}
private static class JobTimestampComparator implements Comparator<Job<?>> {
@Override
public int compare(Job first, Job second) {
long firstTimestamp = getJobCreateTimestamp(first);
long secondTimestamp = getJobCreateTimestamp(second);
int cmp = Long.compare(firstTimestamp, secondTimestamp);
if (cmp != 0) {
return cmp;
}
return first.getId().compareTo(second.getId());
}
}
private static class TaskTimestampComparator implements Comparator<Task> {
@Override
public int compare(Task first, Task second) {
long firstTimestamp = getTaskCreateTimestamp(first);
long secondTimestamp = getTaskCreateTimestamp(second);
int cmp = Long.compare(firstTimestamp, secondTimestamp);
if (cmp != 0) {
return cmp;
}
return first.getId().compareTo(second.getId());
}
}
public static long getJobCreateTimestamp(Job job) {
List<JobStatus> statusHistory = job.getStatusHistory();
int historySize = statusHistory.size();
// Fast path
if (historySize == 0) {
return job.getStatus().getTimestamp();
}
JobStatus first = statusHistory.get(0);
if (historySize == 1 || first.getState() == JobState.Accepted) {
return first.getTimestamp();
}
// Slow path
for (int i = 1; i < historySize; i++) {
JobStatus next = statusHistory.get(i);
if (next.getState() == JobState.Accepted) {
return next.getTimestamp();
}
}
// No Accepted state
return job.getStatus().getTimestamp();
}
public static long getTaskCreateTimestamp(Task task) {
List<TaskStatus> statusHistory = task.getStatusHistory();
int historySize = statusHistory.size();
// Fast path
if (historySize == 0) {
return task.getStatus().getTimestamp();
}
com.netflix.titus.api.jobmanager.model.job.TaskStatus first = statusHistory.get(0);
if (historySize == 1 || first.getState() == TaskState.Accepted) {
return first.getTimestamp();
}
// Slow path
for (int i = 1; i < historySize; i++) {
com.netflix.titus.api.jobmanager.model.job.TaskStatus next = statusHistory.get(i);
if (next.getState() == TaskState.Accepted) {
return next.getTimestamp();
}
}
// No Accepted state
return task.getStatus().getTimestamp();
}
public static IdAndTimestampKey<Job<?>> createJobKeyOf(Job<?> job) {
return new IdAndTimestampKey<>(job, job.getId(), getJobCreateTimestamp(job));
}
public static IdAndTimestampKey<Task> createTaskKeyOf(Task task) {
return new IdAndTimestampKey<>(task, task.getId(), getTaskCreateTimestamp(task));
}
}
| 311 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/JobManagerConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.jobmanager;
import java.util.List;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.jobManager")
public interface JobManagerConfiguration {
@DefaultValue("_none_")
String getDefaultIamRole();
List<String> getDefaultSecurityGroups();
/**
* @return A comma separated string of one or more subnets to launch the container in. This string is set as an annotation on the pod.
*/
String getDefaultSubnets();
/**
* @return Default account to launch containers in. This value is used when not explicitly provided by the caller.
*/
String getDefaultContainerAccountId();
@DefaultValue("_none_")
String getNoncompliantClientWhiteList();
/**
* @return the minimum disk size in megabytes that the disk resource dimension should be set to.
*/
@DefaultValue("10000")
int getMinDiskSizeMB();
}
| 312 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/gateway/SanitizingJobServiceGateway.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.jobmanager.gateway;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.model.job.Capacity;
import com.netflix.titus.api.jobmanager.model.job.CapacityAttributes;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.sanitizer.EntitySanitizer;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobCapacityWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobChangeNotification;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.common.util.rx.ReactorExt.toObservable;
public class SanitizingJobServiceGateway extends JobServiceGatewayDelegate {
private static final Logger logger = LoggerFactory.getLogger(SanitizingJobServiceGateway.class);
private final JobServiceGateway delegate;
private final EntitySanitizer entitySanitizer;
private final AdmissionValidator<com.netflix.titus.api.jobmanager.model.job.JobDescriptor> admissionValidator;
private final AdmissionSanitizer<com.netflix.titus.api.jobmanager.model.job.JobDescriptor> admissionSanitizer;
public SanitizingJobServiceGateway(JobServiceGateway delegate,
EntitySanitizer entitySanitizer,
AdmissionValidator<com.netflix.titus.api.jobmanager.model.job.JobDescriptor> validator,
AdmissionSanitizer<com.netflix.titus.api.jobmanager.model.job.JobDescriptor> sanitizer) {
super(delegate);
this.delegate = delegate;
this.entitySanitizer = entitySanitizer;
this.admissionValidator = validator;
this.admissionSanitizer = sanitizer;
}
@Override
public Observable<String> createJob(JobDescriptor jobDescriptor, CallMetadata callMetadata) {
com.netflix.titus.api.jobmanager.model.job.JobDescriptor coreJobDescriptorUnfiltered;
try {
coreJobDescriptorUnfiltered = GrpcJobManagementModelConverters.toCoreJobDescriptor(jobDescriptor);
} catch (Exception e) {
return Observable.error(TitusServiceException.invalidArgument("Error creating core job descriptor: " + e.getMessage()));
}
com.netflix.titus.api.jobmanager.model.job.JobDescriptor coreJobDescriptor;
try {
coreJobDescriptor = JobFunctions.filterOutGeneratedAttributes(coreJobDescriptorUnfiltered);
} catch (Exception e) {
return Observable.error(TitusServiceException.invalidArgument("Error when filtering out generated attributes: " + e.getMessage()));
}
// basic entity validations based on class/field constraints
com.netflix.titus.api.jobmanager.model.job.JobDescriptor sanitizedCoreJobDescriptor = entitySanitizer.sanitize(coreJobDescriptor).orElse(coreJobDescriptor);
Set<ValidationError> violations = entitySanitizer.validate(sanitizedCoreJobDescriptor);
if (!violations.isEmpty()) {
return Observable.error(TitusServiceException.invalidArgument(violations));
}
// validations that need external data
return toObservable(admissionSanitizer.sanitizeAndApply(sanitizedCoreJobDescriptor)
.switchIfEmpty(Mono.just(sanitizedCoreJobDescriptor)))
.onErrorResumeNext(throwable -> {
logger.error("Sanitization error", throwable);
return Observable.error(
TitusServiceException.newBuilder(
TitusServiceException.ErrorCode.INVALID_ARGUMENT,
"Job sanitization error in TitusGateway: " + throwable.getMessage())
.withCause(throwable)
.build()
);
})
.flatMap(jd -> toObservable(admissionValidator.validate(jd))
.flatMap(errors -> {
// Only emit an error on HARD validation errors
errors = errors.stream().filter(ValidationError::isHard).collect(Collectors.toSet());
if (!errors.isEmpty()) {
return Observable.error(TitusServiceException.invalidJob(errors));
} else {
return Observable.just(jd);
}
})
)
.flatMap(jd -> delegate.createJob(GrpcJobManagementModelConverters.toGrpcJobDescriptor(jd), callMetadata));
}
@Override
public Completable updateJobProcesses(JobProcessesUpdate jobProcessesUpdate, CallMetadata callMetadata) {
return checkJobId(jobProcessesUpdate.getJobId())
.map(Completable::error)
.orElseGet(() -> delegate.updateJobProcesses(jobProcessesUpdate, callMetadata));
}
@Override
public Completable updateJobStatus(JobStatusUpdate statusUpdate, CallMetadata callMetadata) {
return checkJobId(statusUpdate.getId())
.map(Completable::error)
.orElseGet(() -> delegate.updateJobStatus(statusUpdate, callMetadata));
}
@Override
public Mono<Void> updateJobDisruptionBudget(JobDisruptionBudgetUpdate request, CallMetadata callMetadata) {
return checkJobId(request.getJobId())
.map(Mono::<Void>error)
.orElseGet(() -> delegate.updateJobDisruptionBudget(request, callMetadata));
}
@Override
public Mono<Void> updateJobAttributes(JobAttributesUpdate request, CallMetadata callMetadata) {
return checkJobId(request.getJobId())
.map(Mono::<Void>error)
.orElseGet(() -> delegate.updateJobAttributes(request, callMetadata));
}
@Override
public Mono<Void> deleteJobAttributes(JobAttributesDeleteRequest request, CallMetadata callMetadata) {
return checkJobId(request.getJobId())
.map(Mono::<Void>error)
.orElseGet(() -> delegate.deleteJobAttributes(request, callMetadata));
}
@Override
public Observable<Job> findJob(String jobId, CallMetadata callMetadata) {
return checkJobId(jobId)
.map(Observable::<Job>error)
.orElseGet(() -> findJob(jobId, callMetadata));
}
@Override
public Observable<JobChangeNotification> observeJob(String jobId, CallMetadata callMetadata) {
return checkJobId(jobId)
.map(Observable::<JobChangeNotification>error)
.orElseGet(() -> delegate.observeJob(jobId, callMetadata));
}
@Override
public Completable killJob(String jobId, CallMetadata callMetadata) {
return checkJobId(jobId)
.map(Completable::error)
.orElseGet(() -> delegate.killJob(jobId, callMetadata));
}
@Override
public Observable<Task> findTask(String taskId, CallMetadata callMetadata) {
return checkTaskId(taskId)
.map(Observable::<Task>error)
.orElseGet(() -> delegate.findTask(taskId, callMetadata));
}
@Override
public Completable killTask(TaskKillRequest taskKillRequest, CallMetadata callMetadata) {
return checkTaskId(taskKillRequest.getTaskId())
.map(Completable::error)
.orElseGet(() -> delegate.killTask(taskKillRequest, callMetadata));
}
@Override
public Completable updateTaskAttributes(TaskAttributesUpdate attributesUpdate, CallMetadata callMetadata) {
return checkTaskId(attributesUpdate.getTaskId())
.map(Completable::error)
.orElseGet(() -> delegate.updateTaskAttributes(attributesUpdate, callMetadata));
}
@Override
public Completable deleteTaskAttributes(TaskAttributesDeleteRequest deleteRequest, CallMetadata callMetadata) {
return checkTaskId(deleteRequest.getTaskId())
.map(Completable::error)
.orElseGet(() -> delegate.deleteTaskAttributes(deleteRequest, callMetadata));
}
@Override
public Completable moveTask(TaskMoveRequest taskMoveRequest, CallMetadata callMetadata) {
return checkTaskId(taskMoveRequest.getTaskId())
.map(Completable::error)
.orElseGet(() -> delegate.moveTask(taskMoveRequest, callMetadata));
}
@Override
public Completable updateJobCapacity(JobCapacityUpdate jobCapacityUpdate, CallMetadata callMetadata) {
Optional<TitusServiceException> badId = checkJobId(jobCapacityUpdate.getJobId());
if (badId.isPresent()) {
return Completable.error(badId.get());
}
Capacity newCapacity = GrpcJobManagementModelConverters.toCoreCapacity(jobCapacityUpdate.getCapacity());
Set<ValidationError> violations = entitySanitizer.validate(newCapacity);
if (!violations.isEmpty()) {
return Completable.error(TitusServiceException.invalidArgument(violations));
}
return delegate.updateJobCapacity(jobCapacityUpdate, callMetadata);
}
@Override
public Completable updateJobCapacityWithOptionalAttributes(JobCapacityUpdateWithOptionalAttributes jobCapacityUpdateWithOptionalAttributes,
CallMetadata callMetadata) {
Optional<TitusServiceException> badId = checkJobId(jobCapacityUpdateWithOptionalAttributes.getJobId());
if (badId.isPresent()) {
return Completable.error(badId.get());
}
final JobCapacityWithOptionalAttributes jobCapacityWithOptionalAttributes = jobCapacityUpdateWithOptionalAttributes.getJobCapacityWithOptionalAttributes();
CapacityAttributes capacityAttributes = GrpcJobManagementModelConverters.toCoreCapacityAttributes(jobCapacityWithOptionalAttributes);
Set<ValidationError> violations = entitySanitizer.validate(capacityAttributes);
if (!violations.isEmpty()) {
return Completable.error(TitusServiceException.invalidArgument(violations));
}
return delegate.updateJobCapacityWithOptionalAttributes(jobCapacityUpdateWithOptionalAttributes, callMetadata);
}
public static Optional<TitusServiceException> checkJobId(String jobId) {
if (StringExt.isUUID(jobId)) {
return Optional.empty();
}
return Optional.of(TitusServiceException.invalidArgument("Job id must be UUID string, but is: " + jobId));
}
public static Optional<TitusServiceException> checkTaskId(String taskId) {
if (StringExt.isUUID(taskId)) {
return Optional.empty();
}
return Optional.of(TitusServiceException.invalidArgument("Task id must be UUID string, but is: " + taskId));
}
}
| 313 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/gateway/JobServiceGatewayDelegate.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.jobmanager.gateway;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobChangeNotification;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.ObserveJobsQuery;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
public class JobServiceGatewayDelegate implements JobServiceGateway {
private final JobServiceGateway delegate;
public JobServiceGatewayDelegate(JobServiceGateway delegate) {
this.delegate = delegate;
}
@Override
public Observable<String> createJob(JobDescriptor jobDescriptor, CallMetadata callMetadata) {
return delegate.createJob(jobDescriptor, callMetadata);
}
@Override
public Completable updateJobCapacity(JobCapacityUpdate jobCapacityUpdate, CallMetadata callMetadata) {
return delegate.updateJobCapacity(jobCapacityUpdate, callMetadata);
}
@Override
public Completable updateJobCapacityWithOptionalAttributes(JobCapacityUpdateWithOptionalAttributes jobCapacityUpdateWithOptionalAttributes,
CallMetadata callMetadata) {
return delegate.updateJobCapacityWithOptionalAttributes(jobCapacityUpdateWithOptionalAttributes, callMetadata);
}
@Override
public Completable updateJobProcesses(JobProcessesUpdate jobProcessesUpdate, CallMetadata callMetadata) {
return delegate.updateJobProcesses(jobProcessesUpdate, callMetadata);
}
@Override
public Completable updateJobStatus(JobStatusUpdate statusUpdate, CallMetadata callMetadata) {
return delegate.updateJobStatus(statusUpdate, callMetadata);
}
@Override
public Mono<Void> updateJobDisruptionBudget(JobDisruptionBudgetUpdate request, CallMetadata callMetadata) {
return delegate.updateJobDisruptionBudget(request, callMetadata);
}
@Override
public Mono<Void> updateJobAttributes(JobAttributesUpdate request, CallMetadata callMetadata) {
return delegate.updateJobAttributes(request, callMetadata);
}
@Override
public Mono<Void> deleteJobAttributes(JobAttributesDeleteRequest request, CallMetadata callMetadata) {
return delegate.deleteJobAttributes(request, callMetadata);
}
@Override
public Observable<Job> findJob(String jobId, CallMetadata callMetadata) {
return delegate.findJob(jobId, callMetadata);
}
@Override
public Observable<JobQueryResult> findJobs(JobQuery jobQuery, CallMetadata callMetadata) {
return delegate.findJobs(jobQuery, callMetadata);
}
@Override
public Observable<JobChangeNotification> observeJob(String jobId, CallMetadata callMetadata) {
return delegate.observeJob(jobId, callMetadata);
}
@Override
public Observable<JobChangeNotification> observeJobs(ObserveJobsQuery query, CallMetadata callMetadata) {
return delegate.observeJobs(query, callMetadata);
}
@Override
public Completable killJob(String jobId, CallMetadata callMetadata) {
return delegate.killJob(jobId, callMetadata);
}
@Override
public Observable<Task> findTask(String taskId, CallMetadata callMetadata) {
return delegate.findTask(taskId, callMetadata);
}
@Override
public Observable<TaskQueryResult> findTasks(TaskQuery taskQuery, CallMetadata callMetadata) {
return delegate.findTasks(taskQuery, callMetadata);
}
@Override
public Completable killTask(TaskKillRequest taskKillRequest, CallMetadata callMetadata) {
return delegate.killTask(taskKillRequest, callMetadata);
}
@Override
public Completable updateTaskAttributes(TaskAttributesUpdate attributesUpdate, CallMetadata callMetadata) {
return delegate.updateTaskAttributes(attributesUpdate, callMetadata);
}
@Override
public Completable deleteTaskAttributes(TaskAttributesDeleteRequest deleteRequest, CallMetadata callMetadata) {
return delegate.deleteTaskAttributes(deleteRequest, callMetadata);
}
@Override
public Completable moveTask(TaskMoveRequest taskMoveRequest, CallMetadata callMetadata) {
return delegate.moveTask(taskMoveRequest, callMetadata);
}
}
| 314 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/gateway/JobServiceGateway.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.jobmanager.gateway;
import java.util.Set;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobChangeNotification;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.ObserveJobsQuery;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.common.util.CollectionsExt.asSet;
/**
* Remote job management client API.
*/
public interface JobServiceGateway {
Set<String> JOB_MINIMUM_FIELD_SET = asSet("id");
Set<String> TASK_MINIMUM_FIELD_SET = asSet("id");
Observable<String> createJob(JobDescriptor jobDescriptor, CallMetadata callMetadata);
Completable updateJobCapacity(JobCapacityUpdate jobCapacityUpdate, CallMetadata callMetadata);
Completable updateJobCapacityWithOptionalAttributes(JobCapacityUpdateWithOptionalAttributes jobCapacityUpdateWithOptionalAttributes,
CallMetadata callMetadata);
Completable updateJobProcesses(JobProcessesUpdate jobProcessesUpdate, CallMetadata callMetadata);
Completable updateJobStatus(JobStatusUpdate statusUpdate, CallMetadata callMetadata);
Mono<Void> updateJobDisruptionBudget(JobDisruptionBudgetUpdate request, CallMetadata callMetadata);
Mono<Void> updateJobAttributes(JobAttributesUpdate request, CallMetadata callMetadata);
Mono<Void> deleteJobAttributes(JobAttributesDeleteRequest request, CallMetadata callMetadata);
Observable<Job> findJob(String jobId, CallMetadata callMetadata);
Observable<JobQueryResult> findJobs(JobQuery jobQuery, CallMetadata callMetadata);
Observable<JobChangeNotification> observeJob(String jobId, CallMetadata callMetadata);
Observable<JobChangeNotification> observeJobs(ObserveJobsQuery query, CallMetadata callMetadata);
Completable killJob(String jobId, CallMetadata callMetadata);
Observable<Task> findTask(String taskId, CallMetadata callMetadata);
Observable<TaskQueryResult> findTasks(TaskQuery taskQuery, CallMetadata callMetadata);
Completable killTask(TaskKillRequest taskKillRequest, CallMetadata callMetadata);
Completable updateTaskAttributes(TaskAttributesUpdate request, CallMetadata callMetadata);
Completable deleteTaskAttributes(TaskAttributesDeleteRequest request, CallMetadata callMetadata);
Completable moveTask(TaskMoveRequest taskMoveRequest, CallMetadata callMetadata);
}
| 315 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/jobmanager/gateway/GrpcJobServiceGateway.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.jobmanager.gateway;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.protobuf.Empty;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobChangeNotification;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.ObserveJobsQuery;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskId;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import com.netflix.titus.runtime.connector.GrpcRequestConfiguration;
import com.netflix.titus.runtime.connector.jobmanager.JobEventPropagationUtil;
import com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import io.grpc.stub.StreamObserver;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.runtime.connector.jobmanager.JobEventPropagationUtil.CHECKPOINT_GATEWAY_CLIENT;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.createMonoVoidRequest;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.createRequestCompletable;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.createRequestObservable;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.createSimpleClientResponseObserver;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.createWrappedStub;
/**
* {@link JobServiceGateway} implementation that connects to TitusMaster over the GRPC channel.
*/
@Singleton
public class GrpcJobServiceGateway implements JobServiceGateway {
private final JobManagementServiceGrpc.JobManagementServiceStub client;
private final GrpcRequestConfiguration configuration;
private final TitusRuntime titusRuntime;
@Inject
public GrpcJobServiceGateway(JobManagementServiceGrpc.JobManagementServiceStub client,
GrpcRequestConfiguration configuration,
TitusRuntime titusRuntime) {
this.client = client;
this.configuration = configuration;
this.titusRuntime = titusRuntime;
}
@Override
public Observable<String> createJob(JobDescriptor jobDescriptor, CallMetadata callMetadata) {
return createRequestObservable(emitter -> {
StreamObserver<JobId> streamObserver = GrpcUtil.createClientResponseObserver(
emitter,
jobId -> emitter.onNext(jobId.getId()),
emitter::onError,
emitter::onCompleted
);
V3HeaderInterceptor.attachCallMetadata(client, callMetadata)
.withDeadlineAfter(configuration.getRequestTimeoutMs(), TimeUnit.MILLISECONDS)
.createJob(jobDescriptor, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable updateJobCapacity(JobCapacityUpdate jobCapacityUpdate, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobCapacity(jobCapacityUpdate, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable updateJobCapacityWithOptionalAttributes(JobCapacityUpdateWithOptionalAttributes jobCapacityUpdateWithOptionalAttributes,
CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobCapacityWithOptionalAttributes(jobCapacityUpdateWithOptionalAttributes, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable updateJobProcesses(JobProcessesUpdate jobProcessesUpdate, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobProcesses(jobProcessesUpdate, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable updateJobStatus(JobStatusUpdate statusUpdate, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobStatus(statusUpdate, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Mono<Void> updateJobDisruptionBudget(JobDisruptionBudgetUpdate request, CallMetadata callMetadata) {
return createMonoVoidRequest(
emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientMonoResponse(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobDisruptionBudget(request, streamObserver);
},
configuration.getRequestTimeoutMs()
).ignoreElement().cast(Void.class);
}
@Override
public Mono<Void> updateJobAttributes(JobAttributesUpdate request, CallMetadata callMetadata) {
return createMonoVoidRequest(
emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientMonoResponse(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobAttributes(request, streamObserver);
},
configuration.getRequestTimeoutMs()
).ignoreElement().cast(Void.class);
}
@Override
public Mono<Void> deleteJobAttributes(JobAttributesDeleteRequest request, CallMetadata callMetadata) {
return createMonoVoidRequest(
emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientMonoResponse(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).deleteJobAttributes(request, streamObserver);
},
configuration.getRequestTimeoutMs()
).ignoreElement().cast(Void.class);
}
@Override
public Observable<Job> findJob(String jobId, CallMetadata callMetadata) {
Observable<Job> observable = createRequestObservable(emitter -> {
StreamObserver<Job> streamObserver = createSimpleClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).findJob(JobId.newBuilder().setId(jobId).build(), streamObserver);
}, configuration.getRequestTimeoutMs());
return observable.timeout(configuration.getRequestTimeoutMs(), TimeUnit.MILLISECONDS);
}
@Override
public Observable<JobQueryResult> findJobs(JobQuery jobQuery, CallMetadata callMetadata) {
return createRequestObservable(emitter -> {
StreamObserver<JobQueryResult> streamObserver = createSimpleClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).findJobs(jobQuery, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Observable<JobChangeNotification> observeJob(String jobId, CallMetadata callMetadata) {
return createRequestObservable(emitter -> {
StreamObserver<JobChangeNotification> streamObserver = createSimpleClientResponseObserver(emitter);
createWrappedStub(client, callMetadata).observeJob(JobId.newBuilder().setId(jobId).build(), streamObserver);
});
}
@Override
public Observable<JobChangeNotification> observeJobs(ObserveJobsQuery query, CallMetadata callMetadata) {
Observable<JobChangeNotification> source = createRequestObservable(emitter -> {
StreamObserver<JobChangeNotification> streamObserver = createSimpleClientResponseObserver(emitter);
createWrappedStub(client, callMetadata).observeJobs(query, streamObserver);
});
return source.map(event -> {
if (event.getNotificationCase() == JobChangeNotification.NotificationCase.JOBUPDATE) {
return event.toBuilder().setJobUpdate(
event.getJobUpdate().toBuilder()
.setJob(JobEventPropagationUtil.recordChannelLatency(
CHECKPOINT_GATEWAY_CLIENT,
event.getJobUpdate().getJob(),
event.getTimestamp(),
titusRuntime.getClock()
))
.build()
).build();
}
if (event.getNotificationCase() == JobChangeNotification.NotificationCase.TASKUPDATE) {
return event.toBuilder().setTaskUpdate(
event.getTaskUpdate().toBuilder()
.setTask(JobEventPropagationUtil.recordChannelLatency(
CHECKPOINT_GATEWAY_CLIENT,
event.getTaskUpdate().getTask(),
event.getTimestamp(),
titusRuntime.getClock()
))
.build()
).build();
}
return event;
});
}
@Override
public Completable killJob(String jobId, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).killJob(JobId.newBuilder().setId(jobId).build(), streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Observable<com.netflix.titus.grpc.protogen.Task> findTask(String taskId, CallMetadata callMetadata) {
Observable<com.netflix.titus.grpc.protogen.Task> observable = createRequestObservable(emitter -> {
StreamObserver<com.netflix.titus.grpc.protogen.Task> streamObserver = createSimpleClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).findTask(TaskId.newBuilder().setId(taskId).build(), streamObserver);
}, configuration.getRequestTimeoutMs());
return observable.timeout(configuration.getRequestTimeoutMs(), TimeUnit.MILLISECONDS);
}
@Override
public Observable<TaskQueryResult> findTasks(TaskQuery taskQuery, CallMetadata callMetadata) {
Observable<TaskQueryResult> observable = createRequestObservable(emitter -> {
StreamObserver<TaskQueryResult> streamObserver = createSimpleClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).findTasks(taskQuery, streamObserver);
}, configuration.getRequestTimeoutMs());
return observable.timeout(configuration.getRequestTimeoutMs(), TimeUnit.MILLISECONDS);
}
@Override
public Completable killTask(TaskKillRequest taskKillRequest, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).killTask(taskKillRequest, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable updateTaskAttributes(TaskAttributesUpdate attributesUpdate, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateTaskAttributes(attributesUpdate, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable deleteTaskAttributes(TaskAttributesDeleteRequest deleteRequest, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).deleteTaskAttributes(deleteRequest, streamObserver);
}, configuration.getRequestTimeoutMs());
}
@Override
public Completable moveTask(TaskMoveRequest taskMoveRequest, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).moveTask(taskMoveRequest, streamObserver);
}, configuration.getRequestTimeoutMs());
}
}
| 316 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/containerhealth | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/containerhealth/service/ContainerHealthServiceModule.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.containerhealth.service;
import com.google.inject.AbstractModule;
import com.netflix.titus.api.containerhealth.service.ContainerHealthService;
public final class ContainerHealthServiceModule extends AbstractModule {
@Override
protected void configure() {
bind(ContainerHealthService.class).to(AggregatingContainerHealthService.class);
}
}
| 317 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/containerhealth | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/containerhealth/service/AggregatingContainerHealthService.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.containerhealth.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.containerhealth.model.ContainerHealthFunctions;
import com.netflix.titus.api.containerhealth.model.ContainerHealthState;
import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthEvent;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthSnapshotEvent;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthUpdateEvent;
import com.netflix.titus.api.containerhealth.service.ContainerHealthService;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.ContainerHealthProvider;
import com.netflix.titus.api.jobmanager.service.ReadOnlyJobOperations;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.time.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import static com.netflix.titus.common.util.CollectionsExt.transformSet;
@Singleton
public class AggregatingContainerHealthService implements ContainerHealthService {
private static final Logger logger = LoggerFactory.getLogger(AggregatingContainerHealthService.class);
public static final String NAME = "aggregating";
private final Map<String, ContainerHealthService> healthServices;
private final ReadOnlyJobOperations jobOperations;
private final TitusRuntime titusRuntime;
private final Clock clock;
private final Flux<ContainerHealthEvent> healthStatuses;
@Inject
public AggregatingContainerHealthService(Set<ContainerHealthService> healthServices,
ReadOnlyJobOperations jobOperations,
TitusRuntime titusRuntime) {
logger.info("Registered container health services: {}", healthServices.stream().map(ContainerHealthService::getName).collect(Collectors.toList()));
this.healthServices = healthServices.stream().collect(Collectors.toMap(ContainerHealthService::getName, Function.identity()));
this.jobOperations = jobOperations;
this.titusRuntime = titusRuntime;
this.clock = titusRuntime.getClock();
this.healthStatuses = Flux
.defer(() -> {
ConcurrentMap<String, ContainerHealthState> emittedStates = new ConcurrentHashMap<>();
return Flux
.merge(transformSet(healthServices, h -> h.events(false)))
.flatMap(event -> handleContainerHealthUpdateEvent(event, emittedStates));
}).share().transformDeferred(ReactorExt.badSubscriberHandler(logger));
}
@Override
public String getName() {
return NAME;
}
@Override
public Optional<ContainerHealthStatus> findHealthStatus(String taskId) {
return jobOperations.findTaskById(taskId).map(jobTaskPair -> takeStatusOf(jobTaskPair.getLeft(), jobTaskPair.getRight()));
}
@Override
public Flux<ContainerHealthEvent> events(boolean snapshot) {
return snapshot
? healthStatuses.transformDeferred(ReactorExt.head(() -> Collections.singletonList(buildCurrentSnapshot())))
: healthStatuses;
}
private ContainerHealthSnapshotEvent buildCurrentSnapshot() {
List<ContainerHealthStatus> snapshot = new ArrayList<>();
jobOperations.getJobsAndTasks().forEach(p -> {
Job job = p.getLeft();
p.getRight().forEach(task -> {
if (task.getStatus().getState() == TaskState.Finished) {
snapshot.add(ContainerHealthStatus.terminated(task.getId(), titusRuntime.getClock().wallTime()));
} else {
snapshot.add(takeStatusOf(job, task));
}
});
});
return new ContainerHealthSnapshotEvent(snapshot);
}
private Flux<ContainerHealthEvent> handleContainerHealthUpdateEvent(ContainerHealthEvent event, ConcurrentMap<String, ContainerHealthState> emittedStates) {
if (!(event instanceof ContainerHealthUpdateEvent)) {
return Flux.empty();
}
String taskId = ((ContainerHealthUpdateEvent) event).getContainerHealthStatus().getTaskId();
return jobOperations.findTaskById(taskId)
.map(pair -> handleNewState(pair.getLeft(), pair.getRight(), emittedStates))
.orElseGet(() -> handleContainerHealthEventForUnknownTask(taskId, event, emittedStates));
}
private Flux<ContainerHealthEvent> handleNewState(Job<?> job, Task task, ConcurrentMap<String, ContainerHealthState> emittedStates) {
ContainerHealthStatus newStatus = takeStatusOf(job, task);
ContainerHealthState previousState = emittedStates.get(task.getId());
ContainerHealthState newState = newStatus.getState();
if (newState == previousState) {
return Flux.empty();
}
if (newState == ContainerHealthState.Terminated) {
emittedStates.remove(task.getId());
} else {
emittedStates.put(task.getId(), newState);
}
return Flux.just(ContainerHealthEvent.healthChanged(newStatus));
}
private Flux<ContainerHealthEvent> handleContainerHealthEventForUnknownTask(String taskId, ContainerHealthEvent event, ConcurrentMap<String, ContainerHealthState> emittedStates) {
logger.info("Received health update event for an unknown task: taskId={}, event={}", taskId, event);
emittedStates.remove(taskId);
return Flux.empty();
}
private ContainerHealthStatus takeStatusOf(Job<?> job, Task task) {
Set<String> healthProviders = job.getJobDescriptor().getDisruptionBudget().getContainerHealthProviders().stream()
.map(ContainerHealthProvider::getName)
.filter(healthServices::containsKey)
.collect(Collectors.toSet());
return healthProviders.isEmpty()
? taskStatusOfTaskWithNoHealthProviders(task)
: takeStatusOfTaskWithHealthProviders(task, healthProviders);
}
private ContainerHealthStatus taskStatusOfTaskWithNoHealthProviders(Task task) {
ContainerHealthState healthState;
switch (task.getStatus().getState()) {
case Accepted:
case Launched:
case StartInitiated:
case KillInitiated:
healthState = ContainerHealthState.Unhealthy;
break;
case Started:
healthState = ContainerHealthState.Healthy;
break;
case Disconnected:
healthState = ContainerHealthState.Unknown;
break;
case Finished:
healthState = ContainerHealthState.Terminated;
break;
default:
healthState = ContainerHealthState.Unknown;
}
return ContainerHealthStatus.newBuilder()
.withTaskId(task.getId())
.withState(healthState)
.withReason(task.getStatus().getState() + " != Started")
.withTimestamp(clock.wallTime())
.build();
}
private ContainerHealthStatus takeStatusOfTaskWithHealthProviders(Task task, Set<String> enabledServices) {
ContainerHealthStatus current = null;
for (String name : enabledServices) {
ContainerHealthService healthService = healthServices.get(name);
ContainerHealthStatus newStatus;
if (healthService != null) {
newStatus = healthService
.findHealthStatus(task.getId())
.orElseGet(() -> ContainerHealthStatus.newBuilder()
.withTaskId(task.getId())
.withState(ContainerHealthState.Unknown)
.withReason("not known to: " + name)
.withTimestamp(clock.wallTime())
.build()
);
} else {
newStatus = ContainerHealthStatus.newBuilder()
.withTaskId(task.getId())
.withState(ContainerHealthState.Unknown)
.withReason("unknown container health provider set: " + name)
.withTimestamp(clock.wallTime())
.build();
}
current = current == null ? newStatus : ContainerHealthFunctions.merge(current, newStatus);
}
return current;
}
}
| 318 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/containerhealth | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/containerhealth/service/AlwaysHealthyContainerHealthService.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.containerhealth.service;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.containerhealth.model.ContainerHealthState;
import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthEvent;
import com.netflix.titus.api.containerhealth.service.ContainerHealthService;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent;
import com.netflix.titus.api.jobmanager.service.V3JobOperations;
import com.netflix.titus.common.util.rx.ReactorExt;
import reactor.core.publisher.Flux;
@Singleton
public class AlwaysHealthyContainerHealthService implements ContainerHealthService {
private static final String NAME = "alwaysHealthy";
private final V3JobOperations jobOperations;
@Inject
public AlwaysHealthyContainerHealthService(V3JobOperations jobOperations) {
this.jobOperations = jobOperations;
}
@Override
public String getName() {
return NAME;
}
@Override
public Optional<ContainerHealthStatus> findHealthStatus(String taskId) {
return jobOperations.findTaskById(taskId).map(jobAndTaskPair -> buildHealthStatus(jobAndTaskPair.getRight()));
}
@Override
public Flux<ContainerHealthEvent> events(boolean snapshot) {
return ReactorExt.toFlux(jobOperations.observeJobs()).flatMap(event -> {
if (event instanceof TaskUpdateEvent) {
TaskUpdateEvent taskUpdateEvent = (TaskUpdateEvent) event;
Task task = taskUpdateEvent.getCurrentTask();
return Flux.just(ContainerHealthEvent.healthChanged(buildHealthStatus(task)));
}
return Flux.empty();
});
}
private ContainerHealthStatus buildHealthStatus(Task task) {
return ContainerHealthStatus.newBuilder()
.withTaskId(task.getId())
.withState(task.getStatus().getState() == TaskState.Finished ? ContainerHealthState.Terminated : ContainerHealthState.Healthy)
.withTimestamp(System.currentTimeMillis())
.build();
}
}
| 319 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/loadbalancer/GrpcModelConverters.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.loadbalancer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer;
import com.netflix.titus.api.model.Pagination;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import com.netflix.titus.grpc.protogen.LoadBalancerId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobQueryModelConverters.toGrpcPagination;
/**
* Collection of functions to convert load balancer models from internal to gRPC formats.
*/
public final class GrpcModelConverters {
private static Logger logger = LoggerFactory.getLogger(GrpcModelConverters.class);
public static GetAllLoadBalancersResult toGetAllLoadBalancersResult(List<JobLoadBalancer> jobLoadBalancerList, Pagination runtimePagination) {
GetAllLoadBalancersResult.Builder allLoadBalancersResult = GetAllLoadBalancersResult.newBuilder();
allLoadBalancersResult.setPagination(toGrpcPagination(runtimePagination));
// We expect the list to be in a sorted-by-jobId order and iterate as such
GetJobLoadBalancersResult.Builder getJobLoadBalancersResultBuilder = GetJobLoadBalancersResult.newBuilder();
Set<String> addedJobIds = new HashSet<>();
for (JobLoadBalancer jobLoadBalancer : jobLoadBalancerList) {
String jobId = jobLoadBalancer.getJobId();
// Check if we're processing a new Job ID
if (!addedJobIds.contains(jobId)) {
// Add any previous JobID's result if it existed
if (getJobLoadBalancersResultBuilder.getLoadBalancersBuilderList().size() > 0) {
allLoadBalancersResult.addJobLoadBalancers(getJobLoadBalancersResultBuilder.build());
}
getJobLoadBalancersResultBuilder = GetJobLoadBalancersResult.newBuilder()
.setJobId(jobId);
addedJobIds.add(jobId);
}
getJobLoadBalancersResultBuilder.addLoadBalancers(LoadBalancerId.newBuilder().setId(jobLoadBalancer.getLoadBalancerId()).build());
}
if (getJobLoadBalancersResultBuilder.getLoadBalancersBuilderList().size() > 0) {
allLoadBalancersResult.addJobLoadBalancers(getJobLoadBalancersResultBuilder.build());
}
return allLoadBalancersResult.build();
}
}
| 320 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/loadbalancer/LoadBalancerCursors.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.loadbalancer;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoadBalancerCursors {
private static final Logger logger = LoggerFactory.getLogger(LoadBalancerCursors.class);
private static final Pattern CURSOR_FORMAT_RE = Pattern.compile("(.*)@(.*)");
public static Comparator<JobLoadBalancer> loadBalancerComparator() {
return (first, second) -> {
String firstValue = first.getJobId() + '@' + first.getLoadBalancerId();
String secondValue = second.getJobId() + '@' + second.getLoadBalancerId();
return firstValue.compareTo(secondValue);
};
}
public static Optional<Integer> loadBalancerIndexOf(List<JobLoadBalancer> sortedLoadBalancers, String cursor) {
return decode(cursor).map(p -> {
final JobLoadBalancer jobLoadBalancer = new JobLoadBalancer(p.getLeft(), p.getRight());
final int idx = Collections.binarySearch(sortedLoadBalancers, jobLoadBalancer, loadBalancerComparator());
return idx >= 0 ? idx : Math.max(-1, -idx - 2);
});
}
public static String newCursorFrom(JobLoadBalancer jobLoadBalancer) {
return encode(jobLoadBalancer.getJobId(), jobLoadBalancer.getLoadBalancerId());
}
private static String encode(String jobId, String loadBalancerId) {
String value = jobId + '@' + loadBalancerId;
return Base64.getEncoder().encodeToString(value.getBytes());
}
private static Optional<Pair<String, String>> decode(String encodedValue) {
String decoded;
try {
decoded = new String(Base64.getDecoder().decode(encodedValue.getBytes()));
} catch (Exception e) {
logger.debug("Cannot decode value: {}", encodedValue, e);
return Optional.empty();
}
Matcher matcher = CURSOR_FORMAT_RE.matcher(decoded);
if (!matcher.matches()) {
logger.debug("Not valid cursor value: {}", decoded);
return Optional.empty();
}
return Optional.of(Pair.of(matcher.group(1), matcher.group(2)));
}
}
| 321 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/AggregatingSanitizer.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.TitusValidatorConfiguration;
import com.netflix.titus.common.util.CollectionsExt;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
@Singleton
public class AggregatingSanitizer implements AdmissionSanitizer<JobDescriptor> {
private final TitusValidatorConfiguration configuration;
private final Collection<? extends AdmissionSanitizer<JobDescriptor>> sanitizers;
@Inject
public AggregatingSanitizer(TitusValidatorConfiguration configuration, Collection<? extends AdmissionSanitizer<JobDescriptor>> sanitizers) {
this.configuration = configuration;
this.sanitizers = sanitizers;
}
/**
* Executes all sanitizers in parallel, collecting partial results in the first phase, and applying them all
* sequentially through each sanitizer in the second phase.
* <p>
* The iteration order of the sanitizers is not guaranteed. Any sanitization failure results in the Mono
* emitting an error.
*
* @return a {@link Function} that applies partial updates through all sanitizers sequentially
*/
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) {
List<Mono<UnaryOperator<JobDescriptor>>> sanitizationFunctions = sanitizers.stream()
.map(s -> s.sanitize(entity)
.subscribeOn(Schedulers.parallel())
.timeout(getTimeout(), Mono.error(() -> TitusServiceException.internal(
s.getClass().getSimpleName() + " timed out running job sanitization")
))
// important: Mono.zip will be short circuited if members are empty
.switchIfEmpty(Mono.just(UnaryOperator.identity()))
)
.collect(Collectors.toList());
Mono<UnaryOperator<JobDescriptor>> merged = Mono.zip(sanitizationFunctions, partials -> {
if (CollectionsExt.isNullOrEmpty(partials)) {
return UnaryOperator.identity();
}
//noinspection unchecked
return applyAll(Arrays.stream(partials).map(partial -> (UnaryOperator<JobDescriptor>) partial));
});
return merged.switchIfEmpty(Mono.just(UnaryOperator.identity()))
.timeout(getTimeout().multipliedBy(2),
Mono.error(() -> TitusServiceException.internal("Job sanitization timed out")));
}
private Duration getTimeout() {
return Duration.ofMillis(configuration.getTimeoutMs());
}
private static UnaryOperator<JobDescriptor> applyAll(Stream<UnaryOperator<JobDescriptor>> partialUpdates) {
return entity -> {
AtomicReference<JobDescriptor> result = new AtomicReference<>(entity);
partialUpdates.forEachOrdered(result::updateAndGet);
return result.get();
};
}
}
| 322 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionUtil.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Optional;
import java.util.SortedSet;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePrediction;
import org.apache.commons.math3.distribution.NormalDistribution;
public final class JobRuntimePredictionUtil {
private static final double LOW_QUANTILE = 0.05;
public static final double HIGH_QUANTILE = 0.95;
static final double NORM_SIGMA = computeNormSigma();
private JobRuntimePredictionUtil() {
}
static boolean expectedLowest(JobRuntimePrediction low) {
return low.getConfidence() == LOW_QUANTILE;
}
static Optional<JobRuntimePrediction> findRequested(SortedSet<JobRuntimePrediction> predictions, double quantile) {
if (predictions.isEmpty()) {
return Optional.empty();
}
return predictions.stream().filter(p -> p.getConfidence() == quantile).findFirst();
}
/**
* Estimate the standard deviation of a gaussian distribution given 2 quantiles. See https://www.johndcook.com/quantiles_parameters.pdf
*/
private static double computeNormSigma() {
NormalDistribution normal = new NormalDistribution();
return normal.inverseCumulativeProbability(HIGH_QUANTILE) - normal.inverseCumulativeProbability(LOW_QUANTILE);
}
}
| 323 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/ServiceMeshImageSanitizerConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.titus.common.model.admission.AdmissionValidatorConfiguration;
import com.netflix.titus.common.model.admission.TitusValidatorConfiguration;
@Configuration(prefix = "titus.validate.serviceMesh.image")
public interface ServiceMeshImageSanitizerConfiguration extends AdmissionValidatorConfiguration {
@DefaultValue("true")
boolean isEnabled();
/**
* Since Image validations are on the job accept path the timeout value is aggressive.
* This must be smaller than {@link TitusValidatorConfiguration#getTimeoutMs()}.
*/
@DefaultValue("4500")
long getServiceMeshImageValidationTimeoutMs();
}
| 324 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSelectors.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.google.common.collect.Iterators;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.api.ConfigListener;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.DateTimeExt;
import com.netflix.titus.common.util.PropertiesExt;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import com.netflix.titus.common.util.closeable.CloseableReference;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePrediction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_SELECTOR_INFO;
public final class JobRuntimePredictionSelectors {
private static final Logger logger = LoggerFactory.getLogger(JobRuntimePredictionSelectors.class);
private static final JobRuntimePredictionSelector NEVER_SELECTOR = (jobDescriptor, predictions) -> Optional.empty();
private JobRuntimePredictionSelectors() {
}
public static JobRuntimePredictionSelector never() {
return NEVER_SELECTOR;
}
/**
* Always select the highest confidence prediction.
*/
public static JobRuntimePredictionSelector best() {
return best(Collections.emptyMap());
}
/**
* Always select the highest confidence prediction, with additional metadata.
*/
public static JobRuntimePredictionSelector best(Map<String, String> selectionMetadata) {
Map<String, String> allMetadata = appendSelectorInfoIfMissing(
selectionMetadata,
() -> "best, createdAt: " + DateTimeExt.toLocalDateTimeString(System.currentTimeMillis())
);
return (jobDescriptor, predictions) -> CollectionsExt.isNullOrEmpty(predictions.getPredictions())
? Optional.empty()
: Optional.of(JobRuntimePredictionSelection.newBuilder().withPrediction(predictions.getPredictions().last()).withMetadata(allMetadata).build());
}
/**
* Select prediction with the highest confidence if it is below `runtimeThresholdInSeconds` and if the estimated
* standard deviation of the predicted distribution is below `sigmaThreshold`
*/
public static JobRuntimePredictionSelector aboveThreshold(double runtimeThresholdInSeconds,
double sigmaThreshold,
double quantile,
Map<String, String> selectionMetadata) {
Map<String, String> allMetadata = appendSelectorInfoIfMissing(
selectionMetadata,
() -> String.format("aboveThreshold{runtimeThresholdInSeconds=%s, sigmaThreshold=%s}, createdAt: %s",
runtimeThresholdInSeconds, sigmaThreshold,
DateTimeExt.toLocalDateTimeString(System.currentTimeMillis())
)
);
return (jobDescriptor, predictions) -> {
SortedSet<JobRuntimePrediction> predictionsSet = predictions.getPredictions();
if (CollectionsExt.isNullOrEmpty(predictionsSet) || predictionsSet.size() < 2) {
return Optional.empty();
}
JobRuntimePrediction first = predictionsSet.first();
if (!JobRuntimePredictionUtil.expectedLowest(first)) {
return Optional.empty();
}
JobRuntimePrediction requested = JobRuntimePredictionUtil.findRequested(predictionsSet, quantile).orElse(null);
if (requested == null || requested.getRuntimeInSeconds() > runtimeThresholdInSeconds) {
return Optional.empty();
}
double sigma = (requested.getRuntimeInSeconds() - first.getRuntimeInSeconds()) / JobRuntimePredictionUtil.NORM_SIGMA;
if (sigma > sigmaThreshold) {
return Optional.empty();
}
return Optional.of(JobRuntimePredictionSelection.newBuilder()
.withPrediction(requested)
.withMetadata(allMetadata)
.build()
);
};
}
/**
* See {@link #aboveThreshold(double, double, double, Map)}.
*/
public static JobRuntimePredictionSelector aboveThreshold(Config config, Map<String, String> selectionMetadata) {
double runtimeThresholdInSeconds = config.getDouble("runtimeThresholdInSeconds", Double.MAX_VALUE);
double sigmaThreshold = config.getDouble("sigmaThreshold", Double.MAX_VALUE);
double quantile = config.getDouble("quantile", JobRuntimePredictionUtil.HIGH_QUANTILE);
return aboveThreshold(runtimeThresholdInSeconds, sigmaThreshold, quantile, selectionMetadata);
}
/**
* Create a map threshold selectors. The first segment in the key name is a selector name.
*/
public static Map<String, JobRuntimePredictionSelector> aboveThresholds(Config config, Map<String, String> selectionMetadata) {
String[] keys = Iterators.toArray(config.getKeys(), String.class);
Set<String> cellNames = PropertiesExt.getRootNames(Arrays.asList(keys), 1);
Map<String, Config> subConfigs = new HashMap<>();
cellNames.forEach(cell -> subConfigs.put(cell, config.getPrefixedView(cell)));
Map<String, String> allMetadata = appendSelectorInfoIfMissing(
selectionMetadata,
() -> String.format("aboveThresholds[%s], createdAt: %s",
new TreeSet<>(subConfigs.keySet()).stream().map(k -> k + '=' + Archaius2Ext.toString(subConfigs.get(k))).collect(Collectors.joining(", ")) + ']',
DateTimeExt.toLocalDateTimeString(System.currentTimeMillis())
)
);
return CollectionsExt.mapValues(subConfigs, cell -> aboveThreshold(cell, allMetadata), HashMap::new);
}
/**
* A helper selector which listens to configuration changes, and reloads downstream selectors when that happens.
*/
public static CloseableReference<JobRuntimePredictionSelector> reloadedOnConfigurationUpdate(Config config, Function<Config, JobRuntimePredictionSelector> factory) {
AtomicReference<JobRuntimePredictionSelector> last = new AtomicReference<>(factory.apply(config));
ConfigListener listener = new ConfigListener() {
@Override
public void onConfigAdded(Config config) {
tryReload(config);
}
@Override
public void onConfigRemoved(Config config) {
tryReload(config);
}
@Override
public void onConfigUpdated(Config config) {
tryReload(config);
}
@Override
public void onError(Throwable error, Config config) {
tryReload(config);
}
private void tryReload(Config updated) {
try {
// Use the past config, in case it is prefixed view
last.set(factory.apply(config));
} catch (Exception e) {
logger.info("Failed to reload job runtime prediction selectors", e);
}
}
};
config.addListener(listener);
JobRuntimePredictionSelector wrapper = (jobDescriptor, predictions) -> last.get().apply(jobDescriptor, predictions);
return CloseableReference.<JobRuntimePredictionSelector>newBuilder()
.withResource(wrapper)
.withCloseAction(() -> config.removeListener(listener))
.withSwallowException(true)
.withSerialize(true)
.build();
}
/**
* AB test choosing randomly from the provided collection of selectors. At each invocation, a one
* downstream selector is chosen, and the result is tagged with its id.
*/
public static JobRuntimePredictionSelector abTestRandom(Map<String, JobRuntimePredictionSelector> selectors) {
if (CollectionsExt.isNullOrEmpty(selectors)) {
return never();
}
List<Map.Entry<String, JobRuntimePredictionSelector>> entries = new ArrayList<>(selectors.entrySet());
Random random = new Random(System.nanoTime());
return (jobDescriptor, predictions) -> {
Map.Entry<String, JobRuntimePredictionSelector> entry = entries.get(random.nextInt(selectors.size()));
String id = entry.getKey();
JobRuntimePredictionSelector selector = entry.getValue();
return selector.apply(jobDescriptor, predictions).map(selection -> {
Map<String, String> metadata = CollectionsExt.copyAndAdd(selection.getMetadata(), JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_AB_TEST, id);
return selection.toBuilder().withMetadata(metadata).build();
});
};
}
private static Map<String, String> appendSelectorInfoIfMissing(Map<String, String> selectionMetadata, Supplier<String> infoSupplier) {
return selectionMetadata.containsKey(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SELECTOR_INFO)
? selectionMetadata
: CollectionsExt.copyAndAdd(selectionMetadata, JOB_ATTRIBUTES_RUNTIME_PREDICTION_SELECTOR_INFO, infoSupplier.get());
}
}
| 325 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobSecurityValidatorConfiguration.java | /*
*
* * Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.titus.common.model.admission.AdmissionValidatorConfiguration;
import com.netflix.titus.common.model.admission.TitusValidatorConfiguration;
@Configuration(prefix = "titus.validate.job.security")
public interface JobSecurityValidatorConfiguration extends AdmissionValidatorConfiguration {
@DefaultValue("true")
boolean isIamValidatorEnabled();
/**
* If set to true, validation process executes assume role by calling AWS STS service. For safety reason, the
* acquired credentials are valid for short amount of time only.
*/
@DefaultValue("false")
boolean isIamRoleWithStsValidationEnabled();
@DefaultValue("titusagentInstanceProfile")
String getAgentIamAssumeRole();
/**
* Since IAM validations are on the job accept path the timeout value is aggressive.
* This must be smaller than {@link TitusValidatorConfiguration#getTimeoutMs()}.
*/
@DefaultValue("4500")
long getIamValidationTimeoutMs();
@DefaultValue("1000,2000,3000")
String getIamValidationHedgeThresholdsMs();
}
| 326 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/TitusAdmissionModule.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Arrays;
import java.util.Collections;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.admission.TitusValidatorConfiguration;
import com.netflix.titus.runtime.TitusEntitySanitizerModule;
/**
* This module provides dependencies for Titus validation ({@link AdmissionValidator} and {@link AdmissionSanitizer})
* which is beyond syntactic validation. See {@link TitusEntitySanitizerModule} for syntactic sanitization and validation.
*/
public class TitusAdmissionModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
TitusValidatorConfiguration getConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(TitusValidatorConfiguration.class);
}
@Provides
@Singleton
public AdmissionValidator<JobDescriptor> getJobValidator(TitusValidatorConfiguration configuration,
JobIamValidator jobIamValidator,
Registry registry) {
return new AggregatingValidator(configuration, registry, Collections.singletonList(jobIamValidator));
}
@Provides
@Singleton
public AdmissionSanitizer<JobDescriptor> getJobSanitizer(TitusValidatorConfiguration configuration,
JobImageSanitizer jobImageSanitizer,
JobIamValidator jobIamSanitizer,
ServiceMeshImageSanitizer serviceMeshImageSanitizer) {
return new AggregatingSanitizer(configuration, Arrays.asList(jobImageSanitizer, jobIamSanitizer, serviceMeshImageSanitizer));
}
}
| 327 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobSecurityValidatorModule.java | /*
*
* * Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.titus.api.connector.cloud.IamConnector;
import com.netflix.titus.api.connector.cloud.noop.NoOpIamConnector;
public class JobSecurityValidatorModule extends AbstractModule {
@Override
protected void configure() {
bind(IamConnector.class).to(NoOpIamConnector.class);
}
@Provides
@Singleton
public JobSecurityValidatorConfiguration getJobSecurityValidatorConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(JobSecurityValidatorConfiguration.class);
}
}
| 328 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobImageSanitizer.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.time.Duration;
import java.util.function.UnaryOperator;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.api.jobmanager.model.job.Image;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.admission.ValidatorMetrics;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.runtime.connector.registry.RegistryClient;
import com.netflix.titus.runtime.connector.registry.TitusRegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
/**
* This {@link AdmissionValidator} implementation validates and sanitizes Job image information.
*/
@Singleton
public class JobImageSanitizer implements AdmissionSanitizer<JobDescriptor> {
private static final Logger logger = LoggerFactory.getLogger(JobImageSanitizer.class);
private final JobImageSanitizerConfiguration configuration;
private final RegistryClient registryClient;
private final ValidatorMetrics validatorMetrics;
@Inject
public JobImageSanitizer(JobImageSanitizerConfiguration configuration, RegistryClient registryClient, Registry spectatorRegistry) {
this.configuration = configuration;
this.registryClient = registryClient;
this.validatorMetrics = new ValidatorMetrics(this.getClass().getSimpleName(), spectatorRegistry);
}
/**
* @return a {@link UnaryOperator} that adds a sanitized Image or job attributes when sanitization was skipped
*/
@Override
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor jobDescriptor) {
if (isDisabled()) {
return Mono.just(JobImageSanitizer::skipSanitization);
}
Image image = jobDescriptor.getContainer().getImage();
return sanitizeImage(jobDescriptor)
.map(JobImageSanitizer::setImageFunction)
.timeout(Duration.ofMillis(configuration.getJobImageValidationTimeoutMs()))
.doOnSuccess(j -> validatorMetrics.incrementValidationSuccess(image.getName()))
.onErrorReturn(throwable -> isAllowedException(throwable, image), JobImageSanitizer::skipSanitization)
.onErrorMap(Exception.class, error -> new IllegalArgumentException(String.format(
"Image validation error: image=%s, cause=%s",
image, error.getMessage()
), error));
}
private static UnaryOperator<JobDescriptor> setImageFunction(Image image) {
return entity -> entity.toBuilder()
.withContainer(entity.getContainer().toBuilder()
.withImage(image)
.build())
.build();
}
private Mono<Image> sanitizeImage(JobDescriptor jobDescriptor) {
Image image = jobDescriptor.getContainer().getImage();
if (StringExt.isNotEmpty(image.getDigest())) {
return Mono.empty();
}
return registryClient.getImageDigest(image.getName(), image.getTag())
.map(digest -> image.toBuilder().withDigest(digest).build());
}
private Mono<String> checkImageDigestExist(Image image) {
return registryClient.getImageDigest(image.getName(), image.getDigest());
}
private boolean isDisabled() {
return !configuration.isEnabled();
}
/**
* Determines if this Exception should fail open, or produce a sanitization failure
*/
private boolean isAllowedException(Throwable throwable, Image image) {
logger.error("Exception while checking image digest: {}", throwable.getMessage());
logger.debug("Full stacktrace", throwable);
String imageName = image.getName();
String imageVersion = image.getDigest().isEmpty() ? image.getTag() : image.getDigest();
String imageResource = String.format("%s_%s", imageName, imageVersion);
if (throwable instanceof TitusRegistryException) {
TitusRegistryException tre = (TitusRegistryException) throwable;
// Use a more specific error tag if available
validatorMetrics.incrementValidationError(
imageResource,
tre.getErrorCode().name()
);
// We are ignoring most image validation errors. We will filter
// fewer errors as we gain feature confidence.
switch (tre.getErrorCode()) {
case IMAGE_NOT_FOUND:
return false;
default:
return true;
}
}
validatorMetrics.incrementValidationError(
imageResource,
throwable.getClass().getSimpleName()
);
// unknown errors should prevent job creation
return false;
}
@SuppressWarnings("unchecked")
private static JobDescriptor skipSanitization(JobDescriptor jobDescriptor) {
return JobFunctions.appendJobDescriptorAttribute(jobDescriptor,
JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IMAGE, true
);
}
}
| 329 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/FailJobValidator.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.function.UnaryOperator;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import reactor.core.publisher.Mono;
/**
* This {@link AdmissionValidator} implementation always causes validation to fail. It is used for testing purposes.
*/
public class FailJobValidator implements AdmissionValidator<JobDescriptor>, AdmissionSanitizer<JobDescriptor> {
public static final String ERR_FIELD = "fail-field";
public static final String ERR_DESCRIPTION = "The FailJobValidator should always fail with a unique error:";
private final ValidationError.Type errorType;
public FailJobValidator() {
this(ValidationError.Type.HARD);
}
public FailJobValidator(ValidationError.Type errorType) {
this.errorType = errorType;
}
@Override
public Mono<Set<ValidationError>> validate(JobDescriptor entity) {
final String errorMsg = String.format("%s %s", ERR_DESCRIPTION, UUID.randomUUID().toString());
final ValidationError error = new ValidationError(ERR_FIELD, errorMsg);
return Mono.just(new HashSet<>(Collections.singletonList(error)));
}
@Override
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) {
return Mono.error(TitusServiceException.invalidArgument(ERR_DESCRIPTION));
}
@Override
public ValidationError.Type getErrorType() {
return errorType;
}
}
| 330 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobImageSanitizerConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.titus.common.model.admission.AdmissionValidatorConfiguration;
import com.netflix.titus.common.model.admission.TitusValidatorConfiguration;
@Configuration(prefix = "titus.validate.job.image")
public interface JobImageSanitizerConfiguration extends AdmissionValidatorConfiguration {
@DefaultValue("true")
boolean isEnabled();
/**
* Since Image validations are on the job accept path the timeout value is aggressive.
* This must be smaller than {@link TitusValidatorConfiguration#getTimeoutMs()}.
*/
@DefaultValue("4500")
long getJobImageValidationTimeoutMs();
}
| 331 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/PassJobValidator.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Collections;
import java.util.Set;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import reactor.core.publisher.Mono;
/**
* This {@link AdmissionValidator} implementation always causes validation to pass. It is used as a default implementation which
* should be overridden.
*/
@Singleton
public class PassJobValidator implements AdmissionValidator<JobDescriptor>, AdmissionSanitizer<JobDescriptor> {
private final ValidationError.Type errorType;
public PassJobValidator() {
this(ValidationError.Type.SOFT);
}
public PassJobValidator(ValidationError.Type errorType) {
this.errorType = errorType;
}
@Override
public Mono<Set<ValidationError>> validate(JobDescriptor entity) {
return Mono.just(Collections.emptySet());
}
@Override
public ValidationError.Type getErrorType() {
return errorType;
}
@Override
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) {
// Sets an availability zone and capacity for any EBS volumes
return Mono.just(jd -> jd.toBuilder()
.withContainer(jd.getContainer().toBuilder()
.withContainerResources(jd.getContainer().getContainerResources().toBuilder()
.withEbsVolumes(jd.getContainer().getContainerResources().getEbsVolumes().stream()
.map(ebsVolume -> ebsVolume.toBuilder()
.withVolumeAvailabilityZone("us-east-1a")
.withVolumeCapacityGB(5)
.build())
.collect(Collectors.toList()))
.build())
.build())
.build());
}
}
| 332 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSanitizer.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.UnaryOperator;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.FunctionExt;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePrediction;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePredictionClient;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePredictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION;
import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_SKIP_RUNTIME_PREDICTION;
import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.appendJobDescriptorAttributes;
/**
* Decorates {@link JobDescriptor job descriptors} with a prediction of their expected runtime. All information about
* predictions will be available as Job attributes.
*/
@Singleton
public class JobRuntimePredictionSanitizer implements AdmissionSanitizer<JobDescriptor> {
private static final Logger logger = LoggerFactory.getLogger(JobRuntimePredictionSanitizer.class);
private final JobRuntimePredictionClient predictionsClient;
private final JobRuntimePredictionSelector selector;
private final JobRuntimePredictionConfiguration configuration;
private final JobRuntimePredictionSanitizerMetrics metrics;
@Inject
public JobRuntimePredictionSanitizer(JobRuntimePredictionClient predictionsClient,
JobRuntimePredictionSelector selector,
JobRuntimePredictionConfiguration configuration,
TitusRuntime runtime) {
this.predictionsClient = predictionsClient;
this.selector = selector;
this.configuration = configuration;
this.metrics = new JobRuntimePredictionSanitizerMetrics(runtime.getRegistry());
}
@Override
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) {
if (!JobFunctions.isBatchJob(entity)) {
return Mono.empty();
}
if (isSkippedForJob(entity)) {
metrics.jobOptedOut();
return Mono.just(JobRuntimePredictionSanitizer::skipSanitization);
}
return predictionsClient.getRuntimePredictions(entity)
.map(this::addPredictionToJob)
.doOnError(throwable -> {
metrics.predictionServiceError();
logger.error("Error calling the job runtime prediction service, skipping prediction for {}: {}",
entity.getApplicationName(), throwable.getMessage());
})
.onErrorReturn(JobRuntimePredictionSanitizer::skipSanitization)
// the runtime limit acts as a cap on the prediction, or a fallback when no prediction is selected
.map(sanitizer -> FunctionExt.andThen(sanitizer, this::capPredictionToRuntimeLimit))
.defaultIfEmpty(this::capPredictionToRuntimeLimit);
}
@SuppressWarnings("unchecked")
private UnaryOperator<JobDescriptor> addPredictionToJob(JobRuntimePredictions predictions) {
return jobDescriptor -> {
Map<String, String> metadata = new HashMap<>();
metadata.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, predictions.getModelId());
metadata.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, predictions.getVersion());
predictions.toSimpleString().ifPresent(predictionsStr ->
metadata.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE, predictionsStr)
);
Optional<JobRuntimePredictionSelection> selectionOpt;
if (isValid(predictions)) {
selectionOpt = FunctionExt.ifNotPresent(
selector.apply(jobDescriptor, predictions),
metrics::noPredictionSelected
);
} else {
selectionOpt = Optional.empty();
metrics.invalidPredictions();
}
// extra local variable otherwise compiler type inference breaks
Optional<JobDescriptor> resultOpt = selectionOpt
.map(selection -> {
metadata.putAll(selection.getMetadata());
metadata.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, Double.toString(selection.getPrediction().getRuntimeInSeconds()));
metadata.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, Double.toString(selection.getPrediction().getConfidence()));
return appendJobDescriptorAttributes(jobDescriptor, metadata);
});
return resultOpt.orElseGet(() -> skipSanitization(appendJobDescriptorAttributes(jobDescriptor, metadata)));
};
}
/**
* Use the prediction when available and shorter than the runtime limit, otherwise the runtime limit becomes
* the prediction if within {@link JobRuntimePredictionConfiguration#getMaxOpportunisticRuntimeLimitMs()}
*/
@SuppressWarnings("unchecked")
private JobDescriptor capPredictionToRuntimeLimit(JobDescriptor jobDescriptor) {
// non-batch jobs have been filtered before this point, it is safe to cast
BatchJobExt extensions = ((JobDescriptor<BatchJobExt>) jobDescriptor).getExtensions();
long runtimeLimitMs = extensions.getRuntimeLimitMs();
if (runtimeLimitMs <= 0 || runtimeLimitMs > configuration.getMaxOpportunisticRuntimeLimitMs()) {
return jobDescriptor; // no runtime limit or too high to be used, noop
}
return JobFunctions.getJobRuntimePrediction(jobDescriptor)
.filter(prediction -> runtimeLimitMs > prediction.toMillis())
.map(ignored -> jobDescriptor)
.orElseGet(() -> JobFunctions.appendJobDescriptorAttributes(jobDescriptor, ImmutableMap.<String, String>builder()
.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, Double.toString(runtimeLimitMs / 1000.0))
.put(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, Double.toString(1.0))
.build()));
}
private static boolean isValid(JobRuntimePredictions predictions) {
if (CollectionsExt.isNullOrEmpty(predictions.getPredictions())) {
return false;
}
// higher quality predictions are always expected to be longer, and no zeroes allowed
double lastSeen = 0.0;
for (JobRuntimePrediction prediction : predictions.getPredictions()) {
double current = prediction.getRuntimeInSeconds();
if (current <= 0.0 || current < lastSeen) {
return false;
}
lastSeen = current;
}
return true;
}
private static boolean isSkippedForJob(JobDescriptor<?> entity) {
return Boolean.parseBoolean(
entity.getAttributes().getOrDefault(JOB_PARAMETER_SKIP_RUNTIME_PREDICTION, "false").trim()
);
}
@SuppressWarnings("unchecked")
private static JobDescriptor skipSanitization(JobDescriptor jobDescriptor) {
return JobFunctions.appendJobDescriptorAttribute(jobDescriptor,
JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, true
);
}
}
| 333 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSelector.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Optional;
import java.util.function.BiFunction;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePredictions;
/**
* Strategy for selecting a particular job runtime prediction to use, given a collection sorted from lower to higher
* quality. In addition to returning one of the predictions to be used, implementations may return job attributes to
* be appended to a {@link JobDescriptor} as metadata about the selection.
*/
public interface JobRuntimePredictionSelector extends BiFunction<JobDescriptor<?>, JobRuntimePredictions, Optional<JobRuntimePredictionSelection>> {
}
| 334 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSanitizerMetrics.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.model.admission.ValidatorMetrics;
class JobRuntimePredictionSanitizerMetrics {
private enum Reason {
OPTED_OUT, PREDICTION_SERVICE_ERROR, INVALID_PREDICTIONS, NO_PREDICTION_SELECTED;
public String asTag() {
return name().toLowerCase();
}
}
private final ValidatorMetrics metrics;
JobRuntimePredictionSanitizerMetrics(Registry registry) {
this.metrics = new ValidatorMetrics("JobRuntimePredictionSanitizer", registry);
}
void jobOptedOut() {
metrics.incrementValidationSkipped(Reason.OPTED_OUT.asTag());
}
void predictionServiceError() {
metrics.incrementValidationSkipped(Reason.PREDICTION_SERVICE_ERROR.asTag());
}
void invalidPredictions() {
metrics.incrementValidationSkipped(Reason.INVALID_PREDICTIONS.asTag());
}
void noPredictionSelected() {
metrics.incrementValidationSkipped(Reason.NO_PREDICTION_SELECTED.asTag());
}
}
| 335 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/ServiceMeshImageSanitizer.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.time.Duration;
import java.util.function.UnaryOperator;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.api.jobmanager.model.job.Image;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.ValidatorMetrics;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.runtime.connector.registry.RegistryClient;
import com.netflix.titus.runtime.connector.registry.TitusRegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
/**
* This {@link AdmissionSanitizer} implementation validates and sanitizes service mesh image attributes.
*/
@Singleton
public class ServiceMeshImageSanitizer implements AdmissionSanitizer<JobDescriptor> {
private static final Logger logger = LoggerFactory.getLogger(ServiceMeshImageSanitizer.class);
private final ServiceMeshImageSanitizerConfiguration configuration;
private final RegistryClient registryClient;
private final ValidatorMetrics validatorMetrics;
@Inject
public ServiceMeshImageSanitizer(ServiceMeshImageSanitizerConfiguration configuration, RegistryClient registryClient, Registry spectatorRegistry) {
this.configuration = configuration;
this.registryClient = registryClient;
this.validatorMetrics = new ValidatorMetrics(this.getClass().getSimpleName(), spectatorRegistry);
}
/**
* @return a {@link UnaryOperator} that adds a sanitized Image or container attributes when sanitization was skipped
*/
@Override
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor jobDescriptor) {
if (isDisabled()) {
return Mono.just(ServiceMeshImageSanitizer::skipSanitization);
}
if (!serviceMeshIsEnabled(jobDescriptor)) {
validatorMetrics.incrementValidationSkipped("serviceMeshNotEnabled");
return Mono.just(UnaryOperator.identity());
}
if (!serviceMeshIsPinned(jobDescriptor)) {
validatorMetrics.incrementValidationSkipped("serviceMeshNotPinned");
return Mono.just(UnaryOperator.identity());
}
try {
Image image = getServiceMeshImage(jobDescriptor);
return sanitizeServiceMeshImage(image)
.map(ServiceMeshImageSanitizer::setMeshImageFunction)
.timeout(Duration.ofMillis(configuration.getServiceMeshImageValidationTimeoutMs()))
.doOnSuccess(j -> validatorMetrics.incrementValidationSuccess(image.getName()))
.onErrorReturn(throwable -> isAllowedException(throwable, image), ServiceMeshImageSanitizer::skipSanitization)
.onErrorMap(Exception.class, error -> new IllegalArgumentException(String.format(
"Service mesh image validation error: image=%s, cause=%s",
image, error.getMessage()
), error));
} catch (Throwable t) {
return Mono.error(t);
}
}
private static UnaryOperator<JobDescriptor> setMeshImageFunction(Image image) {
String imageName = toImageName(image);
return jobDescriptor -> JobFunctions.appendContainerAttribute(jobDescriptor,
JobAttributes.JOB_CONTAINER_ATTRIBUTE_SERVICEMESH_CONTAINER, imageName);
}
private Mono<Image> sanitizeServiceMeshImage(Image image) {
if (StringExt.isNotEmpty(image.getDigest())) {
return checkImageDigestExist(image).then(Mono.empty());
}
return registryClient.getImageDigest(image.getName(), image.getTag())
.map(digest -> image.toBuilder().withDigest(digest).build());
}
private Mono<String> checkImageDigestExist(Image image) {
return registryClient.getImageDigest(image.getName(), image.getDigest());
}
private boolean isDisabled() {
return !configuration.isEnabled();
}
private boolean serviceMeshIsEnabled(JobDescriptor<?> jobDescriptor) {
String enabled = jobDescriptor
.getContainer()
.getAttributes()
.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_SERVICEMESH_ENABLED);
if (enabled == null) {
return false;
}
return Boolean.parseBoolean(enabled);
}
private boolean serviceMeshIsPinned(JobDescriptor<?> jobDescriptor) {
return jobDescriptor
.getContainer()
.getAttributes()
.containsKey(JobAttributes.JOB_CONTAINER_ATTRIBUTE_SERVICEMESH_CONTAINER);
}
private Image getServiceMeshImage(JobDescriptor<?> jobDescriptor) {
String image = jobDescriptor
.getContainer()
.getAttributes()
.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_SERVICEMESH_CONTAINER);
return parseImageName(image);
}
private static Image parseImageName(String imageName) {
// Grammar
//
// reference := name [ ":" tag ] [ "@" digest ]
// name := [hostname '/'] component ['/' component]*
// hostname := hostcomponent ['.' hostcomponent]* [':' port-number]
// hostcomponent := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/
// port-number := /[0-9]+/
// component := alpha-numeric [separator alpha-numeric]*
// alpha-numeric := /[a-z0-9]+/
// separator := /[_.]|__|[-]*/
//
// tag := /[\w][\w.-]{0,127}/
//
// digest := digest-algorithm ":" digest-hex
// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]
// digest-algorithm-separator := /[+.-_]/
// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/
// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value
int digestStart = imageName.lastIndexOf("@");
if (digestStart < 0) {
int tagStart = imageName.lastIndexOf(":");
if (tagStart < 0) {
throw new IllegalArgumentException("cannot parse " + imageName + " as versioned docker image name");
}
String name = imageName.substring(0, tagStart);
String tag = imageName.substring(tagStart + 1);
return Image.newBuilder().withName(name).withTag(tag).build();
} else {
String name = imageName.substring(0, digestStart);
String digest = imageName.substring(digestStart + 1);
return Image.newBuilder().withName(name).withDigest(digest).build();
}
}
private static String toImageName(Image image) {
return String.format("%s@%s", image.getName(), image.getDigest());
}
/**
* Determines if this Exception should fail open, or produce a sanitization failure
*/
private boolean isAllowedException(Throwable throwable, Image image) {
logger.error("Exception while checking image digest: {}", throwable.getMessage());
logger.debug("Full stacktrace", throwable);
String imageName = image.getName();
String imageVersion = image.getDigest().isEmpty() ? image.getTag() : image.getDigest();
String imageResource = String.format("%s_%s", imageName, imageVersion);
// Use a more specific error tag if available
if (throwable instanceof TitusRegistryException) {
TitusRegistryException tre = (TitusRegistryException) throwable;
validatorMetrics.incrementValidationError(
imageResource,
tre.getErrorCode().name());
return tre.getErrorCode() != TitusRegistryException.ErrorCode.IMAGE_NOT_FOUND;
} else {
validatorMetrics.incrementValidationError(
imageResource,
throwable.getClass().getSimpleName());
}
return true;
}
@SuppressWarnings("unchecked")
private static JobDescriptor<?> skipSanitization(JobDescriptor<?> jobDescriptor) {
return JobFunctions.appendContainerAttribute(jobDescriptor,
JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_SERVICEMESH_IMAGE, true
);
}
}
| 336 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/AggregatingValidator.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.admission.TitusValidatorConfiguration;
import com.netflix.titus.common.model.admission.ValidatorMetrics;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
* An AggregatingValidator executes and aggregates the results of multiple {@link AdmissionValidator}s.
*/
@Singleton
public class AggregatingValidator implements AdmissionValidator<JobDescriptor> {
private final TitusValidatorConfiguration configuration;
private final Duration timeout;
private final Collection<? extends AdmissionValidator<JobDescriptor>> validators;
private final ValidatorMetrics validatorMetrics;
/**
* A AggregatingValidator ensures that all its constituent validators or sanitizers complete within a specified
* duration. Each validator specifies its error type, either "hard" or "soft". The distinction between "hard" and
* "soft" validators is behavior on timeout. When a "hard" validator
* fails to complete within the specified duration it produces a {@link ValidationError} with a
* {@link ValidationError.Type} of HARD. Conversely "soft" validators which fail to complete within the specified
* duration have a {@link ValidationError.Type} of SOFT.
*
* @param configuration The configuration of the validator.
*/
@Inject
public AggregatingValidator(
TitusValidatorConfiguration configuration,
Registry registry,
Collection<? extends AdmissionValidator<JobDescriptor>> validators) {
this.configuration = configuration;
this.timeout = Duration.ofMillis(this.configuration.getTimeoutMs());
this.validators = validators;
this.validatorMetrics = new ValidatorMetrics(this.getClass().getSimpleName(), registry);
}
/**
* Validate executes all of the hard and soft validators in parallel. Validation errors for both are
* returned and noted if the specific error was a hard or soft failure.
*/
@Override
public Mono<Set<ValidationError>> validate(JobDescriptor jobDescriptor) {
return Mono.zip(
getMonos(jobDescriptor, timeout, validators),
objects -> Arrays.stream(objects)
.map(objectSet -> (Set<ValidationError>) objectSet)
.flatMap(Set::stream)
.collect(Collectors.toSet()))
.defaultIfEmpty(Collections.emptySet());
}
@Override
public ValidationError.Type getErrorType() {
return configuration.toValidatorErrorType();
}
private Collection<Mono<Set<ValidationError>>> getMonos(
JobDescriptor jobDescriptor,
Duration timeout,
Collection<? extends AdmissionValidator<JobDescriptor>> validators) {
return validators.stream()
.map(v -> v.validate(jobDescriptor)
.subscribeOn(Schedulers.parallel())
.timeout(timeout, Mono.just(Collections.singleton(
new ValidationError(v.getClass().getSimpleName(), getTimeoutMsg(timeout), v.getErrorType())
)))
.switchIfEmpty(Mono.just(Collections.emptySet()))
.doOnSuccessOrError(this::registerMetrics))
.collect(Collectors.toList());
}
private void registerMetrics(Collection<ValidationError> validationErrors,
Throwable throwable) {
if (null == throwable) {
validationErrors.forEach(validationError -> {
validatorMetrics.incrementValidationError(
validationError.getField(),
validationError.getDescription(),
Collections.singletonMap("type", validationError.getType().name()));
});
} else {
validatorMetrics.incrementValidationError(this.getClass().getSimpleName(), throwable.getClass().getSimpleName());
}
}
public static String getTimeoutMsg(Duration timeout) {
return String.format("Timed out in %s ms", timeout.toMillis());
}
}
| 337 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionConfiguration.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.admissionSanitizer.jobRuntimePrediction")
public interface JobRuntimePredictionConfiguration {
@DefaultValue("300000")
long getMaxOpportunisticRuntimeLimitMs();
}
| 338 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobEbsVolumeValidator.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume;
import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobAssertions;
import com.netflix.titus.api.jobmanager.model.job.vpc.SignedIpAddressAllocation;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.admission.ValidatorMetrics;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.StringExt;
import reactor.core.publisher.Mono;
/**
* This {@link com.netflix.titus.common.model.admission.AdmissionValidator} validates Job EBS volumes
* have all of the appropriate volume metadata set. This metadata should be set during a prior sanitization step.
*/
public class JobEbsVolumeValidator implements AdmissionValidator<JobDescriptor> {
private static final String REASON_MISSING_FIELD = "missingField";
private final Supplier<ValidationError.Type> validationErrorTypeProvider;
private final ValidatorMetrics metrics;
public JobEbsVolumeValidator(Supplier<ValidationError.Type> validationErrorTypeProvider,
TitusRuntime titusRuntime) {
this.validationErrorTypeProvider = validationErrorTypeProvider;
this.metrics = new ValidatorMetrics(JobEbsVolumeValidator.class.getSimpleName(), titusRuntime.getRegistry());
}
@Override
public Mono<Set<ValidationError>> validate(JobDescriptor jobDescriptor) {
return Mono.fromCallable(() -> CollectionsExt.merge(
validateFieldsSet(jobDescriptor),
validateDuplicateVolumeIds(jobDescriptor),
validateMatchEbsAndIpZones(jobDescriptor)
))
.doOnNext(validationErrors -> {
if (validationErrors.isEmpty()) {
metrics.incrementValidationSuccess(JobAttributes.JOB_ATTRIBUTES_EBS_VOLUME_IDS);
}
});
}
@Override
public ValidationError.Type getErrorType() {
return validationErrorTypeProvider.get();
}
/**
* Validates that all required EBS fields are set.
*/
private Set<ValidationError> validateFieldsSet(JobDescriptor jobDescriptor) {
return jobDescriptor.getContainer().getContainerResources().getEbsVolumes().stream()
.filter(ebsVolume -> StringExt.isEmpty(ebsVolume.getVolumeAvailabilityZone()) ||
ebsVolume.getVolumeCapacityGB() == 0)
.peek(ebsVolume -> metrics.incrementValidationError(ebsVolume.getVolumeId(), REASON_MISSING_FIELD))
.map(ebsVolume -> new ValidationError(
JobAttributes.JOB_ATTRIBUTES_EBS_VOLUME_IDS,
String.format("Required field missing from EBS volume %s", ebsVolume)))
.collect(Collectors.toSet());
}
/**
* Validates that there are no duplicate volume IDs.
*/
private Set<ValidationError> validateDuplicateVolumeIds(JobDescriptor jobDescriptor) {
return jobDescriptor.getContainer().getContainerResources().getEbsVolumes().stream()
.map(EbsVolume::getVolumeId)
.distinct()
.count() == jobDescriptor.getContainer().getContainerResources().getEbsVolumes().size()
? Collections.emptySet()
: Collections.singleton(new ValidationError(
JobAttributes.JOB_ATTRIBUTES_EBS_VOLUME_IDS,
"Duplicate volume IDs exist"));
}
/**
* Validates that EBS volumes and any Static IP resources have matching AZs
*/
private Set<ValidationError> validateMatchEbsAndIpZones(JobDescriptor jobDescriptor) {
List<SignedIpAddressAllocation> signedIpAddressAllocations = jobDescriptor.getContainer().getContainerResources().getSignedIpAddressAllocations();
return signedIpAddressAllocations.isEmpty()
? Collections.emptySet()
: JobAssertions.validateMatchingEbsAndIpZones(jobDescriptor.getContainer().getContainerResources().getEbsVolumes(), signedIpAddressAllocations);
}
}
| 339 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSelection.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.util.Map;
import java.util.Objects;
import com.netflix.titus.runtime.connector.prediction.JobRuntimePrediction;
public class JobRuntimePredictionSelection {
private final JobRuntimePrediction prediction;
private final Map<String, String> metadata;
JobRuntimePredictionSelection(JobRuntimePrediction prediction, Map<String, String> metadata) {
this.prediction = prediction;
this.metadata = metadata;
}
public JobRuntimePrediction getPrediction() {
return prediction;
}
public Map<String, String> getMetadata() {
return metadata;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JobRuntimePredictionSelection that = (JobRuntimePredictionSelection) o;
return Objects.equals(prediction, that.prediction) &&
Objects.equals(metadata, that.metadata);
}
@Override
public int hashCode() {
return Objects.hash(prediction, metadata);
}
@Override
public String toString() {
return "JobRuntimePredictionSelection{" +
"prediction=" + prediction +
", metadata=" + metadata +
'}';
}
public Builder toBuilder() {
return newBuilder().withPrediction(prediction).withMetadata(metadata);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private JobRuntimePrediction prediction;
private Map<String, String> metadata;
private Builder() {
}
public Builder withPrediction(JobRuntimePrediction prediction) {
this.prediction = prediction;
return this;
}
public Builder withMetadata(Map<String, String> metadata) {
this.metadata = metadata;
return this;
}
public JobRuntimePredictionSelection build() {
return new JobRuntimePredictionSelection(prediction, metadata);
}
}
}
| 340 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/admission/JobIamValidator.java | /*
*
* * Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.admission;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.collect.ImmutableMap;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.api.connector.cloud.IamConnector;
import com.netflix.titus.api.iam.model.IamRole;
import com.netflix.titus.api.iam.service.IamConnectorException;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.api.jobmanager.model.job.Container;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.common.model.admission.AdmissionSanitizer;
import com.netflix.titus.common.model.admission.AdmissionValidator;
import com.netflix.titus.common.model.admission.ValidatorMetrics;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import com.netflix.titus.common.util.rx.ReactorExt;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
* This {@link AdmissionValidator} implementation validates and sanitizes Job IAM information.
*/
@Singleton
public class JobIamValidator implements AdmissionValidator<JobDescriptor>, AdmissionSanitizer<JobDescriptor> {
private final JobSecurityValidatorConfiguration configuration;
private final IamConnector iamConnector;
private final ValidatorMetrics validatorMetrics;
private final Registry registry;
private final Supplier<List<Duration>> iamValidationHedgeThresholdsConfig;
@Inject
public JobIamValidator(JobSecurityValidatorConfiguration configuration, IamConnector iamConnector, Registry registry) {
this.configuration = configuration;
this.iamConnector = iamConnector;
validatorMetrics = new ValidatorMetrics(this.getClass().getSimpleName(), registry);
this.registry = registry;
this.iamValidationHedgeThresholdsConfig = Archaius2Ext.asDurationList(configuration::getIamValidationHedgeThresholdsMs);
}
@Override
public Mono<Set<ValidationError>> validate(JobDescriptor jobDescriptor) {
if (isDisabled()) {
validatorMetrics.incrementValidationSkipped("disabled");
return Mono.just(Collections.emptySet());
}
String iamRoleName = jobDescriptor.getContainer().getSecurityProfile().getIamRole();
// Skip validation if no IAM was provided because a valid default will be used.
if (iamRoleName.isEmpty()) {
validatorMetrics.incrementValidationSkipped("noIamProvided");
return Mono.just(Collections.emptySet());
}
return Mono
.defer(() -> {
if (configuration.isIamRoleWithStsValidationEnabled()) {
return iamConnector.canAgentAssume(iamRoleName).transformDeferred(
ReactorExt.hedged(
iamValidationHedgeThresholdsConfig.get(),
error -> {
if (error instanceof IamConnectorException) {
IamConnectorException iamError = (IamConnectorException) error;
return iamError.isRetryable();
}
return true;
},
ImmutableMap.of(
"caller", "jobIamValidator",
"action", "iamConnector:canAgentAssume"
),
registry,
Schedulers.parallel()
)
);
}
// Skip any IAM that is not in "friendly" format. A non-friendly format is
// likely a cross-account IAM and would need cross-account access to get and validate.
if (isIamArn(iamRoleName)) {
validatorMetrics.incrementValidationSkipped(iamRoleName, "notFriendly");
return Mono.just(Collections.emptySet());
}
return iamConnector.canIamAssume(iamRoleName, configuration.getAgentIamAssumeRole());
}
)
.timeout(Duration.ofMillis(configuration.getIamValidationTimeoutMs()))
// If role is found and is assumable return an empty ValidationError set, otherwise
// populate the set with a specific error.
.thenReturn(Collections.<ValidationError>emptySet())
.doOnSuccess(result -> validatorMetrics.incrementValidationSuccess(iamRoleName))
.onErrorResume(throwable -> {
String errorReason = throwable.getClass().getSimpleName();
if (throwable instanceof IamConnectorException) {
// Use a more specific error tag if available
errorReason = ((IamConnectorException) throwable).getErrorCode().name();
}
validatorMetrics.incrementValidationError(iamRoleName, errorReason);
return Mono.just(Collections.singleton(
new ValidationError(
JobIamValidator.class.getSimpleName(),
throwable.getMessage(),
getErrorType())));
});
}
@Override
public ValidationError.Type getErrorType() {
return configuration.toValidatorErrorType();
}
/**
* @return a {@link UnaryOperator} that adds a sanitized role or job attributes when sanitization was skipped
*/
@Override
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor jobDescriptor) {
if (isDisabled()) {
return Mono.just(JobIamValidator::skipSanitization);
}
String iamRoleName = jobDescriptor.getContainer().getSecurityProfile().getIamRole();
// If empty, it should be set to ARN value or rejected, but not in this place.
if (iamRoleName.isEmpty()) {
return Mono.empty();
}
if (isIamArn(iamRoleName)) {
return Mono.empty();
}
return iamConnector.getIamRole(iamRoleName)
.timeout(Duration.ofMillis(configuration.getIamValidationTimeoutMs()))
.map(JobIamValidator::setIamRoleFunction)
.onErrorReturn(JobIamValidator::skipSanitization);
}
private static UnaryOperator<JobDescriptor> setIamRoleFunction(IamRole iamRole) {
return entity -> {
Container container = entity.getContainer();
return entity.toBuilder()
.withContainer(container.toBuilder()
.withSecurityProfile(container.getSecurityProfile().toBuilder()
.withIamRole(iamRole.getResourceName())
.build())
.build()
)
.build();
};
}
/**
* Check if this looks like an ARN
*/
private boolean isIamArn(String iamRoleName) {
return iamRoleName.startsWith("arn:aws:");
}
private boolean isDisabled() {
return !configuration.isIamValidatorEnabled();
}
@SuppressWarnings("unchecked")
private static JobDescriptor skipSanitization(JobDescriptor jobDescriptor) {
return JobFunctions.appendJobDescriptorAttribute(jobDescriptor,
JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IAM, true
);
}
}
| 341 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/EmptyLogStorageInfo.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common;
import java.util.Optional;
import javax.inject.Singleton;
import com.netflix.titus.api.jobmanager.model.job.LogStorageInfo;
@Singleton
public class EmptyLogStorageInfo<TASK> implements LogStorageInfo<TASK> {
private static final LogLinks EMPTY = new LogLinks(Optional.empty(), Optional.empty(), Optional.empty());
public static final LogStorageInfo INSTANCE = new EmptyLogStorageInfo();
@Override
public LogLinks getLinks(TASK task) {
return EMPTY;
}
@Override
public Optional<String> getTitusUiLink(TASK task) {
return Optional.empty();
}
@Override
public Optional<S3LogLocation> getS3LogLocation(TASK task, boolean onlyIfScheduled) {
return Optional.empty();
}
public static <TASK> LogStorageInfo<TASK> empty() {
return INSTANCE;
}
}
| 342 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/AbstractTitusGrpcServer.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.grpc;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.ExecutorsExt;
import com.netflix.titus.grpc.protogen.HealthGrpc;
import com.netflix.titus.runtime.endpoint.common.grpc.interceptor.ErrorCatchingServerInterceptor;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.ServerServiceDefinition;
import io.grpc.ServiceDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractTitusGrpcServer {
private static final Logger logger = LoggerFactory.getLogger(AbstractTitusGrpcServer.class);
private final GrpcEndpointConfiguration configuration;
private final ServerServiceDefinition serviceDefinition;
private final TitusRuntime runtime;
private final ExecutorService grpcCallbackExecutor;
private final AtomicBoolean started = new AtomicBoolean();
private Server server;
/**
* If the configured port is 0, the assigned ephemeral port will be set here after the server is started.
*/
private int port;
protected AbstractTitusGrpcServer(GrpcEndpointConfiguration configuration,
BindableService bindableService,
TitusRuntime runtime) {
this.configuration = configuration;
this.serviceDefinition = bindableService.bindService();
this.runtime = runtime;
this.grpcCallbackExecutor = ExecutorsExt.instrumentedCachedThreadPool(runtime.getRegistry(), "grpcCallbackExecutor");
}
protected AbstractTitusGrpcServer(GrpcEndpointConfiguration configuration,
ServerServiceDefinition serviceDefinition, TitusRuntime runtime) {
this.configuration = configuration;
this.serviceDefinition = serviceDefinition;
this.runtime = runtime;
this.grpcCallbackExecutor = ExecutorsExt.instrumentedCachedThreadPool(runtime.getRegistry(), "grpcCallbackExecutor");
}
public int getPort() {
return port;
}
@PostConstruct
public void start() {
if (started.getAndSet(true)) {
return;
}
this.server = configure(ServerBuilder.forPort(port).executor(grpcCallbackExecutor))
.addService(ServerInterceptors.intercept(
serviceDefinition,
createInterceptors(HealthGrpc.getServiceDescriptor())
))
.build();
logger.info("Starting {} on port {}.", getClass().getSimpleName(), configuration.getPort());
try {
this.server.start();
this.port = server.getPort();
} catch (final IOException e) {
throw new RuntimeException(e);
}
logger.info("Started {} on port {}.", getClass().getSimpleName(), port);
}
@PreDestroy
public void shutdown() {
if (server.isShutdown()) {
return;
}
long timeoutMs = configuration.getShutdownTimeoutMs();
try {
if (timeoutMs <= 0) {
server.shutdownNow();
} else {
server.shutdown();
try {
server.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
}
if (!server.isShutdown()) {
server.shutdownNow();
}
}
} finally {
grpcCallbackExecutor.shutdown();
if (timeoutMs > 0) {
try {
grpcCallbackExecutor.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
}
}
}
}
/**
* Override to change default server configuration.
*/
protected ServerBuilder configure(ServerBuilder serverBuilder) {
return serverBuilder;
}
/**
* Override to add server side interceptors.
*/
protected List<ServerInterceptor> createInterceptors(ServiceDescriptor serviceDescriptor) {
return Arrays.asList(new ErrorCatchingServerInterceptor(), new V3HeaderInterceptor());
}
}
| 343 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/GrpcEndpointConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.grpc;
import com.netflix.archaius.api.annotations.DefaultValue;
public interface GrpcEndpointConfiguration {
@DefaultValue("7104")
int getPort();
/**
* Graceful shutdown time for GRPC server. If zero, shutdown happens immediately, and all client connections are
* terminated abruptly.
*/
@DefaultValue("30000")
long getShutdownTimeoutMs();
/**
* Maximum amount of time a client connection may last. Connections not disconnected by client after this time
* passes, are closed by server. The clients are expected to reconnect if that happens.
*/
@DefaultValue("1800000")
long getMaxConnectionAgeMs();
}
| 344 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/grpc/interceptor/ErrorCatchingServerInterceptor.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.grpc.interceptor;
import com.netflix.titus.common.util.Evaluators;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.runtime.endpoint.v3.grpc.ErrorResponses;
import io.grpc.ForwardingServerCall;
import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCall.Listener;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.titus.common.util.Evaluators.getOrDefault;
import static com.netflix.titus.runtime.endpoint.v3.grpc.ErrorResponses.KEY_TITUS_DEBUG;
/**
* (adapted from netflix-grpc-extensions)
* <p>
* Interceptor that ensures any exception thrown by a method handler is propagated
* as a close() to all upstream {@link ServerInterceptor}s.
* Custom exceptions mapping can be provided through customMappingFunction.
*
* @deprecated Use {@link CommonErrorCatchingServerInterceptor}
*/
public final class ErrorCatchingServerInterceptor implements ServerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ErrorCatchingServerInterceptor.class);
private <ReqT, RespT> void handlingException(ServerCall<ReqT, RespT> call, Exception e, boolean debug) {
logger.info("Returning exception to the client: {}", e.getMessage(), e);
Pair<Status, Metadata> statusAndMeta = ErrorResponses.of(e, debug);
Status status = statusAndMeta.getLeft();
safeClose(() -> call.close(status, statusAndMeta.getRight()));
throw status.asRuntimeException();
}
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
boolean debug = "true".equalsIgnoreCase(getOrDefault(headers.get(KEY_TITUS_DEBUG), "false"));
Listener<ReqT> listener = null;
try {
listener = next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
@Override
public void close(Status status, Metadata trailers) {
if (status.getCode() != Status.Code.OK) {
Pair<Status, Metadata> pair = ErrorResponses.of(status, trailers, debug);
Status newStatus = pair.getLeft();
if (isCriticalError(newStatus)) {
logger.warn("Returning exception to the client: {}", formatStatus(newStatus));
} else {
logger.debug("Returning exception to the client: {}", formatStatus(newStatus));
}
Evaluators.acceptNotNull(newStatus.getCause(), error -> logger.debug("Stack trace", error));
safeClose(() -> super.close(newStatus, pair.getRight()));
}
safeClose(() -> super.close(status, trailers));
}
}, headers);
} catch (Exception e) {
handlingException(call, e, debug);
}
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(listener) {
// Clients sends one requests are handled through onHalfClose() (not onMessage)
@Override
public void onHalfClose() {
try {
super.onHalfClose();
} catch (Exception e) {
handlingException(call, e, debug);
}
}
// Streaming client requests are handled in onMessage()
@Override
public void onMessage(ReqT message) {
try {
super.onMessage(message);
} catch (Exception e) {
handlingException(call, e, debug);
}
}
};
}
private boolean isCriticalError(Status status) {
switch (status.getCode()) {
case OK:
case CANCELLED:
case INVALID_ARGUMENT:
case NOT_FOUND:
case ALREADY_EXISTS:
case PERMISSION_DENIED:
case FAILED_PRECONDITION:
case OUT_OF_RANGE:
case UNAUTHENTICATED:
return false;
case UNKNOWN:
case DEADLINE_EXCEEDED:
case RESOURCE_EXHAUSTED:
case ABORTED:
case UNIMPLEMENTED:
case INTERNAL:
case UNAVAILABLE:
case DATA_LOSS:
return true;
}
// In case we missed something
return true;
}
private String formatStatus(Status status) {
return "{code=" + status.getCode()
+ ", description=" + status.getDescription()
+ ", error=" + (status.getCause() == null ? "N/A" : status.getCause().getMessage())
+ '}';
}
private void safeClose(Runnable action) {
try {
action.run();
} catch (IllegalStateException ignore) {
// Ignore, as most likely connection is already closed
}
}
}
| 345 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/TitusExceptionHandlers.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import java.util.Collection;
import javax.servlet.http.HttpServletResponse;
import com.netflix.titus.api.eviction.service.EvictionException;
import com.netflix.titus.api.jobmanager.service.JobManagerException;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.model.sanitizer.EntitySanitizerUtil;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.runtime.endpoint.rest.ErrorResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TitusExceptionHandlers {
private static final int TOO_MANY_REQUESTS = 429;
@ExceptionHandler(value = {RestException.class})
public ResponseEntity<ErrorResponse> handleException(RestException e, WebRequest request) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(e.getStatusCode(), e.getMessage())
.clientRequest(request)
.serverContext()
.exceptionContext(e);
ErrorResponse errorResponse = errorBuilder.build();
return ResponseEntity.status(e.getStatusCode()).body(errorResponse);
}
@ExceptionHandler(value = {TitusServiceException.class})
public ResponseEntity<ErrorResponse> handleException(TitusServiceException e, WebRequest request) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage())
.clientRequest(request)
.serverContext()
.exceptionContext(e);
switch (e.getErrorCode()) {
case CELL_NOT_FOUND:
case JOB_NOT_FOUND:
case TASK_NOT_FOUND:
errorBuilder.status(HttpServletResponse.SC_NOT_FOUND);
break;
case INVALID_ARGUMENT:
case INVALID_JOB:
case INVALID_PAGE_OFFSET:
case NO_CALLER_ID:
errorBuilder.status(HttpServletResponse.SC_BAD_REQUEST);
break;
case INTERNAL:
case UNEXPECTED:
default:
errorBuilder.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
if (!CollectionsExt.isNullOrEmpty(e.getValidationErrors())) {
errorBuilder.withContext(
"constraintViolations",
EntitySanitizerUtil.toStringMap((Collection) e.getValidationErrors())
);
}
ErrorResponse errorResponse = errorBuilder.build();
return ResponseEntity.status(errorResponse.getStatusCode()).body(errorResponse);
}
@ExceptionHandler(value = {JobManagerException.class})
public ResponseEntity<ErrorResponse> handleException(JobManagerException e, WebRequest request) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage())
.clientRequest(request)
.serverContext()
.exceptionContext(e);
switch (e.getErrorCode()) {
case JobCreateLimited:
errorBuilder.status(TOO_MANY_REQUESTS);
break;
case JobNotFound:
case TaskNotFound:
errorBuilder.status(HttpServletResponse.SC_NOT_FOUND);
break;
case JobTerminating:
case TaskTerminating:
case UnexpectedJobState:
case UnexpectedTaskState:
errorBuilder.status(HttpServletResponse.SC_PRECONDITION_FAILED);
break;
case NotEnabled:
errorBuilder.status(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
break;
case InvalidContainerResources:
case InvalidDesiredCapacity:
case InvalidMaxCapacity:
case NotServiceJob:
case NotServiceJobDescriptor:
case NotBatchJob:
case NotBatchJobDescriptor:
case BelowMinCapacity:
case AboveMaxCapacity:
case TaskJobMismatch:
case SameJobIds:
errorBuilder.status(HttpServletResponse.SC_BAD_REQUEST);
break;
default:
errorBuilder.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ErrorResponse errorResponse = errorBuilder.build();
return ResponseEntity.status(errorResponse.getStatusCode()).body(errorResponse);
}
@ExceptionHandler(value = {EvictionException.class})
public ResponseEntity<ErrorResponse> handleException(EvictionException e, WebRequest request) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage())
.clientRequest(request)
.serverContext()
.exceptionContext(e);
switch (e.getErrorCode()) {
case BadConfiguration:
errorBuilder.status(HttpServletResponse.SC_BAD_REQUEST);
break;
case CapacityGroupNotFound:
case TaskNotFound:
errorBuilder.status(HttpServletResponse.SC_NOT_FOUND);
break;
case TaskNotScheduledYet:
case TaskAlreadyStopped:
case NoQuota:
errorBuilder.status(HttpServletResponse.SC_FORBIDDEN);
break;
default:
errorBuilder.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ErrorResponse errorResponse = errorBuilder.build();
return ResponseEntity.status(errorResponse.getStatusCode()).body(errorResponse);
}
}
| 346 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/TitusExceptionMapper.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import java.net.SocketException;
import java.util.Collection;
import java.util.concurrent.TimeoutException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.netflix.titus.api.eviction.service.EvictionException;
import com.netflix.titus.api.jobmanager.service.JobManagerException;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.model.sanitizer.EntitySanitizerUtil;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.runtime.endpoint.rest.ErrorResponse;
import com.sun.jersey.api.NotFoundException;
import com.sun.jersey.api.ParamException;
@Provider
public class TitusExceptionMapper implements ExceptionMapper<Throwable> {
private static final int TOO_MANY_REQUESTS = 429;
@Context
private HttpServletRequest httpServletRequest;
@Override
public Response toResponse(Throwable exception) {
if (exception instanceof SocketException) {
return fromSocketException((SocketException) exception);
}
if (exception instanceof WebApplicationException) {
return fromWebApplicationException((WebApplicationException) exception);
}
if (exception instanceof RestException) {
return fromRestException((RestException) exception);
}
if (exception instanceof JsonProcessingException) {
return fromJsonProcessingException((JsonProcessingException) exception);
}
if (exception instanceof TitusServiceException) {
return fromTitusServiceException((TitusServiceException) exception);
}
if (exception instanceof JobManagerException) {
return fromJobManagerException((JobManagerException) exception);
}
if (exception instanceof EvictionException) {
return fromEvictionException((EvictionException) exception);
}
if (exception instanceof TimeoutException) {
return fromTimeoutException((TimeoutException) exception);
}
ErrorResponse errorResponse = ErrorResponse.newError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unexpected error: " + exception.getMessage())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(exception)
.build();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorResponse).build();
}
private Response fromSocketException(SocketException e) {
int status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
Throwable cause = e.getCause() == null ? e : e.getCause();
String errorMessage = toStandardHttpErrorMessage(status, cause);
ErrorResponse errorResponse = ErrorResponse.newError(status, errorMessage)
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(cause)
.build();
return Response.status(status).entity(errorResponse).build();
}
private Response fromRestException(RestException e) {
ErrorResponse errorResponse = ErrorResponse.newError(e.getStatusCode(), e.getMessage())
.errorDetails(e.getDetails())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(e)
.build();
return Response.status(e.getStatusCode()).entity(errorResponse).build();
}
private Response fromWebApplicationException(WebApplicationException e) {
int status = e.getResponse().getStatus();
Throwable cause = e.getCause() == null ? e : e.getCause();
String errorMessage = toStandardHttpErrorMessage(status, cause);
ErrorResponse errorResponse = ErrorResponse.newError(status, errorMessage)
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(cause)
.build();
return Response.status(status).entity(errorResponse).build();
}
private String toStandardHttpErrorMessage(int status, Throwable cause) {
// Do not use message from Jersey exceptions, as we can do better
if (cause instanceof ParamException) {
ParamException pe = (ParamException) cause;
return "invalid parameter " + pe.getParameterName() + "=" + pe.getDefaultStringValue() + " of type " + pe.getParameterType();
}
if (cause instanceof NotFoundException) {
NotFoundException nfe = (NotFoundException) cause;
return "resource not found: " + nfe.getNotFoundUri();
}
if (cause.getMessage() != null) {
return cause.getMessage();
}
try {
return Status.fromStatusCode(status).getReasonPhrase();
} catch (Exception e) {
return "HTTP error " + status;
}
}
private Response fromJsonProcessingException(JsonProcessingException e) {
StringBuilder msgBuilder = new StringBuilder();
if (e.getOriginalMessage() != null) {
msgBuilder.append(e.getOriginalMessage());
} else {
msgBuilder.append("JSON processing error");
}
JsonLocation location = e.getLocation();
if (location != null) {
msgBuilder.append(" location: [line: ").append(location.getLineNr())
.append(", column: ").append(location.getColumnNr()).append(']');
}
ErrorResponse errorResponse = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, msgBuilder.toString())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(e)
.build();
return Response.status(Status.BAD_REQUEST).entity(errorResponse).build();
}
private Response fromTitusServiceException(TitusServiceException e) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(e);
switch (e.getErrorCode()) {
case CELL_NOT_FOUND:
case JOB_NOT_FOUND:
case TASK_NOT_FOUND:
errorBuilder.status(HttpServletResponse.SC_NOT_FOUND);
break;
case INVALID_ARGUMENT:
case INVALID_JOB:
case INVALID_PAGE_OFFSET:
case NO_CALLER_ID:
errorBuilder.status(HttpServletResponse.SC_BAD_REQUEST);
break;
case INTERNAL:
case UNEXPECTED:
default:
errorBuilder.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
if (!CollectionsExt.isNullOrEmpty(e.getValidationErrors())) {
errorBuilder.withContext(
"constraintViolations",
EntitySanitizerUtil.toStringMap((Collection) e.getValidationErrors())
);
}
ErrorResponse errorResponse = errorBuilder.build();
return Response.status(errorResponse.getStatusCode()).entity(errorResponse).build();
}
private Response fromJobManagerException(JobManagerException e) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(e);
switch (e.getErrorCode()) {
case JobCreateLimited:
errorBuilder.status(TOO_MANY_REQUESTS);
break;
case JobNotFound:
case TaskNotFound:
errorBuilder.status(HttpServletResponse.SC_NOT_FOUND);
break;
case JobTerminating:
case TaskTerminating:
case UnexpectedJobState:
case UnexpectedTaskState:
errorBuilder.status(HttpServletResponse.SC_PRECONDITION_FAILED);
break;
case NotEnabled:
errorBuilder.status(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
break;
case InvalidContainerResources:
case InvalidDesiredCapacity:
case InvalidMaxCapacity:
case NotServiceJob:
case NotServiceJobDescriptor:
case NotBatchJob:
case NotBatchJobDescriptor:
case BelowMinCapacity:
case AboveMaxCapacity:
case TaskJobMismatch:
case SameJobIds:
errorBuilder.status(HttpServletResponse.SC_BAD_REQUEST);
break;
default:
errorBuilder.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ErrorResponse errorResponse = errorBuilder.build();
return Response.status(errorResponse.getStatusCode()).entity(errorResponse).build();
}
private Response fromEvictionException(EvictionException e) {
ErrorResponse.ErrorResponseBuilder errorBuilder = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(e);
switch (e.getErrorCode()) {
case BadConfiguration:
errorBuilder.status(HttpServletResponse.SC_BAD_REQUEST);
break;
case CapacityGroupNotFound:
case TaskNotFound:
errorBuilder.status(HttpServletResponse.SC_NOT_FOUND);
break;
case TaskNotScheduledYet:
case TaskAlreadyStopped:
case NoQuota:
errorBuilder.status(HttpServletResponse.SC_FORBIDDEN);
break;
default:
errorBuilder.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ErrorResponse errorResponse = errorBuilder.build();
return Response.status(errorResponse.getStatusCode()).entity(errorResponse).build();
}
private Response fromTimeoutException(TimeoutException e) {
int status = HttpServletResponse.SC_GATEWAY_TIMEOUT;
Throwable cause = e.getCause() == null ? e : e.getCause();
String errorMessage = toStandardHttpErrorMessage(status, cause);
ErrorResponse errorResponse = ErrorResponse.newError(status, errorMessage)
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(cause)
.build();
return Response.status(status).entity(errorResponse).build();
}
}
| 347 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/RestException.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
/**
*
*/
public class RestException extends RuntimeException {
private final int statusCode;
private final String message;
private final Object details;
private final Throwable cause;
private RestException(int statusCode,
String message,
Object details,
Throwable cause) {
super();
this.statusCode = statusCode;
this.message = message;
this.details = details;
this.cause = cause;
}
public int getStatusCode() {
return statusCode;
}
@Override
public String getMessage() {
return message;
}
public Object getDetails() {
return details;
}
@Override
public Throwable getCause() {
return cause;
}
public static RestExceptionBuilder newBuilder(int statusCode, String message) {
return new RestExceptionBuilder(statusCode, message);
}
public static final class RestExceptionBuilder {
private int statusCode;
private String message;
private Object details;
private Throwable cause;
private RestExceptionBuilder(int statusCode, String message) {
this.statusCode = statusCode;
this.message = message;
}
public RestExceptionBuilder withDetails(Object details) {
this.details = details;
return this;
}
public RestExceptionBuilder withCause(Throwable cause) {
this.cause = cause;
return this;
}
public RestExceptionBuilder but() {
return new RestExceptionBuilder(statusCode, message).withDetails(details).withCause(cause);
}
public RestException build() {
return new RestException(statusCode, message, details, cause);
}
}
}
| 348 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/Responses.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import com.netflix.titus.api.service.TitusServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
public class Responses {
private static final Duration REST_TIMEOUT_DURATION = Duration.ofMinutes(1);
private static final long REST_TIMEOUT_DURATION_MS = REST_TIMEOUT_DURATION.toMillis();
public static <T> List<T> fromObservable(Observable<?> observable) {
try {
return (List<T>) observable.timeout(1, TimeUnit.MINUTES).toList().toBlocking().firstOrDefault(null);
} catch (Exception e) {
throw fromException(e);
}
}
public static <T> T fromMono(Mono<T> mono) {
try {
return mono.timeout(REST_TIMEOUT_DURATION).block();
} catch (Exception e) {
throw fromException(e);
}
}
public static Response fromVoidMono(Mono<Void> mono) {
try {
mono.timeout(REST_TIMEOUT_DURATION).ignoreElement().block();
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
throw fromException(e);
}
}
public static ResponseEntity<Void> fromVoidMono(Mono<Void> mono, HttpStatus status) {
try {
mono.timeout(REST_TIMEOUT_DURATION).ignoreElement().block();
return ResponseEntity.status(status).build();
} catch (Exception e) {
throw fromException(e);
}
}
public static <T> T fromSingleValueObservable(Observable<?> observable) {
List result = fromObservable(observable);
if (result.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return (T) result.get(0);
}
public static Response fromCompletable(Completable completable) {
return fromCompletable(completable, Response.Status.OK);
}
public static Response fromCompletable(Completable completable, Response.Status statusCode) {
try {
completable.await(REST_TIMEOUT_DURATION_MS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw fromException(e);
}
return Response.status(statusCode).build();
}
public static ResponseEntity<Void> fromCompletable(Completable completable, HttpStatus statusCode) {
try {
completable.await(REST_TIMEOUT_DURATION_MS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw fromException(e);
}
return ResponseEntity.status(statusCode).build();
}
private static RuntimeException fromException(Exception e) {
if (e instanceof TitusServiceException) {
return (TitusServiceException) e;
} else if (e instanceof ConstraintViolationException) {
return (ConstraintViolationException) e;
}
return RestExceptions.from(e);
}
}
| 349 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/RestExceptions.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import javax.servlet.http.HttpServletResponse;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.StatusRuntimeException;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
public class RestExceptions {
private static final int TOO_MANY_REQUESTS = 429;
public static RestException from(Throwable t) {
if (t instanceof StatusRuntimeException) {
return fromStatusRuntimeException((StatusRuntimeException) t);
} else if (t instanceof InvalidProtocolBufferException) {
return fromInvalidProtocolBufferException((InvalidProtocolBufferException) t);
}
return RestException.newBuilder(INTERNAL_SERVER_ERROR.getStatusCode(), t.getMessage())
.withCause(t)
.build();
}
public static RestException badRequest(Exception e) {
return RestException.newBuilder(BAD_REQUEST.getStatusCode(), e.getMessage())
.withCause(e)
.build();
}
private static RestException fromStatusRuntimeException(StatusRuntimeException e) {
int statusCode;
switch (e.getStatus().getCode()) {
case OK:
statusCode = HttpServletResponse.SC_OK;
break;
case INVALID_ARGUMENT:
statusCode = HttpServletResponse.SC_BAD_REQUEST;
break;
case DEADLINE_EXCEEDED:
statusCode = HttpServletResponse.SC_REQUEST_TIMEOUT;
break;
case NOT_FOUND:
statusCode = HttpServletResponse.SC_NOT_FOUND;
break;
case ALREADY_EXISTS:
statusCode = HttpServletResponse.SC_CONFLICT;
break;
case PERMISSION_DENIED:
statusCode = HttpServletResponse.SC_FORBIDDEN;
break;
case RESOURCE_EXHAUSTED:
statusCode = TOO_MANY_REQUESTS;
break;
case FAILED_PRECONDITION:
statusCode = HttpServletResponse.SC_CONFLICT;
break;
case UNIMPLEMENTED:
statusCode = HttpServletResponse.SC_NOT_IMPLEMENTED;
break;
case UNAVAILABLE:
statusCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
break;
case UNAUTHENTICATED:
statusCode = HttpServletResponse.SC_UNAUTHORIZED;
break;
default:
statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
return RestException.newBuilder(statusCode, e.getMessage())
.withCause(e)
.build();
}
private static RestException fromInvalidProtocolBufferException(InvalidProtocolBufferException e) {
return RestException.newBuilder(BAD_REQUEST.getStatusCode(), e.getMessage())
.withCause(e)
.build();
}
}
| 350 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/JsonMessageReaderWriter.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.netflix.titus.api.json.ObjectMappers;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.common.util.jackson.CommonObjectMappers;
import com.netflix.titus.runtime.endpoint.rest.ErrorResponse;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonMessageReaderWriter implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
/**
* If 'debug' parameter is included in query, include error context when printing {@link ErrorResponse}.
*/
static final String DEBUG_PARAM = "debug";
/**
* if 'fields' parameter is included in a query, only the requested field values are returned.
*/
static final String FIELDS_PARAM = "fields";
private static final ObjectMapper MAPPER = CommonObjectMappers.protobufMapper();
private static final ObjectWriter COMPACT_ERROR_WRITER = MAPPER.writer().withView(CommonObjectMappers.PublicView.class);
private static final Validator VALIDATION = Validation.buildDefaultValidatorFactory().getValidator();
@Context
/* Visible for testing */ HttpServletRequest httpServletRequest;
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
}
@Override
public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
}
@Override
public long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public Object readFrom(Class<Object> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws WebApplicationException {
Object entity;
try {
entity = MAPPER.readValue(entityStream, type);
} catch (IOException e) {
throw RestExceptions.badRequest(e);
}
Set<ConstraintViolation<Object>> constraintViolations = VALIDATION.validate(entity);
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(type.getSimpleName() +
" in request body is incomplete or contains invalid data", constraintViolations);
}
return entity;
}
@Override
public void writeTo(Object entity,
Class type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
// Unless 'debug' flag is set, do not write error context
if (entity instanceof ErrorResponse) {
String debug = httpServletRequest.getParameter(DEBUG_PARAM);
if (debug == null || debug.equalsIgnoreCase("false")) {
COMPACT_ERROR_WRITER.writeValue(entityStream, entity);
return;
}
}
List<String> fields = StringExt.splitByComma(httpServletRequest.getParameter(FIELDS_PARAM));
if (fields.isEmpty()) {
MAPPER.writeValue(entityStream, entity);
} else {
ObjectMappers.applyFieldsFilter(MAPPER, fields).writeValue(entityStream, entity);
}
}
}
| 351 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/EmbeddedJettyModule.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.governator.guice.jetty.Archaius2JettyConfig;
import com.netflix.governator.guice.jetty.JettyConfig;
import com.netflix.governator.guice.jetty.JettyModule;
public class EmbeddedJettyModule extends AbstractModule {
private final int httpPort;
public EmbeddedJettyModule(int httpPort) {
this.httpPort = httpPort;
}
@Override
protected void configure() {
install(new JettyModule());
}
@Provides
@Singleton
public JettyConfig jettyConfig(ConfigProxyFactory configProxyFactory) {
Archaius2JettyConfig config = configProxyFactory.newProxy(Archaius2JettyConfig.class);
return new JettyConfig() {
@Override
public int getPort() {
return httpPort;
}
@Override
public String getResourceBase() {
return config.getResourceBase();
}
@Override
public String getWebAppResourceBase() {
return config.getWebAppResourceBase();
}
};
}
@Override
public boolean equals(Object obj) {
return EmbeddedJettyModule.class.equals(obj.getClass());
}
@Override
public int hashCode() {
return EmbeddedJettyModule.class.hashCode();
}
}
| 352 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/RestServerConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest;
import com.netflix.archaius.api.annotations.DefaultValue;
public interface RestServerConfiguration {
/**
* Default is false
*
* @return whether or not to log verbose resource errors in the log file.
*/
@DefaultValue("false")
boolean isJaxrsErrorLoggingEnabled();
}
| 353 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/provider/InstrumentedResourceMethodDispatchAdapter.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest.provider;
import javax.inject.Inject;
import javax.ws.rs.ext.Provider;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.runtime.endpoint.common.rest.RestServerConfiguration;
import com.netflix.titus.runtime.endpoint.common.rest.metric.InstrumentedResourceMethodDispatchProvider;
import com.netflix.titus.runtime.endpoint.resolver.HostCallerIdResolver;
import com.sun.jersey.spi.container.ResourceMethodDispatchAdapter;
import com.sun.jersey.spi.container.ResourceMethodDispatchProvider;
@Provider
public class InstrumentedResourceMethodDispatchAdapter implements ResourceMethodDispatchAdapter {
private final RestServerConfiguration config;
private final Registry registry;
private final HostCallerIdResolver hostCallerIdResolver;
@Inject
public InstrumentedResourceMethodDispatchAdapter(RestServerConfiguration config, HostCallerIdResolver hostCallerIdResolver, Registry registry) {
this.config = config;
this.registry = registry;
this.hostCallerIdResolver = hostCallerIdResolver;
}
@Override
public ResourceMethodDispatchProvider adapt(ResourceMethodDispatchProvider provider) {
return new InstrumentedResourceMethodDispatchProvider(config, hostCallerIdResolver, registry, provider);
}
}
| 354 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/filter/CallerContextFilter.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest.filter;
import java.io.IOException;
import java.util.Optional;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Jersey does not expose all {@link javax.servlet.http.HttpServletRequest} data. To make it available we inject
* them in this filter into thread local variable.
*/
@Singleton
public class CallerContextFilter implements Filter {
private static final ThreadLocal<String> currentCallerAddress = new ThreadLocal<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
currentCallerAddress.set(request.getRemoteAddr());
try {
chain.doFilter(request, response);
} finally {
currentCallerAddress.set(null);
}
}
@Override
public void destroy() {
}
public static Optional<String> getCurrentCallerAddress() {
return Optional.ofNullable(currentCallerAddress.get());
}
}
| 355 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/metric/ResettableInputStreamFilter.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest.metric;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import com.google.common.io.ByteStreams;
import com.netflix.titus.runtime.endpoint.common.rest.RestServerConfiguration;
@Singleton
public class ResettableInputStreamFilter implements Filter {
private final RestServerConfiguration config;
@Inject
public ResettableInputStreamFilter(RestServerConfiguration config) {
this.config = config;
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!config.isJaxrsErrorLoggingEnabled()) {
chain.doFilter(request, response);
} else {
chain.doFilter(new ResettableStreamHttpServletRequest((HttpServletRequest) request), response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
private static class ResettableStreamHttpServletRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
private ResettableServletInputStream servletStream;
public ResettableStreamHttpServletRequest(HttpServletRequest request) {
super(request);
this.request = request;
this.servletStream = new ResettableServletInputStream();
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (servletStream.rawData == null) {
servletStream.rawData = ByteStreams.toByteArray(request.getInputStream());
servletStream.reset();
}
return servletStream;
}
@Override
public BufferedReader getReader() throws IOException {
if (servletStream.rawData == null) {
servletStream.rawData = ByteStreams.toByteArray(request.getInputStream());
servletStream.reset();
}
return new BufferedReader(new InputStreamReader(servletStream));
}
/**
* A simplified resettable input stream using a byte array
*/
private class ResettableServletInputStream extends ServletInputStream {
private byte[] rawData;
private InputStream stream;
@Override
public int read() throws IOException {
return stream.read();
}
@Override
public void reset() throws IOException {
if (rawData == null) {
throw new IOException("reset not supported");
}
stream = new ByteArrayInputStream(rawData);
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void close() throws IOException {
rawData = null;
stream.close();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
}
}
}
| 356 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/metric/InstrumentedResourceMethodDispatchProvider.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest.metric;
import java.util.Arrays;
import java.util.List;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.titus.runtime.endpoint.common.ClientInvocationMetrics;
import com.netflix.titus.runtime.endpoint.common.rest.RestServerConfiguration;
import com.netflix.titus.runtime.endpoint.resolver.HostCallerIdResolver;
import com.sun.jersey.api.model.AbstractResourceMethod;
import com.sun.jersey.spi.container.ResourceMethodDispatchProvider;
import com.sun.jersey.spi.dispatch.RequestDispatcher;
public class InstrumentedResourceMethodDispatchProvider implements ResourceMethodDispatchProvider {
private static final String METRIC_ROOT = "titus.rest.resource.";
private final RestServerConfiguration config;
private final Registry registry;
private final ResourceMethodDispatchProvider provider;
private ClientInvocationMetrics clientInvocationMetrics;
public InstrumentedResourceMethodDispatchProvider(RestServerConfiguration config,
HostCallerIdResolver hostCallerIdResolver,
Registry registry,
ResourceMethodDispatchProvider provider) {
this.config = config;
this.registry = registry;
this.provider = provider;
this.clientInvocationMetrics = new ClientInvocationMetrics(METRIC_ROOT, hostCallerIdResolver, registry);
}
@Override
public RequestDispatcher create(AbstractResourceMethod method) {
RequestDispatcher dispatcher = provider.create(method);
if (dispatcher == null) {
return null;
}
String resourceName = method.getDeclaringResource().getResourceClass().getSimpleName();
String methodName = method.getMethod().getName();
List<Tag> tags = Arrays.asList(new BasicTag("resource", resourceName), new BasicTag("method", methodName));
return new InstrumentedRequestDispatcher(dispatcher, config, clientInvocationMetrics, tags, registry);
}
}
| 357 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/common/rest/metric/InstrumentedRequestDispatcher.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.common.rest.metric;
import java.util.List;
import java.util.stream.Collectors;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.titus.runtime.endpoint.common.ClientInvocationMetrics;
import com.netflix.titus.runtime.endpoint.common.rest.RestServerConfiguration;
import com.netflix.titus.runtime.endpoint.common.rest.filter.CallerContextFilter;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.core.HttpRequestContext;
import com.sun.jersey.api.core.HttpResponseContext;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.dispatch.RequestDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InstrumentedRequestDispatcher implements RequestDispatcher {
private static final Logger logger = LoggerFactory.getLogger(InstrumentedRequestDispatcher.class);
private final RequestDispatcher underlying;
private final RestServerConfiguration config;
private final ClientInvocationMetrics clientInvocationMetrics;
private final List<Tag> tags;
private final Registry registry;
public InstrumentedRequestDispatcher(RequestDispatcher underlying,
RestServerConfiguration config,
ClientInvocationMetrics clientInvocationMetrics,
List<Tag> tags,
Registry registry) {
this.underlying = underlying;
this.config = config;
this.clientInvocationMetrics = clientInvocationMetrics;
this.tags = tags;
this.registry = registry;
}
@Override
public void dispatch(Object resource, HttpContext httpContext) {
final long start = registry.clock().wallTime();
String callerId = CallerContextFilter.getCurrentCallerAddress().orElse("UNKNOWN");
try {
underlying.dispatch(resource, httpContext);
clientInvocationMetrics.registerSuccess(callerId, tags, registry.clock().wallTime() - start);
} catch (Exception e) {
clientInvocationMetrics.registerFailure(callerId, tags, registry.clock().wallTime() - start);
if (config.isJaxrsErrorLoggingEnabled()) {
logger.error(generateRequestResponseErrorMessage(httpContext, e));
}
throw e;
}
}
private String generateRequestResponseErrorMessage(HttpContext context, Exception e) {
StringBuilder result = new StringBuilder();
HttpRequestContext request = context.getRequest();
HttpResponseContext response = context.getResponse();
result.append("An error occurred during an HTTP request:\r\n");
if (request != null) {
String bodyLengthString = request.getHeaderValue("Content-Length");
result.append("Request Path: " + request.getMethod().toUpperCase() + " " + request.getRequestUri().toString() + "\r\n");
result.append("Request Content-Length: " + bodyLengthString + "\r\n");
result.append("Request Headers:\r\n" + request.getRequestHeaders()
.entrySet()
.stream()
.map(entry -> "\t" + entry.getKey() + ": " + entry.getValue() + "\r\n")
.collect(Collectors.joining())
);
long bodyLength = Strings.isNullOrEmpty(bodyLengthString) ? 0 : Long.parseLong(bodyLengthString);
if (bodyLength > 0 && ((ContainerRequest) request).getEntityInputStream().markSupported()) {
try {
((ContainerRequest) request).getEntityInputStream().reset();
result.append("Request Body:\r\n" + request.getEntity(String.class) + "\r\n");
} catch (Exception ignore) {
}
}
}
result.append("Error response http code: " + response.getStatus() + "\r\n");
result.append("Error message: " + e.getMessage() + "\r\n");
result.append("Error stack trace :\r\n" + Throwables.getStackTraceAsString(e) + "\r\n");
return result.toString();
}
} | 358 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/DefaultJobManagementServiceGrpc.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.protobuf.Empty;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobChangeNotification;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.ObserveJobsQuery;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskId;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.jobmanager.gateway.JobServiceGateway;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Subscription;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.attachCancellingCallback;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.checkPageIsValid;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.logPageNumberUsage;
@Singleton
public class DefaultJobManagementServiceGrpc extends JobManagementServiceGrpc.JobManagementServiceImplBase {
private static final Logger logger = LoggerFactory.getLogger(DefaultJobManagementServiceGrpc.class);
private final JobServiceGateway jobServiceGateway;
private final SystemLogService systemLog;
private final CallMetadataResolver callMetadataResolver;
private final TitusRuntime titusRuntime;
@Inject
public DefaultJobManagementServiceGrpc(JobServiceGateway jobServiceGateway,
SystemLogService systemLog,
CallMetadataResolver callMetadataResolver,
TitusRuntime titusRuntime) {
this.jobServiceGateway = jobServiceGateway;
this.systemLog = systemLog;
this.callMetadataResolver = callMetadataResolver;
this.titusRuntime = titusRuntime;
}
@Override
public void createJob(JobDescriptor request, StreamObserver<JobId> responseObserver) {
Subscription subscription = jobServiceGateway.createJob(request, resolveCallMetadata()).subscribe(
jobId -> responseObserver.onNext(JobId.newBuilder().setId(jobId).build()),
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void updateJobCapacity(JobCapacityUpdate request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.updateJobCapacity(request, resolveCallMetadata()), responseObserver);
}
@Override
public void updateJobCapacityWithOptionalAttributes(JobCapacityUpdateWithOptionalAttributes request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.updateJobCapacityWithOptionalAttributes(request, resolveCallMetadata()), responseObserver);
}
@Override
public void updateJobProcesses(JobProcessesUpdate request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.updateJobProcesses(request, resolveCallMetadata()), responseObserver);
}
@Override
public void findJobs(JobQuery jobQuery, StreamObserver<JobQueryResult> responseObserver) {
if (!checkPageIsValid(jobQuery.getPage(), responseObserver)) {
return;
}
CallMetadata callMetadata = resolveCallMetadata();
logPageNumberUsage(systemLog, callMetadata, getClass().getSimpleName(), "findJobs", jobQuery.getPage());
Subscription subscription = jobServiceGateway.findJobs(jobQuery, callMetadata).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void findJob(JobId request, StreamObserver<Job> responseObserver) {
Subscription subscription = jobServiceGateway.findJob(request.getId(), resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void updateJobStatus(JobStatusUpdate request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.updateJobStatus(request, resolveCallMetadata()), responseObserver);
}
@Override
public void updateJobDisruptionBudget(JobDisruptionBudgetUpdate request, StreamObserver<Empty> responseObserver) {
streamMonoResponse(jobServiceGateway.updateJobDisruptionBudget(request, resolveCallMetadata()), responseObserver);
}
@Override
public void updateJobAttributes(JobAttributesUpdate request, StreamObserver<Empty> responseObserver) {
streamMonoResponse(jobServiceGateway.updateJobAttributes(request, resolveCallMetadata()), responseObserver);
}
@Override
public void deleteJobAttributes(JobAttributesDeleteRequest request, StreamObserver<Empty> responseObserver) {
streamMonoResponse(jobServiceGateway.deleteJobAttributes(request, resolveCallMetadata()), responseObserver);
}
@Override
public void observeJobs(ObserveJobsQuery request, StreamObserver<JobChangeNotification> responseObserver) {
Subscription subscription = jobServiceGateway.observeJobs(request, resolveCallMetadata()).subscribe(
value -> responseObserver.onNext(
value.toBuilder().setTimestamp(titusRuntime.getClock().wallTime()).build()
),
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void observeJob(JobId request, StreamObserver<JobChangeNotification> responseObserver) {
Subscription subscription = jobServiceGateway.observeJob(request.getId(), resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void killJob(JobId request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.killJob(request.getId(), resolveCallMetadata()), responseObserver);
}
@Override
public void findTask(TaskId request, StreamObserver<Task> responseObserver) {
Subscription subscription = jobServiceGateway.findTask(request.getId(), resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void findTasks(TaskQuery request, StreamObserver<TaskQueryResult> responseObserver) {
if (!checkPageIsValid(request.getPage(), responseObserver)) {
return;
}
CallMetadata callMetadata = resolveCallMetadata();
logPageNumberUsage(systemLog, callMetadata, getClass().getSimpleName(), "findTasks", request.getPage());
Subscription subscription = jobServiceGateway.findTasks(request, callMetadata).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void killTask(TaskKillRequest request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.killTask(request, resolveCallMetadata()), responseObserver);
}
@Override
public void updateTaskAttributes(TaskAttributesUpdate request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.updateTaskAttributes(request, resolveCallMetadata()), responseObserver);
}
@Override
public void deleteTaskAttributes(TaskAttributesDeleteRequest request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.deleteTaskAttributes(request, resolveCallMetadata()), responseObserver);
}
@Override
public void moveTask(TaskMoveRequest request, StreamObserver<Empty> responseObserver) {
streamCompletableResponse(jobServiceGateway.moveTask(request, resolveCallMetadata()), responseObserver);
}
private static void streamCompletableResponse(Completable completable, StreamObserver<Empty> responseObserver) {
Subscription subscription = completable.subscribe(
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
},
e -> safeOnError(logger, e, responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}
private static void streamMonoResponse(Mono<Void> completable, StreamObserver<Empty> responseObserver) {
Disposable subscription = completable.subscribe(
next -> {
},
e -> safeOnError(logger, e, responseObserver),
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
}
);
attachCancellingCallback(responseObserver, subscription);
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 359 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/ErrorResponses.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc;
import java.net.SocketException;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import com.google.protobuf.Any;
import com.google.rpc.BadRequest;
import com.google.rpc.DebugInfo;
import com.netflix.titus.api.eviction.service.EvictionException;
import com.netflix.titus.api.jobmanager.service.JobManagerException;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.util.tuple.Pair;
import io.grpc.Metadata;
import io.grpc.Status;
import rx.exceptions.CompositeException;
import static java.util.Arrays.stream;
/**
* GRPC layer errors.
*/
public final class ErrorResponses {
public static final String X_TITUS_DEBUG = "X-Titus-Debug";
public static final String X_TITUS_ERROR = "X-Titus-Error";
public static final String X_TITUS_ERROR_BIN = "X-Titus-Error-bin";
public static final Metadata.Key<String> KEY_TITUS_DEBUG = Metadata.Key.of(X_TITUS_DEBUG, Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> KEY_TITUS_ERROR_REPORT = Metadata.Key.of(X_TITUS_ERROR, Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<byte[]> KEY_TITUS_ERROR_REPORT_BIN = Metadata.Key.of(X_TITUS_ERROR_BIN, Metadata.BINARY_BYTE_MARSHALLER);
private ErrorResponses() {
}
public static Pair<Status, Metadata> of(Throwable t, boolean debug) {
Throwable exception = unwrap(t);
Status status = toGrpcStatus(exception)
.withDescription(getNonNullMessage(exception))
.withCause(exception);
int errorCode = status.getCode().value();
Metadata metadata = buildMetadata(exception, errorCode, debug);
return Pair.of(status, metadata);
}
public static Pair<Status, Metadata> of(Status status, Metadata trailers, boolean debug) {
Throwable cause = unwrap(status.getCause());
if (cause == null) {
return Pair.of(status, trailers);
}
Status newStatus = toGrpcStatus(cause)
.withDescription(getNonNullMessage(cause))
.withCause(cause);
Metadata metadata = buildMetadata(newStatus.getCause(), newStatus.getCode().value(), debug);
metadata.merge(trailers);
return Pair.of(newStatus, metadata);
}
private static Metadata buildMetadata(Throwable exception, int errorCode, boolean debug) {
Metadata metadata = new Metadata();
metadata.put(KEY_TITUS_ERROR_REPORT, getNonNullMessage(exception));
if (debug) {
metadata.put(KEY_TITUS_ERROR_REPORT_BIN, buildRpcStatus(exception, errorCode).toByteArray());
}
return metadata;
}
private static com.google.rpc.Status buildRpcStatus(Throwable exception, int errorCode) {
com.google.rpc.Status.Builder builder = com.google.rpc.Status.newBuilder()
.setCode(errorCode)
.setMessage(getNonNullMessage(exception));
DebugInfo debugInfo = DebugInfo.newBuilder()
.addAllStackEntries(stream(exception.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.toList()))
.build();
builder.addDetails(Any.pack(debugInfo));
if (exception instanceof TitusServiceException) {
TitusServiceException e = (TitusServiceException) exception;
if (!e.getValidationErrors().isEmpty()) {
BadRequest.Builder rbuilder = BadRequest.newBuilder();
e.getValidationErrors().forEach(v -> {
BadRequest.FieldViolation.Builder fbuilder = BadRequest.FieldViolation.newBuilder();
fbuilder.setField(v.getField());
fbuilder.setDescription(v.getDescription());
rbuilder.addFieldViolations(fbuilder.build());
});
builder.addDetails(Any.pack(rbuilder.build()));
}
}
return builder.build();
}
private static Status toGrpcStatus(Throwable original) {
Throwable cause = unwrap(original);
if (cause instanceof SocketException) {
return Status.UNAVAILABLE;
} else if (cause instanceof TimeoutException) {
return Status.DEADLINE_EXCEEDED;
} else if (cause instanceof TitusServiceException) {
TitusServiceException e = (TitusServiceException) cause;
switch (e.getErrorCode()) {
case CELL_NOT_FOUND:
case JOB_NOT_FOUND:
case TASK_NOT_FOUND:
return Status.NOT_FOUND;
case INVALID_ARGUMENT:
case NO_CALLER_ID:
case INVALID_JOB:
case INVALID_PAGE_OFFSET:
return Status.INVALID_ARGUMENT;
case INTERNAL:
case UNEXPECTED:
default:
return Status.INTERNAL;
}
} else if (cause instanceof JobManagerException) {
JobManagerException e = (JobManagerException) cause;
switch (e.getErrorCode()) {
case JobNotFound:
case TaskNotFound:
return Status.NOT_FOUND;
case JobTerminating:
case TaskTerminating:
case UnexpectedJobState:
case UnexpectedTaskState:
case TerminateAndShrinkNotAllowed:
return Status.FAILED_PRECONDITION;
case NotEnabled:
return Status.PERMISSION_DENIED;
case JobCreateLimited:
return Status.RESOURCE_EXHAUSTED;
case InvalidContainerResources:
case InvalidDesiredCapacity:
case InvalidMaxCapacity:
case InvalidSequenceId:
case NotServiceJob:
case NotServiceJobDescriptor:
case NotBatchJob:
case NotBatchJobDescriptor:
case BelowMinCapacity:
case AboveMaxCapacity:
case TaskJobMismatch:
case SameJobIds:
return Status.INVALID_ARGUMENT;
}
} else if (cause instanceof EvictionException) {
EvictionException e = (EvictionException) cause;
switch (e.getErrorCode()) {
case BadConfiguration:
return Status.INVALID_ARGUMENT;
case CapacityGroupNotFound:
case TaskNotFound:
return Status.NOT_FOUND;
case TaskNotScheduledYet:
case TaskAlreadyStopped:
case NoQuota:
return Status.FAILED_PRECONDITION;
case Unknown:
return Status.INTERNAL;
}
}
return Status.INTERNAL;
}
private static String getNonNullMessage(Throwable t) {
Throwable e = unwrap(t);
return e.getMessage() == null
? e.getClass().getSimpleName() + " (no message)"
: e.getClass().getSimpleName() + ": " + e.getMessage();
}
private static Throwable unwrap(Throwable throwable) {
if (throwable instanceof CompositeException) {
CompositeException composite = (CompositeException) throwable;
if (composite.getExceptions().size() == 1) {
return composite.getExceptions().get(0);
}
}
return throwable;
}
}
| 360 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/DefaultJobActivityHistoryServiceGrpc.java | package com.netflix.titus.runtime.endpoint.v3.grpc;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.grpc.protogen.ActivityQueryResult;
import com.netflix.titus.grpc.protogen.JobActivityHistoryServiceGrpc;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.service.JobActivityHistoryService;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
import javax.inject.Inject;
import javax.inject.Singleton;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.attachCancellingCallback;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError;
@Singleton
public class DefaultJobActivityHistoryServiceGrpc extends JobActivityHistoryServiceGrpc.JobActivityHistoryServiceImplBase {
private static final Logger logger = LoggerFactory.getLogger(DefaultJobActivityHistoryServiceGrpc.class);
private final JobActivityHistoryService jobActivityHistoryService;
private final CallMetadataResolver callMetadataResolver;
@Inject
public DefaultJobActivityHistoryServiceGrpc(JobActivityHistoryService jobActivityHistoryService,
CallMetadataResolver callMetadataResolver) {
this.jobActivityHistoryService = jobActivityHistoryService;
this.callMetadataResolver = callMetadataResolver;
}
@Override
public void viewScalingActivities(JobId request, StreamObserver<ActivityQueryResult> responseObserver) {
logger.debug("Received view scaling activity request {}", request);
Subscription subscription = jobActivityHistoryService.viewScalingActivities(request, resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 361 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/DefaultLoadBalancerServiceGrpc.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.protobuf.Empty;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.service.LoadBalancerService;
import com.netflix.titus.grpc.protogen.AddLoadBalancerRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc;
import com.netflix.titus.grpc.protogen.RemoveLoadBalancerRequest;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.attachCancellingCallback;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.logPageNumberUsage;
@Singleton
public class DefaultLoadBalancerServiceGrpc extends LoadBalancerServiceGrpc.LoadBalancerServiceImplBase {
private static Logger logger = LoggerFactory.getLogger(DefaultLoadBalancerServiceGrpc.class);
private final LoadBalancerService loadBalancerService;
private final SystemLogService systemLog;
private final CallMetadataResolver callMetadataResolver;
@Inject
public DefaultLoadBalancerServiceGrpc(LoadBalancerService loadBalancerService,
SystemLogService systemLog,
CallMetadataResolver callMetadataResolver) {
this.loadBalancerService = loadBalancerService;
this.systemLog = systemLog;
this.callMetadataResolver = callMetadataResolver;
}
@Override
public void getJobLoadBalancers(JobId request, StreamObserver<GetJobLoadBalancersResult> responseObserver) {
logger.debug("Received get load balancer request {}", request);
Subscription subscription = loadBalancerService.getLoadBalancers(request, resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void getAllLoadBalancers(com.netflix.titus.grpc.protogen.GetAllLoadBalancersRequest request,
StreamObserver<GetAllLoadBalancersResult> responseObserver) {
logger.debug("Received get all load balancer request {}", request);
CallMetadata callMetadata = resolveCallMetadata();
logPageNumberUsage(systemLog, callMetadata, getClass().getSimpleName(), "getAllLoadBalancers", request.getPage());
Subscription subscription = loadBalancerService.getAllLoadBalancers(request, callMetadata).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void addLoadBalancer(AddLoadBalancerRequest request, StreamObserver<Empty> responseObserver) {
logger.debug("Received add load balancer request {}", request);
Subscription subscription = loadBalancerService.addLoadBalancer(request, resolveCallMetadata()).subscribe(
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
},
e -> safeOnError(logger, e, responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void removeLoadBalancer(RemoveLoadBalancerRequest request, StreamObserver<Empty> responseObserver) {
logger.debug("Received remove load balancer request {}", request);
Subscription subscription = loadBalancerService.removeLoadBalancer(request, resolveCallMetadata()).subscribe(
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
},
e -> safeOnError(logger, e, responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 362 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/TitusPaginationUtils.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc;
import java.util.Collections;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.runtime.SystemLogEvent;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Page;
import io.grpc.stub.StreamObserver;
/**
* Helper method for APIs using pagination.
*/
public class TitusPaginationUtils {
public static boolean checkPageIsValid(Page page, StreamObserver<?> responseObserver) {
if (page == null) {
responseObserver.onError(TitusServiceException.invalidArgument("Page not defined for the query"));
return false;
}
if (page.getPageSize() <= 0) {
responseObserver.onError(TitusServiceException.invalidArgument("Page size must be > 0 (is " + page.getPageSize() + ')'));
return false;
}
if (page.getPageNumber() < 0) {
responseObserver.onError(TitusServiceException.invalidArgument("Page number must be >= 0 (is " + page.getPageNumber() + ')'));
return false;
}
return true;
}
public static void logPageNumberUsage(SystemLogService systemLog,
CallMetadata callMetadata,
String component,
String apiName,
Page page) {
if (page.getPageNumber() == 0 || StringExt.isNotEmpty(page.getCursor())) {
return;
}
ImmutableMap.Builder<String, String> contextBuilder = new ImmutableMap.Builder<>();
contextBuilder.put("apiName", apiName);
contextBuilder
.put("callPath", String.join(",", callMetadata.getCallPath()))
.put("callerId", callMetadata.getCallerId())
.put("reason", callMetadata.getCallReason());
systemLog.submit(SystemLogEvent.newBuilder()
.withCategory(SystemLogEvent.Category.Other)
.withComponent(component)
.withPriority(SystemLogEvent.Priority.Info)
.withTags(Collections.singleton("pageNumberUsage"))
.withContext(contextBuilder.build())
.withMessage("API called with a pageNumber")
.build()
);
}
}
| 363 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/DefaultAutoScalingServiceGrpc.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.protobuf.Empty;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc;
import com.netflix.titus.grpc.protogen.GetPolicyResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.UpdatePolicyRequest;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.service.AutoScalingService;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.attachCancellingCallback;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError;
@Singleton
public class DefaultAutoScalingServiceGrpc extends AutoScalingServiceGrpc.AutoScalingServiceImplBase {
private static final Logger logger = LoggerFactory.getLogger(DefaultAutoScalingServiceGrpc.class);
private final AutoScalingService autoScalingService;
private final CallMetadataResolver callMetadataResolver;
@Inject
public DefaultAutoScalingServiceGrpc(AutoScalingService autoScalingService,
CallMetadataResolver callMetadataResolver) {
this.autoScalingService = autoScalingService;
this.callMetadataResolver = callMetadataResolver;
}
@Override
public void getAllScalingPolicies(com.google.protobuf.Empty request,
io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.GetPolicyResult> responseObserver) {
Subscription subscription = autoScalingService.getAllScalingPolicies(resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void getScalingPolicy(com.netflix.titus.grpc.protogen.ScalingPolicyID request,
io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.GetPolicyResult> responseObserver) {
Subscription subscription = autoScalingService.getScalingPolicy(request, resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void getJobScalingPolicies(JobId request, StreamObserver<GetPolicyResult> responseObserver) {
Subscription subscription = autoScalingService.getJobScalingPolicies(request, resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void setAutoScalingPolicy(com.netflix.titus.grpc.protogen.PutPolicyRequest request,
io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.ScalingPolicyID> responseObserver) {
Subscription subscription = autoScalingService.setAutoScalingPolicy(request, resolveCallMetadata()).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void deleteAutoScalingPolicy(com.netflix.titus.grpc.protogen.DeletePolicyRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
Subscription subscription = autoScalingService.deleteAutoScalingPolicy(request, resolveCallMetadata()).subscribe(
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
},
e -> safeOnError(logger, e, responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void updateAutoScalingPolicy(UpdatePolicyRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
Subscription subscription = autoScalingService.updateAutoScalingPolicy(request, resolveCallMetadata()).subscribe(
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
},
e -> safeOnError(logger, e, responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 364 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/DefaultHealthServiceGrpc.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.titus.grpc.protogen.HealthCheckRequest;
import com.netflix.titus.grpc.protogen.HealthCheckResponse;
import com.netflix.titus.grpc.protogen.HealthGrpc;
import com.netflix.titus.runtime.service.HealthService;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.attachCancellingCallback;
import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError;
@Singleton
public class DefaultHealthServiceGrpc extends HealthGrpc.HealthImplBase {
private static final Logger logger = LoggerFactory.getLogger(DefaultHealthServiceGrpc.class);
private final HealthService healthService;
@Inject
public DefaultHealthServiceGrpc(HealthService healthService) {
this.healthService = healthService;
}
@Override
public void check(HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver) {
Subscription subscription = healthService.check(request).subscribe(
responseObserver::onNext,
e -> safeOnError(logger, e, responseObserver),
responseObserver::onCompleted
);
attachCancellingCallback(responseObserver, subscription);
}
}
| 365 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/query/V3JobQueryCriteriaEvaluator.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.ServiceJobTask;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.grpc.protogen.JobDescriptor.JobSpecCase;
import com.netflix.titus.grpc.protogen.TaskStatus;
import com.netflix.titus.runtime.endpoint.JobQueryCriteria;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters;
/**
*/
public class V3JobQueryCriteriaEvaluator extends V3AbstractQueryCriteriaEvaluator<List<Task>> {
public V3JobQueryCriteriaEvaluator(JobQueryCriteria<TaskStatus.TaskState, JobSpecCase> criteria, TitusRuntime titusRuntime) {
super(createTaskPredicates(criteria, titusRuntime), criteria);
}
private static List<Predicate<Pair<Job<?>, List<Task>>>> createTaskPredicates(JobQueryCriteria<TaskStatus.TaskState, JobSpecCase> criteria, TitusRuntime titusRuntime) {
List<Predicate<Pair<Job<?>, List<Task>>>> predicates = new ArrayList<>();
applyTaskIds(criteria.getTaskIds()).ifPresent(predicates::add);
applyTaskStates(criteria.getTaskStates()).ifPresent(predicates::add);
applyTaskStateReasons(criteria.getTaskStateReasons());
applyNeedsMigration(criteria.isNeedsMigration(), titusRuntime).ifPresent(predicates::add);
return predicates;
}
private static Optional<Predicate<Pair<Job<?>, List<Task>>>> applyTaskIds(Set<String> taskIds) {
if (taskIds.isEmpty()) {
return Optional.empty();
}
return Optional.of(jobAndTasks -> {
List<Task> tasks = jobAndTasks.getRight();
return tasks.stream().anyMatch(t -> taskIds.contains(t.getId()));
});
}
private static Optional<Predicate<Pair<Job<?>, List<Task>>>> applyTaskStates(Set<TaskStatus.TaskState> taskStates) {
if (taskStates.isEmpty()) {
return Optional.empty();
}
Set<TaskState> coreTaskStates = taskStates.stream().map(GrpcJobManagementModelConverters::toCoreTaskState).collect(Collectors.toSet());
return Optional.of(jobAndTasks -> {
List<Task> tasks = jobAndTasks.getRight();
return tasks.stream().anyMatch(t -> coreTaskStates.contains(t.getStatus().getState()));
});
}
private static Optional<Predicate<Pair<Job<?>, List<Task>>>> applyTaskStateReasons(Set<String> taskStateReasons) {
if (taskStateReasons.isEmpty()) {
return Optional.empty();
}
return Optional.of(jobAndTasks -> {
List<Task> tasks = jobAndTasks.getRight();
return tasks.stream().anyMatch(t -> taskStateReasons.contains(t.getStatus().getReasonCode()));
});
}
private static Optional<Predicate<Pair<Job<?>, List<Task>>>> applyNeedsMigration(boolean needsMigration, TitusRuntime titusRuntime) {
if (!needsMigration) {
return Optional.empty();
}
return Optional.of(jobAndTasks -> jobAndTasks.getRight().stream().anyMatch(t -> {
if (!JobFunctions.isServiceTask(t)) {
return false;
}
ServiceJobTask serviceTask = (ServiceJobTask) t;
titusRuntime.getCodeInvariants().notNull(serviceTask.getMigrationDetails(), "MigrationDetails is null in task: %s", t.getId());
return serviceTask.getMigrationDetails() != null && serviceTask.getMigrationDetails().isNeedsMigration();
}));
}
}
| 366 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/query/V3AbstractQueryCriteriaEvaluator.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobGroupInfo;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.PlatformSidecar;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobStatus;
import com.netflix.titus.grpc.protogen.TaskStatus;
import com.netflix.titus.runtime.endpoint.JobQueryCriteria;
import com.netflix.titus.runtime.endpoint.common.QueryUtils;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters;
public abstract class V3AbstractQueryCriteriaEvaluator<TASK_OR_SET> implements Predicate<Pair<Job<?>, TASK_OR_SET>> {
private final Predicate<Pair<Job<?>, TASK_OR_SET>> queryPredicate;
protected V3AbstractQueryCriteriaEvaluator(List<Predicate<Pair<Job<?>, TASK_OR_SET>>> taskPredicates,
JobQueryCriteria<TaskStatus.TaskState, JobDescriptor.JobSpecCase> criteria) {
List<Predicate<Pair<Job<?>, TASK_OR_SET>>> predicates = createJobPredicates(criteria);
predicates.addAll(taskPredicates);
this.queryPredicate = matchAll(predicates);
}
@Override
public boolean test(Pair<Job<?>, TASK_OR_SET> jobListPair) {
return queryPredicate.test(jobListPair);
}
private List<Predicate<Pair<Job<?>, TASK_OR_SET>>> createJobPredicates(JobQueryCriteria<TaskStatus.TaskState, JobDescriptor.JobSpecCase> criteria) {
List<Predicate<Pair<Job<?>, TASK_OR_SET>>> predicates = new ArrayList<>();
applyJobIds(criteria.getJobIds()).ifPresent(predicates::add);
applyJobType(criteria.getJobType()).ifPresent(predicates::add);
applyJobState(criteria.getJobState()).ifPresent(predicates::add);
applyOwner(criteria.getOwner()).ifPresent(predicates::add);
applyApplicationName(criteria.getAppName()).ifPresent(predicates::add);
applyCapacityGroup(criteria.getCapacityGroup()).ifPresent(predicates::add);
applyJobGroupStack(criteria.getJobGroupStack()).ifPresent(predicates::add);
applyJobGroupDetail(criteria.getJobGroupDetail()).ifPresent(predicates::add);
applyJobGroupSequence(criteria.getJobGroupSequence()).ifPresent(predicates::add);
applyImageName(criteria.getImageName()).ifPresent(predicates::add);
applyImageTag(criteria.getImageTag()).ifPresent(predicates::add);
applyPlatformSidecar(criteria.getPlatformSidecar()).ifPresent(predicates::add);
applyPlatformSidecarChannel(criteria.getPlatformSidecarChannel()).ifPresent(predicates::add);
applyJobDescriptorAttributes(criteria.getLabels(), criteria.isLabelsAndOp()).ifPresent(predicates::add);
return predicates;
}
private Predicate<Pair<Job<?>, TASK_OR_SET>> matchAll(List<Predicate<Pair<Job<?>, TASK_OR_SET>>> predicates) {
return jobAndTasks -> {
for (Predicate<Pair<Job<?>, TASK_OR_SET>> predicate : predicates) {
if (!predicate.test(jobAndTasks)) {
return false;
}
}
return true;
};
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobType(Optional<JobDescriptor.JobSpecCase> jobTypeOpt) {
return jobTypeOpt.map(jobType ->
jobTaskPair -> {
boolean isBatchJob = jobTaskPair.getLeft().getJobDescriptor().getExtensions() instanceof BatchJobExt;
return (isBatchJob && jobType.equals(JobDescriptor.JobSpecCase.BATCH)) || (!isBatchJob && jobType.equals(JobDescriptor.JobSpecCase.SERVICE));
}
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobIds(Set<String> jobIds) {
return jobIds.isEmpty() ? Optional.empty() : Optional.of(jobAndTasks -> jobIds.contains(jobAndTasks.getLeft().getId()));
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobState(Optional<Object> jobStateOpt) {
return jobStateOpt.map(jobStateObj -> {
JobState jobState = GrpcJobManagementModelConverters.toCoreJobState((JobStatus.JobState) jobStateObj);
return jobTaskPair -> jobTaskPair.getLeft().getStatus().getState().equals(jobState);
});
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyOwner(Optional<String> ownerOpt) {
return ownerOpt.map(owner ->
jobTaskPair -> jobTaskPair.getLeft().getJobDescriptor().getOwner().getTeamEmail().equals(owner)
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyApplicationName(Optional<String> appNameOpt) {
return appNameOpt.map(appName ->
jobTaskPair -> {
String currentAppName = jobTaskPair.getLeft().getJobDescriptor().getApplicationName();
return currentAppName != null && currentAppName.equals(appName);
}
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyCapacityGroup(Optional<String> capacityGroupOpt) {
return capacityGroupOpt.map(capacityGroup ->
jobTaskPair -> {
String currentCapacityGroup = jobTaskPair.getLeft().getJobDescriptor().getCapacityGroup();
return currentCapacityGroup != null && currentCapacityGroup.equals(capacityGroup);
}
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobGroupStack(Optional<String> jobGroupStack) {
return apply(jobGroupStack, job -> {
JobGroupInfo jobGroupInfo = job.getJobDescriptor().getJobGroupInfo();
return jobGroupInfo == null ? null : jobGroupInfo.getStack();
});
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobGroupDetail(Optional<String> jobGroupDetail) {
return apply(jobGroupDetail, job -> {
JobGroupInfo jobGroupInfo = job.getJobDescriptor().getJobGroupInfo();
return jobGroupInfo == null ? null : jobGroupInfo.getDetail();
});
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobGroupSequence(Optional<String> jobGroupSequence) {
return apply(jobGroupSequence, job -> {
JobGroupInfo jobGroupInfo = job.getJobDescriptor().getJobGroupInfo();
return jobGroupInfo == null ? null : jobGroupInfo.getSequence();
});
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyImageName(Optional<String> imageName) {
return apply(imageName, job -> job.getJobDescriptor().getContainer().getImage().getName());
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyImageTag(Optional<String> imageTag) {
return apply(imageTag, job -> job.getJobDescriptor().getContainer().getImage().getTag());
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyPlatformSidecar(Optional<String> platformSidecarNameOpt) {
return platformSidecarNameOpt.map(platformSidecarName ->
jobTaskPair -> {
for (PlatformSidecar ps : jobTaskPair.getLeft().getJobDescriptor().getPlatformSidecars()) {
if (ps.getName().equals(platformSidecarName)) {
return true;
}
}
return false;
}
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyPlatformSidecarChannel(Optional<String> platformSidecarChannelOpt) {
return platformSidecarChannelOpt.map(platformSidecarChannel ->
jobTaskPair -> {
for (PlatformSidecar ps : jobTaskPair.getLeft().getJobDescriptor().getPlatformSidecars()) {
if (ps.getChannel().equals(platformSidecarChannel)) {
return true;
}
}
return false;
}
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> apply(Optional<String> expectedOpt, Function<Job<?>, String> valueGetter) {
return expectedOpt.map(expected ->
jobTaskPair -> {
String actual = valueGetter.apply(jobTaskPair.getLeft());
return actual != null && actual.equals(expected);
}
);
}
private Optional<Predicate<Pair<Job<?>, TASK_OR_SET>>> applyJobDescriptorAttributes(Map<String, Set<String>> attributes, boolean andOperator) {
if (attributes.isEmpty()) {
return Optional.empty();
}
return Optional.of(jobTaskPair -> {
Map<String, String> jobAttributes = jobTaskPair.getLeft().getJobDescriptor().getAttributes();
return QueryUtils.matchesAttributes(attributes, jobAttributes, andOperator);
}
);
}
}
| 367 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/grpc/query/V3TaskQueryCriteriaEvaluator.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.grpc.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.ServiceJobTask;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.TaskStatus;
import com.netflix.titus.runtime.endpoint.JobQueryCriteria;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters;
public class V3TaskQueryCriteriaEvaluator extends V3AbstractQueryCriteriaEvaluator<Task> {
public V3TaskQueryCriteriaEvaluator(JobQueryCriteria<TaskStatus.TaskState, JobDescriptor.JobSpecCase> criteria, TitusRuntime titusRuntime) {
super(createTaskPredicates(criteria, titusRuntime), criteria);
}
private static List<Predicate<Pair<Job<?>, Task>>> createTaskPredicates(JobQueryCriteria<TaskStatus.TaskState, JobDescriptor.JobSpecCase> criteria, TitusRuntime titusRuntime) {
List<Predicate<Pair<Job<?>, Task>>> predicates = new ArrayList<>();
applyJobIds(criteria.getJobIds()).ifPresent(predicates::add);
applyTaskIds(criteria.getTaskIds()).ifPresent(predicates::add);
applyTaskStates(criteria.getTaskStates()).ifPresent(predicates::add);
applyTaskStateReasons(criteria.getTaskStateReasons()).ifPresent(predicates::add);
applyNeedsMigration(criteria.isNeedsMigration(), titusRuntime).ifPresent(predicates::add);
applySkipSystemFailures(criteria.isSkipSystemFailures()).ifPresent(predicates::add);
return predicates;
}
private static Optional<Predicate<Pair<Job<?>, Task>>> applyJobIds(Set<String> jobIds) {
if (jobIds.isEmpty()) {
return Optional.empty();
}
return Optional.of(jobAndTask -> jobIds.contains(jobAndTask.getLeft().getId()));
}
private static Optional<Predicate<Pair<Job<?>, Task>>> applyTaskIds(Set<String> taskIds) {
if (taskIds.isEmpty()) {
return Optional.empty();
}
return Optional.of(jobAndTask -> taskIds.contains(jobAndTask.getRight().getId()));
}
private static Optional<Predicate<Pair<Job<?>, Task>>> applyTaskStates(Set<TaskStatus.TaskState> taskStates) {
if (taskStates.isEmpty()) {
return Optional.empty();
}
Set<TaskState> coreTaskStates = taskStates.stream().map(GrpcJobManagementModelConverters::toCoreTaskState).collect(Collectors.toSet());
return Optional.of(jobAndTasks -> {
Task task = jobAndTasks.getRight();
return coreTaskStates.contains(task.getStatus().getState());
});
}
private static Optional<Predicate<Pair<Job<?>, Task>>> applyTaskStateReasons(Set<String> taskStateReasons) {
if (taskStateReasons.isEmpty()) {
return Optional.empty();
}
return Optional.of(jobAndTasks -> {
Task task = jobAndTasks.getRight();
return taskStateReasons.contains(task.getStatus().getReasonCode());
});
}
private static Optional<Predicate<Pair<Job<?>, Task>>> applyNeedsMigration(boolean needsMigration, TitusRuntime titusRuntime) {
if (!needsMigration) {
return Optional.empty();
}
return Optional.of(jobAndTask -> {
Task t = jobAndTask.getRight();
if (!JobFunctions.isServiceTask(t)) {
return false;
}
ServiceJobTask serviceTask = (ServiceJobTask) t;
titusRuntime.getCodeInvariants().notNull(serviceTask.getMigrationDetails(), "MigrationDetails is null in task: %s", t.getId());
return serviceTask.getMigrationDetails() != null && serviceTask.getMigrationDetails().isNeedsMigration();
}
);
}
private static Optional<Predicate<Pair<Job<?>, Task>>> applySkipSystemFailures(boolean skipSystemFailures) {
if (!skipSystemFailures) {
return Optional.empty();
}
return Optional.of(jobAndTask -> {
Task task = jobAndTask.getRight();
return !com.netflix.titus.api.jobmanager.model.job.TaskStatus.isSystemError(task.getStatus());
});
}
}
| 368 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/LoadBalancerResource.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.grpc.protogen.AddLoadBalancerRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.LoadBalancerId;
import com.netflix.titus.grpc.protogen.Page;
import com.netflix.titus.grpc.protogen.RemoveLoadBalancerRequest;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.service.LoadBalancerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.logPageNumberUsage;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(tags = "Load Balancing")
@Path("/v3/loadBalancers")
@Singleton
public class LoadBalancerResource {
private final LoadBalancerService loadBalancerService;
private final SystemLogService systemLog;
private final CallMetadataResolver callMetadataResolver;
@Inject
public LoadBalancerResource(LoadBalancerService loadBalancerService,
SystemLogService systemLog,
CallMetadataResolver callMetadataResolver) {
this.loadBalancerService = loadBalancerService;
this.systemLog = systemLog;
this.callMetadataResolver = callMetadataResolver;
}
@GET
@ApiOperation("Find the load balancer(s) with the specified ID")
@Path("/{jobId}")
public GetJobLoadBalancersResult getJobLoadBalancers(@PathParam("jobId") String jobId) {
return Responses.fromSingleValueObservable(
loadBalancerService.getLoadBalancers(JobId.newBuilder().setId(jobId).build(), resolveCallMetadata())
);
}
@GET
@ApiOperation("Get all load balancers")
public GetAllLoadBalancersResult getAllLoadBalancers(@Context UriInfo info) {
Page page = RestUtil.createPage(info.getQueryParameters());
CallMetadata callMetadata = resolveCallMetadata();
logPageNumberUsage(systemLog, callMetadata, getClass().getSimpleName(), "getAllLoadBalancers", page);
return Responses.fromSingleValueObservable(
loadBalancerService.getAllLoadBalancers(GetAllLoadBalancersRequest.newBuilder().setPage(page).build(), callMetadata)
);
}
@POST
@ApiOperation("Add a load balancer")
public Response addLoadBalancer(
@QueryParam("jobId") String jobId,
@QueryParam("loadBalancerId") String loadBalancerId) {
return Responses.fromCompletable(loadBalancerService.addLoadBalancer(
AddLoadBalancerRequest.newBuilder().setJobId(jobId).setLoadBalancerId(LoadBalancerId.newBuilder().setId(loadBalancerId).build()).build(),
resolveCallMetadata())
);
}
@DELETE
@ApiOperation("Remove a load balancer")
public Response removeLoadBalancer(
@QueryParam("jobId") String jobId,
@QueryParam("loadBalancerId") String loadBalancerId) {
return Responses.fromCompletable(loadBalancerService.removeLoadBalancer(
RemoveLoadBalancerRequest.newBuilder()
.setJobId(jobId)
.setLoadBalancerId(LoadBalancerId.newBuilder().setId(loadBalancerId).build())
.build(),
resolveCallMetadata())
);
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 369 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/AutoScalingSpringResource.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.inject.Inject;
import com.netflix.titus.grpc.protogen.DeletePolicyRequest;
import com.netflix.titus.grpc.protogen.GetPolicyResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.PutPolicyRequest;
import com.netflix.titus.grpc.protogen.ScalingPolicyID;
import com.netflix.titus.grpc.protogen.UpdatePolicyRequest;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.endpoint.metadata.spring.CallMetadataAuthentication;
import com.netflix.titus.runtime.service.AutoScalingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rx.Observable;
@Api(tags = "Auto scaling")
@RestController
@RequestMapping(path = "/api/v3/autoscaling", produces = MediaType.APPLICATION_JSON_VALUE)
public class AutoScalingSpringResource {
private static Logger log = LoggerFactory.getLogger(AutoScalingResource.class);
private AutoScalingService autoScalingService;
@Inject
public AutoScalingSpringResource(AutoScalingService autoScalingService) {
this.autoScalingService = autoScalingService;
}
@ApiOperation("Find scaling policies for a job")
@GetMapping(path = "/scalingPolicies")
public GetPolicyResult getAllScalingPolicies(CallMetadataAuthentication authentication) {
return Responses.fromSingleValueObservable(autoScalingService.getAllScalingPolicies(authentication.getCallMetadata()));
}
@ApiOperation("Find scaling policies for a job")
@GetMapping(path = "/scalingPolicies/{jobId}")
public GetPolicyResult getScalingPolicyForJob(@PathVariable("jobId") String jobId, CallMetadataAuthentication authentication) {
JobId request = JobId.newBuilder().setId(jobId).build();
return Responses.fromSingleValueObservable(autoScalingService.getJobScalingPolicies(request, authentication.getCallMetadata()));
}
@ApiOperation("Create or Update scaling policy")
@PostMapping(path = "/scalingPolicy")
public ScalingPolicyID setScalingPolicy(@RequestBody PutPolicyRequest putPolicyRequest, CallMetadataAuthentication authentication) {
Observable<ScalingPolicyID> putPolicyResult = autoScalingService.setAutoScalingPolicy(putPolicyRequest, authentication.getCallMetadata());
ScalingPolicyID policyId = Responses.fromSingleValueObservable(putPolicyResult);
log.info("New policy created {}", policyId);
return policyId;
}
@ApiOperation("Find scaling policy for a policy Id")
@GetMapping(path = "scalingPolicy/{policyId}")
public GetPolicyResult getScalingPolicy(@PathVariable("policyId") String policyId, CallMetadataAuthentication authentication) {
ScalingPolicyID scalingPolicyId = ScalingPolicyID.newBuilder().setId(policyId).build();
return Responses.fromSingleValueObservable(autoScalingService.getScalingPolicy(scalingPolicyId, authentication.getCallMetadata()));
}
@ApiOperation("Delete scaling policy")
@DeleteMapping(path = "scalingPolicy/{policyId}")
public ResponseEntity<Void> removePolicy(@PathVariable("policyId") String policyId, CallMetadataAuthentication authentication) {
ScalingPolicyID scalingPolicyId = ScalingPolicyID.newBuilder().setId(policyId).build();
DeletePolicyRequest deletePolicyRequest = DeletePolicyRequest.newBuilder().setId(scalingPolicyId).build();
return Responses.fromCompletable(autoScalingService.deleteAutoScalingPolicy(deletePolicyRequest, authentication.getCallMetadata()), HttpStatus.OK);
}
@ApiOperation("Update scaling policy")
@PutMapping("scalingPolicy")
public ResponseEntity<Void> updateScalingPolicy(@RequestBody UpdatePolicyRequest updatePolicyRequest, CallMetadataAuthentication authentication) {
return Responses.fromCompletable(autoScalingService.updateAutoScalingPolicy(updatePolicyRequest, authentication.getCallMetadata()), HttpStatus.OK);
}
}
| 370 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/JobManagementSpringResource.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import java.util.Set;
import javax.inject.Inject;
import com.google.common.base.Strings;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Capacity;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobCapacityWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudget;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.Page;
import com.netflix.titus.grpc.protogen.ServiceJobSpec;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.endpoint.metadata.spring.CallMetadataAuthentication;
import com.netflix.titus.runtime.jobmanager.gateway.JobServiceGateway;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.logPageNumberUsage;
@Api(tags = "Job Management")
@RestController
@RequestMapping(path = "/api/v3", produces = "application/json")
public class JobManagementSpringResource {
private final JobServiceGateway jobServiceGateway;
private final SystemLogService systemLog;
@Inject
public JobManagementSpringResource(JobServiceGateway jobServiceGateway, SystemLogService systemLog) {
this.jobServiceGateway = jobServiceGateway;
this.systemLog = systemLog;
}
@ApiOperation("Create a job")
@PostMapping(path = "/jobs")
public ResponseEntity<JobId> createJob(@RequestBody JobDescriptor jobDescriptor, CallMetadataAuthentication authentication) {
String jobId = Responses.fromSingleValueObservable(jobServiceGateway.createJob(jobDescriptor, authentication.getCallMetadata()));
return ResponseEntity.status(HttpStatus.ACCEPTED).body(JobId.newBuilder().setId(jobId).build());
}
@ApiOperation("Update an existing job's capacity")
@PutMapping(path = "/jobs/{jobId}/instances")
public ResponseEntity<Void> setInstances(@PathVariable("jobId") String jobId,
@RequestBody Capacity capacity,
CallMetadataAuthentication authentication) {
JobCapacityUpdate jobCapacityUpdate = JobCapacityUpdate.newBuilder()
.setJobId(jobId)
.setCapacity(capacity)
.build();
return Responses.fromCompletable(
jobServiceGateway.updateJobCapacity(jobCapacityUpdate, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Update an existing job's capacity. Optional attributes min / max / desired are supported.")
@PutMapping(path = "/jobs/{jobId}/capacityAttributes")
public ResponseEntity<Void> setCapacityWithOptionalAttributes(@PathVariable("jobId") String jobId,
@RequestBody JobCapacityWithOptionalAttributes capacity,
CallMetadataAuthentication authentication) {
JobCapacityUpdateWithOptionalAttributes jobCapacityUpdateWithOptionalAttributes = JobCapacityUpdateWithOptionalAttributes.newBuilder()
.setJobId(jobId)
.setJobCapacityWithOptionalAttributes(capacity)
.build();
return Responses.fromCompletable(
jobServiceGateway.updateJobCapacityWithOptionalAttributes(jobCapacityUpdateWithOptionalAttributes, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Update an existing job's processes")
@PutMapping(path = "/jobs/{jobId}/jobprocesses")
public ResponseEntity<Void> setJobProcesses(@PathVariable("jobId") String jobId,
@RequestBody ServiceJobSpec.ServiceJobProcesses jobProcesses,
CallMetadataAuthentication authentication) {
JobProcessesUpdate jobProcessesUpdate = JobProcessesUpdate.newBuilder()
.setJobId(jobId)
.setServiceJobProcesses(jobProcesses)
.build();
return Responses.fromCompletable(
jobServiceGateway.updateJobProcesses(jobProcessesUpdate, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Update job's disruption budget")
@PutMapping(path = "/jobs/{jobId}/disruptionBudget")
public ResponseEntity<Void> setJobDisruptionBudget(@PathVariable("jobId") String jobId,
@RequestBody JobDisruptionBudget jobDisruptionBudget,
CallMetadataAuthentication authentication) {
JobDisruptionBudgetUpdate request = JobDisruptionBudgetUpdate.newBuilder()
.setJobId(jobId)
.setDisruptionBudget(jobDisruptionBudget)
.build();
return Responses.fromVoidMono(
jobServiceGateway.updateJobDisruptionBudget(request, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Update attributes of a job")
@PutMapping(path = "/jobs/{jobId}/attributes")
public ResponseEntity<Void> updateJobAttributes(@PathVariable("jobId") String jobId,
@RequestBody JobAttributesUpdate request,
CallMetadataAuthentication authentication) {
JobAttributesUpdate sanitizedRequest;
if (request.getJobId().isEmpty()) {
sanitizedRequest = request.toBuilder().setJobId(jobId).build();
} else {
if (!jobId.equals(request.getJobId())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
sanitizedRequest = request;
}
return Responses.fromVoidMono(
jobServiceGateway.updateJobAttributes(sanitizedRequest, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Delete attributes of a job with the specified key names")
@DeleteMapping(path = "/jobs/{jobId}/attributes")
public ResponseEntity<Void> deleteJobAttributes(@PathVariable("jobId") String jobId,
@RequestParam("keys") String delimitedKeys,
CallMetadataAuthentication authentication) {
if (Strings.isNullOrEmpty(delimitedKeys)) {
throw TitusServiceException.invalidArgument("Path parameter 'keys' cannot be empty");
}
Set<String> keys = StringExt.splitByCommaIntoSet(delimitedKeys);
if (keys.isEmpty()) {
throw TitusServiceException.invalidArgument("Parsed path parameter 'keys' cannot be empty");
}
JobAttributesDeleteRequest request = JobAttributesDeleteRequest.newBuilder()
.setJobId(jobId)
.addAllKeys(keys)
.build();
return Responses.fromVoidMono(
jobServiceGateway.deleteJobAttributes(request, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Update an existing job's status")
@PostMapping(path = "/jobs/{jobId}/enable")
public ResponseEntity<Void> enableJob(@PathVariable("jobId") String jobId, CallMetadataAuthentication authentication) {
JobStatusUpdate jobStatusUpdate = JobStatusUpdate.newBuilder()
.setId(jobId)
.setEnableStatus(true)
.build();
return Responses.fromCompletable(
jobServiceGateway.updateJobStatus(jobStatusUpdate, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Update an existing job's status")
@PostMapping(path = "/jobs/{jobId}/disable")
public ResponseEntity<Void> disableJob(@PathVariable("jobId") String jobId, CallMetadataAuthentication authentication) {
JobStatusUpdate jobStatusUpdate = JobStatusUpdate.newBuilder()
.setId(jobId)
.setEnableStatus(false)
.build();
return Responses.fromCompletable(
jobServiceGateway.updateJobStatus(jobStatusUpdate, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Find the job with the specified ID")
@GetMapping(path = "/jobs/{jobId}", produces = org.springframework.http.MediaType.APPLICATION_JSON_VALUE)
public Job findJob(@PathVariable("jobId") String jobId, CallMetadataAuthentication authentication) {
return Responses.fromSingleValueObservable(jobServiceGateway.findJob(jobId, authentication.getCallMetadata()));
}
@ApiOperation("Find jobs")
@GetMapping(path = "/jobs", produces = MediaType.APPLICATION_JSON_VALUE)
public JobQueryResult findJobs(@RequestParam MultiValueMap<String, String> queryParameters, CallMetadataAuthentication authentication) {
JobQuery.Builder queryBuilder = JobQuery.newBuilder();
Page page = RestUtil.createPage(queryParameters);
logPageNumberUsage(systemLog, authentication.getCallMetadata(), getClass().getSimpleName(), "findJobs", page);
queryBuilder.setPage(page);
queryBuilder.putAllFilteringCriteria(RestUtil.getFilteringCriteria(queryParameters));
queryBuilder.addAllFields(RestUtil.getFieldsParameter(queryParameters));
return Responses.fromSingleValueObservable(jobServiceGateway.findJobs(queryBuilder.build(), authentication.getCallMetadata()));
}
@ApiOperation("Kill a job")
@DeleteMapping(path = "/jobs/{jobId}")
public ResponseEntity<Void> killJob(@PathVariable("jobId") String jobId, CallMetadataAuthentication authentication) {
return Responses.fromCompletable(jobServiceGateway.killJob(jobId, authentication.getCallMetadata()), HttpStatus.OK);
}
@ApiOperation(value = "Find a task with the specified ID", notes = "Returns an exact task if you already know the task ID", response = Job.class)
@GetMapping(path = "/tasks/{taskId}")
public Task findTask(@PathVariable("taskId") String taskId, CallMetadataAuthentication authentication) {
return Responses.fromSingleValueObservable(jobServiceGateway.findTask(taskId, authentication.getCallMetadata()));
}
@ApiOperation(value = "Find tasks", notes = "Find tasks with optional filtering criteria")
@GetMapping(path = "/tasks")
public TaskQueryResult findTasks(@RequestParam MultiValueMap<String, String> queryParameters, CallMetadataAuthentication authentication) {
TaskQuery.Builder queryBuilder = TaskQuery.newBuilder();
Page page = RestUtil.createPage(queryParameters);
logPageNumberUsage(systemLog, authentication.getCallMetadata(), getClass().getSimpleName(), "findTasks", page);
queryBuilder.setPage(page);
queryBuilder.putAllFilteringCriteria(RestUtil.getFilteringCriteria(queryParameters));
queryBuilder.addAllFields(RestUtil.getFieldsParameter(queryParameters));
return Responses.fromSingleValueObservable(jobServiceGateway.findTasks(queryBuilder.build(), authentication.getCallMetadata()));
}
@ApiOperation(value = "Kill task", notes = "Terminates a Titus Task given a particular Task ID.")
@DeleteMapping(path = "/tasks/{taskId}")
public ResponseEntity<Void> killTask(
@ApiParam(name = "taskId", value = "Titus Task ID you which to terminate")
@PathVariable("taskId") String taskId,
@ApiParam(name = "shrink", value = "Set true to shrink the desired of the job after killing the task. Defaults to false.", defaultValue = "false")
@RequestParam(name = "shrink", defaultValue = "false") boolean shrink,
@ApiParam(name = "preventMinSizeUpdate", value = "Set true to prevent the job from going below its minimum size. Defaults to false.", defaultValue = "false")
@RequestParam(name = "preventMinSizeUpdate", defaultValue = "false") boolean preventMinSizeUpdate,
CallMetadataAuthentication authentication
) {
TaskKillRequest taskKillRequest = TaskKillRequest.newBuilder()
.setTaskId(taskId)
.setShrink(shrink)
.setPreventMinSizeUpdate(preventMinSizeUpdate)
.build();
return Responses.fromCompletable(jobServiceGateway.killTask(taskKillRequest, authentication.getCallMetadata()), HttpStatus.OK);
}
@ApiOperation("Update attributes of a task")
@PutMapping(path = "/tasks/{taskId}/attributes")
public ResponseEntity<Void> updateTaskAttributes(@PathVariable("taskId") String taskId,
@RequestBody TaskAttributesUpdate request,
CallMetadataAuthentication authentication) {
TaskAttributesUpdate sanitizedRequest;
if (request.getTaskId().isEmpty()) {
sanitizedRequest = request.toBuilder().setTaskId(taskId).build();
} else {
if (!taskId.equals(request.getTaskId())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
sanitizedRequest = request;
}
return Responses.fromCompletable(
jobServiceGateway.updateTaskAttributes(sanitizedRequest, authentication.getCallMetadata()),
HttpStatus.OK
);
}
@ApiOperation("Delete attributes of a task with the specified key names")
@DeleteMapping(path = "/tasks/{taskId}/attributes")
public ResponseEntity<Void> deleteTaskAttributes(@PathVariable("taskId") String taskId,
@RequestParam("keys") String delimitedKeys,
CallMetadataAuthentication authentication) {
if (Strings.isNullOrEmpty(delimitedKeys)) {
throw TitusServiceException.invalidArgument("Path parameter 'keys' cannot be empty");
}
Set<String> keys = StringExt.splitByCommaIntoSet(delimitedKeys);
if (keys.isEmpty()) {
throw TitusServiceException.invalidArgument("Parsed path parameter 'keys' cannot be empty");
}
TaskAttributesDeleteRequest request = TaskAttributesDeleteRequest.newBuilder()
.setTaskId(taskId)
.addAllKeys(keys)
.build();
return Responses.fromCompletable(jobServiceGateway.deleteTaskAttributes(request, authentication.getCallMetadata()), HttpStatus.OK);
}
@ApiOperation("Move task to another job")
@PostMapping(path = "/tasks/move")
public ResponseEntity<Void> moveTask(@RequestBody TaskMoveRequest taskMoveRequest, CallMetadataAuthentication authentication) {
return Responses.fromCompletable(jobServiceGateway.moveTask(taskMoveRequest, authentication.getCallMetadata()), HttpStatus.OK);
}
}
| 371 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/LoadBalancerSpringResource.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.inject.Inject;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.grpc.protogen.AddLoadBalancerRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersRequest;
import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult;
import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.LoadBalancerId;
import com.netflix.titus.grpc.protogen.Page;
import com.netflix.titus.grpc.protogen.RemoveLoadBalancerRequest;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.endpoint.metadata.spring.CallMetadataAuthentication;
import com.netflix.titus.runtime.service.LoadBalancerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.logPageNumberUsage;
@Api(tags = "Load Balancing")
@RestController
@RequestMapping(path = "/api/v3/loadBalancers", produces = MediaType.APPLICATION_JSON_VALUE)
public class LoadBalancerSpringResource {
private final LoadBalancerService loadBalancerService;
private final SystemLogService systemLog;
@Inject
public LoadBalancerSpringResource(LoadBalancerService loadBalancerService, SystemLogService systemLog) {
this.loadBalancerService = loadBalancerService;
this.systemLog = systemLog;
}
@ApiOperation("Find the load balancer(s) with the specified Job ID")
@GetMapping(path = "/{jobId}")
public GetJobLoadBalancersResult getJobLoadBalancers(@PathVariable("jobId") String jobId, CallMetadataAuthentication authentication) {
return Responses.fromSingleValueObservable(loadBalancerService.getLoadBalancers(
JobId.newBuilder().setId(jobId).build(),
authentication.getCallMetadata()
));
}
@ApiOperation("Get all load balancers")
@GetMapping
public GetAllLoadBalancersResult getAllLoadBalancers(@RequestParam MultiValueMap<String, String> queryParameters,
CallMetadataAuthentication authentication) {
Page page = RestUtil.createPage(queryParameters);
logPageNumberUsage(systemLog, authentication.getCallMetadata(), getClass().getSimpleName(), "getAllLoadBalancers", page);
return Responses.fromSingleValueObservable(loadBalancerService.getAllLoadBalancers(
GetAllLoadBalancersRequest.newBuilder().setPage(page).build(),
authentication.getCallMetadata()
));
}
@ApiOperation("Add a load balancer")
@PostMapping
public ResponseEntity<Void> addLoadBalancer(
@RequestParam("jobId") String jobId,
@RequestParam("loadBalancerId") String loadBalancerId,
CallMetadataAuthentication authentication) {
return Responses.fromCompletable(
loadBalancerService.addLoadBalancer(
AddLoadBalancerRequest.newBuilder()
.setJobId(jobId)
.setLoadBalancerId(LoadBalancerId.newBuilder().setId(loadBalancerId).build())
.build(),
authentication.getCallMetadata()
),
HttpStatus.NO_CONTENT
);
}
@ApiOperation("Remove a load balancer")
@DeleteMapping
public ResponseEntity<Void> removeLoadBalancer(
@RequestParam("jobId") String jobId,
@RequestParam("loadBalancerId") String loadBalancerId,
CallMetadataAuthentication authentication) {
return Responses.fromCompletable(
loadBalancerService.removeLoadBalancer(
RemoveLoadBalancerRequest.newBuilder()
.setJobId(jobId)
.setLoadBalancerId(LoadBalancerId.newBuilder().setId(loadBalancerId).build())
.build(),
authentication.getCallMetadata()
),
HttpStatus.OK
);
}
}
| 372 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/RestUtil.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Page;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.CURSOR_QUERY_KEY;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.FIELDS_QUERY_KEY;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.IGNORED_QUERY_PARAMS;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.PAGE_QUERY_KEY;
import static com.netflix.titus.runtime.endpoint.v3.rest.RestConstants.PAGE_SIZE_QUERY_KEY;
public final class RestUtil {
public static Page createPage(Map<String, List<String>> map) {
Page.Builder pageBuilder = Page.newBuilder();
pageBuilder.setPageNumber(Integer.parseInt(getFirstOrDefault(map, PAGE_QUERY_KEY, "0")));
pageBuilder.setPageSize(Integer.parseInt(getFirstOrDefault(map, PAGE_SIZE_QUERY_KEY, "10")));
pageBuilder.setCursor(getFirstOrDefault(map, CURSOR_QUERY_KEY, ""));
return pageBuilder.build();
}
private static String getFirstOrDefault(Map<String, List<String>> map, String key, String defaultValue) {
List<String> values = map.get(key);
return CollectionsExt.isNullOrEmpty(values) ? defaultValue : values.get(0);
}
public static Map<String, String> getFilteringCriteria(Map<String, List<String>> map) {
Map<String, String> filterCriteria = new HashMap<>();
map.keySet()
.stream()
.filter(e -> !IGNORED_QUERY_PARAMS.contains(e.toLowerCase()))
.forEach(e -> {
List<String> values = map.get(e);
if (!CollectionsExt.isNullOrEmpty(values)) {
filterCriteria.put(e, values.get(0));
}
});
return filterCriteria;
}
public static List<String> getFieldsParameter(Map<String, List<String>> queryParameters) {
List<String> fields = queryParameters.get(FIELDS_QUERY_KEY);
if (CollectionsExt.isNullOrEmpty(fields)) {
return Collections.emptyList();
}
return fields.stream().flatMap(f -> StringExt.splitByComma(f).stream()).collect(Collectors.toList());
}
}
| 373 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/HealthSpringResource.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.inject.Inject;
import com.netflix.titus.grpc.protogen.HealthCheckRequest;
import com.netflix.titus.grpc.protogen.HealthCheckResponse;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.service.HealthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "Health")
@RestController
@RequestMapping(path = "/api/v3/status", produces = "application/json")
public class HealthSpringResource {
private final HealthService healthService;
@Inject
public HealthSpringResource(HealthService healthService) {
this.healthService = healthService;
}
@ApiOperation("Get the health status")
@GetMapping
public HealthCheckResponse check() {
return Responses.fromSingleValueObservable(healthService.check(HealthCheckRequest.newBuilder().build()));
}
}
| 374 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/JobManagementResource.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.google.common.base.Strings;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.runtime.SystemLogService;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Capacity;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.JobAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.JobAttributesUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdate;
import com.netflix.titus.grpc.protogen.JobCapacityUpdateWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobCapacityWithOptionalAttributes;
import com.netflix.titus.grpc.protogen.JobDescriptor;
import com.netflix.titus.grpc.protogen.JobDisruptionBudget;
import com.netflix.titus.grpc.protogen.JobDisruptionBudgetUpdate;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.JobProcessesUpdate;
import com.netflix.titus.grpc.protogen.JobQuery;
import com.netflix.titus.grpc.protogen.JobQueryResult;
import com.netflix.titus.grpc.protogen.JobStatusUpdate;
import com.netflix.titus.grpc.protogen.Page;
import com.netflix.titus.grpc.protogen.ServiceJobSpec;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.grpc.protogen.TaskAttributesDeleteRequest;
import com.netflix.titus.grpc.protogen.TaskAttributesUpdate;
import com.netflix.titus.grpc.protogen.TaskKillRequest;
import com.netflix.titus.grpc.protogen.TaskMoveRequest;
import com.netflix.titus.grpc.protogen.TaskQuery;
import com.netflix.titus.grpc.protogen.TaskQueryResult;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.jobmanager.gateway.JobServiceGateway;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.logPageNumberUsage;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(tags = "Job Management")
@Path("/v3")
@Singleton
public class JobManagementResource {
private final JobServiceGateway jobServiceGateway;
private final SystemLogService systemLog;
private final CallMetadataResolver callMetadataResolver;
@Inject
public JobManagementResource(JobServiceGateway jobServiceGateway,
SystemLogService systemLog,
CallMetadataResolver callMetadataResolver) {
this.jobServiceGateway = jobServiceGateway;
this.systemLog = systemLog;
this.callMetadataResolver = callMetadataResolver;
}
@POST
@ApiOperation("Create a job")
@Path("/jobs")
public Response createJob(JobDescriptor jobDescriptor) {
String jobId = Responses.fromSingleValueObservable(jobServiceGateway.createJob(jobDescriptor, resolveCallMetadata()));
return Response.status(Response.Status.ACCEPTED).entity(JobId.newBuilder().setId(jobId).build()).build();
}
@PUT
@ApiOperation("Update an existing job's capacity")
@Path("/jobs/{jobId}/instances")
public Response setInstances(@PathParam("jobId") String jobId,
Capacity capacity) {
JobCapacityUpdate jobCapacityUpdate = JobCapacityUpdate.newBuilder()
.setJobId(jobId)
.setCapacity(capacity)
.build();
return Responses.fromCompletable(jobServiceGateway.updateJobCapacity(jobCapacityUpdate, resolveCallMetadata()));
}
@PUT
@ApiOperation("Update an existing job's capacity. Optional attributes min / max / desired are supported.")
@Path("/jobs/{jobId}/capacityAttributes")
public Response setCapacityWithOptionalAttributes(@PathParam("jobId") String jobId,
JobCapacityWithOptionalAttributes capacity) {
JobCapacityUpdateWithOptionalAttributes jobCapacityUpdateWithOptionalAttributes = JobCapacityUpdateWithOptionalAttributes.newBuilder()
.setJobId(jobId)
.setJobCapacityWithOptionalAttributes(capacity)
.build();
return Responses.fromCompletable(jobServiceGateway.updateJobCapacityWithOptionalAttributes(jobCapacityUpdateWithOptionalAttributes, resolveCallMetadata()));
}
@PUT
@ApiOperation("Update an existing job's processes")
@Path("/jobs/{jobId}/jobprocesses")
public Response setJobProcesses(@PathParam("jobId") String jobId,
ServiceJobSpec.ServiceJobProcesses jobProcesses) {
JobProcessesUpdate jobProcessesUpdate = JobProcessesUpdate.newBuilder()
.setJobId(jobId)
.setServiceJobProcesses(jobProcesses)
.build();
return Responses.fromCompletable(jobServiceGateway.updateJobProcesses(jobProcessesUpdate, resolveCallMetadata()));
}
@PUT
@ApiOperation("Update job's disruption budget")
@Path("/jobs/{jobId}/disruptionBudget")
public Response setJobDisruptionBudget(@PathParam("jobId") String jobId,
JobDisruptionBudget jobDisruptionBudget) {
JobDisruptionBudgetUpdate request = JobDisruptionBudgetUpdate.newBuilder()
.setJobId(jobId)
.setDisruptionBudget(jobDisruptionBudget)
.build();
return Responses.fromVoidMono(jobServiceGateway.updateJobDisruptionBudget(request, resolveCallMetadata()));
}
@PUT
@ApiOperation("Update attributes of a job")
@Path("/jobs/{jobId}/attributes")
public Response updateJobAttributes(@PathParam("jobId") String jobId,
JobAttributesUpdate request) {
JobAttributesUpdate sanitizedRequest;
if (request.getJobId().isEmpty()) {
sanitizedRequest = request.toBuilder().setJobId(jobId).build();
} else {
if (!jobId.equals(request.getJobId())) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
sanitizedRequest = request;
}
return Responses.fromVoidMono(jobServiceGateway.updateJobAttributes(sanitizedRequest, resolveCallMetadata()));
}
@DELETE
@ApiOperation("Delete attributes of a job with the specified key names")
@Path("/jobs/{jobId}/attributes")
public Response deleteJobAttributes(@PathParam("jobId") String jobId, @QueryParam("keys") String delimitedKeys) {
if (Strings.isNullOrEmpty(delimitedKeys)) {
throw TitusServiceException.invalidArgument("Path parameter 'keys' cannot be empty");
}
Set<String> keys = StringExt.splitByCommaIntoSet(delimitedKeys);
if (keys.isEmpty()) {
throw TitusServiceException.invalidArgument("Parsed path parameter 'keys' cannot be empty");
}
JobAttributesDeleteRequest request = JobAttributesDeleteRequest.newBuilder()
.setJobId(jobId)
.addAllKeys(keys)
.build();
return Responses.fromVoidMono(jobServiceGateway.deleteJobAttributes(request, resolveCallMetadata()));
}
@POST
@ApiOperation("Update an existing job's status")
@Path("/jobs/{jobId}/enable")
public Response enableJob(@PathParam("jobId") String jobId) {
JobStatusUpdate jobStatusUpdate = JobStatusUpdate.newBuilder()
.setId(jobId)
.setEnableStatus(true)
.build();
return Responses.fromCompletable(jobServiceGateway.updateJobStatus(jobStatusUpdate, resolveCallMetadata()));
}
@POST
@ApiOperation("Update an existing job's status")
@Path("/jobs/{jobId}/disable")
public Response disableJob(@PathParam("jobId") String jobId) {
JobStatusUpdate jobStatusUpdate = JobStatusUpdate.newBuilder()
.setId(jobId)
.setEnableStatus(false)
.build();
return Responses.fromCompletable(jobServiceGateway.updateJobStatus(jobStatusUpdate, resolveCallMetadata()));
}
@GET
@ApiOperation("Find the job with the specified ID")
@Path("/jobs/{jobId}")
public Job findJob(@PathParam("jobId") String jobId) {
return Responses.fromSingleValueObservable(jobServiceGateway.findJob(jobId, resolveCallMetadata()));
}
@GET
@ApiOperation("Find jobs")
@Path("/jobs")
public JobQueryResult findJobs(@Context UriInfo info) {
MultivaluedMap<String, String> queryParameters = info.getQueryParameters(true);
JobQuery.Builder queryBuilder = JobQuery.newBuilder();
Page page = RestUtil.createPage(queryParameters);
CallMetadata callMetadata = resolveCallMetadata();
logPageNumberUsage(systemLog, callMetadata, getClass().getSimpleName(), "findJobs", page);
queryBuilder.setPage(page);
queryBuilder.putAllFilteringCriteria(RestUtil.getFilteringCriteria(queryParameters));
queryBuilder.addAllFields(RestUtil.getFieldsParameter(queryParameters));
return Responses.fromSingleValueObservable(jobServiceGateway.findJobs(queryBuilder.build(), callMetadata));
}
@DELETE
@ApiOperation("Kill a job")
@Path("/jobs/{jobId}")
public Response killJob(@PathParam("jobId") String jobId) {
return Responses.fromCompletable(jobServiceGateway.killJob(jobId, resolveCallMetadata()));
}
@GET
@ApiOperation("Find the task with the specified ID")
@Path("/tasks/{taskId}")
public Task findTask(@PathParam("taskId") String taskId) {
return Responses.fromSingleValueObservable(jobServiceGateway.findTask(taskId, resolveCallMetadata()));
}
@GET
@ApiOperation("Find tasks")
@Path("/tasks")
public TaskQueryResult findTasks(@Context UriInfo info) {
MultivaluedMap<String, String> queryParameters = info.getQueryParameters(true);
TaskQuery.Builder queryBuilder = TaskQuery.newBuilder();
Page page = RestUtil.createPage(queryParameters);
CallMetadata callMetadata = resolveCallMetadata();
logPageNumberUsage(systemLog, callMetadata, getClass().getSimpleName(), "findTasks", page);
queryBuilder.setPage(page);
queryBuilder.putAllFilteringCriteria(RestUtil.getFilteringCriteria(queryParameters));
queryBuilder.addAllFields(RestUtil.getFieldsParameter(queryParameters));
return Responses.fromSingleValueObservable(jobServiceGateway.findTasks(queryBuilder.build(), callMetadata));
}
@DELETE
@ApiOperation("Kill task")
@Path("/tasks/{taskId}")
public Response killTask(
@PathParam("taskId") String taskId,
@DefaultValue("false") @QueryParam("shrink") boolean shrink,
@DefaultValue("false") @QueryParam("preventMinSizeUpdate") boolean preventMinSizeUpdate
) {
TaskKillRequest taskKillRequest = TaskKillRequest.newBuilder()
.setTaskId(taskId)
.setShrink(shrink)
.setPreventMinSizeUpdate(preventMinSizeUpdate)
.build();
return Responses.fromCompletable(jobServiceGateway.killTask(taskKillRequest, resolveCallMetadata()));
}
@PUT
@ApiOperation("Update attributes of a task")
@Path("/tasks/{taskId}/attributes")
public Response updateTaskAttributes(@PathParam("taskId") String taskId,
TaskAttributesUpdate request) {
TaskAttributesUpdate sanitizedRequest;
if (request.getTaskId().isEmpty()) {
sanitizedRequest = request.toBuilder().setTaskId(taskId).build();
} else {
if (!taskId.equals(request.getTaskId())) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
sanitizedRequest = request;
}
return Responses.fromCompletable(jobServiceGateway.updateTaskAttributes(sanitizedRequest, resolveCallMetadata()));
}
@DELETE
@ApiOperation("Delete attributes of a task with the specified key names")
@Path("/tasks/{taskId}/attributes")
public Response deleteTaskAttributes(@PathParam("taskId") String taskId, @QueryParam("keys") String delimitedKeys) {
if (Strings.isNullOrEmpty(delimitedKeys)) {
throw TitusServiceException.invalidArgument("Path parameter 'keys' cannot be empty");
}
Set<String> keys = StringExt.splitByCommaIntoSet(delimitedKeys);
if (keys.isEmpty()) {
throw TitusServiceException.invalidArgument("Parsed path parameter 'keys' cannot be empty");
}
TaskAttributesDeleteRequest request = TaskAttributesDeleteRequest.newBuilder()
.setTaskId(taskId)
.addAllKeys(keys)
.build();
return Responses.fromCompletable(jobServiceGateway.deleteTaskAttributes(request, resolveCallMetadata()));
}
@POST
@ApiOperation("Move task to another job")
@Path("/tasks/move")
public Response moveTask(TaskMoveRequest taskMoveRequest) {
return Responses.fromCompletable(jobServiceGateway.moveTask(taskMoveRequest, resolveCallMetadata()));
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 375 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/AutoScalingResource.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.netflix.titus.api.jobmanager.service.JobManagerConstants;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.grpc.protogen.DeletePolicyRequest;
import com.netflix.titus.grpc.protogen.GetPolicyResult;
import com.netflix.titus.grpc.protogen.JobId;
import com.netflix.titus.grpc.protogen.PutPolicyRequest;
import com.netflix.titus.grpc.protogen.ScalingPolicyID;
import com.netflix.titus.grpc.protogen.UpdatePolicyRequest;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.service.AutoScalingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(tags = "Auto scaling")
@Path("/v3/autoscaling")
@Singleton
public class AutoScalingResource {
private static Logger log = LoggerFactory.getLogger(AutoScalingResource.class);
private AutoScalingService autoScalingService;
private final CallMetadataResolver callMetadataResolver;
@Inject
public AutoScalingResource(AutoScalingService autoScalingService,
CallMetadataResolver callMetadataResolver) {
this.autoScalingService = autoScalingService;
this.callMetadataResolver = callMetadataResolver;
}
@GET
@ApiOperation("Find scaling policies for a job")
@Path("scalingPolicies")
public GetPolicyResult getAllScalingPolicies() {
GetPolicyResult getPolicyResult = Responses.fromSingleValueObservable(autoScalingService.getAllScalingPolicies(resolveCallMetadata()));
return getPolicyResult;
}
@GET
@ApiOperation("Find scaling policies for a job")
@Path("scalingPolicies/{jobId}")
public GetPolicyResult getScalingPolicyForJob(@PathParam("jobId") String jobId) {
JobId request = JobId.newBuilder().setId(jobId).build();
GetPolicyResult getPolicyResult = Responses.fromSingleValueObservable(autoScalingService.getJobScalingPolicies(request, resolveCallMetadata()));
return getPolicyResult;
}
@POST
@ApiOperation("Create or Update scaling policy")
@Path("scalingPolicy")
public ScalingPolicyID setScalingPolicy(PutPolicyRequest putPolicyRequest) {
Observable<ScalingPolicyID> putPolicyResult = autoScalingService.setAutoScalingPolicy(putPolicyRequest, resolveCallMetadata());
ScalingPolicyID policyId = Responses.fromSingleValueObservable(putPolicyResult);
log.info("New policy created {}", policyId);
return policyId;
}
@GET
@ApiOperation("Find scaling policy for a policy Id")
@Path("scalingPolicy/{policyId}")
public GetPolicyResult getScalingPolicy(@PathParam("policyId") String policyId) {
ScalingPolicyID scalingPolicyId = ScalingPolicyID.newBuilder().setId(policyId).build();
return Responses.fromSingleValueObservable(autoScalingService.getScalingPolicy(scalingPolicyId, resolveCallMetadata()));
}
@DELETE
@ApiOperation("Delete scaling policy")
@Path("scalingPolicy/{policyId}")
public javax.ws.rs.core.Response removePolicy(@PathParam("policyId") String policyId) {
ScalingPolicyID scalingPolicyId = ScalingPolicyID.newBuilder().setId(policyId).build();
DeletePolicyRequest deletePolicyRequest = DeletePolicyRequest.newBuilder().setId(scalingPolicyId).build();
return Responses.fromCompletable(autoScalingService.deleteAutoScalingPolicy(deletePolicyRequest, resolveCallMetadata()));
}
@PUT
@ApiOperation("Update scaling policy")
@Path("scalingPolicy")
public javax.ws.rs.core.Response updateScalingPolicy(UpdatePolicyRequest updatePolicyRequest) {
return Responses.fromCompletable(autoScalingService.updateAutoScalingPolicy(updatePolicyRequest, resolveCallMetadata()));
}
private CallMetadata resolveCallMetadata() {
return callMetadataResolver.resolve().orElse(JobManagerConstants.UNDEFINED_CALL_METADATA);
}
}
| 376 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/RestConstants.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import java.util.Set;
import static com.netflix.titus.common.util.CollectionsExt.asSet;
public class RestConstants {
static final Set<String> IGNORED_QUERY_PARAMS = asSet(
"debug", "fields", "page", "pagesize", "cursor", "accesstoken"
);
public static final String PAGE_QUERY_KEY = "page";
public static final String PAGE_SIZE_QUERY_KEY = "pageSize";
public static final String CURSOR_QUERY_KEY = "cursor";
public static final String FIELDS_QUERY_KEY = "fields";
}
| 377 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/v3/rest/HealthResource.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.v3.rest;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.netflix.titus.grpc.protogen.HealthCheckRequest;
import com.netflix.titus.grpc.protogen.HealthCheckResponse;
import com.netflix.titus.runtime.endpoint.common.rest.Responses;
import com.netflix.titus.runtime.service.HealthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(tags = "Health")
@Path("/v3/status")
@Singleton
public class HealthResource {
private final HealthService healthService;
@Inject
public HealthResource(HealthService healthService) {
this.healthService = healthService;
}
@GET
@ApiOperation("Get the health status")
public HealthCheckResponse check() {
return Responses.fromSingleValueObservable(healthService.check(HealthCheckRequest.newBuilder().build()));
}
}
| 378 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/authorization/AuthorizationService.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.authorization;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import reactor.core.publisher.Mono;
/**
* {@link AuthorizationService} checks users access rights to data.
*/
public interface AuthorizationService {
/**
* Based on the security context provided and the object being accessed, returns the authorization result.
*/
<T> Mono<AuthorizationStatus> authorize(CallMetadata callMetadata, T object);
}
| 379 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/authorization/AuthorizationServiceModule.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.authorization;
import com.google.inject.AbstractModule;
public class AuthorizationServiceModule extends AbstractModule {
@Override
protected void configure() {
bind(AuthorizationService.class).to(AllowAllAuthorizationService.class);
}
}
| 380 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/authorization/AllowAllAuthorizationService.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.authorization;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import reactor.core.publisher.Mono;
public class AllowAllAuthorizationService implements AuthorizationService {
private static final Mono<AuthorizationStatus> STATUS = Mono.just(AuthorizationStatus.success("Authorization not enabled"));
@Override
public <T> Mono<AuthorizationStatus> authorize(CallMetadata callMetadata, T object) {
return STATUS;
}
}
| 381 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/authorization/AuthorizationStatus.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.endpoint.authorization;
public class AuthorizationStatus {
private static final AuthorizationStatus SUCCESS = new AuthorizationStatus(true, "Access granted");
private final boolean authorized;
private final String reason;
private AuthorizationStatus(boolean authorized, String reason) {
this.authorized = authorized;
this.reason = reason;
}
public boolean isAuthorized() {
return authorized;
}
public String getReason() {
return reason;
}
public static AuthorizationStatus success() {
return SUCCESS;
}
public static AuthorizationStatus success(String reason) {
return new AuthorizationStatus(true, reason);
}
public static AuthorizationStatus failure(String reason) {
return new AuthorizationStatus(false, reason);
}
}
| 382 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/metadata/CallMetadataUtils.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.metadata;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.service.TitusServiceException;
import com.netflix.titus.common.util.StringExt;
import io.grpc.stub.StreamObserver;
public class CallMetadataUtils {
public static final String UNKNOWN_CALLER_ID = "unknownDirectCaller";
public static boolean isUnknown(CallMetadata callMetadata) {
return UNKNOWN_CALLER_ID.equals(callMetadata.getCallerId());
}
/**
* Execute an action with the resolved call metadata context.
*/
public static void execute(CallMetadataResolver callMetadataResolver,
StreamObserver<?> responseObserver,
Consumer<CallMetadata> action) {
Optional<CallMetadata> callMetadata = callMetadataResolver.resolve();
if (!callMetadata.isPresent()) {
responseObserver.onError(TitusServiceException.noCallerId());
return;
}
try {
action.accept(callMetadata.get());
} catch (Exception e) {
responseObserver.onError(e);
}
}
public static Map<String, String> asMap(CallMetadata callMetadata) {
return ImmutableMap.of(
"callerId", callMetadata.getCallerId(),
"callPath", String.join("/", callMetadata.getCallPath()),
"callReason", callMetadata.getCallReason()
);
}
public static String toCallerId(CallMetadata callMetadata) {
return String.join("/", callMetadata.getCallPath());
}
public static String getFirstCallerId(CallMetadata callMetadata) {
StringBuilder builder = new StringBuilder();
if (callMetadata.getCallers().isEmpty()) {
builder.append("calledBy=Titus");
return builder.toString();
}
builder.append("calledBy=").append(callMetadata.getCallers().get(0).getId());
return builder.toString();
}
public static String toReasonString(CallMetadata callMetadata) {
StringBuilder builder = new StringBuilder();
builder.append("calledBy=").append(callMetadata.getCallerId());
builder.append(", relayedVia=");
List<String> callPath = callMetadata.getCallPath();
if (callPath.isEmpty()) {
builder.append("Titus");
} else {
for (int i = 0; i < callPath.size(); i++) {
if (i > 0) {
builder.append(',');
}
builder.append(callPath.get(i));
}
}
if (StringExt.isNotEmpty(callMetadata.getCallReason())) {
builder.append(", reason=").append(callMetadata.getCallReason());
}
return builder.toString();
}
}
| 383 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/metadata/CallMetadataResolverComponent.java | /*
* Copyright 2020 Netflix, 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.netflix.titus.runtime.endpoint.metadata;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({
SimpleCallMetadataResolverProvider.class
})
public class CallMetadataResolverComponent {
}
| 384 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/endpoint/metadata/CallMetadataResolveModule.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.endpoint.metadata;
import com.google.inject.AbstractModule;
public final class CallMetadataResolveModule extends AbstractModule {
@Override
protected void configure() {
bind(CallMetadataResolver.class).toProvider(SimpleCallMetadataResolverProvider.class);
}
}
| 385 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/GrpcClientConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.grpcClient")
public interface GrpcClientConfiguration {
/**
* GRPC server hostname.
*/
@DefaultValue("localhost")
String getHostname();
/**
* GRPC server port number.
*/
@DefaultValue("7004")
int getGrpcPort();
/**
* GRPC operation timeout.
*
* @deprecated Use {@link GrpcRequestConfiguration} instead
*/
@DefaultValue("10000")
@Deprecated
long getRequestTimeout();
}
| 386 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/LeaderEndpointResolver.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import java.util.Optional;
import com.netflix.titus.common.network.http.EndpointResolver;
public class LeaderEndpointResolver implements EndpointResolver {
private final LeaderResolver leaderResolver;
public LeaderEndpointResolver(LeaderResolver leaderResolver) {
this.leaderResolver = leaderResolver;
}
@Override
public String resolve() {
Optional<Address> addressOptional = leaderResolver.resolve();
if (addressOptional.isPresent()) {
return addressOptional.get().toString();
} else {
throw new RuntimeException("No Leader Host Available");
}
}
}
| 387 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/TitusMasterClientConfiguration.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.masterClient")
public interface TitusMasterClientConfiguration {
@DefaultValue("http")
String getMasterScheme();
@DefaultValue("127.0.0.1")
String getMasterIp();
@DefaultValue("7001")
int getMasterHttpPort();
@DefaultValue("7104")
int getMasterGrpcPort();
}
| 388 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/ConfigurationLeaderResolver.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.subjects.PublishSubject;
@Singleton
public class ConfigurationLeaderResolver implements LeaderResolver {
private static final Logger logger = LoggerFactory.getLogger(ConfigurationLeaderResolver.class);
private static final int LEADER_REFRESH_INTERVAL_MS = 5_000;
private final ScheduledExecutorService executorService;
private final PublishSubject<Optional<Address>> leaderPublishSubject;
private volatile Address leaderAddress;
@Inject
public ConfigurationLeaderResolver(TitusMasterClientConfiguration configuration) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("configuration-leader-resolver-%d").build();
this.executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
leaderPublishSubject = PublishSubject.create();
executorService.scheduleAtFixedRate(() -> {
try {
logger.debug("Current leaderAddress: {}", leaderAddress);
Address newLeaderAddress = new Address(configuration.getMasterScheme(), configuration.getMasterIp(), configuration.getMasterHttpPort());
if (!Objects.equals(leaderAddress, newLeaderAddress)) {
logger.info("Updating leaderAddress from: {} to: {}", leaderAddress, newLeaderAddress);
leaderAddress = newLeaderAddress;
}
leaderPublishSubject.onNext(Optional.of(newLeaderAddress));
} catch (Exception e) {
logger.error("Unable to resolve current titus master with error: ", e);
}
}, 0, LEADER_REFRESH_INTERVAL_MS, TimeUnit.MILLISECONDS);
}
@PreDestroy
public void shutdown() {
executorService.shutdownNow();
}
public Optional<Address> resolve() {
return Optional.of(leaderAddress);
}
@Override
public Observable<Optional<Address>> observeLeader() {
return leaderPublishSubject;
}
}
| 389 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/ConfigurationLeaderResolverComponent.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import io.grpc.Channel;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigurationLeaderResolverComponent {
public static final String TITUS_MASTER_CHANNEL = "titusMasterChannel";
@Bean
public TitusMasterClientConfiguration getTitusMasterClientConfiguration(TitusRuntime titusRuntime) {
return Archaius2Ext.newConfiguration(TitusMasterClientConfiguration.class, "titus.masterClient", titusRuntime.getMyEnvironment());
}
@Bean
public LeaderResolver getLeaderResolver(TitusMasterClientConfiguration configuration) {
return new ConfigurationLeaderResolver(configuration);
}
@Bean(name = TITUS_MASTER_CHANNEL)
public Channel getManagedChannel(TitusMasterClientConfiguration configuration, LeaderResolver leaderResolver, TitusRuntime titusRuntime) {
return NettyChannelBuilder
.forTarget("leader://titusmaster")
.nameResolverFactory(new LeaderNameResolverFactory(leaderResolver, configuration.getMasterGrpcPort(), titusRuntime))
.usePlaintext()
.maxInboundMetadataSize(65536)
.build();
}
}
| 390 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/LeaderResolver.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import java.util.Optional;
import com.netflix.titus.common.util.rx.ReactorExt;
import reactor.core.publisher.Flux;
import rx.Observable;
public interface LeaderResolver {
/**
* @return {@link Address} of the leader
*/
Optional<Address> resolve();
/**
* @return a persistent observable that emits the {@link Address} of the leader at some interval. The consumer should be able to handle
* duplicates.
* @deprecated Use {@link #observeLeaderFlux()} instead.
*/
@Deprecated
Observable<Optional<Address>> observeLeader();
/**
* Spring-Reactor variant of {@link #observeLeader()}.
*/
default Flux<Optional<Address>> observeLeaderFlux() {
return ReactorExt.toFlux(observeLeader());
}
}
| 391 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/Address.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
public class Address {
private final String scheme;
private final String host;
private final int port;
public Address(String scheme, String host, int port) {
this.scheme = scheme;
this.host = host;
this.port = port;
}
public String getScheme() {
return scheme;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Address address = (Address) o;
if (port != address.port) {
return false;
}
if (scheme != null ? !scheme.equals(address.scheme) : address.scheme != null) {
return false;
}
return host != null ? host.equals(address.host) : address.host == null;
}
@Override
public int hashCode() {
int result = scheme != null ? scheme.hashCode() : 0;
result = 31 * result + (host != null ? host.hashCode() : 0);
result = 31 * result + port;
return result;
}
@Override
public String toString() {
return scheme + "://" + host + ":" + port;
}
}
| 392 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/LeaderNameResolver.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.concurrent.GuardedBy;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.rx.ObservableExt;
import io.grpc.Attributes;
import io.grpc.EquivalentAddressGroup;
import io.grpc.NameResolver;
import io.grpc.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
public class LeaderNameResolver extends NameResolver {
private static final Logger logger = LoggerFactory.getLogger(LeaderNameResolver.class);
private final String authority;
private final LeaderResolver leaderResolver;
private final int port;
private final TitusRuntime titusRuntime;
@GuardedBy("this")
private boolean shutdown;
@GuardedBy("this")
private Listener listener;
@GuardedBy("this")
private Subscription leaderSubscription;
public LeaderNameResolver(URI targetUri,
LeaderResolver leaderResolver,
int port,
TitusRuntime titusRuntime) {
this.leaderResolver = leaderResolver;
this.port = port;
this.titusRuntime = titusRuntime;
if (targetUri.getAuthority() != null) {
this.authority = targetUri.getAuthority();
} else {
this.authority = targetUri.getPath().substring(1);
}
}
@Override
public String getServiceAuthority() {
return this.authority;
}
@Override
public void start(Listener listener) {
Preconditions.checkState(this.listener == null, "already started");
this.listener = Preconditions.checkNotNull(listener, "listener");
try {
Optional<Address> leaderAddressOpt = leaderResolver.resolve();
refreshServers(listener, leaderAddressOpt);
} catch (Exception e) {
logger.error("Unable to resolve leader on start with error: ", e);
listener.onError(Status.UNAVAILABLE.withCause(e));
}
leaderSubscription = titusRuntime.persistentStream(leaderResolver.observeLeader()).subscribe(
leaderAddressOpt -> refreshServers(listener, leaderAddressOpt),
e -> {
logger.error("Unable to observe leader with error: ", e);
listener.onError(Status.UNAVAILABLE.withCause(e));
},
() -> logger.debug("Completed the leader resolver observable")
);
}
private void refreshServers(Listener listener, Optional<Address> leaderAddressOpt) {
List<EquivalentAddressGroup> servers = new ArrayList<>();
try {
if (leaderAddressOpt.isPresent()) {
Address address = leaderAddressOpt.get();
EquivalentAddressGroup server = new EquivalentAddressGroup(new InetSocketAddress(address.getHost(), port));
servers.add(server);
}
} catch (Exception e) {
logger.error("Unable to create server with error: ", e);
listener.onError(Status.UNAVAILABLE.withCause(e));
}
if (servers.isEmpty()) {
listener.onError(Status.UNAVAILABLE.withDescription("Unable to resolve leader server. Refreshing."));
} else {
logger.debug("Refreshing servers: {}", servers);
listener.onAddresses(servers, Attributes.EMPTY);
}
}
public final synchronized void shutdown() {
if (!this.shutdown) {
this.shutdown = true;
ObservableExt.safeUnsubscribe(leaderSubscription);
}
}
} | 393 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/TitusMasterConnectorModule.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import java.util.Collections;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Names;
import com.netflix.archaius.ConfigProxyFactory;
import com.netflix.titus.api.connector.cloud.LoadBalancerConnector;
import com.netflix.titus.api.connector.cloud.noop.NoOpLoadBalancerConnector;
import com.netflix.titus.api.loadbalancer.model.sanitizer.DefaultLoadBalancerResourceValidator;
import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerResourceValidator;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.network.http.HttpClient;
import com.netflix.titus.common.network.http.RxHttpClient;
import com.netflix.titus.common.network.http.internal.okhttp.CompositeRetryInterceptor;
import com.netflix.titus.common.network.http.internal.okhttp.EndpointResolverInterceptor;
import com.netflix.titus.common.network.http.internal.okhttp.OkHttpClient;
import com.netflix.titus.common.network.http.internal.okhttp.PassthroughInterceptor;
import com.netflix.titus.common.network.http.internal.okhttp.RxOkHttpClient;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.grpc.reactor.GrpcToReactorClientFactory;
import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc;
import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc.AutoScalingServiceStub;
import com.netflix.titus.grpc.protogen.HealthGrpc;
import com.netflix.titus.grpc.protogen.HealthGrpc.HealthStub;
import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc;
import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc.JobManagementServiceStub;
import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc;
import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc.LoadBalancerServiceStub;
import com.netflix.titus.grpc.protogen.SchedulerServiceGrpc;
import com.netflix.titus.grpc.protogen.SchedulerServiceGrpc.SchedulerServiceStub;
import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc;
import com.netflix.titus.runtime.connector.GrpcRequestConfiguration;
import com.netflix.titus.runtime.connector.common.reactor.DefaultGrpcToReactorClientFactory;
import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver;
import com.netflix.titus.runtime.endpoint.metadata.CommonCallMetadataUtils;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import okhttp3.Interceptor;
public class TitusMasterConnectorModule extends AbstractModule {
public static final String MANAGED_CHANNEL_NAME = "ManagedChannel";
public static final String TITUS_MASTER_CLIENT = "TitusMaster";
public static final String RX_TITUS_MASTER_CLIENT = "RxTitusMaster";
private static final int NUMBER_OF_RETRIES = 3;
private static final int DEFAULT_CONNECT_TIMEOUT = 10_000;
private static final int DEFAULT_READ_TIMEOUT = 30_000;
@Override
protected void configure() {
bind(LeaderResolver.class).to(ConfigurationLeaderResolver.class);
bind(LoadBalancerResourceValidator.class).to(DefaultLoadBalancerResourceValidator.class);
bind(LoadBalancerConnector.class).to(NoOpLoadBalancerConnector.class);
bind(Channel.class).annotatedWith(Names.named(MANAGED_CHANNEL_NAME)).toProvider(TitusMasterManagedChannelProvider.class);
}
@Provides
@Singleton
public TitusMasterClientConfiguration getTitusMasterClientConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(TitusMasterClientConfiguration.class);
}
@Named(TITUS_MASTER_CLIENT)
@Provides
@Singleton
public HttpClient httpClient() {
OkHttpClient.Builder builder = OkHttpClient.newBuilder();
Interceptor retryInterceptor = new CompositeRetryInterceptor(Collections.singletonList(new PassthroughInterceptor()), NUMBER_OF_RETRIES);
builder.interceptor(retryInterceptor)
.connectTimeout(DEFAULT_CONNECT_TIMEOUT)
.readTimeout(DEFAULT_READ_TIMEOUT);
return builder.build();
}
@Named(RX_TITUS_MASTER_CLIENT)
@Provides
@Singleton
public RxHttpClient rxHttpClient(LeaderResolver leaderResolver) {
RxOkHttpClient.Builder builder = RxOkHttpClient.newBuilder();
LeaderEndpointResolver endpointResolver = new LeaderEndpointResolver(leaderResolver);
Interceptor retryInterceptor = new CompositeRetryInterceptor(Collections.singletonList(new EndpointResolverInterceptor(endpointResolver)), NUMBER_OF_RETRIES);
builder.interceptor(retryInterceptor)
.connectTimeout(DEFAULT_CONNECT_TIMEOUT)
.readTimeout(DEFAULT_READ_TIMEOUT);
return builder.build();
}
@Provides
@Singleton
public GrpcToReactorClientFactory getReactorGrpcClientAdapterFactory(GrpcRequestConfiguration configuration,
CallMetadataResolver callMetadataResolver) {
return new DefaultGrpcToReactorClientFactory<>(configuration,
CommonCallMetadataUtils.newGrpcStubDecorator(callMetadataResolver),
CallMetadata.class
);
}
@Provides
@Singleton
HealthStub healthClient(final @Named(MANAGED_CHANNEL_NAME) Channel channel) {
return HealthGrpc.newStub(channel);
}
@Provides
@Singleton
SupervisorServiceGrpc.SupervisorServiceStub supervisorClient(final @Named(MANAGED_CHANNEL_NAME) Channel channel) {
return SupervisorServiceGrpc.newStub(channel);
}
@Provides
@Singleton
JobManagementServiceStub jobManagementClient(final @Named(MANAGED_CHANNEL_NAME) Channel channel) {
return JobManagementServiceGrpc.newStub(channel);
}
@Provides
@Singleton
SchedulerServiceStub schedulerClient(final @Named(MANAGED_CHANNEL_NAME) Channel channel) {
return SchedulerServiceGrpc.newStub(channel);
}
@Provides
@Singleton
LoadBalancerServiceStub loadBalancerClient(final @Named(MANAGED_CHANNEL_NAME) Channel channel) {
return LoadBalancerServiceGrpc.newStub(channel);
}
@Provides
@Singleton
AutoScalingServiceStub autoScalingClient(final @Named(MANAGED_CHANNEL_NAME) Channel channel) {
return AutoScalingServiceGrpc.newStub(channel);
}
@Singleton
public static class TitusMasterManagedChannelProvider implements Provider<ManagedChannel> {
private final ManagedChannel managedChannel;
@Inject
public TitusMasterManagedChannelProvider(TitusMasterClientConfiguration configuration, LeaderResolver leaderResolver, TitusRuntime titusRuntime) {
this.managedChannel = NettyChannelBuilder
.forTarget("leader://titusmaster")
.nameResolverFactory(new LeaderNameResolverFactory(leaderResolver, configuration.getMasterGrpcPort(), titusRuntime))
.usePlaintext()
.maxInboundMetadataSize(65536)
.build();
}
@PreDestroy
public void shutdown() {
managedChannel.shutdownNow();
}
@Override
public ManagedChannel get() {
return managedChannel;
}
}
}
| 394 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/titusmaster/LeaderNameResolverFactory.java | /*
* Copyright 2018 Netflix, 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.netflix.titus.runtime.connector.titusmaster;
import java.net.URI;
import com.netflix.titus.common.runtime.TitusRuntime;
import io.grpc.Attributes;
import io.grpc.NameResolver;
public final class LeaderNameResolverFactory extends NameResolver.Factory {
private static final String SCHEME = "leader";
private final LeaderResolver leaderResolver;
private final int port;
private final TitusRuntime titusRuntime;
public LeaderNameResolverFactory(LeaderResolver leaderResolver, int port, TitusRuntime titusRuntime) {
this.leaderResolver = leaderResolver;
this.port = port;
this.titusRuntime = titusRuntime;
}
@Override
public LeaderNameResolver newNameResolver(URI targetUri, NameResolver.Args args) {
if (SCHEME.equals(targetUri.getScheme())) {
return new LeaderNameResolver(targetUri, leaderResolver, port, titusRuntime);
} else {
return null;
}
}
@Override
public String getDefaultScheme() {
return SCHEME;
}
}
| 395 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/prediction/JobRuntimePredictions.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.connector.prediction;
import java.util.Collection;
import java.util.Optional;
import java.util.SortedSet;
import com.netflix.titus.common.util.CollectionsExt;
public class JobRuntimePredictions {
private final String version;
private final String modelId;
private final SortedSet<JobRuntimePrediction> predictions;
private final Optional<String> simpleStringRepresentation;
public JobRuntimePredictions(String version, String modelId, SortedSet<JobRuntimePrediction> predictions) {
this.version = version;
this.modelId = modelId;
this.predictions = predictions;
this.simpleStringRepresentation = buildSimpleString(predictions);
}
public String getVersion() {
return version;
}
public String getModelId() {
return modelId;
}
public SortedSet<JobRuntimePrediction> getPredictions() {
return predictions;
}
/**
* One line representation of all predictions in seconds, and their confidence percentile, e.g.:
* <tt>0.1=10.0;0.2=15.1;0.9=40.5</tt>
*/
public Optional<String> toSimpleString() {
return simpleStringRepresentation;
}
@Override
public String toString() {
return "JobRuntimePredictions{" +
"version='" + version + '\'' +
", modelId='" + modelId + '\'' +
", predictions=" + predictions +
'}';
}
private static Optional<String> buildSimpleString(Collection<JobRuntimePrediction> predictions) {
if (CollectionsExt.isNullOrEmpty(predictions)) {
return Optional.empty();
}
StringBuilder builder = new StringBuilder();
boolean first = true;
for (JobRuntimePrediction prediction : predictions) {
if (first) {
first = false;
} else {
builder.append(';');
}
builder.append(prediction.getConfidence()).append('=').append(prediction.getRuntimeInSeconds());
}
return Optional.of(builder.toString());
}
}
| 396 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/prediction/JobRuntimePredictionClient.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.connector.prediction;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import reactor.core.publisher.Mono;
/**
* Client for the service providing runtime predictions for Titus (batch) jobs.
*/
public interface JobRuntimePredictionClient {
/**
* @param jobDescriptor to run predictions on
* @return a sorted collection of predictions, from lower to higher quality
*/
Mono<JobRuntimePredictions> getRuntimePredictions(JobDescriptor jobDescriptor);
}
| 397 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/prediction/EmptyJobRuntimePredictionClient.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.connector.prediction;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import reactor.core.publisher.Mono;
public class EmptyJobRuntimePredictionClient implements JobRuntimePredictionClient {
@Override
public Mono<JobRuntimePredictions> getRuntimePredictions(JobDescriptor jobDescriptor) {
return Mono.empty();
}
}
| 398 |
0 | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector | Create_ds/titus-control-plane/titus-server-runtime/src/main/java/com/netflix/titus/runtime/connector/prediction/JobRuntimePrediction.java | /*
* Copyright 2019 Netflix, 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.netflix.titus.runtime.connector.prediction;
public class JobRuntimePrediction implements Comparable<JobRuntimePrediction> {
private final double confidence;
private final double runtimeInSeconds;
public JobRuntimePrediction(double confidence, double runtime) {
this.confidence = confidence;
this.runtimeInSeconds = runtime;
}
/**
* Statistical confidence associated with the runtimeInSeconds prediction, e.g.: 95% confidence will be 0.95
*/
public double getConfidence() {
return confidence;
}
/**
* Predicted job runtime, in seconds
*/
public double getRuntimeInSeconds() {
return runtimeInSeconds;
}
/**
* Predictions are ordered according to their quality (lower to higher):
*
* <ul>
* <li>Higher confidence means higher quality</li>
* <li>For the same confidence (a tie), a higher runtimeInSeconds prediction is safer and has higher quality</li>
* </ul>
*/
@Override
public int compareTo(JobRuntimePrediction other) {
int confidenceComparison = Double.compare(this.confidence, other.confidence);
if (confidenceComparison != 0) {
return confidenceComparison;
}
return Double.compare(this.runtimeInSeconds, other.runtimeInSeconds);
}
@Override
public String toString() {
return "JobRuntimePrediction{" +
"confidence=" + confidence +
", runtimeInSeconds=" + runtimeInSeconds +
'}';
}
}
| 399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.