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/genie/genie-ui/src/test/java/com/netflix/genie/ui | Create_ds/genie/genie-ui/src/test/java/com/netflix/genie/ui/controllers/package-info.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.
*
*/
/**
* Tests for MVC controllers.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.ui.controllers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,300 |
0 | Create_ds/genie/genie-ui/src/main/java/com/netflix/genie/ui | Create_ds/genie/genie-ui/src/main/java/com/netflix/genie/ui/controllers/UserRestController.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.genie.ui.controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
/**
* A helper {@link RestController} which allows the UI to request information about the current user.
*
* @author tgianos
* @since 4.0.0
*/
@RestController
@RequestMapping(path = "/ui/user", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserRestController {
static final String NAME_KEY = "name";
static final String DEFAULT_USER = "user@genie";
/**
* Get the information about the current session user.
*
* @param request The http request to get a principal from
* @return The user information as a JSON object
*/
@GetMapping
public JsonNode getUserInfo(final HttpServletRequest request) {
final Principal principal = request.getUserPrincipal();
return JsonNodeFactory.instance
.objectNode()
.set(NAME_KEY, JsonNodeFactory.instance.textNode(principal == null ? DEFAULT_USER : principal.getName()));
}
}
| 2,301 |
0 | Create_ds/genie/genie-ui/src/main/java/com/netflix/genie/ui | Create_ds/genie/genie-ui/src/main/java/com/netflix/genie/ui/controllers/UIController.java | /*
*
* Copyright 2016 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.genie.ui.controllers;
import com.netflix.genie.web.apis.rest.v3.controllers.ControllerUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Controller for forwarding UI requests.
*
* @author tgianos
* @since 3.0.0
*/
@Controller
public class UIController {
/**
* Return the getIndex.html template for requests to root.
*
* @return The index page
*/
@GetMapping(
value = {
"/",
"/applications/**",
"/clusters/**",
"/commands/**",
"/jobs/**",
"/output/**"
}
)
public String getIndex() {
return "index";
}
/**
* Forward the file request to the API.
*
* @param id The id of the job
* @param request the servlet request to get path information from
* @return The forward address to go to at the API endpoint
* @throws UnsupportedEncodingException if URL-encoding of the job id fails
*/
@GetMapping(value = "/file/{id}/**")
public String getFile(
@PathVariable("id") final String id,
final HttpServletRequest request
) throws UnsupportedEncodingException {
// When forwarding, the downstream ApplicationContext will perform URL decoding.
// If the job ID contains special characters (such as '+'), they will be interpreted as url-encoded and
// decoded, resulting in an invalid job ID that cannot be found.
// To prevent this, always perform URL encoding on the ID before forwarding.
final String encodedId = URLEncoder.encode(id, "UTF-8");
final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request);
return "forward:" + path;
}
}
| 2,302 |
0 | Create_ds/genie/genie-ui/src/main/java/com/netflix/genie/ui | Create_ds/genie/genie-ui/src/main/java/com/netflix/genie/ui/controllers/package-info.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.
*
*/
/**
* Controllers for MVC.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.ui.controllers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,303 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/GenieClientIntegrationTest.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.genie.client;
/**
* Aggregate class for all the integration tests for the clients.
* <p>
* NOTE: This is done so that the single Genie test container can be reused throughout the tests and save time.
* The way the classes extend from each other gives it ordering that {@literal @Nested} didn't seem to accomplish.
* Since resources attached to jobs can't be deleted executing the job test(s) last makes it so that the previous
* tests can maintain their functionality without completely re-writing them.
*
* @author tgianos
* @since 4.0.0
*/
class GenieClientIntegrationTest extends JobClientIntegrationTest {
}
| 2,304 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/ApplicationClientIntegrationTest.java | /*
*
* Copyright 2015 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.genie.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.JsonPatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
* Integration tests for {@link ApplicationClient}.
*
* @author amsharma
*/
abstract class ApplicationClientIntegrationTest extends GenieClientIntegrationTestBase {
@Test
void testCanCreateAndGetApplication() throws Exception {
final String id = UUID.randomUUID().toString();
final Application application = this.constructApplicationDTO(id);
final String applicationId = this.applicationClient.createApplication(application);
Assertions.assertThat(applicationId).isEqualTo(id);
// Make sure Genie Not Found Exception is not thrown for this call.
final Application app2 = this.applicationClient.getApplication(id);
// Make sure the object returned is exactly what was sent to be created
Assertions.assertThat(application.getId()).isEqualTo(app2.getId());
Assertions.assertThat(application.getName()).isEqualTo(app2.getName());
Assertions.assertThat(application.getDescription()).isEqualTo(app2.getDescription());
Assertions.assertThat(application.getConfigs()).isEqualTo(app2.getConfigs());
Assertions.assertThat(application.getSetupFile()).isEqualTo(app2.getSetupFile());
Assertions.assertThat(application.getTags()).contains("foo", "bar");
Assertions.assertThat(application.getStatus()).isEqualTo(app2.getStatus());
}
@Test
void testGetApplicationsUsingParams() throws Exception {
final String application1Id = UUID.randomUUID().toString();
final String application2Id = UUID.randomUUID().toString();
final Set<String> application1Tags = Sets.newHashSet("foo", "pi");
final Set<String> application2Tags = Sets.newHashSet("bar", "pi");
final Application application1 = new Application.Builder(
"application1name",
"application1user",
"1.0",
ApplicationStatus.ACTIVE
)
.withId(application1Id)
.withTags(application1Tags)
.build();
final Application application2 =
new Application.Builder(
"application2name",
"application2user",
"2.0",
ApplicationStatus.INACTIVE
)
.withId(application2Id)
.withTags(application2Tags)
.build();
this.applicationClient.createApplication(application1);
this.applicationClient.createApplication(application2);
// Test get by tags
List<Application> applicationList = this.applicationClient.getApplications(
null,
null,
null,
Lists.newArrayList("foo"),
null
);
Assertions
.assertThat(applicationList)
.hasSize(1)
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(application1Id);
applicationList = this.applicationClient.getApplications(
null,
null,
null,
Lists.newArrayList("pi"),
null
);
Assertions
.assertThat(applicationList)
.hasSize(2)
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(application2Id, application1Id);
// Test get by name
applicationList = this.applicationClient.getApplications(
"application1name",
null,
null,
null,
null
);
Assertions
.assertThat(applicationList)
.hasSize(1)
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(application1Id);
// Test get by status
applicationList = this.applicationClient.getApplications(
null,
null,
Lists.newArrayList(ApplicationStatus.ACTIVE.toString()),
null,
null
);
Assertions
.assertThat(applicationList)
.hasSize(1)
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(application1Id);
applicationList = this.applicationClient.getApplications(
null,
null,
Arrays.asList(ApplicationStatus.ACTIVE.toString(), ApplicationStatus.INACTIVE.toString()),
null,
null
);
Assertions
.assertThat(applicationList)
.hasSize(2)
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactlyInAnyOrder(application1Id, application2Id);
}
@Test
void testGetApplicationsUsingPagination() throws Exception {
final String id1 = UUID.randomUUID() + "_1";
final String id2 = UUID.randomUUID() + "_2";
final String id3 = UUID.randomUUID() + "_3";
final List<String> ids = Lists.newArrayList(id1, id2, id3);
for (final String id : ids) {
final Application application = new Application.Builder(
"ApplicationName",
"user",
"1.0",
ApplicationStatus.ACTIVE
)
.withId(id)
.withTags(Sets.newHashSet("foo", "bar"))
.build();
this.applicationClient.createApplication(application);
}
final List<Application> results = this.applicationClient.getApplications(
null,
null,
null,
null,
null,
null,
null,
null,
null
);
Assertions.assertThat(results).hasSize(3);
Assertions.assertThat(
results.stream()
.map(Application::getId)
.filter(Optional::isPresent)
.map(Optional::get)
).containsExactlyInAnyOrder(id1, id2, id3);
// Paginate, 1 result per page
for (int i = 0; i < ids.size(); i++) {
final List<Application> page = this.applicationClient.getApplications(
null,
null,
null,
null,
null,
1,
SortAttribute.UPDATED,
SortDirection.ASC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId().orElse(null)).isEqualTo(ids.get(i));
}
// Paginate, 1 result per page, reverse order
Collections.reverse(ids);
for (int i = 0; i < ids.size(); i++) {
final List<Application> page = this.applicationClient.getApplications(
null,
null,
null,
null,
null,
1,
SortAttribute.UPDATED,
SortDirection.DESC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId().orElse(null)).isEqualTo(ids.get(i));
}
// Ask for page beyond end of results
Assertions.assertThat(
this.applicationClient.getApplications(
null,
null,
null,
null,
null,
3,
null,
null,
1
)
).isEmpty();
}
@Test
void testApplicationNotExist() {
Assertions.assertThatIOException().isThrownBy(() -> this.applicationClient.getApplication("foo"));
}
@Test
void testGetAllAndDeleteAllApplications() throws Exception {
final List<Application> initialApplicationList = this.applicationClient.getApplications();
Assertions.assertThat(initialApplicationList).isEmpty();
final Application application1 = constructApplicationDTO(null);
final Application application2 = constructApplicationDTO(null);
final String app1Id = this.applicationClient.createApplication(application1);
final String app2Id = this.applicationClient.createApplication(application2);
final List<Application> finalApplicationList = this.applicationClient.getApplications();
Assertions.assertThat(finalApplicationList).hasSize(2)
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(app2Id, app1Id);
this.applicationClient.deleteAllApplications();
Assertions.assertThat(this.applicationClient.getApplications()).isEmpty();
}
@Test
void testDeleteApplication() throws Exception {
final Application application1 = constructApplicationDTO(null);
final String appId1 = this.applicationClient.createApplication(application1);
final Application application2 = this.applicationClient.getApplication(appId1);
Assertions.assertThat(application2.getId()).isPresent().contains(appId1);
this.applicationClient.deleteApplication(appId1);
Assertions.assertThatIOException().isThrownBy(() -> this.applicationClient.getApplication(appId1));
}
@Test
void testUpdateApplication() throws Exception {
final Application application1 = constructApplicationDTO(null);
final String app1Id = this.applicationClient.createApplication(application1);
final Application application2 = this.applicationClient.getApplication(app1Id);
Assertions.assertThat(application2.getName()).isEqualTo(application1.getName());
final Application application3 = new Application.Builder(
"newname",
"newuser",
"new version",
ApplicationStatus.ACTIVE
)
.withId(app1Id)
.build();
this.applicationClient.updateApplication(app1Id, application3);
final Application application4 = this.applicationClient.getApplication(app1Id);
Assertions.assertThat(application4.getName()).isEqualTo("newname");
Assertions.assertThat(application4.getUser()).isEqualTo("newuser");
Assertions.assertThat(application4.getVersion()).isEqualTo("new version");
Assertions.assertThat(application4.getStatus()).isEqualByComparingTo(ApplicationStatus.ACTIVE);
Assertions.assertThat(application4.getSetupFile()).isNotPresent();
Assertions.assertThat(application4.getDescription()).isNotPresent();
Assertions.assertThat(application4.getConfigs()).isEmpty();
Assertions.assertThat(application4.getTags()).doesNotContain("foo");
}
@Test
void testApplicationTagsMethods() throws Exception {
final Set<String> initialTags = Sets.newHashSet("foo", "bar");
final Application application = new Application.Builder("name", "user", "1.0", ApplicationStatus.ACTIVE)
.withTags(initialTags)
.build();
final String appId = this.applicationClient.createApplication(application);
// Test getTags for application
Assertions
.assertThat(this.applicationClient.getTagsForApplication(appId))
.hasSize(4)
.contains("foo", "bar");
// Test adding a tag for application
final Set<String> moreTags = Sets.newHashSet("pi");
this.applicationClient.addTagsToApplication(appId, moreTags);
Assertions
.assertThat(this.applicationClient.getTagsForApplication(appId))
.hasSize(5)
.contains("foo", "bar", "pi");
// Test removing a tag for application
this.applicationClient.removeTagFromApplication(appId, "bar");
Assertions
.assertThat(this.applicationClient.getTagsForApplication(appId))
.hasSize(4)
.doesNotContain("bar")
.contains("foo", "pi");
// Test update tags for a application
this.applicationClient.updateTagsForApplication(appId, initialTags);
Assertions
.assertThat(this.applicationClient.getTagsForApplication(appId))
.hasSize(4)
.contains("foo", "bar");
// Test delete all tags in a application
this.applicationClient.removeAllTagsForApplication(appId);
Assertions
.assertThat(this.applicationClient.getTagsForApplication(appId))
.hasSize(2)
.doesNotContain("foo", "bar");
}
@Test
void testApplicationConfigsMethods() throws Exception {
final Set<String> initialConfigs = Sets.newHashSet("foo", "bar");
final Application application = new Application.Builder("name", "user", "1.0", ApplicationStatus.ACTIVE)
.withConfigs(initialConfigs)
.build();
final String appId = this.applicationClient.createApplication(application);
// Test getConfigs for application
Assertions
.assertThat(this.applicationClient.getConfigsForApplication(appId))
.hasSize(2)
.contains("foo", "bar");
// Test adding a config to the application
final Set<String> moreConfigs = Sets.newHashSet("pi");
this.applicationClient.addConfigsToApplication(appId, moreConfigs);
Assertions
.assertThat(this.applicationClient.getConfigsForApplication(appId))
.hasSize(3)
.contains("foo", "bar", "pi");
// Test update configs for an application
this.applicationClient.updateConfigsForApplication(appId, initialConfigs);
Assertions
.assertThat(this.applicationClient.getConfigsForApplication(appId))
.hasSize(2)
.contains("foo", "bar");
// Test delete all configs for an application
this.applicationClient.removeAllConfigsForApplication(appId);
Assertions.assertThat(this.applicationClient.getConfigsForApplication(appId)).isEmpty();
}
@Test
void testApplicationDependenciesMethods() throws Exception {
final Set<String> initialDependencies = Sets.newHashSet("foo", "bar");
final Application application = new Application.Builder("name", "user", "1.0", ApplicationStatus.ACTIVE)
.withDependencies(initialDependencies)
.build();
final String appId = this.applicationClient.createApplication(application);
// Test getDependencies for application
Assertions
.assertThat(this.applicationClient.getDependenciesForApplication(appId))
.hasSize(2)
.contains("foo", "bar");
// Test adding a dependency to the application
final Set<String> moreDependencies = Sets.newHashSet("pi");
this.applicationClient.addDependenciesToApplication(appId, moreDependencies);
Assertions
.assertThat(this.applicationClient.getDependenciesForApplication(appId))
.hasSize(3)
.contains("foo", "bar", "pi");
// Test update dependencies for an application
this.applicationClient.updateDependenciesForApplication(appId, initialDependencies);
Assertions
.assertThat(this.applicationClient.getDependenciesForApplication(appId))
.hasSize(2)
.contains("foo", "bar");
// Test delete all dependencies for an application
this.applicationClient.removeAllDependenciesForApplication(appId);
Assertions.assertThat(this.applicationClient.getDependenciesForApplication(appId)).isEmpty();
}
@Test
void testApplicationPatchMethod() throws Exception {
final ObjectMapper mapper = GenieObjectMapper.getMapper();
final String newName = UUID.randomUUID().toString();
final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
final JsonPatch patch = JsonPatch.fromJson(mapper.readTree(patchString));
final Application application = this.constructApplicationDTO("application1");
final String appId = this.applicationClient.createApplication(application);
this.applicationClient.patchApplication(appId, patch);
Assertions
.assertThat(this.applicationClient.getApplication(appId))
.extracting(Application::getName)
.isEqualTo(newName);
}
@Test
void testCanGetCommandsForApplication() throws Exception {
final Command command1 = constructCommandDTO(null);
final Command command2 = constructCommandDTO(null);
final String command1Id = this.commandClient.createCommand(command1);
final String command2Id = this.commandClient.createCommand(command2);
final Application application = constructApplicationDTO(null);
final String appId = this.applicationClient.createApplication(application);
this.commandClient.addApplicationsToCommand(command1Id, Lists.newArrayList(appId));
this.commandClient.addApplicationsToCommand(command2Id, Lists.newArrayList(appId));
Assertions
.assertThat(this.applicationClient.getCommandsForApplication(appId))
.hasSize(2)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.contains(command1Id, command2Id);
}
}
| 2,305 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/GenieClientIntegrationTestBase.java | /*
*
* Copyright 2016 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.genie.client;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import retrofit2.Retrofit;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Base class for all Genie client integration tests.
*
* @author amsharma
* @since 3.0.0
*/
@Testcontainers(disabledWithoutDocker = true)
@SuppressWarnings(
{
"rawtypes"
}
)
abstract class GenieClientIntegrationTestBase {
// Note: Attempt made to make this use the version currently under build however the gradle compiler avoidance
// doesn't work right and generates new images every test / build run. This leaves a lot of orphaned
// layers on the developers machine which takes up a lot of space. Not currently worth the gain.
// Also passing in environment variable from gradle file wasn't being picked up properly in IDE tests for some
// reason. For now just leave it hardcoded as the `latest` tags float anyway. This does become problem
// for making builds repeatable on tags long term though so it might be better to just periodically update
// a static tagged image if we can't get local docker images to reproduce without disk usage overhead.
// TODO: Improve genie-app image packaging to leverage unpacked (application plugin) based agent so that startup
// is faster as in agent mode the tests are much slower than embedded. Also once we move to boot 2.3 we can
// leverage their layered jars to produce less changing images.
@Container
private static final GenericContainer GENIE = new GenericContainer("netflixoss/genie-app:latest.release")
.waitingFor(Wait.forHttp("/admin/health").forStatusCode(200).withStartupTimeout(Duration.ofMinutes(1L)))
.withExposedPorts(8080);
protected ApplicationClient applicationClient;
protected CommandClient commandClient;
protected ClusterClient clusterClient;
protected JobClient jobClient;
@BeforeEach
void setup() throws Exception {
// Just run these once but don't make it a static BeforeAll in case it would be executed before container starts
if (
this.applicationClient == null
|| this.commandClient == null
|| this.clusterClient == null
|| this.jobClient == null
) {
final String baseUrl = "http://" + GENIE.getContainerIpAddress() + ":" + GENIE.getFirstMappedPort();
final Retrofit retrofit = GenieClientUtils.createRetrofitInstance(baseUrl, null, null);
if (this.applicationClient == null) {
this.applicationClient = new ApplicationClient(retrofit);
}
if (this.commandClient == null) {
this.commandClient = new CommandClient(retrofit);
}
if (this.clusterClient == null) {
this.clusterClient = new ClusterClient(retrofit);
}
if (this.jobClient == null) {
this.jobClient = new JobClient(retrofit, 3);
}
}
}
@AfterEach
void cleanup() {
try {
this.clusterClient.deleteAllClusters();
this.commandClient.deleteAllCommands();
this.applicationClient.deleteAllApplications();
} catch (final Exception e) {
// swallow
}
}
Cluster constructClusterDTO(final String id) {
final String clusterId;
if (StringUtils.isBlank(id)) {
clusterId = UUID.randomUUID().toString();
} else {
clusterId = id;
}
final Set<String> tags = Sets.newHashSet("foo", "bar");
final Set<String> configList = Sets.newHashSet("config1", "configs2");
final Set<String> dependenciesList = Sets.newHashSet("cluster-dep1", "cluster-dep2");
return new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP)
.withId(clusterId)
.withDescription("client Test")
.withSetupFile("path to set up file")
.withTags(tags)
.withConfigs(configList)
.withDependencies(dependenciesList)
.build();
}
Command constructCommandDTO(final String id) {
final String commandId;
if (StringUtils.isBlank(id)) {
commandId = UUID.randomUUID().toString();
} else {
commandId = id;
}
final Set<String> tags = Sets.newHashSet("foo", "bar");
final Set<String> configList = Sets.newHashSet("config1", "configs2");
final Set<String> dependenciesList = Sets.newHashSet("command-dep1", "command-dep2");
final List<String> executableAndArgs = Lists.newArrayList("exec");
return new Command.Builder("name", "user", "1.0", CommandStatus.ACTIVE, executableAndArgs)
.withId(commandId)
.withDescription("client Test")
.withSetupFile("path to set up file")
.withTags(tags)
.withConfigs(configList)
.withDependencies(dependenciesList)
.build();
}
Application constructApplicationDTO(final String id) {
final String applicationId;
if (StringUtils.isBlank(id)) {
applicationId = UUID.randomUUID().toString();
} else {
applicationId = id;
}
final Set<String> tags = Sets.newHashSet("foo", "bar");
final Set<String> configList = Sets.newHashSet("config1", "configs2");
final Set<String> dependenciesList = Sets.newHashSet("dep1", "dep2");
return new Application.Builder("name", "user", "1.0", ApplicationStatus.ACTIVE)
.withId(applicationId)
.withDescription("client Test")
.withSetupFile("path to set up file")
.withTags(tags)
.withConfigs(configList)
.withDependencies(dependenciesList)
.build();
}
}
| 2,306 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/JobClientIntegrationTest.java | /*
*
* Copyright 2015 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.genie.client;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterCriteria;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.dto.Criterion;
import com.netflix.genie.common.dto.JobRequest;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.dto.search.JobSearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
/**
* Integration tests for {@link JobClient}.
*
* @author amsharma
* @since 3.0.0
*/
@Slf4j
abstract class JobClientIntegrationTest extends ClusterClientIntegrationTest {
private static final String DATE_TAG = "type:date";
private static final String ECHO_TAG = "type:echo";
private static final String SLEEP_TAG = "type:sleep";
private static final String DUMMY_TAG = "type:dummy";
@SuppressWarnings("MethodLength")
@Test
void canSubmitJob() throws Exception {
final String dummyClusterId = this.createDummyCluster();
final String sleepCommandId = this.createSleepCommand();
final String dateCommandId = this.createDateCommand();
final String echoCommandId = this.createEchoCommand();
final List<ClusterCriteria> clusterCriteriaList = Lists.newArrayList(
new ClusterCriteria(Sets.newHashSet(DUMMY_TAG))
);
final JobRequest sleepJob = new JobRequest.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
clusterCriteriaList,
Sets.newHashSet(SLEEP_TAG)
)
.withCommandArgs(Lists.newArrayList("1"))
.withDisableLogArchival(true)
.build();
final JobRequest killJob = new JobRequest.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
clusterCriteriaList,
Sets.newHashSet(SLEEP_TAG)
)
.withCommandArgs(Lists.newArrayList("60"))
.withDisableLogArchival(true)
.build();
final JobRequest timeoutJob = new JobRequest.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
clusterCriteriaList,
Sets.newHashSet(SLEEP_TAG)
)
.withCommandArgs(Lists.newArrayList("60"))
.withTimeout(1)
.withDisableLogArchival(true)
.build();
final JobRequest dateJob = new JobRequest.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
clusterCriteriaList,
Sets.newHashSet(DATE_TAG)
)
.withDisableLogArchival(true)
.build();
final JobRequest echoJob = new JobRequest.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
clusterCriteriaList,
Sets.newHashSet(ECHO_TAG)
)
.withCommandArgs(Lists.newArrayList("hello"))
.withDisableLogArchival(true)
.build();
final String sleepJobId;
final byte[] attachmentBytes = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
try (ByteArrayInputStream bis = new ByteArrayInputStream(attachmentBytes)) {
final Map<String, InputStream> attachments = ImmutableMap.of("attachment.txt", bis);
sleepJobId = this.jobClient.submitJobWithAttachments(sleepJob, attachments);
}
final String killJobId = this.jobClient.submitJob(killJob);
final Thread killThread = new Thread(
() -> {
try {
while (this.jobClient.getJobStatus(killJobId) != JobStatus.RUNNING) {
Thread.sleep(10);
}
this.jobClient.killJob(killJobId);
} catch (final Exception e) {
Assertions.fail(e.getMessage(), e);
}
}
);
killThread.start();
final String timeoutJobId = this.jobClient.submitJob(timeoutJob);
final String dateJobId = this.jobClient.submitJob(dateJob);
final String echoJobId = this.jobClient.submitJob(echoJob);
final Map<String, JobStatus> expectedStatuses = ImmutableMap.<String, JobStatus>builder()
.put(sleepJobId, JobStatus.SUCCEEDED)
.put(killJobId, JobStatus.KILLED)
.put(timeoutJobId, JobStatus.KILLED)
.put(dateJobId, JobStatus.SUCCEEDED)
.put(echoJobId, JobStatus.SUCCEEDED)
.build();
final long waitStart = System.currentTimeMillis();
final long maxTotalWait = 120000;
for (final Map.Entry<String, JobStatus> entry : expectedStatuses.entrySet()) {
final String jobId = entry.getKey();
final JobStatus status = entry.getValue();
log.info("Waiting for job: {} (expected final status: {})", jobId, status.name());
final long timeElapsed = System.currentTimeMillis() - waitStart;
final long timeLeft = maxTotalWait - timeElapsed;
if (timeLeft <= 0) {
throw new TimeoutException("Timed out waiting for jobs to complete");
}
Assertions
.assertThat(this.jobClient.waitForCompletion(jobId, timeLeft, 100))
.isEqualByComparingTo(entry.getValue());
}
// Some basic checking of fields
Assertions.assertThat(this.jobClient.getJob(sleepJobId).getName()).isEqualTo(sleepJob.getName());
Assertions.assertThat(this.jobClient.getJobRequest(sleepJobId).getUser()).isEqualTo(sleepJob.getUser());
Assertions.assertThat(this.jobClient.getJobExecution(sleepJobId)).isNotNull();
Assertions.assertThat(this.jobClient.getJobMetadata(sleepJobId)).isNotNull();
Assertions.assertThat(this.jobClient.getJobCluster(sleepJobId).getId()).isPresent().contains(dummyClusterId);
Assertions.assertThat(this.jobClient.getJobCommand(sleepJobId).getId()).isPresent().contains(sleepCommandId);
Assertions.assertThat(this.jobClient.getJobCommand(dateJobId).getId()).isPresent().contains(dateCommandId);
Assertions.assertThat(this.jobClient.getJobCommand(echoJobId).getId()).isPresent().contains(echoCommandId);
Assertions.assertThat(this.jobClient.getJobApplications(sleepJobId)).isEmpty();
Assertions
.assertThat(IOUtils.toString(this.jobClient.getJobStdout(echoJobId), StandardCharsets.UTF_8))
.isEqualTo("hello\n");
Assertions
.assertThat(IOUtils.toString(this.jobClient.getJobStdout(echoJobId, null, null), StandardCharsets.UTF_8))
.isEqualTo("hello\n");
Assertions
.assertThat(IOUtils.toString(this.jobClient.getJobStdout(echoJobId, 4L, null), StandardCharsets.UTF_8))
.isEqualTo("o\n");
Assertions
.assertThat(IOUtils.toString(this.jobClient.getJobStdout(echoJobId, 0L, 3L), StandardCharsets.UTF_8))
.isEqualTo("hell");
Assertions
.assertThat(IOUtils.toString(this.jobClient.getJobStdout(echoJobId, null, 2L), StandardCharsets.UTF_8))
.isEqualTo("o\n");
Assertions
.assertThat(IOUtils.toString(this.jobClient.getJobStderr(echoJobId), StandardCharsets.UTF_8))
.isBlank();
Assertions
.assertThat(IOUtils.toString(
this.jobClient.getJobOutputFile(echoJobId, "stdout"), StandardCharsets.UTF_8))
.isEqualTo("hello\n");
Assertions
.assertThat(IOUtils.toString(
this.jobClient.getJobOutputFile(echoJobId, "run"), StandardCharsets.UTF_8))
.isNotBlank();
Assertions
.assertThat(IOUtils.toString(
this.jobClient.getJobOutputFile(echoJobId, ""), StandardCharsets.UTF_8))
.isNotBlank();
Assertions
.assertThat(IOUtils.toString(
this.jobClient.getJobOutputFile(echoJobId, null), StandardCharsets.UTF_8))
.isNotBlank();
// Some quick find jobs calls
Assertions
.assertThat(this.jobClient.getJobs())
.extracting(JobSearchResult::getId)
.containsExactlyInAnyOrder(sleepJobId, killJobId, timeoutJobId, dateJobId, echoJobId);
Assertions
.assertThat(
this.jobClient.getJobs(
null,
null,
null,
null,
null,
null,
null,
null,
echoCommandId,
null,
null,
null,
null,
null,
null
)
)
.extracting(JobSearchResult::getId)
.containsExactlyInAnyOrder(echoJobId);
Assertions
.assertThat(
this.jobClient.getJobs(
null,
null,
null,
Sets.newHashSet(JobStatus.KILLED.name()),
null,
null,
null,
null,
null,
null,
null,
null,
null
)
)
.extracting(JobSearchResult::getId)
.containsExactlyInAnyOrder(killJobId, timeoutJobId);
final List<String> ids = Lists.newArrayList(sleepJobId, killJobId, timeoutJobId, dateJobId, echoJobId);
// Paginate, 1 result per page
for (int i = 0; i < ids.size(); i++) {
final List<JobSearchResult> page = this.jobClient.getJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
1,
SortAttribute.CREATED,
SortDirection.ASC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId()).isEqualTo(ids.get(i));
}
// Paginate, 1 result per page, reverse order
Collections.reverse(ids);
for (int i = 0; i < ids.size(); i++) {
final List<JobSearchResult> page = this.jobClient.getJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
1,
SortAttribute.CREATED,
SortDirection.DESC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId()).isEqualTo(ids.get(i));
}
// Ask for page beyond end of results
Assertions.assertThat(
this.jobClient.getJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
10,
SortAttribute.CREATED,
SortDirection.DESC,
1
)
).isEmpty();
}
private String createDummyCluster() throws Exception {
return this.clusterClient.createCluster(
new Cluster.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
ClusterStatus.UP
)
.withTags(Sets.newHashSet(DUMMY_TAG, UUID.randomUUID().toString()))
.build()
);
}
private String createSleepCommand() throws Exception {
return this.commandClient.createCommand(
new Command.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
CommandStatus.ACTIVE,
Lists.newArrayList("sleep")
)
.withTags(Sets.newHashSet(SLEEP_TAG, UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.withMemory(128)
.withClusterCriteria(
Lists.newArrayList(
new Criterion.Builder().withTags(Sets.newHashSet(DUMMY_TAG)).build()
)
)
.build()
);
}
private String createDateCommand() throws Exception {
return this.commandClient.createCommand(
new Command.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
CommandStatus.ACTIVE,
Lists.newArrayList("date")
)
.withTags(Sets.newHashSet(DATE_TAG, UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.withMemory(128)
.withClusterCriteria(
Lists.newArrayList(new Criterion.Builder().withTags(Sets.newHashSet(DUMMY_TAG)).build())
)
.build()
);
}
private String createEchoCommand() throws Exception {
return this.commandClient.createCommand(
new Command.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
CommandStatus.ACTIVE,
Lists.newArrayList("echo"),
100
)
.withTags(Sets.newHashSet(ECHO_TAG, UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.withMemory(128)
.withClusterCriteria(
Lists.newArrayList(new Criterion.Builder().withTags(Sets.newHashSet(DUMMY_TAG)).build())
)
.build()
);
}
}
| 2,307 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/ClusterClientIntegrationTest.java | /*
*
* Copyright 2015 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.genie.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.JsonPatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
* Integration tests for {@link ClusterClient}.
*
* @author amsharma
*/
abstract class ClusterClientIntegrationTest extends CommandClientIntegrationTest {
@Test
void testGetClustersUsingPagination() throws Exception {
final String id1 = UUID.randomUUID() + "_1";
final String id2 = UUID.randomUUID() + "_2";
final String id3 = UUID.randomUUID() + "_3";
final List<String> ids = Lists.newArrayList(id1, id2, id3);
for (final String id : ids) {
final Cluster cluster = new Cluster.Builder(
"ClusterName",
"cluster-user",
"1.0",
ClusterStatus.UP
)
.withId(id)
.build();
this.clusterClient.createCluster(cluster);
}
final List<Cluster> results = this.clusterClient.getClusters(
null,
null,
null,
null,
null,
null,
null,
null,
null
);
Assertions.assertThat(results).hasSize(3);
Assertions.assertThat(
results.stream()
.map(Cluster::getId)
.filter(Optional::isPresent)
.map(Optional::get)
).containsExactlyInAnyOrder(id1, id2, id3);
// Paginate, 1 result per page
for (int i = 0; i < ids.size(); i++) {
final List<Cluster> page = this.clusterClient.getClusters(
null,
null,
null,
null,
null,
1,
SortAttribute.UPDATED,
SortDirection.ASC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId().orElse(null)).isEqualTo(ids.get(i));
}
// Paginate, 1 result per page, reverse order
Collections.reverse(ids);
for (int i = 0; i < ids.size(); i++) {
final List<Cluster> page = this.clusterClient.getClusters(
null,
null,
null,
null,
null,
1,
SortAttribute.UPDATED,
SortDirection.DESC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId().orElse(null)).isEqualTo(ids.get(i));
}
// Ask for page beyond end of results
Assertions.assertThat(
this.clusterClient.getClusters(
null,
null,
null,
null,
null,
3,
null,
null,
1
)
).isEmpty();
}
@Test
void testUpdateCluster() throws Exception {
final Cluster cluster1 = constructClusterDTO(null);
final String cluster1Id = this.clusterClient.createCluster(cluster1);
final Cluster cluster2 = this.clusterClient.getCluster(cluster1Id);
Assertions.assertThat(cluster2.getName()).isEqualTo(cluster1.getName());
final Cluster cluster3 = new Cluster.Builder(
"newname",
"newuser",
"new version",
ClusterStatus.OUT_OF_SERVICE
)
.withId(cluster1Id)
.build();
this.clusterClient.updateCluster(cluster1Id, cluster3);
final Cluster cluster4 = this.clusterClient.getCluster(cluster1Id);
Assertions.assertThat(cluster4.getName()).isEqualTo("newname");
Assertions.assertThat(cluster4.getUser()).isEqualTo("newuser");
Assertions.assertThat(cluster4.getVersion()).isEqualTo("new version");
Assertions.assertThat(cluster4.getStatus()).isEqualByComparingTo(ClusterStatus.OUT_OF_SERVICE);
Assertions.assertThat(cluster4.getSetupFile()).isNotPresent();
Assertions.assertThat(cluster4.getDescription()).isNotPresent();
Assertions.assertThat(cluster4.getConfigs()).isEmpty();
Assertions.assertThat(cluster4.getTags()).doesNotContain("foo");
}
@Test
void testClusterTagsMethods() throws Exception {
final Set<String> initialTags = Sets.newHashSet("foo", "bar");
final Cluster cluster = new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP)
.withTags(initialTags)
.build();
final String clusterId = this.clusterClient.createCluster(cluster);
// Test getTags for cluster
Assertions.assertThat(this.clusterClient.getTagsForCluster(clusterId)).hasSize(4).contains("foo", "bar");
// Test adding a tag for cluster
final Set<String> moreTags = Sets.newHashSet("pi");
this.clusterClient.addTagsToCluster(clusterId, moreTags);
Assertions.assertThat(this.clusterClient.getTagsForCluster(clusterId)).hasSize(5).contains("foo", "bar", "pi");
// Test removing a tag for cluster
this.clusterClient.removeTagFromCluster(clusterId, "bar");
Assertions.assertThat(this.clusterClient.getTagsForCluster(clusterId)).hasSize(4).contains("foo", "pi");
// Test update tags for a cluster
this.clusterClient.updateTagsForCluster(clusterId, initialTags);
Assertions.assertThat(this.clusterClient.getTagsForCluster(clusterId)).hasSize(4).contains("foo", "bar");
// Test delete all tags in a cluster
this.clusterClient.removeAllTagsForCluster(clusterId);
Assertions.assertThat(this.clusterClient.getTagsForCluster(clusterId)).hasSize(2).doesNotContain("foo", "bar");
}
@Test
void testClusterConfigsMethods() throws Exception {
final Set<String> initialConfigs = Sets.newHashSet("foo", "bar");
final Cluster cluster = new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP)
.withConfigs(initialConfigs)
.build();
final String clusterId = this.clusterClient.createCluster(cluster);
// Test getConfigs for cluster
Assertions.assertThat(this.clusterClient.getConfigsForCluster(clusterId)).hasSize(2).contains("foo", "bar");
// Test adding a config for cluster
final Set<String> moreConfigs = Sets.newHashSet("pi");
this.clusterClient.addConfigsToCluster(clusterId, moreConfigs);
Assertions
.assertThat(this.clusterClient.getConfigsForCluster(clusterId))
.hasSize(3)
.contains("foo", "bar", "pi");
// Test update configs for a cluster
this.clusterClient.updateConfigsForCluster(clusterId, initialConfigs);
Assertions.assertThat(this.clusterClient.getConfigsForCluster(clusterId)).hasSize(2).contains("foo", "bar");
// Test delete all configs in a cluster
this.clusterClient.removeAllConfigsForCluster(clusterId);
Assertions.assertThat(this.clusterClient.getConfigsForCluster(clusterId)).isEmpty();
}
@Test
void testClusterDependenciesMethods() throws Exception {
final Set<String> initialDependencies = Sets.newHashSet("foo", "bar");
final Cluster cluster = new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP)
.withDependencies(initialDependencies)
.build();
final String clusterId = this.clusterClient.createCluster(cluster);
// Test getDependencies for cluster
Assertions
.assertThat(this.clusterClient.getDependenciesForCluster(clusterId))
.hasSize(2)
.contains("foo", "bar");
// Test adding a config for cluster
final Set<String> moreDependencies = Sets.newHashSet("pi");
this.clusterClient.addDependenciesToCluster(clusterId, moreDependencies);
Assertions
.assertThat(this.clusterClient.getDependenciesForCluster(clusterId))
.hasSize(3)
.contains("foo", "bar", "pi");
// Test update configs for a cluster
this.clusterClient.updateDependenciesForCluster(clusterId, initialDependencies);
Assertions
.assertThat(this.clusterClient.getDependenciesForCluster(clusterId))
.hasSize(2)
.contains("foo", "bar");
// Test delete all configs in a cluster
this.clusterClient.removeAllDependenciesForCluster(clusterId);
Assertions.assertThat(this.clusterClient.getDependenciesForCluster(clusterId)).isEmpty();
}
@Test
void testClusterCommandsMethods() throws Exception {
final List<String> executableAndArgs = Lists.newArrayList("exec");
final Command foo = new Command.Builder(
"name",
"user",
"version",
CommandStatus.ACTIVE,
executableAndArgs
).build();
final String fooId = this.commandClient.createCommand(foo);
final Command bar = new Command.Builder(
"name",
"user",
"version",
CommandStatus.ACTIVE,
executableAndArgs
).build();
final String barId = this.commandClient.createCommand(bar);
final Command pi = new Command.Builder(
"name",
"user",
"version",
CommandStatus.ACTIVE,
executableAndArgs
).build();
final String piId = this.commandClient.createCommand(pi);
final Cluster cluster = new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP).build();
final String clusterId = this.clusterClient.createCluster(cluster);
// Test add Commands to cluster
final List<String> initialCommands = Lists.newArrayList(fooId, barId, piId);
// These are all no-ops now so just make sure they don't throw exceptions
this.clusterClient.addCommandsToCluster(clusterId, initialCommands);
Assertions.assertThat(this.clusterClient.getCommandsForCluster(clusterId)).isEmpty();
this.clusterClient.removeCommandFromCluster(clusterId, barId);
Assertions.assertThat(this.clusterClient.getCommandsForCluster(clusterId)).isEmpty();
this.clusterClient.updateCommandsForCluster(clusterId, Lists.newArrayList(barId, fooId));
Assertions.assertThat(this.clusterClient.getCommandsForCluster(clusterId)).isEmpty();
this.clusterClient.removeAllCommandsForCluster(clusterId);
}
@Test
void testClusterPatchMethod() throws Exception {
final ObjectMapper mapper = GenieObjectMapper.getMapper();
final String newName = UUID.randomUUID().toString();
final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
final JsonPatch patch = JsonPatch.fromJson(mapper.readTree(patchString));
final Cluster cluster = new Cluster.Builder("name", "user", "1.0", ClusterStatus.UP).build();
final String clusterId = this.clusterClient.createCluster(cluster);
this.clusterClient.patchCluster(clusterId, patch);
Assertions.assertThat(this.clusterClient.getCluster(clusterId).getName()).isEqualTo(newName);
}
}
| 2,308 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/package-info.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.
*
*/
/**
* Integration tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
package com.netflix.genie.client;
| 2,309 |
0 | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie | Create_ds/genie/genie-client/src/integTest/java/com/netflix/genie/client/CommandClientIntegrationTest.java | /*
*
* Copyright 2015 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.genie.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.JsonPatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.dto.Criterion;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
* Integration Tests for {@link CommandClient}.
*
* @author amsharma
*/
abstract class CommandClientIntegrationTest extends ApplicationClientIntegrationTest {
@Test
void testCanCreateAndGetCommand() throws Exception {
final String id = UUID.randomUUID().toString();
final Command command = this.constructCommandDTO(id);
final String commandId = this.commandClient.createCommand(command);
Assertions.assertThat(commandId).isEqualTo(id);
// Make sure Genie Not Found Exception is not thrown for this call.
final Command cmd = this.commandClient.getCommand(id);
// Make sure the object returned is exactly what was sent to be created
Assertions.assertThat(cmd.getId()).isPresent().contains(id);
Assertions.assertThat(cmd.getName()).isEqualTo(command.getName());
Assertions.assertThat(cmd.getDescription()).isEqualTo(command.getDescription());
Assertions.assertThat(cmd.getConfigs()).isEqualTo(command.getConfigs());
Assertions.assertThat(cmd.getSetupFile()).isEqualTo(command.getSetupFile());
Assertions.assertThat(cmd.getTags()).contains("foo", "bar");
Assertions.assertThat(cmd.getStatus()).isEqualByComparingTo(command.getStatus());
}
@SuppressWarnings("deprecation")
@Test
void testGetCommandsUsingParams() throws Exception {
final Set<String> command1Tags = Sets.newHashSet("foo", "pi");
final Set<String> command2Tags = Sets.newHashSet("bar", "pi");
final List<String> executableAndArgs = Lists.newArrayList("exec");
final Command command1 = new Command.Builder(
"command1name",
"command1user",
"1.0",
CommandStatus.ACTIVE,
executableAndArgs,
1000
)
.withTags(command1Tags)
.build();
final Command command2 =
new Command.Builder(
"command2name",
"command2user",
"2.0",
CommandStatus.INACTIVE,
executableAndArgs
)
.withTags(command2Tags)
.build();
final String command1Id = this.commandClient.createCommand(command1);
final String command2Id = this.commandClient.createCommand(command2);
// Test get by tags
Assertions
.assertThat(
this.commandClient.getCommands(
null, null, null, Lists.newArrayList("foo"), null, null, null, null
)
)
.hasSize(1)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command1Id);
Assertions
.assertThat(
this.commandClient.getCommands(
null, null, null, Lists.newArrayList("pi"), null, null, null, null
)
)
.hasSize(2)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command2Id, command1Id);
// Test get by name
Assertions
.assertThat(
this.commandClient.getCommands(
"command1name", null, null, null, null, null, null, null
)
)
.hasSize(1)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command1Id);
// Test get by status
Assertions
.assertThat(
this.commandClient.getCommands(
null, null, Lists.newArrayList(CommandStatus.ACTIVE.toString()), null, null, null, null, null
)
)
.hasSize(1)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command1Id);
final List<String> statuses = Lists.newArrayList(
CommandStatus.ACTIVE.toString(),
CommandStatus.INACTIVE.toString()
);
Assertions
.assertThat(
this.commandClient.getCommands(
null, null, statuses, null, null, null, null, null
)
)
.hasSize(2)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command2Id, command1Id);
// Test find by user
Assertions
.assertThat(
this.commandClient.getCommands(
null, "command2user", null, null
)
)
.hasSize(1)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command2Id);
}
@Test
void testGetCommandsUsingPagination() throws Exception {
final String id1 = UUID.randomUUID() + "_1";
final String id2 = UUID.randomUUID() + "_2";
final String id3 = UUID.randomUUID() + "_3";
final List<String> ids = Lists.newArrayList(id1, id2, id3);
for (final String id : ids) {
final Command command = new Command.Builder(
"ClusterName",
"user",
"1.0",
CommandStatus.ACTIVE,
Lists.newArrayList("echo")
)
.withId(id)
.withTags(Sets.newHashSet("foo", "bar"))
.build();
this.commandClient.createCommand(command);
}
final List<Command> results = this.commandClient.getCommands(
null,
null,
null,
null,
null,
null,
null,
null
);
Assertions.assertThat(results).hasSize(3);
Assertions.assertThat(
results.stream()
.map(Command::getId)
.filter(Optional::isPresent)
.map(Optional::get)
).containsExactlyInAnyOrder(id1, id2, id3);
// Paginate, 1 result per page
for (int i = 0; i < ids.size(); i++) {
final List<Command> page = this.commandClient.getCommands(
null,
null,
null,
null,
1,
SortAttribute.UPDATED,
SortDirection.ASC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId().orElse(null)).isEqualTo(ids.get(i));
}
// Paginate, 1 result per page, reverse order
Collections.reverse(ids);
for (int i = 0; i < ids.size(); i++) {
final List<Command> page = this.commandClient.getCommands(
null,
null,
null,
null,
1,
SortAttribute.UPDATED,
SortDirection.DESC,
i
);
Assertions.assertThat(page.size()).isEqualTo(1);
Assertions.assertThat(page.get(0).getId().orElse(null)).isEqualTo(ids.get(i));
}
// Ask for page beyond end of results
Assertions.assertThat(
this.commandClient.getCommands(
null,
null,
null,
null,
3,
null,
null,
1
)
).isEmpty();
}
@Test
void testCommandNotExist() {
Assertions
.assertThatIOException()
.isThrownBy(() -> this.commandClient.getCommand(UUID.randomUUID().toString()));
}
@Test
void testGetAllAndDeleteAllCommands() throws Exception {
Assertions.assertThat(this.commandClient.getCommands()).isEmpty();
final Command command1 = this.constructCommandDTO(null);
final Command command2 = this.constructCommandDTO(null);
final String command1Id = this.commandClient.createCommand(command1);
final String command2Id = this.commandClient.createCommand(command2);
Assertions
.assertThat(this.commandClient.getCommands())
.hasSize(2)
.extracting(Command::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(command2Id, command1Id);
this.commandClient.deleteAllCommands();
Assertions.assertThat(this.commandClient.getCommands()).isEmpty();
}
@Test
void testDeleteCommand() throws Exception {
final Command command = this.constructCommandDTO(null);
final String commandId = this.commandClient.createCommand(command);
Assertions.assertThat(this.commandClient.getCommand(commandId).getId()).isPresent().contains(commandId);
this.commandClient.deleteCommand(commandId);
Assertions.assertThatIOException().isThrownBy(() -> this.commandClient.getCommand(commandId));
}
@Test
void testUpdateCommand() throws Exception {
final Command command1 = this.constructCommandDTO(null);
final String commandId = this.commandClient.createCommand(command1);
final Command command2 = this.commandClient.getCommand(commandId);
Assertions.assertThat(command2.getId()).isPresent().contains(commandId);
final List<String> executableAndArgs = Lists.newArrayList("exec");
final Command command3 = new Command.Builder(
"newname",
"newuser",
"new version",
CommandStatus.ACTIVE,
executableAndArgs
)
.withId(commandId)
.build();
this.commandClient.updateCommand(commandId, command3);
final Command command4 = this.commandClient.getCommand(commandId);
Assertions.assertThat(command4.getName()).isEqualTo("newname");
Assertions.assertThat(command4.getUser()).isEqualTo("newuser");
Assertions.assertThat(command4.getVersion()).isEqualTo("new version");
Assertions.assertThat(command4.getExecutableAndArguments()).isEqualTo(executableAndArgs);
Assertions.assertThat(command4.getStatus()).isEqualByComparingTo(CommandStatus.ACTIVE);
Assertions.assertThat(command4.getSetupFile()).isNotPresent();
Assertions.assertThat(command4.getDescription()).isNotPresent();
Assertions.assertThat(command4.getConfigs()).isEmpty();
Assertions.assertThat(command4.getTags()).doesNotContain("foo");
}
@Test
void testCommandTagsMethods() throws Exception {
final Set<String> initialTags = Sets.newHashSet("foo", "bar");
final List<String> executable = Lists.newArrayList("exec");
final Command command = new Command.Builder("name", "user", "1.0", CommandStatus.ACTIVE, executable)
.withTags(initialTags)
.build();
final String commandId = this.commandClient.createCommand(command);
// Test getTags for command
Assertions.assertThat(this.commandClient.getTagsForCommand(commandId)).hasSize(4).contains("foo", "bar");
// Test adding a tag for command
final Set<String> moreTags = Sets.newHashSet("pi");
this.commandClient.addTagsToCommand(commandId, moreTags);
Assertions.assertThat(this.commandClient.getTagsForCommand(commandId)).hasSize(5).contains("foo", "bar", "pi");
// Test removing a tag for command
this.commandClient.removeTagFromCommand(commandId, "bar");
Assertions.assertThat(this.commandClient.getTagsForCommand(commandId)).hasSize(4).contains("foo", "pi");
// Test update tags for a command
this.commandClient.updateTagsForCommand(commandId, initialTags);
Assertions.assertThat(this.commandClient.getTagsForCommand(commandId)).hasSize(4).contains("foo", "bar");
// Test delete all tags in a command
this.commandClient.removeAllTagsForCommand(commandId);
Assertions.assertThat(this.commandClient.getTagsForCommand(commandId)).hasSize(2);
}
@Test
void testCommandConfigsMethods() throws Exception {
final Set<String> initialConfigs = Sets.newHashSet("foo", "bar");
final List<String> executable = Lists.newArrayList("exec");
final Command command = new Command.Builder("name", "user", "1.0", CommandStatus.ACTIVE, executable)
.withConfigs(initialConfigs)
.build();
final String commandId = this.commandClient.createCommand(command);
// Test getConfigs for command
Assertions.assertThat(this.commandClient.getConfigsForCommand(commandId)).hasSize(2).contains("foo", "bar");
// Test adding a tag for command
final Set<String> moreConfigs = Sets.newHashSet("pi");
this.commandClient.addConfigsToCommand(commandId, moreConfigs);
Assertions
.assertThat(this.commandClient.getConfigsForCommand(commandId))
.hasSize(3)
.contains("foo", "bar", "pi");
// Test update configs for a command
this.commandClient.updateConfigsForCommand(commandId, initialConfigs);
Assertions.assertThat(this.commandClient.getConfigsForCommand(commandId)).hasSize(2).contains("foo", "bar");
// Test delete all configs in a command
this.commandClient.removeAllConfigsForCommand(commandId);
Assertions.assertThat(this.commandClient.getConfigsForCommand(commandId)).isEmpty();
}
@Test
void testCommandDependenciesMethods() throws Exception {
final Set<String> initialDependencies = Sets.newHashSet("foo", "bar");
final List<String> executable = Lists.newArrayList("exec");
final Command command = new Command.Builder("name", "user", "1.0", CommandStatus.ACTIVE, executable)
.withDependencies(initialDependencies)
.build();
final String commandId = this.commandClient.createCommand(command);
// Test getDependencies for command
Assertions
.assertThat(this.commandClient.getDependenciesForCommand(commandId))
.hasSize(2)
.contains("foo", "bar");
// Test adding a tag for command
final Set<String> moreDependencies = Sets.newHashSet("pi");
this.commandClient.addDependenciesToCommand(commandId, moreDependencies);
Assertions
.assertThat(this.commandClient.getDependenciesForCommand(commandId))
.hasSize(3)
.contains("foo", "bar", "pi");
// Test update configs for a command
this.commandClient.updateDependenciesForCommand(commandId, initialDependencies);
Assertions
.assertThat(this.commandClient.getDependenciesForCommand(commandId))
.hasSize(2)
.contains("foo", "bar");
// Test delete all configs in a command
this.commandClient.removeAllDependenciesForCommand(commandId);
Assertions.assertThat(this.commandClient.getDependenciesForCommand(commandId)).isEmpty();
}
@Test
void testCommandApplicationsMethods() throws Exception {
final Application foo = new Application.Builder(
"name",
"user",
"version",
ApplicationStatus.ACTIVE
).build();
final String fooId = this.applicationClient.createApplication(foo);
final Application bar = new Application.Builder(
"name",
"user",
"version",
ApplicationStatus.ACTIVE
).build();
final String barId = this.applicationClient.createApplication(bar);
final Application pi = new Application.Builder(
"name",
"user",
"version",
ApplicationStatus.ACTIVE
).build();
final String piId = this.applicationClient.createApplication(pi);
final Command command = this.constructCommandDTO("command1");
final String commandId = this.commandClient.createCommand(command);
// Test add Applications to command
final List<String> initialApplications = Lists.newArrayList(fooId, barId, piId);
this.commandClient.addApplicationsToCommand(commandId, initialApplications);
Assertions
.assertThat(this.commandClient.getApplicationsForCommand(commandId))
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.isEqualTo(initialApplications);
// Test removing a application for command
this.commandClient.removeApplicationFromCommand(commandId, piId);
Assertions
.assertThat(this.commandClient.getApplicationsForCommand(commandId))
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(fooId, barId);
final List<String> updatedApplications = Lists.newArrayList(fooId, piId);
// Test update applications for a command
this.commandClient.updateApplicationsForCommand(commandId, updatedApplications);
Assertions
.assertThat(this.commandClient.getApplicationsForCommand(commandId))
.extracting(Application::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactly(fooId, piId);
// Test delete all applications in a command
this.commandClient.removeAllApplicationsForCommand(commandId);
Assertions.assertThat(this.commandClient.getApplicationsForCommand(commandId)).isEmpty();
}
@Test
void testCommandPatchMethod() throws Exception {
final ObjectMapper mapper = GenieObjectMapper.getMapper();
final String newName = UUID.randomUUID().toString();
final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
final JsonPatch patch = JsonPatch.fromJson(mapper.readTree(patchString));
final Command command = this.constructCommandDTO(null);
final String commandId = this.commandClient.createCommand(command);
this.commandClient.patchCommand(commandId, patch);
Assertions.assertThat(this.commandClient.getCommand(commandId).getName()).isEqualTo(newName);
}
@Test
void testCanGetClustersForCommand() throws Exception {
final Cluster cluster1 = this.constructClusterDTO(null);
final Cluster cluster2 = this.constructClusterDTO(null);
final String cluster1Id = this.clusterClient.createCluster(cluster1);
final String cluster2Id = this.clusterClient.createCluster(cluster2);
final Command command = new Command.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(),
CommandStatus.ACTIVE,
Lists.newArrayList(UUID.randomUUID().toString())
)
.withClusterCriteria(
Lists.newArrayList(
new Criterion.Builder().withId(cluster1Id).build(),
new Criterion.Builder().withId(cluster2Id).build()
)
)
.build();
final String commandId = this.commandClient.createCommand(command);
Assertions
.assertThat(this.commandClient.getClustersForCommand(commandId))
.extracting(Cluster::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsOnly(cluster1Id, cluster2Id);
}
}
| 2,310 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/package-info.java | /*
*
* Copyright 2015 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.
*
*/
/**
* Classes that test Base Genie Client Code.
*
* @author tgianos
*/
package com.netflix.genie.client;
| 2,311 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/interceptors/ResponseMappingInterceptorTest.java | /*
*
* Copyright 2016 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.genie.client.interceptors;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.client.exceptions.GenieClientTooManyRequestsException;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.UUID;
/**
* Unit tests for the {@link ResponseMappingInterceptor} class.
*
* @author tgianos
* @since 3.0.0
*/
class ResponseMappingInterceptorTest {
private MockWebServer server;
private OkHttpClient client;
private HttpUrl baseUrl;
@BeforeEach
void setup() throws IOException {
this.server = new MockWebServer();
this.server.start();
this.baseUrl = this.server.url("/api/v3/jobs");
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new ResponseMappingInterceptor());
this.client = builder.build();
}
@AfterEach
void tearDown() throws IOException {
this.server.shutdown();
}
@Test
void canInterceptSuccess() throws IOException {
this.server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK));
final Request request = new Request.Builder().url(this.baseUrl).get().build();
final Response response = this.client.newCall(request).execute();
Assertions.assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_OK);
}
@Test
void canInterceptFailure() {
this.server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR));
final Request request = new Request.Builder().url(this.baseUrl).get().build();
Assertions
.assertThatExceptionOfType(GenieClientException.class)
.isThrownBy(() -> this.client.newCall(request).execute())
.satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR));
final String message = UUID.randomUUID().toString();
final String bodyString = "{\"message\":\"" + message + "\"}";
this.server.enqueue(
new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_UNAVAILABLE)
.setBody(bodyString)
);
Assertions
.assertThatExceptionOfType(GenieClientException.class)
.isThrownBy(() -> this.client.newCall(request).execute())
.satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE))
.withMessage(HttpURLConnection.HTTP_UNAVAILABLE + ": " + message);
this.server.enqueue(
new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_PRECON_FAILED)
.setBody("this is not valid JSON")
);
Assertions
.assertThatExceptionOfType(GenieClientException.class)
.isThrownBy(() -> this.client.newCall(request).execute())
.satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(-1))
.withMessage("Failed to parse server response as JSON");
}
@Test
void canIntercept429() {
this.server.enqueue(new MockResponse().setResponseCode(429));
final Request request = new Request.Builder().url(this.baseUrl).get().build();
Assertions
.assertThatExceptionOfType(GenieClientTooManyRequestsException.class)
.isThrownBy(() -> this.client.newCall(request).execute());
}
}
| 2,312 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/interceptors/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for the interceptor classes.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.client.interceptors;
| 2,313 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2/AccessTokenTest.java | /*
*
* Copyright 2016 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.genie.client.security.oauth2;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit Tests for AccessToken class.
*
* @author amsharma
* @since 3.0.0
*/
class AccessTokenTest {
private AccessToken accessToken;
@BeforeEach
void setup() {
this.accessToken = new AccessToken();
}
@Test
void canSetAccessToken() {
final String token = "token";
this.accessToken.setAccessToken(token);
Assertions.assertThat(this.accessToken.getAccessToken()).isEqualTo(token);
}
@Test
void canSetTokenType() {
final String tokenType = "token_type";
this.accessToken.setTokenType(tokenType);
Assertions.assertThat(this.accessToken.getTokenType()).isEqualTo(tokenType);
}
@Test
void canSetExpiresIn() {
final int expiresIn = 3600;
this.accessToken.setExpiresIn(expiresIn);
Assertions.assertThat(this.accessToken.getExpiresIn()).isEqualTo(expiresIn);
}
}
| 2,314 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2/TokenFetcherTest.java | /*
*
* Copyright 2016 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.genie.client.security.oauth2;
import com.netflix.genie.client.exceptions.GenieClientException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Unit Tests for the Token Fetcher class.
*
* @author amsharma
* @since 3.0.0
*/
class TokenFetcherTest {
private static final String URL = "http://url";
private static final String CLIENT_ID = "client_id";
private static final String CLIENT_SECRET = "client_secret";
private static final String GRANT_TYPE = "grant_type";
private static final String SCOPE = "scope";
@Test
void testConstructorWithEmptyUrl() {
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> new TokenFetcher(null, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE));
}
@Test
void testConstructorWithEmptyClientIdl() {
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> new TokenFetcher(URL, null, CLIENT_SECRET, GRANT_TYPE, SCOPE));
}
@Test
void testConstructorWithEmptyClientSecret() {
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> new TokenFetcher(URL, CLIENT_ID, null, GRANT_TYPE, SCOPE));
}
@Test
void testConstructorWithEmptyGrantType() {
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> new TokenFetcher(URL, CLIENT_ID, CLIENT_SECRET, null, SCOPE));
}
@Test
void testConstructorWithEmptyScope() {
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> new TokenFetcher(URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, null));
}
@Test
void testConstructorWithMalformedUrl() {
Assertions
.assertThatExceptionOfType(GenieClientException.class)
.isThrownBy(() -> new TokenFetcher("foo", CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE));
}
@Test
void testConstructorWithValidParams() {
Assertions
.assertThatCode(() -> new TokenFetcher(URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE))
.doesNotThrowAnyException();
}
@Test
@Disabled("Fails from time to time non-deterministically")
void testGetTokenFailure() {
Assertions
.assertThatExceptionOfType(GenieClientException.class)
.isThrownBy(
() -> {
final TokenFetcher tokenFetcher
= new TokenFetcher(URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE);
tokenFetcher.getToken();
}
)
.satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(-1));
}
}
| 2,315 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2/package-info.java | /*
*
* Copyright 2015 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 containing tests for classes in the com.netflix.genie.client.security.oauth package.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.security.oauth2;
| 2,316 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2/impl/OAuth2SecurityInterceptorTest.java | /*
*
* Copyright 2016 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.genie.client.security.oauth2.impl;
import okhttp3.Interceptor;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* Unit Tests for {@link OAuth2SecurityInterceptor} Class.
*
* @author amsharma
* @since 3.0.0
*/
class OAuth2SecurityInterceptorTest {
private static final String URL = "http://localhost/foo";
private static final String CLIENT_ID = "client_id";
private static final String CLIENT_SECRET = "client_secret";
private static final String GRANT_TYPE = "grant_type";
private static final String SCOPE = "scope";
@Test
void testCanConstruct() {
Assertions
.assertThatCode(() -> new OAuth2SecurityInterceptor(URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE))
.doesNotThrowAnyException();
}
@Disabled("fails randomly")
@Test
void testTokenFetchFailure() throws Exception {
final Interceptor.Chain chain = Mockito.mock(Interceptor.Chain.class);
final OAuth2SecurityInterceptor oAuth2SecurityInterceptor = new OAuth2SecurityInterceptor(
URL,
CLIENT_ID,
CLIENT_SECRET,
GRANT_TYPE,
SCOPE
);
Assertions.assertThatIOException().isThrownBy(() -> oAuth2SecurityInterceptor.intercept(chain));
}
}
| 2,317 |
0 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2 | Create_ds/genie/genie-client/src/test/java/com/netflix/genie/client/security/oauth2/impl/package-info.java | /*
*
* Copyright 2016 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 containing tests for the oauth security impl package.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.security.oauth2.impl;
| 2,318 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/ClusterClient.java | /*
*
* Copyright 2016 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.genie.client;
import com.github.fge.jsonpatch.JsonPatch;
import com.netflix.genie.client.apis.ClusterService;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.client.configs.GenieNetworkConfiguration;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Retrofit;
import javax.annotation.Nullable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* Client library for the Cluster Service.
*
* @author amsharma
* @since 3.0.0
*/
@Slf4j
public class ClusterClient {
private final ClusterService clusterService;
/**
* Constructor.
*
* @param retrofit The configured {@link Retrofit} client to a Genie server
*/
public ClusterClient(@NotNull final Retrofit retrofit) {
this.clusterService = retrofit.create(ClusterService.class);
}
/**
* Constructor.
*
* @param url The endpoint URL of the Genie API. Not null or empty
* @param interceptors Any interceptors to configure the client with, can include security ones
* @param genieNetworkConfiguration The network configuration parameters. Could be null
* @throws GenieClientException On error
* @deprecated Use {@link #ClusterClient(Retrofit)}
*/
@Deprecated
public ClusterClient(
@NotEmpty final String url,
@Nullable final List<Interceptor> interceptors,
@Nullable final GenieNetworkConfiguration genieNetworkConfiguration
) throws GenieClientException {
this(GenieClientUtils.createRetrofitInstance(url, interceptors, genieNetworkConfiguration));
}
/* CRUD Methods */
/**
* Create a cluster ing genie.
*
* @param cluster A cluster object.
* @return The id of the cluster created.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public String createCluster(
final Cluster cluster
) throws IOException, GenieClientException {
if (cluster == null) {
throw new IllegalArgumentException("Cluster cannot be null.");
}
final String locationHeader = this.clusterService
.createCluster(cluster)
.execute()
.headers()
.get(GenieClientUtils.LOCATION_HEADER);
if (StringUtils.isBlank(locationHeader)) {
throw new GenieClientException("No location header. Unable to get ID");
}
return GenieClientUtils.getIdFromLocation(locationHeader);
}
/**
* Method to get a list of all the clusters.
*
* @return A list of clusters.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Cluster> getClusters() throws IOException, GenieClientException {
return this.getClusters(
null,
null,
null,
null,
null
);
}
/**
* Method to get a list of all the clusters from Genie for the query parameters specified.
*
* @param name The name of the cluster.
* @param statusList The list of statuses.
* @param tagList The list of tags.
* @param minUpdateTime Minimum Time after which cluster was updated.
* @param maxUpdateTime Maximum Time before which cluster was updated.
* @return A list of clusters.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @deprecated Use {@link #getClusters(String, List, List, Long, Long, Integer, SortAttribute, SortDirection,
* Integer)}
*/
public List<Cluster> getClusters(
final String name,
final List<String> statusList,
final List<String> tagList,
final Long minUpdateTime,
final Long maxUpdateTime
) throws IOException, GenieClientException {
return this.getClusters(
name,
statusList,
tagList,
minUpdateTime,
maxUpdateTime,
null,
null,
null,
null
);
}
/**
* Method to get a list of all the clusters from Genie for the query parameters specified.
*
* @param name The name of the cluster.
* @param statusList The list of statuses.
* @param tagList The list of tags.
* @param minUpdateTime Minimum Time after which cluster was updated.
* @param maxUpdateTime Maximum Time before which cluster was updated.
* @param pageSize The maximum number of results returned
* @param sortAttribute The entity attribute used to sort
* @param sortDirection The sort direction
* @param pageIndex The page index
* @return A list of clusters.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Cluster> getClusters(
@Nullable final String name,
@Nullable final List<String> statusList,
@Nullable final List<String> tagList,
@Nullable final Long minUpdateTime,
@Nullable final Long maxUpdateTime,
@Nullable @Min(1) final Integer pageSize,
@Nullable final SortAttribute sortAttribute,
@Nullable final SortDirection sortDirection,
@Nullable @Min(0) final Integer pageIndex
) throws IOException, GenieClientException {
return GenieClientUtils.parseSearchResultsResponse(
this.clusterService.getClusters(
name,
statusList,
tagList,
minUpdateTime,
maxUpdateTime,
pageSize,
GenieClientUtils.getSortParameter(sortAttribute, sortDirection),
pageIndex
).execute(),
"clusterList",
Cluster.class
);
}
/**
* Method to get a Cluster from Genie.
*
* @param clusterId The id of the cluster to get.
* @return The cluster details.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Cluster getCluster(
final String clusterId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
return clusterService.getCluster(clusterId).execute().body();
}
/**
* Method to delete a cluster from Genie.
*
* @param clusterId The id of the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void deleteCluster(final String clusterId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
clusterService.deleteCluster(clusterId).execute();
}
/**
* Method to delete all clusters from Genie.
*
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void deleteAllClusters() throws IOException, GenieClientException {
clusterService.deleteAllClusters().execute();
}
/**
* Method to patch a cluster using json patch instructions.
*
* @param clusterId The id of the cluster.
* @param patch The patch object specifying all the instructions.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void patchCluster(final String clusterId, final JsonPatch patch) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (patch == null) {
throw new IllegalArgumentException("Patch cannot be null");
}
clusterService.patchCluster(clusterId, patch).execute();
}
/**
* Method to updated a cluster.
*
* @param clusterId The id of the cluster.
* @param cluster The updated cluster object to use.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateCluster(final String clusterId, final Cluster cluster) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (cluster == null) {
throw new IllegalArgumentException("Patch cannot be null");
}
clusterService.updateCluster(clusterId, cluster).execute();
}
//****************** Methods to manipulate configs for a cluster *********************/
/**
* Method to get all the configs for a cluster.
*
* @param clusterId The id of the cluster.
* @return The set of configs for the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Set<String> getConfigsForCluster(final String clusterId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
return clusterService.getConfigsForCluster(clusterId).execute().body();
}
/**
* Method to add configs to a cluster.
*
* @param clusterId The id of the cluster.
* @param configs The set of configs to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void addConfigsToCluster(
final String clusterId, final Set<String> configs
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (configs == null || configs.isEmpty()) {
throw new IllegalArgumentException("Configs cannot be null or empty");
}
clusterService.addConfigsToCluster(clusterId, configs).execute();
}
/**
* Method to update configs for a cluster.
*
* @param clusterId The id of the cluster.
* @param configs The set of configs to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateConfigsForCluster(
final String clusterId, final Set<String> configs
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (configs == null || configs.isEmpty()) {
throw new IllegalArgumentException("Configs cannot be null or empty");
}
clusterService.updateConfigsForCluster(clusterId, configs).execute();
}
/**
* Remove all configs for this cluster.
*
* @param clusterId The id of the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeAllConfigsForCluster(
final String clusterId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
clusterService.removeAllConfigsForCluster(clusterId).execute();
}
//****************** Methods to manipulate dependencies for a cluster *********************/
/**
* Method to get all the dependency files for an cluster.
*
* @param clusterId The id of the cluster.
* @return The set of dependencies for the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public Set<String> getDependenciesForCluster(final String clusterId) throws IOException,
GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
return clusterService.getDependenciesForCluster(clusterId).execute().body();
}
/**
* Method to add dependencies to a cluster.
*
* @param clusterId The id of the cluster.
* @param dependencies The set of dependencies to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void addDependenciesToCluster(
final String clusterId, final Set<String> dependencies
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (dependencies == null || dependencies.isEmpty()) {
throw new IllegalArgumentException("Dependencies cannot be null or empty");
}
clusterService.addDependenciesToCluster(clusterId, dependencies).execute();
}
/**
* Method to update dependencies for a cluster.
*
* @param clusterId The id of the cluster.
* @param dependencies The set of dependencies to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void updateDependenciesForCluster(
final String clusterId, final Set<String> dependencies
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (dependencies == null || dependencies.isEmpty()) {
throw new IllegalArgumentException("Dependencies cannot be null or empty");
}
clusterService.updateDependenciesForCluster(clusterId, dependencies).execute();
}
/**
* Remove all dependencies for this cluster.
*
* @param clusterId The id of the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void removeAllDependenciesForCluster(
final String clusterId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
clusterService.removeAllDependenciesForCluster(clusterId).execute();
}
//****************** Methods to manipulate commands for a cluster *********************/
/**
* Method to get all the commands for a cluster.
*
* @param clusterId The id of the cluster.
* @return The set of commands for the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Command> getCommandsForCluster(final String clusterId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
return clusterService.getCommandsForCluster(clusterId).execute().body();
}
/**
* Method to add commands to a cluster.
*
* @param clusterId The id of the cluster.
* @param commandIds The list of commands to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void addCommandsToCluster(
final String clusterId, final List<String> commandIds
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (commandIds == null || commandIds.isEmpty()) {
throw new IllegalArgumentException("Command Ids cannot be null or empty");
}
clusterService.addCommandsToCluster(clusterId, commandIds).execute();
}
/**
* Method to update commands for a cluster.
*
* @param clusterId The id of the cluster.
* @param commandIds The set of commands to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateCommandsForCluster(
final String clusterId, final List<String> commandIds
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (commandIds == null || commandIds.isEmpty()) {
throw new IllegalArgumentException("commandIds cannot be null or empty");
}
clusterService.setCommandsForCluster(clusterId, commandIds).execute();
}
/**
* Remove a command from a cluster.
*
* @param clusterId The id of the cluster.
* @param commandId The id of the command to remove.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeCommandFromCluster(
final String clusterId,
final String commandId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
clusterService.removeCommandForCluster(clusterId, commandId).execute();
}
/**
* Remove all commands for this cluster.
*
* @param clusterId The id of the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeAllCommandsForCluster(
final String clusterId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
clusterService.removeAllCommandsForCluster(clusterId).execute();
}
//****************** Methods to manipulate tags for a cluster *********************/
/**
* Method to get all the tags for a cluster.
*
* @param clusterId The id of the cluster.
* @return The set of tags for the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Set<String> getTagsForCluster(final String clusterId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
return clusterService.getTagsForCluster(clusterId).execute().body();
}
/**
* Method to add tags to a cluster.
*
* @param clusterId The id of the cluster.
* @param tags The set of tags to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void addTagsToCluster(
final String clusterId, final Set<String> tags
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (tags == null || tags.isEmpty()) {
throw new IllegalArgumentException("Tags cannot be null or empty");
}
clusterService.addTagsToCluster(clusterId, tags).execute();
}
/**
* Method to update tags for a cluster.
*
* @param clusterId The id of the cluster.
* @param tags The set of tags to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateTagsForCluster(
final String clusterId, final Set<String> tags
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (tags == null || tags.isEmpty()) {
throw new IllegalArgumentException("Tags cannot be null or empty");
}
clusterService.updateTagsForCluster(clusterId, tags).execute();
}
/**
* Remove a tag from a cluster.
*
* @param clusterId The id of the cluster.
* @param tag The tag to remove.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeTagFromCluster(
final String clusterId,
final String tag
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
if (StringUtils.isEmpty(tag)) {
throw new IllegalArgumentException("Missing required parameter: tag.");
}
clusterService.removeTagForCluster(clusterId, tag).execute();
}
/**
* Remove all tags for this cluster.
*
* @param clusterId The id of the cluster.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeAllTagsForCluster(
final String clusterId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(clusterId)) {
throw new IllegalArgumentException("Missing required parameter: clusterId.");
}
clusterService.removeAllTagsForCluster(clusterId).execute();
}
}
| 2,319 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/CommandClient.java | /*
*
* Copyright 2016 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.genie.client;
import com.github.fge.jsonpatch.JsonPatch;
import com.netflix.genie.client.apis.CommandService;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.client.configs.GenieNetworkConfiguration;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Retrofit;
import javax.annotation.Nullable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* Client library for the Command Service.
*
* @author amsharma
* @since 3.0.0
*/
@Slf4j
public class CommandClient {
private final CommandService commandService;
/**
* Constructor.
*
* @param retrofit The configured {@link Retrofit} client to a Genie server
*/
public CommandClient(@NotNull final Retrofit retrofit) {
this.commandService = retrofit.create(CommandService.class);
}
/**
* Constructor.
*
* @param url The endpoint URL of the Genie API. Not null or empty
* @param interceptors Any interceptors to configure the client with, can include security ones
* @param genieNetworkConfiguration The network configuration parameters. Could be null
* @throws GenieClientException On error
* @deprecated Use {@link #CommandClient(Retrofit)}
*/
@Deprecated
public CommandClient(
@NotEmpty final String url,
@Nullable final List<Interceptor> interceptors,
@Nullable final GenieNetworkConfiguration genieNetworkConfiguration
) throws GenieClientException {
this(GenieClientUtils.createRetrofitInstance(url, interceptors, genieNetworkConfiguration));
}
/* CRUD Methods */
/**
* Create a command ing genie.
*
* @param command A command object.
* @return id Id of the command created.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public String createCommand(
final Command command
) throws IOException, GenieClientException {
if (command == null) {
throw new IllegalArgumentException("Command cannot be null.");
}
final String locationHeader = this.commandService
.createCommand(command)
.execute()
.headers()
.get(GenieClientUtils.LOCATION_HEADER);
if (StringUtils.isBlank(locationHeader)) {
throw new GenieClientException("No location header. Unable to get ID");
}
return GenieClientUtils.getIdFromLocation(locationHeader);
}
/**
* Method to get a list of all the commands.
*
* @return A list of commands.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Command> getCommands() throws IOException, GenieClientException {
return this.getCommands(null, null, null, null);
}
/**
* Method to get a list of all the commands from Genie for the query parameters specified.
*
* @param name The name of the commands.
* @param user The user who created the command.
* @param statusList The list of Command statuses.
* @param tagList The list of tags.
* @return A list of commands.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @deprecated Use {@link #getCommands(String, String, List, List, Integer, SortAttribute, SortDirection, Integer)}
*/
@Deprecated
public List<Command> getCommands(
final String name,
final String user,
final List<String> statusList,
final List<String> tagList
) throws IOException, GenieClientException {
return this.getCommands(
name,
user,
statusList,
tagList,
null,
null,
null,
null
);
}
/**
* Method to get a list of all the commands from Genie for the query parameters specified.
*
* @param name The name of the commands.
* @param user The user who created the command.
* @param statusList The list of Command statuses.
* @param tagList The list of tags.
* @param pageSize The maximum number of results returned
* @param sortAttribute The entity attribute used to sort
* @param sortDirection The sort direction
* @param pageIndex The page index
* @return A list of commands.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Command> getCommands(
@Nullable final String name,
@Nullable final String user,
@Nullable final List<String> statusList,
@Nullable final List<String> tagList,
@Nullable @Min(1) final Integer pageSize,
@Nullable final SortAttribute sortAttribute,
@Nullable final SortDirection sortDirection,
@Nullable @Min(0) final Integer pageIndex
) throws IOException, GenieClientException {
return GenieClientUtils.parseSearchResultsResponse(
this.commandService.getCommands(
name,
user,
statusList,
tagList,
pageSize,
GenieClientUtils.getSortParameter(sortAttribute, sortDirection),
pageIndex
).execute(),
"commandList",
Command.class
);
}
/**
* Method to get a Command from Genie.
*
* @param commandId The id of the command to get.
* @return The command details.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Command getCommand(
final String commandId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
return commandService.getCommand(commandId).execute().body();
}
/**
* Method to delete a command from Genie.
*
* @param commandId The id of the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void deleteCommand(final String commandId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
commandService.deleteCommand(commandId).execute();
}
/**
* Method to delete all commands from Genie.
*
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void deleteAllCommands() throws IOException, GenieClientException {
commandService.deleteAllCommands().execute();
}
/**
* Method to patch a command using json patch instructions.
*
* @param commandId The id of the command.
* @param patch The patch object specifying all the instructions.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void patchCommand(final String commandId, final JsonPatch patch) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (patch == null) {
throw new IllegalArgumentException("Patch cannot be null");
}
commandService.patchCommand(commandId, patch).execute();
}
/**
* Method to updated a command.
*
* @param commandId The id of the command.
* @param command The updated command object to use.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateCommand(final String commandId, final Command command) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (command == null) {
throw new IllegalArgumentException("Patch cannot be null");
}
commandService.updateCommand(commandId, command).execute();
}
//****************** Methods to manipulate configs for a command *********************/
/**
* Method to get all the configs for a command.
*
* @param commandId The id of the command.
* @return The set of configs for the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Set<String> getConfigsForCommand(final String commandId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
return commandService.getConfigsForCommand(commandId).execute().body();
}
/**
* Method to add configs to a command.
*
* @param commandId The id of the command.
* @param configs The set of configs to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void addConfigsToCommand(
final String commandId, final Set<String> configs
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (configs == null || configs.isEmpty()) {
throw new IllegalArgumentException("Configs cannot be null or empty");
}
commandService.addConfigsToCommand(commandId, configs).execute();
}
/**
* Method to update configs for a command.
*
* @param commandId The id of the command.
* @param configs The set of configs to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateConfigsForCommand(
final String commandId, final Set<String> configs
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (configs == null || configs.isEmpty()) {
throw new IllegalArgumentException("Configs cannot be null or empty");
}
commandService.updateConfigsForCommand(commandId, configs).execute();
}
/**
* Remove all configs for this command.
*
* @param commandId The id of the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeAllConfigsForCommand(
final String commandId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
commandService.removeAllConfigsForCommand(commandId).execute();
}
//****************** Methods to manipulate dependencies for a command *********************/
/**
* Method to get all the dependency files for an command.
*
* @param commandId The id of the command.
* @return The set of dependencies for the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public Set<String> getDependenciesForCommand(final String commandId) throws IOException,
GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
return commandService.getDependenciesForCommand(commandId).execute().body();
}
/**
* Method to add dependencies to a command.
*
* @param commandId The id of the command.
* @param dependencies The set of dependencies to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void addDependenciesToCommand(
final String commandId, final Set<String> dependencies
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (dependencies == null || dependencies.isEmpty()) {
throw new IllegalArgumentException("Dependencies cannot be null or empty");
}
commandService.addDependenciesToCommand(commandId, dependencies).execute();
}
/**
* Method to update dependencies for a command.
*
* @param commandId The id of the command.
* @param dependencies The set of dependencies to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void updateDependenciesForCommand(
final String commandId, final Set<String> dependencies
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (dependencies == null || dependencies.isEmpty()) {
throw new IllegalArgumentException("Dependencies cannot be null or empty");
}
commandService.updateDependenciesForCommand(commandId, dependencies).execute();
}
/**
* Remove all dependencies for this command.
*
* @param commandId The id of the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void removeAllDependenciesForCommand(
final String commandId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
commandService.removeAllDependenciesForCommand(commandId).execute();
}
//****************** Methods to manipulate applications for a command *********************/
/**
* Method to get all the applications for a command.
*
* @param commandId The id of the command.
* @return The set of applications for the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Application> getApplicationsForCommand(final String commandId)
throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
return commandService.getApplicationsForCommand(commandId).execute().body();
}
/**
* Method to get all the clusters for a command.
*
* @param commandId The id of the command.
* @return The set of clusters for the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Cluster> getClustersForCommand(final String commandId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
return commandService.getClustersForCommand(commandId).execute().body();
}
/**
* Method to add applications to a command.
*
* @param commandId The id of the command.
* @param applicationIds The set of applications ids to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void addApplicationsToCommand(
final String commandId, final List<String> applicationIds
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (applicationIds == null || applicationIds.isEmpty()) {
throw new IllegalArgumentException("applicationIds cannot be null or empty");
}
commandService.addApplicationsToCommand(commandId, applicationIds).execute();
}
/**
* Method to update applications for a command.
*
* @param commandId The id of the command.
* @param applicationIds The set of application ids to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateApplicationsForCommand(
final String commandId, final List<String> applicationIds
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (applicationIds == null || applicationIds.isEmpty()) {
throw new IllegalArgumentException("applicationIds cannot be null or empty");
}
commandService.setApplicationsForCommand(commandId, applicationIds).execute();
}
/**
* Remove an application from a command.
*
* @param commandId The id of the command.
* @param applicationId The id of the application to remove.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeApplicationFromCommand(
final String commandId,
final String applicationId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
commandService.removeApplicationForCommand(commandId, applicationId).execute();
}
/**
* Remove all applications for this command.
*
* @param commandId The id of the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeAllApplicationsForCommand(
final String commandId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
commandService.removeAllApplicationsForCommand(commandId).execute();
}
//****************** Methods to manipulate tags for a command *********************/
/**
* Method to get all the tags for a command.
*
* @param commandId The id of the command.
* @return The set of configs for the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Set<String> getTagsForCommand(final String commandId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
return commandService.getTagsForCommand(commandId).execute().body();
}
/**
* Method to add tags to a command.
*
* @param commandId The id of the command.
* @param tags The set of tags to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void addTagsToCommand(
final String commandId, final Set<String> tags
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (tags == null || tags.isEmpty()) {
throw new IllegalArgumentException("Tags cannot be null or empty");
}
commandService.addTagsToCommand(commandId, tags).execute();
}
/**
* Method to update tags for a command.
*
* @param commandId The id of the command.
* @param tags The set of tags to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void updateTagsForCommand(
final String commandId, final Set<String> tags
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (tags == null || tags.isEmpty()) {
throw new IllegalArgumentException("Tags cannot be null or empty");
}
commandService.updateTagsForCommand(commandId, tags).execute();
}
/**
* Remove a tag from a command.
*
* @param commandId The id of the command.
* @param tag The tag to remove.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeTagFromCommand(
final String commandId,
final String tag
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
if (StringUtils.isEmpty(tag)) {
throw new IllegalArgumentException("Missing required parameter: tag.");
}
commandService.removeTagForCommand(commandId, tag).execute();
}
/**
* Remove all tags for this command.
*
* @param commandId The id of the command.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void removeAllTagsForCommand(
final String commandId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(commandId)) {
throw new IllegalArgumentException("Missing required parameter: commandId.");
}
commandService.removeAllTagsForCommand(commandId).execute();
}
}
| 2,320 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/JobClient.java | /*
*
* Copyright 2016 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.genie.client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.google.common.io.ByteStreams;
import com.netflix.genie.client.apis.JobService;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.client.configs.GenieNetworkConfiguration;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.Job;
import com.netflix.genie.common.dto.JobExecution;
import com.netflix.genie.common.dto.JobMetadata;
import com.netflix.genie.common.dto.JobRequest;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.dto.search.JobSearchResult;
import com.netflix.genie.common.exceptions.GeniePreconditionException;
import com.netflix.genie.common.exceptions.GenieTimeoutException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Call;
import retrofit2.Retrofit;
import javax.annotation.Nullable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* Client library for the Job Service.
*
* @author amsharma
* @since 3.0.0
*/
public class JobClient {
private static final String STATUS = "status";
private static final String ATTACHMENT = "attachment";
private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
private static final String EMPTY_STRING = "";
private static final int ZERO = 0;
private static final String STDOUT = "stdout";
private static final String STDERR = "stderr";
private final JobService jobService;
private final int maxStatusRetries;
/**
* Constructor.
*
* @param retrofit The configured {@link Retrofit} client to a Genie server
* @param maxStatusRetries The maximum number of retries to check for job status
*/
public JobClient(@NotNull final Retrofit retrofit, final int maxStatusRetries) {
this.jobService = retrofit.create(JobService.class);
this.maxStatusRetries = maxStatusRetries;
}
/**
* Constructor.
*
* @param url The endpoint URL of the Genie API. Not null or empty
* @param interceptors Any interceptors to configure the client with, can include security ones
* @param genieNetworkConfiguration The network configuration parameters. Could be null
* @throws GenieClientException On error
* @deprecated Use {@link #JobClient(Retrofit, int)}
*/
@Deprecated
public JobClient(
@NotEmpty final String url,
@Nullable final List<Interceptor> interceptors,
@Nullable final GenieNetworkConfiguration genieNetworkConfiguration
) throws GenieClientException {
this(
GenieClientUtils.createRetrofitInstance(url, interceptors, genieNetworkConfiguration),
genieNetworkConfiguration == null
? GenieNetworkConfiguration.DEFAULT_NUM_RETRIES
: genieNetworkConfiguration.getMaxStatusRetries()
);
}
/**
* Submit a job to genie using the jobRequest provided.
*
* @param jobRequest A job request containing all the details for running a job.
* @return jobId The id of the job submitted.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public String submitJob(
final JobRequest jobRequest
) throws IOException {
return submitJob(jobRequest, jobService::submitJob);
}
/**
* Submit a job to genie using the jobRequest and upstream security token information.
*
* @param jobRequest A job request containing all the details for running a job.
* @param upstreamSecurityTokenName the security token name provided by upstream.
* @param upstreamSecurityTokenValue the security token value provided by upstream.
* @return jobId The id of the job submitted.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public String submitJob(
final JobRequest jobRequest,
final String upstreamSecurityTokenName,
final String upstreamSecurityTokenValue
) throws IOException {
final Map<String, String> headers =
Collections.singletonMap(upstreamSecurityTokenName, upstreamSecurityTokenValue);
return submitJob(jobRequest, jr -> jobService.submitJob(headers, jr));
}
private String submitJob(
final JobRequest jobRequest,
final Function<JobRequest, Call<Void>> submitFn) throws IOException {
if (jobRequest == null) {
throw new IllegalArgumentException("Job Request cannot be null.");
}
final String locationHeader =
submitFn.apply(jobRequest).execute().headers().get(GenieClientUtils.LOCATION_HEADER);
if (StringUtils.isBlank(locationHeader)) {
throw new GenieClientException("No location header. Unable to get ID");
}
return GenieClientUtils.getIdFromLocation(locationHeader);
}
/**
* Submit a job to genie using the jobRequest and attachments provided.
*
* @param jobRequest A job request containing all the details for running a job.
* @param attachments A map of filenames/input-streams needed to be sent to the server as attachments.
* @return jobId The id of the job submitted.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public String submitJobWithAttachments(
final JobRequest jobRequest,
final Map<String, InputStream> attachments
) throws IOException {
return submitJobWithAttachments(jobRequest, attachments, jobService::submitJobWithAttachments);
}
/**
* Submit a job to genie using the jobRequest and attachments provided with the upstream security information.
*
* @param jobRequest A job request containing all the details for running a job.
* @param attachments A map of filenames/input-streams needed to be sent to the server as attachments.
* @param upstreamSecurityTokenName the security token name provided by upstream.
* @param upstreamSecurityTokenValue the security token value provided by upstream.
* @return jobId The id of the job submitted.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public String submitJobWithAttachments(
final JobRequest jobRequest,
final Map<String, InputStream> attachments,
final String upstreamSecurityTokenName,
final String upstreamSecurityTokenValue
) throws IOException {
final Map<String, String> headers =
Collections.singletonMap(upstreamSecurityTokenName, upstreamSecurityTokenValue);
return submitJobWithAttachments(
jobRequest, attachments, (jr, at) -> jobService.submitJobWithAttachments(headers, jr, at));
}
private String submitJobWithAttachments(
final JobRequest jobRequest,
final Map<String, InputStream> attachments,
final BiFunction<JobRequest, List<MultipartBody.Part>, Call<Void>> submitFn) throws IOException {
if (jobRequest == null) {
throw new IllegalArgumentException("Job Request cannot be null.");
}
final MediaType attachmentMediaType = MediaType.parse(APPLICATION_OCTET_STREAM);
final ArrayList<MultipartBody.Part> attachmentFiles = new ArrayList<>();
for (Map.Entry<String, InputStream> entry : attachments.entrySet()) {
// create a request body from the input stream provided
final RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return attachmentMediaType;
}
@Override
public void writeTo(final BufferedSink sink) throws IOException {
ByteStreams.copy(entry.getValue(), sink.outputStream());
}
};
final MultipartBody.Part part = MultipartBody.Part.createFormData(
ATTACHMENT,
entry.getKey(),
requestBody);
attachmentFiles.add(part);
}
final String locationHeader = submitFn.apply(jobRequest, attachmentFiles)
.execute()
.headers()
.get(GenieClientUtils.LOCATION_HEADER);
if (StringUtils.isBlank(locationHeader)) {
throw new GenieClientException("No location header. Unable to get ID");
}
return GenieClientUtils.getIdFromLocation(locationHeader);
}
/**
* Method to get a list of all the jobs.
*
* @return A list of jobs.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<JobSearchResult> getJobs() throws IOException, GenieClientException {
return this.getJobs(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
}
/**
* Method to get a list of all the jobs from Genie for the query parameters specified.
* <p>
* Deprecated: For new search fields
*
* @param id id for job
* @param name name of job (can be a SQL-style pattern such as HIVE%)
* @param user user who submitted job
* @param statuses statuses of jobs to find
* @param tags tags for the job
* @param clusterName the name of the cluster
* @param clusterId the id of the cluster
* @param commandName the name of the command run by the job
* @param commandId the id of the command run by the job
* @param minStarted The time which the job had to start after in order to be return (inclusive)
* @param maxStarted The time which the job had to start before in order to be returned (exclusive)
* @param minFinished The time which the job had to finish after in order to be return (inclusive)
* @param maxFinished The time which the job had to finish before in order to be returned (exclusive)
* @return A list of jobs.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @see #getJobs(
*String,
* String,
* String,
* Set,
* Set,
* String,
* String,
* String,
* String,
* Long,
* Long,
* Long,
* Long,
* String,
* String
*)
*/
@Deprecated
public List<JobSearchResult> getJobs(
final String id,
final String name,
final String user,
final Set<String> statuses,
final Set<String> tags,
final String clusterName,
final String clusterId,
final String commandName,
final String commandId,
final Long minStarted,
final Long maxStarted,
final Long minFinished,
final Long maxFinished
) throws IOException, GenieClientException {
return this.getJobs(
id,
name,
user,
statuses,
tags,
clusterName,
clusterId,
commandName,
commandId,
minStarted,
maxStarted,
minFinished,
maxFinished,
null,
null
);
}
/**
* Method to get a list of all the jobs from Genie for the query parameters specified.
*
* @param id id for job
* @param name name of job (can be a SQL-style pattern such as HIVE%)
* @param user user who submitted job
* @param statuses statuses of jobs to find
* @param tags tags for the job
* @param clusterName the name of the cluster
* @param clusterId the id of the cluster
* @param commandName the name of the command run by the job
* @param commandId the id of the command run by the job
* @param minStarted The time which the job had to start after in order to be return (inclusive)
* @param maxStarted The time which the job had to start before in order to be returned (exclusive)
* @param minFinished The time which the job had to finish after in order to be return (inclusive)
* @param maxFinished The time which the job had to finish before in order to be returned (exclusive)
* @param grouping The grouping the job should be a member of
* @param groupingInstance The grouping instance the job should be a member of
* @return A list of jobs.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @deprecated Use {@link #getJobs(String, String, String, Set, Set, String, String, String, String, Long, Long,
* Long, Long, String, String, Integer, SortAttribute, SortDirection, Integer)}
*/
public List<JobSearchResult> getJobs(
@Nullable final String id,
@Nullable final String name,
@Nullable final String user,
@Nullable final Set<String> statuses,
@Nullable final Set<String> tags,
@Nullable final String clusterName,
@Nullable final String clusterId,
@Nullable final String commandName,
@Nullable final String commandId,
@Nullable final Long minStarted,
@Nullable final Long maxStarted,
@Nullable final Long minFinished,
@Nullable final Long maxFinished,
@Nullable final String grouping,
@Nullable final String groupingInstance
) throws IOException, GenieClientException {
return this.getJobs(
id,
name,
user,
statuses,
tags,
clusterName,
clusterId,
commandName,
commandId,
minStarted,
maxStarted,
minFinished,
maxFinished,
grouping,
groupingInstance,
null,
null,
null,
null
);
}
/**
* Method to get a list of all the jobs from Genie for the query parameters specified.
*
* @param id id for job
* @param name name of job (can be a SQL-style pattern such as HIVE%)
* @param user user who submitted job
* @param statuses statuses of jobs to find
* @param tags tags for the job
* @param clusterName the name of the cluster
* @param clusterId the id of the cluster
* @param commandName the name of the command run by the job
* @param commandId the id of the command run by the job
* @param minStarted The time which the job had to start after in order to be return (inclusive)
* @param maxStarted The time which the job had to start before in order to be returned (exclusive)
* @param minFinished The time which the job had to finish after in order to be return (inclusive)
* @param maxFinished The time which the job had to finish before in order to be returned (exclusive)
* @param grouping The grouping the job should be a member of
* @param groupingInstance The grouping instance the job should be a member of
* @param pageSize The maximum number of results returned
* @param sortAttribute The entity attribute used to sort
* @param sortDirection The sort direction
* @param pageIndex The page index
* @return A list of jobs.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
@SuppressWarnings("checkstyle:ParameterNumber")
public List<JobSearchResult> getJobs(
@Nullable final String id,
@Nullable final String name,
@Nullable final String user,
@Nullable final Set<String> statuses,
@Nullable final Set<String> tags,
@Nullable final String clusterName,
@Nullable final String clusterId,
@Nullable final String commandName,
@Nullable final String commandId,
@Nullable final Long minStarted,
@Nullable final Long maxStarted,
@Nullable final Long minFinished,
@Nullable final Long maxFinished,
@Nullable final String grouping,
@Nullable final String groupingInstance,
@Nullable @Min(1) final Integer pageSize,
@Nullable final SortAttribute sortAttribute,
@Nullable final SortDirection sortDirection,
@Nullable @Min(0) final Integer pageIndex
) throws IOException, GenieClientException {
return GenieClientUtils.parseSearchResultsResponse(
this.jobService.getJobs(
id,
name,
user,
statuses,
tags,
clusterName,
clusterId,
commandName,
commandId,
minStarted,
maxStarted,
minFinished,
maxFinished,
grouping,
groupingInstance,
pageSize,
GenieClientUtils.getSortParameter(sortAttribute, sortDirection),
pageIndex
).execute(),
"jobSearchResultList",
JobSearchResult.class
);
}
/**
* Method to get a job from Genie.
*
* @param jobId The id of the job to get.
* @return The job details.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Job getJob(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return jobService.getJob(jobId).execute().body();
}
/**
* Method to get the cluster on which the job executes.
*
* @param jobId The id of the job.
* @return The cluster object.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Cluster getJobCluster(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return jobService.getJobCluster(jobId).execute().body();
}
/**
* Method to get the command on which the job executes.
*
* @param jobId The id of the job.
* @return The command object.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public Command getJobCommand(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return jobService.getJobCommand(jobId).execute().body();
}
/**
* Method to get the Job Request for the job.
*
* @param jobId The id of the job.
* @return The job requests object.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public JobRequest getJobRequest(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return jobService.getJobRequest(jobId).execute().body();
}
/**
* Method to get the Job Execution information for the job.
*
* @param jobId The id of the job.
* @return The job execution object.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public JobExecution getJobExecution(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return jobService.getJobExecution(jobId).execute().body();
}
/**
* Method to get the metadata information for the job.
*
* @param jobId The id of the job.
* @return The metadata object.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public JobMetadata getJobMetadata(final String jobId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return this.jobService.getJobMetadata(jobId).execute().body();
}
/**
* Method to get the Applications for the job.
*
* @param jobId The id of the job.
* @return The list of Applications.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public List<Application> getJobApplications(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
return jobService.getJobApplications(jobId).execute().body();
}
/**
* Method to fetch the stdout of a job from Genie.
*
* @param jobId The id of the job whose output is desired.
* @return An input stream to the output contents.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public InputStream getJobStdout(final String jobId) throws IOException, GenieClientException {
return this.getJobStdout(jobId, null, null);
}
/**
* Method to fetch the stdout of a job from Genie.
*
* <p>
* Range Logic:
* <p>
* {@literal rangeStart} but no {@literal rangeEnd} then go from the start byte to the end of available content
* <p>
* {@literal rangeStart} and {@literal rangeEnd} return that range of bytes from the file if they exist
* <p>
* If only {@literal rangeEnd} then return the last number of those bytes from the file if they exist
*
* @param jobId The id of the job whose output is desired.
* @param rangeStart The start byte of the file to retrieve. Optional. Greater than or equal to 0.
* @param rangeEnd The end byte of the file to retrieve. Optional. Greater than or equal to 0. Must be
* greater than {@literal rangeStart}.
* @return An input stream to the output contents.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public InputStream getJobStdout(
final String jobId,
@Nullable final Long rangeStart,
@Nullable final Long rangeEnd
) throws IOException, GenieClientException {
return this.getJobOutputFile(jobId, STDOUT, rangeStart, rangeEnd);
}
/**
* Method to fetch the stderr of a job from Genie.
*
* @param jobId The id of the job whose stderr is desired.
* @return An input stream to the stderr contents.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public InputStream getJobStderr(final String jobId) throws IOException, GenieClientException {
return this.getJobStderr(jobId, null, null);
}
/**
* Method to fetch the stderr of a job from Genie.
*
* <p>
* Range Logic:
* <p>
* {@literal rangeStart} but no {@literal rangeEnd} then go from the start byte to the end of available content
* <p>
* {@literal rangeStart} and {@literal rangeEnd} return that range of bytes from the file if they exist
* <p>
* If only {@literal rangeEnd} then return the last number of those bytes from the file if they exist
*
* @param jobId The id of the job whose stderr is desired.
* @param rangeStart The start byte of the file to retrieve. Optional. Greater than or equal to 0.
* @param rangeEnd The end byte of the file to retrieve. Optional. Greater than or equal to 0. Must be
* greater than {@literal rangeStart}.
* @return An input stream to the stderr contents.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public InputStream getJobStderr(
final String jobId,
@Nullable final Long rangeStart,
@Nullable final Long rangeEnd
) throws IOException, GenieClientException {
return this.getJobOutputFile(jobId, STDERR, rangeStart, rangeEnd);
}
/**
* Method to fetch an output file for a job from Genie.
*
* <p>
* <b>NOTE</b>: If the specified outputFilePath is a directory, then the directory
* manifest is returned.
* </p>
*
* @param jobId The id of the job whose output file is desired.
* @param outputFilePath The path to the file within output directory.
* @return An input stream to the output file contents.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public InputStream getJobOutputFile(
final String jobId,
final String outputFilePath
) throws IOException, GenieClientException {
return this.getJobOutputFile(jobId, outputFilePath, null, null);
}
/**
* Method to fetch an output file for a job from Genie and accepting an range of bytes to return.
*
* <p>
* <b>NOTE</b>: If the specified outputFilePath is a directory, then the directory
* manifest is returned.
* </p>
*
* <p>
* Range Logic:
* <p>
* {@literal rangeStart} but no {@literal rangeEnd} then go from the start byte to the end of available content
* <p>
* {@literal rangeStart} and {@literal rangeEnd} return that range of bytes from the file if they exist
* <p>
* If only {@literal rangeEnd} then return the last number of those bytes from the file if they exist
*
* @param jobId The id of the job whose output file is desired.
* @param outputFilePath The path to the file within output directory.
* @param rangeStart The start byte of the file to retrieve. Optional. Greater than or equal to 0.
* @param rangeEnd The end byte of the file to retrieve. Optional. Greater than or equal to 0. Must be
* greater than {@literal rangeStart}.
* @return An input stream to the output file contents.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range">Range Header Documentation</a>
*/
public InputStream getJobOutputFile(
final String jobId,
final String outputFilePath,
@Nullable final Long rangeStart,
@Nullable final Long rangeEnd
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
if (rangeStart != null && rangeStart < ZERO) {
throw new IllegalArgumentException("Range start must be greater than or equal to 0");
}
if (rangeEnd != null && rangeEnd < ZERO) {
throw new IllegalArgumentException("Range end must be greater than or equal to 0");
}
String rangeHeader = null;
if (rangeStart != null || rangeEnd != null) {
if (rangeStart != null && rangeEnd != null) {
if (rangeEnd < rangeStart) {
throw new IllegalArgumentException("Range end must be greater than range start");
}
rangeHeader = "bytes=" + rangeStart + "-" + rangeEnd;
} else if (rangeStart != null) {
rangeHeader = "bytes=" + rangeStart + "-";
} else {
rangeHeader = "bytes=-" + rangeEnd;
}
}
final String pathArg = StringUtils.isEmpty(outputFilePath) ? EMPTY_STRING : outputFilePath;
final ResponseBody body = rangeHeader == null
? this.jobService.getJobOutputFile(jobId, pathArg).execute().body()
: this.jobService.getJobOutputFile(jobId, pathArg, rangeHeader).execute().body();
if (body == null) {
throw new GenieClientException(String.format("No data for %s returned", outputFilePath));
}
return body.byteStream();
}
/**
* Method to fetch the status of a job.
*
* @param jobId The id of the job.
* @return The status of the Job.
* @throws GenieClientException If the response recieved is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public JobStatus getJobStatus(
final String jobId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
final JsonNode jsonNode = this.jobService.getJobStatus(jobId).execute().body();
if (jsonNode == null || jsonNode.getNodeType() != JsonNodeType.OBJECT) {
throw new GenieClientException("Unknown response from server: " + jsonNode);
}
try {
final JsonNode statusNode = jsonNode.get(STATUS);
if (statusNode == null || statusNode.getNodeType() != JsonNodeType.STRING) {
throw new GenieClientException("Unknown response format for status: " + statusNode);
}
return JobStatus.parse(statusNode.asText());
} catch (GeniePreconditionException ge) {
throw new GenieClientException(ge.getMessage());
}
}
/**
* Method to send a kill job request to Genie.
*
* @param jobId The id of the job.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
*/
public void killJob(final String jobId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
jobService.killJob(jobId).execute();
}
/**
* Wait for job to complete, until the given timeout.
*
* @param jobId the Genie job ID to wait for completion
* @param blockTimeout the time to block for (in ms), after which a
* GenieClientException will be thrown
* @param pollTime the time to sleep between polling for job status
* @return The job status for the job after completion
* @throws InterruptedException on thread errors.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @throws GenieTimeoutException If the job times out.
*/
public JobStatus waitForCompletion(final String jobId, final long blockTimeout, final long pollTime)
throws GenieClientException, InterruptedException, IOException, GenieTimeoutException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
final long startTime = System.currentTimeMillis();
int errorCount = 0;
// wait for job to finish
while (true) {
try {
final JobStatus status = this.getJobStatus(jobId);
if (status.isFinished()) {
return status;
}
// reset the error count
errorCount = 0;
} catch (final IOException ioe) {
errorCount++;
// Ignore for 5 times in a row
if (errorCount >= this.maxStatusRetries) {
throw ioe;
}
}
if (System.currentTimeMillis() - startTime < blockTimeout) {
Thread.sleep(pollTime);
} else {
throw new GenieTimeoutException("Timed out waiting for job to finish: " + jobId);
}
}
}
/**
* Wait for job to complete, until the given timeout.
*
* @param jobId the Genie job ID to wait for completion.
* @param blockTimeout the time to block for (in ms), after which a
* GenieClientException will be thrown.
* @return The job status for the job after completion.
* @throws InterruptedException on thread errors.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues.
* @throws GenieTimeoutException If the job times out.
*/
public JobStatus waitForCompletion(final String jobId, final long blockTimeout)
throws GenieClientException, InterruptedException, IOException, GenieTimeoutException {
if (StringUtils.isEmpty(jobId)) {
throw new IllegalArgumentException("Missing required parameter: jobId.");
}
final long pollTime = 10000L;
return waitForCompletion(jobId, blockTimeout, pollTime);
}
}
| 2,321 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/ApplicationClient.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.genie.client;
import com.github.fge.jsonpatch.JsonPatch;
import com.netflix.genie.client.apis.ApplicationService;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.client.configs.GenieNetworkConfiguration;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Command;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Retrofit;
import javax.annotation.Nullable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* Client library for the Application Service.
*
* @author amsharma
* @since 3.0.0
*/
@Slf4j
public class ApplicationClient {
private final ApplicationService applicationService;
/**
* Constructor.
*
* @param retrofit The configured {@link Retrofit} client to a Genie server
*/
public ApplicationClient(@NotNull final Retrofit retrofit) {
this.applicationService = retrofit.create(ApplicationService.class);
}
/**
* Constructor.
*
* @param url The endpoint URL of the Genie API. Not null or empty
* @param interceptors Any interceptors to configure the client with, can include security ones
* @param genieNetworkConfiguration The network configuration parameters. Could be null
* @throws GenieClientException On error
* @deprecated Use {@link #ApplicationClient(Retrofit)}
*/
@Deprecated
public ApplicationClient(
@NotEmpty final String url,
@Nullable final List<Interceptor> interceptors,
@Nullable final GenieNetworkConfiguration genieNetworkConfiguration
) throws GenieClientException {
this(GenieClientUtils.createRetrofitInstance(url, interceptors, genieNetworkConfiguration));
}
/* CRUD Methods */
/**
* Create an application in genie.
*
* @param application A application object.
* @return The id of the application created.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public String createApplication(final Application application) throws IOException, GenieClientException {
if (application == null) {
throw new IllegalArgumentException("Application cannot be null.");
}
final String locationHeader = this.applicationService
.createApplication(application)
.execute()
.headers()
.get(GenieClientUtils.LOCATION_HEADER);
if (StringUtils.isBlank(locationHeader)) {
throw new GenieClientException("No location header. Unable to get ID");
}
return GenieClientUtils.getIdFromLocation(locationHeader);
}
/**
* Method to get a list of all the applications.
*
* @return A list of applications.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public List<Application> getApplications() throws IOException, GenieClientException {
return this.getApplications(null, null, null, null, null);
}
/**
* Method to get a list of all the applications from Genie for the query parameters specified.
*
* @param name The name of the commands.
* @param user The user who created the command.
* @param statusList The list of Command statuses.
* @param tagList The list of tags.
* @param type The type of the application.
* @return A list of applications.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
* @deprecated Use {@link #getApplications(String, String, List, List, String, Integer, SortAttribute,
* SortDirection, Integer)}
*/
public List<Application> getApplications(
final String name,
final String user,
final List<String> statusList,
final List<String> tagList,
final String type
) throws IOException {
return this.getApplications(name, user, statusList, tagList, type, null, null, null, null);
}
/**
* Method to get a list of all the applications from Genie for the query parameters specified.
*
* @param name The name of the commands.
* @param user The user who created the command.
* @param statusList The list of Command statuses.
* @param tagList The list of tags.
* @param type The type of the application.
* @param pageSize The maximum number of results returned
* @param sortAttribute The entity attribute used to sort
* @param sortDirection The sort direction
* @param pageIndex The page index
* @return A list of applications.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public List<Application> getApplications(
@Nullable final String name,
@Nullable final String user,
@Nullable final List<String> statusList,
@Nullable final List<String> tagList,
@Nullable final String type,
@Nullable @Min(1) final Integer pageSize,
@Nullable final SortAttribute sortAttribute,
@Nullable final SortDirection sortDirection,
@Nullable @Min(0) final Integer pageIndex
) throws IOException {
return GenieClientUtils.parseSearchResultsResponse(
this.applicationService.getApplications(
name,
user,
statusList,
tagList,
type,
pageSize,
GenieClientUtils.getSortParameter(sortAttribute, sortDirection),
pageIndex
).execute(),
"applicationList",
Application.class
);
}
/**
* Method to get a Application from Genie.
*
* @param applicationId The id of the application to get.
* @return The application details.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public Application getApplication(final String applicationId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
return this.applicationService.getApplication(applicationId).execute().body();
}
/**
* Method to delete a application from Genie.
*
* @param applicationId The id of the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void deleteApplication(final String applicationId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
this.applicationService.deleteApplication(applicationId).execute();
}
/**
* Method to delete all applications from Genie.
*
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void deleteAllApplications() throws IOException, GenieClientException {
this.applicationService.deleteAllApplications().execute();
}
/**
* Method to patch a application using json patch instructions.
*
* @param applicationId The id of the application.
* @param patch The patch object specifying all the instructions.
* @throws GenieClientException For any other error.
* @throws IOException If the response received is not 2xx.
*/
public void patchApplication(final String applicationId, final JsonPatch patch)
throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (patch == null) {
throw new IllegalArgumentException("Patch cannot be null");
}
this.applicationService.patchApplication(applicationId, patch).execute();
}
/**
* Method to updated a application.
*
* @param applicationId The id of the application.
* @param application The updated application object to use.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void updateApplication(final String applicationId, final Application application)
throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (application == null) {
throw new IllegalArgumentException("Patch cannot be null");
}
this.applicationService.updateApplication(applicationId, application).execute();
}
/**
* Method to get all the commands for an application.
*
* @param applicationId The id of the application.
* @return The set of commands for the applications.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public List<Command> getCommandsForApplication(final String applicationId)
throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
return applicationService.getCommandsForApplication(applicationId).execute().body();
}
/* Methods to manipulate configs for a application */
/**
* Method to get all the configs for a application.
*
* @param applicationId The id of the application.
* @return The set of configs for the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public Set<String> getConfigsForApplication(final String applicationId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
return applicationService.getConfigsForApplication(applicationId).execute().body();
}
/**
* Method to add configs to a application.
*
* @param applicationId The id of the application.
* @param configs The set of configs to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void addConfigsToApplication(
final String applicationId, final Set<String> configs
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (configs == null || configs.isEmpty()) {
throw new IllegalArgumentException("Configs cannot be null or empty");
}
applicationService.addConfigsToApplication(applicationId, configs).execute();
}
/**
* Method to update configs for a application.
*
* @param applicationId The id of the application.
* @param configs The set of configs to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void updateConfigsForApplication(
final String applicationId, final Set<String> configs
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (configs == null || configs.isEmpty()) {
throw new IllegalArgumentException("Configs cannot be null or empty");
}
applicationService.updateConfigsForApplication(applicationId, configs).execute();
}
/**
* Remove all configs for this application.
*
* @param applicationId The id of the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void removeAllConfigsForApplication(
final String applicationId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
applicationService.removeAllConfigsForApplication(applicationId).execute();
}
//****************** Methods to manipulate dependencies for a application *********************/
/**
* Method to get all the dependency files for an application.
*
* @param applicationId The id of the application.
* @return The set of dependencies for the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public Set<String> getDependenciesForApplication(final String applicationId) throws IOException,
GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
return applicationService.getDependenciesForApplication(applicationId).execute().body();
}
/**
* Method to add dependencies to a application.
*
* @param applicationId The id of the application.
* @param dependencies The set of dependencies to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void addDependenciesToApplication(
final String applicationId, final Set<String> dependencies
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (dependencies == null || dependencies.isEmpty()) {
throw new IllegalArgumentException("Dependencies cannot be null or empty");
}
applicationService.addDependenciesToApplication(applicationId, dependencies).execute();
}
/**
* Method to update dependencies for a application.
*
* @param applicationId The id of the application.
* @param dependencies The set of dependencies to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void updateDependenciesForApplication(
final String applicationId, final Set<String> dependencies
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (dependencies == null || dependencies.isEmpty()) {
throw new IllegalArgumentException("Dependencies cannot be null or empty");
}
applicationService.updateDependenciesForApplication(applicationId, dependencies).execute();
}
/**
* Remove all dependencies for this application.
*
* @param applicationId The id of the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void removeAllDependenciesForApplication(
final String applicationId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
applicationService.removeAllDependenciesForApplication(applicationId).execute();
}
//**************** Methods to manipulate tags for a application *********************/
/**
* Method to get all the tags for a application.
*
* @param applicationId The id of the application.
* @return The set of configs for the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public Set<String> getTagsForApplication(final String applicationId) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
return applicationService.getTagsForApplication(applicationId).execute().body();
}
/**
* Method to add tags to a application.
*
* @param applicationId The id of the application.
* @param tags The set of tags to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void addTagsToApplication(
final String applicationId, final Set<String> tags
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (tags == null || tags.isEmpty()) {
throw new IllegalArgumentException("Tags cannot be null or empty");
}
applicationService.addTagsToApplication(applicationId, tags).execute();
}
/**
* Method to update tags for a application.
*
* @param applicationId The id of the application.
* @param tags The set of tags to add.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void updateTagsForApplication(
final String applicationId, final Set<String> tags
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (tags == null || tags.isEmpty()) {
throw new IllegalArgumentException("Tags cannot be null or empty");
}
applicationService.updateTagsForApplication(applicationId, tags).execute();
}
/**
* Remove a tag from a application.
*
* @param applicationId The id of the application.
* @param tag The tag to remove.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void removeTagFromApplication(
final String applicationId,
final String tag
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
if (StringUtils.isEmpty(tag)) {
throw new IllegalArgumentException("Missing required parameter: tag.");
}
applicationService.removeTagForApplication(applicationId, tag).execute();
}
/**
* Remove all tags for this application.
*
* @param applicationId The id of the application.
* @throws GenieClientException If the response received is not 2xx.
* @throws IOException For Network and other IO issues
*/
public void removeAllTagsForApplication(
final String applicationId
) throws IOException, GenieClientException {
if (StringUtils.isEmpty(applicationId)) {
throw new IllegalArgumentException("Missing required parameter: applicationId.");
}
applicationService.removeAllTagsForApplication(applicationId).execute();
}
}
| 2,322 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/GenieClientUtils.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.genie.client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.google.common.collect.Lists;
import com.netflix.genie.client.apis.SortAttribute;
import com.netflix.genie.client.apis.SortDirection;
import com.netflix.genie.client.configs.GenieNetworkConfiguration;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.client.interceptors.ResponseMappingInterceptor;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import javax.annotation.Nullable;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Utility methods for the Genie client.
*
* @author tgianos
* @since 4.0.0
*/
final class GenieClientUtils {
static final String LOCATION_HEADER = "location";
private static final String SLASH = "/";
/**
* Utility class doesn't need a public constructor.
*/
private GenieClientUtils() {
}
/**
* Get a {@link Retrofit} instance given the parameters.
*
* @param url The url of the Genie Service.
* @param interceptors All desired interceptors for the client to be created
* @param genieNetworkConfiguration A configuration object that provides network settings for HTTP calls.
* @return A {@link Retrofit} instance configured with the given information
* @throws GenieClientException If there is any problem creating the constructor
*/
static Retrofit createRetrofitInstance(
@NotBlank final String url,
@Nullable final List<Interceptor> interceptors,
@Nullable final GenieNetworkConfiguration genieNetworkConfiguration
) throws GenieClientException {
if (StringUtils.isBlank(url)) {
throw new GenieClientException("Service URL cannot be empty or null");
}
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (genieNetworkConfiguration != null) {
if (genieNetworkConfiguration.getConnectTimeout() != GenieNetworkConfiguration.DEFAULT_TIMEOUT) {
builder.connectTimeout(genieNetworkConfiguration.getConnectTimeout(), TimeUnit.MILLISECONDS);
}
if (genieNetworkConfiguration.getReadTimeout() != GenieNetworkConfiguration.DEFAULT_TIMEOUT) {
builder.readTimeout(genieNetworkConfiguration.getReadTimeout(), TimeUnit.MILLISECONDS);
}
if (genieNetworkConfiguration.getWriteTimeout() != GenieNetworkConfiguration.DEFAULT_TIMEOUT) {
builder.writeTimeout(genieNetworkConfiguration.getWriteTimeout(), TimeUnit.MILLISECONDS);
}
builder.retryOnConnectionFailure(genieNetworkConfiguration.isRetryOnConnectionFailure());
}
// Add the interceptor to map the retrofit response code to corresponding Genie Exceptions in case of
// 4xx and 5xx errors.
builder.addInterceptor(new ResponseMappingInterceptor());
if (interceptors != null) {
interceptors.forEach(builder::addInterceptor);
}
return new Retrofit
.Builder()
.baseUrl(url)
.addConverterFactory(JacksonConverterFactory.create(GenieObjectMapper.getMapper()))
.client(builder.build())
.build();
}
/**
* Bind JSON to a Java POJO.
*
* @param node The JSON to convert
* @param clazz The clazz to bind to
* @param <T> The type of the POJO returned
* @return An instance of {@code T}
* @throws IOException If the JSON can't bind
*/
static <T> T treeToValue(final JsonNode node, final Class<T> clazz) throws IOException {
return GenieObjectMapper.getMapper().treeToValue(node, clazz);
}
/**
* Helper method to parse the id out of the location string in the Header.
*
* @param location The location string in the header.
* @return The id of the entity embedded in the location.
*/
static String getIdFromLocation(final String location) {
return location.substring(location.lastIndexOf(SLASH) + 1);
}
/**
* Given a response from a Genie search API parse the results from the list.
*
* @param response The response JSON from the server
* @param searchResultKey The JSON key the search result list is expected to exist under
* @param clazz The expected response type to bind to
* @param <T> The type of POJO to bind to
* @return A {@link List} of {@literal T} or empty if no results
* @throws IOException On error reading the body
* @throws GenieClientException On unsuccessful query
*/
static <T> List<T> parseSearchResultsResponse(
final Response<JsonNode> response,
final String searchResultKey,
final Class<T> clazz
) throws IOException {
if (!response.isSuccessful()) {
throw new GenieClientException(
"Search failed due to "
+ (response.errorBody() == null ? response.message() : response.errorBody().toString())
);
}
// Request returned some 2xx
final JsonNode body = response.body();
if (body == null || body.getNodeType() != JsonNodeType.OBJECT) {
return Lists.newArrayList();
}
final JsonNode embedded = body.get("_embedded");
if (embedded == null || embedded.getNodeType() != JsonNodeType.OBJECT) {
// Kind of an invalid response? Could return error or just swallow?
return Lists.newArrayList();
}
final JsonNode searchResultsJson = embedded.get(searchResultKey);
if (searchResultsJson == null || searchResultsJson.getNodeType() != JsonNodeType.ARRAY) {
return Lists.newArrayList();
}
final List<T> searchList = new ArrayList<>();
for (final JsonNode searchResultJson : searchResultsJson) {
final T searchResult = GenieClientUtils.treeToValue(searchResultJson, clazz);
searchList.add(searchResult);
}
return searchList;
}
@Nullable
public static String getSortParameter(
@Nullable final SortAttribute sortAttribute,
@Nullable final SortDirection sortDirection
) {
if (sortAttribute != null || sortDirection != null) {
return ""
+ StringUtils.lowerCase((sortAttribute != null ? sortAttribute : SortAttribute.DEFAULT).name())
+ ","
+ (sortDirection != null ? sortDirection : SortDirection.DEFAULT);
} else {
return null;
}
}
}
| 2,323 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/package-info.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.
*
*/
/**
* Client library for Genie.
*
* @author tgianos
*/
package com.netflix.genie.client;
| 2,324 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/interceptors/ResponseMappingInterceptor.java | /*
*
* Copyright 2016 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.genie.client.interceptors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.client.exceptions.GenieClientTooManyRequestsException;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.IOException;
import java.io.Reader;
/**
* Class that evaluates the retrofit response code and maps it to an appropriate Genie Exception.
*
* @author amsharma
* @since 3.0.0
*/
public class ResponseMappingInterceptor implements Interceptor {
private static final String NO_MESSAGE_FALLBACK = "No error detailed message in server response";
private static final String ERROR_MESSAGE_KEY = "message";
private static final int HTTP_TOO_MANY_REQUESTS = 429;
/**
* Constructor.
*/
public ResponseMappingInterceptor() {
}
/**
* {@inheritDoc}
*/
@Override
public Response intercept(final Chain chain) throws IOException {
final Response response = chain.proceed(chain.request());
if (response.isSuccessful()) {
return response;
} else {
final ResponseBody body = response.body();
if (body != null) {
final Reader bodyReader = body.charStream();
if (bodyReader != null) {
try {
final JsonNode responseBody = GenieObjectMapper.getMapper().readTree(bodyReader);
final String errorMessage =
responseBody == null || !responseBody.has(ERROR_MESSAGE_KEY)
? NO_MESSAGE_FALLBACK
: responseBody.get(ERROR_MESSAGE_KEY).asText();
final int responseCode = response.code();
if (responseCode == HTTP_TOO_MANY_REQUESTS) {
throw new GenieClientTooManyRequestsException(errorMessage);
}
throw new GenieClientException(
responseCode,
errorMessage
);
} catch (final JsonProcessingException jpe) {
throw new GenieClientException("Failed to parse server response as JSON", jpe);
}
}
}
throw new GenieClientException(response.code(), "Server response body is empty");
}
}
}
| 2,325 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/interceptors/SecurityInterceptor.java | /*
*
* Copyright 2016 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.genie.client.interceptors;
import okhttp3.Interceptor;
/**
* An interface whose implementation is supposed to modify the HTTP Request by adding Security credentials.
*
* @author amsharma
* @since 3.0.0
*/
public interface SecurityInterceptor extends Interceptor {
}
| 2,326 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/interceptors/UserAgentInsertInterceptor.java | /*
*
* Copyright 2016 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.genie.client.interceptors;
import com.google.common.net.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
/**
* An interceptor class that updates the User Agent String of the request with user info.
*
* @author amsharma
* @since 3.0.0
*/
@Slf4j
public class UserAgentInsertInterceptor implements Interceptor {
private static final String DEFAULT_USER_AGENT_STRING = "Genie Java Client";
private final String userAgent;
/**
* Constructor.
*
* @param userAgent The user agent string to use
*/
public UserAgentInsertInterceptor(final String userAgent) {
if (StringUtils.isEmpty(userAgent)) {
this.userAgent = DEFAULT_USER_AGENT_STRING;
} else {
this.userAgent = userAgent;
}
}
/**
* {@inheritDoc}
*/
@Override
public Response intercept(final Chain chain) throws IOException {
final Request newRequest = chain
.request()
.newBuilder()
.addHeader(HttpHeaders.USER_AGENT, this.userAgent)
.build();
log.debug("Sending request {} on {} {}", newRequest.url(), chain.connection(), newRequest.headers());
return chain.proceed(newRequest);
}
}
| 2,327 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/interceptors/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* A package that contains all interceptors to be added to modify outgoing requests and incoming responses.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.interceptors;
| 2,328 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/JobService.java | /*
*
* Copyright 2016 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.genie.client.apis;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.Job;
import com.netflix.genie.common.dto.JobExecution;
import com.netflix.genie.common.dto.JobMetadata;
import com.netflix.genie.common.dto.JobRequest;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.HeaderMap;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Streaming;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An interface that provides all methods needed for the Genie job client implementation.
*
* @author amsharma
* @since 3.0.0
*/
public interface JobService {
/**
* Path to Jobs.
*/
String JOBS_URL_SUFFIX = "/api/v3/jobs";
/**
* Method to submit a job to Genie.
*
* @param request The request object containing all the
* @return A callable object.
*/
@POST(JOBS_URL_SUFFIX)
Call<Void> submitJob(@Body JobRequest request);
/**
* Method to submit a job to Genie with user defined custom headers.
*
* @param customHeaders client defined custom headers.
* @param request The request object containing all the
* @return A callable object.
*/
@POST(JOBS_URL_SUFFIX)
Call<Void> submitJob(@HeaderMap Map<String, String> customHeaders,
@Body JobRequest request);
/**
* Submit a job with attachments.
*
* @param request A JobRequest object containing all the details needed to run the job.
* @param attachments A list of all the attachment files to be sent to the server.
* @return A callable object.
*/
@Multipart
@POST(JOBS_URL_SUFFIX)
Call<Void> submitJobWithAttachments(
@Part("request") JobRequest request,
@Part List<MultipartBody.Part> attachments
);
/**
* Submit a job with attachments and custom headers.
*
* @param customHeaders client defined custom headers.
* @param request A JobRequest object containing all the details needed to run the job.
* @param attachments A list of all the attachment files to be sent to the server.
* @return A callable object.
*/
@Multipart
@POST(JOBS_URL_SUFFIX)
Call<Void> submitJobWithAttachments(
@HeaderMap Map<String, String> customHeaders,
@Part("request") JobRequest request,
@Part List<MultipartBody.Part> attachments
);
/**
* Method to get all jobs from Genie.
*
* @param id id for job
* @param name name of job (can be a SQL-style pattern such as HIVE%)
* @param user user who submitted job
* @param statuses statuses of jobs to find
* @param tags tags for the job
* @param clusterName the name of the cluster
* @param clusterId the id of the cluster
* @param commandName the name of the command run by the job
* @param commandId the id of the command run by the job
* @param minStarted The time which the job had to start after in order to be return (inclusive)
* @param maxStarted The time which the job had to start before in order to be returned (exclusive)
* @param minFinished The time which the job had to finish after in order to be return (inclusive)
* @param maxFinished The time which the job had to finish before in order to be returned (exclusive)
* @param grouping The grouping the job should be a member of
* @param groupingInstance The grouping instance the job should be a member of
* @param size The maximum number of results in the page
* @param sort The sort order
* @param page The page index
* @return A callable object.
*/
@SuppressWarnings("checkstyle:parameternumber")
@GET(JOBS_URL_SUFFIX)
Call<JsonNode> getJobs(
@Query("id") String id,
@Query("name") String name,
@Query("user") String user,
@Query("status") Set<String> statuses,
@Query("tag") Set<String> tags,
@Query("clusterName") String clusterName,
@Query("clusterId") String clusterId,
@Query("commandName") String commandName,
@Query("commandId") String commandId,
@Query("minStarted") Long minStarted,
@Query("maxStarted") Long maxStarted,
@Query("minFinished") Long minFinished,
@Query("maxFinished") Long maxFinished,
@Query("grouping") String grouping,
@Query("groupingInstance") String groupingInstance,
@Query("size") Integer size,
@Query("sort") String sort,
@Query("page") Integer page
);
/**
* Method to fetch a single job from Genie.
*
* @param jobId The id of the job to get.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}")
Call<Job> getJob(@Path("id") String jobId);
/**
* Method to fetch an output file for a job from Genie.
*
* <p>
* <b>NOTE</b>: If the specified outputFilePath is a directory, then the directory
* manifest is returned.
* </p>
*
* @param jobId The id of the job whose output file is desired.
* @param outputFilePath The path to the file within output directory.
* @return A callable object.
*/
@Streaming
@GET(JOBS_URL_SUFFIX + "/{id}/output/{path}")
Call<ResponseBody> getJobOutputFile(
@Path("id") String jobId,
@Path(value = "path", encoded = true) String outputFilePath
);
/**
* Method to fetch partial output file for a job from Genie.
*
* <p>
* <b>NOTE</b>: If the specified outputFilePath is a directory, then the directory
* manifest is returned.
* </p>
*
* @param jobId The id of the job whose output file is desired.
* @param outputFilePath The path to the file within output directory.
* @param range The range header value
* @return A callable object.
*/
@Streaming
@GET(JOBS_URL_SUFFIX + "/{id}/output/{path}")
Call<ResponseBody> getJobOutputFile(
@Path("id") String jobId,
@Path(value = "path", encoded = true) String outputFilePath,
@Header("Range") String range
);
/**
* Method to get Job status.
*
* @param jobId The id of the job whose status is desired.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/status")
Call<JsonNode> getJobStatus(@Path("id") String jobId);
/**
* Method to get the cluster information on which a job is run.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/cluster")
Call<Cluster> getJobCluster(@Path("id") String jobId);
/**
* Method to get the command information on which a job is run.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/command")
Call<Command> getJobCommand(@Path("id") String jobId);
/**
* Method to get the JobRequest for a job.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/request")
Call<JobRequest> getJobRequest(@Path("id") String jobId);
/**
* Method to get the execution information for a job.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/execution")
Call<JobExecution> getJobExecution(@Path("id") String jobId);
/**
* Method to get the metadata information for a job.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/metadata")
Call<JobMetadata> getJobMetadata(@Path("id") String jobId);
/**
* Method to get the Applications for a job.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@GET(JOBS_URL_SUFFIX + "/{id}/applications")
Call<List<Application>> getJobApplications(@Path("id") String jobId);
/**
* Method to send a job kill request to Genie.
*
* @param jobId The id of the job.
* @return A callable object.
*/
@DELETE(JOBS_URL_SUFFIX + "/{id}")
Call<Void> killJob(@Path("id") String jobId);
}
| 2,329 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/CommandService.java | /*
*
* Copyright 2016 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.genie.client.apis;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonpatch.JsonPatch;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import java.util.List;
import java.util.Set;
/**
* An interface that provides all methods needed for the Genie command client implementation.
*
* @author amsharma
* @since 3.0.0
*/
public interface CommandService {
/**
* Path to Commands.
*/
String COMMAND_URL_SUFFIX = "/api/v3/commands";
/******************* CRUD Methods ***************************/
/**
* Method to create a command in Genie.
*
* @param command The command object.
* @return A callable object.
*/
@POST(COMMAND_URL_SUFFIX)
Call<Void> createCommand(@Body Command command);
/**
* Method to update a command in Genie.
*
* @param commandId The id of the command to update.
* @param command The command object.
* @return A callable object.
*/
@PUT(COMMAND_URL_SUFFIX + "/{id}")
Call<Void> updateCommand(@Path("id") String commandId, @Body Command command);
/**
* Method to get all commands from Genie filtered based on query params.
*
* @param name The name of the commands.
* @param user The user who created the command.
* @param statusList The list of Command statuses.
* @param tagList The list of tags.
* @param size The maximum number of results in the page
* @param sort The sort order
* @param page The page index
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX)
Call<JsonNode> getCommands(
@Query("name") String name,
@Query("user") String user,
@Query("status") List<String> statusList,
@Query("tag") List<String> tagList,
@Query("size") Integer size,
@Query("sort") String sort,
@Query("page") Integer page
);
/**
* Method to fetch a single job from Genie.
*
* @param commandId The id of the command to get.
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX + "/{id}")
Call<Command> getCommand(@Path("id") String commandId);
/**
* Method to delete a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}")
Call<Void> deleteCommand(@Path("id") String commandId);
/**
* Method to delete all commands in Genie.
*
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX)
Call<Void> deleteAllCommands();
/**
* Patch a command using JSON Patch.
*
* @param commandId The id of the command to patch
* @param patch The JSON Patch instructions
* @return A callable object.
*/
@PATCH(COMMAND_URL_SUFFIX + "/{id}")
Call<Void> patchCommand(@Path("id") String commandId, @Body JsonPatch patch);
/****************** Methods to manipulate applications and clusters for a command *********************/
/**
* Method to get applications for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX + "/{id}/applications")
Call<List<Application>> getApplicationsForCommand(@Path("id") String commandId);
/**
* Method to get clusters for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX + "/{id}/clusters")
Call<List<Cluster>> getClustersForCommand(@Path("id") String commandId);
/**
* Method to add applications to a command in Genie.
*
* @param commandId The id of the command..
* @param applicationIds The application Ids to be added.
* @return A callable object.
*/
@POST(COMMAND_URL_SUFFIX + "/{id}/applications")
Call<Void> addApplicationsToCommand(@Path("id") String commandId, @Body List<String> applicationIds);
/**
* Method to override and set applications for a command in Genie.
*
* @param commandId The id of the command..
* @param applicationIds The application Ids to be added.
* @return A callable object.
*/
@PUT(COMMAND_URL_SUFFIX + "/{id}/applications")
Call<Void> setApplicationsForCommand(@Path("id") String commandId, @Body List<String> applicationIds);
/**
* Method to delete a application for a command in Genie.
*
* @param commandId The id of the command.
* @param applicationId The application to delete.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}/applications/{applicationId}")
Call<Void> removeApplicationForCommand(
@Path("id") String commandId,
@Path("applicationId") String applicationId
);
/**
* Method to delete all applications for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}/applications")
Call<Void> removeAllApplicationsForCommand(@Path("id") String commandId);
/****************** Methods to manipulate configs for a command *********************/
/**
* Method to get configs for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX + "/{id}/configs")
Call<Set<String>> getConfigsForCommand(@Path("id") String commandId);
/**
* Method to add configs to a command in Genie.
*
* @param commandId The id of the command..
* @param configs The configs to be added.
* @return A callable object.
*/
@POST(COMMAND_URL_SUFFIX + "/{id}/configs")
Call<Void> addConfigsToCommand(@Path("id") String commandId, @Body Set<String> configs);
/**
* Method to update configs for a command in Genie.
*
* @param commandId The id of the command..
* @param configs The configs to be added.
* @return A callable object.
*/
@PUT(COMMAND_URL_SUFFIX + "/{id}/configs")
Call<Void> updateConfigsForCommand(@Path("id") String commandId, @Body Set<String> configs);
/**
* Method to delete all configs for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}/configs")
Call<Void> removeAllConfigsForCommand(@Path("id") String commandId);
/****************** Methods to manipulate dependencies for a command *********************/
/**
* Method to get dependency files for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX + "/{id}/dependencies")
Call<Set<String>> getDependenciesForCommand(@Path("id") String commandId);
/**
* Method to add dependencies to a command in Genie.
*
* @param commandId The id of the command..
* @param dependencies The dependencies to be added.
* @return A callable object.
*/
@POST(COMMAND_URL_SUFFIX + "/{id}/dependencies")
Call<Void> addDependenciesToCommand(
@Path("id") String commandId,
@Body Set<String> dependencies
);
/**
* Method to update dependencies for a command in Genie.
*
* @param commandId The id of the command..
* @param dependencies The dependencies to be added.
* @return A callable object.
*/
@PUT(COMMAND_URL_SUFFIX + "/{id}/dependencies")
Call<Void> updateDependenciesForCommand(
@Path("id") String commandId,
@Body Set<String> dependencies
);
/**
* Method to delete all dependencies for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}/dependencies")
Call<Void> removeAllDependenciesForCommand(@Path("id") String commandId);
/****************** Methods to manipulate tags for a command *********************/
/**
* Method to get tags for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@GET(COMMAND_URL_SUFFIX + "/{id}/tags")
Call<Set<String>> getTagsForCommand(@Path("id") String commandId);
/**
* Method to add tags to a command in Genie.
*
* @param commandId The id of the command..
* @param tags The tags to be added.
* @return A callable object.
*/
@POST(COMMAND_URL_SUFFIX + "/{id}/tags")
Call<Void> addTagsToCommand(@Path("id") String commandId, @Body Set<String> tags);
/**
* Method to update tags for a command in Genie.
*
* @param commandId The id of the command..
* @param tags The tags to be added.
* @return A callable object.
*/
@PUT(COMMAND_URL_SUFFIX + "/{id}/tags")
Call<Void> updateTagsForCommand(@Path("id") String commandId, @Body Set<String> tags);
/**
* Method to delete a tag for a command in Genie.
*
* @param commandId The id of the command.
* @param tag The tag to delete.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}/tags/{tag}")
Call<Void> removeTagForCommand(@Path("id") String commandId, @Path("tag") String tag);
/**
* Method to delete all tags for a command in Genie.
*
* @param commandId The id of the command.
* @return A callable object.
*/
@DELETE(COMMAND_URL_SUFFIX + "/{id}/tags")
Call<Void> removeAllTagsForCommand(@Path("id") String commandId);
}
| 2,330 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/SortAttribute.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.genie.client.apis;
/**
* Sort key for entity search results.
* This is a subset of all sort attributes supported by the server.
*
* @author mprimi
* @since 4.0.0
*/
public enum SortAttribute {
/**
* Entity unique id.
*/
ID,
/**
* Creation date.
*/
CREATED,
/**
* Last update.
*/
UPDATED,
/**
* Entity version.
*/
VERSION;
/**
* Default sort attribute.
*/
public static final SortAttribute DEFAULT = CREATED;
}
| 2,331 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/SortDirection.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.genie.client.apis;
/**
* Sort direction of entity search results.
*
* @author mprimi
* @since 4.0.0
*/
public enum SortDirection {
/**
* Ascending.
*/
ASC,
/**
* Descending.
*/
DESC;
/**
* Default sort direction.
*/
public static final SortDirection DEFAULT = SortDirection.ASC;
}
| 2,332 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/ApplicationService.java | /*
*
* Copyright 2016 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.genie.client.apis;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonpatch.JsonPatch;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Command;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import java.util.List;
import java.util.Set;
/**
* An interface that provides all methods needed for the Genie application client implementation.
*
* @author amsharma
* @since 3.0.0
*/
public interface ApplicationService {
/**
* Path to Applications.
*/
String APPLICATION_URL_SUFFIX = "/api/v3/applications";
/******************* CRUD Methods ***************************/
/**
* Method to create a application in Genie.
*
* @param application The application object.
* @return A callable object.
*/
@POST(APPLICATION_URL_SUFFIX)
Call<Void> createApplication(@Body Application application);
/**
* Method to update a application in Genie.
*
* @param applicationId The id of the application to update.
* @param application The application object.
* @return A callable object.
*/
@PUT(APPLICATION_URL_SUFFIX + "/{id}")
Call<Void> updateApplication(@Path("id") String applicationId, @Body Application application);
/**
* Method to get all applications from Genie.
*
* @param name The name of the commands.
* @param user The user who created the command.
* @param statusList The list of Command statuses.
* @param tagList The list of tags.
* @param type The type of the application.
* @param size The maximum number of results in the page
* @param sort The sort order
* @param page The page index
* @return A callable object.
*/
@GET(APPLICATION_URL_SUFFIX)
Call<JsonNode> getApplications(
@Query("name") String name,
@Query("user") String user,
@Query("status") List<String> statusList,
@Query("tag") List<String> tagList,
@Query("type") String type,
@Query("size") Integer size,
@Query("sort") String sort,
@Query("page") Integer page
);
/**
* Method to fetch a single job from Genie.
*
* @param applicationId The id of the application to get.
* @return A callable object.
*/
@GET(APPLICATION_URL_SUFFIX + "/{id}")
Call<Application> getApplication(@Path("id") String applicationId);
/**
* Method to delete a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@DELETE(APPLICATION_URL_SUFFIX + "/{id}")
Call<Void> deleteApplication(@Path("id") String applicationId);
/**
* Method to delete all applications in Genie.
*
* @return A callable object.
*/
@DELETE(APPLICATION_URL_SUFFIX)
Call<Void> deleteAllApplications();
/**
* Patch a application using JSON Patch.
*
* @param applicationId The id of the application to patch
* @param patch The JSON Patch instructions
* @return A callable object.
*/
@PATCH(APPLICATION_URL_SUFFIX + "/{id}")
Call<Void> patchApplication(@Path("id") String applicationId, @Body JsonPatch patch);
/**
* Method to get commmands for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@GET(APPLICATION_URL_SUFFIX + "/{id}/commands")
Call<List<Command>> getCommandsForApplication(@Path("id") String applicationId);
/****************** Methods to manipulate dependencies for a application *********************/
/**
* Method to get dependency files for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@GET(APPLICATION_URL_SUFFIX + "/{id}/dependencies")
Call<Set<String>> getDependenciesForApplication(@Path("id") String applicationId);
/**
* Method to add dependencies to a application in Genie.
*
* @param applicationId The id of the application..
* @param dependencies The dependencies to be added.
* @return A callable object.
*/
@POST(APPLICATION_URL_SUFFIX + "/{id}/dependencies")
Call<Void> addDependenciesToApplication(
@Path("id") String applicationId,
@Body Set<String> dependencies
);
/**
* Method to update dependencies for a application in Genie.
*
* @param applicationId The id of the application..
* @param dependencies The dependencies to be added.
* @return A callable object.
*/
@PUT(APPLICATION_URL_SUFFIX + "/{id}/dependencies")
Call<Void> updateDependenciesForApplication(
@Path("id") String applicationId,
@Body Set<String> dependencies
);
/**
* Method to delete all dependencies for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@DELETE(APPLICATION_URL_SUFFIX + "/{id}/dependencies")
Call<Void> removeAllDependenciesForApplication(@Path("id") String applicationId);
/****************** Methods to manipulate configs for a application *********************/
/**
* Method to get configs for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@GET(APPLICATION_URL_SUFFIX + "/{id}/configs")
Call<Set<String>> getConfigsForApplication(@Path("id") String applicationId);
/**
* Method to add configs to a application in Genie.
*
* @param applicationId The id of the application..
* @param configs The configs to be added.
* @return A callable object.
*/
@POST(APPLICATION_URL_SUFFIX + "/{id}/configs")
Call<Void> addConfigsToApplication(@Path("id") String applicationId, @Body Set<String> configs);
/**
* Method to update configs for a application in Genie.
*
* @param applicationId The id of the application..
* @param configs The configs to be added.
* @return A callable object.
*/
@PUT(APPLICATION_URL_SUFFIX + "/{id}/configs")
Call<Void> updateConfigsForApplication(@Path("id") String applicationId, @Body Set<String> configs);
/**
* Method to delete all configs for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@DELETE(APPLICATION_URL_SUFFIX + "/{id}/configs")
Call<Void> removeAllConfigsForApplication(@Path("id") String applicationId);
/****************** Methods to manipulate tags for a application *********************/
/**
* Method to get tags for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@GET(APPLICATION_URL_SUFFIX + "/{id}/tags")
Call<Set<String>> getTagsForApplication(@Path("id") String applicationId);
/**
* Method to add tags to a application in Genie.
*
* @param applicationId The id of the application..
* @param tags The tags to be added.
* @return A callable object.
*/
@POST(APPLICATION_URL_SUFFIX + "/{id}/tags")
Call<Void> addTagsToApplication(@Path("id") String applicationId, @Body Set<String> tags);
/**
* Method to update tags for a application in Genie.
*
* @param applicationId The id of the application..
* @param tags The tags to be added.
* @return A callable object.
*/
@PUT(APPLICATION_URL_SUFFIX + "/{id}/tags")
Call<Void> updateTagsForApplication(@Path("id") String applicationId, @Body Set<String> tags);
/**
* Method to delete a tag for a application in Genie.
*
* @param applicationId The id of the application.
* @param tag The tag to delete.
* @return A callable object.
*/
@DELETE(APPLICATION_URL_SUFFIX + "/{id}/tags/{tag}")
Call<Void> removeTagForApplication(@Path("id") String applicationId, @Path("tag") String tag);
/**
* Method to delete all tags for a application in Genie.
*
* @param applicationId The id of the application.
* @return A callable object.
*/
@DELETE(APPLICATION_URL_SUFFIX + "/{id}/tags")
Call<Void> removeAllTagsForApplication(@Path("id") String applicationId);
}
| 2,333 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/TokenService.java | /*
*
* Copyright 2016 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.genie.client.apis;
import com.netflix.genie.client.security.oauth2.AccessToken;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import retrofit2.http.Url;
import java.util.Map;
/**
* A interface to fetch access tokens.
*
* @author amsharma
* @since 3.0.0
*/
public interface TokenService {
/**
* A method to retrieve oauth tokens from the server.
*
* @param params A map of all the fields needed to fetch credentials.
* @param url The URL of the IDP from where to get the credentials.
* @return A callable object.
*/
@FormUrlEncoded
@POST
Call<AccessToken> getToken(@Url String url, @FieldMap Map<String, String> params);
}
| 2,334 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/ClusterService.java | /*
*
* Copyright 2016 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.genie.client.apis;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonpatch.JsonPatch;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import java.util.List;
import java.util.Set;
/**
* An interface that provides all methods needed for the Genie cluster client implementation.
*
* @author amsharma
* @since 3.0.0
*/
public interface ClusterService {
/**
* Path to Clusters.
*/
String CLUSTER_URL_SUFFIX = "/api/v3/clusters";
/******************* CRUD Methods ***************************/
/**
* Method to create a cluster in Genie.
*
* @param cluster The cluster object.
* @return A callable object.
*/
@POST(CLUSTER_URL_SUFFIX)
Call<Void> createCluster(@Body Cluster cluster);
/**
* Method to update a cluster in Genie.
*
* @param clusterId The id of the cluster to update.
* @param cluster The cluster object.
* @return A callable object.
*/
@PUT(CLUSTER_URL_SUFFIX + "/{id}")
Call<Void> updateCluster(@Path("id") String clusterId, @Body Cluster cluster);
/**
* Method to get clusters from Genie based on filters specified.
*
* @param name The name of the cluster.
* @param statusList The list of statuses.
* @param tagList The list of tags.
* @param minUpdateTime Minimum Time after which cluster was updated.
* @param maxUpdateTime Maximum Time before which cluster was updated.
* @param size The maximum number of results in the page
* @param sort The sort order
* @param page The page index
* @return A callable object.
*/
@GET(CLUSTER_URL_SUFFIX)
Call<JsonNode> getClusters(
@Query("name") String name,
@Query("status") List<String> statusList,
@Query("tag") List<String> tagList,
@Query("minUpdateTime") Long minUpdateTime,
@Query("maxUpdateTime") Long maxUpdateTime,
@Query("size") Integer size,
@Query("sort") String sort,
@Query("page") Integer page
);
/**
* getClusters(
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "status", required = false) Set<String> statuses,
@RequestParam(value = "tag", required = false) Set<String> tags,
@RequestParam(value = "minUpdateTime", required = false) Long minUpdateTime,
@RequestParam(value = "maxUpdateTime", required = false) Long maxUpdateTime,
@PageableDefault(page = 0, size = 64, sort = {"updated"}, direction = Sort.Direction.DESC) Pageable page,
PagedResourcesAssembler<Cluster> assembler
)
*
*/
/**
* Method to fetch a single job from Genie.
*
* @param clusterId The id of the cluster to get.
* @return A callable object.
*/
@GET(CLUSTER_URL_SUFFIX + "/{id}")
Call<Cluster> getCluster(@Path("id") String clusterId);
/**
* Method to delete a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}")
Call<Void> deleteCluster(@Path("id") String clusterId);
/**
* Method to delete all clusters in Genie.
*
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX)
Call<Void> deleteAllClusters();
/**
* Patch a cluster using JSON Patch.
*
* @param clusterId The id of the cluster to patch
* @param patch The JSON Patch instructions
* @return A callable object.
*/
@PATCH(CLUSTER_URL_SUFFIX + "/{id}")
Call<Void> patchCluster(@Path("id") String clusterId, @Body JsonPatch patch);
/****************** Methods to manipulate commands for a cluster *********************/
/**
* Method to get commmands for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@GET(CLUSTER_URL_SUFFIX + "/{id}/commands")
Call<List<Command>> getCommandsForCluster(@Path("id") String clusterId);
/**
* Method to add commands to a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param commandIds The command Ids to be added.
* @return A callable object.
*/
@POST(CLUSTER_URL_SUFFIX + "/{id}/commands")
Call<Void> addCommandsToCluster(@Path("id") String clusterId, @Body List<String> commandIds);
/**
* Method to override and set commands for a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param commandIds The command Ids to be added.
* @return A callable object.
*/
@PUT(CLUSTER_URL_SUFFIX + "/{id}/commands")
Call<Void> setCommandsForCluster(@Path("id") String clusterId, @Body List<String> commandIds);
/**
* Method to delete a command for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @param commandId The command to delete.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}/commands/{commandId}")
Call<Void> removeCommandForCluster(@Path("id") String clusterId, @Path("commandId") String commandId);
/**
* Method to delete all commands for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}/commands")
Call<Void> removeAllCommandsForCluster(@Path("id") String clusterId);
/****************** Methods to manipulate dependencies for a cluster *********************/
/**
* Method to get dependency files for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@GET(CLUSTER_URL_SUFFIX + "/{id}/dependencies")
Call<Set<String>> getDependenciesForCluster(@Path("id") String clusterId);
/**
* Method to add dependencies to a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param dependencies The dependencies to be added.
* @return A callable object.
*/
@POST(CLUSTER_URL_SUFFIX + "/{id}/dependencies")
Call<Void> addDependenciesToCluster(
@Path("id") String clusterId,
@Body Set<String> dependencies
);
/**
* Method to update dependencies for a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param dependencies The dependencies to be added.
* @return A callable object.
*/
@PUT(CLUSTER_URL_SUFFIX + "/{id}/dependencies")
Call<Void> updateDependenciesForCluster(
@Path("id") String clusterId,
@Body Set<String> dependencies
);
/**
* Method to delete all dependencies for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}/dependencies")
Call<Void> removeAllDependenciesForCluster(@Path("id") String clusterId);
/****************** Methods to manipulate configs for a cluster *********************/
/**
* Method to get configs for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@GET(CLUSTER_URL_SUFFIX + "/{id}/configs")
Call<Set<String>> getConfigsForCluster(@Path("id") String clusterId);
/**
* Method to add configs to a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param configs The configs to be added.
* @return A callable object.
*/
@POST(CLUSTER_URL_SUFFIX + "/{id}/configs")
Call<Void> addConfigsToCluster(@Path("id") String clusterId, @Body Set<String> configs);
/**
* Method to update configs for a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param configs The configs to be added.
* @return A callable object.
*/
@PUT(CLUSTER_URL_SUFFIX + "/{id}/configs")
Call<Void> updateConfigsForCluster(@Path("id") String clusterId, @Body Set<String> configs);
/**
* Method to delete all configs for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}/configs")
Call<Void> removeAllConfigsForCluster(@Path("id") String clusterId);
/****************** Methods to manipulate tags for a cluster *********************/
/**
* Method to get tags for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@GET(CLUSTER_URL_SUFFIX + "/{id}/tags")
Call<Set<String>> getTagsForCluster(@Path("id") String clusterId);
/**
* Method to add tags to a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param tags The tags to be added.
* @return A callable object.
*/
@POST(CLUSTER_URL_SUFFIX + "/{id}/tags")
Call<Void> addTagsToCluster(@Path("id") String clusterId, @Body Set<String> tags);
/**
* Method to update tags for a cluster in Genie.
*
* @param clusterId The id of the cluster..
* @param tags The tags to be added.
* @return A callable object.
*/
@PUT(CLUSTER_URL_SUFFIX + "/{id}/tags")
Call<Void> updateTagsForCluster(@Path("id") String clusterId, @Body Set<String> tags);
/**
* Method to delete a tag for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @param tag The tag to delete.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}/tags/{tag}")
Call<Void> removeTagForCluster(@Path("id") String clusterId, @Path("tag") String tag);
/**
* Method to delete all tags for a cluster in Genie.
*
* @param clusterId The id of the cluster.
* @return A callable object.
*/
@DELETE(CLUSTER_URL_SUFFIX + "/{id}/tags")
Call<Void> removeAllTagsForCluster(@Path("id") String clusterId);
}
| 2,335 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/apis/package-info.java | /*
*
* Copyright 2016 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 containing all the interfaces encapsulating request calls to Genie.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.apis;
| 2,336 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/package-info.java | /*
*
* Copyright 2016 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 containing classes providing security details for the Genie clients.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.security;
| 2,337 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2/TokenFetcher.java | /*
*
* Copyright 2016 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.genie.client.security.oauth2;
import com.netflix.genie.client.apis.TokenService;
import com.netflix.genie.client.exceptions.GenieClientException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.net.URL;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
/**
* Class that contains the logic to get OAuth credentials from IDP.
*
* @author amsharma
* @since 3.0.0
*/
@Slf4j
public class TokenFetcher {
private static final String CLIENT_ID = "client_id";
private static final String CLIENT_SECRET = "client_secret";
private static final String GRANT_TYPE = "grant_type";
private static final String SCOPE = "scope";
// A map of all the fields needed to get the credentials
private final HashMap<String, String> credentialParams = new HashMap<>();
// An instance of the TokenService
private final TokenService tokenService;
// The url of the IDP server to get OAuth credentials
private final String oauthUrl;
private Instant expirationTime = Instant.now();
private AccessToken accessToken;
/**
* Constructor.
*
* @param oauthUrl The url of the IDP from where to get the credentials.
* @param clientId The clientId to use to get the credentials.
* @param clientSecret The clientSecret to use to get the credentials.
* @param grantType The type of the grant.
* @param scope The scope of the credentials returned.
* @throws GenieClientException If there is any problem.
*/
public TokenFetcher(
final String oauthUrl,
final String clientId,
final String clientSecret,
final String grantType,
final String scope
) throws GenieClientException {
log.debug("Constructor called.");
if (StringUtils.isBlank(oauthUrl)) {
throw new IllegalArgumentException("URL cannot be null or empty");
}
if (StringUtils.isBlank(clientId)) {
throw new IllegalArgumentException("Client Id cannot be null or empty");
}
if (StringUtils.isBlank(clientSecret)) {
throw new IllegalArgumentException("Client Secret cannot be null or empty");
}
if (StringUtils.isBlank(grantType)) {
throw new IllegalArgumentException("Grant Type cannot be null or empty");
}
if (StringUtils.isBlank(scope)) {
throw new IllegalArgumentException("Scope cannot be null or empty");
}
try {
final URL url = new URL(oauthUrl);
// Construct the Base path of the type http[s]://serverhost/ for retrofit to work.
final String oAuthServerUrl = url.getProtocol() + "://" + url.getHost() + "/";
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(oAuthServerUrl)
.addConverterFactory(JacksonConverterFactory.create())
.build();
this.oauthUrl = oauthUrl;
// Instantiate the token service
this.tokenService = retrofit.create(TokenService.class);
// Construct the fields map to send to the IDP url.
this.credentialParams.put(CLIENT_ID, clientId);
this.credentialParams.put(CLIENT_SECRET, clientSecret);
this.credentialParams.put(GRANT_TYPE, grantType);
this.credentialParams.put(SCOPE, scope);
} catch (final Exception e) {
throw new GenieClientException("Could not instantiate Token Service due to exception " + e);
}
}
/**
* Method that returns the OAuth credentials.
*
* @return An access token object.
* @throws GenieClientException If there is any problem.
*/
public AccessToken getToken() throws GenieClientException {
try {
if (Instant.now().isAfter(this.expirationTime)) {
final Response<AccessToken> response = tokenService.getToken(oauthUrl, credentialParams).execute();
if (response.isSuccessful()) {
// Get current date, add expiresIn for the access token with a buffer of 5 minutes
this.accessToken = response.body();
this.expirationTime = Instant
.now()
.plus(this.accessToken.getExpiresIn() - 300, ChronoUnit.SECONDS);
return this.accessToken;
} else {
throw new GenieClientException(response.code(), "Could not fetch Token");
}
} else {
return this.accessToken;
}
} catch (final Exception e) {
throw new GenieClientException("Could not get access tokens" + e);
}
}
}
| 2,338 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2/AccessToken.java | /*
*
* Copyright 2016 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.genie.client.security.oauth2;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* Class that encapsulates the OAuth credentials.
*
* @author amsharma
* @since 3.0.0
*/
@Getter
@Setter
public class AccessToken {
// The type of the token
@JsonProperty("token_type")
private String tokenType;
// The accessToken
@JsonProperty("access_token")
private String accessToken;
// Time to expire from creation
@JsonProperty("expires_in")
private int expiresIn;
}
| 2,339 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2/package-info.java | /*
*
* Copyright 2016 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 containing Oauth security related classes.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.security.oauth2;
| 2,340 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2/impl/OAuth2SecurityInterceptor.java | /*
*
* Copyright 2016 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.genie.client.security.oauth2.impl;
import com.google.common.net.HttpHeaders;
import com.netflix.genie.client.exceptions.GenieClientException;
import com.netflix.genie.client.interceptors.SecurityInterceptor;
import com.netflix.genie.client.security.oauth2.AccessToken;
import com.netflix.genie.client.security.oauth2.TokenFetcher;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
/**
* An interceptor that adds security headers to all outgoing requests.
*
* @author amsharma
*/
@Slf4j
public class OAuth2SecurityInterceptor implements SecurityInterceptor {
private final TokenFetcher tokenFetcher;
/**
* Constructor.
*
* @param url The URL of the IDP server for getting oauth token.
* @param clientId The client id to use to fetch credentials.
* @param clientSecret The client secret to use to fetch credentials.
* @param grantType The grant type for the user.
* @param scope The scope of the user permissions.
* @throws GenieClientException If there is a problem initializing the object.
*/
public OAuth2SecurityInterceptor(
final String url,
final String clientId,
final String clientSecret,
final String grantType,
final String scope
) throws GenieClientException {
log.debug("Constructor called.");
tokenFetcher = new TokenFetcher(url, clientId, clientSecret, grantType, scope);
}
@Override
public Response intercept(
final Chain chain
) throws IOException {
final AccessToken accessToken = this.tokenFetcher.getToken();
final Request newRequest = chain
.request()
.newBuilder()
.addHeader(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getAccessToken())
.build();
log.debug("Sending request {} on {} {}", newRequest.url(), chain.connection(), newRequest.headers());
return chain.proceed(newRequest);
}
}
| 2,341 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/security/oauth2/impl/package-info.java | /*
*
* Copyright 2016 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 containing implementations of interfaces defined in the oauth package.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.security.oauth2.impl;
| 2,342 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/exceptions/GenieClientTooManyRequestsException.java | /*
*
* Copyright 2022 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.genie.client.exceptions;
/**
* An exception class that represents 429 - Too Many Requests received from the server.
*
* @author andrew
* @since 4.0.0
*/
public class GenieClientTooManyRequestsException extends GenieClientException {
/**
* Constructor.
*/
public GenieClientTooManyRequestsException() {
super(429, "");
}
/**
* Constructor.
*
* @param msg human readable message
*/
public GenieClientTooManyRequestsException(final String msg) {
super(429, msg);
}
}
| 2,343 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/exceptions/GenieClientException.java | /*
*
* Copyright 2015 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.genie.client.exceptions;
import java.io.IOException;
/**
* An exception class that represents all failures received by the client. It includes an
* HTTP error code and a human-readable error message. The HTTP Error code is -1 in case the error is not
* from the server.
*
* @author amsharma
* @since 3.0.0
*/
public class GenieClientException extends IOException {
/* the HTTP error code received from the server. -1 if the error is on the client side only.*/
private final int errorCode;
/**
* Constructor.
*
* @param errorCode the HTTP status code for this exception
* @param msg human readable message
*/
public GenieClientException(final int errorCode, final String msg) {
super(errorCode + ": " + msg);
this.errorCode = errorCode;
}
/**
* Constructor.
*
* @param msg human readable message
*/
public GenieClientException(final String msg) {
super(msg);
this.errorCode = -1;
}
/**
* Constructor.
*
* @param messasge human readable message
* @param cause cause
*/
public GenieClientException(final String messasge, final Throwable cause) {
super(messasge, cause);
this.errorCode = -1;
}
/**
* Return the HTTP status code for this exception.
*
* @return the HTTP status code
*/
public int getErrorCode() {
return errorCode;
}
}
| 2,344 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/exceptions/package-info.java | /*
*
* Copyright 2015 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.
*
*/
/**
* A package containing all exceptions in the Genie client.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.exceptions;
| 2,345 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/configs/GenieNetworkConfiguration.java | /*
*
* Copyright 2016 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.genie.client.configs;
import lombok.Getter;
import lombok.Setter;
/**
* An object that encapsulates network configurations for Genie client HTTP requests.
*
* @author amsharma
* @since 3.0.0
*/
@Getter
@Setter
public class GenieNetworkConfiguration {
/**
* Default network timeout value if not specified.
*/
public static final long DEFAULT_TIMEOUT = -1;
/**
* The default number of times to retry connections if desired.
*/
public static final int DEFAULT_NUM_RETRIES = 5;
// The default read timeout for new connections.
private long readTimeout = DEFAULT_TIMEOUT;
// The default write timeout for new connections.
private long writeTimeout = DEFAULT_TIMEOUT;
// Default connection timeout in milliseconds for new connections.
private long connectTimeout = DEFAULT_TIMEOUT;
// Whether to retry on connection failures: https://goo.gl/2A8EoO
private boolean retryOnConnectionFailure = true;
// The number of times to retry checks for job status within wait for completion
private int maxStatusRetries = DEFAULT_NUM_RETRIES;
}
| 2,346 |
0 | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client | Create_ds/genie/genie-client/src/main/java/com/netflix/genie/client/configs/package-info.java | /*
*
* Copyright 2016 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 containing configuration classes for Genie client.
*
* @author amsharma
* @since 3.0.0
*/
package com.netflix.genie.client.configs;
| 2,347 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/ClusterRestControllerIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.apis.rest.v3.controllers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonpatch.JsonPatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import io.restassured.RestAssured;
import org.apache.catalina.util.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.restdocs.payload.PayloadDocumentation;
import org.springframework.restdocs.request.RequestDocumentation;
import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation;
import org.springframework.restdocs.restassured3.RestDocumentationFilter;
import org.springframework.restdocs.snippet.Attributes;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Integration tests for the Clusters REST API.
*
* @author tgianos
* @since 3.0.0
*/
class ClusterRestControllerIntegrationTest extends RestControllerIntegrationTestBase {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = "h2prod";
private static final String USER = "genie";
private static final String VERSION = "2.7.1";
private static final String CLUSTERS_LIST_PATH = EMBEDDED_PATH + ".clusterList";
private static final String CLUSTERS_ID_LIST_PATH = CLUSTERS_LIST_PATH + ".id";
private static final String CLUSTER_COMMANDS_LINK_PATH = "_links.commands.href";
private static final String CLUSTERS_COMMANDS_LINK_PATH = CLUSTERS_LIST_PATH + "._links.commands.href";
private static final List<String> EXECUTABLE_AND_ARGS = Lists.newArrayList("bash");
@BeforeEach
void beforeClusters() {
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(0L);
}
@Test
void canCreateClusterWithoutId() throws Exception {
final RestDocumentationFilter createFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request headers
Snippets.getClusterRequestPayload(), // Request fields
Snippets.LOCATION_HEADER // Response headers
);
final String id = this.createConfigResource(
new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).build(),
createFilter
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // response headers
Snippets.getClusterResponsePayload(), // response payload
Snippets.CLUSTER_LINKS // response links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getFilter)
.when()
.port(this.port)
.get(CLUSTERS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(NAME))
.body(USER_PATH, Matchers.is(USER))
.body(VERSION_PATH, Matchers.is(VERSION))
.body(TAGS_PATH, Matchers.hasItem("genie.id:" + id))
.body(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME))
.body(SETUP_FILE_PATH, Matchers.nullValue())
.body(STATUS_PATH, Matchers.is(ClusterStatus.UP.toString()))
.body(CONFIGS_PATH, Matchers.hasSize(0))
.body(DEPENDENCIES_PATH, Matchers.hasSize(0))
.body(LINKS_PATH + ".keySet().size()", Matchers.is(2))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY))
.body(
CLUSTER_COMMANDS_LINK_PATH,
EntityLinkMatcher.matchUri(
CLUSTERS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS,
id
)
);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(1L);
}
@Test
void canCreateClusterWithId() throws Exception {
this.createConfigResource(
new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(CLUSTERS_API + "/{id}", ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(ID))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(NAME))
.body(USER_PATH, Matchers.is(USER))
.body(VERSION_PATH, Matchers.is(VERSION))
.body(TAGS_PATH, Matchers.hasItem("genie.id:" + ID))
.body(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME))
.body(SETUP_FILE_PATH, Matchers.nullValue())
.body(STATUS_PATH, Matchers.is(ClusterStatus.UP.toString()))
.body(CONFIGS_PATH, Matchers.hasSize(0))
.body(DEPENDENCIES_PATH, Matchers.hasSize(0))
.body(LINKS_PATH + ".keySet().size()", Matchers.is(2))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY))
.body(
CLUSTER_COMMANDS_LINK_PATH,
EntityLinkMatcher.matchUri(
CLUSTERS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS,
ID
)
);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(1L);
}
@Test
void canHandleBadInputToCreateCluster() throws Exception {
final Cluster cluster = new Cluster.Builder(" ", " ", " ", ClusterStatus.UP).build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(cluster))
.when()
.port(this.port)
.post(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("A version is required and must be at most 255 characters")
);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(0L);
}
@Test
void canFindClusters() throws Exception {
final String id1 = UUID.randomUUID().toString();
final String id2 = UUID.randomUUID().toString();
final String id3 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString();
final String name3 = UUID.randomUUID().toString();
final String user1 = UUID.randomUUID().toString();
final String user2 = UUID.randomUUID().toString();
final String user3 = UUID.randomUUID().toString();
final String version1 = UUID.randomUUID().toString();
final String version2 = UUID.randomUUID().toString();
final String version3 = UUID.randomUUID().toString();
this.createConfigResource(
new Cluster.Builder(name1, user1, version1, ClusterStatus.UP).withId(id1).build(),
null
);
Thread.sleep(1000);
this.createConfigResource(
new Cluster.Builder(name2, user2, version2, ClusterStatus.OUT_OF_SERVICE).withId(id2).build(),
null
);
Thread.sleep(1000);
this.createConfigResource(
new Cluster.Builder(name3, user3, version3, ClusterStatus.TERMINATED).withId(id3).build(),
null
);
final RestDocumentationFilter findFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CLUSTER_SEARCH_QUERY_PARAMETERS, // Request query parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response headers
Snippets.CLUSTER_SEARCH_RESULT_FIELDS, // Result fields
Snippets.SEARCH_LINKS // HAL Links
);
// Test finding all clusters
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.when()
.port(this.port)
.get(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(CLUSTERS_LIST_PATH, Matchers.hasSize(3))
.body(CLUSTERS_ID_LIST_PATH, Matchers.containsInAnyOrder(id1, id2, id3))
.body(
CLUSTERS_COMMANDS_LINK_PATH,
EntitiesLinksMatcher.matchUrisAnyOrder(
CLUSTERS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS,
Lists.newArrayList(id1, id2, id3)
)
);
// Try to limit the number of results
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("size", 2)
.when()
.port(this.port)
.get(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(CLUSTERS_LIST_PATH, Matchers.hasSize(2));
// Query by name
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("name", name2)
.when()
.port(this.port)
.get(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(CLUSTERS_LIST_PATH, Matchers.hasSize(1))
.body(CLUSTERS_LIST_PATH + "[0].id", Matchers.is(id2));
// Query by statuses
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("status", ClusterStatus.UP.toString(), ClusterStatus.TERMINATED.toString())
.when()
.port(this.port)
.get(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(CLUSTERS_LIST_PATH, Matchers.hasSize(2))
.body(CLUSTERS_LIST_PATH + "[0].id", Matchers.is(id3))
.body(CLUSTERS_LIST_PATH + "[1].id", Matchers.is(id1));
// Query by tags
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("tag", "genie.id:" + id1)
.when()
.port(this.port)
.get(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(CLUSTERS_LIST_PATH, Matchers.hasSize(1))
.body(CLUSTERS_LIST_PATH + "[0].id", Matchers.is(id1));
//TODO: Add tests for searching by min and max update time as those are available parameters
//TODO: Add tests for sort, orderBy etc
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(3L);
}
@Test
void canUpdateCluster() throws Exception {
this.createConfigResource(
new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(),
null
);
final String clusterResource = CLUSTERS_API + "/{id}";
final Cluster createdCluster = GenieObjectMapper.getMapper()
.readValue(
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.extract()
.asByteArray(),
new TypeReference<EntityModel<Cluster>>() {
}
).getContent();
Assertions.assertThat(createdCluster).isNotNull();
Assertions.assertThat(createdCluster.getStatus()).isEqualByComparingTo(ClusterStatus.UP);
final Cluster.Builder updateCluster = new Cluster.Builder(
createdCluster.getName(),
createdCluster.getUser(),
createdCluster.getVersion(),
ClusterStatus.OUT_OF_SERVICE
)
.withId(createdCluster.getId().orElseThrow(IllegalArgumentException::new))
.withCreated(createdCluster.getCreated().orElseThrow(IllegalArgumentException::new))
.withUpdated(createdCluster.getUpdated().orElseThrow(IllegalArgumentException::new))
.withTags(createdCluster.getTags())
.withConfigs(createdCluster.getConfigs())
.withDependencies(createdCluster.getDependencies());
createdCluster.getDescription().ifPresent(updateCluster::withDescription);
createdCluster.getSetupFile().ifPresent(updateCluster::withSetupFile);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request header
Snippets.ID_PATH_PARAM, // path parameters
Snippets.getClusterRequestPayload() // payload fields
);
RestAssured
.given(this.getRequestSpecification())
.filter(updateFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(updateCluster.build()))
.when()
.port(this.port)
.put(clusterResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(STATUS_PATH, Matchers.is(ClusterStatus.OUT_OF_SERVICE.toString()));
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(1L);
}
@Test
void canPatchCluster() throws Exception {
final String id = this.createConfigResource(
new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(),
null
);
final String clusterResource = CLUSTERS_API + "/{id}";
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(NAME_PATH, Matchers.is(NAME));
final String newName = UUID.randomUUID().toString();
final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
final JsonPatch patch = JsonPatch.fromJson(GenieObjectMapper.getMapper().readTree(patchString));
final RestDocumentationFilter patchFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request headers
Snippets.ID_PATH_PARAM, // path params
Snippets.PATCH_FIELDS // request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(patchFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(patch))
.when()
.port(this.port)
.patch(clusterResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(NAME_PATH, Matchers.is(newName));
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(1L);
}
@Test
void canDeleteAllClusters() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).build(), null);
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.OUT_OF_SERVICE).build(), null);
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.TERMINATED).build(), null);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(3L);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/"
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(0L);
}
@Test
void canDeleteACluster() throws Exception {
final String id1 = UUID.randomUUID().toString();
final String id2 = UUID.randomUUID().toString();
final String id3 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString();
final String name3 = UUID.randomUUID().toString();
final String user1 = UUID.randomUUID().toString();
final String user2 = UUID.randomUUID().toString();
final String user3 = UUID.randomUUID().toString();
final String version1 = UUID.randomUUID().toString();
final String version2 = UUID.randomUUID().toString();
final String version3 = UUID.randomUUID().toString();
this.createConfigResource(
new Cluster.Builder(name1, user1, version1, ClusterStatus.UP).withId(id1).build(),
null
);
this.createConfigResource(
new Cluster.Builder(name2, user2, version2, ClusterStatus.OUT_OF_SERVICE).withId(id2).build(),
null
);
this.createConfigResource(
new Cluster.Builder(name3, user3, version3, ClusterStatus.TERMINATED).withId(id3).build(),
null
);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(3L);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(CLUSTERS_API + "/{id}", id2)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(CLUSTERS_API + "/{id}", id2)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("No cluster with id")
);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(2L);
}
@Test
void canAddConfigsToCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.CONTENT_TYPE_HEADER, // request header
PayloadDocumentation.requestFields(Snippets.CONFIG_FIELDS) // response fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.CONFIG_FIELDS) // response fields
);
this.canAddElementsToResource(CLUSTERS_API + "/{id}/configs", ID, addFilter, getFilter);
}
@Test
void canUpdateConfigsForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.CONFIG_FIELDS) // Request fields
);
this.canUpdateElementsForResource(CLUSTERS_API + "/{id}/configs", ID, updateFilter);
}
@Test
void canDeleteConfigsForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM
);
this.canDeleteElementsFromResource(CLUSTERS_API + "/{id}/configs", ID, deleteFilter);
}
@Test
void canAddDependenciesToCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.CONTENT_TYPE_HEADER, // request header
PayloadDocumentation.requestFields(Snippets.DEPENDENCIES_FIELDS) // response fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.DEPENDENCIES_FIELDS) // response fields
);
this.canAddElementsToResource(CLUSTERS_API + "/{id}/dependencies", ID, addFilter, getFilter);
}
@Test
void canUpdateDependenciesForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.DEPENDENCIES_FIELDS) // Request fields
);
this.canUpdateElementsForResource(CLUSTERS_API + "/{id}/configs", ID, updateFilter);
}
@Test
void canDeleteDependenciesForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM
);
this.canDeleteElementsFromResource(CLUSTERS_API + "/{id}/dependencies", ID, deleteFilter);
}
@Test
void canAddTagsToCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String api = CLUSTERS_API + "/{id}/tags";
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.TAGS_FIELDS) // Request fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.JSON_CONTENT_TYPE_HEADER, // Response header
PayloadDocumentation.responseFields(Snippets.TAGS_FIELDS)
);
this.canAddTagsToResource(api, ID, NAME, addFilter, getFilter);
}
@Test
void canUpdateTagsForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String api = CLUSTERS_API + "/{id}/tags";
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.TAGS_FIELDS) // Request fields
);
this.canUpdateTagsForResource(api, ID, NAME, updateFilter);
}
@Test
void canDeleteTagsForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM
);
final String api = CLUSTERS_API + "/{id}/tags";
this.canDeleteTagsForResource(api, ID, NAME, deleteFilter);
}
@Test
void canDeleteTagForCluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String api = CLUSTERS_API + "/{id}/tags";
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("tag").description("The tag to remove"))
);
this.canDeleteTagForResource(api, ID, NAME, deleteFilter);
}
@Test
void canAddCommandsForACluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String clusterCommandsAPI = CLUSTERS_API + "/{id}/commands";
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request Headers
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of command ids (in preferred order) to append to the existing list of commands")
.attributes(Snippets.EMPTY_CONSTRAINTS)
) // Request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(addFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(
GenieObjectMapper
.getMapper()
.writeValueAsBytes(Lists.newArrayList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
)
.when()
.port(this.port)
.post(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
// Test the filtering
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
RequestDocumentation.requestParameters(
RequestDocumentation
.parameterWithName("status")
.description("The status of commands to search for")
.attributes(Attributes.key(Snippets.CONSTRAINTS).value(CommandStatus.values()))
.optional()
), // Query Parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
PayloadDocumentation.responseFields(
PayloadDocumentation
.subsectionWithPath("[]")
.description("The list of commands found")
.attributes(Snippets.EMPTY_CONSTRAINTS)
)
);
RestAssured
.given(this.getRequestSpecification())
.filter(getFilter)
.param("status", CommandStatus.ACTIVE.toString())
.when()
.port(this.port)
.get(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
}
@Test
void canSetCommandsForACluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String clusterCommandsAPI = CLUSTERS_API + "/{id}/commands";
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
final RestDocumentationFilter setFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request Headers
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of command ids (in preferred order) to replace the existing list of commands")
.attributes(Snippets.EMPTY_CONSTRAINTS)
) // Request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(setFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(
GenieObjectMapper
.getMapper()
.writeValueAsBytes(Lists.newArrayList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
)
.when()
.port(this.port)
.put(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
}
@Test
void canRemoveCommandsFromACluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String clusterCommandsAPI = CLUSTERS_API + "/{id}/commands";
final String placeholder = UUID.randomUUID().toString();
final String commandId1 = UUID.randomUUID().toString();
final String commandId2 = UUID.randomUUID().toString();
this.createConfigResource(
new Command
.Builder(placeholder, placeholder, placeholder, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, 7000L)
.withId(commandId1)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(placeholder, placeholder, placeholder, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, 8000L)
.withId(commandId2)
.build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList(commandId1, commandId2)))
.when()
.port(this.port)
.post(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // Path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
}
@Test
void canRemoveCommandFromACluster() throws Exception {
this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
final String clusterCommandsAPI = CLUSTERS_API + "/{id}/commands";
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation.parameterWithName("commandId").description("The id of the command to remove")
) // Path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(clusterCommandsAPI + "/{commandId}", ID, UUID.randomUUID().toString())
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(clusterCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
}
/**
* This test "documents" a known bug in Spring HATEOAS links that resulted in doubly-encoded pagination links.
* https://github.com/spring-projects/spring-hateoas/issues/559
* We worked around this bug in the UI by decoding these elements (see Pagination.js).
* This test now documents the contract that this bug should be fixed.
*
* @throws Exception on error
*/
@Test
void testPagingDoubleEncoding() throws Exception {
final String id1 = UUID.randomUUID().toString();
final String id2 = UUID.randomUUID().toString();
final String id3 = UUID.randomUUID().toString();
final String name1 = "Test " + UUID.randomUUID().toString();
final String name2 = "Test " + UUID.randomUUID().toString();
final String name3 = "Test " + UUID.randomUUID().toString();
final String user1 = UUID.randomUUID().toString();
final String user2 = UUID.randomUUID().toString();
final String user3 = UUID.randomUUID().toString();
final String version1 = UUID.randomUUID().toString();
final String version2 = UUID.randomUUID().toString();
final String version3 = UUID.randomUUID().toString();
this.createConfigResource(
new Cluster.Builder(name1, user1, version1, ClusterStatus.UP).withId(id1).build(),
null
);
Thread.sleep(1000);
this.createConfigResource(
new Cluster.Builder(name2, user2, version2, ClusterStatus.OUT_OF_SERVICE).withId(id2).build(),
null
);
Thread.sleep(1000);
this.createConfigResource(
new Cluster.Builder(name3, user3, version3, ClusterStatus.TERMINATED).withId(id3).build(),
null
);
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(3L);
final URLEncoder urlEncoder = new URLEncoder();
final String unencodedNameQuery = "Test %";
final String singleEncodedNameQuery = urlEncoder.encode(unencodedNameQuery, StandardCharsets.UTF_8);
// Query by name with wildcard and get the second page containing a single result (out of 3)
final JsonNode responseJsonNode = GenieObjectMapper
.getMapper()
.readTree(
RestAssured
.given(this.getRequestSpecification())
.param("name", unencodedNameQuery)
.param("size", 1)
.param("page", 1)
.when()
.port(this.port)
.get(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(CLUSTERS_LIST_PATH, Matchers.hasSize(1))
.extract()
.asByteArray()
);
// Self link is not double-encoded
Assertions
.assertThat(
responseJsonNode
.get("_links")
.get("self")
.get("href")
.asText()
)
.contains(singleEncodedNameQuery);
// Pagination links that were double-encoded
final String[] doubleEncodedHREFS = new String[]{
"first", "next", "prev", "last",
};
for (String doubleEncodedHref : doubleEncodedHREFS) {
final String linkString = responseJsonNode
.get("_links")
.get(doubleEncodedHref)
.get("href")
.asText();
Assertions.assertThat(linkString).isNotBlank();
final Map<String, String> params = Maps.newHashMap();
URLEncodedUtils
.parse(new URI(linkString), StandardCharsets.UTF_8)
.forEach(nameValuePair -> params.put(nameValuePair.getName(), nameValuePair.getValue()));
Assertions.assertThat(params).containsKey("name");
Assertions.assertThat(params.get("name")).isEqualTo(unencodedNameQuery);
}
}
@Test
void canCreateClusterWithBlankFields() throws Exception {
final List<Cluster> invalidClusterResources = Lists.newArrayList(
new Cluster
.Builder(NAME, USER, VERSION, ClusterStatus.UP)
.withId(UUID.randomUUID().toString())
.withDependencies(Sets.newHashSet("foo", " "))
.build(),
new Cluster
.Builder(NAME, USER, VERSION, ClusterStatus.UP)
.withId(UUID.randomUUID().toString())
.withConfigs(Sets.newHashSet("foo", " "))
.build(),
new Cluster
.Builder(NAME, USER, VERSION, ClusterStatus.UP)
.withId(UUID.randomUUID().toString())
.withTags(Sets.newHashSet("foo", " "))
.build()
);
long i = 0L;
for (final Cluster invalidClusterResource : invalidClusterResources) {
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(i);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(invalidClusterResource))
.when()
.port(this.port)
.post(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()));
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(++i);
}
}
@Test
void testClusterNotFound() {
final List<String> paths = Lists.newArrayList("", "/commands");
for (final String path : paths) {
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(CLUSTERS_API + "/{id}" + path, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(EXCEPTION_MESSAGE_PATH, Matchers.startsWith("No cluster with id " + ID));
}
}
}
| 2,348 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/RestControllerIntegrationTestBase.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.controllers;
import com.google.common.collect.Sets;
import com.netflix.genie.GenieTestApp;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.ExecutionEnvironmentDTO;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCriterionRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaJobRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaTagRepository;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Description;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.wiremock.restdocs.WireMockSnippet;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.restdocs.operation.preprocess.Preprocessors;
import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation;
import org.springframework.restdocs.restassured3.RestDocumentationFilter;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Base class for all integration tests for the controllers.
*
* @author tgianos
* @since 3.0.0
*/
@ExtendWith(
{
RestDocumentationExtension.class,
SpringExtension.class
}
)
@SpringBootTest(classes = GenieTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(resolver = IntegrationTestActiveProfilesResolver.class)
abstract class RestControllerIntegrationTestBase {
static final String APPLICATIONS_API = "/api/v3/applications";
static final String CLUSTERS_API = "/api/v3/clusters";
static final String COMMANDS_API = "/api/v3/commands";
static final String JOBS_API = "/api/v3/jobs";
static final String ID_PATH = "id";
static final String CREATED_PATH = "created";
static final String UPDATED_PATH = "updated";
static final String NAME_PATH = "name";
static final String VERSION_PATH = "version";
static final String USER_PATH = "user";
static final String DESCRIPTION_PATH = "description";
static final String METADATA_PATH = "metadata";
static final String TAGS_PATH = "tags";
static final String SETUP_FILE_PATH = "setupFile";
static final String STATUS_PATH = "status";
static final String CONFIGS_PATH = "configs";
static final String DEPENDENCIES_PATH = "dependencies";
static final String LINKS_PATH = "_links";
static final String EMBEDDED_PATH = "_embedded";
static final String EXCEPTION_MESSAGE_PATH = "message";
// Link Keys
static final String SELF_LINK_KEY = "self";
static final String COMMANDS_LINK_KEY = "commands";
static final String CLUSTERS_LINK_KEY = "clusters";
static final String APPLICATIONS_LINK_KEY = "applications";
static final String JOBS_LINK_KEY = "jobs";
static final Set<String> CLUSTERS_OPTIONAL_HAL_LINK_PARAMETERS = Sets.newHashSet("status");
static final Set<String> COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS = Sets.newHashSet("status");
private static final Logger LOG = LoggerFactory.getLogger(RestControllerIntegrationTestBase.class);
private static final String URI_HOST = "genie.example.com";
private static final String URI_SCHEME = "https";
private static final String LOCAL_TEST_SERVER_PORT_PROPERTY_NAME = "local.server.port";
@Autowired
protected JpaApplicationRepository applicationRepository;
@Autowired
protected JpaClusterRepository clusterRepository;
@Autowired
protected JpaCommandRepository commandRepository;
@Autowired
protected JpaJobRepository jobRepository;
@Autowired
protected JpaFileRepository fileRepository;
@Autowired
protected JpaTagRepository tagRepository;
@Autowired
protected JpaCriterionRepository criterionRepository;
@Autowired
protected Environment environment;
protected int port;
@Autowired
private PlatformTransactionManager transactionManager;
private TransactionTemplate transactionTemplate;
private RequestSpecification requestSpecification;
private static String getLinkedResourceExpectedUri(
final String entityApi,
final String entityId,
@Nullable final Set<String> optionalHalParams,
final String linkedEntityType
) {
final String uriPath = entityApi + "/" + entityId + "/" + linkedEntityType;
// Append HAL parameters separately to avoid URI encoding
final StringBuilder halParamsStringBuilder = new StringBuilder();
if (optionalHalParams != null && !optionalHalParams.isEmpty()) {
halParamsStringBuilder
.append("{?")
.append(StringUtils.join(optionalHalParams, ","))
.append("}");
}
return uriPath + halParamsStringBuilder.toString();
}
RequestSpecification getRequestSpecification() {
return this.requestSpecification;
}
private void doInTransactionWithoutResult(final Supplier<Void> supplier) {
int retriesLeft = 3;
while (retriesLeft > 0) {
try {
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(final TransactionStatus status) {
supplier.get();
}
});
return;
} catch (DataAccessException e) {
LOG.warn("Exception caught when running transactions.", e);
retriesLeft--;
if (retriesLeft <= 0) {
throw e;
}
}
}
}
@BeforeEach
void beforeBase(final RestDocumentationContextProvider documentationContextProvider) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
doInTransactionWithoutResult(() -> {
this.jobRepository.deleteAll();
return null;
});
doInTransactionWithoutResult(() -> {
this.clusterRepository.deleteAll();
return null;
});
doInTransactionWithoutResult(() -> {
this.commandRepository.deleteAll();
return null;
});
doInTransactionWithoutResult(() -> {
this.applicationRepository.deleteAll();
return null;
});
doInTransactionWithoutResult(() -> {
this.criterionRepository.deleteAll();
return null;
});
doInTransactionWithoutResult(() -> {
this.fileRepository.deleteAll();
return null;
});
doInTransactionWithoutResult(() -> {
this.tagRepository.deleteAll();
return null;
});
this.requestSpecification = new RequestSpecBuilder()
.addFilter(
RestAssuredRestDocumentation
.documentationConfiguration(documentationContextProvider)
.snippets()
.withAdditionalDefaults(new WireMockSnippet())
.and()
.operationPreprocessors()
.withRequestDefaults(
Preprocessors.prettyPrint(),
Preprocessors.modifyUris().scheme(URI_SCHEME).host(URI_HOST).removePort()
)
.withResponseDefaults(
Preprocessors.prettyPrint(),
Preprocessors.modifyUris().host(URI_HOST).scheme(URI_SCHEME).removePort()
)
)
// .addFilter(new RequestLoggingFilter())
// .addFilter(new ResponseLoggingFilter())
.build();
// The proper way to do this is annotate `port` with @LocalServerPort.
// However what looks like a race condition during context initialization makes the test sporadically fail.
// This should work more reliably since it happens after context is initialized
this.port = this.environment.getRequiredProperty(LOCAL_TEST_SERVER_PORT_PROPERTY_NAME, Integer.class);
}
void canAddElementsToResource(
final String api,
final String id,
final RestDocumentationFilter addFilter,
final RestDocumentationFilter getFilter
) throws Exception {
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.empty());
final String element1 = UUID.randomUUID().toString();
final String element2 = UUID.randomUUID().toString();
final Set<String> elements = Sets.newHashSet(element1, element2);
RestAssured
.given(this.requestSpecification)
.filter(addFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(elements))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.filter(getFilter)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("$", Matchers.hasItem(element1))
.body("$", Matchers.hasItem(element2));
}
void canUpdateElementsForResource(
final String api,
final String id,
final RestDocumentationFilter updateFilter
) throws Exception {
final String element1 = UUID.randomUUID().toString();
final String element2 = UUID.randomUUID().toString();
final Set<String> elements = Sets.newHashSet(element1, element2);
RestAssured
.given(this.requestSpecification)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(elements))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final String element3 = UUID.randomUUID().toString();
RestAssured
.given(this.requestSpecification)
.filter(updateFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Sets.newHashSet(element3)))
.when()
.port(this.port)
.put(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(1))
.body("$", Matchers.hasItem(element3));
}
void canDeleteElementsFromResource(
final String api,
final String id,
final RestDocumentationFilter deleteFilter
) throws Exception {
final String element1 = UUID.randomUUID().toString();
final String element2 = UUID.randomUUID().toString();
RestAssured
.given(this.requestSpecification)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Sets.newHashSet(element1, element2)))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.filter(deleteFilter)
.when()
.port(this.port)
.delete(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.empty());
}
void canAddTagsToResource(
final String api,
final String id,
final String name,
final RestDocumentationFilter addFilter,
final RestDocumentationFilter getFilter
) throws Exception {
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("$", Matchers.hasItem("genie.id:" + id))
.body("$", Matchers.hasItem("genie.name:" + name));
final String tag1 = UUID.randomUUID().toString();
final String tag2 = UUID.randomUUID().toString();
final Set<String> tags = Sets.newHashSet(tag1, tag2);
RestAssured
.given(this.requestSpecification)
.filter(addFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(tags))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.filter(getFilter)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(4))
.body("$", Matchers.hasItem("genie.id:" + id))
.body("$", Matchers.hasItem("genie.name:" + name))
.body("$", Matchers.hasItem(tag1))
.body("$", Matchers.hasItem(tag2));
}
void canUpdateTagsForResource(
final String api,
final String id,
final String name,
final RestDocumentationFilter updateFilter
) throws Exception {
final String tag1 = UUID.randomUUID().toString();
final String tag2 = UUID.randomUUID().toString();
final Set<String> tags = Sets.newHashSet(tag1, tag2);
RestAssured
.given(this.requestSpecification)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(tags))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final String tag3 = UUID.randomUUID().toString();
RestAssured
.given(this.requestSpecification)
.filter(updateFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Sets.newHashSet(tag3)))
.when()
.port(this.port)
.put(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(3))
.body("$", Matchers.hasItem("genie.id:" + id))
.body("$", Matchers.hasItem("genie.name:" + name))
.body("$", Matchers.hasItem(tag3));
}
void canDeleteTagsForResource(
final String api,
final String id,
final String name,
final RestDocumentationFilter deleteFilter
) throws Exception {
final String tag1 = UUID.randomUUID().toString();
final String tag2 = UUID.randomUUID().toString();
final Set<String> tags = Sets.newHashSet(tag1, tag2);
RestAssured
.given(this.requestSpecification)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(tags))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.filter(deleteFilter)
.when()
.port(this.port)
.delete(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("$", Matchers.hasItem("genie.id:" + id))
.body("$", Matchers.hasItem("genie.name:" + name));
}
void canDeleteTagForResource(
final String api,
final String id,
final String name,
final RestDocumentationFilter deleteFilter
) throws Exception {
final String tag1 = UUID.randomUUID().toString();
final String tag2 = UUID.randomUUID().toString();
RestAssured
.given(this.requestSpecification)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Sets.newHashSet(tag1, tag2)))
.when()
.port(this.port)
.post(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.filter(deleteFilter)
.when()
.port(this.port)
.delete(api + "/{tag}", id, tag1)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.requestSpecification)
.when()
.port(this.port)
.get(api, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body("$", Matchers.hasSize(3))
.body("$", Matchers.hasItem("genie.id:" + id))
.body("$", Matchers.hasItem("genie.name:" + name))
.body("$", Matchers.hasItem(tag2));
}
<R extends ExecutionEnvironmentDTO> String createConfigResource(
@NotNull final R resource,
@Nullable final RestDocumentationFilter documentationFilter
) throws Exception {
final String endpoint;
if (resource instanceof Application) {
endpoint = APPLICATIONS_API;
} else if (resource instanceof Cluster) {
endpoint = CLUSTERS_API;
} else if (resource instanceof Command) {
endpoint = COMMANDS_API;
} else {
throw new IllegalArgumentException("Unexpected type: " + resource.getClass().getCanonicalName());
}
final RequestSpecification configRequestSpec = RestAssured
.given(this.requestSpecification)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(resource));
if (documentationFilter != null) {
configRequestSpec.filter(documentationFilter);
}
return this.getIdFromLocation(
configRequestSpec
.when()
.port(this.port)
.post(endpoint)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
}
String getIdFromLocation(@Nullable final String location) {
if (location == null) {
Assertions.fail("No location provided");
}
return location.substring(location.lastIndexOf("/") + 1);
}
static class EntityLinkMatcher extends TypeSafeMatcher<String> {
private final String expectedUri;
private String descriptionString = "Not evaluated";
EntityLinkMatcher(final String expectedUri) {
this.expectedUri = expectedUri;
}
static EntityLinkMatcher matchUri(
final String entityApi,
final String linkedEntityKey,
@Nullable final Set<String> optionalHalParams,
final String entityId
) {
return new EntityLinkMatcher(
getLinkedResourceExpectedUri(entityApi, entityId, optionalHalParams, linkedEntityKey)
);
}
@Override
protected boolean matchesSafely(final String actualUrl) {
if (!actualUrl.endsWith(this.expectedUri)) {
this.descriptionString = "Expected to end with: " + this.expectedUri + " got: " + actualUrl;
return false;
} else {
this.descriptionString = "Successfully matched: " + this.expectedUri;
return true;
}
}
@Override
public void describeTo(final Description description) {
description.appendText(this.descriptionString);
}
}
static class EntitiesLinksMatcher extends TypeSafeMatcher<Iterable<String>> {
private final Set<String> expectedUris;
private String mismatchDescription = "Not evaluated";
EntitiesLinksMatcher(final Set<String> expectedUris) {
this.expectedUris = expectedUris;
}
static EntitiesLinksMatcher matchUrisAnyOrder(
final String entityApi,
final String linkedEntityKey,
@Nullable final Set<String> optionalHalParams,
final Iterable<String> entityIds
) {
final Set<String> expectedUris = Sets.newHashSet();
for (String entityId : entityIds) {
expectedUris.add(getLinkedResourceExpectedUri(entityApi, entityId, optionalHalParams, linkedEntityKey));
}
return new EntitiesLinksMatcher(expectedUris);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean matchesSafely(final Iterable<String> inputUrls) {
final Set<String> urisToMatch = Sets.newHashSet(this.expectedUris);
for (String inputUrl : inputUrls) {
final List<String> matchedUrls = urisToMatch
.stream()
.filter(inputUrl::endsWith)
.collect(Collectors.toList());
if (matchedUrls.size() == 1) {
urisToMatch.remove(matchedUrls.get(0));
} else if (matchedUrls.size() == 0) {
this.mismatchDescription = "Unexpected input URL: " + inputUrl;
return false;
} else {
this.mismatchDescription = "Duplicate input URL: " + inputUrl;
return false;
}
}
if (!urisToMatch.isEmpty()) {
this.mismatchDescription = "Unmatched URLs: " + urisToMatch.toString();
return false;
}
this.mismatchDescription = "Successfully matched";
return true;
}
@Override
public void describeTo(final Description description) {
description.appendText(this.mismatchDescription);
}
}
}
| 2,349 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/RootRestControllerIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.apis.rest.v3.controllers;
import io.restassured.RestAssured;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpStatus;
/**
* Integration tests for the Root REST API.
*
* @author tgianos
* @since 3.0.0
*/
class RootRestControllerIntegrationTest extends RestControllerIntegrationTestBase {
@Test
void canGetRootResource() {
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get("/api/v3")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("description", Matchers.notNullValue())
.body(LINKS_PATH + ".keySet().size()", Matchers.is(5))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(APPLICATIONS_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(CLUSTERS_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(JOBS_LINK_KEY));
}
}
| 2,350 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/JobRestControllerIntegrationTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.ArchiveStatus;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterCriteria;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.dto.Criterion;
import com.netflix.genie.common.dto.JobRequest;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.dto.JobStatusMessages;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.web.introspection.GenieWebHostInfo;
import com.netflix.genie.web.properties.JobsLocationsProperties;
import com.netflix.genie.web.properties.LocalAgentLauncherProperties;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.restdocs.headers.HeaderDocumentation;
import org.springframework.restdocs.payload.PayloadDocumentation;
import org.springframework.restdocs.request.RequestDocumentation;
import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation;
import org.springframework.restdocs.restassured3.RestDocumentationFilter;
import org.springframework.test.context.TestPropertySource;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Integration tests for Jobs REST API.
*
* @author amsharma
* @author tgianos
* @since 3.0.0
*/
@TestPropertySource(
properties = {
LocalAgentLauncherProperties.PROPERTY_PREFIX + ".run-as-user=false",
}
)
class JobRestControllerIntegrationTest extends RestControllerIntegrationTestBase {
private static final Logger LOG = LoggerFactory.getLogger(JobRestControllerIntegrationTest.class);
private static final long SLEEP_TIME = 500L;
private static final String SCHEDULER_JOB_NAME_KEY = "schedulerJobName";
private static final String SCHEDULER_RUN_ID_KEY = "schedulerRunId";
private static final String COMMAND_ARGS_PATH = "commandArgs";
private static final String STATUS_MESSAGE_PATH = "statusMsg";
private static final String CLUSTER_NAME_PATH = "clusterName";
private static final String COMMAND_NAME_PATH = "commandName";
private static final String ARCHIVE_LOCATION_PATH = "archiveLocation";
private static final String STARTED_PATH = "started";
private static final String FINISHED_PATH = "finished";
private static final String CLUSTER_CRITERIAS_PATH = "clusterCriterias";
private static final String COMMAND_CRITERIA_PATH = "commandCriteria";
private static final String GROUP_PATH = "group";
private static final String DISABLE_LOG_ARCHIVAL_PATH = "disableLogArchival";
private static final String EMAIL_PATH = "email";
private static final String CPU_PATH = "cpu";
private static final String MEMORY_PATH = "memory";
private static final String APPLICATIONS_PATH = "applications";
private static final String HOST_NAME_PATH = "hostName";
private static final String PROCESS_ID_PATH = "processId";
private static final String CHECK_DELAY_PATH = "checkDelay";
private static final String EXIT_CODE_PATH = "exitCode";
private static final String CLIENT_HOST_PATH = "clientHost";
private static final String USER_AGENT_PATH = "userAgent";
private static final String NUM_ATTACHMENTS_PATH = "numAttachments";
private static final String TOTAL_SIZE_ATTACHMENTS_PATH = "totalSizeOfAttachments";
private static final String STD_OUT_SIZE_PATH = "stdOutSize";
private static final String STD_ERR_SIZE_PATH = "stdErrSize";
private static final String JOBS_LIST_PATH = EMBEDDED_PATH + ".jobSearchResultList";
private static final String GROUPING_PATH = "grouping";
private static final String GROUPING_INSTANCE_PATH = "groupingInstance";
private static final String ARCHIVE_STATUS_PATH = "archiveStatus";
private static final String JOB_COMMAND_LINK_PATH = "_links.command.href";
private static final String JOB_CLUSTER_LINK_PATH = "_links.cluster.href";
private static final String JOB_APPLICATIONS_LINK_PATH = "_links.applications.href";
private static final String BASE_DIR
= "com/netflix/genie/web/apis/rest/v3/controllers/JobRestControllerIntegrationTests/";
private static final String FILE_DELIMITER = "/";
private static final String LOCALHOST_CLUSTER_TAG = "localhost";
private static final String BASH_COMMAND_TAG = "bash";
private static final String JOB_NAME = "List * ... Directories bash job";
private static final String JOB_USER = "genie";
private static final String JOB_VERSION = "1.0";
private static final String JOB_DESCRIPTION = "Genie 3 Test Job";
private static final String JOB_STATUS_MSG = JobStatusMessages.JOB_FINISHED_SUCCESSFULLY;
private static final String APP1_ID = "app1";
private static final String APP1_NAME = "Application 1";
private static final String APP1_USER = "genie";
private static final String APP1_VERSION = "1.0";
private static final String APP2_ID = "app2";
private static final String APP2_NAME = "Application 2";
private static final String CMD1_ID = "cmd1";
private static final String CMD1_NAME = "Unix Bash command";
private static final String CMD1_USER = "genie";
private static final String CMD1_VERSION = "1.0";
private static final String CMD1_EXECUTABLE = "/bin/bash";
private static final ArrayList<String> CMD1_EXECUTABLE_AND_ARGS = Lists.newArrayList(CMD1_EXECUTABLE);
private static final String CLUSTER1_ID = "cluster1";
private static final String CLUSTER1_NAME = "Local laptop";
private static final String CLUSTER1_USER = "genie";
private static final String CLUSTER1_VERSION = "1.0";
private static final String JOB_TAG_1 = "aTag";
private static final String JOB_TAG_2 = "zTag";
private static final Set<String> JOB_TAGS = Sets.newHashSet(JOB_TAG_1, JOB_TAG_2);
private static final String JOB_GROUPING = "Workflow.Foo";
private static final String JOB_GROUPING_INSTANCE = "Workflow.Foo_Step.Blah-2020021919:12:34.000_1";
// This file is not UTF-8 encoded. It is uploaded to test server behavior
// related to charset headers
private static final String GB18030_TXT = "GB18030.txt";
private static final List<String> SLEEP_AND_ECHO_COMMAND_ARGS =
Lists.newArrayList("-c", "'sleep 5 && echo hello world'");
private static final ArrayList<String> SLEEP_60_COMMAND_ARGS = Lists.newArrayList("-c", "'sleep 60'");
private static final String EXPECTED_STDOUT_CONTENT = "hello world\n";
private static final int EXPECTED_STDOUT_LENGTH = EXPECTED_STDOUT_CONTENT.length();
private ResourceLoader resourceLoader;
private JsonNode metadata;
private String schedulerJobName;
private String schedulerRunId;
@Autowired
private JobsLocationsProperties jobsLocationsProperties;
@Autowired
private GenieWebHostInfo genieHostInfo;
@BeforeEach
void beforeJobs() throws Exception {
this.schedulerJobName = UUID.randomUUID().toString();
this.schedulerRunId = UUID.randomUUID().toString();
this.metadata = GenieObjectMapper.getMapper().readTree(
"{\""
+ SCHEDULER_JOB_NAME_KEY
+ "\":\""
+ this.schedulerJobName
+ "\", \""
+ SCHEDULER_RUN_ID_KEY
+ "\":\""
+ this.schedulerRunId
+ "\"}"
);
this.resourceLoader = new DefaultResourceLoader();
this.createAnApplication(APP1_ID, APP1_NAME);
this.createAnApplication(APP2_ID, APP2_NAME);
this.createAllClusters();
this.createAllCommands();
this.linkAllEntities();
}
@Test
void testSubmitJobMethodSuccess() throws Exception {
this.submitAndCheckJob(1, true);
}
@Test
void testForTooManyCommandArgs() throws Exception {
final JobRequest tooManyCommandArguments = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
Lists.newArrayList(new ClusterCriteria(Sets.newHashSet(LOCALHOST_CLUSTER_TAG))),
Sets.newHashSet(BASH_COMMAND_TAG)
)
.withCommandArgs(StringUtils.leftPad("bad", 10_001, 'a'))
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(tooManyCommandArguments))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("The maximum number of characters for the command arguments is 10,000"
)
);
}
private void submitAndCheckJob(final int documentationId, final boolean archiveJob) throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<String> commandArgs = SLEEP_AND_ECHO_COMMAND_ARGS;
final String clusterTag = LOCALHOST_CLUSTER_TAG;
final List<ClusterCriteria> clusterCriteriaList = Lists.newArrayList(
new ClusterCriteria(Sets.newHashSet(clusterTag))
);
final String setUpFile = this.getResourceURI(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile");
final String configFile1 = this.getResourceURI(BASE_DIR + "job" + FILE_DELIMITER + "config1");
final Set<String> configs = Sets.newHashSet(configFile1);
final String depFile1 = this.getResourceURI(BASE_DIR + "job" + FILE_DELIMITER + "dep1");
final Set<String> dependencies = Sets.newHashSet(depFile1);
final String commandTag = BASH_COMMAND_TAG;
final Set<String> commandCriteria = Sets.newHashSet(commandTag);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(!archiveJob)
.withSetupFile(setUpFile)
.withConfigs(configs)
.withDependencies(dependencies)
.withDescription(JOB_DESCRIPTION)
.withMetadata(this.metadata)
.withTags(JOB_TAGS)
.withGrouping(JOB_GROUPING)
.withGroupingInstance(JOB_GROUPING_INSTANCE)
.build();
final String id = this.submitJob(documentationId, jobRequest, null);
this.waitForDone(id);
this.checkJobStatus(documentationId, id);
this.checkJob(documentationId, id, commandArgs);
if (archiveJob) {
this.checkJobOutput(documentationId, id);
}
this.checkJobRequest(
documentationId,
id,
commandArgs,
setUpFile,
clusterTag,
commandTag,
configFile1,
depFile1,
archiveJob
);
this.checkJobExecution(documentationId, id);
this.checkJobMetadata(documentationId, id);
this.checkJobCluster(documentationId, id);
this.checkJobCommand(documentationId, id);
this.checkJobApplications(documentationId, id);
this.checkFindJobs(documentationId, id, JOB_USER);
this.checkJobArchive(id);
Assertions.assertThat(this.jobRepository.count()).isEqualTo(1L);
// Test for conflicts
this.testForConflicts(id, commandArgs, clusterCriteriaList, commandCriteria);
}
private String submitJob(
final int documentationId,
final JobRequest jobRequest,
@Nullable final List<MockMultipartFile> attachments
) throws Exception {
if (attachments != null) {
final RestDocumentationFilter createResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/submitJobWithAttachments/",
HeaderDocumentation.requestHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.CONTENT_TYPE)
.description(MediaType.MULTIPART_FORM_DATA_VALUE)
), // Request headers
RequestDocumentation.requestParts(
RequestDocumentation
.partWithName("request")
.description("The job request JSON. Content type must be application/json for part"),
RequestDocumentation
.partWithName("attachment")
.description("An attachment file. There can be multiple. Type should be octet-stream")
), // Request parts
Snippets.LOCATION_HEADER // Response Headers
);
final RequestSpecification jobRequestSpecification = RestAssured
.given(this.getRequestSpecification())
.filter(createResultFilter)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.multiPart(
"request",
GenieObjectMapper.getMapper().writeValueAsString(jobRequest),
MediaType.APPLICATION_JSON_VALUE
);
for (final MockMultipartFile attachment : attachments) {
jobRequestSpecification.multiPart(
"attachment",
attachment.getOriginalFilename(),
attachment.getBytes(),
MediaType.APPLICATION_OCTET_STREAM_VALUE
);
}
return this.getIdFromLocation(
jobRequestSpecification
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
} else {
// Use regular POST
final RestDocumentationFilter createResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/submitJobWithoutAttachments/",
Snippets.CONTENT_TYPE_HEADER, // Request headers
Snippets.getJobRequestRequestPayload(), // Request Fields
Snippets.LOCATION_HEADER // Response Headers
);
return this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.filter(createResultFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
}
}
private void checkJobStatus(final int documentationId, final String id) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobStatus/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.JSON_CONTENT_TYPE_HEADER, // Response Headers
PayloadDocumentation.responseFields(
PayloadDocumentation
.fieldWithPath("status")
.description("The job status. One of: " + Arrays.toString(JobStatus.values()))
.attributes(Snippets.EMPTY_CONSTRAINTS)
) // Response fields
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/status", id)
.then()
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body(STATUS_PATH, Matchers.is(JobStatus.SUCCEEDED.toString()));
}
private void checkJob(
final int documentationId,
final String id,
final List<String> commandArgs
) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJob/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getJobResponsePayload(), // Response fields
Snippets.JOB_LINKS // Links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(VERSION_PATH, Matchers.is(JOB_VERSION))
.body(USER_PATH, Matchers.is(JOB_USER))
.body(NAME_PATH, Matchers.is(JOB_NAME))
.body(DESCRIPTION_PATH, Matchers.is(JOB_DESCRIPTION))
.body(METADATA_PATH + "." + SCHEDULER_JOB_NAME_KEY, Matchers.is(this.schedulerJobName))
.body(METADATA_PATH + "." + SCHEDULER_RUN_ID_KEY, Matchers.is(this.schedulerRunId))
.body(COMMAND_ARGS_PATH, Matchers.is(StringUtils.join(commandArgs, StringUtils.SPACE)))
.body(STATUS_PATH, Matchers.is(JobStatus.SUCCEEDED.toString()))
.body(STATUS_MESSAGE_PATH, Matchers.is(JOB_STATUS_MSG))
.body(STARTED_PATH, Matchers.not(Instant.EPOCH))
.body(FINISHED_PATH, Matchers.notNullValue())
// TODO: Flipped during V4 migration to always be on to replicate expected behavior of V3 until clients
// can be migrated
// .body(ARCHIVE_LOCATION_PATH, archiveJob ? Matchers.notNullValue() : Matchers.isEmptyOrNullString())
.body(ARCHIVE_LOCATION_PATH, Matchers.notNullValue())
.body(CLUSTER_NAME_PATH, Matchers.is(CLUSTER1_NAME))
.body(COMMAND_NAME_PATH, Matchers.is(CMD1_NAME))
.body(TAGS_PATH, Matchers.contains(JOB_TAG_1, JOB_TAG_2))
.body(GROUPING_PATH, Matchers.is(JOB_GROUPING))
.body(GROUPING_INSTANCE_PATH, Matchers.is(JOB_GROUPING_INSTANCE))
.body(LINKS_PATH + ".keySet().size()", Matchers.is(9))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey("request"))
.body(LINKS_PATH, Matchers.hasKey("execution"))
.body(LINKS_PATH, Matchers.hasKey("output"))
.body(LINKS_PATH, Matchers.hasKey("status"))
.body(LINKS_PATH, Matchers.hasKey("cluster"))
.body(LINKS_PATH, Matchers.hasKey("command"))
.body(LINKS_PATH, Matchers.hasKey("applications"))
.body(LINKS_PATH, Matchers.hasKey("metadata"))
.body(
JOB_CLUSTER_LINK_PATH,
EntityLinkMatcher.matchUri(JOBS_API, "cluster", null, id))
.body(
JOB_COMMAND_LINK_PATH,
EntityLinkMatcher.matchUri(JOBS_API, "command", null, id))
.body(
JOB_APPLICATIONS_LINK_PATH,
EntityLinkMatcher.matchUri(JOBS_API, APPLICATIONS_LINK_KEY, null, id)
);
}
private void checkJobOutput(final int documentationId, final String id) throws Exception {
// Check getting a directory as json
final RestDocumentationFilter jsonResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobOutput/json/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation
.parameterWithName("filePath")
.description("The path to the directory to get")
.optional()
), // Path parameters
HeaderDocumentation.requestHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.ACCEPT)
.description(MediaType.APPLICATION_JSON_VALUE)
.optional()
), // Request header
HeaderDocumentation.responseHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.CONTENT_TYPE)
.description(MediaType.APPLICATION_JSON_VALUE)
), // Response Headers
Snippets.OUTPUT_DIRECTORY_FIELDS
);
final ValidatableResponse outputDirJsonResponse = RestAssured
.given(this.getRequestSpecification())
.filter(jsonResultFilter)
.accept(MediaType.APPLICATION_JSON_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE));
outputDirJsonResponse
.body("parent", Matchers.blankOrNullString())
.body("directories[0].name", Matchers.is("genie/"))
.body("files[0].name", Matchers.is("config1"))
.body("files[1].name", Matchers.is("dep1"))
.body("files[2].name", Matchers.is("genie_setup.sh"))
.body("files[3].name", Matchers.is("run"))
.body("files[4].name", Matchers.is("stderr"))
.body("files[5].name", Matchers.is("stdout"));
// Check getting a directory as HTML
final RestDocumentationFilter htmlResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobOutput/html/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation
.parameterWithName("filePath")
.description("The path to the directory to get")
.optional()
), // Path parameters
HeaderDocumentation.requestHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.ACCEPT)
.description(MediaType.TEXT_HTML)
), // Request header
HeaderDocumentation.responseHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.CONTENT_TYPE)
.description(MediaType.TEXT_HTML)
) // Response Headers
);
RestAssured
.given(this.getRequestSpecification())
.filter(htmlResultFilter)
.accept(MediaType.TEXT_HTML_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.TEXT_HTML_VALUE));
// Check getting a file
final RestDocumentationFilter fileResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobOutput/file/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation
.parameterWithName("filePath")
.description("The path to the file to get")
.optional()
), // Path parameters
HeaderDocumentation.requestHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.ACCEPT)
.description(MediaType.ALL_VALUE)
.optional()
), // Request header
HeaderDocumentation.responseHeaders(
HeaderDocumentation
.headerWithName(HttpHeaders.CONTENT_TYPE)
.description("The content type of the file being returned")
.optional()
) // Response Headers
);
final String setupFile = this.getResourceURI(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile");
final String setupFileContents = Files.readString(Paths.get(new URI(setupFile)));
RestAssured
.given(this.getRequestSpecification())
.filter(fileResultFilter)
.when()
.port(this.port)
.get(
JOBS_API + "/{id}/output/{filePath}",
id,
"genie_setup.sh"
)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.body(Matchers.is(setupFileContents));
// Validate content of 'run' file
final String expectedFilename = "runsh-agent.txt";
final String runFile = this.getResourceURI(BASE_DIR + expectedFilename);
final String runFileContent = Files.readString(Paths.get(new URI(runFile)));
final String testJobsDir = this.jobsLocationsProperties.getJobs().getPath();
final String expectedRunFileContent = this.getExpectedRunContents(
runFileContent,
testJobsDir + id,
id
);
RestAssured
.given(this.getRequestSpecification())
.filter(fileResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "run")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.body(Matchers.equalTo(expectedRunFileContent));
// Check stderr content and size
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stderr")
.then()
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(0))
.body(Matchers.emptyString());
// Check stdout content and size
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.header(HttpHeaders.CONTENT_LENGTH, Integer.toString(EXPECTED_STDOUT_LENGTH))
.body(Matchers.equalTo(EXPECTED_STDOUT_CONTENT));
checkGetFileRanges(id);
}
private void checkGetFileRanges(final String id) {
// Range request -- full range
RestAssured
.given(this.getRequestSpecification())
.header(HttpHeaders.RANGE, "bytes=0-" + (EXPECTED_STDOUT_LENGTH - 1))
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.PARTIAL_CONTENT.value()))
.header(HttpHeaders.CONTENT_LENGTH, Integer.toString(EXPECTED_STDOUT_LENGTH))
.body(Matchers.equalTo(EXPECTED_STDOUT_CONTENT));
// Range request -- start offset
RestAssured
.given(this.getRequestSpecification())
.header(HttpHeaders.RANGE, "bytes=" + (EXPECTED_STDOUT_LENGTH - 2) + "-")
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.PARTIAL_CONTENT.value()))
.header(HttpHeaders.CONTENT_LENGTH, Integer.toString(2))
.body(Matchers.equalTo(EXPECTED_STDOUT_CONTENT.substring(EXPECTED_STDOUT_LENGTH - 2)));
// Range request -- suffix
RestAssured
.given(this.getRequestSpecification())
.header(HttpHeaders.RANGE, "bytes=" + (-2))
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.PARTIAL_CONTENT.value()))
.header(HttpHeaders.CONTENT_LENGTH, Integer.toString(2))
.body(Matchers.equalTo(EXPECTED_STDOUT_CONTENT.substring(EXPECTED_STDOUT_LENGTH - 2)));
// Range request -- range
RestAssured
.given(this.getRequestSpecification())
.header(HttpHeaders.RANGE, "bytes=6-10")
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.PARTIAL_CONTENT.value()))
.header(HttpHeaders.CONTENT_LENGTH, Integer.toString(5))
.body(Matchers.equalTo(EXPECTED_STDOUT_CONTENT.substring(6, 11)));
// Range request -- request more than it's available
RestAssured
.given(this.getRequestSpecification())
.header(HttpHeaders.RANGE, "bytes=0-1000")
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.header(HttpHeaders.CONTENT_LENGTH, Integer.toString(EXPECTED_STDOUT_LENGTH))
.body(Matchers.equalTo(EXPECTED_STDOUT_CONTENT));
// Range request -- out of range
RestAssured
.given(this.getRequestSpecification())
.header(HttpHeaders.RANGE, "bytes=" + EXPECTED_STDOUT_LENGTH + "-")
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", id, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value()))
.header(HttpHeaders.CONTENT_LENGTH, Matchers.blankOrNullString());
}
private void checkJobRequest(
final int documentationId,
final String id,
final List<String> commandArgs,
final String setupFile,
final String clusterTag,
final String commandTag,
final String configFile1,
final String depFile1,
final boolean archiveJob
) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobRequest/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getJobRequestResponsePayload(), // Response fields
Snippets.JOB_REQUEST_LINKS // Links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/request", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.nullValue())
.body(CREATED_PATH, Matchers.nullValue())
.body(UPDATED_PATH, Matchers.nullValue())
.body(NAME_PATH, Matchers.is(JOB_NAME))
.body(VERSION_PATH, Matchers.is(JOB_VERSION))
.body(USER_PATH, Matchers.is(JOB_USER))
.body(DESCRIPTION_PATH, Matchers.is(JOB_DESCRIPTION))
.body(METADATA_PATH + "." + SCHEDULER_JOB_NAME_KEY, Matchers.is(this.schedulerJobName))
.body(METADATA_PATH + "." + SCHEDULER_RUN_ID_KEY, Matchers.is(this.schedulerRunId))
.body(COMMAND_ARGS_PATH, Matchers.is(StringUtils.join(commandArgs, StringUtils.SPACE)))
.body(SETUP_FILE_PATH, Matchers.is(setupFile))
.body(CLUSTER_CRITERIAS_PATH, Matchers.hasSize(1))
.body(CLUSTER_CRITERIAS_PATH + "[0].tags", Matchers.hasSize(1))
.body(CLUSTER_CRITERIAS_PATH + "[0].tags[0]", Matchers.is(clusterTag))
.body(COMMAND_CRITERIA_PATH, Matchers.hasSize(1))
.body(COMMAND_CRITERIA_PATH + "[0]", Matchers.is(commandTag))
.body(GROUP_PATH, Matchers.nullValue())
.body(DISABLE_LOG_ARCHIVAL_PATH, Matchers.is(!archiveJob))
.body(CONFIGS_PATH, Matchers.hasSize(1))
.body(CONFIGS_PATH + "[0]", Matchers.is(configFile1))
.body(DEPENDENCIES_PATH, Matchers.hasSize(1))
.body(DEPENDENCIES_PATH + "[0]", Matchers.is(depFile1))
.body(EMAIL_PATH, Matchers.nullValue())
.body(CPU_PATH, Matchers.nullValue())
.body(MEMORY_PATH, Matchers.nullValue())
.body(APPLICATIONS_PATH, Matchers.empty())
.body(TAGS_PATH, Matchers.contains(JOB_TAG_1, JOB_TAG_2))
.body(GROUPING_PATH, Matchers.is(JOB_GROUPING))
.body(GROUPING_INSTANCE_PATH, Matchers.is(JOB_GROUPING_INSTANCE));
}
private void checkJobExecution(final int documentationId, final String id) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobExecution/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getJobExecutionResponsePayload(), // Response fields
Snippets.JOB_EXECUTION_LINKS // Links
);
final ValidatableResponse validatableResponse = RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/execution", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(HOST_NAME_PATH, Matchers.is(this.genieHostInfo.getHostname()))
.body(ARCHIVE_STATUS_PATH, Matchers.is(ArchiveStatus.ARCHIVED.toString()));
// TODO these are not populated
validatableResponse
.body(PROCESS_ID_PATH, Matchers.nullValue())
.body(CHECK_DELAY_PATH, Matchers.nullValue())
.body(EXIT_CODE_PATH, Matchers.nullValue());
}
private void checkJobMetadata(final int documentationId, final String id) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobMetadata/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getJobMetadataResponsePayload(), // Response fields
Snippets.JOB_METADATA_LINKS // Links
);
final ValidatableResponse validatableResponse = RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/metadata", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(CLIENT_HOST_PATH, Matchers.notNullValue())
.body(USER_AGENT_PATH, Matchers.notNullValue())
.body(NUM_ATTACHMENTS_PATH, Matchers.notNullValue())
.body(TOTAL_SIZE_ATTACHMENTS_PATH, Matchers.notNullValue());
// TODO: These are not populated
validatableResponse
.body(STD_OUT_SIZE_PATH, Matchers.nullValue())
.body(STD_ERR_SIZE_PATH, Matchers.nullValue());
}
private void checkJobCluster(final int documentationId, final String id) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobCluster/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getClusterResponsePayload(), // Response fields
Snippets.CLUSTER_LINKS // Links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/cluster", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(CLUSTER1_ID))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(CLUSTER1_NAME))
.body(USER_PATH, Matchers.is(CLUSTER1_USER))
.body(VERSION_PATH, Matchers.is(CLUSTER1_VERSION));
}
private void checkJobCommand(final int documentationId, final String id) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobCommand/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getCommandResponsePayload(), // Response fields
Snippets.COMMAND_LINKS // Links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/command", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(CMD1_ID))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(CMD1_NAME))
.body(USER_PATH, Matchers.is(CMD1_USER))
.body(VERSION_PATH, Matchers.is(CMD1_VERSION))
.body("executable", Matchers.is(CMD1_EXECUTABLE))
.body("executableAndArguments", Matchers.equalTo(CMD1_EXECUTABLE_AND_ARGS));
}
private void checkJobApplications(final int documentationId, final String id) {
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/getJobApplications/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
PayloadDocumentation.responseFields(
PayloadDocumentation
.subsectionWithPath("[]")
.description("The applications for the job")
.attributes(Snippets.EMPTY_CONSTRAINTS)
) // Response fields
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/applications", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("[0].id", Matchers.is(APP1_ID))
.body("[1].id", Matchers.is(APP2_ID));
}
private void checkFindJobs(final int documentationId, final String id, final String user) {
final RestDocumentationFilter findResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/" + documentationId + "/findJobs/",
Snippets.JOB_SEARCH_QUERY_PARAMETERS, // Request query parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response headers
Snippets.JOB_SEARCH_RESULT_FIELDS, // Result fields
Snippets.SEARCH_LINKS // HAL Links
);
RestAssured
.given(this.getRequestSpecification())
.filter(findResultFilter)
.param("user", user)
.when()
.port(this.port)
.get(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(JOBS_LIST_PATH, Matchers.hasSize(1))
.body(JOBS_LIST_PATH + "[0].id", Matchers.is(id));
}
private void testForConflicts(
final String id,
final List<String> commandArgs,
final List<ClusterCriteria> clusterCriteriaList,
final Set<String> commandCriteria
) throws Exception {
final JobRequest jobConflictRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withId(id)
.withCommandArgs(commandArgs)
.withDisableLogArchival(true)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobConflictRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CONFLICT.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE));
}
private void checkJobArchive(
final String id
) {
final Path archiveDirectory = Paths.get(this.jobsLocationsProperties.getArchives()).resolve(id);
// TODO: This is flipped during V4 migration and should be changed back once clients are fixed
Assertions.assertThat(Files.exists(archiveDirectory)).isTrue();
Assertions.assertThat(Files.isDirectory(archiveDirectory)).isTrue();
}
@Test
void canSubmitJobWithAttachments() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = Lists.newArrayList(
new ClusterCriteria(Sets.newHashSet(LOCALHOST_CLUSTER_TAG))
);
final String setUpFile = this.getResourceURI(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile");
final File attachment1File = this.resourceLoader
.getResource(BASE_DIR + "job/query.sql")
.getFile();
final MockMultipartFile attachment1;
try (InputStream is = new FileInputStream(attachment1File)) {
attachment1 = new MockMultipartFile(
"attachment",
attachment1File.getName(),
MediaType.APPLICATION_OCTET_STREAM_VALUE,
is
);
}
final File attachment2File = this.resourceLoader
.getResource(BASE_DIR + "job/query2.sql")
.getFile();
final MockMultipartFile attachment2;
try (InputStream is = new FileInputStream(attachment2File)) {
attachment2 = new MockMultipartFile(
"attachment",
attachment2File.getName(),
MediaType.APPLICATION_OCTET_STREAM_VALUE,
is
);
}
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(true)
.withSetupFile(setUpFile)
.withDescription(JOB_DESCRIPTION)
.build();
this.waitForDone(this.submitJob(4, jobRequest, Lists.newArrayList(attachment1, attachment2)));
}
@Test
void testSubmitJobMethodMissingCluster() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet("undefined");
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final String jobId = UUID.randomUUID().toString();
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withId(jobId)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.anyOf(
Matchers.containsString(
"No cluster/command combination found for the given criteria. Unable to continue"
),
Matchers.containsString("No cluster selected given criteria for job"),
Matchers.containsString("No clusters available to run any candidate command on")
)
)
.body("stackTrace", Matchers.nullValue());
Assertions.assertThat(this.getStatus(jobId)).isEqualByComparingTo(JobStatus.FAILED);
}
@Test
void testSubmitJobMethodInvalidClusterCriteria() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList
= Lists.newArrayList(new ClusterCriteria(Sets.newHashSet(" ", "", null)));
final String jobId = UUID.randomUUID().toString();
final Set<String> commandCriteria = Sets.newHashSet("bash");
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withId(jobId)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/status", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()));
}
@Test
void testSubmitJobMethodInvalidCommandCriteria() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList
= Lists.newArrayList(new ClusterCriteria(Sets.newHashSet("ok")));
final String jobId = UUID.randomUUID().toString();
final Set<String> commandCriteria = Sets.newHashSet(" ", "", null);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withId(jobId)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/status", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()));
}
@Test
void testSubmitJobMethodMissingCommand() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final String jobId = UUID.randomUUID().toString();
final Set<String> commandCriteria = Sets.newHashSet("undefined");
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withId(jobId)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()));
Assertions.assertThat(this.getStatus(jobId)).isEqualByComparingTo(JobStatus.FAILED);
}
@Test
void testSubmitJobMethodKill() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withCommandArgs(SLEEP_60_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
final String jobId = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
this.waitForRunning(jobId);
// Make sure we can get output for a running job
final ValidatableResponse outputResponse = RestAssured
.given(this.getRequestSpecification())
.accept(MediaType.APPLICATION_JSON_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", jobId, "")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body("parent", Matchers.is(Matchers.emptyOrNullString()))
.body("directories[0].name", Matchers.is("genie/"));
outputResponse
.body("files[0].name", Matchers.is("run"))
.body("files[1].name", Matchers.is("stderr"))
.body("files[2].name", Matchers.is("stdout"));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output/{filePath}", jobId, "stdout")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(ContentType.TEXT.toString()));
// Let it run for a couple of seconds
Thread.sleep(2000);
// Send a kill request to the job.
final RestDocumentationFilter killResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/killJob/",
Snippets.ID_PATH_PARAM
);
RestAssured
.given(this.getRequestSpecification())
.filter(killResultFilter)
.when()
.port(this.port)
.delete(JOBS_API + "/{id}", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()));
this.waitForDone(jobId);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(jobId))
.body(STATUS_PATH, Matchers.is(JobStatus.KILLED.toString()))
.body(STATUS_MESSAGE_PATH, Matchers.is(JobStatusMessages.JOB_KILLED_BY_USER));
// Kill the job again to make sure it doesn't cause a problem.
RestAssured
.given(this.getRequestSpecification())
.filter(killResultFilter)
.when()
.port(this.port)
.delete(JOBS_API + "/{id}", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()));
}
@Test
void testSubmitJobMethodKillOnTimeout() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest.Builder builder = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withTimeout(1)
.withDisableLogArchival(true)
.withCommandArgs(SLEEP_60_COMMAND_ARGS);
final JobRequest jobRequest = builder.build();
final String id = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
this.waitForDone(id);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(STATUS_PATH, Matchers.is(JobStatus.KILLED.toString()))
.body(STATUS_MESSAGE_PATH, Matchers.is(JobStatusMessages.JOB_EXCEEDED_TIMEOUT));
}
@Test
void testKillJobImmediately() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withCommandArgs(SLEEP_60_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
final String jobId = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
// // Let it run for a couple of seconds
// Thread.sleep(2000);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.delete(JOBS_API + "/{id}", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()));
this.waitForDone(jobId);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(jobId))
.body(STATUS_PATH, Matchers.is(JobStatus.KILLED.toString()))
.body(STATUS_MESSAGE_PATH, Matchers.is(JobStatusMessages.JOB_KILLED_BY_USER));
// Kill the job again to make sure it doesn't cause a problem.
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.delete(JOBS_API + "/{id}", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()));
}
@Test
void testSubmitJobMethodFailure() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<String> commandArgs;
commandArgs = Lists.newArrayList("-c", "sleep 3 && exit 1");
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withCommandArgs(commandArgs)
.withDisableLogArchival(true)
.build();
final String id = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
this.waitForDone(id);
Assertions.assertThat(this.getStatus(id)).isEqualByComparingTo(JobStatus.FAILED);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(STATUS_PATH, Matchers.is(JobStatus.FAILED.toString()))
.body(STATUS_MESSAGE_PATH, Matchers.is(JobStatusMessages.JOB_FAILED));
}
@Test
void testResponseContentType() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final String utf8 = "UTF-8";
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
Lists.newArrayList(new ClusterCriteria(Sets.newHashSet("localhost"))),
Sets.newHashSet("bash")
)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.build();
final String jobId = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
this.waitForRunning(jobId);
RestAssured
.given(this.getRequestSpecification())
.accept(MediaType.ALL_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/" + jobId + "/output/stdout")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
.contentType(Matchers.containsString(utf8));
RestAssured
.given(this.getRequestSpecification())
.accept(MediaType.ALL_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/" + jobId + "/output/stderr")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
.contentType(Matchers.containsString(utf8));
// Verify the file is served as UTF-8 even if it's not
RestAssured
.given(this.getRequestSpecification())
.accept(MediaType.ALL_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/" + jobId + "/output/genie/command/" + CMD1_ID + "/config/" + GB18030_TXT)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
.contentType(Matchers.containsString(utf8));
}
@Test
void testJobNotFound() {
Assertions.assertThat(this.jobRepository.count()).isEqualTo(0L);
final String jobId = UUID.randomUUID().toString();
final ArrayList<String> paths = Lists.newArrayList(
"",
"/request",
"/execution",
"/status",
"/metadata"
);
for (final String path : paths) {
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}" + path, jobId)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(EXCEPTION_MESSAGE_PATH, Matchers.startsWith("No job"))
.body(EXCEPTION_MESSAGE_PATH, Matchers.containsString(jobId));
}
// TODO '/output' behaves differently than the rest.
// The resource handler composes the response, including in case of error, rather than just throwing.
// Would be nice to align this. Hard for now due to support of both V3 and V4 logic.
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/output", jobId)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(EXCEPTION_MESSAGE_PATH, Matchers.startsWith("No job with id " + jobId));
}
@Test
void testFileNotFound() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final String utf8 = "UTF-8";
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
Lists.newArrayList(new ClusterCriteria(Sets.newHashSet("localhost"))),
Sets.newHashSet("bash")
)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.build();
final String jobId = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
this.waitForRunning(jobId);
RestAssured
.given(this.getRequestSpecification())
.accept(MediaType.ALL_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/" + jobId + "/output/stdout")
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaType.TEXT_PLAIN_VALUE))
.contentType(Matchers.containsString(utf8));
RestAssured
.given(this.getRequestSpecification())
.accept(MediaType.ALL_VALUE)
.when()
.port(this.port)
.get(JOBS_API + "/" + jobId + "/output/" + UUID.randomUUID())
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()));
}
private JobStatus getStatus(final String jobId) throws IOException {
final String statusString = RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}/status", jobId)
.asString();
return JobStatus.valueOf(GenieObjectMapper.getMapper().readTree(statusString).get("status").textValue());
}
private void waitForDone(final String jobId) throws Exception {
int counter = 0;
while (true) {
final JobStatus status = this.getStatus(jobId);
if (status.isActive()) {
LOG.info("Iteration {} sleeping for {} ms", counter, SLEEP_TIME);
Thread.sleep(SLEEP_TIME);
counter++;
} else {
break;
}
}
}
private void waitForRunning(final String jobId) throws Exception {
int counter = 0;
while (true) {
final JobStatus status = this.getStatus(jobId);
if (status != JobStatus.RUNNING && !status.isFinished()) {
LOG.info("Iteration {} sleeping for {} ms", counter, SLEEP_TIME);
Thread.sleep(SLEEP_TIME);
counter++;
} else {
break;
}
}
}
private void linkAllEntities() throws Exception {
final List<String> apps = new ArrayList<>();
apps.add(APP1_ID);
apps.add(APP2_ID);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(apps))
.when()
.port(this.port)
.post(COMMANDS_API + FILE_DELIMITER + CMD1_ID + FILE_DELIMITER + APPLICATIONS_LINK_KEY)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
}
private void createAnApplication(final String id, final String appName) throws Exception {
final String setUpFile = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "setupfile");
final String depFile1 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "dep1");
final String depFile2 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "dep2");
final Set<String> app1Dependencies = Sets.newHashSet(depFile1, depFile2);
final String configFile1 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "config1");
final String configFile2 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "config2");
final Set<String> app1Configs = Sets.newHashSet(configFile1, configFile2);
final Application app = new Application.Builder(
appName,
APP1_USER,
APP1_VERSION,
ApplicationStatus.ACTIVE)
.withId(id)
.withSetupFile(setUpFile)
.withConfigs(app1Configs)
.withDependencies(app1Dependencies)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(app))
.when()
.port(this.port)
.post(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue());
}
private void createAllClusters() throws Exception {
final String setUpFile = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "setupfile");
final String configFile1 = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "config1");
final String configFile2 = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "config2");
final Set<String> configs = Sets.newHashSet(configFile1, configFile2);
final String depFile1 = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "dep1");
final String depFile2 = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "dep2");
final Set<String> clusterDependencies = Sets.newHashSet(depFile1, depFile2);
final Set<String> tags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final Cluster cluster = new Cluster.Builder(
CLUSTER1_NAME,
CLUSTER1_USER,
CLUSTER1_VERSION,
ClusterStatus.UP
)
.withId(CLUSTER1_ID)
.withSetupFile(setUpFile)
.withConfigs(configs)
.withDependencies(clusterDependencies)
.withTags(tags)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(cluster))
.when()
.port(this.port)
.post(CLUSTERS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue());
}
private void createAllCommands() throws Exception {
final String setUpFile = this.getResourceURI(BASE_DIR + CMD1_ID + FILE_DELIMITER + "setupfile");
final String configFile1 = this.getResourceURI(BASE_DIR + CMD1_ID + FILE_DELIMITER + "config1");
final String configFile2 = this.getResourceURI(BASE_DIR + CMD1_ID + FILE_DELIMITER + "config2");
final String configFile3 = this.getResourceURI(BASE_DIR + CMD1_ID + FILE_DELIMITER + GB18030_TXT);
final Set<String> configs = Sets.newHashSet(configFile1, configFile2, configFile3);
final String depFile1 = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "dep1");
final String depFile2 = this.getResourceURI(BASE_DIR + CLUSTER1_ID + FILE_DELIMITER + "dep2");
final Set<String> commandDependencies = Sets.newHashSet(depFile1, depFile2);
final Set<String> tags = Sets.newHashSet(BASH_COMMAND_TAG);
final Command cmd = new Command.Builder(
CMD1_NAME,
CMD1_USER,
CMD1_VERSION,
CommandStatus.ACTIVE,
CMD1_EXECUTABLE_AND_ARGS
)
.withId(CMD1_ID)
.withSetupFile(setUpFile)
.withConfigs(configs)
.withDependencies(commandDependencies)
.withTags(tags)
.withClusterCriteria(
Lists.newArrayList(
new Criterion.Builder().withTags(Sets.newHashSet(LOCALHOST_CLUSTER_TAG)).build()
)
)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(cmd))
.when()
.port(this.port)
.post(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue());
}
private String getResourceURI(final String location) throws IOException {
return this.resourceLoader.getResource(location).getURI().toString();
}
private String getExpectedRunContents(
final String runFileContents,
final String jobWorkingDir,
final String jobId
) {
return runFileContents
.replaceAll("TEST_GENIE_JOB_WORKING_DIR_PLACEHOLDER", jobWorkingDir)
.replaceAll("JOB_ID_PLACEHOLDER", jobId);
}
}
| 2,351 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/IntegrationTestActiveProfilesResolver.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.controllers;
import com.google.common.collect.Sets;
import org.springframework.test.context.ActiveProfilesResolver;
import java.util.Set;
/**
* A class to switch the active profiles for integration tests based on environment variables.
*
* @author tgianos
* @since 3.0.0
*/
public class IntegrationTestActiveProfilesResolver implements ActiveProfilesResolver {
private static final String DB_SELECTOR_ENV_VARIABLE_NAME = "INTEGRATION_TEST_DB";
private static final String MYSQL = "mysql";
private static final String POSTGRESQL = "postgresql";
private static final String H2 = "h2";
private final Set<String> knownDatabaseProfiles = Sets.newHashSet(
MYSQL,
POSTGRESQL,
H2
);
/**
* {@inheritDoc}
*/
@Override
public String[] resolve(final Class<?> testClass) {
final String integrationTestDatabase = System.getProperty(DB_SELECTOR_ENV_VARIABLE_NAME, H2);
if (!this.knownDatabaseProfiles.contains(integrationTestDatabase)) {
throw new IllegalStateException("Unknown database profile: " + integrationTestDatabase);
}
return new String[]{
"integration",
"db",
"db-" + integrationTestDatabase,
};
}
}
| 2,352 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/CommandRestControllerIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.apis.rest.v3.controllers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.fge.jsonpatch.JsonPatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.dto.Criterion;
import com.netflix.genie.common.dto.ResolvedResources;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.restdocs.payload.PayloadDocumentation;
import org.springframework.restdocs.request.RequestDocumentation;
import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation;
import org.springframework.restdocs.restassured3.RestDocumentationFilter;
import org.springframework.restdocs.snippet.Attributes;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Integration tests for the Commands REST API.
*
* @author tgianos
* @since 3.0.0
*/
class CommandRestControllerIntegrationTest extends RestControllerIntegrationTestBase {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = "hive";
private static final String USER = "genie";
private static final String VERSION = "1.0.0";
private static final String EXECUTABLE = "/apps/hive/bin/hive";
private static final ImmutableList<String> EXECUTABLE_AND_ARGS = ImmutableList.of("/apps/hive/bin/hive");
private static final String DESCRIPTION = "Hive command v" + VERSION;
private static final int MEMORY = 1024;
private static final String CONFIG_1 = "s3:///path/to/config-foo";
private static final String CONFIG_2 = "s3:///path/to/config-bar";
private static final ImmutableSet<String> CONFIGS = ImmutableSet.of(CONFIG_1, CONFIG_2);
private static final String DEP_1 = "/path/to/file/foo";
private static final String DEP_2 = "/path/to/file/bar";
private static final ImmutableSet<String> DEPENDENCIES = ImmutableSet.of(DEP_1, DEP_2);
private static final String TAG_1 = "tag:foo";
private static final String TAG_2 = "tag:bar";
private static final Set<String> TAGS = Sets.newHashSet(TAG_1, TAG_2);
private static final ImmutableList<Criterion> CLUSTER_CRITERIA = ImmutableList.of(
new Criterion
.Builder()
.withId(UUID.randomUUID().toString())
.withTags(Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build(),
new Criterion
.Builder()
.withId(UUID.randomUUID().toString())
.withName("prod")
.withVersion("1.0.0")
.withStatus(ClusterStatus.UP.name())
.withTags(
Sets.newHashSet(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
)
)
.build()
);
private static final String EXECUTABLE_PATH = "executable";
private static final String EXECUTABLE_AND_ARGS_PATH = "executableAndArguments";
private static final String CHECK_DELAY_PATH = "checkDelay";
private static final String MEMORY_PATH = "memory";
private static final String CLUSTER_CRITERIA_PATH = "clusterCriteria";
private static final String COMMANDS_LIST_PATH = EMBEDDED_PATH + ".commandList";
private static final String COMMAND_APPS_LINK_PATH = "_links.applications.href";
private static final String COMMANDS_APPS_LINK_PATH = COMMANDS_LIST_PATH + "._links.applications.href";
private static final String COMMAND_CLUSTERS_LINK_PATH = "_links.clusters.href";
private static final String COMMANDS_CLUSTERS_LINK_PATH = COMMANDS_LIST_PATH + "._links.clusters.href";
private static final String COMMANDS_ID_LIST_PATH = EMBEDDED_PATH + ".commandList.id";
@BeforeEach
void beforeCommands() {
Assertions.assertThat(this.commandRepository.count()).isEqualTo(0L);
}
@Test
void canCreateCommandWithoutId() throws Exception {
final RestDocumentationFilter createFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request headers
Snippets.getCommandRequestPayload(), // Request fields
Snippets.LOCATION_HEADER // Response headers
);
final String id = this.createConfigResource(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withDescription(DESCRIPTION)
.withMemory(MEMORY)
.withConfigs(CONFIGS)
.withDependencies(DEPENDENCIES)
.withTags(TAGS)
.withClusterCriteria(CLUSTER_CRITERIA)
.build(),
createFilter
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // response headers
Snippets.getCommandResponsePayload(), // response payload
Snippets.COMMAND_LINKS // response links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getFilter)
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(NAME))
.body(USER_PATH, Matchers.is(USER))
.body(VERSION_PATH, Matchers.is(VERSION))
.body(STATUS_PATH, Matchers.is(CommandStatus.ACTIVE.toString()))
.body(EXECUTABLE_PATH, Matchers.is(EXECUTABLE))
.body(CHECK_DELAY_PATH, Matchers.is((int) Command.DEFAULT_CHECK_DELAY))
.body(DESCRIPTION_PATH, Matchers.is(DESCRIPTION))
.body(MEMORY_PATH, Matchers.is(MEMORY))
.body(CONFIGS_PATH, Matchers.hasSize(2))
.body(CONFIGS_PATH, Matchers.hasItems(CONFIG_1, CONFIG_2))
.body(DEPENDENCIES_PATH, Matchers.hasSize(2))
.body(DEPENDENCIES_PATH, Matchers.hasItems(DEP_1, DEP_2))
.body(TAGS_PATH, Matchers.hasSize(4))
.body(TAGS_PATH, Matchers.hasItem("genie.id:" + id))
.body(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME))
.body(TAGS_PATH, Matchers.hasItems(TAG_1, TAG_2))
.body(CLUSTER_CRITERIA_PATH, Matchers.hasSize(CLUSTER_CRITERIA.size()))
.body(
CLUSTER_CRITERIA_PATH + "[0].id",
Matchers.is(CLUSTER_CRITERIA.get(0).getId().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[0].name",
Matchers.is(CLUSTER_CRITERIA.get(0).getName().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[0].version",
Matchers.is(CLUSTER_CRITERIA.get(0).getVersion().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[0].status",
Matchers.is(CLUSTER_CRITERIA.get(0).getStatus().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[0].tags",
Matchers.containsInAnyOrder(CLUSTER_CRITERIA.get(0).getTags().toArray(new String[0]))
)
.body(
CLUSTER_CRITERIA_PATH + "[1].id",
Matchers.is(CLUSTER_CRITERIA.get(1).getId().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[1].name",
Matchers.is(CLUSTER_CRITERIA.get(1).getName().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[1].version",
Matchers.is(CLUSTER_CRITERIA.get(1).getVersion().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[1].status",
Matchers.is(CLUSTER_CRITERIA.get(1).getStatus().orElse(null))
)
.body(
CLUSTER_CRITERIA_PATH + "[1].tags",
Matchers.containsInAnyOrder(CLUSTER_CRITERIA.get(1).getTags().toArray(new String[0]))
)
.body(LINKS_PATH + ".keySet().size()", Matchers.is(3))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(CLUSTERS_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(APPLICATIONS_LINK_KEY))
.body(
COMMAND_CLUSTERS_LINK_PATH,
EntityLinkMatcher.matchUri(
COMMANDS_API,
CLUSTERS_LINK_KEY,
CLUSTERS_OPTIONAL_HAL_LINK_PARAMETERS,
id
)
)
.body(
COMMAND_APPS_LINK_PATH,
EntityLinkMatcher.matchUri(
COMMANDS_API,
APPLICATIONS_LINK_KEY,
null,
id
)
);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(1L);
}
@Test
void canCreateCommandWithId() throws Exception {
this.createConfigResource(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.withDescription(DESCRIPTION)
.withMemory(MEMORY)
.withConfigs(CONFIGS)
.withDependencies(DEPENDENCIES)
.withTags(TAGS)
.build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}", ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(ID))
.body(CREATED_PATH, Matchers.notNullValue())
.body(UPDATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(NAME))
.body(USER_PATH, Matchers.is(USER))
.body(VERSION_PATH, Matchers.is(VERSION))
.body(STATUS_PATH, Matchers.is(CommandStatus.ACTIVE.toString()))
.body(EXECUTABLE_PATH, Matchers.is(EXECUTABLE))
.body(EXECUTABLE_AND_ARGS_PATH, Matchers.is(EXECUTABLE_AND_ARGS))
.body(CHECK_DELAY_PATH, Matchers.is((int) Command.DEFAULT_CHECK_DELAY))
.body(DESCRIPTION_PATH, Matchers.is(DESCRIPTION))
.body(MEMORY_PATH, Matchers.is(MEMORY))
.body(CONFIGS_PATH, Matchers.hasSize(2))
.body(CONFIGS_PATH, Matchers.hasItems(CONFIG_1, CONFIG_2))
.body(DEPENDENCIES_PATH, Matchers.hasSize(2))
.body(DEPENDENCIES_PATH, Matchers.hasItems(DEP_1, DEP_2))
.body(TAGS_PATH, Matchers.hasSize(4))
.body(TAGS_PATH, Matchers.hasItem("genie.id:" + ID))
.body(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME))
.body(TAGS_PATH, Matchers.hasItems(TAG_1, TAG_2))
.body(CLUSTER_CRITERIA_PATH, Matchers.hasSize(0))
.body(LINKS_PATH + ".keySet().size()", Matchers.is(3))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(CLUSTERS_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(APPLICATIONS_LINK_KEY))
.body(
COMMAND_CLUSTERS_LINK_PATH,
EntityLinkMatcher.matchUri(
COMMANDS_API,
CLUSTERS_LINK_KEY,
CLUSTERS_OPTIONAL_HAL_LINK_PARAMETERS,
ID
)
)
.body(
COMMAND_APPS_LINK_PATH,
EntityLinkMatcher.matchUri(
COMMANDS_API,
APPLICATIONS_LINK_KEY,
null,
ID
)
);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(1L);
}
@Test
void canHandleBadInputToCreateCommand() throws Exception {
final Command cluster =
new Command.Builder(" ", " ", " ", CommandStatus.ACTIVE, Lists.newArrayList("")).build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(cluster))
.when()
.port(this.port)
.post(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("must not be empty"
)
);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(0L);
}
@Test
void canFindCommands() throws Exception {
final String id1 = UUID.randomUUID().toString();
final String id2 = UUID.randomUUID().toString();
final String id3 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString();
final String name3 = UUID.randomUUID().toString();
final String user1 = UUID.randomUUID().toString();
final String user2 = UUID.randomUUID().toString();
final String user3 = UUID.randomUUID().toString();
final String version1 = UUID.randomUUID().toString();
final String version2 = UUID.randomUUID().toString();
final String version3 = UUID.randomUUID().toString();
this.createConfigResource(
new Command
.Builder(name1, user1, version1, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(id1)
.build(),
null
);
Thread.sleep(1000);
this.createConfigResource(
new Command
.Builder(name2, user2, version2, CommandStatus.DEPRECATED, EXECUTABLE_AND_ARGS)
.withId(id2)
.build(),
null
);
Thread.sleep(1000);
this.createConfigResource(
new Command
.Builder(name3, user3, version3, CommandStatus.INACTIVE, EXECUTABLE_AND_ARGS)
.withId(id3)
.build(),
null
);
final RestDocumentationFilter findFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.COMMAND_SEARCH_QUERY_PARAMETERS, // Request query parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response headers
Snippets.COMMAND_SEARCH_RESULT_FIELDS, // Result fields
Snippets.SEARCH_LINKS // HAL Links
);
// Test finding all commands
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.when()
.port(this.port)
.get(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(COMMANDS_LIST_PATH, Matchers.hasSize(3))
.body(COMMANDS_ID_LIST_PATH, Matchers.containsInAnyOrder(id1, id2, id3))
.body(
COMMANDS_APPS_LINK_PATH,
EntitiesLinksMatcher
.matchUrisAnyOrder(
COMMANDS_API,
APPLICATIONS_LINK_KEY,
null,
Lists.newArrayList(id1, id2, id3)
)
)
.body(
COMMANDS_CLUSTERS_LINK_PATH,
EntitiesLinksMatcher.
matchUrisAnyOrder(
COMMANDS_API,
CLUSTERS_LINK_KEY,
CLUSTERS_OPTIONAL_HAL_LINK_PARAMETERS,
Lists.newArrayList(id1, id2, id3)
)
);
// Try to limit the number of results
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("size", 2)
.when()
.port(this.port)
.get(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(COMMANDS_LIST_PATH, Matchers.hasSize(2));
// Query by name
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("name", name2)
.when()
.port(this.port)
.get(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(COMMANDS_LIST_PATH, Matchers.hasSize(1))
.body(COMMANDS_LIST_PATH + "[0].id", Matchers.is(id2));
// Query by user
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("user", user3)
.when()
.port(this.port)
.get(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(COMMANDS_LIST_PATH, Matchers.hasSize(1))
.body(COMMANDS_LIST_PATH + "[0].id", Matchers.is(id3));
// Query by statuses
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("status", CommandStatus.ACTIVE.toString(), CommandStatus.INACTIVE.toString())
.when()
.port(this.port)
.get(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(COMMANDS_LIST_PATH, Matchers.hasSize(2))
.body(COMMANDS_LIST_PATH + "[0].id", Matchers.is(id3))
.body(COMMANDS_LIST_PATH + "[1].id", Matchers.is(id1));
// Query by tags
RestAssured
.given(this.getRequestSpecification())
.filter(findFilter)
.param("tag", "genie.id:" + id1)
.when()
.port(this.port)
.get(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(COMMANDS_LIST_PATH, Matchers.hasSize(1))
.body(COMMANDS_LIST_PATH + "[0].id", Matchers.is(id1));
//TODO: Add tests for sort, orderBy etc
Assertions.assertThat(this.commandRepository.count()).isEqualTo(3L);
}
@Test
void canUpdateCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String commandResource = COMMANDS_API + "/{id}";
final Command createdCommand = GenieObjectMapper.getMapper()
.readValue(
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.extract()
.asByteArray(),
new TypeReference<EntityModel<Command>>() {
}
).getContent();
Assertions.assertThat(createdCommand).isNotNull();
Assertions.assertThat(createdCommand.getStatus()).isEqualByComparingTo(CommandStatus.ACTIVE);
final Command.Builder updateCommand = new Command.Builder(
createdCommand.getName(),
createdCommand.getUser(),
createdCommand.getVersion(),
CommandStatus.INACTIVE,
createdCommand.getExecutableAndArguments()
)
.withId(createdCommand.getId().orElseThrow(IllegalArgumentException::new))
.withCreated(createdCommand.getCreated().orElseThrow(IllegalArgumentException::new))
.withUpdated(createdCommand.getUpdated().orElseThrow(IllegalArgumentException::new))
.withTags(createdCommand.getTags())
.withConfigs(createdCommand.getConfigs())
.withDependencies(createdCommand.getDependencies());
createdCommand.getDescription().ifPresent(updateCommand::withDescription);
createdCommand.getSetupFile().ifPresent(updateCommand::withSetupFile);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request header
Snippets.ID_PATH_PARAM, // path parameters
Snippets.getCommandRequestPayload() // payload fields
);
RestAssured
.given(this.getRequestSpecification())
.filter(updateFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(updateCommand.build()))
.when()
.port(this.port)
.put(commandResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(STATUS_PATH, Matchers.is(CommandStatus.INACTIVE.toString()));
Assertions.assertThat(this.commandRepository.count()).isEqualTo(1L);
}
@Test
void canPatchCommand() throws Exception {
final String id = this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String commandResource = COMMANDS_API + "/{id}";
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(NAME_PATH, Matchers.is(NAME));
final String newName = UUID.randomUUID().toString();
final String patchString = "[{ \"op\": \"replace\", \"path\": \"/name\", \"value\": \"" + newName + "\" }]";
final JsonPatch patch = JsonPatch.fromJson(GenieObjectMapper.getMapper().readTree(patchString));
final RestDocumentationFilter patchFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request headers
Snippets.ID_PATH_PARAM, // path params
Snippets.PATCH_FIELDS // request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(patchFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(patch))
.when()
.port(this.port)
.patch(commandResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(NAME_PATH, Matchers.is(newName));
Assertions.assertThat(this.commandRepository.count()).isEqualTo(1L);
}
@Test
void canDeleteAllCommands() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.DEPRECATED, EXECUTABLE_AND_ARGS)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.INACTIVE, EXECUTABLE_AND_ARGS)
.build(),
null
);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(3L);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/"
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
Assertions.assertThat(this.commandRepository.count()).isEqualTo(0L);
}
@Test
void canDeleteACommand() throws Exception {
final String id1 = UUID.randomUUID().toString();
final String id2 = UUID.randomUUID().toString();
final String id3 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString();
final String name3 = UUID.randomUUID().toString();
final String user1 = UUID.randomUUID().toString();
final String user2 = UUID.randomUUID().toString();
final String user3 = UUID.randomUUID().toString();
final String version1 = UUID.randomUUID().toString();
final String version2 = UUID.randomUUID().toString();
final String version3 = UUID.randomUUID().toString();
this.createConfigResource(
new Command
.Builder(name1, user1, version1, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(id1)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(name2, user2, version2, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(id2)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(name3, user3, version3, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(id3)
.build(),
null
);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(3L);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(COMMANDS_API + "/{id}", id2)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}", id2)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("No command with id"
)
);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(2L);
}
@Test
void canAddConfigsToCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.CONTENT_TYPE_HEADER, // request header
PayloadDocumentation.requestFields(Snippets.CONFIG_FIELDS) // response fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.CONFIG_FIELDS) // response fields
);
this.canAddElementsToResource(COMMANDS_API + "/{id}/configs", ID, addFilter, getFilter);
}
@Test
void canUpdateConfigsForCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.CONFIG_FIELDS) // Request fields
);
this.canUpdateElementsForResource(COMMANDS_API + "/{id}/configs", ID, updateFilter);
}
@Test
void canDeleteConfigsForCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM
);
this.canDeleteElementsFromResource(COMMANDS_API + "/{id}/configs", ID, deleteFilter);
}
@Test
void canAddDependenciesToCommand() throws Exception {
this.createConfigResource(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.CONTENT_TYPE_HEADER, // request header
PayloadDocumentation.requestFields(Snippets.DEPENDENCIES_FIELDS) // response fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.DEPENDENCIES_FIELDS) // response fields
);
this.canAddElementsToResource(
COMMANDS_API + "/{id}/dependencies",
ID,
addFilter,
getFilter
);
}
@Test
void canUpdateDependenciesForCommand() throws Exception {
this.createConfigResource(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.DEPENDENCIES_FIELDS) // Request fields
);
this.canUpdateElementsForResource(
COMMANDS_API + "/{id}/dependencies",
ID,
updateFilter
);
}
@Test
void canDeleteDependenciesForCommand() throws Exception {
this.createConfigResource(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // Path variables
);
this.canDeleteElementsFromResource(
COMMANDS_API + "/{id}/dependencies",
ID,
deleteFilter
);
}
@Test
void canAddTagsToCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String api = COMMANDS_API + "/{id}/tags";
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.TAGS_FIELDS) // Request fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.JSON_CONTENT_TYPE_HEADER, // Response header
PayloadDocumentation.responseFields(Snippets.TAGS_FIELDS)
);
this.canAddTagsToResource(api, ID, NAME, addFilter, getFilter);
}
@Test
void canUpdateTagsForCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String api = COMMANDS_API + "/{id}/tags";
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.TAGS_FIELDS) // Request fields
);
this.canUpdateTagsForResource(api, ID, NAME, updateFilter);
}
@Test
void canDeleteTagsForCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String api = COMMANDS_API + "/{id}/tags";
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM
);
this.canDeleteTagsForResource(api, ID, NAME, deleteFilter);
}
@Test
void canDeleteTagForCommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String api = COMMANDS_API + "/{id}/tags";
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation.parameterWithName("tag").description("The tag to remove")
)
);
this.canDeleteTagForResource(api, ID, NAME, deleteFilter);
}
@Test
void canAddApplicationsForACommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String commandApplicationsAPI = COMMANDS_API + "/{id}/applications";
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
final String placeholder = UUID.randomUUID().toString();
final String applicationId1 = UUID.randomUUID().toString();
final String applicationId2 = UUID.randomUUID().toString();
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId1)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId2)
.build(),
null
);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request Headers
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of application ids to add to existing set of applications")
.attributes(Snippets.EMPTY_CONSTRAINTS)
) // Request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(addFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(
GenieObjectMapper
.getMapper()
.writeValueAsBytes(Lists.newArrayList(applicationId1, applicationId2))
)
.when()
.port(this.port)
.post(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("[0].id", Matchers.is(applicationId1))
.body("[1].id", Matchers.is(applicationId2));
//Shouldn't add anything
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList()))
.when()
.port(this.port)
.post(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(EXCEPTION_MESSAGE_PATH, Matchers.notNullValue());
final String applicationId3 = UUID.randomUUID().toString();
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId3)
.build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.filter(addFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList(applicationId3)))
.when()
.port(this.port)
.post(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
PayloadDocumentation.responseFields(
PayloadDocumentation
.subsectionWithPath("[]")
.description("The set of applications this command depends on")
.attributes(Snippets.EMPTY_CONSTRAINTS)
)
);
RestAssured
.given(this.getRequestSpecification())
.filter(getFilter)
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(3))
.body("[0].id", Matchers.is(applicationId1))
.body("[1].id", Matchers.is(applicationId2))
.body("[2].id", Matchers.is(applicationId3));
}
@Test
void canSetApplicationsForACommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String commandApplicationsAPI = COMMANDS_API + "/{id}/applications";
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
final String placeholder = UUID.randomUUID().toString();
final String applicationId1 = UUID.randomUUID().toString();
final String applicationId2 = UUID.randomUUID().toString();
final String applicationId3 = UUID.randomUUID().toString();
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId1)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId2)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId3)
.build(),
null
);
final RestDocumentationFilter setFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request Headers
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of application ids to replace the existing set of applications with")
.attributes(Snippets.EMPTY_CONSTRAINTS)
) // Request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(setFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList(applicationId1, applicationId2)))
.when()
.port(this.port)
.put(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("[0].id", Matchers.is(applicationId1))
.body("[1].id", Matchers.is(applicationId2));
// Should flip the order
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList(applicationId2, applicationId1)))
.when()
.port(this.port)
.put(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("[0].id", Matchers.is(applicationId2))
.body("[1].id", Matchers.is(applicationId1));
// Should reorder and add a new one
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(
GenieObjectMapper
.getMapper()
.writeValueAsBytes(Lists.newArrayList(applicationId1, applicationId2, applicationId3))
)
.when()
.port(this.port)
.put(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(3))
.body("[0].id", Matchers.is(applicationId1))
.body("[1].id", Matchers.is(applicationId2))
.body("[2].id", Matchers.is(applicationId3));
//Should clear applications
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList()))
.when()
.port(this.port)
.put(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
}
@Test
void canRemoveApplicationsFromACommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String commandApplicationsAPI = COMMANDS_API + "/{id}/applications";
final String placeholder = UUID.randomUUID().toString();
final String applicationId1 = UUID.randomUUID().toString();
final String applicationId2 = UUID.randomUUID().toString();
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId1)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId2)
.build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(Lists.newArrayList(applicationId1, applicationId2)))
.when()
.port(this.port)
.post(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // Path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
}
@Test
void canRemoveApplicationFromACommand() throws Exception {
this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build(),
null
);
final String commandApplicationsAPI = COMMANDS_API + "/{id}/applications";
final String placeholder = UUID.randomUUID().toString();
final String applicationId1 = UUID.randomUUID().toString();
final String applicationId2 = UUID.randomUUID().toString();
final String applicationId3 = UUID.randomUUID().toString();
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId1)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId2)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(placeholder, placeholder, placeholder, ApplicationStatus.ACTIVE)
.withId(applicationId3)
.build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(
GenieObjectMapper
.getMapper()
.writeValueAsBytes(Lists.newArrayList(applicationId1, applicationId2, applicationId3))
)
.when()
.port(this.port)
.post(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation
.parameterWithName("applicationId")
.description("The id of the application to remove")
) // Path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(commandApplicationsAPI + "/{applicationId}", ID, applicationId2)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(commandApplicationsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(2))
.body("[0].id", Matchers.is(applicationId1))
.body("[1].id", Matchers.is(applicationId3));
// Check reverse side of relationship
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}/commands", applicationId1)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(1))
.body("[0].id", Matchers.is(ID));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}/commands", applicationId2)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.empty());
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}/commands", applicationId3)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(1))
.body("[0].id", Matchers.is(ID));
}
@Test
void canGetClustersForCommand() throws Exception {
final String placeholder = UUID.randomUUID().toString();
final String cluster1Id = this.createConfigResource(
new Cluster.Builder(placeholder, placeholder, placeholder, ClusterStatus.UP).build(),
null
);
final String cluster2Id = this.createConfigResource(
new Cluster.Builder(placeholder, placeholder, placeholder, ClusterStatus.OUT_OF_SERVICE).build(),
null
);
final String cluster3Id = this.createConfigResource(
new Cluster
.Builder(placeholder, placeholder, placeholder, ClusterStatus.TERMINATED)
.build(),
null
);
final String commandId = this.createConfigResource(
new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withClusterCriteria(
Lists.newArrayList(
new Criterion.Builder().withId(cluster1Id).build(),
new Criterion.Builder().withId(cluster2Id).build(),
new Criterion.Builder().withId(cluster3Id).build()
)
)
.build(),
null
);
Assertions
.assertThat(
Arrays.stream(
GenieObjectMapper.getMapper().readValue(
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}/clusters", commandId)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.extract()
.asByteArray(),
new TypeReference<EntityModel<Cluster>[]>() {
}
)
)
.map(EntityModel::getContent)
.filter(Objects::nonNull)
.map(Cluster::getId)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList())
)
.containsExactlyInAnyOrder(cluster1Id, cluster2Id, cluster3Id);
// Test filtering
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
RequestDocumentation.requestParameters(
RequestDocumentation
.parameterWithName("status")
.description("The status of clusters to search for")
.attributes(
Attributes.key(Snippets.CONSTRAINTS).value(CommandStatus.values())
)
.optional()
), // Query Parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
PayloadDocumentation.responseFields(
PayloadDocumentation
.subsectionWithPath("[]")
.description("The list of clusters found")
.attributes(Snippets.EMPTY_CONSTRAINTS)
)
);
RestAssured
.given(this.getRequestSpecification())
.filter(getFilter)
.param("status", ClusterStatus.UP.toString())
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}/clusters", commandId)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(1))
.body("[0].id", Matchers.is(cluster1Id));
}
@Test
void canCreateCommandWithBlankFields() throws Exception {
final Set<String> stringSetWithBlank = Sets.newHashSet("foo", " ");
final List<Command> invalidCommandResources = Lists.newArrayList(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(UUID.randomUUID().toString())
.withSetupFile(" ")
.build(),
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(UUID.randomUUID().toString())
.withConfigs(stringSetWithBlank)
.build(),
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(UUID.randomUUID().toString())
.withDependencies(stringSetWithBlank)
.build(),
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(UUID.randomUUID().toString())
.withTags(stringSetWithBlank)
.build()
);
long i = 0L;
for (final Command invalidCommandResource : invalidCommandResources) {
Assertions.assertThat(this.commandRepository.count()).isEqualTo(i);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(invalidCommandResource))
.when()
.port(this.port)
.post(COMMANDS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()));
Assertions.assertThat(this.commandRepository.count()).isEqualTo(++i);
}
}
@Test
void testCommandNotFound() {
final List<String> paths = Lists.newArrayList("", "/applications", "/clusters", "/clusterCriteria");
for (final String relationPath : paths) {
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}" + relationPath, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.startsWith(MediaType.APPLICATION_JSON_VALUE))
.body(EXCEPTION_MESSAGE_PATH, Matchers.is("No command with id " + ID + " exists"));
}
}
@Test
void testGetClusterCriteria() throws Exception {
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
Snippets.JSON_CONTENT_TYPE_HEADER, // Response Headers
Snippets.getClusterCriteriaForCommandResponsePayload() // Response Fields
);
final String id = this.createCommandWithDefaultClusterCriteria();
// Don't use the helper method as we want to document this call this time
final List<Criterion> clusterCriteria = RestAssured
.given(this.getRequestSpecification())
.filter(getFilter)
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}/clusterCriteria", id)
.then()
.statusCode(HttpStatus.OK.value())
.contentType(ContentType.JSON)
.extract()
.jsonPath()
.getList(".", Criterion.class);
Assertions.assertThat(clusterCriteria).isEqualTo(CLUSTER_CRITERIA);
}
@Test
void testRemoveAllClusterCriteriaFromCommand() throws Exception {
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // Path parameters
);
final String id = this.createCommandWithDefaultClusterCriteria();
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(COMMANDS_API + "/{id}/clusterCriteria", id)
.then()
.statusCode(HttpStatus.OK.value());
Assertions.assertThat(this.getClusterCriteria(id)).isEmpty();
}
@Test
void testAddLowestPriorityClusterCriterion() throws Exception {
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters,
Snippets.CONTENT_TYPE_HEADER, // Request Header
Snippets.addClusterCriterionForCommandRequestPayload() // Payload Docs
);
final String id = this.createCommandWithDefaultClusterCriteria();
final Criterion newCriterion = new Criterion
.Builder()
.withVersion("3.0.0")
.withId(UUID.randomUUID().toString())
.withName("adhocCluster")
.withStatus(ClusterStatus.UP.name())
.withTags(Sets.newHashSet("sched:adhoc", "type:yarn"))
.build();
RestAssured
.given(this.getRequestSpecification())
.filter(addFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(newCriterion))
.when()
.port(this.port)
.post(COMMANDS_API + "/{id}/clusterCriteria", id)
.then()
.statusCode(HttpStatus.OK.value());
Assertions
.assertThat(this.getClusterCriteria(id))
.hasSize(CLUSTER_CRITERIA.size() + 1)
.containsSequence(CLUSTER_CRITERIA)
.last()
.isEqualTo(newCriterion);
}
@Test
void testSetClusterCriteriaForCommand() throws Exception {
final RestDocumentationFilter setFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters,
Snippets.CONTENT_TYPE_HEADER, // Request Header
Snippets.setClusterCriteriaForCommandRequestPayload() // Payload Docs
);
final String id = this.createCommandWithDefaultClusterCriteria();
final List<Criterion> newCriteria = Lists.newArrayList(
new Criterion.Builder().withId(UUID.randomUUID().toString()).build(),
new Criterion.Builder().withVersion(UUID.randomUUID().toString()).build(),
new Criterion.Builder().withName(UUID.randomUUID().toString()).build()
);
Assertions.assertThat(newCriteria).doesNotContainAnyElementsOf(CLUSTER_CRITERIA);
RestAssured
.given(this.getRequestSpecification())
.filter(setFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(newCriteria))
.when()
.port(this.port)
.put(COMMANDS_API + "/{id}/clusterCriteria", id)
.then()
.statusCode(HttpStatus.OK.value());
Assertions.assertThat(this.getClusterCriteria(id)).isEqualTo(newCriteria);
}
@Test
void testInsertClusterCriterionForCommand() throws Exception {
final RestDocumentationFilter insertFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
// Path parameters
Snippets
.ID_PATH_PARAM
.and(
RequestDocumentation
.parameterWithName("priority")
.description("Priority of the criterion to insert")
),
Snippets.CONTENT_TYPE_HEADER, // Request Header
Snippets.addClusterCriterionForCommandRequestPayload() // Payload Docs
);
final String id = this.createCommandWithDefaultClusterCriteria();
final Criterion newCriterion = new Criterion
.Builder()
.withVersion("4.0.0")
.withId(UUID.randomUUID().toString())
.withName("insightCluster")
.withStatus(ClusterStatus.OUT_OF_SERVICE.name())
.withTags(Sets.newHashSet("sched:insights", "type:presto"))
.build();
RestAssured
.given(this.getRequestSpecification())
.filter(insertFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(newCriterion))
.when()
.port(this.port)
.put(COMMANDS_API + "/{id}/clusterCriteria/{priority}", id, 1)
.then()
.statusCode(HttpStatus.OK.value());
Assertions
.assertThat(this.getClusterCriteria(id))
.hasSize(CLUSTER_CRITERIA.size() + 1)
.containsExactly(CLUSTER_CRITERIA.get(0), newCriterion, CLUSTER_CRITERIA.get(1));
}
@Test
void testRemoveClusterCriterionFromCommand() throws Exception {
final RestDocumentationFilter removeFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
// Path parameters
Snippets
.ID_PATH_PARAM
.and(
RequestDocumentation
.parameterWithName("priority")
.description("Priority of the criterion to insert")
)
);
final String id = this.createCommandWithDefaultClusterCriteria();
RestAssured
.given(this.getRequestSpecification())
.filter(removeFilter)
.when()
.port(this.port)
.delete(COMMANDS_API + "/{id}/clusterCriteria/{priority}", id, 1)
.then()
.statusCode(HttpStatus.OK.value());
Assertions
.assertThat(this.getClusterCriteria(id))
.hasSize(CLUSTER_CRITERIA.size() - 1)
.containsExactly(CLUSTER_CRITERIA.get(0));
// Running again throws 404
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.delete(COMMANDS_API + "/{id}/clusterCriteria/{priority}", id, 1)
.then()
.statusCode(HttpStatus.NOT_FOUND.value());
}
@Test
void testResolveClustersForCommandClusterCriteria() throws Exception {
final Cluster cluster0 = new Cluster.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
ClusterStatus.UP
)
.withTags(Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build();
final Cluster cluster1 = new Cluster.Builder(
cluster0.getName(),
cluster0.getUser(),
cluster0.getVersion(),
ClusterStatus.UP
)
.withTags(cluster0.getTags())
.build();
final Cluster cluster2 = new Cluster.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
ClusterStatus.UP
)
.withTags(Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build();
final String cluster0Id = this.createConfigResource(cluster0, null);
final String cluster1Id = this.createConfigResource(cluster1, null);
final String cluster2Id = this.createConfigResource(cluster2, null);
final Command command = new Command
.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withClusterCriteria(
Lists.newArrayList(
new Criterion.Builder().withId(cluster0Id).build(),
new Criterion.Builder().withName(cluster1.getName()).build(),
new Criterion.Builder().withVersion(cluster2.getVersion()).build(),
new Criterion.Builder().withStatus(ClusterStatus.TERMINATED.name()).build(),
new Criterion.Builder().withTags(cluster2.getTags()).build()
)
)
.build();
final String commandId = this.createConfigResource(command, null);
final RestDocumentationFilter resolveFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
// Path parameters
Snippets.ID_PATH_PARAM,
// Request parameters
RequestDocumentation.requestParameters(
RequestDocumentation
.parameterWithName("addDefaultStatus")
.description(
"Whether the system should add the default cluster status to the criteria. Default: true"
)
.optional()
),
// Response Content Type
Snippets.JSON_CONTENT_TYPE_HEADER,
// Response Fields
Snippets.resolveClustersForCommandClusterCriteriaResponsePayload()
);
final List<ResolvedResources<Cluster>> resolvedClusters = GenieObjectMapper.getMapper().readValue(
RestAssured
.given(this.getRequestSpecification())
.filter(resolveFilter)
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}/resolvedClusters", commandId)
.then()
.statusCode(HttpStatus.OK.value())
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.extract()
.asString(),
new TypeReference<>() {
}
);
Assertions.assertThat(resolvedClusters).hasSize(5);
ResolvedResources<Cluster> resolvedResources = resolvedClusters.get(0);
Assertions.assertThat(resolvedResources.getCriterion()).isEqualTo(command.getClusterCriteria().get(0));
Assertions
.assertThat(resolvedResources.getResources())
.extracting(Cluster::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactlyInAnyOrder(cluster0Id);
resolvedResources = resolvedClusters.get(1);
Assertions.assertThat(resolvedResources.getCriterion()).isEqualTo(command.getClusterCriteria().get(1));
Assertions
.assertThat(resolvedResources.getResources())
.extracting(Cluster::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactlyInAnyOrder(cluster0Id, cluster1Id);
resolvedResources = resolvedClusters.get(2);
Assertions.assertThat(resolvedResources.getCriterion()).isEqualTo(command.getClusterCriteria().get(2));
Assertions
.assertThat(resolvedResources.getResources())
.extracting(Cluster::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactlyInAnyOrder(cluster2Id);
resolvedResources = resolvedClusters.get(3);
Assertions.assertThat(resolvedResources.getCriterion()).isEqualTo(command.getClusterCriteria().get(3));
Assertions.assertThat(resolvedResources.getResources()).isEmpty();
resolvedResources = resolvedClusters.get(4);
Assertions.assertThat(resolvedResources.getCriterion()).isEqualTo(command.getClusterCriteria().get(4));
Assertions
.assertThat(resolvedResources.getResources())
.extracting(Cluster::getId)
.filteredOn(Optional::isPresent)
.extracting(Optional::get)
.containsExactlyInAnyOrder(cluster2Id);
}
private String createCommandWithDefaultClusterCriteria() throws Exception {
return this.createConfigResource(
new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withClusterCriteria(CLUSTER_CRITERIA)
.build(),
null
);
}
private List<Criterion> getClusterCriteria(final String id) {
return RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(COMMANDS_API + "/{id}/clusterCriteria", id)
.then()
.statusCode(HttpStatus.OK.value())
.contentType(ContentType.JSON)
.extract()
.jsonPath()
.getList(".", Criterion.class);
}
}
| 2,353 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/Snippets.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.controllers;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.dto.ContainerImage;
import com.netflix.genie.common.dto.Job;
import com.netflix.genie.common.dto.JobExecution;
import com.netflix.genie.common.dto.JobMetadata;
import com.netflix.genie.common.dto.JobRequest;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.dto.Runtime;
import com.netflix.genie.common.dto.RuntimeResources;
import com.netflix.genie.common.internal.dtos.Criterion;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import org.springframework.restdocs.headers.HeaderDocumentation;
import org.springframework.restdocs.headers.RequestHeadersSnippet;
import org.springframework.restdocs.headers.ResponseHeadersSnippet;
import org.springframework.restdocs.hypermedia.HypermediaDocumentation;
import org.springframework.restdocs.hypermedia.LinksSnippet;
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.restdocs.payload.JsonFieldType;
import org.springframework.restdocs.payload.PayloadDocumentation;
import org.springframework.restdocs.payload.RequestFieldsSnippet;
import org.springframework.restdocs.payload.ResponseFieldsSnippet;
import org.springframework.restdocs.request.ParameterDescriptor;
import org.springframework.restdocs.request.PathParametersSnippet;
import org.springframework.restdocs.request.RequestDocumentation;
import org.springframework.restdocs.request.RequestParametersSnippet;
import org.springframework.restdocs.snippet.Attributes;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* Helper class for getting field descriptors for various DTOs.
*
* @author tgianos
* @since 3.0.0
*/
final class Snippets {
static final RequestHeadersSnippet CONTENT_TYPE_HEADER = HeaderDocumentation.requestHeaders(
HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE).description(MediaType.APPLICATION_JSON_VALUE)
);
static final ResponseHeadersSnippet LOCATION_HEADER = HeaderDocumentation.responseHeaders(
HeaderDocumentation.headerWithName(HttpHeaders.LOCATION).description("The URI")
);
static final ResponseHeadersSnippet HAL_CONTENT_TYPE_HEADER = HeaderDocumentation.responseHeaders(
HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE).description(MediaTypes.HAL_JSON_VALUE)
);
static final ResponseHeadersSnippet JSON_CONTENT_TYPE_HEADER = HeaderDocumentation.responseHeaders(
HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE).description(MediaType.APPLICATION_JSON_VALUE)
);
static final PathParametersSnippet ID_PATH_PARAM = RequestDocumentation.pathParameters(
RequestDocumentation.parameterWithName("id").description("The resource id")
);
static final LinksSnippet SEARCH_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("The current search"),
HypermediaDocumentation
.linkWithRel("first")
.description("The first page for this search")
.optional(),
HypermediaDocumentation
.linkWithRel("prev")
.description("The previous page for this search")
.optional(),
HypermediaDocumentation
.linkWithRel("next")
.description("The next page for this search")
.optional(),
HypermediaDocumentation
.linkWithRel("last")
.description("The last page for this search")
.optional()
);
static final LinksSnippet APPLICATION_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this application"),
HypermediaDocumentation
.linkWithRel("commands")
.description("Get all the commands using this application")
);
static final LinksSnippet CLUSTER_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this cluster"),
HypermediaDocumentation
.linkWithRel("commands")
.description("Get all the commands this cluster can use")
);
static final LinksSnippet COMMAND_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this command"),
HypermediaDocumentation
.linkWithRel("applications")
.description("Get all the applications this command depends on"),
HypermediaDocumentation
.linkWithRel("clusters")
.description("Get all clusters this command is available on")
);
static final LinksSnippet JOB_REQUEST_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this job request"),
HypermediaDocumentation
.linkWithRel("job")
.description("The job that resulted from this request"),
HypermediaDocumentation
.linkWithRel("execution")
.description("The job execution that resulted from this request"),
HypermediaDocumentation
.linkWithRel("metadata")
.description("The job metadata information for this job"),
HypermediaDocumentation
.linkWithRel("output")
.description("The output URI for the job"),
HypermediaDocumentation
.linkWithRel("status")
.description("The current status of the job")
);
static final LinksSnippet JOB_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this job"),
HypermediaDocumentation
.linkWithRel("request")
.description("The request that kicked off this job"),
HypermediaDocumentation
.linkWithRel("execution")
.description("The job execution information for this job"),
HypermediaDocumentation
.linkWithRel("metadata")
.description("The job metadata information for this job"),
HypermediaDocumentation
.linkWithRel("output")
.description("The output URI for the job"),
HypermediaDocumentation
.linkWithRel("status")
.description("The current status of the job"),
HypermediaDocumentation
.linkWithRel("cluster")
.description("The cluster this job ran on")
.optional(),
HypermediaDocumentation
.linkWithRel("command")
.description("The command this job executed")
.optional(),
HypermediaDocumentation
.linkWithRel("applications")
.description("The applications this job used")
.optional()
);
static final LinksSnippet JOB_EXECUTION_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this job execution"),
HypermediaDocumentation
.linkWithRel("job")
.description("The job associated with this execution"),
HypermediaDocumentation
.linkWithRel("request")
.description("The job request that spawned this execution"),
HypermediaDocumentation
.linkWithRel("metadata")
.description("The job metadata information for this job"),
HypermediaDocumentation
.linkWithRel("output")
.description("The output URI for the job"),
HypermediaDocumentation
.linkWithRel("status")
.description("The current status of the job")
);
static final LinksSnippet JOB_METADATA_LINKS = HypermediaDocumentation.links(
HypermediaDocumentation
.linkWithRel("self")
.description("URI for this job metadata"),
HypermediaDocumentation
.linkWithRel("job")
.description("The job associated with this execution"),
HypermediaDocumentation
.linkWithRel("request")
.description("The job request that spawned this execution"),
HypermediaDocumentation
.linkWithRel("execution")
.description("The job execution information for this job"),
HypermediaDocumentation
.linkWithRel("output")
.description("The output URI for the job"),
HypermediaDocumentation
.linkWithRel("status")
.description("The current status of the job")
);
static final String CONSTRAINTS = "constraints";
static final Attributes.Attribute EMPTY_CONSTRAINTS = Attributes.key(CONSTRAINTS).value("");
static final FieldDescriptor[] CONFIG_FIELDS = new FieldDescriptor[]{
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of configuration file locations")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS),
};
static final FieldDescriptor[] DEPENDENCIES_FIELDS = new FieldDescriptor[]{
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of dependency file locations")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS),
};
static final FieldDescriptor[] TAGS_FIELDS = new FieldDescriptor[]{
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of tags")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS),
};
static final RequestFieldsSnippet PATCH_FIELDS = PayloadDocumentation.requestFields(
PayloadDocumentation
.fieldWithPath("[]")
.description("Array of patches to apply")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("[].op")
.description("Patch operation to perform.")
.type(JsonFieldType.STRING)
.attributes(Attributes.key(CONSTRAINTS).value("add, remove, replace, copy, move, test")),
PayloadDocumentation
.fieldWithPath("[].path")
.description("The json path to operate on. e.g. /user")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("[].from")
.description("The json path to move or copy from. e.g. /user")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS)
.optional(),
PayloadDocumentation
.fieldWithPath("[].value")
.description("The json value to put at the path for an add, replace or test")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS)
.optional()
);
static final ResponseFieldsSnippet APPLICATION_SEARCH_RESULT_FIELDS = PayloadDocumentation
.responseFields(
ArrayUtils.addAll(
getSearchResultFields(),
PayloadDocumentation
.subsectionWithPath("_embedded.applicationList")
.description("The found applications.")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS)
)
);
static final ResponseFieldsSnippet CLUSTER_SEARCH_RESULT_FIELDS = PayloadDocumentation
.responseFields(
ArrayUtils.addAll(
getSearchResultFields(),
PayloadDocumentation
.subsectionWithPath("_embedded.clusterList")
.description("The found clusters.")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS)
)
);
static final ResponseFieldsSnippet COMMAND_SEARCH_RESULT_FIELDS = PayloadDocumentation
.responseFields(
ArrayUtils.addAll(
getSearchResultFields(),
PayloadDocumentation
.subsectionWithPath("_embedded.commandList")
.description("The found commands.")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS)
)
);
static final ResponseFieldsSnippet JOB_SEARCH_RESULT_FIELDS = PayloadDocumentation
.responseFields(
ArrayUtils.addAll(
getSearchResultFields(),
PayloadDocumentation
.subsectionWithPath("_embedded.jobSearchResultList")
.description("The found jobs.")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS)
)
);
static final ResponseFieldsSnippet OUTPUT_DIRECTORY_FIELDS = PayloadDocumentation
.responseFields(
PayloadDocumentation
.fieldWithPath("parent")
.description("Information about the parent of this directory")
.attributes(EMPTY_CONSTRAINTS)
.type(JsonFieldType.OBJECT)
.optional(),
PayloadDocumentation
.fieldWithPath("parent.name")
.description("The name of the parent directory")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS)
.optional(),
PayloadDocumentation
.fieldWithPath("parent.url")
.description("The url to get the parent")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS)
.optional(),
PayloadDocumentation
.fieldWithPath("parent.size")
.description("The size of the parent in bytes")
.type(JsonFieldType.NUMBER)
.attributes(EMPTY_CONSTRAINTS)
.optional(),
PayloadDocumentation
.fieldWithPath("parent.lastModified")
.description("The last time the parent was modified in ISO8601 UTC with milliseconds included")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS)
.optional(),
PayloadDocumentation
.fieldWithPath("directories")
.description("All the subdirectories of this directory")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("directories[].name")
.description("The name of the directory")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("directories[].url")
.description("The url to get the directory")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("directories[].size")
.description("The size of the directory in bytes")
.type(JsonFieldType.NUMBER)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("directories[].lastModified")
.description("The last time the directory was modified in ISO8601 UTC with milliseconds included")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("files")
.description("All the files in this directory")
.type(JsonFieldType.ARRAY)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("files[].name")
.description("The name of the file")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("files[].url")
.description("The url to get the file")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("files[].size")
.description("The size of the file in bytes")
.type(JsonFieldType.NUMBER)
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("files[].lastModified")
.description("The last time the file was modified in ISO8601 UTC with milliseconds included")
.type(JsonFieldType.STRING)
.attributes(EMPTY_CONSTRAINTS)
);
static final RequestParametersSnippet APPLICATION_SEARCH_QUERY_PARAMETERS = RequestDocumentation.requestParameters(
ArrayUtils.addAll(
getCommonSearchParameters(),
RequestDocumentation
.parameterWithName("name")
.description("The name of the applications to find. Use % to perform a regex like query")
.optional(),
RequestDocumentation
.parameterWithName("user")
.description("The user of the applications to find. Use % to perform a regex like query")
.optional(),
RequestDocumentation
.parameterWithName("status")
.description(
"The status(es) of the applications to find. Can have multiple. Options: "
+ Arrays.toString(ApplicationStatus.values())
)
.optional(),
RequestDocumentation
.parameterWithName("tag")
.description("The tag(s) of the applications to find. Can have multiple.")
.optional(),
RequestDocumentation
.parameterWithName("type")
.description("The type of the applications to find. Use % to perform a regex like query")
.optional()
)
);
static final RequestParametersSnippet CLUSTER_SEARCH_QUERY_PARAMETERS = RequestDocumentation.requestParameters(
ArrayUtils.addAll(
getCommonSearchParameters(),
RequestDocumentation
.parameterWithName("name")
.description("The name of the clusters to find. Use % to perform a regex like query")
.optional(),
RequestDocumentation
.parameterWithName("status")
.description(
"The status(es) of the clusters to find. Can have multiple. Options: "
+ Arrays.toString(ClusterStatus.values())
)
.optional(),
RequestDocumentation
.parameterWithName("tag")
.description("The tag(s) of the clusters to find. Can have multiple.")
.optional(),
RequestDocumentation
.parameterWithName("minUpdateTime")
.description("The minimum time (in milliseconds from epoch UTC) that the cluster(s) were updated at.")
.optional(),
RequestDocumentation
.parameterWithName("maxUpdateTime")
.description("The maximum time (in milliseconds from epoch UTC) that the cluster(s) were updated at.")
.optional()
)
);
static final RequestParametersSnippet COMMAND_SEARCH_QUERY_PARAMETERS = RequestDocumentation.requestParameters(
ArrayUtils.addAll(
getCommonSearchParameters(),
RequestDocumentation
.parameterWithName("name")
.description("The name of the commands to find. Use % to perform a regex like query")
.optional(),
RequestDocumentation
.parameterWithName("user")
.description("The user of the commands to find. Use % to perform a regex like query")
.optional(),
RequestDocumentation
.parameterWithName("status")
.description(
"The status(es) of the commands to find. Can have multiple. Options: "
+ Arrays.toString(CommandStatus.values())
)
.optional(),
RequestDocumentation
.parameterWithName("tag")
.description("The tag(s) of the commands to find. Can have multiple.")
.optional()
)
);
static final RequestParametersSnippet JOB_SEARCH_QUERY_PARAMETERS = RequestDocumentation.requestParameters(
ArrayUtils.addAll(
getCommonSearchParameters(),
RequestDocumentation
.parameterWithName("id")
.description("The id of the jobs to find. Use % symbol for regex like search.")
.optional(),
RequestDocumentation
.parameterWithName("name")
.description("The name of the jobs to find. Use % symbol for regex like search.")
.optional(),
RequestDocumentation
.parameterWithName("user")
.description("The user of the jobs to find. Use % symbol for regex like search.")
.optional(),
RequestDocumentation
.parameterWithName("status")
.description(
"The status(es) of the jobs to find. Can have multiple. Options: "
+ Arrays.toString(JobStatus.values())
)
.optional(),
RequestDocumentation
.parameterWithName("tag")
.description("The tag(s) of the jobs to find. Can have multiple.")
.optional(),
RequestDocumentation
.parameterWithName("clusterName")
.description("The name of the cluster on which the jobs ran. Use % symbol for regex like search.")
.optional(),
RequestDocumentation
.parameterWithName("clusterId")
.description("The id of the cluster on which the jobs ran.")
.optional(),
RequestDocumentation
.parameterWithName("commandName")
.description(
"The name of the command which was executed by the job. Use % symbol for regex like search."
)
.optional(),
RequestDocumentation
.parameterWithName("commandId")
.description("The id of the command which was executed by the job.")
.optional(),
RequestDocumentation
.parameterWithName("minStarted")
.description("The minimum started time of the job in milliseconds since epoch. (inclusive)")
.optional(),
RequestDocumentation
.parameterWithName("maxStarted")
.description("The maximum started time of the job in milliseconds since epoch. (exclusive)")
.optional(),
RequestDocumentation
.parameterWithName("minFinished")
.description("The minimum finished time of the job in milliseconds since epoch. (inclusive)")
.optional(),
RequestDocumentation
.parameterWithName("maxFinished")
.description("The maximum finished time of the job in milliseconds since epoch. (exclusive)")
.optional(),
RequestDocumentation
.parameterWithName("grouping")
.description("The grouping the job should be a member of. Use % symbol for regex like search.")
.optional(),
RequestDocumentation
.parameterWithName("groupingInstance")
.description("The grouping instance the job should be a member of. Use % symbol for regex like search.")
.optional()
)
);
private static final ConstraintDescriptions COMMAND_CONSTRAINTS = new ConstraintDescriptions(Command.class);
private static final ConstraintDescriptions JOB_REQUEST_CONSTRAINTS = new ConstraintDescriptions(JobRequest.class);
private static final ConstraintDescriptions JOB_CONSTRAINTS = new ConstraintDescriptions(Job.class);
private static final ConstraintDescriptions JOB_EXECUTION_CONSTRAINTS
= new ConstraintDescriptions(JobExecution.class);
private static final ConstraintDescriptions JOB_METADATA_CONSTRAINTS
= new ConstraintDescriptions(JobMetadata.class);
private static final ConstraintDescriptions APPLICATION_CONSTRAINTS = new ConstraintDescriptions(Application.class);
private static final ConstraintDescriptions CLUSTER_CONSTRAINTS = new ConstraintDescriptions(Cluster.class);
private static final ConstraintDescriptions CRITERION_CONSTRAINTS = new ConstraintDescriptions(Criterion.class);
private static final ConstraintDescriptions RUNTIME_CONSTRAINTS = new ConstraintDescriptions(Runtime.class);
private static final ConstraintDescriptions RUNTIME_RESOURCES_CONSTRAINTS
= new ConstraintDescriptions(RuntimeResources.class);
private static final ConstraintDescriptions CONTAINER_IMAGE_CONSTRAINTS
= new ConstraintDescriptions(ContainerImage.class);
private Snippets() {
}
static RequestFieldsSnippet getApplicationRequestPayload() {
return PayloadDocumentation.requestFields(getApplicationFieldDescriptors());
}
static ResponseFieldsSnippet getApplicationResponsePayload() {
return PayloadDocumentation.responseFields(getApplicationFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static RequestFieldsSnippet getClusterRequestPayload() {
return PayloadDocumentation.requestFields(getClusterFieldDescriptors());
}
static ResponseFieldsSnippet getClusterResponsePayload() {
return PayloadDocumentation.responseFields(getClusterFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static RequestFieldsSnippet getCommandRequestPayload() {
return PayloadDocumentation.requestFields(getCommandFieldDescriptors());
}
static ResponseFieldsSnippet getCommandResponsePayload() {
return PayloadDocumentation.responseFields(getCommandFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static RequestFieldsSnippet getJobRequestRequestPayload() {
return PayloadDocumentation.requestFields(getJobRequestFieldDescriptors());
}
static ResponseFieldsSnippet getJobRequestResponsePayload() {
return PayloadDocumentation.responseFields(getJobRequestFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static ResponseFieldsSnippet getJobResponsePayload() {
return PayloadDocumentation.responseFields(getJobFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static ResponseFieldsSnippet getJobExecutionResponsePayload() {
return PayloadDocumentation.responseFields(getJobExecutionFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static ResponseFieldsSnippet getJobMetadataResponsePayload() {
return PayloadDocumentation.responseFields(getJobMetadataFieldDescriptors())
.and(
PayloadDocumentation
.subsectionWithPath("_links")
.attributes(
Attributes
.key(CONSTRAINTS)
.value("")
)
.description("<<_hateoas,Links>> to other resources.")
.ignored()
);
}
static RequestFieldsSnippet addClusterCriterionForCommandRequestPayload() {
return PayloadDocumentation.requestFields(getCriterionFieldDescriptors());
}
static RequestFieldsSnippet setClusterCriteriaForCommandRequestPayload() {
return PayloadDocumentation
.requestFields(
PayloadDocumentation
.fieldWithPath("[]")
.attributes(EMPTY_CONSTRAINTS)
.description("A priority ordered list of criteria")
.type(JsonFieldType.ARRAY)
.optional()
)
.andWithPrefix("[].", getCriterionFieldDescriptors());
}
static ResponseFieldsSnippet getClusterCriteriaForCommandResponsePayload() {
return PayloadDocumentation
.responseFields(
PayloadDocumentation
.fieldWithPath("[]")
.attributes(EMPTY_CONSTRAINTS)
.description("A priority ordered list of criteria")
.type(JsonFieldType.ARRAY)
.optional()
)
.andWithPrefix("[].", getCriterionFieldDescriptors());
}
static ResponseFieldsSnippet resolveClustersForCommandClusterCriteriaResponsePayload() {
return PayloadDocumentation
.responseFields(
PayloadDocumentation
.fieldWithPath("[]")
.attributes(EMPTY_CONSTRAINTS)
.description("The list of criterion and associated resolved clusters")
.type(JsonFieldType.ARRAY)
.optional()
)
.andWithPrefix(
"[].",
PayloadDocumentation
.fieldWithPath("criterion")
.attributes(EMPTY_CONSTRAINTS)
.description("The criterion that was evaluated to yield the resources")
.type(JsonFieldType.OBJECT),
PayloadDocumentation
.fieldWithPath("resources")
.attributes(EMPTY_CONSTRAINTS)
.description("The resources that were resolved by evaluating the criterion")
.type(JsonFieldType.ARRAY)
)
.andWithPrefix("[].criterion.", getCriterionFieldDescriptors())
.andWithPrefix("[].resources[].", getClusterFieldDescriptors());
}
private static FieldDescriptor[] getApplicationFieldDescriptors() {
return ArrayUtils.addAll(
getConfigFieldDescriptors(APPLICATION_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("type")
.attributes(getConstraintsForField(APPLICATION_CONSTRAINTS, "type"))
.description("The type of application this is (e.g. hadoop, presto, spark). Can be used to group.")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("status")
.attributes(getConstraintsForField(APPLICATION_CONSTRAINTS, "status"))
.description(
"The status of the application. Options: " + Arrays.toString(ApplicationStatus.values())
)
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("dependencies")
.attributes(getConstraintsForField(APPLICATION_CONSTRAINTS, "dependencies"))
.description("The dependencies for the application")
.type(JsonFieldType.ARRAY)
.optional()
);
}
private static FieldDescriptor[] getClusterFieldDescriptors() {
return ArrayUtils.addAll(
getConfigFieldDescriptors(CLUSTER_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("status")
.attributes(getConstraintsForField(CLUSTER_CONSTRAINTS, "status"))
.description(
"The status of the cluster. Options: " + Arrays.toString(ClusterStatus.values())
)
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("dependencies")
.attributes(getConstraintsForField(CLUSTER_CONSTRAINTS, "dependencies"))
.description("The dependencies for the cluster")
.type(JsonFieldType.ARRAY)
.optional()
);
}
private static FieldDescriptor[] getCommandFieldDescriptors() {
return ArrayUtils.addAll(
getConfigFieldDescriptors(COMMAND_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("status")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "status"))
.description(
"The status of the command. Options: " + Arrays.toString(CommandStatus.values())
)
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("executable")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "executable"))
.description("The executable to run on the Genie node when this command is used. e.g. /usr/bin/hadoop")
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("executableAndArguments")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "executableAndArguments"))
.description(
"The executable and arguments to run on the Genie node when this command is used."
+ " e.g. /usr/bin/hadoop"
)
.type(JsonFieldType.ARRAY),
PayloadDocumentation
.fieldWithPath("checkDelay")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "checkDelay"))
.description("Deprecated as of 4.3.0. Now is a no-op on the server side.")
.type(JsonFieldType.NUMBER),
PayloadDocumentation
.fieldWithPath("memory")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "memory"))
.description(
"The default amount of memory (in MB) that should be allocated for instances of this command client"
)
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("dependencies")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "dependencies"))
.description("The dependencies for the command")
.type(JsonFieldType.ARRAY)
.optional(),
PayloadDocumentation
.subsectionWithPath("clusterCriteria")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "clusterCriteria"))
.description(
"The priority ordered list of criteria to resolve clusters that this command can run jobs on"
)
.type(JsonFieldType.ARRAY)
.optional(),
PayloadDocumentation
.subsectionWithPath("runtime")
.attributes(getConstraintsForField(COMMAND_CONSTRAINTS, "runtime"))
.description("The various job runtime parameters that should be used if this command is used")
.type(JsonFieldType.OBJECT)
);
}
private static FieldDescriptor[] getJobRequestFieldDescriptors() {
return ArrayUtils.addAll(
getSetupFieldDescriptors(JOB_REQUEST_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("commandArgs")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "commandArgs"))
.description("Any arguments to append to the command executable when the job is run")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.subsectionWithPath("clusterCriterias")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "clusterCriterias"))
.description(
"List of cluster criteria's for which a match will be attempted with register cluster tags."
+ " Each set of tags within a given cluster criteria must have at least one non-blank "
+ "(e.g. ' ', ' ', null) tag."
)
.type(JsonFieldType.ARRAY),
PayloadDocumentation
.fieldWithPath("commandCriteria")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "commandCriteria"))
.description(
"Set of tags which will attempt to match against the commands linked to selected cluster."
+ " There must be at least one non-blank (e.g. ' ', ' ', null) criteria within the set"
)
.type(JsonFieldType.ARRAY),
PayloadDocumentation
.fieldWithPath("group")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "group"))
.description("A group that the job should be run under on the linux system")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("disableLogArchival")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "disableLogArchival"))
.description("If you want to disable backing up job output files set this to true. Default: false")
.type(JsonFieldType.BOOLEAN)
.optional(),
PayloadDocumentation
.fieldWithPath("email")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "email"))
.description("If you want e-mail notification on job completion enter address here")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("cpu")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "cpu"))
.description("For future use. Currently has no impact.")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("memory")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "memory"))
.description("The amount of memory (in MB) desired for job client. Cannot exceed configured max.")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("timeout")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "timeout"))
.description(
"The timeout (in seconds) after which job will be killed by system, system setting used if not set"
)
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("configs")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "configs"))
.description(
"URI's of configuration files which will be downloaded into job working directory at runtime"
)
.type(JsonFieldType.ARRAY)
.optional(),
PayloadDocumentation
.fieldWithPath("dependencies")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "dependencies"))
.description("URI's of dependency files which will be downloaded into job working directory at runtime")
.type(JsonFieldType.ARRAY)
.optional(),
PayloadDocumentation
.fieldWithPath("applications")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "applications"))
.description(
"Complete list of application ids if power user wishes to override selected command defaults"
)
.type(JsonFieldType.ARRAY)
.optional(),
PayloadDocumentation
.fieldWithPath("grouping")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "grouping"))
.description("The grouping of the job relative to other jobs. e.g. scheduler job name")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("groupingInstance")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "groupingInstance"))
.description("The grouping instance of the job relative to other jobs. e.g. scheduler job run")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.subsectionWithPath("runtime")
.attributes(getConstraintsForField(JOB_REQUEST_CONSTRAINTS, "runtime"))
.description("The requested job runtime values")
.type(JsonFieldType.OBJECT)
);
}
private static FieldDescriptor[] getJobFieldDescriptors() {
return ArrayUtils.addAll(
getCommonFieldDescriptors(JOB_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("commandArgs")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "commandArgs"))
.description("Any arguments to append to the command executable when the job is run")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("status")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "status"))
.description("The status of the job. Options: " + Arrays.toString(JobStatus.values()))
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("statusMsg")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "statusMsg"))
.description("The status message of the job")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("started")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "started"))
.description("The time (UTC ISO8601 with millis) the job was started")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("finished")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "finished"))
.description("The time (UTC ISO8601 with millis) the job finished")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("archiveLocation")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "archiveLocation"))
.description("The URI where the working directory zip was stored")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("clusterName")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "clusterName"))
.description("The name of the cluster the job was run on if it's been determined")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("commandName")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "commandName"))
.description("The name of the command the job was run with if it's been determined")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("runtime")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "runtime"))
.description("Runtime of the job in ISO8601 duration format")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("grouping")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "grouping"))
.description("The grouping of the job relative to other jobs. e.g. scheduler job name")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("groupingInstance")
.attributes(getConstraintsForField(JOB_CONSTRAINTS, "groupingInstance"))
.description("The grouping instance of the job relative to other jobs. e.g. scheduler job run")
.type(JsonFieldType.STRING)
.optional()
);
}
private static FieldDescriptor[] getJobExecutionFieldDescriptors() {
return ArrayUtils.addAll(
getBaseFieldDescriptors(JOB_EXECUTION_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("hostName")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "hostName"))
.description("The host name of the Genie node responsible for the job")
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("processId")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "processId"))
.description("The id of the job client process on the Genie node")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("checkDelay")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "checkDelay"))
.description("The amount of time in milliseconds between checks of the job status by Genie")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("timeout")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "timeout"))
.description("The date (UTC ISO8601 with millis) when the job will be killed by Genie due to timeout")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("exitCode")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "exitCode"))
.description("The job client process exit code after the job is done")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("memory")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "memory"))
.description("The amount of memory (in MB) allocated to the job client")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("archiveStatus")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "archiveStatus"))
.description("The archival status of the job directory")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.subsectionWithPath("launcherExt")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "launcherExt"))
.description("JSON object that contains metadata specific to the launcher implementation for the job")
.type(JsonFieldType.OBJECT)
.optional(),
PayloadDocumentation
.subsectionWithPath("runtime")
.attributes(getConstraintsForField(JOB_EXECUTION_CONSTRAINTS, "runtime"))
.description("The runtime execution environment for a job")
.type(JsonFieldType.OBJECT)
);
}
private static FieldDescriptor[] getJobMetadataFieldDescriptors() {
return ArrayUtils.addAll(
getBaseFieldDescriptors(JOB_METADATA_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("clientHost")
.attributes(getConstraintsForField(JOB_METADATA_CONSTRAINTS, "clientHost"))
.description("The host name of the client that submitted the job to Genie")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("userAgent")
.attributes(getConstraintsForField(JOB_METADATA_CONSTRAINTS, "userAgent"))
.description("The user agent string that was passed to Genie on job request")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("numAttachments")
.attributes(getConstraintsForField(JOB_METADATA_CONSTRAINTS, "numAttachments"))
.description("The number of attachments sent to Genie with the job request")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("totalSizeOfAttachments")
.attributes(getConstraintsForField(JOB_METADATA_CONSTRAINTS, "totalSizeOfAttachments"))
.description("The total size of all attachments sent to Genie with the job request. In bytes.")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("stdOutSize")
.attributes(getConstraintsForField(JOB_METADATA_CONSTRAINTS, "stdOutSize"))
.description("The final size of the stdout file after a job is completed. In bytes.")
.type(JsonFieldType.NUMBER)
.optional(),
PayloadDocumentation
.fieldWithPath("stdErrSize")
.attributes(getConstraintsForField(JOB_METADATA_CONSTRAINTS, "stdErrSize"))
.description("The final size of the stderr file after a job is completed. In bytes.")
.type(JsonFieldType.NUMBER)
.optional()
);
}
private static FieldDescriptor[] getConfigFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
return ArrayUtils.addAll(
getSetupFieldDescriptors(constraintDescriptions),
PayloadDocumentation
.fieldWithPath("configs")
.attributes(getConstraintsForField(constraintDescriptions, "configs"))
.description("Any configuration files needed for the resource")
.type(JsonFieldType.ARRAY)
.optional()
);
}
private static FieldDescriptor[] getSetupFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
return ArrayUtils.addAll(
getCommonFieldDescriptors(constraintDescriptions),
PayloadDocumentation
.fieldWithPath("setupFile")
.attributes(getConstraintsForField(constraintDescriptions, "setupFile"))
.description("A location for any setup that needs to be done when installing")
.type(JsonFieldType.STRING)
.optional()
);
}
private static FieldDescriptor[] getCommonFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
return ArrayUtils.addAll(
getBaseFieldDescriptors(constraintDescriptions),
PayloadDocumentation
.fieldWithPath("name")
.attributes(getConstraintsForField(constraintDescriptions, "name"))
.description("The name")
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("user")
.attributes(getConstraintsForField(constraintDescriptions, "user"))
.description("The user")
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("version")
.attributes(getConstraintsForField(constraintDescriptions, "version"))
.description("The version")
.type(JsonFieldType.STRING),
PayloadDocumentation
.fieldWithPath("description")
.attributes(getConstraintsForField(constraintDescriptions, "description"))
.description("Any description")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.subsectionWithPath("metadata")
.attributes(getConstraintsForField(constraintDescriptions, "metadata"))
.description("Any semi-structured metadata. Must be valid JSON")
.type(JsonFieldType.OBJECT)
.optional(),
PayloadDocumentation
.fieldWithPath("tags")
.attributes(getConstraintsForField(constraintDescriptions, "tags"))
.description("The tags")
.type(JsonFieldType.ARRAY)
.optional()
);
}
private static FieldDescriptor[] getBaseFieldDescriptors(final ConstraintDescriptions constraintDescriptions) {
return new FieldDescriptor[]{
PayloadDocumentation
.fieldWithPath("id")
.attributes(getConstraintsForField(constraintDescriptions, "id"))
.description("The id. If not set the system will set one.")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("created")
.attributes(getConstraintsForField(constraintDescriptions, "created"))
.description("The UTC time of creation. Set by system. ISO8601 format including milliseconds.")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("updated")
.attributes(getConstraintsForField(constraintDescriptions, "updated"))
.description("The UTC time of last update. Set by system. ISO8601 format including milliseconds.")
.type(JsonFieldType.STRING)
.optional(),
};
}
private static FieldDescriptor[] getSearchResultFields() {
return new FieldDescriptor[]{
PayloadDocumentation
.subsectionWithPath("_links")
.description("<<_hateoas,Links>> to other resources.")
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("page")
.description("The result page information.")
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("page.size")
.description("The number of elements in this page result.")
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("page.totalElements")
.description("The total number of elements this search result could return.")
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("page.totalPages")
.description("The total number of pages there could be at the current page size.")
.attributes(EMPTY_CONSTRAINTS),
PayloadDocumentation
.fieldWithPath("page.number")
.description("The current page number.")
.attributes(EMPTY_CONSTRAINTS),
};
}
private static ParameterDescriptor[] getCommonSearchParameters() {
return new ParameterDescriptor[]{
RequestDocumentation
.parameterWithName("page")
.description("The page number to get. Default to 0.")
.optional(),
RequestDocumentation
.parameterWithName("size")
.description("The size of the page to get. Default to 64.")
.optional(),
RequestDocumentation
.parameterWithName("sort")
.description("The fields to sort the results by. Defaults to 'updated,desc'.")
.optional(),
};
}
private static Attributes.Attribute getConstraintsForField(
final ConstraintDescriptions constraints,
final String fieldName
) {
return Attributes
.key(CONSTRAINTS)
.value(StringUtils.collectionToDelimitedString(constraints.descriptionsForProperty(fieldName), ". "));
}
private static FieldDescriptor[] getCriterionFieldDescriptors() {
return new FieldDescriptor[]{
PayloadDocumentation
.fieldWithPath("id")
.attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "id"))
.description("The unique identifier a resource needs to have to match this criterion")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("name")
.attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "name"))
.description("The name a resource needs to have to match this criterion")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("version")
.attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "version"))
.description("The version a resource needs to have to match this criterion")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("status")
.attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "status"))
.description("The status a resource needs to have to match this criterion")
.type(JsonFieldType.STRING)
.optional(),
PayloadDocumentation
.fieldWithPath("tags")
.attributes(getConstraintsForField(CRITERION_CONSTRAINTS, "tags"))
.description("The set of tags a resource needs to have to match this criterion")
.type(JsonFieldType.ARRAY)
.optional(),
};
}
private static FieldDescriptor[] getRuntimeFieldDescriptors() {
return new FieldDescriptor[]{
PayloadDocumentation
.fieldWithPath("resources")
.attributes(getConstraintsForField(RUNTIME_CONSTRAINTS, "resources"))
.description("The runtime resources (cpu, gpu, memory, disk, network) that should be allocated")
.type(JsonFieldType.OBJECT),
PayloadDocumentation
.fieldWithPath("images")
.attributes(getConstraintsForField(RUNTIME_CONSTRAINTS, "images"))
.description("The map of system wide key to container image definition")
.type(JsonFieldType.OBJECT),
};
}
}
| 2,354 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/ApplicationRestControllerIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.apis.rest.v3.controllers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.fge.jsonpatch.JsonPatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import io.restassured.RestAssured;
import org.assertj.core.api.Assertions;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.restdocs.payload.PayloadDocumentation;
import org.springframework.restdocs.request.RequestDocumentation;
import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation;
import org.springframework.restdocs.restassured3.RestDocumentationFilter;
import org.springframework.restdocs.snippet.Attributes;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Integration tests for the Applications REST API.
*
* @author tgianos
* @since 3.0.0
*/
class ApplicationRestControllerIntegrationTest extends RestControllerIntegrationTestBase {
// Use a `.` to ensure that the Spring prefix matcher is turned off
// see: https://tinyurl.com/yblzglk8
private static final String ID = UUID.randomUUID().toString() + "." + UUID.randomUUID().toString();
private static final String NAME = "spark";
private static final String USER = "genie";
private static final String VERSION = "1.5.1";
private static final String TYPE = "spark";
private static final String TYPE_PATH = "type";
private static final String APPLICATIONS_LIST_PATH = EMBEDDED_PATH + ".applicationList";
private static final String APPLICATIONS_ID_LIST_PATH = APPLICATIONS_LIST_PATH + ".id";
private static final String APPLICATION_COMMANDS_LINK_PATH = "_links.commands.href";
private static final String APPLICATIONS_COMMANDS_LINK_PATH = APPLICATIONS_LIST_PATH + "._links.commands.href";
private static final List<String> EXECUTABLE_AND_ARGS = Lists.newArrayList("bash");
@BeforeEach
void beforeApplications() {
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(0L);
}
@Test
void canCreateApplicationWithoutId() throws Exception {
final RestDocumentationFilter creationResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request headers
Snippets.getApplicationRequestPayload(), // Request fields
Snippets.LOCATION_HEADER // Response headers
);
final String id = this.createConfigResource(
new Application
.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE)
.withType(TYPE)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/" + VERSION + "/spark.tar.gz"))
.withSetupFile("s3://mybucket/spark/" + VERSION + "/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/" + VERSION + "/spark-env.sh"))
.withDescription("Spark for Genie")
.withTags(Sets.newHashSet("type:" + TYPE, "ver:" + VERSION))
.build(),
creationResultFilter
);
final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // response headers
Snippets.getApplicationResponsePayload(), // response payload
Snippets.APPLICATION_LINKS // response links
);
RestAssured
.given(this.getRequestSpecification())
.filter(getResultFilter)
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(UPDATED_PATH, Matchers.notNullValue())
.body(CREATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(NAME))
.body(VERSION_PATH, Matchers.is(VERSION))
.body(USER_PATH, Matchers.is(USER))
.body(DESCRIPTION_PATH, Matchers.is("Spark for Genie"))
.body(SETUP_FILE_PATH, Matchers.is("s3://mybucket/spark/" + VERSION + "/setupBase-spark.sh"))
.body(CONFIGS_PATH, Matchers.hasItem("s3://mybucket/spark/" + VERSION + "/spark-env.sh"))
.body(TAGS_PATH, Matchers.hasSize(4))
.body(TAGS_PATH, Matchers.hasItem("genie.id:" + id))
.body(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME))
.body(TAGS_PATH, Matchers.hasItem("ver:" + VERSION))
.body(TAGS_PATH, Matchers.hasItem("type:" + TYPE))
.body(STATUS_PATH, Matchers.is(ApplicationStatus.ACTIVE.toString()))
.body(DEPENDENCIES_PATH, Matchers.hasItem("s3://mybucket/spark/" + VERSION + "/spark.tar.gz"))
.body(TYPE_PATH, Matchers.is(TYPE))
.body(LINKS_PATH + ".keySet().size()", Matchers.is(2))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY))
.body(APPLICATION_COMMANDS_LINK_PATH, EntityLinkMatcher
.matchUri(
APPLICATIONS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS,
id
)
);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(1L);
}
@Test
void canCreateApplicationWithId() throws Exception {
this.createConfigResource(
new Application
.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE)
.withId(ID)
.withType(TYPE)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/" + VERSION + "/spark.tar.gz"))
.withSetupFile("s3://mybucket/spark/" + VERSION + "/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/" + VERSION + "/spark-env.sh"))
.withDescription("Spark for Genie")
.withTags(Sets.newHashSet("type:" + TYPE, "ver:" + VERSION))
.build(),
null
);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}", ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(ID))
.body(UPDATED_PATH, Matchers.notNullValue())
.body(CREATED_PATH, Matchers.notNullValue())
.body(NAME_PATH, Matchers.is(NAME))
.body(VERSION_PATH, Matchers.is(VERSION))
.body(USER_PATH, Matchers.is(USER))
.body(DESCRIPTION_PATH, Matchers.is("Spark for Genie"))
.body(SETUP_FILE_PATH, Matchers.is("s3://mybucket/spark/" + VERSION + "/setupBase-spark.sh"))
.body(CONFIGS_PATH, Matchers.hasItem("s3://mybucket/spark/" + VERSION + "/spark-env.sh"))
.body(TAGS_PATH, Matchers.hasSize(4))
.body(TAGS_PATH, Matchers.hasItem("genie.id:" + ID))
.body(TAGS_PATH, Matchers.hasItem("genie.name:" + NAME))
.body(TAGS_PATH, Matchers.hasItem("ver:" + VERSION))
.body(TAGS_PATH, Matchers.hasItem("type:" + TYPE))
.body(STATUS_PATH, Matchers.is(ApplicationStatus.ACTIVE.toString()))
.body(DEPENDENCIES_PATH, Matchers.hasItem("s3://mybucket/spark/" + VERSION + "/spark.tar.gz"))
.body(TYPE_PATH, Matchers.is(TYPE))
.body(LINKS_PATH + ".keySet().size()", Matchers.is(2))
.body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY))
.body(LINKS_PATH, Matchers.hasKey(COMMANDS_LINK_KEY))
.body(
APPLICATION_COMMANDS_LINK_PATH,
EntityLinkMatcher.matchUri(
APPLICATIONS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS,
ID
)
);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(1L);
}
@Test
void canHandleBadInputToCreateApplication() throws Exception {
final Application app = new Application.Builder(" ", " ", " ", ApplicationStatus.ACTIVE).build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(app))
.when()
.port(this.port)
.post(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("A version is required and must be at most 255 characters")
);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(0L);
}
@Test
void canFindApplications() throws Exception {
final Application spark151 = new Application.Builder("spark", "genieUser1", "1.5.1", ApplicationStatus.ACTIVE)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/spark-1.5.1.tar.gz"))
.withSetupFile("s3://mybucket/spark/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/spark-env.sh"))
.withDescription("Spark 1.5.1 for Genie")
.withTags(Sets.newHashSet("type:spark", "ver:1.5.1"))
.withType("spark")
.build();
final Application spark150 = new Application.Builder("spark", "genieUser2", "1.5.0", ApplicationStatus.ACTIVE)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/spark-1.5.0.tar.gz"))
.withSetupFile("s3://mybucket/spark/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/spark-env.sh"))
.withDescription("Spark 1.5.0 for Genie")
.withTags(Sets.newHashSet("type:spark", "ver:1.5.0"))
.withType("spark")
.build();
final Application spark141 = new Application.Builder("spark", "genieUser3", "1.4.1", ApplicationStatus.INACTIVE)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/spark-1.4.1.tar.gz"))
.withSetupFile("s3://mybucket/spark/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/spark-env.sh"))
.withDescription("Spark 1.4.1 for Genie")
.withTags(Sets.newHashSet("type:spark", "ver:1.4.1"))
.withType("spark")
.build();
final Application spark140
= new Application.Builder("spark", "genieUser4", "1.4.0", ApplicationStatus.DEPRECATED)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/spark-1.4.0.tar.gz"))
.withSetupFile("s3://mybucket/spark/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/spark-env.sh"))
.withDescription("Spark 1.4.0 for Genie")
.withTags(Sets.newHashSet("type:spark", "ver:1.4.0"))
.withType("spark")
.build();
final Application spark131
= new Application.Builder("spark", "genieUser5", "1.3.1", ApplicationStatus.DEPRECATED)
.withDependencies(Sets.newHashSet("s3://mybucket/spark/spark-1.3.1.tar.gz"))
.withSetupFile("s3://mybucket/spark/setupBase-spark.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/spark/spark-env.sh"))
.withDescription("Spark 1.3.1 for Genie")
.withTags(Sets.newHashSet("type:spark", "ver:1.3.1"))
.withType("spark")
.build();
final Application pig = new Application.Builder("spark", "genieUser6", "0.4.0", ApplicationStatus.ACTIVE)
.withDependencies(Sets.newHashSet("s3://mybucket/pig/pig-0.15.0.tar.gz"))
.withSetupFile("s3://mybucket/pig/setupBase-pig.sh")
.withConfigs(Sets.newHashSet("s3://mybucket/pig/pig.properties"))
.withDescription("Pig 0.15.0 for Genie")
.withTags(Sets.newHashSet("type:pig", "ver:0.15.0"))
.withType("pig")
.build();
final Application hive = new Application.Builder("hive", "genieUser7", "1.0.0", ApplicationStatus.ACTIVE)
.withDependencies(Sets.newHashSet("s3://mybucket/hive/hive-1.0.0.tar.gz"))
.withSetupFile("s3://mybucket/hive/setupBase-hive.sh")
.withConfigs(
Sets.newHashSet("s3://mybucket/hive/hive-env.sh", "s3://mybucket/hive/hive-log4j.properties")
)
.withDescription("Hive 1.0.0 for Genie")
.withTags(Sets.newHashSet("type:hive", "ver:1.0.0"))
.withType("hive")
.build();
final String spark151Id = this.createConfigResource(spark151, null);
final String spark150Id = this.createConfigResource(spark150, null);
final String spark141Id = this.createConfigResource(spark141, null);
final String spark140Id = this.createConfigResource(spark140, null);
final String spark131Id = this.createConfigResource(spark131, null);
final String pigId = this.createConfigResource(pig, null);
final String hiveId = this.createConfigResource(hive, null);
final List<String> appIds = Lists.newArrayList(
spark151Id, spark150Id, spark141Id, spark140Id, spark131Id, pigId, hiveId);
final RestDocumentationFilter findFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.APPLICATION_SEARCH_QUERY_PARAMETERS, // Request query parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response headers
Snippets.APPLICATION_SEARCH_RESULT_FIELDS, // Result fields
Snippets.SEARCH_LINKS // HAL Links
);
// Test finding all applications
RestAssured
.given(this.getRequestSpecification()).filter(findFilter)
.when()
.port(this.port).get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(7))
.body(APPLICATIONS_ID_LIST_PATH, Matchers.hasSize(7))
.body(
APPLICATIONS_ID_LIST_PATH,
Matchers.containsInAnyOrder(spark151Id, spark150Id, spark141Id, spark140Id, spark131Id, pigId, hiveId)
)
.body(
APPLICATIONS_COMMANDS_LINK_PATH,
EntitiesLinksMatcher.matchUrisAnyOrder(
APPLICATIONS_API, COMMANDS_LINK_KEY, COMMANDS_OPTIONAL_HAL_LINK_PARAMETERS, appIds
)
);
// Limit the size
RestAssured
.given(this.getRequestSpecification()).filter(findFilter).param("size", 2)
.when()
.port(this.port)
.get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(2));
// Query by name
RestAssured
.given(this.getRequestSpecification()).filter(findFilter).param("name", "hive")
.when()
.port(this.port)
.get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(1))
.body(APPLICATIONS_LIST_PATH + "[0].id", Matchers.is(hiveId));
// Query by user
RestAssured
.given(this.getRequestSpecification()).filter(findFilter).param("user", "genieUser3")
.when()
.port(this.port)
.get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(1))
.body(APPLICATIONS_LIST_PATH + "[0].id", Matchers.is(spark141Id));
// Query by statuses
RestAssured
.given(this.getRequestSpecification()).filter(findFilter)
.param("status", ApplicationStatus.ACTIVE.toString(), ApplicationStatus.DEPRECATED.toString())
.when()
.port(this.port)
.get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(6))
.body(APPLICATIONS_LIST_PATH + "[0].id", Matchers.is(hiveId))
.body(APPLICATIONS_LIST_PATH + "[1].id", Matchers.is(pigId))
.body(APPLICATIONS_LIST_PATH + "[2].id", Matchers.is(spark131Id))
.body(APPLICATIONS_LIST_PATH + "[3].id", Matchers.is(spark140Id))
.body(APPLICATIONS_LIST_PATH + "[4].id", Matchers.is(spark150Id))
.body(APPLICATIONS_LIST_PATH + "[5].id", Matchers.is(spark151Id));
// Query by tags
RestAssured
.given(this.getRequestSpecification()).filter(findFilter).param("tag", "genie.id:" + spark131Id)
.when()
.port(this.port)
.get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(1))
.body(APPLICATIONS_LIST_PATH + "[0].id", Matchers.is(spark131Id));
// Query by type
RestAssured
.given(this.getRequestSpecification()).filter(findFilter).param("type", "spark")
.when()
.port(this.port)
.get(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(APPLICATIONS_LIST_PATH, Matchers.hasSize(5))
.body(APPLICATIONS_LIST_PATH + "[0].id", Matchers.is(spark131Id))
.body(APPLICATIONS_LIST_PATH + "[1].id", Matchers.is(spark140Id))
.body(APPLICATIONS_LIST_PATH + "[2].id", Matchers.is(spark141Id))
.body(APPLICATIONS_LIST_PATH + "[3].id", Matchers.is(spark150Id))
.body(APPLICATIONS_LIST_PATH + "[4].id", Matchers.is(spark151Id));
//TODO: Add tests for sort, orderBy etc
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(7L);
}
@Test
void canUpdateApplication() throws Exception {
final String id = this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String applicationResource = APPLICATIONS_API + "/{id}";
final Application createdApp = GenieObjectMapper.getMapper()
.readValue(
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(applicationResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.extract()
.asByteArray(),
new TypeReference<EntityModel<Application>>() {
}
).getContent();
Assertions.assertThat(createdApp).isNotNull();
Assertions.assertThat(createdApp.getStatus()).isEqualByComparingTo(ApplicationStatus.ACTIVE);
final Application.Builder newStatusApp = new Application.Builder(
createdApp.getName(),
createdApp.getUser(),
createdApp.getVersion(),
ApplicationStatus.INACTIVE
)
.withId(createdApp.getId().orElseThrow(IllegalArgumentException::new))
.withCreated(createdApp.getCreated().orElseThrow(IllegalArgumentException::new))
.withUpdated(createdApp.getUpdated().orElseThrow(IllegalArgumentException::new))
.withTags(createdApp.getTags())
.withConfigs(createdApp.getConfigs())
.withDependencies(createdApp.getDependencies());
createdApp.getDescription().ifPresent(newStatusApp::withDescription);
createdApp.getSetupFile().ifPresent(newStatusApp::withSetupFile);
final RestDocumentationFilter updateResultFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request header
Snippets.ID_PATH_PARAM, // path parameters
Snippets.getApplicationRequestPayload() // payload fields
);
RestAssured
.given(this.getRequestSpecification())
.filter(updateResultFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(newStatusApp.build()))
.when()
.port(this.port)
.put(applicationResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(applicationResource, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(STATUS_PATH, Matchers.is(ApplicationStatus.INACTIVE.toString()));
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(1L);
}
@Test
void canPatchApplication() throws Exception {
final String id = this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String applicationResource = APPLICATIONS_API + "/{id}";
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(applicationResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(USER_PATH, Matchers.is(USER));
final String newUser = UUID.randomUUID().toString();
final String patchString = "[{ \"op\": \"replace\", \"path\": \"/user\", \"value\": \"" + newUser + "\" }]";
final JsonPatch patch = JsonPatch.fromJson(GenieObjectMapper.getMapper().readTree(patchString));
final RestDocumentationFilter patchFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request headers
Snippets.ID_PATH_PARAM, // path params
Snippets.PATCH_FIELDS // request payload
);
RestAssured
.given(this.getRequestSpecification())
.filter(patchFilter)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(patch))
.when()
.port(this.port)
.patch(applicationResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(applicationResource, id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(USER_PATH, Matchers.is(newUser));
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(1L);
}
@Test
void canDeleteAllApplications() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).build(),
null
);
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.DEPRECATED).build(),
null
);
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.INACTIVE).build(),
null
);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(3L);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/"
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(0L);
}
@Test
void canDeleteAnApplication() throws Exception {
final String id1 = UUID.randomUUID().toString();
final String id2 = UUID.randomUUID().toString();
final String id3 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString();
final String name3 = UUID.randomUUID().toString();
final String user1 = UUID.randomUUID().toString();
final String user2 = UUID.randomUUID().toString();
final String user3 = UUID.randomUUID().toString();
final String version1 = UUID.randomUUID().toString();
final String version2 = UUID.randomUUID().toString();
final String version3 = UUID.randomUUID().toString();
this.createConfigResource(
new Application
.Builder(name1, user1, version1, ApplicationStatus.ACTIVE)
.withId(id1)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(name2, user2, version2, ApplicationStatus.DEPRECATED)
.withId(id2)
.build(),
null
);
this.createConfigResource(
new Application
.Builder(name3, user3, version3, ApplicationStatus.INACTIVE)
.withId(id3)
.build(),
null
);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(3L);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // path parameters
);
RestAssured
.given(this.getRequestSpecification())
.filter(deleteFilter)
.when()
.port(this.port)
.delete(APPLICATIONS_API + "/{id}", id2)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}", id2)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body(
EXCEPTION_MESSAGE_PATH,
Matchers.containsString("No application with id")
);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(2L);
}
@Test
void canAddConfigsToApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // request headers
Snippets.ID_PATH_PARAM, // path parameters
PayloadDocumentation.requestFields(Snippets.CONFIG_FIELDS) // request payload fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path parameters
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.CONFIG_FIELDS) // response fields
);
this.canAddElementsToResource(APPLICATIONS_API + "/{id}/configs", ID, addFilter, getFilter);
}
@Test
void canUpdateConfigsForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.CONFIG_FIELDS) // Request fields
);
this.canUpdateElementsForResource(APPLICATIONS_API + "/{id}/configs", ID, updateFilter);
}
@Test
void canDeleteConfigsForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // Path parameters
);
this.canDeleteElementsFromResource(APPLICATIONS_API + "/{id}/configs", ID, deleteFilter);
}
@Test
void canAddDependenciesToApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.CONTENT_TYPE_HEADER, // request header
PayloadDocumentation.requestFields(Snippets.DEPENDENCIES_FIELDS) // response fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.DEPENDENCIES_FIELDS) // response fields
);
this.canAddElementsToResource(
APPLICATIONS_API + "/{id}/dependencies",
ID,
addFilter,
getFilter
);
}
@Test
void canUpdateDependenciesForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.DEPENDENCIES_FIELDS) // Request fields
);
this.canUpdateElementsForResource(
APPLICATIONS_API + "/{id}/dependencies",
ID,
updateFilter
);
}
@Test
void canDeleteDependenciesForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM // Path variables
);
this.canDeleteElementsFromResource(
APPLICATIONS_API + "/{id}/dependencies",
ID,
deleteFilter
);
}
@Test
void canAddTagsToApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String api = APPLICATIONS_API + "/{id}/tags";
final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path params
Snippets.CONTENT_TYPE_HEADER, // request header
PayloadDocumentation.requestFields(Snippets.TAGS_FIELDS) // response fields
);
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // path parameters
Snippets.JSON_CONTENT_TYPE_HEADER, // response headers
PayloadDocumentation.responseFields(Snippets.TAGS_FIELDS) // response fields
);
this.canAddTagsToResource(api, ID, NAME, addFilter, getFilter);
}
@Test
void canUpdateTagsForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String api = APPLICATIONS_API + "/{id}/tags";
final RestDocumentationFilter updateFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.CONTENT_TYPE_HEADER, // Request header
Snippets.ID_PATH_PARAM, // Path parameters
PayloadDocumentation.requestFields(Snippets.TAGS_FIELDS) // Request fields
);
this.canUpdateTagsForResource(api, ID, NAME, updateFilter);
}
@Test
void canDeleteTagsForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String api = APPLICATIONS_API + "/{id}/tags";
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM
);
this.canDeleteTagsForResource(api, ID, NAME, deleteFilter);
}
@Test
void canDeleteTagForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String api = APPLICATIONS_API + "/{id}/tags";
final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM.and(
RequestDocumentation.parameterWithName("tag").description("The tag to remove")
)
);
this.canDeleteTagForResource(api, ID, NAME, deleteFilter);
}
@Test
void canGetCommandsForApplication() throws Exception {
this.createConfigResource(
new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
null
);
final String placeholder = UUID.randomUUID().toString();
final String command1Id = UUID.randomUUID().toString();
final String command2Id = UUID.randomUUID().toString();
final String command3Id = UUID.randomUUID().toString();
this.createConfigResource(
new Command
.Builder(placeholder, placeholder, placeholder, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, 1000L)
.withId(command1Id)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(placeholder, placeholder, placeholder, CommandStatus.INACTIVE, EXECUTABLE_AND_ARGS, 1100L)
.withId(command2Id)
.build(),
null
);
this.createConfigResource(
new Command
.Builder(placeholder, placeholder, placeholder, CommandStatus.DEPRECATED, EXECUTABLE_AND_ARGS, 1200L)
.withId(command3Id)
.build(),
null
);
final Set<String> appIds = Sets.newHashSet(ID);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(appIds))
.when()
.port(this.port)
.post(COMMANDS_API + "/{id}/applications", command1Id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(appIds))
.when()
.port(this.port)
.post(COMMANDS_API + "/{id}/applications", command3Id)
.then()
.statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));
final String applicationCommandsAPI = APPLICATIONS_API + "/{id}/commands";
Arrays.asList(
GenieObjectMapper.getMapper().readValue(
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(applicationCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.extract()
.asByteArray(),
Command[].class
)
).forEach(
command -> {
if (!command.getId().orElseThrow(IllegalArgumentException::new).equals(command1Id)
&& !command.getId().orElseThrow(IllegalArgumentException::new).equals(command3Id)) {
Assertions.fail("Unexpected command");
}
}
);
// Filter by status
final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
"{class-name}/{method-name}/{step}/",
Snippets.ID_PATH_PARAM, // Path parameters
RequestDocumentation.requestParameters(
RequestDocumentation
.parameterWithName("status")
.description("The status of commands to search for")
.attributes(
Attributes.key(Snippets.CONSTRAINTS).value(CommandStatus.values())
)
.optional()
), // Query Parameters
Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
PayloadDocumentation.responseFields(
PayloadDocumentation
.subsectionWithPath("[]")
.description("The list of commands found")
.attributes(Snippets.EMPTY_CONSTRAINTS)
)
);
RestAssured
.given(this.getRequestSpecification())
.param("status", CommandStatus.ACTIVE.toString(), CommandStatus.INACTIVE.toString())
.filter(getFilter)
.when()
.port(this.port)
.get(applicationCommandsAPI, ID)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body("$", Matchers.hasSize(1))
.body("[0].id", Matchers.is(command1Id));
}
@Test
void canCreateApplicationWithBlankFields() throws Exception {
final Set<String> stringSetWithBlank = Sets.newHashSet("foo", " ");
final List<Application> invalidApplicationResources = Lists.newArrayList(
new Application
.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE)
.withId(UUID.randomUUID().toString())
.withSetupFile(" ")
.build(),
new Application
.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE)
.withId(UUID.randomUUID().toString())
.withConfigs(stringSetWithBlank)
.build(),
new Application
.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE)
.withId(UUID.randomUUID().toString())
.withDependencies(stringSetWithBlank)
.build(),
new Application
.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE)
.withId(UUID.randomUUID().toString())
.withTags(stringSetWithBlank)
.build()
);
long i = 0L;
for (final Application invalidApplicationResource : invalidApplicationResources) {
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(i);
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(invalidApplicationResource))
.when()
.port(this.port)
.post(APPLICATIONS_API)
.then()
.statusCode(Matchers.is(HttpStatus.CREATED.value()));
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(++i);
}
}
@Test
void testApplicationNotFound() {
final List<String> paths = Lists.newArrayList("", "/commands");
for (final String path : paths) {
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(APPLICATIONS_API + "/{id}" + path, ID)
.then()
.statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()))
.contentType(Matchers.containsString(MediaType.APPLICATION_JSON_VALUE))
.body(EXCEPTION_MESSAGE_PATH, Matchers.startsWith("No application with id " + ID));
}
}
}
| 2,355 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/apis/rest/v3/controllers/package-info.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.
*
*/
/**
* Integration tests for the controllers.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.apis.rest.v3.controllers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,356 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/agent/services | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/agent/services/impl/package-info.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.
*
*/
/**
* Integration tests for this package.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.agent.services.impl;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,357 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/agent/services | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/agent/services/impl/CuratorDiscoveryIntegrationTest.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.genie.web.agent.services.impl;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceType;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* This integration test "documents" the behavior of Curator's Discovery Service and the assumptions on top of which
* {@link AgentRoutingServiceCuratorDiscoveryImpl} is build upon.
* - Multiple calls to {@code registerService} are idempotent
* - {@code registerService} overwrites the existing service instance (if one exists) regardless of owner/timestamp
* - {@code unregisterService} deletes the service instance regardless of owner/timestamp
* - {@code unregisterService} deletes the service instance regardless of owner/timestamp
*/
class CuratorDiscoveryIntegrationTest {
protected static final String SERVICE_NAME = "agent_connections";
protected static final ServiceType SERVICE_TYPE = ServiceType.DYNAMIC;
private final String jobId = UUID.randomUUID().toString();
private final AgentRoutingServiceCuratorDiscoveryImpl.Agent agent =
new AgentRoutingServiceCuratorDiscoveryImpl.Agent(jobId);
private final String address1 = "A.B.C.D";
private final String address2 = "A.B.X.Y";
private final ServiceInstance<AgentRoutingServiceCuratorDiscoveryImpl.Agent> agentInstance1 = new ServiceInstance<>(
SERVICE_NAME,
jobId,
address1,
null,
null,
agent,
Instant.now().minus(10, ChronoUnit.SECONDS).getEpochSecond(),
SERVICE_TYPE,
null
);
private final ServiceInstance<AgentRoutingServiceCuratorDiscoveryImpl.Agent> agentInstance2 = new ServiceInstance<>(
SERVICE_NAME,
jobId,
address2,
null,
null,
agent,
Instant.now().getEpochSecond(),
SERVICE_TYPE,
null
);
private TestingServer zkServer;
private CuratorFramework curator;
private ServiceDiscovery<AgentRoutingServiceCuratorDiscoveryImpl.Agent> serviceDiscovery;
@BeforeEach
void setUp() throws Exception {
this.zkServer = new TestingServer();
this.curator = CuratorFrameworkFactory.builder()
.connectString(zkServer.getConnectString())
.retryPolicy(new ExponentialBackoffRetry(50, 4))
.build();
this.curator.start();
this.curator.blockUntilConnected(10, TimeUnit.SECONDS);
this.serviceDiscovery = ServiceDiscoveryBuilder.builder(AgentRoutingServiceCuratorDiscoveryImpl.Agent.class)
.basePath("/discovery")
.client(curator)
.build();
}
@AfterEach
void tearDown() throws IOException {
this.curator.close();
this.zkServer.stop();
}
@Test
void registerMultipleTimes() throws Exception {
this.serviceDiscovery.registerService(agentInstance1);
this.serviceDiscovery.registerService(agentInstance1);
this.serviceDiscovery.registerService(agentInstance1);
Assertions.assertThat(this.serviceDiscovery.queryForInstances(SERVICE_NAME)).hasSize(1);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isEqualTo(agentInstance1);
this.serviceDiscovery.unregisterService(agentInstance1);
Assertions.assertThat(this.serviceDiscovery.queryForInstances(SERVICE_NAME)).hasSize(0);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isNull();
}
@Test
void lastRegisterOverwrites() throws Exception {
this.serviceDiscovery.registerService(agentInstance1);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isEqualTo(agentInstance1);
this.serviceDiscovery.registerService(agentInstance2);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isEqualTo(agentInstance2);
this.serviceDiscovery.registerService(agentInstance1);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isEqualTo(agentInstance1);
}
@Test
void unregisterDeletesInstanceByName() throws Exception {
this.serviceDiscovery.registerService(agentInstance1);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isEqualTo(agentInstance1);
this.serviceDiscovery.unregisterService(agentInstance2);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isNull();
}
@Test
void updateFailsIfInstanceDoesNotExist() throws Exception {
this.serviceDiscovery.registerService(agentInstance1);
this.serviceDiscovery.unregisterService(agentInstance1);
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isNull();
Exception updateError = null;
try {
this.serviceDiscovery.updateService(agentInstance1);
} catch (Exception e) {
updateError = e;
}
Assertions.assertThat(updateError).isNotNull();
Assertions.assertThat(this.serviceDiscovery.queryForInstance(SERVICE_NAME, jobId)).isNull();
}
}
| 2,358 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/scripts/ClusterSelectorManagedScriptIntegrationTest.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.genie.web.scripts;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.ClusterMetadata;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria;
import com.netflix.genie.common.internal.dtos.JobMetadata;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.exceptions.checked.ScriptExecutionException;
import com.netflix.genie.web.properties.ClusterSelectorScriptProperties;
import com.netflix.genie.web.properties.ScriptManagerProperties;
import com.netflix.genie.web.selectors.ClusterSelectionContext;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import javax.script.ScriptEngineManager;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class ClusterSelectorManagedScriptIntegrationTest {
private static final ExecutionResourceCriteria CRITERIA = new ExecutionResourceCriteria(
Lists.newArrayList(new Criterion.Builder().withId(UUID.randomUUID().toString()).build()),
new Criterion.Builder().withName(UUID.randomUUID().toString()).build(),
null
);
private static final JobMetadata JOB_METADATA = new JobMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
).build();
private static final Cluster CLUSTER_0 = createTestCluster("0");
private static final Cluster CLUSTER_1 = createTestCluster("1");
private static final Cluster CLUSTER_2 = createTestCluster("2");
private static final String JOB_REQUEST_0_ID = "0";
private static final String JOB_REQUEST_1_ID = "1";
private static final String JOB_REQUEST_2_ID = "2";
private static final String JOB_REQUEST_3_ID = "3";
private static final String JOB_REQUEST_4_ID = "4";
private static final String JOB_REQUEST_5_ID = "5";
private static final JobRequest JOB_REQUEST_0 = createTestJobRequest(JOB_REQUEST_0_ID);
private static final JobRequest JOB_REQUEST_1 = createTestJobRequest(JOB_REQUEST_1_ID);
private static final JobRequest JOB_REQUEST_2 = createTestJobRequest(JOB_REQUEST_2_ID);
private static final JobRequest JOB_REQUEST_3 = createTestJobRequest(JOB_REQUEST_3_ID);
private static final JobRequest JOB_REQUEST_4 = createTestJobRequest(JOB_REQUEST_4_ID);
private static final JobRequest JOB_REQUEST_5 = createTestJobRequest(JOB_REQUEST_5_ID);
private static final Set<Cluster> CLUSTERS = Sets.newHashSet(CLUSTER_0, CLUSTER_1, CLUSTER_2);
private ClusterSelectorScriptProperties scriptProperties;
private ClusterSelectorManagedScript clusterSelectorScript;
private PropertiesMapCache cache;
private static Cluster createTestCluster(final String id) {
return new Cluster(
id,
Instant.now(),
Instant.now(),
new ExecutionEnvironment(null, null, null),
new ClusterMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
ClusterStatus.UP
).build()
);
}
private static JobRequest createTestJobRequest(final String requestedId) {
return new JobRequest(
requestedId,
null,
null,
JOB_METADATA,
CRITERIA,
null,
null
);
}
@BeforeEach
void setUp() {
final MeterRegistry meterRegistry = new SimpleMeterRegistry();
final ScriptManagerProperties scriptManagerProperties = new ScriptManagerProperties();
final TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
final ExecutorService executorService = Executors.newCachedThreadPool();
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
final ResourceLoader resourceLoader = new DefaultResourceLoader();
final ScriptManager scriptManager = new ScriptManager(
scriptManagerProperties,
taskScheduler,
executorService,
scriptEngineManager,
resourceLoader,
meterRegistry
);
this.scriptProperties = new ClusterSelectorScriptProperties();
this.cache = Mockito.mock(PropertiesMapCache.class);
this.clusterSelectorScript = new ClusterSelectorManagedScript(
scriptManager,
this.scriptProperties,
meterRegistry,
this.cache
);
}
@Test
void selectClusterTest() throws Exception {
ManagedScriptIntegrationTest.loadScript(
"selectCluster.groovy",
this.clusterSelectorScript,
this.scriptProperties
);
ResourceSelectorScriptResult<Cluster> result;
result = this.clusterSelectorScript.selectResource(this.createContext(JOB_REQUEST_0_ID));
Assertions.assertThat(result.getResource()).isPresent().contains(CLUSTER_0);
Assertions.assertThat(result.getRationale()).isPresent().contains("selected 0");
result = this.clusterSelectorScript.selectResource(this.createContext(JOB_REQUEST_1_ID));
Assertions.assertThat(result.getResource()).isNotPresent();
Assertions.assertThat(result.getRationale()).isPresent().contains("Couldn't find anything");
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.clusterSelectorScript.selectResource(this.createContext(JOB_REQUEST_2_ID)))
.withNoCause();
result = this.clusterSelectorScript.selectResource(this.createContext(JOB_REQUEST_3_ID));
Assertions.assertThat(result.getResource()).isNotPresent();
Assertions.assertThat(result.getRationale()).isNotPresent();
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.clusterSelectorScript.selectResource(this.createContext(JOB_REQUEST_4_ID)))
.withCauseInstanceOf(ScriptExecutionException.class);
// Invalid return type from script
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.clusterSelectorScript.selectResource(this.createContext(JOB_REQUEST_5_ID)));
}
private ClusterSelectionContext createContext(final String jobId) {
final JobRequest jobRequest;
final boolean apiJob;
switch (jobId) {
case JOB_REQUEST_0_ID:
apiJob = true;
jobRequest = JOB_REQUEST_0;
break;
case JOB_REQUEST_1_ID:
apiJob = false;
jobRequest = JOB_REQUEST_1;
break;
case JOB_REQUEST_2_ID:
apiJob = false;
jobRequest = JOB_REQUEST_2;
break;
case JOB_REQUEST_3_ID:
apiJob = true;
jobRequest = JOB_REQUEST_3;
break;
case JOB_REQUEST_4_ID:
apiJob = false;
jobRequest = JOB_REQUEST_4;
break;
case JOB_REQUEST_5_ID:
apiJob = true;
jobRequest = JOB_REQUEST_5;
break;
default:
throw new IllegalArgumentException(jobId + " is currently unsupported");
}
return new ClusterSelectionContext(
jobId,
jobRequest,
apiJob,
null,
CLUSTERS
);
}
}
| 2,359 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/scripts/AgentLauncherSelectorManagedScriptIntegrationTest.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.genie.web.scripts;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ApiClientMetadata;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria;
import com.netflix.genie.common.internal.dtos.JobMetadata;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.dtos.JobRequestMetadata;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.dtos.ResolvedJob;
import com.netflix.genie.web.exceptions.checked.AgentLaunchException;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.exceptions.checked.ScriptExecutionException;
import com.netflix.genie.web.properties.AgentLauncherSelectorScriptProperties;
import com.netflix.genie.web.properties.ScriptManagerProperties;
import com.netflix.genie.web.selectors.AgentLauncherSelectionContext;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.actuate.health.Health;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import javax.script.ScriptEngineManager;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class AgentLauncherSelectorManagedScriptIntegrationTest {
private static final ExecutionResourceCriteria CRITERIA = new ExecutionResourceCriteria(
Lists.newArrayList(new Criterion.Builder().withId(UUID.randomUUID().toString()).build()),
new Criterion.Builder().withName(UUID.randomUUID().toString()).build(),
null
);
private static final JobMetadata JOB_METADATA = new JobMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
).build();
private static final AgentLauncher AGENT_LAUNCHER_0 = new TestAgentLauncher0();
private static final AgentLauncher AGENT_LAUNCHER_1 = new TestAgentLauncher1();
private static final AgentLauncher AGENT_LAUNCHER_2 = new TestAgentLauncher2();
private static final String JOB_REQUEST_0_ID = "0";
private static final String JOB_REQUEST_1_ID = "1";
private static final String JOB_REQUEST_2_ID = "2";
private static final String JOB_REQUEST_3_ID = "3";
private static final String JOB_REQUEST_4_ID = "4";
private static final String JOB_REQUEST_5_ID = "5";
private static final JobRequest JOB_REQUEST_0 = createTestJobRequest(JOB_REQUEST_0_ID);
private static final JobRequest JOB_REQUEST_1 = createTestJobRequest(JOB_REQUEST_1_ID);
private static final JobRequest JOB_REQUEST_2 = createTestJobRequest(JOB_REQUEST_2_ID);
private static final JobRequest JOB_REQUEST_3 = createTestJobRequest(JOB_REQUEST_3_ID);
private static final JobRequest JOB_REQUEST_4 = createTestJobRequest(JOB_REQUEST_4_ID);
private static final JobRequest JOB_REQUEST_5 = createTestJobRequest(JOB_REQUEST_5_ID);
private static final JobRequestMetadata JOB_REQUEST_METADATA = new JobRequestMetadata(
new ApiClientMetadata("somehost", "user-agent-foo"),
null,
0,
0,
null
);
private static final ResolvedJob RESOLVED_JOB = Mockito.mock(ResolvedJob.class);
private static final Set<AgentLauncher> AGENT_LAUNCHERS = Sets.newHashSet(
AGENT_LAUNCHER_0,
AGENT_LAUNCHER_1,
AGENT_LAUNCHER_2
);
private AgentLauncherSelectorScriptProperties scriptProperties;
private AgentLauncherSelectorManagedScript agentLauncherSelectorScript;
private PropertiesMapCache cache;
private static JobRequest createTestJobRequest(final String requestedId) {
return new JobRequest(
requestedId,
null,
null,
JOB_METADATA,
CRITERIA,
null,
null
);
}
@BeforeEach
void setUp() {
final MeterRegistry meterRegistry = new SimpleMeterRegistry();
final ScriptManagerProperties scriptManagerProperties = new ScriptManagerProperties();
final TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
final ExecutorService executorService = Executors.newCachedThreadPool();
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
final ResourceLoader resourceLoader = new DefaultResourceLoader();
final ScriptManager scriptManager = new ScriptManager(
scriptManagerProperties,
taskScheduler,
executorService,
scriptEngineManager,
resourceLoader,
meterRegistry
);
this.scriptProperties = new AgentLauncherSelectorScriptProperties();
this.cache = Mockito.mock(PropertiesMapCache.class);
this.agentLauncherSelectorScript = new AgentLauncherSelectorManagedScript(
scriptManager,
this.scriptProperties,
meterRegistry,
cache
);
}
@Test
void selectAgentLauncherTest() throws Exception {
ManagedScriptIntegrationTest.loadScript(
"selectAgentLauncher.groovy",
this.agentLauncherSelectorScript,
this.scriptProperties
);
ResourceSelectorScriptResult<AgentLauncher> result;
result = this.agentLauncherSelectorScript.selectResource(this.createContext(JOB_REQUEST_0_ID));
Assertions.assertThat(result.getResource()).isPresent().contains(AGENT_LAUNCHER_1);
Assertions.assertThat(result.getRationale()).isPresent().contains("selected 1");
result = this.agentLauncherSelectorScript.selectResource(this.createContext(JOB_REQUEST_1_ID));
Assertions.assertThat(result.getResource()).isNotPresent();
Assertions.assertThat(result.getRationale()).isPresent().contains("Couldn't find anything");
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.agentLauncherSelectorScript.selectResource(this.createContext(JOB_REQUEST_2_ID)))
.withNoCause();
result = this.agentLauncherSelectorScript.selectResource(this.createContext(JOB_REQUEST_3_ID));
Assertions.assertThat(result.getResource()).isNotPresent();
Assertions.assertThat(result.getRationale()).isNotPresent();
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.agentLauncherSelectorScript.selectResource(this.createContext(JOB_REQUEST_4_ID)))
.withCauseInstanceOf(ScriptExecutionException.class);
// Invalid return type from script
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.agentLauncherSelectorScript.selectResource(this.createContext(JOB_REQUEST_5_ID)));
}
private AgentLauncherSelectionContext createContext(final String jobId) {
final JobRequest jobRequest;
switch (jobId) {
case JOB_REQUEST_0_ID:
jobRequest = JOB_REQUEST_0;
break;
case JOB_REQUEST_1_ID:
jobRequest = JOB_REQUEST_1;
break;
case JOB_REQUEST_2_ID:
jobRequest = JOB_REQUEST_2;
break;
case JOB_REQUEST_3_ID:
jobRequest = JOB_REQUEST_3;
break;
case JOB_REQUEST_4_ID:
jobRequest = JOB_REQUEST_4;
break;
case JOB_REQUEST_5_ID:
jobRequest = JOB_REQUEST_5;
break;
default:
throw new IllegalArgumentException(jobId + " is currently unsupported");
}
return new AgentLauncherSelectionContext(
jobId,
jobRequest,
JOB_REQUEST_METADATA,
RESOLVED_JOB,
AGENT_LAUNCHERS
);
}
private static class TestAgentLauncher implements AgentLauncher {
@Override
public Optional<JsonNode> launchAgent(
final ResolvedJob resolvedJob,
final JsonNode requestedLauncherExt
) throws AgentLaunchException {
return Optional.empty();
}
@Override
public Health health() {
return null;
}
}
private static class TestAgentLauncher0 extends TestAgentLauncher {
}
private static class TestAgentLauncher1 extends TestAgentLauncher {
}
private static class TestAgentLauncher2 extends TestAgentLauncher {
}
}
| 2,360 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/scripts/ManagedScriptIntegrationTest.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.genie.web.scripts;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.web.exceptions.checked.ScriptExecutionException;
import com.netflix.genie.web.exceptions.checked.ScriptNotConfiguredException;
import com.netflix.genie.web.properties.ScriptManagerProperties;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import javax.script.ScriptEngineManager;
import java.net.URI;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
class ManagedScriptIntegrationTest {
private TestScriptProperties scriptProperties;
private TestScript script;
private ObjectMapper objectMapper;
static void loadScript(
final String scriptFilename,
final ManagedScript script,
final ManagedScriptBaseProperties scriptProperties
) throws Exception {
// Find the script resource
final URI scriptUri = ManagedScriptIntegrationTest.class.getResource(scriptFilename).toURI();
// Configure script to use it
scriptProperties.setSource(scriptUri);
// Trigger loading of script
scriptProperties.setAutoLoadEnabled(true);
script.warmUp();
// Wait for script to be ready to evaluate
final Instant deadline = Instant.now().plus(10, ChronoUnit.SECONDS);
while (!script.isReadyToEvaluate()) {
if (Instant.now().isAfter(deadline)) {
throw new RuntimeException("Timed out waiting for script to load");
}
System.out.println("Script not loaded yet...");
Thread.sleep(500);
}
System.out.println("Script loaded");
}
@BeforeEach
void setUp() {
final MeterRegistry meterRegistry = new SimpleMeterRegistry();
final ScriptManagerProperties scriptManagerProperties = new ScriptManagerProperties();
final TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
final ExecutorService executorService = Executors.newCachedThreadPool();
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
final ResourceLoader resourceLoader = new DefaultResourceLoader();
this.objectMapper = GenieObjectMapper.getMapper();
final ScriptManager scriptManager = new ScriptManager(
scriptManagerProperties,
taskScheduler,
executorService,
scriptEngineManager,
resourceLoader,
meterRegistry
);
this.scriptProperties = new TestScriptProperties();
this.script = new TestScript(
scriptManager,
this.scriptProperties,
meterRegistry
);
}
@ParameterizedTest(name = "Evaluate NOOP script: {0}")
@ValueSource(strings = {"noop.js", "noop.groovy"})
void evaluateSuccessfully(
final String scriptFilename
) throws Exception {
ManagedScriptIntegrationTest.loadScript(scriptFilename, this.script, this.scriptProperties);
this.script.evaluate();
}
@ParameterizedTest(name = "Timeout evaluating {0}")
@ValueSource(strings = {"sleep.js", "sleep.groovy"})
void scriptEvaluationTimeoutTest(
final String scriptFilename
) throws Exception {
ManagedScriptIntegrationTest.loadScript(scriptFilename, this.script, this.scriptProperties);
this.scriptProperties.setTimeout(1);
Assertions
.assertThatThrownBy(() -> this.script.evaluate())
.isInstanceOf(ScriptExecutionException.class)
.hasCauseInstanceOf(TimeoutException.class);
}
@Test
void evaluateScriptNotLoadedTest() {
Assertions
.assertThatThrownBy(() -> this.script.evaluate())
.isInstanceOf(ScriptNotConfiguredException.class);
}
@Test
void validateArgsGroovyScriptTest() throws Exception {
ManagedScriptIntegrationTest.loadScript("validate-args.groovy", this.script, this.scriptProperties);
final ImmutableMap<String, Object> expectedResult = ImmutableMap.of(
"booleanArg", Boolean.TRUE,
"stringArg", "Foo",
"integerArg", 678
);
final Map<String, Object> arguments = expectedResult
.entrySet()
.stream()
.collect(
Collectors.toMap(
Map.Entry::getKey,
e -> {
try {
return this.objectMapper.writeValueAsString(e.getValue());
} catch (final JsonProcessingException jpe) {
throw new RuntimeException(jpe);
}
}
)
);
Assertions
.assertThat(this.script.evaluateScript(arguments))
.isEqualTo(expectedResult);
}
private static class TestScript extends ManagedScript {
TestScript(
final ScriptManager scriptManager,
final ManagedScriptBaseProperties properties,
final MeterRegistry registry
) {
super(scriptManager, properties, registry);
}
void evaluate() throws ScriptNotConfiguredException, ScriptExecutionException {
super.evaluateScript(ImmutableMap.of());
}
}
private static class TestScriptProperties extends ManagedScriptBaseProperties {
}
}
| 2,361 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/scripts/CommandSelectorManagedScriptIntegrationTest.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.genie.web.scripts;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.CommandMetadata;
import com.netflix.genie.common.internal.dtos.CommandStatus;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria;
import com.netflix.genie.common.internal.dtos.JobMetadata;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.exceptions.checked.ScriptExecutionException;
import com.netflix.genie.web.properties.CommandSelectorManagedScriptProperties;
import com.netflix.genie.web.properties.ScriptManagerProperties;
import com.netflix.genie.web.selectors.CommandSelectionContext;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import javax.script.ScriptEngineManager;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
class CommandSelectorManagedScriptIntegrationTest {
private static final ExecutionResourceCriteria CRITERIA = new ExecutionResourceCriteria(
List.of(new Criterion.Builder().withId(UUID.randomUUID().toString()).build()),
new Criterion.Builder().withName(UUID.randomUUID().toString()).build(),
null
);
private static final JobMetadata JOB_METADATA = new JobMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
).build();
private static final Command COMMAND_0 = createTestCommand("0");
private static final Command COMMAND_1 = createTestCommand("1");
private static final Command COMMAND_2 = createTestCommand("2");
private static final String JOB_REQUEST_0_ID = "0";
private static final String JOB_REQUEST_1_ID = "1";
private static final String JOB_REQUEST_2_ID = "2";
private static final String JOB_REQUEST_3_ID = "3";
private static final String JOB_REQUEST_4_ID = "4";
private static final String JOB_REQUEST_5_ID = "5";
private static final JobRequest JOB_REQUEST_0 = createTestJobRequest(JOB_REQUEST_0_ID);
private static final JobRequest JOB_REQUEST_1 = createTestJobRequest(JOB_REQUEST_1_ID);
private static final JobRequest JOB_REQUEST_2 = createTestJobRequest(JOB_REQUEST_2_ID);
private static final JobRequest JOB_REQUEST_3 = createTestJobRequest(JOB_REQUEST_3_ID);
private static final JobRequest JOB_REQUEST_4 = createTestJobRequest(JOB_REQUEST_4_ID);
private static final JobRequest JOB_REQUEST_5 = createTestJobRequest(JOB_REQUEST_5_ID);
private static final Set<Command> COMMANDS = Sets.newHashSet(COMMAND_0, COMMAND_1, COMMAND_2);
private static final Set<Cluster> CLUSTERS = Sets.newHashSet(
Mockito.mock(Cluster.class),
Mockito.mock(Cluster.class)
);
private static final Map<Command, Set<Cluster>> COMMAND_CLUSTERS = COMMANDS
.stream()
.collect(Collectors.toMap(command -> command, command -> CLUSTERS));
private CommandSelectorManagedScriptProperties scriptProperties;
private CommandSelectorManagedScript commandSelectorManagedScript;
private MeterRegistry meterRegistry;
private ExecutorService executorService;
private static Command createTestCommand(final String id) {
return new Command(
id,
Instant.now(),
Instant.now(),
new ExecutionEnvironment(null, null, null),
new CommandMetadata.Builder(
"d",
"e",
"f",
CommandStatus.ACTIVE
).build(),
Lists.newArrayList(UUID.randomUUID().toString()),
null,
null,
null
);
}
private static JobRequest createTestJobRequest(final String requestedId) {
return new JobRequest(
requestedId,
null,
null,
JOB_METADATA,
CRITERIA,
null,
null
);
}
@BeforeEach
void setUp() {
this.meterRegistry = new SimpleMeterRegistry();
this.executorService = Executors.newCachedThreadPool();
final ScriptManager scriptManager = new ScriptManager(
new ScriptManagerProperties(),
new ConcurrentTaskScheduler(),
this.executorService,
new ScriptEngineManager(),
new DefaultResourceLoader(),
this.meterRegistry
);
this.scriptProperties = new CommandSelectorManagedScriptProperties();
this.commandSelectorManagedScript = new CommandSelectorManagedScript(
scriptManager,
this.scriptProperties,
this.meterRegistry,
Mockito.mock(PropertiesMapCache.class)
);
}
@AfterEach
void tearDown() {
this.meterRegistry.close();
this.executorService.shutdownNow();
}
@Test
void selectCommandTest() throws Exception {
ManagedScriptIntegrationTest.loadScript(
"selectCommand.groovy",
this.commandSelectorManagedScript,
this.scriptProperties
);
ResourceSelectorScriptResult<Command> result;
result = this.commandSelectorManagedScript.selectResource(this.createContext(JOB_REQUEST_0_ID));
Assertions.assertThat(result.getResource()).isPresent().contains(COMMAND_0);
Assertions.assertThat(result.getRationale()).isPresent().contains("selected 0");
result = this.commandSelectorManagedScript.selectResource(this.createContext(JOB_REQUEST_1_ID));
Assertions.assertThat(result.getResource()).isNotPresent();
Assertions.assertThat(result.getRationale()).isPresent().contains("Couldn't find anything");
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.commandSelectorManagedScript.selectResource(this.createContext(JOB_REQUEST_2_ID)))
.withNoCause();
result = this.commandSelectorManagedScript.selectResource(this.createContext(JOB_REQUEST_3_ID));
Assertions.assertThat(result.getResource()).isNotPresent();
Assertions.assertThat(result.getRationale()).isNotPresent();
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.commandSelectorManagedScript.selectResource(this.createContext(JOB_REQUEST_4_ID)))
.withCauseInstanceOf(ScriptExecutionException.class);
// Invalid return type from script
Assertions
.assertThatExceptionOfType(ResourceSelectionException.class)
.isThrownBy(() -> this.commandSelectorManagedScript.selectResource(this.createContext(JOB_REQUEST_5_ID)));
}
private CommandSelectionContext createContext(final String jobId) {
final JobRequest jobRequest;
final boolean apiJob;
switch (jobId) {
case JOB_REQUEST_0_ID:
apiJob = true;
jobRequest = JOB_REQUEST_0;
break;
case JOB_REQUEST_1_ID:
apiJob = false;
jobRequest = JOB_REQUEST_1;
break;
case JOB_REQUEST_2_ID:
apiJob = false;
jobRequest = JOB_REQUEST_2;
break;
case JOB_REQUEST_3_ID:
apiJob = true;
jobRequest = JOB_REQUEST_3;
break;
case JOB_REQUEST_4_ID:
apiJob = false;
jobRequest = JOB_REQUEST_4;
break;
case JOB_REQUEST_5_ID:
apiJob = true;
jobRequest = JOB_REQUEST_5;
break;
default:
throw new IllegalArgumentException(jobId + " is currently unsupported");
}
return new CommandSelectionContext(
jobId,
jobRequest,
apiJob,
COMMAND_CLUSTERS
);
}
}
| 2,362 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/scripts/package-info.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.
*
*/
/**
* Integration tests for script components.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.scripts;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,363 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplTagsIntegrationTest.java | /*
*
* Copyright 2017 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.genie.web.data.services.impl.jpa;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ApplicationMetadata;
import com.netflix.genie.common.internal.dtos.ApplicationRequest;
import com.netflix.genie.common.internal.dtos.ApplicationStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.UUID;
/**
* Integration tests for the {@link JpaPersistenceServiceImpl} focusing on the Tag APIs.
*
* @author tgianos
* @since 3.3.0
*/
class JpaPersistenceServiceImplTagsIntegrationTest extends JpaPersistenceServiceIntegrationTestBase {
@Test
void canDeleteUnusedTags() throws GenieCheckedException {
Assertions.assertThat(this.tagRepository.count()).isEqualTo(0L);
final String tag1 = UUID.randomUUID().toString();
final String tag2 = UUID.randomUUID().toString();
this.tagRepository.saveAndFlush(new TagEntity(tag1));
final ApplicationRequest app = new ApplicationRequest.Builder(
new ApplicationMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
ApplicationStatus.ACTIVE
)
.withTags(Sets.newHashSet(tag2))
.build()
).build();
// Create a relationship between tag2 and some resource in the system that should block it from being deleted
this.service.saveApplication(app);
Assertions.assertThat(this.tagRepository.existsByTag(tag1)).isTrue();
Assertions.assertThat(this.tagRepository.existsByTag(tag2)).isTrue();
Assertions.assertThat(this.service.deleteUnusedTags(Instant.now(), 10)).isEqualTo(1L);
Assertions.assertThat(this.tagRepository.existsByTag(tag1)).isFalse();
Assertions.assertThat(this.tagRepository.existsByTag(tag2)).isTrue();
}
}
| 2,364 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplCommandsIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.data.services.impl.jpa;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import com.github.springtestdbunit.assertion.DatabaseAssertionMode;
import com.netflix.genie.common.internal.dtos.Application;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.CommandMetadata;
import com.netflix.genie.common.internal.dtos.CommandRequest;
import com.netflix.genie.common.internal.dtos.CommandStatus;
import com.netflix.genie.common.internal.dtos.ComputeResources;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.Image;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.annotation.Nullable;
import javax.validation.ConstraintViolationException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
* Integration Tests for the {@link JpaPersistenceServiceImpl} command specific functionality.
*
* @author tgianos
*/
class JpaPersistenceServiceImplCommandsIntegrationTest extends JpaPersistenceServiceIntegrationTestBase {
private static final String APP_1_ID = "app1";
private static final String COMMAND_1_ID = "command1";
private static final String COMMAND_1_NAME = "pig_13_prod";
private static final String COMMAND_1_USER = "tgianos";
private static final String COMMAND_1_VERSION = "1.2.3";
private static final List<String> COMMAND_1_EXECUTABLE = List.of("pig");
private static final CommandStatus COMMAND_1_STATUS = CommandStatus.ACTIVE;
private static final String COMMAND_2_ID = "command2";
private static final String COMMAND_2_NAME = "hive_11_prod";
private static final String COMMAND_2_USER = "amsharma";
private static final String COMMAND_2_VERSION = "4.5.6";
private static final List<String> COMMAND_2_EXECUTABLE = List.of("hive");
private static final CommandStatus COMMAND_2_STATUS = CommandStatus.INACTIVE;
private static final String COMMAND_3_ID = "command3";
private static final String COMMAND_3_NAME = "pig_11_prod";
private static final String COMMAND_3_USER = "tgianos";
private static final String COMMAND_3_VERSION = "7.8.9";
private static final List<String> COMMAND_3_EXECUTABLE = List.of("pig");
private static final CommandStatus COMMAND_3_STATUS = CommandStatus.DEPRECATED;
private static final Pageable PAGE = PageRequest.of(0, 10, Sort.Direction.DESC, "updated");
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommand() throws GenieCheckedException {
final Command command1 = this.service.getCommand(COMMAND_1_ID);
Assertions.assertThat(command1.getId()).isEqualTo(COMMAND_1_ID);
Assertions.assertThat(command1.getMetadata().getName()).isEqualTo(COMMAND_1_NAME);
Assertions.assertThat(command1.getMetadata().getUser()).isEqualTo(COMMAND_1_USER);
Assertions.assertThat(command1.getMetadata().getVersion()).isEqualTo(COMMAND_1_VERSION);
Assertions.assertThat(command1.getMetadata().getStatus()).isEqualTo(COMMAND_1_STATUS);
Assertions.assertThat(command1.getExecutable()).isEqualTo(COMMAND_1_EXECUTABLE);
Assertions.assertThat(command1.getMetadata().getTags().size()).isEqualTo(3);
Assertions.assertThat(command1.getResources().getConfigs().size()).isEqualTo(2);
Assertions.assertThat(command1.getResources().getDependencies()).isEmpty();
final Command command2 = this.service.getCommand(COMMAND_2_ID);
Assertions.assertThat(command2.getId()).isEqualTo(COMMAND_2_ID);
Assertions.assertThat(command2.getMetadata().getName()).isEqualTo(COMMAND_2_NAME);
Assertions.assertThat(command2.getMetadata().getUser()).isEqualTo(COMMAND_2_USER);
Assertions.assertThat(command2.getMetadata().getVersion()).isEqualTo(COMMAND_2_VERSION);
Assertions.assertThat(command2.getMetadata().getStatus()).isEqualTo(COMMAND_2_STATUS);
Assertions.assertThat(command2.getExecutable()).isEqualTo(COMMAND_2_EXECUTABLE);
Assertions.assertThat(command2.getMetadata().getTags().size()).isEqualTo(2);
Assertions.assertThat(command2.getResources().getConfigs().size()).isEqualTo(1);
Assertions.assertThat(command2.getResources().getDependencies().size()).isEqualTo(1);
final Command command3 = this.service.getCommand(COMMAND_3_ID);
Assertions.assertThat(command3.getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(command3.getMetadata().getName()).isEqualTo(COMMAND_3_NAME);
Assertions.assertThat(command3.getMetadata().getUser()).isEqualTo(COMMAND_3_USER);
Assertions.assertThat(command3.getMetadata().getVersion()).isEqualTo(COMMAND_3_VERSION);
Assertions.assertThat(command3.getMetadata().getStatus()).isEqualTo(COMMAND_3_STATUS);
Assertions.assertThat(command3.getExecutable()).isEqualTo(COMMAND_3_EXECUTABLE);
Assertions.assertThat(command3.getMetadata().getTags().size()).isEqualTo(3);
Assertions.assertThat(command3.getResources().getConfigs().size()).isEqualTo(1);
Assertions.assertThat(command3.getResources().getDependencies().size()).isEqualTo(2);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsByName() {
final Page<Command> commands = this.service.findCommands(COMMAND_2_NAME, null, null, null, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsByUserName() {
final Page<Command> commands = this.service.findCommands(null, COMMAND_1_USER, null, null, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_1_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsByStatuses() {
final Set<CommandStatus> statuses = Set.of(CommandStatus.INACTIVE, CommandStatus.DEPRECATED);
final Page<Command> commands = this.service.findCommands(null, null, statuses, null, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_3_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsByTags() {
final Set<String> tags = new HashSet<>();
tags.add("prod");
Page<Command> commands = this.service.findCommands(null, null, null, tags, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(2).getId()).isEqualTo(COMMAND_1_ID);
tags.add("pig");
commands = this.service.findCommands(null, null, null, tags, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_1_ID);
tags.clear();
tags.add("hive");
commands = this.service.findCommands(null, null, null, tags, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
tags.add("somethingThatWouldNeverReallyExist");
commands = this.service.findCommands(null, null, null, tags, PAGE);
Assertions.assertThat(commands.getContent()).isEmpty();
tags.clear();
commands = this.service.findCommands(null, null, null, tags, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(2).getId()).isEqualTo(COMMAND_1_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsDescending() {
//Default to order by Updated
final Page<Command> commands = this.service.findCommands(null, null, null, null, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(2).getId()).isEqualTo(COMMAND_1_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsAscending() {
final Pageable ascending = PageRequest.of(0, 10, Sort.Direction.ASC, "updated");
//Default to order by Updated
final Page<Command> commands = this.service.findCommands(null, null, null, null, ascending);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_1_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(2).getId()).isEqualTo(COMMAND_2_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsOrderBysName() {
final Pageable name = PageRequest.of(0, 10, Sort.Direction.DESC, "name");
final Page<Command> commands = this.service.findCommands(null, null, null, null, name);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_1_ID);
Assertions.assertThat(commands.getContent().get(1).getId()).isEqualTo(COMMAND_3_ID);
Assertions.assertThat(commands.getContent().get(2).getId()).isEqualTo(COMMAND_2_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsOrderBysInvalidField() {
final Pageable invalid = PageRequest.of(0, 10, Sort.Direction.DESC, "I'mNotAValidField");
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.service.findCommands(null, null, null, null, invalid));
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetCommandsWithTags() {
final Set<CommandStatus> activeStatuses = Set.of(CommandStatus.ACTIVE);
final Set<CommandStatus> inactiveStatuses = Set.of(CommandStatus.INACTIVE);
final Set<String> tags = Set.of("prod", "hive");
Page<Command> commands;
commands = this.service.findCommands(null, null, activeStatuses, tags, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(0);
commands = this.service.findCommands(null, null, inactiveStatuses, tags, PAGE);
Assertions.assertThat(commands.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(commands.getContent().get(0).getId()).isEqualTo(COMMAND_2_ID);
}
@Test
void testSaveCommand() throws GenieCheckedException {
final String id = UUID.randomUUID().toString();
final ComputeResources computeResources = new ComputeResources.Builder()
.withCpu(7)
.withGpu(8)
.withMemoryMb(1_352L)
.withDiskMb(10_324L)
.withNetworkMbps(534L)
.build();
final Map<String, Image> images = Map.of(
UUID.randomUUID().toString(),
new Image.Builder().withName(UUID.randomUUID().toString()).withTag(UUID.randomUUID().toString()).build(),
UUID.randomUUID().toString(),
new Image.Builder()
.withName(UUID.randomUUID().toString())
.withTag(UUID.randomUUID().toString())
.withArguments(List.of(UUID.randomUUID().toString()))
.build()
);
final CommandRequest command = new CommandRequest.Builder(
new CommandMetadata.Builder(
COMMAND_1_NAME,
COMMAND_1_USER,
COMMAND_1_VERSION,
CommandStatus.ACTIVE
)
.build(),
COMMAND_1_EXECUTABLE
)
.withRequestedId(id)
.withComputeResources(computeResources)
.withImages(images)
.build();
final String createdId = this.service.saveCommand(command);
Assertions.assertThat(createdId).isEqualTo(id);
final Command created = this.service.getCommand(id);
Assertions.assertThat(created).isNotNull();
Assertions.assertThat(created.getId()).isEqualTo(id);
Assertions.assertThat(created.getMetadata().getName()).isEqualTo(COMMAND_1_NAME);
Assertions.assertThat(created.getMetadata().getUser()).isEqualTo(COMMAND_1_USER);
Assertions.assertThat(created.getMetadata().getStatus()).isEqualByComparingTo(CommandStatus.ACTIVE);
Assertions.assertThat(created.getExecutable()).isEqualTo(COMMAND_1_EXECUTABLE);
Assertions.assertThat(created.getClusterCriteria()).isEmpty();
Assertions.assertThat(created.getComputeResources()).isEqualTo(computeResources);
Assertions.assertThat(created.getImages()).isEqualTo(images);
this.service.deleteCommand(id);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getCommand(id));
}
@Test
void testSaveCommandNoId() throws GenieCheckedException {
final List<Criterion> clusterCriteria = List.of(
new Criterion.Builder().withId(UUID.randomUUID().toString()).build(),
new Criterion
.Builder()
.withTags(Set.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build()
);
final long memory = 512L;
final ComputeResources computeResources = new ComputeResources.Builder().withMemoryMb(memory).build();
final CommandRequest command = new CommandRequest.Builder(
new CommandMetadata.Builder(
COMMAND_1_NAME,
COMMAND_1_USER,
COMMAND_1_VERSION,
CommandStatus.ACTIVE
)
.build(),
COMMAND_1_EXECUTABLE
)
.withComputeResources(computeResources)
.withClusterCriteria(clusterCriteria)
.build();
final String id = this.service.saveCommand(command);
final Command created = this.service.getCommand(id);
Assertions.assertThat(created).isNotNull();
Assertions.assertThat(created.getMetadata().getName()).isEqualTo(COMMAND_1_NAME);
Assertions.assertThat(created.getMetadata().getUser()).isEqualTo(COMMAND_1_USER);
Assertions.assertThat(created.getMetadata().getStatus()).isEqualByComparingTo(CommandStatus.ACTIVE);
Assertions.assertThat(created.getExecutable()).isEqualTo(COMMAND_1_EXECUTABLE);
Assertions
.assertThat(created.getComputeResources())
.extracting(ComputeResources::getMemoryMb)
.isEqualTo(Optional.of(memory));
Assertions.assertThat(created.getClusterCriteria()).isEqualTo(clusterCriteria);
this.service.deleteCommand(created.getId());
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getCommand(id));
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateCommand() throws GenieCheckedException {
final Command command = this.service.getCommand(COMMAND_1_ID);
Assertions.assertThat(command.getMetadata().getUser()).isEqualTo(COMMAND_1_USER);
Assertions.assertThat(command.getMetadata().getStatus()).isEqualByComparingTo(CommandStatus.ACTIVE);
Assertions.assertThat(command.getMetadata().getTags().size()).isEqualTo(3);
Assertions.assertThat(command.getComputeResources()).isNotNull();
final Set<String> tags = new HashSet<>();
tags.add("yarn");
tags.add("hadoop");
tags.addAll(command.getMetadata().getTags());
final long memory = 1_024L;
final Command updateCommand = new Command(
command.getId(),
command.getCreated(),
command.getUpdated(),
command.getResources(),
new CommandMetadata.Builder(
command.getMetadata().getName(),
COMMAND_2_USER,
command.getMetadata().getVersion(),
CommandStatus.INACTIVE
)
.withMetadata(command.getMetadata().getMetadata().orElse(null))
.withDescription(command.getMetadata().getDescription().orElse(null))
.withTags(tags)
.build(),
command.getExecutable(),
null,
new ComputeResources.Builder().withMemoryMb(memory).build(),
null
);
this.service.updateCommand(COMMAND_1_ID, updateCommand);
final Command updated = this.service.getCommand(COMMAND_1_ID);
Assertions.assertThat(updated.getMetadata().getUser()).isEqualTo(COMMAND_2_USER);
Assertions.assertThat(updated.getMetadata().getStatus()).isEqualByComparingTo(CommandStatus.INACTIVE);
Assertions.assertThat(updated.getMetadata().getTags().size()).isEqualTo(5);
Assertions
.assertThat(updated.getComputeResources())
.extracting(ComputeResources::getMemoryMb)
.isEqualTo(Optional.of(memory));
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateCommandWithClusterCriteria() throws GenieCheckedException {
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(0L);
final List<Criterion> criteria0 = List.of(
new Criterion.Builder()
.withStatus(ClusterStatus.UP.name())
.build(),
new Criterion.Builder()
.withId(UUID.randomUUID().toString())
.build(),
new Criterion.Builder()
.withTags(Set.of(UUID.randomUUID().toString()))
.build()
);
final List<Criterion> criteria1 = List.of(
new Criterion.Builder()
.withTags(Set.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build(),
new Criterion.Builder()
.withName(ClusterStatus.UP.name())
.build(),
new Criterion.Builder()
.withVersion(UUID.randomUUID().toString())
.build(),
new Criterion.Builder()
.withId(UUID.randomUUID().toString())
.withVersion(UUID.randomUUID().toString())
.build()
);
Command command = this.createTestCommand(null, null, criteria0);
Assertions.assertThat(command.getClusterCriteria()).isEqualTo(criteria0);
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(3L);
Command updateCommand = this.copyCommandWithNewClusterCriteria(command, null);
this.service.updateCommand(command.getId(), updateCommand);
command = this.service.getCommand(command.getId());
Assertions.assertThat(command.getClusterCriteria()).isEmpty();
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(0L);
updateCommand = this.copyCommandWithNewClusterCriteria(command, criteria1);
this.service.updateCommand(command.getId(), updateCommand);
command = this.service.getCommand(command.getId());
Assertions.assertThat(command.getClusterCriteria()).isEqualTo(criteria1);
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(4L);
updateCommand = this.copyCommandWithNewClusterCriteria(command, criteria0);
this.service.updateCommand(command.getId(), updateCommand);
command = this.service.getCommand(command.getId());
Assertions.assertThat(command.getClusterCriteria()).isEqualTo(criteria0);
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(3L);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateCommandWithInvalidCommand() throws GenieCheckedException {
final Command command = this.service.getCommand(COMMAND_1_ID);
final Command updateCommand = new Command(
command.getId(),
command.getCreated(),
command.getUpdated(),
command.getResources(),
new CommandMetadata.Builder(
command.getMetadata().getName(),
"", //invalid
command.getMetadata().getVersion(),
CommandStatus.INACTIVE
)
.withMetadata(command.getMetadata().getMetadata().orElse(null))
.withDescription(command.getMetadata().getDescription().orElse(null))
.withTags(command.getMetadata().getTags())
.build(),
command.getExecutable(),
null,
null,
null
);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.service.updateCommand(COMMAND_1_ID, updateCommand));
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateCreateAndUpdate() throws GenieCheckedException {
final Command init = this.service.getCommand(COMMAND_1_ID);
final Instant created = init.getCreated();
final Instant updated = init.getUpdated();
final Command updateCommand = new Command(
init.getId(),
Instant.now(),
Instant.EPOCH,
init.getResources(),
init.getMetadata(),
init.getExecutable(),
init.getClusterCriteria(),
null,
null
);
this.service.updateCommand(COMMAND_1_ID, updateCommand);
final Command updatedCommand = this.service.getCommand(COMMAND_1_ID);
Assertions.assertThat(updatedCommand.getCreated()).isEqualTo(created);
Assertions.assertThat(updatedCommand.getUpdated()).isNotEqualTo(updated);
Assertions.assertThat(updatedCommand.getUpdated()).isNotEqualTo(Instant.EPOCH);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testDeleteAll() throws GenieCheckedException {
Assertions.assertThat(this.commandRepository.count()).isEqualTo(3L);
this.service.deleteAllCommands();
Assertions.assertThat(this.commandRepository.count()).isEqualTo(0L);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testDelete() throws GenieCheckedException {
Set<Command> appCommands = this.service.getCommandsForApplication(APP_1_ID, null);
Assertions.assertThat(appCommands).hasSize(1);
boolean found = false;
for (final Command command : appCommands) {
if (COMMAND_1_ID.equals(command.getId())) {
found = true;
break;
}
}
Assertions.assertThat(found).isTrue();
//Actually delete it
this.service.deleteCommand(COMMAND_1_ID);
appCommands = this.service.getCommandsForApplication(APP_1_ID, null);
Assertions.assertThat(appCommands).isEmpty();
//Test a case where the app has no commands to
//make sure that also works.
this.service.deleteCommand(COMMAND_3_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testAddConfigsToCommand() throws GenieCheckedException {
final String newConfig1 = UUID.randomUUID().toString();
final String newConfig2 = UUID.randomUUID().toString();
final String newConfig3 = UUID.randomUUID().toString();
final Set<String> newConfigs = Set.of(newConfig1, newConfig2, newConfig3);
Assertions.assertThat(this.service.getConfigsForResource(COMMAND_1_ID, Command.class)).hasSize(2);
this.service.addConfigsToResource(COMMAND_1_ID, newConfigs, Command.class);
final Set<String> finalConfigs = this.service.getConfigsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(finalConfigs).hasSize(5).contains(newConfig1, newConfig2, newConfig3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateConfigsForCommand() throws GenieCheckedException {
final String newConfig1 = UUID.randomUUID().toString();
final String newConfig2 = UUID.randomUUID().toString();
final String newConfig3 = UUID.randomUUID().toString();
final Set<String> newConfigs = Set.of(newConfig1, newConfig2, newConfig3);
Assertions.assertThat(this.service.getConfigsForResource(COMMAND_1_ID, Command.class)).hasSize(2);
this.service.updateConfigsForResource(COMMAND_1_ID, newConfigs, Command.class);
final Set<String> finalConfigs = this.service.getConfigsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(finalConfigs).hasSize(3).contains(newConfig1, newConfig2, newConfig3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetConfigsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getConfigsForResource(COMMAND_1_ID, Command.class)).hasSize(2);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveAllConfigsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getConfigsForResource(COMMAND_1_ID, Command.class)).hasSize(2);
this.service.removeAllConfigsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(this.service.getConfigsForResource(COMMAND_1_ID, Command.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveConfigForCommand() throws GenieCheckedException {
final Set<String> configs = this.service.getConfigsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(configs).hasSize(2);
final String removedConfig = configs.iterator().next();
this.service.removeConfigForResource(COMMAND_1_ID, removedConfig, Command.class);
Assertions
.assertThat(this.service.getConfigsForResource(COMMAND_1_ID, Command.class))
.doesNotContain(removedConfig);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testAddDependenciesToCommand() throws GenieCheckedException {
final String newDependency1 = UUID.randomUUID().toString();
final String newDependency2 = UUID.randomUUID().toString();
final String newDependency3 = UUID.randomUUID().toString();
final Set<String> newDependencies = Set.of(newDependency1, newDependency2, newDependency3);
Assertions.assertThat(this.service.getDependenciesForResource(COMMAND_3_ID, Command.class)).hasSize(2);
this.service.addDependenciesToResource(COMMAND_3_ID, newDependencies, Command.class);
final Set<String> finalDependencies = this.service.getDependenciesForResource(COMMAND_3_ID, Command.class);
Assertions.assertThat(finalDependencies).hasSize(5).contains(newDependency1, newDependency2, newDependency3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateDependenciesForCommand() throws GenieCheckedException {
final String newDependency1 = UUID.randomUUID().toString();
final String newDependency2 = UUID.randomUUID().toString();
final String newDependency3 = UUID.randomUUID().toString();
final Set<String> newDependencies = Set.of(newDependency1, newDependency2, newDependency3);
Assertions.assertThat(this.service.getDependenciesForResource(COMMAND_1_ID, Command.class)).isEmpty();
this.service.updateDependenciesForResource(COMMAND_1_ID, newDependencies, Command.class);
final Set<String> finalDependencies = this.service.getDependenciesForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(finalDependencies).hasSize(3).contains(newDependency1, newDependency2, newDependency3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetDependenciesForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getDependenciesForResource(COMMAND_2_ID, Command.class)).hasSize(1);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveAllDependenciesForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getDependenciesForResource(COMMAND_3_ID, Command.class)).hasSize(2);
this.service.removeAllDependenciesForResource(COMMAND_3_ID, Command.class);
Assertions.assertThat(this.service.getDependenciesForResource(COMMAND_3_ID, Command.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveDependencyForCommand() throws GenieCheckedException {
final Set<String> dependencies = this.service.getDependenciesForResource(COMMAND_3_ID, Command.class);
Assertions.assertThat(dependencies).hasSize(2);
final String removedDependency = dependencies.iterator().next();
this.service.removeDependencyForResource(COMMAND_3_ID, removedDependency, Command.class);
Assertions
.assertThat(this.service.getDependenciesForResource(COMMAND_3_ID, Command.class))
.doesNotContain(removedDependency);
}
@Test
@DatabaseSetup("persistence/commands/addApplicationsForCommand/before.xml")
// @ExpectedDatabase(
// value = "persistence/commands/addApplicationsForCommand/after.xml",
// assertionMode = DatabaseAssertionMode.NON_STRICT
// )
void testAddApplicationsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getApplicationsForCommand(COMMAND_2_ID)).isEmpty();
final List<String> appIds = List.of(APP_1_ID);
final Set<Command> preCommands = this.service.getCommandsForApplication(APP_1_ID, null);
Assertions
.assertThat(preCommands)
.hasSize(1)
.extracting(Command::getId)
.containsOnly(COMMAND_1_ID);
this.service.addApplicationsForCommand(COMMAND_2_ID, appIds);
Assertions
.assertThat(this.service.getCommandsForApplication(APP_1_ID, null))
.hasSize(2)
.extracting(Command::getId)
.containsExactlyInAnyOrder(COMMAND_1_ID, COMMAND_2_ID);
Assertions
.assertThat(this.service.getApplicationsForCommand(COMMAND_2_ID))
.element(0)
.extracting(Application::getId)
.isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testSetApplicationsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getApplicationsForCommand(COMMAND_2_ID)).isEmpty();
final List<String> appIds = List.of(APP_1_ID);
final Set<Command> preCommands = this.service.getCommandsForApplication(APP_1_ID, null);
Assertions
.assertThat(preCommands)
.singleElement()
.extracting(Command::getId)
.isEqualTo(COMMAND_1_ID);
this.service.setApplicationsForCommand(COMMAND_2_ID, appIds);
final Set<Command> savedCommands = this.service.getCommandsForApplication(APP_1_ID, null);
Assertions.assertThat(savedCommands).hasSize(2);
Assertions
.assertThat(this.service.getApplicationsForCommand(COMMAND_2_ID))
.singleElement()
.extracting(Application::getId)
.isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetApplicationsForCommand() throws GenieCheckedException {
Assertions
.assertThat(this.service.getApplicationsForCommand(COMMAND_1_ID))
.singleElement()
.extracting(Application::getId)
.isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveApplicationsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getApplicationsForCommand(COMMAND_1_ID)).hasSize(1);
this.service.removeApplicationsForCommand(COMMAND_1_ID);
Assertions.assertThat(this.service.getApplicationsForCommand(COMMAND_1_ID)).isEmpty();
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveApplicationForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getApplicationsForCommand(COMMAND_1_ID)).hasSize(1);
this.service.removeApplicationForCommand(COMMAND_1_ID, APP_1_ID);
Assertions.assertThat(this.service.getApplicationsForCommand(COMMAND_1_ID)).isEmpty();
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testAddTagsToCommand() throws GenieCheckedException {
final String newTag1 = UUID.randomUUID().toString();
final String newTag2 = UUID.randomUUID().toString();
final String newTag3 = UUID.randomUUID().toString();
final Set<String> newTags = Set.of(newTag1, newTag2, newTag3);
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).hasSize(3);
this.service.addTagsToResource(COMMAND_1_ID, newTags, Command.class);
final Set<String> finalTags = this.service.getTagsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(finalTags).hasSize(6).contains(newTag1, newTag2, newTag3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testUpdateTagsForCommand() throws GenieCheckedException {
final String newTag1 = UUID.randomUUID().toString();
final String newTag2 = UUID.randomUUID().toString();
final String newTag3 = UUID.randomUUID().toString();
final Set<String> newTags = Set.of(newTag1, newTag2, newTag3);
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).hasSize(3);
this.service.updateTagsForResource(COMMAND_1_ID, newTags, Command.class);
final Set<String> finalTags = this.service.getTagsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(finalTags).hasSize(3).contains(newTag1, newTag2, newTag3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testGetTagsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).hasSize(3);
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveAllTagsForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).hasSize(3);
this.service.removeAllTagsForResource(COMMAND_1_ID, Command.class);
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/commands/init.xml")
void testRemoveTagForCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).contains("tez");
this.service.removeTagForResource(COMMAND_1_ID, "tez", Command.class);
Assertions.assertThat(this.service.getTagsForResource(COMMAND_1_ID, Command.class)).doesNotContain("tez");
}
@Test
@DatabaseSetup("persistence/commands/getClustersForCommand/setup.xml")
void testGetClustersForCommand() throws GenieCheckedException {
Assertions
.assertThat(this.service.getClustersForCommand(COMMAND_1_ID, null))
.hasSize(3)
.extracting(Cluster::getId)
.containsExactlyInAnyOrder("cluster1", "cluster2", "cluster3");
Assertions
.assertThat(this.service.getClustersForCommand(COMMAND_1_ID, EnumSet.of(ClusterStatus.OUT_OF_SERVICE)))
.hasSize(1)
.extracting(Cluster::getId)
.containsExactlyInAnyOrder("cluster3");
Assertions
.assertThat(
this.service.getClustersForCommand(
COMMAND_1_ID,
EnumSet.of(ClusterStatus.OUT_OF_SERVICE, ClusterStatus.UP)
)
)
.hasSize(2)
.extracting(Cluster::getId)
.containsExactlyInAnyOrder("cluster1", "cluster3");
}
@Test
void testGetClustersForCommandNoId() {
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.service.getClustersForCommand("", null));
}
@Test
void testClusterCriteriaManipulation() throws GenieCheckedException {
final Criterion criterion0 = new Criterion.Builder().withId(UUID.randomUUID().toString()).build();
final Criterion criterion1 = new Criterion.Builder().withStatus(UUID.randomUUID().toString()).build();
final Criterion criterion2 = new Criterion.Builder().withVersion(UUID.randomUUID().toString()).build();
final Criterion criterion3 = new Criterion.Builder().withName(UUID.randomUUID().toString()).build();
final Criterion criterion4 = new Criterion
.Builder()
.withTags(Set.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build();
final List<Criterion> clusterCriteria = List.of(
criterion0,
criterion1,
criterion2
);
final CommandRequest command = new CommandRequest.Builder(
new CommandMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
CommandStatus.ACTIVE
)
.build(),
List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())
)
.withClusterCriteria(clusterCriteria)
.build();
final String id = this.service.saveCommand(command);
Assertions.assertThat(this.service.getClusterCriteriaForCommand(id)).isEqualTo(clusterCriteria);
this.service.addClusterCriterionForCommand(id, criterion3);
Assertions
.assertThat(this.service.getClusterCriteriaForCommand(id))
.hasSize(4)
.element(3)
.isEqualTo(criterion3);
// Illegal argument
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.removeClusterCriterionForCommand(id, 4));
this.service.removeClusterCriterionForCommand(id, 3);
Assertions.assertThat(this.service.getClusterCriteriaForCommand(id)).isEqualTo(clusterCriteria);
this.service.addClusterCriterionForCommand(id, criterion4, 1);
Assertions
.assertThat(this.service.getClusterCriteriaForCommand(id))
.hasSize(4)
.element(1)
.isEqualTo(criterion4);
this.service.removeClusterCriterionForCommand(id, 1);
Assertions.assertThat(this.service.getClusterCriteriaForCommand(id)).isEqualTo(clusterCriteria);
this.service.removeAllClusterCriteriaForCommand(id);
Assertions.assertThat(this.service.getClusterCriteriaForCommand(id)).isEmpty();
this.service.setClusterCriteriaForCommand(id, clusterCriteria);
Assertions.assertThat(this.service.getClusterCriteriaForCommand(id)).isEqualTo(clusterCriteria);
}
@Test
void testFindCommandsMatchingCriterion() throws Exception {
// Create some commands to test with
final List<Criterion> clusterCriteria = List.of(
new Criterion.Builder().withName("prodCluster").build()
);
final Command command0 = this.createTestCommand(null, null, clusterCriteria);
final Command command1 = this.createTestCommand(null, null, clusterCriteria);
final Command command2 = this.createTestCommand(UUID.randomUUID().toString(), null, clusterCriteria);
// Create two commands with supersets of command1 tags so that we can test that resolution
final Set<String> command3Tags = new HashSet<>(command1.getMetadata().getTags());
command3Tags.add(UUID.randomUUID().toString());
command3Tags.add(UUID.randomUUID().toString());
final Command command3 = this.createTestCommand(null, command3Tags, clusterCriteria);
final Set<String> command4Tags = new HashSet<>(command1.getMetadata().getTags());
command4Tags.add(UUID.randomUUID().toString());
final Command command4 = this.createTestCommand(null, command4Tags, clusterCriteria);
// Create a command that has no cluster criteria to enforce matching doesn't work if there is no cluster
// criteria
final Command command5 = this.createTestCommand(null, null, null);
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withId(command0.getId()).build(), true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(command0);
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withName(command2.getMetadata().getName()).build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(command2);
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withVersion(command1.getMetadata().getVersion()).build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(command1);
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withTags(command1.getMetadata().getTags()).build(),
true
)
)
.hasSize(3)
.containsExactlyInAnyOrder(command1, command3, command4);
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withTags(command4.getMetadata().getTags()).build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(command4);
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withTags(Set.of(UUID.randomUUID().toString())).build(),
true
)
)
.isEmpty();
// Everything
Assertions
.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder()
.withId(command3.getId())
.withName(command3.getMetadata().getName())
.withVersion(command3.getMetadata().getVersion())
.withTags(command1.getMetadata().getTags()) // should be subset
.build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(command3);
// Would match command5 if it had any cluster criteria
Assertions.assertThat(
this.service.findCommandsMatchingCriterion(
new Criterion.Builder().withId(command5.getId()).build(),
true
)
).isEmpty();
}
@Test
@DatabaseSetup("persistence/commands/updateStatusForUnusedCommands/before.xml")
@ExpectedDatabase(
value = "persistence/commands/updateStatusForUnusedCommands/after.xml",
assertionMode = DatabaseAssertionMode.NON_STRICT
)
void testUpdateStatusForUnusedCommands() {
final Instant present = Instant.parse("2020-03-24T00:00:00.000Z");
final Instant commandThreshold = present.minus(60, ChronoUnit.DAYS);
final int batchSize = 100;
Assertions
.assertThat(
this.service.updateStatusForUnusedCommands(
CommandStatus.INACTIVE,
commandThreshold,
EnumSet.of(CommandStatus.ACTIVE, CommandStatus.DEPRECATED),
batchSize
)
)
.isEqualTo(3);
}
@Test
@DatabaseSetup("persistence/commands/deleteUnusedCommands/setup.xml")
@ExpectedDatabase(
value = "persistence/commands/deleteUnusedCommands/expected.xml",
assertionMode = DatabaseAssertionMode.NON_STRICT
)
void testDeleteUnusedCommands() {
final Instant present = Instant.parse("2020-03-24T00:00:00.000Z");
final Instant createdThreshold = present.minus(1, ChronoUnit.DAYS);
Assertions.assertThat(this.commandRepository.count()).isEqualTo(8);
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(1L);
Assertions
.assertThat(
this.service.deleteUnusedCommands(
EnumSet.of(CommandStatus.INACTIVE, CommandStatus.DEPRECATED),
createdThreshold,
10
)
)
.isEqualTo(3);
Assertions.assertThat(this.criterionRepository.count()).isEqualTo(0L);
}
private Command createTestCommand(
@Nullable final String id,
@Nullable final Set<String> tags,
@Nullable final List<Criterion> clusterCriteria
) throws GenieCheckedException {
final CommandRequest.Builder requestBuilder = new CommandRequest.Builder(
new CommandMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
CommandStatus.ACTIVE
)
.withTags(
tags == null ? Set.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()) : tags
)
.build(),
List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())
);
if (id != null) {
requestBuilder.withRequestedId(id);
}
if (clusterCriteria != null) {
requestBuilder.withClusterCriteria(clusterCriteria);
}
final String commandId = this.service.saveCommand(requestBuilder.build());
return this.service.getCommand(commandId);
}
private Command copyCommandWithNewClusterCriteria(
final Command command,
@Nullable final List<Criterion> clusterCriteria
) {
return new Command(
command.getId(),
command.getCreated(),
command.getUpdated(),
command.getResources(),
new CommandMetadata.Builder(
command.getMetadata().getName(),
command.getMetadata().getUser(),
command.getMetadata().getVersion(),
command.getMetadata().getStatus()
)
.withMetadata(command.getMetadata().getMetadata().orElse(null))
.withDescription(command.getMetadata().getDescription().orElse(null))
.withTags(command.getMetadata().getTags())
.build(),
command.getExecutable(),
clusterCriteria,
command.getComputeResources(),
command.getImages()
);
}
}
| 2,365 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplClustersIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.data.services.impl.jpa;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.ClusterMetadata;
import com.netflix.genie.common.internal.dtos.ClusterRequest;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.annotation.Nullable;
import javax.validation.ConstraintViolationException;
import java.time.Instant;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.EnumSet;
import java.util.Set;
import java.util.UUID;
/**
* Integration tests for {@link JpaPersistenceServiceImpl} clusters specific functionality.
*
* @author tgianos
* @since 2.0.0
*/
class JpaPersistenceServiceImplClustersIntegrationTest extends JpaPersistenceServiceIntegrationTestBase {
private static final String CLUSTER_1_ID = "cluster1";
private static final String CLUSTER_1_USER = "tgianos";
private static final String CLUSTER_1_NAME = "h2prod";
private static final String CLUSTER_1_VERSION = "2.4.0";
private static final ClusterStatus CLUSTER_1_STATUS = ClusterStatus.UP;
private static final String CLUSTER_2_ID = "cluster2";
private static final String CLUSTER_2_USER = "amsharma";
private static final String CLUSTER_2_NAME = "h2query";
private static final String CLUSTER_2_VERSION = "2.4.0";
private static final ClusterStatus CLUSTER_2_STATUS = ClusterStatus.UP;
private static final Pageable PAGE = PageRequest.of(0, 10, Sort.Direction.DESC, "updated");
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetCluster() throws NotFoundException {
final Cluster cluster1 = this.service.getCluster(CLUSTER_1_ID);
Assertions.assertThat(cluster1.getId()).isEqualTo(CLUSTER_1_ID);
final ClusterMetadata cluster1Metadata = cluster1.getMetadata();
Assertions.assertThat(cluster1Metadata.getName()).isEqualTo(CLUSTER_1_NAME);
Assertions.assertThat(cluster1Metadata.getUser()).isEqualTo(CLUSTER_1_USER);
Assertions.assertThat(cluster1Metadata.getVersion()).isEqualTo(CLUSTER_1_VERSION);
Assertions.assertThat(cluster1Metadata.getStatus()).isEqualByComparingTo(CLUSTER_1_STATUS);
Assertions.assertThat(cluster1Metadata.getTags()).hasSize(3);
Assertions.assertThat(cluster1.getResources().getConfigs()).hasSize(1);
Assertions.assertThat(cluster1.getResources().getDependencies()).hasSize(2);
final Cluster cluster2 = this.service.getCluster(CLUSTER_2_ID);
Assertions.assertThat(cluster2.getId()).isEqualTo(CLUSTER_2_ID);
final ClusterMetadata cluster2Metadata = cluster2.getMetadata();
Assertions.assertThat(cluster2Metadata.getName()).isEqualTo(CLUSTER_2_NAME);
Assertions.assertThat(cluster2Metadata.getUser()).isEqualTo(CLUSTER_2_USER);
Assertions.assertThat(cluster2Metadata.getVersion()).isEqualTo(CLUSTER_2_VERSION);
Assertions.assertThat(cluster2Metadata.getStatus()).isEqualByComparingTo(CLUSTER_2_STATUS);
Assertions.assertThat(cluster2Metadata.getTags()).hasSize(3);
Assertions.assertThat(cluster2.getResources().getConfigs()).hasSize(2);
Assertions.assertThat(cluster2.getResources().getDependencies()).isEmpty();
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersByName() {
final Page<Cluster> clusters = this.service.findClusters(CLUSTER_2_NAME, null, null, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersByStatuses() {
final Set<ClusterStatus> statuses = EnumSet.of(ClusterStatus.UP);
final Page<Cluster> clusters = this.service.findClusters(null, statuses, null, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_1_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersByTags() {
final Set<String> tags = Sets.newHashSet("prod");
Page<Cluster> clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_1_ID);
tags.clear();
tags.add("hive");
clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_1_ID);
tags.add("somethingThatWouldNeverReallyExist");
clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
Assertions.assertThat(clusters.getContent()).isEmpty();
tags.clear();
clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_1_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersByMinUpdateTime() {
final ZonedDateTime time = ZonedDateTime.of(2014, Month.JULY.getValue(), 9, 2, 58, 59, 0, ZoneId.of("UTC"));
final Page<Cluster> clusters = this.service.findClusters(null, null, null, time.toInstant(), null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersByMaxUpdateTime() {
final ZonedDateTime time = ZonedDateTime.of(2014, Month.JULY.getValue(), 8, 3, 0, 0, 0, ZoneId.of("UTC"));
final Page<Cluster> clusters = this.service.findClusters(null, null, null, null, time.toInstant(), PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_1_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersDescending() {
//Default to order by Updated
final Page<Cluster> clusters = this.service.findClusters(null, null, null, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_1_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersAscending() {
final Pageable ascendingPage = PageRequest.of(0, 10, Sort.Direction.ASC, "updated");
//Default to order by Updated
final Page<Cluster> clusters = this.service.findClusters(null, null, null, null, null, ascendingPage);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_1_ID);
Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_2_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersOrderBysUser() {
final Pageable userPage = PageRequest.of(0, 10, Sort.Direction.DESC, "user");
final Page<Cluster> clusters = this.service.findClusters(null, null, null, null, null, userPage);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_1_ID);
Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_2_ID);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersOrderBysInvalidField() {
final Pageable badPage = PageRequest.of(0, 10, Sort.Direction.DESC, "I'mNotAValidField");
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.service.findClusters(null, null, null, null, null, badPage));
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersWithTags() {
final Set<ClusterStatus> activeStatuses = Sets.newHashSet(ClusterStatus.UP);
final Set<ClusterStatus> inactiveStatuses = Sets.newHashSet(ClusterStatus.TERMINATED);
final Set<String> tags = Sets.newHashSet("pig", "prod");
Page<Cluster> clusters;
clusters = this.service.findClusters(null, activeStatuses, tags, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_1_ID);
clusters = this.service.findClusters(null, inactiveStatuses, tags, null, null, PAGE);
Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(0);
Assertions.assertThat(clusters.getContent()).isEmpty();
}
@Test
void testCreateCluster() throws GenieCheckedException {
final Set<String> configs = Sets.newHashSet("a config", "another config", "yet another config");
final Set<String> dependencies = Sets.newHashSet("a dependency");
final String id = UUID.randomUUID().toString();
final ClusterRequest cluster = new ClusterRequest.Builder(
new ClusterMetadata.Builder(
CLUSTER_1_NAME,
CLUSTER_1_USER,
CLUSTER_1_VERSION,
ClusterStatus.OUT_OF_SERVICE
)
.build()
)
.withRequestedId(id)
.withResources(new ExecutionEnvironment(configs, dependencies, null))
.build();
this.service.saveCluster(cluster);
final Cluster created = this.service.getCluster(id);
Assertions.assertThat(created.getId()).isEqualTo(id);
final ClusterMetadata createdMetadata = created.getMetadata();
Assertions.assertThat(createdMetadata.getName()).isEqualTo(CLUSTER_1_NAME);
Assertions.assertThat(createdMetadata.getUser()).isEqualTo(CLUSTER_1_USER);
Assertions.assertThat(createdMetadata.getStatus()).isEqualByComparingTo(ClusterStatus.OUT_OF_SERVICE);
Assertions.assertThat(created.getResources().getConfigs()).isEqualTo(configs);
Assertions.assertThat(created.getResources().getDependencies()).isEqualTo(dependencies);
this.service.deleteCluster(id);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getCluster(id));
}
@Test
void testCreateClusterNoId() throws GenieCheckedException {
final Set<String> configs = Sets.newHashSet("a config", "another config", "yet another config");
final Set<String> dependencies = Sets.newHashSet("a dependency");
final ClusterRequest cluster = new ClusterRequest.Builder(
new ClusterMetadata.Builder(
CLUSTER_1_NAME,
CLUSTER_1_USER,
CLUSTER_1_VERSION,
ClusterStatus.OUT_OF_SERVICE
)
.build()
)
.withResources(new ExecutionEnvironment(configs, dependencies, null))
.build();
final String id = this.service.saveCluster(cluster);
final Cluster created = this.service.getCluster(id);
final ClusterMetadata createdMetadata = created.getMetadata();
Assertions.assertThat(createdMetadata.getName()).isEqualTo(CLUSTER_1_NAME);
Assertions.assertThat(createdMetadata.getUser()).isEqualTo(CLUSTER_1_USER);
Assertions.assertThat(createdMetadata.getStatus()).isEqualByComparingTo(ClusterStatus.OUT_OF_SERVICE);
Assertions.assertThat(created.getResources().getConfigs()).isEqualTo(configs);
Assertions.assertThat(created.getResources().getDependencies()).isEqualTo(dependencies);
this.service.deleteCluster(id);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getCluster(id));
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testUpdateClusterNoId() throws GenieCheckedException {
final Cluster getCluster = this.service.getCluster(CLUSTER_1_ID);
Assertions.assertThat(getCluster.getMetadata().getUser()).isEqualTo(CLUSTER_1_USER);
Assertions.assertThat(getCluster.getMetadata().getStatus()).isEqualByComparingTo(ClusterStatus.UP);
Assertions.assertThat(getCluster.getMetadata().getTags()).hasSize(3);
final Set<String> tags = Sets.newHashSet("tez", "yarn", "hadoop");
tags.addAll(getCluster.getMetadata().getTags());
final Cluster updateCluster = new Cluster(
getCluster.getId(),
getCluster.getCreated(),
getCluster.getUpdated(),
new ExecutionEnvironment(
getCluster.getResources().getConfigs(),
getCluster.getResources().getDependencies(),
getCluster.getResources().getSetupFile().orElse(null)
),
new ClusterMetadata.Builder(
getCluster.getMetadata().getName(),
CLUSTER_2_USER,
getCluster.getMetadata().getVersion(),
ClusterStatus.OUT_OF_SERVICE
)
.withTags(tags)
.withDescription(getCluster.getMetadata().getDescription().orElse(null))
.build()
);
this.service.updateCluster(CLUSTER_1_ID, updateCluster);
final Cluster updated = this.service.getCluster(CLUSTER_1_ID);
Assertions.assertThat(updated.getMetadata().getUser()).isEqualTo(CLUSTER_2_USER);
Assertions.assertThat(updated.getMetadata().getStatus()).isEqualByComparingTo(ClusterStatus.OUT_OF_SERVICE);
Assertions.assertThat(updated.getMetadata().getTags()).hasSize(6);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testUpdateClusterWithInvalidCluster() throws GenieCheckedException {
final Cluster getCluster = this.service.getCluster(CLUSTER_1_ID);
Assertions.assertThat(getCluster.getMetadata().getUser()).isEqualTo(CLUSTER_1_USER);
Assertions.assertThat(getCluster.getMetadata().getStatus()).isEqualByComparingTo(ClusterStatus.UP);
Assertions.assertThat(getCluster.getMetadata().getTags()).hasSize(3);
final Cluster updateCluster = new Cluster(
getCluster.getId(),
getCluster.getCreated(),
getCluster.getUpdated(),
new ExecutionEnvironment(
getCluster.getResources().getConfigs(),
getCluster.getResources().getDependencies(),
getCluster.getResources().getSetupFile().orElse(null)
),
new ClusterMetadata.Builder(
"",
getCluster.getMetadata().getUser(),
getCluster.getMetadata().getVersion(),
ClusterStatus.OUT_OF_SERVICE
)
.withTags(getCluster.getMetadata().getTags())
.withDescription(getCluster.getMetadata().getDescription().orElse(null))
.build()
);
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.service.updateCluster(CLUSTER_1_ID, updateCluster));
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testUpdateCreateAndUpdate() throws GenieCheckedException {
final Cluster getCluster = this.service.getCluster(CLUSTER_1_ID);
final Instant created = getCluster.getCreated();
final Instant updated = getCluster.getUpdated();
final Cluster updateCluster = new Cluster(
getCluster.getId(),
Instant.now(),
Instant.EPOCH,
new ExecutionEnvironment(
getCluster.getResources().getConfigs(),
getCluster.getResources().getDependencies(),
getCluster.getResources().getSetupFile().orElse(null)
),
new ClusterMetadata.Builder(
getCluster.getMetadata().getUser(),
getCluster.getMetadata().getUser(),
getCluster.getMetadata().getVersion(),
getCluster.getMetadata().getStatus()
)
.withTags(getCluster.getMetadata().getTags())
.withDescription(getCluster.getMetadata().getDescription().orElse(null))
.build()
);
this.service.updateCluster(CLUSTER_1_ID, updateCluster);
final Cluster updatedCluster = this.service.getCluster(CLUSTER_1_ID);
Assertions.assertThat(updatedCluster.getCreated()).isEqualTo(created);
Assertions.assertThat(updatedCluster.getUpdated()).isNotEqualTo(updated).isNotEqualTo(Instant.EPOCH);
Assertions.assertThat(updatedCluster.getMetadata().getTags()).isEqualTo(getCluster.getMetadata().getTags());
Assertions
.assertThat(updatedCluster.getResources().getConfigs())
.isEqualTo(getCluster.getResources().getConfigs());
Assertions
.assertThat(updatedCluster.getResources().getDependencies())
.isEqualTo(getCluster.getResources().getDependencies());
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testDeleteAll() throws GenieCheckedException {
Assertions
.assertThat(this.service.findClusters(null, null, null, null, null, PAGE).getNumberOfElements())
.isEqualTo(2);
this.service.deleteAllClusters();
Assertions
.assertThat(this.service.findClusters(null, null, null, null, null, PAGE).getContent())
.isEmpty();
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testDelete() throws GenieCheckedException {
Assertions.assertThat(this.clusterRepository.existsByUniqueId(CLUSTER_1_ID)).isTrue();
this.service.deleteCluster(CLUSTER_1_ID);
Assertions.assertThat(this.clusterRepository.existsByUniqueId(CLUSTER_1_ID)).isFalse();
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testAddConfigsToCluster() throws GenieCheckedException {
final String newConfig1 = UUID.randomUUID().toString();
final String newConfig2 = UUID.randomUUID().toString();
final String newConfig3 = UUID.randomUUID().toString();
final Set<String> newConfigs = Sets.newHashSet(newConfig1, newConfig2, newConfig3);
Assertions.assertThat(this.service.getConfigsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(1);
this.service.addConfigsToResource(CLUSTER_1_ID, newConfigs, Cluster.class);
Assertions.assertThat(this.service.getConfigsForResource(CLUSTER_1_ID, Cluster.class))
.hasSize(4)
.containsAll(newConfigs);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testUpdateConfigsForCluster() throws GenieCheckedException {
final String newConfig1 = UUID.randomUUID().toString();
final String newConfig2 = UUID.randomUUID().toString();
final String newConfig3 = UUID.randomUUID().toString();
final Set<String> newConfigs = Sets.newHashSet(newConfig1, newConfig2, newConfig3);
Assertions.assertThat(this.service.getConfigsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(1);
this.service.updateConfigsForResource(CLUSTER_1_ID, newConfigs, Cluster.class);
Assertions.assertThat(this.service.getConfigsForResource(CLUSTER_1_ID, Cluster.class))
.hasSize(3)
.containsAll(newConfigs);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetConfigsForCluster() throws GenieCheckedException {
Assertions.assertThat(this.service.getConfigsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(1);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testAddDependenciesToCluster() throws GenieCheckedException {
final String newDep1 = UUID.randomUUID().toString();
final String newDep2 = UUID.randomUUID().toString();
final String newDep3 = UUID.randomUUID().toString();
final Set<String> newDeps = Sets.newHashSet(newDep1, newDep2, newDep3);
Assertions.assertThat(this.service.getDependenciesForResource(CLUSTER_1_ID, Cluster.class)).hasSize(2);
this.service.addDependenciesToResource(CLUSTER_1_ID, newDeps, Cluster.class);
Assertions.assertThat(this.service.getDependenciesForResource(CLUSTER_1_ID, Cluster.class))
.hasSize(5)
.containsAll(newDeps);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testUpdateDependenciesForCluster() throws GenieCheckedException {
final String newDep1 = UUID.randomUUID().toString();
final String newDep2 = UUID.randomUUID().toString();
final String newDep3 = UUID.randomUUID().toString();
final Set<String> newDeps = Sets.newHashSet(newDep1, newDep2, newDep3);
Assertions.assertThat(this.service.getDependenciesForResource(CLUSTER_1_ID, Cluster.class)).hasSize(2);
this.service.updateDependenciesForResource(CLUSTER_1_ID, newDeps, Cluster.class);
Assertions.assertThat(this.service.getDependenciesForResource(CLUSTER_1_ID, Cluster.class))
.hasSize(3)
.containsAll(newDeps);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetDependenciesForCluster() throws GenieCheckedException {
Assertions.assertThat(this.service.getDependenciesForResource(CLUSTER_1_ID, Cluster.class)).hasSize(2);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testAddTagsToCluster() throws GenieCheckedException {
final String newTag1 = UUID.randomUUID().toString();
final String newTag2 = UUID.randomUUID().toString();
final String newTag3 = UUID.randomUUID().toString();
final Set<String> newTags = Sets.newHashSet(newTag1, newTag2, newTag3);
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(3);
this.service.addTagsToResource(CLUSTER_1_ID, newTags, Cluster.class);
Assertions
.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class))
.hasSize(6)
.containsAll(newTags);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testUpdateTagsForCluster() throws GenieCheckedException {
final String newTag1 = UUID.randomUUID().toString();
final String newTag2 = UUID.randomUUID().toString();
final String newTag3 = UUID.randomUUID().toString();
final Set<String> newTags = Sets.newHashSet(newTag1, newTag2, newTag3);
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(3);
this.service.updateTagsForResource(CLUSTER_1_ID, newTags, Cluster.class);
Assertions
.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class))
.hasSize(3)
.containsAll(newTags);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetTagsForCluster() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(3);
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testRemoveAllTagsForCluster() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).hasSize(3);
this.service.removeAllTagsForResource(CLUSTER_1_ID, Cluster.class);
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testRemoveTagForCluster() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).contains("prod");
this.service.removeTagForResource(CLUSTER_1_ID, "prod", Cluster.class);
Assertions.assertThat(this.service.getTagsForResource(CLUSTER_1_ID, Cluster.class)).doesNotContain("prod");
}
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testDeleteUnusedClusters() throws GenieCheckedException {
final int batchSize = 10;
Assertions.assertThat(this.clusterRepository.count()).isEqualTo(2L);
final String testCluster0Id = this.createTestCluster(null, null, ClusterStatus.OUT_OF_SERVICE).getId();
final Instant creationThreshold = Instant.now().plus(10L, ChronoUnit.MINUTES);
final Set<ClusterStatus> deleteStatuses = EnumSet.of(ClusterStatus.TERMINATED);
// Shouldn't delete any clusters as all are UP or OOS
Assertions
.assertThat(this.service.deleteUnusedClusters(deleteStatuses, creationThreshold, batchSize))
.isEqualTo(0);
// Add new up cluster
final String testCluster1Id = this.createTestCluster(null, null, ClusterStatus.UP).getId();
// All clusters are UP/OOS or attached to jobs
Assertions
.assertThat(this.service.deleteUnusedClusters(deleteStatuses, creationThreshold, batchSize))
.isEqualTo(0);
// Create Terminated Cluster
final String testCluster2Id = this.createTestCluster(null, null, ClusterStatus.TERMINATED).getId();
// All clusters are UP/OOS or attached to jobs
Assertions
.assertThat(this.service.deleteUnusedClusters(deleteStatuses, creationThreshold, batchSize))
.isEqualTo(1);
// Make sure it didn't delete any of the clusters we wanted
Assertions.assertThat(this.clusterRepository.existsByUniqueId(CLUSTER_1_ID)).isTrue();
Assertions.assertThat(this.clusterRepository.existsByUniqueId(CLUSTER_2_ID)).isTrue();
Assertions.assertThat(this.clusterRepository.existsByUniqueId(testCluster0Id)).isTrue();
Assertions.assertThat(this.clusterRepository.existsByUniqueId(testCluster1Id)).isTrue();
Assertions.assertThat(this.clusterRepository.existsByUniqueId(testCluster2Id)).isFalse();
}
@Test
void testFindClustersMatchingCriterion() throws Exception {
// Create some clusters to test with
final Cluster cluster0 = this.createTestCluster(null, null, null);
final Cluster cluster1 = this.createTestCluster(null, null, null);
final Cluster cluster2 = this.createTestCluster(UUID.randomUUID().toString(), null, null);
// Create two commands with supersets of cluster1 tags so that we can test that resolution
final Set<String> cluster3Tags = Sets.newHashSet(cluster1.getMetadata().getTags());
cluster3Tags.add(UUID.randomUUID().toString());
cluster3Tags.add(UUID.randomUUID().toString());
final Cluster cluster3 = this.createTestCluster(null, cluster3Tags, null);
final Set<String> cluster4Tags = Sets.newHashSet(cluster1.getMetadata().getTags());
cluster4Tags.add(UUID.randomUUID().toString());
final Cluster cluster4 = this.createTestCluster(null, cluster4Tags, null);
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withId(cluster0.getId()).build(), true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(cluster0);
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withName(cluster2.getMetadata().getName()).build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(cluster2);
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withVersion(cluster1.getMetadata().getVersion()).build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(cluster1);
// This comes from the init.xml
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withStatus(ClusterStatus.OUT_OF_SERVICE.name()).build(),
false
)
)
.isEmpty();
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withTags(cluster1.getMetadata().getTags()).build(),
true
)
)
.hasSize(3)
.containsExactlyInAnyOrder(cluster1, cluster3, cluster4);
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withTags(cluster4.getMetadata().getTags()).build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(cluster4);
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder().withTags(Sets.newHashSet(UUID.randomUUID().toString())).build(),
true
)
)
.isEmpty();
// Everything
Assertions
.assertThat(
this.service.findClustersMatchingCriterion(
new Criterion.Builder()
.withId(cluster3.getId())
.withName(cluster3.getMetadata().getName())
.withVersion(cluster3.getMetadata().getVersion())
.withTags(cluster1.getMetadata().getTags()) // should be subset
.build(),
true
)
)
.hasSize(1)
.containsExactlyInAnyOrder(cluster3);
}
@Test
void testFindClustersMatchingAnyCriterion() throws Exception {
// Create some clusters to test with
final Cluster cluster0 = this.createTestCluster(null, null, ClusterStatus.UP);
final Cluster cluster1 = this.createTestCluster(null, null, ClusterStatus.UP);
final Cluster cluster2 = this.createTestCluster(UUID.randomUUID().toString(), null, ClusterStatus.UP);
// Create two commands with supersets of cluster1 tags so that we can test that resolution
final Set<String> cluster1Tags = cluster1.getMetadata().getTags();
final Set<String> cluster3Tags = Sets.newHashSet(cluster1Tags);
cluster3Tags.add(UUID.randomUUID().toString());
cluster3Tags.add(UUID.randomUUID().toString());
final Cluster cluster3 = this.createTestCluster(null, cluster3Tags, ClusterStatus.UP);
final Set<String> cluster4Tags = Sets.newHashSet(cluster1.getMetadata().getTags());
cluster4Tags.add(UUID.randomUUID().toString());
final Cluster cluster4 = this.createTestCluster(null, cluster4Tags, ClusterStatus.UP);
final Cluster cluster5 = this.createTestCluster(null, cluster1Tags, ClusterStatus.TERMINATED);
final Cluster cluster6 = this.createTestCluster(null, null, ClusterStatus.OUT_OF_SERVICE);
Assertions
.assertThat(
this.service.findClustersMatchingAnyCriterion(
Sets.newHashSet(
new Criterion.Builder().withId(cluster0.getId()).build(),
new Criterion.Builder().withName(cluster2.getMetadata().getName()).build(),
new Criterion.Builder().withVersion(cluster1.getMetadata().getVersion()).build(),
new Criterion.Builder().withStatus(ClusterStatus.OUT_OF_SERVICE.name()).build(),
new Criterion.Builder().withTags(cluster1.getMetadata().getTags()).build(),
new Criterion.Builder().withTags(cluster4.getMetadata().getTags()).build(),
new Criterion.Builder().withTags(Sets.newHashSet(UUID.randomUUID().toString())).build()
),
true
)
)
.hasSize(6)
.containsExactlyInAnyOrder(cluster0, cluster1, cluster2, cluster3, cluster4, cluster6);
Assertions
.assertThat(
this.service.findClustersMatchingAnyCriterion(
Sets.newHashSet(
new Criterion.Builder().withId(cluster0.getId()).build(),
new Criterion.Builder().withName(cluster2.getMetadata().getName()).build(),
new Criterion.Builder().withVersion(cluster1.getMetadata().getVersion()).build(),
new Criterion.Builder().withStatus(ClusterStatus.OUT_OF_SERVICE.name()).build(),
new Criterion.Builder().withTags(cluster1.getMetadata().getTags()).build(),
new Criterion.Builder().withTags(cluster4.getMetadata().getTags()).build(),
new Criterion.Builder().withTags(Sets.newHashSet(UUID.randomUUID().toString())).build()
),
false
)
)
.hasSize(7)
.containsExactlyInAnyOrder(cluster0, cluster1, cluster2, cluster3, cluster4, cluster5, cluster6);
}
private Cluster createTestCluster(
@Nullable final String id,
@Nullable final Set<String> tags,
@Nullable final ClusterStatus status
) throws GenieCheckedException {
final ClusterRequest.Builder requestBuilder = new ClusterRequest.Builder(
new ClusterMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
status == null ? ClusterStatus.UP : status
)
.withTags(
tags == null ? Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()) : tags
)
.build()
);
if (id != null) {
requestBuilder.withRequestedId(id);
}
final String clusterId = this.service.saveCluster(requestBuilder.build());
return this.service.getCluster(clusterId);
}
}
| 2,366 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplApplicationsIntegrationTest.java | /*
*
* Copyright 2015 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.genie.web.data.services.impl.jpa;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import com.github.springtestdbunit.assertion.DatabaseAssertionMode;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Application;
import com.netflix.genie.common.internal.dtos.ApplicationMetadata;
import com.netflix.genie.common.internal.dtos.ApplicationRequest;
import com.netflix.genie.common.internal.dtos.ApplicationStatus;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.validation.ConstraintViolationException;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
/**
* Integration tests for {@link JpaPersistenceServiceImpl} focusing on application related functionality.
*
* @author tgianos
* @since 2.0.0
*/
class JpaPersistenceServiceImplApplicationsIntegrationTest extends JpaPersistenceServiceIntegrationTestBase {
private static final String APP_1_ID = "app1";
private static final String APP_1_NAME = "tez";
private static final String APP_1_USER = "tgianos";
private static final String APP_1_VERSION = "1.2.3";
private static final ApplicationStatus APP_1_STATUS = ApplicationStatus.INACTIVE;
private static final String COMMAND_1_ID = "command1";
private static final String APP_2_ID = "app2";
private static final String APP_2_NAME = "spark";
private static final String APP_2_USER = "amsharma";
private static final String APP_2_VERSION = "4.5.6";
private static final String APP_2_TYPE = "spark";
private static final ApplicationStatus APP_2_STATUS = ApplicationStatus.ACTIVE;
private static final String APP_3_ID = "app3";
private static final String APP_3_NAME = "storm";
private static final String APP_3_USER = "tgianos";
private static final String APP_3_VERSION = "7.8.9";
private static final String APP_3_TYPE = "storm";
private static final ApplicationStatus APP_3_STATUS = ApplicationStatus.DEPRECATED;
private static final Pageable PAGEABLE = PageRequest.of(0, 10, Sort.Direction.DESC, "updated");
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplication() throws NotFoundException {
final Application app = this.service.getApplication(APP_1_ID);
Assertions.assertThat(app.getId()).isEqualTo(APP_1_ID);
final ApplicationMetadata appMetadata = app.getMetadata();
Assertions.assertThat(appMetadata.getName()).isEqualTo(APP_1_NAME);
Assertions.assertThat(appMetadata.getUser()).isEqualTo(APP_1_USER);
Assertions.assertThat(appMetadata.getVersion()).isEqualTo(APP_1_VERSION);
Assertions.assertThat(appMetadata.getStatus()).isEqualByComparingTo(APP_1_STATUS);
Assertions.assertThat(appMetadata.getType()).isNotPresent();
Assertions.assertThat(appMetadata.getTags()).hasSize(1);
Assertions.assertThat(app.getResources().getConfigs()).hasSize(2);
Assertions.assertThat(app.getResources().getDependencies()).hasSize(2);
final Application app2 = this.service.getApplication(APP_2_ID);
Assertions.assertThat(app2.getId()).isEqualTo(APP_2_ID);
final ApplicationMetadata app2Metadata = app2.getMetadata();
Assertions.assertThat(app2Metadata.getName()).isEqualTo(APP_2_NAME);
Assertions.assertThat(app2Metadata.getUser()).isEqualTo(APP_2_USER);
Assertions.assertThat(app2Metadata.getVersion()).isEqualTo(APP_2_VERSION);
Assertions.assertThat(app2Metadata.getStatus()).isEqualByComparingTo(APP_2_STATUS);
Assertions.assertThat(app2Metadata.getType()).isPresent().contains(APP_2_TYPE);
Assertions.assertThat(app2Metadata.getTags()).hasSize(2);
Assertions.assertThat(app2.getResources().getConfigs()).hasSize(2);
Assertions.assertThat(app2.getResources().getDependencies()).hasSize(1);
final Application app3 = this.service.getApplication(APP_3_ID);
Assertions.assertThat(app3.getId()).isEqualTo(APP_3_ID);
final ApplicationMetadata app3Metadata = app3.getMetadata();
Assertions.assertThat(app3Metadata.getName()).isEqualTo(APP_3_NAME);
Assertions.assertThat(app3Metadata.getUser()).isEqualTo(APP_3_USER);
Assertions.assertThat(app3Metadata.getVersion()).isEqualTo(APP_3_VERSION);
Assertions.assertThat(app3Metadata.getStatus()).isEqualByComparingTo(APP_3_STATUS);
Assertions.assertThat(app3Metadata.getType()).isPresent().contains(APP_3_TYPE);
Assertions.assertThat(app3Metadata.getTags()).hasSize(1);
Assertions.assertThat(app3.getResources().getConfigs()).hasSize(1);
Assertions.assertThat(app3.getResources().getDependencies()).hasSize(2);
}
@Test
void testGetApplicationEmpty() {
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.service.getApplication(""));
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsByName() {
final Page<Application> apps = this.service.findApplications(APP_2_NAME, null, null, null, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_2_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsByUser() {
final Page<Application> apps = this.service.findApplications(null, APP_1_USER, null, null, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_3_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsByStatuses() {
final Set<ApplicationStatus> statuses = Sets.newHashSet(ApplicationStatus.ACTIVE, ApplicationStatus.INACTIVE);
final Page<Application> apps = this.service.findApplications(null, null, statuses, null, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(2);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_2_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsByTags() {
final Set<String> tags = Sets.newHashSet("prod");
Page<Application> apps = this.service.findApplications(null, null, null, tags, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_3_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_2_ID);
Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_1_ID);
tags.add("yarn");
apps = this.service.findApplications(null, null, null, tags, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_2_ID);
tags.add("somethingThatWouldNeverReallyExist");
apps = this.service.findApplications(null, null, null, tags, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(0);
tags.clear();
apps = this.service.findApplications(null, null, null, tags, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_3_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_2_ID);
Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsByTagsWhenOneDoesntExist() {
final Set<String> tags = Sets.newHashSet("prod", UUID.randomUUID().toString());
final Page<Application> apps = this.service.findApplications(null, null, null, tags, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(0);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsByType() {
final Page<Application> apps = this.service.findApplications(null, null, null, null, APP_2_TYPE, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(1);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_2_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsDescending() {
//Default to order by Updated
final Page<Application> apps = this.service.findApplications(null, null, null, null, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_3_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_2_ID);
Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsAscending() {
//Default to order by Updated
final Pageable ascendingPage = PageRequest.of(0, 10, Sort.Direction.ASC, "updated");
final Page<Application> apps = this.service.findApplications(null, null, null, null, null, ascendingPage);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_1_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_2_ID);
Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_3_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsOrderBysDefault() {
//Default to order by Updated
final Page<Application> apps = this.service.findApplications(null, null, null, null, null, PAGEABLE);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_3_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_2_ID);
Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_1_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsOrderBysName() {
final Pageable orderByNamePage = PageRequest.of(0, 10, Sort.Direction.DESC, "name");
final Page<Application> apps = this.service.findApplications(null, null, null, null, null, orderByNamePage);
Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_1_ID);
Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_3_ID);
Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_2_ID);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsOrderBysInvalidField() {
final Pageable orderByInvalidPage = PageRequest.of(0, 10, Sort.Direction.DESC, "I'mNotAValidField");
Assertions
.assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.service.findApplications(null, null, null, null, null, orderByInvalidPage));
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsWithTags() {
final Set<ApplicationStatus> inactiveStatuses = Sets.newHashSet(ApplicationStatus.INACTIVE);
final Set<ApplicationStatus> activeStatuses = Sets.newHashSet(ApplicationStatus.ACTIVE);
final Set<String> tags = Sets.newHashSet("prod", "yarn");
Page<Application> apps;
apps = this.service.findApplications(null, null, activeStatuses, tags, null, PAGEABLE);
Assertions.assertThat(apps.getTotalElements()).isEqualTo(1);
Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_2_ID);
apps = this.service.findApplications(null, null, inactiveStatuses, tags, null, PAGEABLE);
Assertions.assertThat(apps.getTotalElements()).isEqualTo(0);
}
@Test
void testCreateApplication() throws GenieCheckedException {
final String id = UUID.randomUUID().toString();
final ApplicationRequest app = new ApplicationRequest.Builder(
new ApplicationMetadata.Builder(
APP_1_NAME,
APP_1_USER,
APP_1_VERSION,
ApplicationStatus.ACTIVE
)
.build()
)
.withRequestedId(id)
.build();
final String createdId = this.service.saveApplication(app);
Assertions.assertThat(createdId).isEqualTo(id);
final Application created = this.service.getApplication(id);
Assertions.assertThat(created.getId()).isEqualTo(createdId);
final ApplicationMetadata appMetadata = created.getMetadata();
Assertions.assertThat(appMetadata.getName()).isEqualTo(APP_1_NAME);
Assertions.assertThat(appMetadata.getUser()).isEqualTo(APP_1_USER);
Assertions.assertThat(appMetadata.getStatus()).isEqualByComparingTo(ApplicationStatus.ACTIVE);
this.service.deleteApplication(id);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getApplication(id));
}
@Test
void testCreateApplicationNoId() throws GenieCheckedException {
final ApplicationRequest app = new ApplicationRequest.Builder(
new ApplicationMetadata.Builder(
APP_1_NAME,
APP_1_USER,
APP_1_VERSION,
ApplicationStatus.ACTIVE
)
.build()
)
.build();
final String id = this.service.saveApplication(app);
final Application created = this.service.getApplication(id);
final ApplicationMetadata appMetadata = created.getMetadata();
Assertions.assertThat(appMetadata.getName()).isEqualTo(APP_1_NAME);
Assertions.assertThat(appMetadata.getUser()).isEqualTo(APP_1_USER);
Assertions.assertThat(appMetadata.getStatus()).isEqualByComparingTo(ApplicationStatus.ACTIVE);
this.service.deleteApplication(id);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getApplication(id));
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testUpdateApplication() throws GenieCheckedException {
final Application getApp = this.service.getApplication(APP_1_ID);
Assertions.assertThat(getApp.getMetadata().getUser()).isEqualTo(APP_1_USER);
Assertions.assertThat(getApp.getMetadata().getStatus()).isEqualByComparingTo(ApplicationStatus.INACTIVE);
Assertions.assertThat(getApp.getMetadata().getTags().size()).isEqualTo(1);
final Instant updateTime = getApp.getUpdated();
final Set<String> tags = Sets.newHashSet("prod", "tez", "yarn", "hadoop");
tags.addAll(getApp.getMetadata().getTags());
final Application updateApp = new Application(
getApp.getId(),
getApp.getCreated(),
getApp.getUpdated(),
getApp.getResources(),
new ApplicationMetadata.Builder(
getApp.getMetadata().getName(),
APP_2_USER,
getApp.getMetadata().getVersion(),
ApplicationStatus.ACTIVE
)
.withDescription(getApp.getMetadata().getDescription().orElse(null))
.withType(getApp.getMetadata().getType().orElse(null))
.withTags(tags)
.build()
);
this.service.updateApplication(APP_1_ID, updateApp);
final Application updated = this.service.getApplication(APP_1_ID);
Assertions.assertThat(updated.getUpdated()).isNotEqualTo(updateTime);
Assertions.assertThat(updated.getMetadata().getUser()).isEqualTo(APP_2_USER);
Assertions.assertThat(updated.getMetadata().getStatus()).isEqualByComparingTo(ApplicationStatus.ACTIVE);
Assertions.assertThat(updated.getMetadata().getTags()).isEqualTo(tags);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testUpdateCreateAndUpdate() throws GenieCheckedException {
final Application init = this.service.getApplication(APP_1_ID);
final Instant created = init.getCreated();
final Instant updated = init.getUpdated();
this.service.updateApplication(APP_1_ID, init);
final Application updatedApp = this.service.getApplication(APP_1_ID);
Assertions.assertThat(updatedApp.getCreated()).isEqualTo(created);
Assertions.assertThat(updatedApp.getUpdated()).isNotEqualTo(updated).isNotEqualTo(Instant.EPOCH);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testDeleteAll() throws GenieCheckedException {
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(3L);
// To solve referential integrity problem
this.commandRepository.findByUniqueId(COMMAND_1_ID).ifPresent(this.commandRepository::delete);
this.commandRepository.flush();
this.service.deleteAllApplications();
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(0L);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testDelete() throws GenieCheckedException {
this.service.deleteApplication(APP_3_ID);
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getApplication(APP_3_ID));
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testAddConfigsToApplication() throws GenieCheckedException {
final String newConfig1 = UUID.randomUUID().toString();
final String newConfig2 = UUID.randomUUID().toString();
final String newConfig3 = UUID.randomUUID().toString();
final Set<String> newConfigs = Sets.newHashSet(newConfig1, newConfig2, newConfig3);
Assertions.assertThat(this.service.getConfigsForResource(APP_1_ID, Application.class)).hasSize(2);
this.service.addConfigsToResource(APP_1_ID, newConfigs, Application.class);
final Set<String> finalConfigs = this.service.getConfigsForResource(APP_1_ID, Application.class);
Assertions.assertThat(finalConfigs).hasSize(5).containsAll(newConfigs);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testUpdateConfigsForApplication() throws GenieCheckedException {
final String newConfig1 = UUID.randomUUID().toString();
final String newConfig2 = UUID.randomUUID().toString();
final String newConfig3 = UUID.randomUUID().toString();
final Set<String> newConfigs = Sets.newHashSet(newConfig1, newConfig2, newConfig3);
Assertions.assertThat(this.service.getConfigsForResource(APP_1_ID, Application.class)).hasSize(2);
this.service.updateConfigsForResource(APP_1_ID, newConfigs, Application.class);
final Set<String> finalConfigs = this.service.getConfigsForResource(APP_1_ID, Application.class);
Assertions.assertThat(finalConfigs).hasSize(3).containsAll(newConfigs);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetConfigsForApplication() throws GenieCheckedException {
Assertions.assertThat(this.service.getConfigsForResource(APP_1_ID, Application.class)).hasSize(2);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testRemoveAllConfigsForApplication() throws GenieCheckedException {
Assertions.assertThat(this.service.getConfigsForResource(APP_1_ID, Application.class)).hasSize(2);
this.service.removeAllConfigsForResource(APP_1_ID, Application.class);
Assertions.assertThat(this.service.getConfigsForResource(APP_1_ID, Application.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testRemoveConfigForApplication() throws GenieCheckedException {
final Set<String> configs = this.service.getConfigsForResource(APP_1_ID, Application.class);
Assertions.assertThat(configs).hasSize(2);
final String removedConfig = configs.iterator().next();
this.service.removeConfigForResource(APP_1_ID, removedConfig, Application.class);
Assertions
.assertThat(this.service.getConfigsForResource(APP_1_ID, Application.class))
.doesNotContain(removedConfig);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testAddDependenciesToApplication() throws GenieCheckedException {
final String newDependency1 = UUID.randomUUID().toString();
final String newDependency2 = UUID.randomUUID().toString();
final String newDependency3 = UUID.randomUUID().toString();
final Set<String> newDependencies = Sets.newHashSet(newDependency1, newDependency2, newDependency3);
Assertions.assertThat(this.service.getDependenciesForResource(APP_1_ID, Application.class)).hasSize(2);
this.service.addDependenciesToResource(APP_1_ID, newDependencies, Application.class);
final Set<String> finalDependencies = this.service.getDependenciesForResource(APP_1_ID, Application.class);
Assertions.assertThat(finalDependencies).hasSize(5).containsAll(newDependencies);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testUpdateDependenciesForApplication() throws GenieCheckedException {
final String newDependency1 = UUID.randomUUID().toString();
final String newDependency2 = UUID.randomUUID().toString();
final String newDependency3 = UUID.randomUUID().toString();
final Set<String> newDependencies = Sets.newHashSet(newDependency1, newDependency2, newDependency3);
Assertions.assertThat(this.service.getDependenciesForResource(APP_1_ID, Application.class)).hasSize(2);
this.service.updateDependenciesForResource(APP_1_ID, newDependencies, Application.class);
final Set<String> finalDependencies = this.service.getDependenciesForResource(APP_1_ID, Application.class);
Assertions.assertThat(finalDependencies).hasSize(3).containsAll(newDependencies);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetDependenciesForApplication() throws GenieCheckedException {
Assertions.assertThat(this.service.getDependenciesForResource(APP_1_ID, Application.class)).hasSize(2);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testRemoveAllDependenciesForApplication() throws GenieCheckedException {
Assertions.assertThat(this.service.getDependenciesForResource(APP_1_ID, Application.class)).hasSize(2);
this.service.removeAllDependenciesForResource(APP_1_ID, Application.class);
Assertions.assertThat(this.service.getDependenciesForResource(APP_1_ID, Application.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testRemoveDependencyForApplication() throws GenieCheckedException {
final Set<String> dependencies = this.service.getDependenciesForResource(APP_1_ID, Application.class);
Assertions.assertThat(dependencies).hasSize(2);
final String removedDependency = dependencies.iterator().next();
this.service.removeDependencyForResource(APP_1_ID, removedDependency, Application.class);
Assertions
.assertThat(this.service.getDependenciesForResource(APP_1_ID, Application.class))
.doesNotContain(removedDependency);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testAddTagsToApplication() throws GenieCheckedException {
final String newTag1 = UUID.randomUUID().toString();
final String newTag2 = UUID.randomUUID().toString();
final String newTag3 = UUID.randomUUID().toString();
final Set<String> newTags = Sets.newHashSet(newTag1, newTag2, newTag3);
Assertions.assertThat(this.service.getTagsForResource(APP_1_ID, Application.class)).hasSize(1);
this.service.addTagsToResource(APP_1_ID, newTags, Application.class);
final Set<String> finalTags = this.service.getTagsForResource(APP_1_ID, Application.class);
Assertions.assertThat(finalTags).hasSize(4).containsAll(newTags);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testUpdateTagsForApplication() throws GenieCheckedException {
final String newTag1 = UUID.randomUUID().toString();
final String newTag2 = UUID.randomUUID().toString();
final String newTag3 = UUID.randomUUID().toString();
final Set<String> newTags = Sets.newHashSet(newTag1, newTag2, newTag3);
Assertions.assertThat(this.service.getTagsForResource(APP_1_ID, Application.class)).hasSize(1);
this.service.updateTagsForResource(APP_1_ID, newTags, Application.class);
final Set<String> finalTags = this.service.getTagsForResource(APP_1_ID, Application.class);
Assertions.assertThat(finalTags).hasSize(3).containsAll(newTags);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetTagsForApplication() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(APP_1_ID, Application.class)).hasSize(1);
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testRemoveAllTagsForApplication() throws GenieCheckedException {
Assertions.assertThat(this.service.getTagsForResource(APP_1_ID, Application.class)).hasSize(1);
this.service.removeAllTagsForResource(APP_1_ID, Application.class);
Assertions.assertThat(this.service.getTagsForResource(APP_1_ID, Application.class)).isEmpty();
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testRemoveTagForApplication() throws GenieCheckedException {
final Set<String> tags = this.service.getTagsForResource(APP_1_ID, Application.class);
Assertions.assertThat(tags).contains("prod");
this.service.removeTagForResource(APP_1_ID, "prod", Application.class);
Assertions.assertThat(this.service.getTagsForResource(APP_1_ID, Application.class)).doesNotContain("prod");
}
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetCommandsForApplication() throws GenieCheckedException {
final Set<Command> commands = this.service.getCommandsForApplication(APP_1_ID, null);
Assertions
.assertThat(commands)
.hasSize(1)
.hasOnlyOneElementSatisfying(command -> Assertions.assertThat(command.getId()).isEqualTo(COMMAND_1_ID));
}
@Test
void testGetCommandsForApplicationNoId() {
Assertions
.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> this.service.getCommandsForApplication("", null));
}
@Test
@DatabaseSetup("persistence/applications/deleteUnusedApplications/before.xml")
@ExpectedDatabase(
value = "persistence/applications/deleteUnusedApplications/after.xml",
assertionMode = DatabaseAssertionMode.NON_STRICT
)
void testDeleteUnusedApplications() {
Assertions.assertThat(this.applicationRepository.existsByUniqueId("app2")).isTrue();
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(6);
final Instant createdThreshold = Instant.parse("2020-03-10T02:44:00.000Z");
Assertions.assertThat(this.service.deleteUnusedApplications(createdThreshold, 10)).isEqualTo(1L);
Assertions.assertThat(this.applicationRepository.count()).isEqualTo(5);
Assertions.assertThat(this.applicationRepository.existsByUniqueId("app2")).isFalse();
}
}
| 2,367 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplFilesIntegrationTest.java | /*
*
* Copyright 2017 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.genie.web.data.services.impl.jpa;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.ApplicationMetadata;
import com.netflix.genie.common.internal.dtos.ApplicationRequest;
import com.netflix.genie.common.internal.dtos.ApplicationStatus;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.UUID;
/**
* Integration tests for the {@link JpaPersistenceServiceImpl} focusing on file APIs.
*
* @author tgianos
* @since 3.3.0
*/
class JpaPersistenceServiceImplFilesIntegrationTest extends JpaPersistenceServiceIntegrationTestBase {
@Test
void canDeleteUnusedFiles() throws GenieCheckedException {
Assertions.assertThat(this.fileRepository.count()).isEqualTo(0L);
final String file1 = UUID.randomUUID().toString();
final String file2 = UUID.randomUUID().toString();
final String file3 = UUID.randomUUID().toString();
final String file4 = UUID.randomUUID().toString();
final String file5 = UUID.randomUUID().toString();
this.fileRepository.saveAndFlush(new FileEntity(file1));
this.fileRepository.saveAndFlush(new FileEntity(file4));
final ApplicationRequest app = new ApplicationRequest.Builder(
new ApplicationMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
ApplicationStatus.ACTIVE
).build())
.withResources(
new ExecutionEnvironment(
Sets.newHashSet(file3),
Sets.newHashSet(file2),
file5
)
)
.build();
// Create a relationship between files and some resource in the system that should block them from being deleted
this.service.saveApplication(app);
Assertions.assertThat(this.fileRepository.existsByFile(file1)).isTrue();
Assertions.assertThat(this.fileRepository.existsByFile(file2)).isTrue();
Assertions.assertThat(this.fileRepository.existsByFile(file3)).isTrue();
Assertions.assertThat(this.fileRepository.existsByFile(file4)).isTrue();
Assertions.assertThat(this.fileRepository.existsByFile(file5)).isTrue();
Assertions.assertThat(this.service.deleteUnusedFiles(Instant.EPOCH, Instant.now(), 10)).isEqualTo(2L);
Assertions.assertThat(this.fileRepository.existsByFile(file1)).isFalse();
Assertions.assertThat(this.fileRepository.existsByFile(file2)).isTrue();
Assertions.assertThat(this.fileRepository.existsByFile(file3)).isTrue();
Assertions.assertThat(this.fileRepository.existsByFile(file4)).isFalse();
Assertions.assertThat(this.fileRepository.existsByFile(file5)).isTrue();
}
}
| 2,368 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImplJobsIntegrationTest.java | /*
*
* Copyright 2016 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.genie.web.data.services.impl.jpa;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.ClusterStatus;
import com.netflix.genie.common.dto.CommandStatus;
import com.netflix.genie.common.dto.UserResourcesSummary;
import com.netflix.genie.common.dto.search.BaseSearchResult;
import com.netflix.genie.common.dto.search.JobSearchResult;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieNotFoundException;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.AgentClientMetadata;
import com.netflix.genie.common.internal.dtos.AgentConfigRequest;
import com.netflix.genie.common.internal.dtos.ApiClientMetadata;
import com.netflix.genie.common.internal.dtos.Application;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.ComputeResources;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.ExecutionEnvironment;
import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria;
import com.netflix.genie.common.internal.dtos.FinishedJob;
import com.netflix.genie.common.internal.dtos.Image;
import com.netflix.genie.common.internal.dtos.JobEnvironment;
import com.netflix.genie.common.internal.dtos.JobEnvironmentRequest;
import com.netflix.genie.common.internal.dtos.JobMetadata;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.dtos.JobRequestMetadata;
import com.netflix.genie.common.internal.dtos.JobSpecification;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException;
import com.netflix.genie.test.suppliers.RandomSuppliers;
import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity;
import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.JobInfoAggregate;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobSpecificationProjection;
import com.netflix.genie.web.dtos.JobSubmission;
import com.netflix.genie.web.dtos.ResolvedJob;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import org.assertj.core.api.Assertions;
import org.hibernate.Hibernate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Integration tests for {@link JpaPersistenceServiceImpl} focusing on the jobs APIs.
*
* @author tgianos
* @since 3.0.0
*/
class JpaPersistenceServiceImplJobsIntegrationTest extends JpaPersistenceServiceIntegrationTestBase {
private static final String JOB_1_ID = "job1";
private static final String JOB_2_ID = "job2";
private static final String JOB_3_ID = "job3";
private static final String AGENT_JOB_1 = "agentJob1";
private static final String AGENT_JOB_2 = "agentJob2";
// Job Request fields
private static final int CPU_REQUESTED = 2;
private static final long MEMORY_REQUESTED = 1024L;
private static final int TIMEOUT_REQUESTED = 84500;
// Job Metadata fields
private static final int NUM_ATTACHMENTS = 3;
private static final long TOTAL_SIZE_ATTACHMENTS = 38023423L;
// Job fields
private static final String ARCHIVE_LOCATION = UUID.randomUUID().toString();
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canDeleteJobsCreatedBeforeDateWithBatchSizeGreaterThanExpectedTotalDeletions() {
final Instant cal = ZonedDateTime
.of(2016, Month.JANUARY.getValue(), 1, 0, 0, 0, 0, ZoneId.of("UTC"))
.toInstant();
final long deleted = this.service.deleteJobsCreatedBefore(cal, JobStatus.getActiveStatuses(), 10);
Assertions.assertThat(deleted).isEqualTo(1L);
Assertions.assertThat(this.jobRepository.count()).isEqualTo(2L);
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_1_ID)).isFalse();
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_2_ID)).isTrue();
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_3_ID)).isTrue();
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canDeleteJobsCreatedBeforeDateWithBatchSizeLessThanExpectedTotalDeletions() {
final Instant cal = ZonedDateTime
.of(2016, Month.JANUARY.getValue(), 1, 0, 0, 0, 0, ZoneId.of("UTC"))
.toInstant();
final long deleted = this.service.deleteJobsCreatedBefore(cal, JobStatus.getActiveStatuses(), 1);
Assertions.assertThat(deleted).isEqualTo(1L);
Assertions.assertThat(this.jobRepository.count()).isEqualTo(2L);
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_3_ID)).isTrue();
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canDeleteJobsRegardlessOfStatus() {
final Instant cal = ZonedDateTime
.of(2016, Month.JANUARY.getValue(), 1, 0, 0, 0, 0, ZoneId.of("UTC"))
.toInstant();
final long deleted = this.service.deleteJobsCreatedBefore(cal, Sets.newHashSet(), 10);
Assertions.assertThat(deleted).isEqualTo(2L);
Assertions.assertThat(this.jobRepository.count()).isEqualTo(1L);
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_1_ID)).isFalse();
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_2_ID)).isFalse();
Assertions.assertThat(this.jobRepository.existsByUniqueId(JOB_3_ID)).isTrue();
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canSaveAndVerifyJobSubmissionWithoutAttachments() throws IOException, GenieCheckedException {
final String job0Id = UUID.randomUUID().toString();
final String job3Id = UUID.randomUUID().toString();
final JobRequest jobRequest0 = this.createJobRequest(job0Id, UUID.randomUUID().toString());
final JobRequest jobRequest1 = this.createJobRequest(null, UUID.randomUUID().toString());
final JobRequest jobRequest2 = this.createJobRequest(JOB_3_ID, UUID.randomUUID().toString());
final JobRequest jobRequest3 = this.createJobRequest(job3Id, null);
final JobRequestMetadata jobRequestMetadata = this.createJobRequestMetadata(
true,
NUM_ATTACHMENTS,
TOTAL_SIZE_ATTACHMENTS
);
String id = this.service.saveJobSubmission(new JobSubmission.Builder(jobRequest0, jobRequestMetadata).build());
Assertions.assertThat(id).isEqualTo(job0Id);
this.validateSavedJobSubmission(id, jobRequest0, jobRequestMetadata);
id = this.service.saveJobSubmission(new JobSubmission.Builder(jobRequest1, jobRequestMetadata).build());
Assertions.assertThat(id).isNotBlank();
this.validateSavedJobSubmission(id, jobRequest1, jobRequestMetadata);
id = this.service.saveJobSubmission(new JobSubmission.Builder(jobRequest3, jobRequestMetadata).build());
Assertions.assertThat(id).isEqualTo(job3Id);
this.validateSavedJobSubmission(id, jobRequest3, jobRequestMetadata);
Assertions
.assertThatExceptionOfType(IdAlreadyExistsException.class)
.isThrownBy(
() -> this.service.saveJobSubmission(
new JobSubmission.Builder(jobRequest2, jobRequestMetadata).build()
)
);
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canSaveAndVerifyJobSubmissionWithAttachments(@TempDir final Path tempDir) throws
GenieCheckedException,
IOException {
final JobRequest jobRequest = this.createJobRequest(null, null);
final int numAttachments = 6;
long totalAttachmentSize = 0L;
final Set<Resource> attachments = Sets.newHashSet();
for (int i = 0; i < numAttachments; i++) {
final Path attachment = tempDir.resolve(UUID.randomUUID().toString());
Files.write(attachment, ("Select * FROM my_table where id = " + i + ";").getBytes(StandardCharsets.UTF_8));
attachments.add(new FileSystemResource(attachment));
totalAttachmentSize += Files.size(attachment);
}
final Set<URI> attachmentURIs = attachments
.stream()
.map(
// checked exceptions are so fun...
attachment -> {
try {
return attachment.getURI();
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
}
)
.collect(Collectors.toSet());
final JobRequestMetadata jobRequestMetadata = this.createJobRequestMetadata(
true,
numAttachments,
totalAttachmentSize
);
// Save the job submission
final String id = this.service.saveJobSubmission(
new JobSubmission.Builder(jobRequest, jobRequestMetadata).withAttachments(attachmentURIs).build()
);
// Going to assume that most other verification of parameters other than attachments is done in
// canSaveAndVerifyJobSubmissionWithoutAttachments()
final JobRequest savedJobRequest = this.service.getJobRequest(id);
// We should have all the original dependencies
Assertions
.assertThat(savedJobRequest.getResources().getDependencies())
.containsAll(jobRequest.getResources().getDependencies());
// Filter out the original dependencies so that we're left with just the attachments
final Set<URI> savedAttachmentURIs = savedJobRequest
.getResources()
.getDependencies()
.stream()
.filter(dependency -> !jobRequest.getResources().getDependencies().contains(dependency))
.map(
dependency -> {
try {
return new URI(dependency);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
)
.collect(Collectors.toSet());
Assertions.assertThat(savedAttachmentURIs).isEqualTo(attachmentURIs);
}
@Test
@DatabaseSetup("persistence/jobs/jobSpecification.xml")
void verifyLazyLoadJobDependencyAndEnvironmentVariables() {
final String jobId = "job3";
// load the projection.
final Optional<JobSpecificationProjection> jobSpecificationProjectionOption =
this.jobRepository.getJobSpecification(jobId);
Assertions.assertThat(jobSpecificationProjectionOption).isPresent();
// None of the lazy-loading attributes is initialized.
final JobSpecificationProjection jobSpecificationProjection = jobSpecificationProjectionOption.get();
Assertions.assertThat(Hibernate.isInitialized(jobSpecificationProjection.getDependencies())).isFalse();
Assertions.assertThat(Hibernate.isInitialized(jobSpecificationProjection.getEnvironmentVariables())).isFalse();
// Initialize job dependencies and check the correctness.
Hibernate.initialize(jobSpecificationProjection.getDependencies());
Assertions.assertThat(Hibernate.isInitialized(jobSpecificationProjection.getDependencies())).isTrue();
Assertions.assertThat(jobSpecificationProjection.getDependencies()).hasSize(3);
// Ensure job environment variables are still not initialized.
Assertions.assertThat(Hibernate.isInitialized(jobSpecificationProjection.getEnvironmentVariables())).isFalse();
// Initialize job environment variables and check the correctness.
Hibernate.initialize(jobSpecificationProjection.getEnvironmentVariables());
Assertions.assertThat(Hibernate.isInitialized(jobSpecificationProjection.getEnvironmentVariables())).isTrue();
Assertions.assertThat(jobSpecificationProjection.getEnvironmentVariables()).hasSize(2);
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canSaveAndRetrieveResolvedJobInformation() throws GenieCheckedException, IOException {
final String jobId = this.service.saveJobSubmission(
new JobSubmission.Builder(
this.createJobRequest(null, UUID.randomUUID().toString()),
this.createJobRequestMetadata(false, NUM_ATTACHMENTS, TOTAL_SIZE_ATTACHMENTS)
).build()
);
final JobRequest jobRequest = this.service.getJobRequest(jobId);
final ResolvedJob resolvedJob = this.createResolvedJob(jobId, jobRequest, null);
this.service.saveResolvedJob(jobId, resolvedJob);
Assertions
.assertThat(this.service.getJobSpecification(jobId))
.isPresent()
.contains(resolvedJob.getJobSpecification());
final JobEntity job = this.jobRepository.findByUniqueId(jobId).orElseThrow();
final ComputeResources computeResources = resolvedJob.getJobEnvironment().getComputeResources();
Assertions.assertThat(job.getCpuUsed()).isEqualTo(computeResources.getCpu());
Assertions.assertThat(job.getGpuUsed()).isEqualTo(computeResources.getGpu());
Assertions.assertThat(job.getMemoryUsed()).isEqualTo(computeResources.getMemoryMb());
Assertions.assertThat(job.getDiskMbUsed()).isEqualTo(computeResources.getDiskMb());
Assertions.assertThat(job.getNetworkMbpsUsed()).isEqualTo(computeResources.getNetworkMbps());
Assertions
.assertThat(job.getImagesUsed())
.isEqualTo(
Optional.ofNullable(
GenieObjectMapper.getMapper().valueToTree(resolvedJob.getJobEnvironment().getImages())
)
);
final String jobId2 = this.service.saveJobSubmission(
new JobSubmission.Builder(
this.createJobRequest(null, null),
this.createJobRequestMetadata(false, NUM_ATTACHMENTS, TOTAL_SIZE_ATTACHMENTS)
).build()
);
final JobRequest jobRequest2 = this.service.getJobRequest(jobId2);
final JobSpecification jobSpecification2 = this.createJobSpecification(
jobId2,
jobRequest2,
10_358
);
final ResolvedJob resolvedJob1 = new ResolvedJob(
jobSpecification2,
new JobEnvironment.Builder().build(),
jobRequest2.getMetadata()
);
this.service.saveResolvedJob(jobId2, resolvedJob1);
Assertions
.assertThat(this.service.getJobSpecification(jobId2))
.isPresent()
.contains(jobSpecification2);
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canClaimJobAndUpdateStatus() throws GenieCheckedException, IOException {
final String jobId = this.service.saveJobSubmission(
new JobSubmission.Builder(
this.createJobRequest(null, UUID.randomUUID().toString()),
this.createJobRequestMetadata(true, NUM_ATTACHMENTS, TOTAL_SIZE_ATTACHMENTS)
).build()
);
final JobRequest jobRequest = this.service.getJobRequest(jobId);
final JobSpecification jobSpecification = this.createJobSpecification(
jobId,
jobRequest,
null
);
final ResolvedJob resolvedJob = new ResolvedJob(
jobSpecification,
new JobEnvironment.Builder().build(),
jobRequest.getMetadata()
);
this.service.saveResolvedJob(jobId, resolvedJob);
final JobEntity preClaimedJob = this.jobRepository
.findByUniqueId(jobId)
.orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(preClaimedJob.isApi()).isTrue();
Assertions.assertThat(preClaimedJob.getStatus()).isEqualTo(JobStatus.RESOLVED.name());
Assertions.assertThat(preClaimedJob.isResolved()).isTrue();
Assertions.assertThat(preClaimedJob.isClaimed()).isFalse();
Assertions.assertThat(preClaimedJob.getAgentHostname()).isNotPresent();
Assertions.assertThat(preClaimedJob.getAgentVersion()).isNotPresent();
Assertions.assertThat(preClaimedJob.getAgentPid()).isNotPresent();
final String agentHostname = UUID.randomUUID().toString();
final String agentVersion = UUID.randomUUID().toString();
final int agentPid = RandomSuppliers.INT.get();
final AgentClientMetadata agentClientMetadata = new AgentClientMetadata(agentHostname, agentVersion, agentPid);
this.service.claimJob(jobId, agentClientMetadata);
final JobEntity postClaimedJob = this.jobRepository
.findByUniqueId(jobId)
.orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(postClaimedJob.getStatus()).isEqualTo(JobStatus.CLAIMED.name());
Assertions.assertThat(postClaimedJob.isResolved()).isTrue();
Assertions.assertThat(postClaimedJob.isClaimed()).isTrue();
Assertions.assertThat(postClaimedJob.getAgentHostname()).isPresent().contains(agentHostname);
Assertions.assertThat(postClaimedJob.getAgentVersion()).isPresent().contains(agentVersion);
Assertions.assertThat(postClaimedJob.getAgentPid()).isPresent().contains(agentPid);
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canUpdateJobStatus() throws GenieCheckedException, IOException {
final String jobId = this.service.saveJobSubmission(
new JobSubmission.Builder(
this.createJobRequest(null, UUID.randomUUID().toString()),
this.createJobRequestMetadata(false, NUM_ATTACHMENTS, TOTAL_SIZE_ATTACHMENTS)
).build()
);
final JobRequest jobRequest = this.service.getJobRequest(jobId);
final ResolvedJob resolvedJob = this.createResolvedJob(jobId, jobRequest, null);
this.service.saveResolvedJob(jobId, resolvedJob);
final String agentHostname = UUID.randomUUID().toString();
final String agentVersion = UUID.randomUUID().toString();
final int agentPid = RandomSuppliers.INT.get();
final AgentClientMetadata agentClientMetadata = new AgentClientMetadata(agentHostname, agentVersion, agentPid);
this.service.claimJob(jobId, agentClientMetadata);
JobEntity jobEntity = this.jobRepository
.findByUniqueId(jobId)
.orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(jobEntity.getStatus()).isEqualTo(JobStatus.CLAIMED.name());
// status won't match so it won't update
Assertions
.assertThat(this.service.updateJobStatus(jobId, JobStatus.RUNNING, JobStatus.FAILED, null))
.isEqualTo(JobStatus.CLAIMED);
final String initStatusMessage = "Job is initializing";
Assertions
.assertThat(this.service.updateJobStatus(jobId, JobStatus.CLAIMED, JobStatus.INIT, initStatusMessage))
.isEqualTo(JobStatus.INIT);
jobEntity = this.jobRepository
.findByUniqueId(jobId)
.orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(jobEntity.isApi()).isFalse();
Assertions.assertThat(jobEntity.getStatus()).isEqualTo(JobStatus.INIT.name());
Assertions.assertThat(jobEntity.getStatusMsg()).isPresent().contains(initStatusMessage);
Assertions.assertThat(jobEntity.getStarted()).isNotPresent();
Assertions.assertThat(jobEntity.getFinished()).isNotPresent();
final String runningStatusMessage = "Job is running";
Assertions
.assertThat(this.service.updateJobStatus(jobId, JobStatus.INIT, JobStatus.RUNNING, runningStatusMessage))
.isEqualTo(JobStatus.RUNNING);
jobEntity = this.jobRepository
.findByUniqueId(jobId)
.orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(jobEntity.getStatus()).isEqualTo(JobStatus.RUNNING.name());
Assertions.assertThat(jobEntity.getStatusMsg()).isPresent().contains(runningStatusMessage);
Assertions.assertThat(jobEntity.getStarted()).isPresent();
Assertions.assertThat(jobEntity.getFinished()).isNotPresent();
final String successMessage = "Job completed successfully";
Assertions
.assertThat(this.service.updateJobStatus(jobId, JobStatus.RUNNING, JobStatus.SUCCEEDED, successMessage))
.isEqualTo(JobStatus.SUCCEEDED);
jobEntity = this.jobRepository
.findByUniqueId(jobId)
.orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(jobEntity.getStatus()).isEqualTo(JobStatus.SUCCEEDED.name());
Assertions.assertThat(jobEntity.getStatusMsg()).isPresent().contains(successMessage);
Assertions.assertThat(jobEntity.getStarted()).isPresent();
Assertions.assertThat(jobEntity.getFinished()).isPresent();
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canGetJobStatus() throws GenieCheckedException {
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getJobStatus(UUID.randomUUID().toString()));
Assertions.assertThat(this.service.getJobStatus(JOB_1_ID)).isEqualTo(JobStatus.SUCCEEDED);
Assertions.assertThat(this.service.getJobStatus(JOB_2_ID)).isEqualTo(JobStatus.RUNNING);
Assertions.assertThat(this.service.getJobStatus(JOB_3_ID)).isEqualTo(JobStatus.RUNNING);
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canGetJobArchiveLocation() throws GenieCheckedException {
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getJobArchiveLocation(UUID.randomUUID().toString()));
Assertions.assertThat(this.service.getJobArchiveLocation(JOB_3_ID)).isNotPresent();
Assertions
.assertThat(this.service.getJobArchiveLocation(JOB_1_ID))
.isPresent()
.contains("s3://somebucket/genie/logs/1/");
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void cantGetFinishedJobNonExistent() {
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getFinishedJob(UUID.randomUUID().toString()));
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void cantGetFinishedJobNotFinished() {
Assertions
.assertThatExceptionOfType(GenieInvalidStatusException.class)
.isThrownBy(() -> this.service.getFinishedJob(JOB_3_ID));
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canGetFinishedJob() throws GenieCheckedException {
final FinishedJob finishedJob = this.service.getFinishedJob(JOB_1_ID);
Assertions.assertThat(finishedJob).isNotNull();
Assertions.assertThat(finishedJob.getUniqueId()).isEqualTo(JOB_1_ID);
Assertions.assertThat(finishedJob.getUser()).isEqualTo("tgianos");
Assertions.assertThat(finishedJob.getName()).isEqualTo("testSparkJob");
Assertions.assertThat(finishedJob.getVersion()).isEqualTo("2.4");
Assertions.assertThat(finishedJob.getCreated()).isNotNull();
Assertions.assertThat(finishedJob.getStatus()).isEqualTo(JobStatus.SUCCEEDED);
Assertions.assertThat(finishedJob.getCommandArgs().size()).isEqualTo(2);
Assertions.assertThat(finishedJob.getCommandCriterion()).isNotNull();
Assertions.assertThat(finishedJob.getClusterCriteria()).hasSize(2);
Assertions.assertThat(finishedJob.getStarted()).isNotPresent();
Assertions.assertThat(finishedJob.getFinished()).isNotPresent();
Assertions.assertThat(finishedJob.getGrouping()).isNotPresent();
Assertions.assertThat(finishedJob.getGroupingInstance()).isNotPresent();
Assertions.assertThat(finishedJob.getStatusMessage()).isNotPresent();
Assertions.assertThat(finishedJob.getRequestedMemory()).isPresent().contains(1560L);
Assertions.assertThat(finishedJob.getRequestApiClientHostname()).isNotPresent();
Assertions.assertThat(finishedJob.getRequestApiClientUserAgent()).isNotPresent();
Assertions.assertThat(finishedJob.getRequestAgentClientHostname()).isNotPresent();
Assertions.assertThat(finishedJob.getRequestAgentClientVersion()).isNotPresent();
Assertions.assertThat(finishedJob.getNumAttachments()).isPresent().contains(2);
Assertions.assertThat(finishedJob.getExitCode()).isPresent().contains(0);
Assertions.assertThat(finishedJob.getArchiveLocation()).isPresent().contains("s3://somebucket/genie/logs/1/");
Assertions.assertThat(finishedJob.getMemoryUsed()).isNotPresent();
final Command command = finishedJob.getCommand().orElse(null);
final Cluster cluster = finishedJob.getCluster().orElse(null);
final List<Application> applications = finishedJob.getApplications();
Assertions.assertThat(command).isNotNull();
Assertions.assertThat(cluster).isNotNull();
Assertions.assertThat(applications).isNotNull();
Assertions.assertThat(command.getMetadata().getName()).isEqualTo("spark");
Assertions.assertThat(cluster.getMetadata().getName()).isEqualTo("h2query");
Assertions.assertThat(applications.size()).isEqualTo(2);
Assertions.assertThat(applications.get(0).getMetadata().getName()).isEqualTo("hadoop");
Assertions.assertThat(applications.get(1).getMetadata().getName()).isEqualTo("spark");
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canDetermineIfIsApiJob() throws GenieCheckedException {
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.isApiJob(UUID.randomUUID().toString()));
Assertions.assertThat(this.service.isApiJob(JOB_1_ID)).isFalse();
Assertions.assertThat(this.service.isApiJob(JOB_2_ID)).isTrue();
Assertions.assertThat(this.service.isApiJob(JOB_3_ID)).isTrue();
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canGetJobArchiveStatus() throws GenieCheckedException {
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.getJobArchiveStatus(UUID.randomUUID().toString()));
Assertions.assertThat(this.service.getJobArchiveStatus(JOB_1_ID)).isEqualTo(ArchiveStatus.ARCHIVED);
Assertions.assertThat(this.service.getJobArchiveStatus(JOB_2_ID)).isEqualTo(ArchiveStatus.PENDING);
Assertions.assertThat(this.service.getJobArchiveStatus(JOB_3_ID)).isEqualTo(ArchiveStatus.UNKNOWN);
}
@Test
@DatabaseSetup("persistence/jobs/init.xml")
void canSetJobArchiveStatus() throws GenieCheckedException {
Assertions.assertThat(this.service.getJobArchiveStatus(JOB_2_ID)).isEqualTo(ArchiveStatus.PENDING);
this.service.updateJobArchiveStatus(JOB_2_ID, ArchiveStatus.ARCHIVED);
Assertions.assertThat(this.service.getJobArchiveStatus(JOB_2_ID)).isEqualTo(ArchiveStatus.ARCHIVED);
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canFindJobs() {
//TODO: add more cases
final Pageable page = PageRequest.of(0, 10, Sort.Direction.DESC, "updated");
Page<JobSearchResult> jobs;
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(5L);
jobs = this.service.findJobs(
null,
null,
null,
Sets.newHashSet(com.netflix.genie.common.dto.JobStatus.RUNNING),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(3L);
Assertions.assertThat(jobs.getContent()).hasSize(3).extracting(BaseSearchResult::getId).contains(JOB_3_ID);
jobs = this.service.findJobs(
JOB_1_ID,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(1L);
Assertions.assertThat(jobs.getContent()).hasSize(1).extracting(BaseSearchResult::getId).containsOnly(JOB_1_ID);
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
"job3Grouping",
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(1L);
Assertions.assertThat(jobs.getContent()).hasSize(1).extracting(BaseSearchResult::getId).containsOnly(JOB_3_ID);
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
"job2%",
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(1L);
Assertions.assertThat(jobs.getContent()).hasSize(1).extracting(BaseSearchResult::getId).containsOnly(JOB_2_ID);
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
"job1%",
"job2%",
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canFindJobsWithTags() {
final Pageable page = PageRequest.of(0, 10);
Page<JobSearchResult> jobs;
jobs = this.service.findJobs(
null,
null,
null,
null,
Sets.newHashSet("SparkJob"),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(5L);
jobs = this.service.findJobs(
null,
null,
null,
null,
Sets.newHashSet("smoke-test", "SparkJob"),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(1L);
Assertions.assertThat(jobs.getContent()).hasSize(1).extracting(BaseSearchResult::getId).containsOnly(JOB_1_ID);
jobs = this.service.findJobs(
null,
null,
null,
null,
Sets.newHashSet("smoke-test", "SparkJob", "blah"),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
jobs = this.service.findJobs(
null,
null,
null,
Sets.newHashSet(com.netflix.genie.common.dto.JobStatus.FAILED),
Sets.newHashSet("smoke-test", "SparkJob"),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canFindJobsByClusterAndCommand() {
final String clusterId = "cluster1";
final String clusterName = "h2query";
final String commandId = "command1";
final String commandName = "spark";
final Pageable page = PageRequest.of(0, 10, Sort.Direction.DESC, "updated");
Page<JobSearchResult> jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
UUID.randomUUID().toString(),
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
null,
null,
UUID.randomUUID().toString(),
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
clusterId,
null,
null,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(5L);
Assertions.assertThat(jobs.getContent().size()).isEqualTo(5);
jobs = this.service
.findJobs(
null,
null,
null,
null,
null,
null,
null,
null,
commandId,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(5L);
Assertions.assertThat(jobs.getContent().size()).isEqualTo(5);
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
null,
clusterId,
null,
commandId,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(5L);
Assertions.assertThat(jobs.getContent().size()).isEqualTo(5);
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
clusterName,
clusterId,
commandName,
commandId,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(5L);
Assertions.assertThat(jobs.getContent().size()).isEqualTo(5);
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
UUID.randomUUID().toString(),
clusterId,
commandName,
commandId,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
jobs = this.service.findJobs(
null,
null,
null,
null,
null,
clusterName,
clusterId,
UUID.randomUUID().toString(),
commandId,
null,
null,
null,
null,
null,
null,
page
);
Assertions.assertThat(jobs.getTotalElements()).isEqualTo(0L);
Assertions.assertThat(jobs.getContent()).isEmpty();
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetJob() throws GenieException {
Assertions.assertThat(this.service.getJob(JOB_1_ID).getName()).isEqualTo("testSparkJob");
Assertions.assertThat(this.service.getJob(JOB_2_ID).getName()).isEqualTo("testSparkJob1");
Assertions.assertThat(this.service.getJob(JOB_3_ID).getName()).isEqualTo("testSparkJob2");
Assertions
.assertThatExceptionOfType(GenieNotFoundException.class)
.isThrownBy(() -> this.service.getJob(UUID.randomUUID().toString()));
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetJobExecution() throws GenieException {
Assertions.assertThat(this.service.getJobExecution(JOB_1_ID).getProcessId()).contains(317);
Assertions.assertThat(this.service.getJobExecution(JOB_2_ID).getProcessId()).contains(318);
Assertions.assertThat(this.service.getJobExecution(JOB_3_ID).getProcessId()).contains(319);
Assertions
.assertThatExceptionOfType(GenieNotFoundException.class)
.isThrownBy(() -> this.service.getJobExecution(UUID.randomUUID().toString()));
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetJobCluster() throws GenieCheckedException {
Assertions.assertThat(this.service.getJobCluster(JOB_1_ID).getId()).contains("cluster1");
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetJobCommand() throws GenieCheckedException {
Assertions.assertThat(this.service.getJobCommand(JOB_1_ID).getId()).contains("command1");
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetJobApplications() throws GenieCheckedException {
Assertions
.assertThat(this.service.getJobApplications(JOB_1_ID))
.hasSize(2)
.extracting(Application::getId)
.containsExactly("app1", "app3");
Assertions
.assertThat(this.service.getJobApplications(JOB_2_ID))
.hasSize(2)
.extracting(Application::getId)
.containsExactly("app1", "app2");
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetActiveJobCountForUser() {
Assertions.assertThat(this.service.getActiveJobCountForUser("nobody")).isEqualTo(0L);
Assertions.assertThat(this.service.getActiveJobCountForUser("tgianos")).isEqualTo(4L);
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetJobMetadata() throws GenieException {
final com.netflix.genie.common.dto.JobMetadata jobMetadata = this.service.getJobMetadata(JOB_1_ID);
Assertions.assertThat(jobMetadata.getClientHost()).isNotPresent();
Assertions.assertThat(jobMetadata.getUserAgent()).isNotPresent();
Assertions.assertThat(jobMetadata.getNumAttachments()).contains(2);
Assertions.assertThat(jobMetadata.getTotalSizeOfAttachments()).contains(38083L);
Assertions.assertThat(jobMetadata.getStdErrSize()).isNotPresent();
Assertions.assertThat(jobMetadata.getStdOutSize()).isNotPresent();
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetUserResourceSummaries() {
final Map<String, UserResourcesSummary> summaries = this.service.getUserResourcesSummaries(
JobStatus.getActiveStatuses(),
true
);
Assertions.assertThat(summaries.keySet()).contains("tgianos");
final UserResourcesSummary userResourcesSummary = summaries.get("tgianos");
Assertions.assertThat(userResourcesSummary.getUser()).isEqualTo("tgianos");
Assertions.assertThat(userResourcesSummary.getRunningJobsCount()).isEqualTo(2L);
Assertions.assertThat(userResourcesSummary.getUsedMemory()).isEqualTo(4096L);
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetUsedMemoryOnHost() {
Assertions.assertThat(this.service.getUsedMemoryOnHost("a.netflix.com")).isEqualTo(2048L);
Assertions.assertThat(this.service.getUsedMemoryOnHost("b.netflix.com")).isEqualTo(2048L);
Assertions.assertThat(this.service.getUsedMemoryOnHost("agent.netflix.com")).isEqualTo(4096L);
Assertions.assertThat(this.service.getUsedMemoryOnHost(UUID.randomUUID().toString())).isEqualTo(0L);
}
@Test
@DatabaseSetup("persistence/jobs/search.xml")
void canGetActiveJobs() {
Assertions
.assertThat(this.service.getActiveJobs())
.hasSize(4)
.containsExactlyInAnyOrder(JOB_2_ID, JOB_3_ID, AGENT_JOB_1, AGENT_JOB_2);
}
@Test
@DatabaseSetup("persistence/jobs/unclaimed.xml")
void canGetUnclaimedJobs() {
Assertions
.assertThat(this.service.getUnclaimedJobs())
.hasSize(3)
.containsExactlyInAnyOrder(JOB_2_ID, AGENT_JOB_1, AGENT_JOB_2);
}
@Test
@DatabaseSetup("persistence/jobs/getHostJobInformation/setup.xml")
void canGetJobHostInformation() {
final JobInfoAggregate aInfo = this.service.getHostJobInformation("a.netflix.com");
Assertions.assertThat(aInfo.getNumberOfActiveJobs()).isEqualTo(1L);
Assertions.assertThat(aInfo.getTotalMemoryAllocated()).isEqualTo(2048L);
Assertions.assertThat(aInfo.getTotalMemoryUsed()).isEqualTo(2048L);
final JobInfoAggregate bInfo = this.service.getHostJobInformation("b.netflix.com");
Assertions.assertThat(bInfo.getNumberOfActiveJobs()).isEqualTo(1L);
Assertions.assertThat(bInfo.getTotalMemoryAllocated()).isEqualTo(2048L);
Assertions.assertThat(bInfo.getTotalMemoryUsed()).isEqualTo(2048L);
final JobInfoAggregate agentInfo = this.service.getHostJobInformation("agent.netflix.com");
Assertions.assertThat(agentInfo.getNumberOfActiveJobs()).isEqualTo(2L);
Assertions.assertThat(agentInfo.getTotalMemoryAllocated()).isEqualTo(4096L);
Assertions.assertThat(agentInfo.getTotalMemoryUsed()).isEqualTo(4096L);
final JobInfoAggregate randomInfo = this.service.getHostJobInformation(UUID.randomUUID().toString());
Assertions.assertThat(randomInfo.getNumberOfActiveJobs()).isEqualTo(0L);
Assertions.assertThat(randomInfo.getTotalMemoryAllocated()).isEqualTo(0L);
Assertions.assertThat(randomInfo.getTotalMemoryUsed()).isEqualTo(0L);
}
@Test
@DatabaseSetup("persistence/jobs/archive_status.xml")
void canGetFinishedJobsWithPendingArchiveStatus() {
// This is the update timestamp of all jobs in the dataset
final Instant lastJobUpdate = Instant.parse("2020-01-01T00:00:00.000Z");
final Set<JobStatus> finishedJobStatuses = JobStatus.getFinishedStatuses();
final HashSet<ArchiveStatus> pendingJobArchiveStatuses = Sets.newHashSet(ArchiveStatus.PENDING);
final Instant notMatchingThreshold = lastJobUpdate.minus(1, ChronoUnit.SECONDS);
final Instant matchingThreshold = lastJobUpdate.plus(1, ChronoUnit.SECONDS);
Assertions
.assertThat(
this.service.getJobsWithStatusAndArchiveStatusUpdatedBefore(
finishedJobStatuses,
pendingJobArchiveStatuses,
lastJobUpdate
)
)
.isEmpty();
Assertions
.assertThat(
this.service.getJobsWithStatusAndArchiveStatusUpdatedBefore(
finishedJobStatuses,
pendingJobArchiveStatuses,
notMatchingThreshold
)
)
.isEmpty();
Assertions
.assertThat(
this.service.getJobsWithStatusAndArchiveStatusUpdatedBefore(
finishedJobStatuses,
pendingJobArchiveStatuses,
matchingThreshold
)
)
.hasSize(3)
.containsExactlyInAnyOrder(AGENT_JOB_1, AGENT_JOB_2, "NotAgentJob1");
}
@Test
@DatabaseSetup("persistence/jobs/launcher_ext.xml")
void canGetAndUpdateLauncherExt() throws NotFoundException, JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode emptyExt = NullNode.getInstance();
final Map<Object, Object> ext1 = Maps.newHashMap();
ext1.put("Foo", 3);
ext1.put("Bar", Lists.newArrayList("x", 3));
final List<Object> ext2 = Lists.newArrayList("Foo", "Bar", 123);
final JsonNode extNode1 = objectMapper.valueToTree(ext1);
final JsonNode extNode2 = objectMapper.valueToTree(ext2);
// Job does not exist, expect null node
Assertions.assertThat(this.service.getRequestedLauncherExt(UUID.randomUUID().toString())).isEqualTo(emptyExt);
// Jobs exists, but all ext fields are null, expect null nodes
Assertions.assertThat(this.service.getRequestedLauncherExt(AGENT_JOB_1)).isEqualTo(emptyExt);
Assertions.assertThat(this.service.getLauncherExt(AGENT_JOB_1)).isEqualTo(emptyExt);
Assertions.assertThat(this.service.getRequestedLauncherExt(AGENT_JOB_2)).isEqualTo(emptyExt);
Assertions.assertThat(this.service.getLauncherExt(AGENT_JOB_2)).isEqualTo(emptyExt);
// Update values for existing jobs
this.service.updateRequestedLauncherExt(AGENT_JOB_1, extNode1);
this.service.updateLauncherExt(AGENT_JOB_2, extNode2);
// Update values for non-existing jobs
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateRequestedLauncherExt(UUID.randomUUID().toString(), extNode1));
Assertions
.assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.service.updateRequestedLauncherExt(UUID.randomUUID().toString(), extNode1));
// Retrieve persisted values
Assertions.assertThat(this.service.getRequestedLauncherExt(AGENT_JOB_1)).isEqualTo(extNode1);
Assertions.assertThat(this.service.getLauncherExt(AGENT_JOB_1)).isEqualTo(emptyExt);
Assertions.assertThat(this.service.getRequestedLauncherExt(AGENT_JOB_2)).isEqualTo(emptyExt);
Assertions.assertThat(this.service.getLauncherExt(AGENT_JOB_2)).isEqualTo(extNode2);
}
private void validateSavedJobSubmission(
final String id,
final JobRequest jobRequest,
final JobRequestMetadata jobRequestMetadata
) throws GenieCheckedException {
Assertions.assertThat(this.service.getJobRequest(id)).isEqualTo(jobRequest);
// TODO: Switch to compare results of a get once implemented to avoid collection transaction problem
final JobEntity jobEntity = this.jobRepository
.findByUniqueId(id)
.orElseThrow(() -> new NotFoundException("No job with id " + id + " found when one was expected"));
Assertions.assertThat(jobEntity.isResolved()).isFalse();
// Job Request Metadata Fields
jobRequestMetadata.getApiClientMetadata().ifPresent(
apiClientMetadata -> {
apiClientMetadata.getHostname().ifPresent(
hostname -> Assertions.assertThat(jobEntity.getRequestApiClientHostname()).contains(hostname)
);
apiClientMetadata.getUserAgent().ifPresent(
userAgent -> Assertions.assertThat(jobEntity.getRequestApiClientUserAgent()).contains(userAgent)
);
}
);
jobRequestMetadata.getAgentClientMetadata().ifPresent(
apiClientMetadata -> {
apiClientMetadata.getHostname().ifPresent(
hostname -> Assertions.assertThat(jobEntity.getRequestAgentClientHostname()).contains(hostname)
);
apiClientMetadata.getVersion().ifPresent(
version -> Assertions.assertThat(jobEntity.getRequestAgentClientVersion()).contains(version)
);
apiClientMetadata.getPid().ifPresent(
pid -> Assertions.assertThat(jobEntity.getRequestAgentClientPid()).contains(pid)
);
}
);
Assertions.assertThat(jobEntity.getNumAttachments()).contains(jobRequestMetadata.getNumAttachments());
Assertions
.assertThat(jobEntity.getTotalSizeOfAttachments())
.contains(jobRequestMetadata.getTotalSizeOfAttachments());
}
private JobRequest createJobRequest(
@Nullable final String requestedId,
@Nullable final String requestedArchivalLocationPrefix
) throws IOException {
final String metadata = "{\"" + UUID.randomUUID() + "\": \"" + UUID.randomUUID() + "\"}";
final JobMetadata jobMetadata = new JobMetadata
.Builder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString())
.withMetadata(metadata)
.withEmail(UUID.randomUUID() + "@" + UUID.randomUUID() + ".com")
.withGroup(UUID.randomUUID().toString())
.withGrouping(UUID.randomUUID().toString())
.withGroupingInstance(UUID.randomUUID().toString())
.withDescription(UUID.randomUUID().toString())
.withTags(Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.build();
final List<Criterion> clusterCriteria = Lists.newArrayList(
new Criterion
.Builder()
.withId(UUID.randomUUID().toString())
.withName(UUID.randomUUID().toString())
.withStatus(ClusterStatus.OUT_OF_SERVICE.toString())
.withTags(Sets.newHashSet(UUID.randomUUID().toString()))
.withVersion(UUID.randomUUID().toString())
.build(),
new Criterion
.Builder()
.withId(UUID.randomUUID().toString())
.withName(UUID.randomUUID().toString())
.withStatus(ClusterStatus.UP.toString())
.withTags(Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.withVersion(UUID.randomUUID().toString())
.build()
);
final Criterion commandCriterion = new Criterion
.Builder()
.withId(UUID.randomUUID().toString())
.withName(UUID.randomUUID().toString())
.withStatus(CommandStatus.ACTIVE.toString())
.withTags(Sets.newHashSet(UUID.randomUUID().toString()))
.withVersion(UUID.randomUUID().toString())
.build();
final List<String> requestedApplications = Lists.newArrayList(
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
);
final ExecutionResourceCriteria criteria = new ExecutionResourceCriteria(
clusterCriteria,
commandCriterion,
requestedApplications
);
final ExecutionEnvironment executionEnvironment = new ExecutionEnvironment(
Sets.newHashSet(UUID.randomUUID().toString()),
Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()),
UUID.randomUUID().toString()
);
final Map<String, String> requestedEnvironmentVariables = ImmutableMap.of(
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
);
final String agentEnvironmentExt
= "{"
+ "\"" + UUID.randomUUID() + "\": \"" + UUID.randomUUID() + "\", "
+ "\"" + UUID.randomUUID() + "\": \"\""
+ "}";
final JobEnvironmentRequest jobEnvironmentRequest = new JobEnvironmentRequest
.Builder()
.withRequestedEnvironmentVariables(requestedEnvironmentVariables)
.withExt(GenieObjectMapper.getMapper().readTree(agentEnvironmentExt))
.withRequestedComputeResources(
new ComputeResources.Builder()
.withCpu(CPU_REQUESTED)
.withMemoryMb(MEMORY_REQUESTED)
.build()
)
.build();
final String agentConfigExt
= "{\"" + UUID.randomUUID() + "\": \"" + UUID.randomUUID() + "\"}";
final String requestedJobDirectoryLocation = "/tmp/" + UUID.randomUUID();
final AgentConfigRequest agentConfigRequest = new AgentConfigRequest
.Builder()
.withExt(GenieObjectMapper.getMapper().readTree(agentConfigExt))
.withInteractive(true)
.withTimeoutRequested(TIMEOUT_REQUESTED)
.withArchivingDisabled(true)
.withRequestedJobDirectoryLocation(requestedJobDirectoryLocation)
.build();
return new JobRequest(
requestedId,
executionEnvironment,
Lists.newArrayList(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
),
jobMetadata,
criteria,
jobEnvironmentRequest,
agentConfigRequest
);
}
private JobRequestMetadata createJobRequestMetadata(
final boolean api,
final int numAttachments,
final long totalAttachmentSize
) {
if (!api) {
final String agentVersion = UUID.randomUUID().toString();
final int agentPid = RandomSuppliers.INT.get();
final AgentClientMetadata agentClientMetadata = new AgentClientMetadata(
UUID.randomUUID().toString(),
agentVersion,
agentPid
);
return new JobRequestMetadata(
null,
agentClientMetadata,
numAttachments,
totalAttachmentSize,
null
);
} else {
final ApiClientMetadata apiClientMetadata = new ApiClientMetadata(
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
);
return new JobRequestMetadata(
apiClientMetadata,
null,
numAttachments,
totalAttachmentSize,
ImmutableMap.of("Foo", "Bar")
);
}
}
private ResolvedJob createResolvedJob(
final String jobId,
final JobRequest jobRequest,
@Nullable final Integer timeout
) throws GenieCheckedException {
return new ResolvedJob(
this.createJobSpecification(jobId, jobRequest, timeout),
this.createJobEnvironment(),
jobRequest.getMetadata()
);
}
private JobSpecification createJobSpecification(
final String jobId,
final JobRequest jobRequest,
@Nullable final Integer timeout
) throws GenieCheckedException {
final String clusterId = "cluster1";
final String commandId = "command1";
final String application0Id = "app1";
final String application1Id = "app2";
final Cluster cluster = this.service.getCluster(clusterId);
final Command command = this.service.getCommand(commandId);
final Application application0 = this.service.getApplication(application0Id);
final Application application1 = this.service.getApplication(application1Id);
final Map<String, String> environmentVariables = ImmutableMap.of(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
);
final File jobDirectoryLocation = new File("/tmp/genie/jobs/" + jobId);
return new JobSpecification(
command.getExecutable(),
jobRequest.getCommandArgs(),
new JobSpecification.ExecutionResource(
jobId,
jobRequest.getResources()
),
new JobSpecification.ExecutionResource(
clusterId,
cluster.getResources()
),
new JobSpecification.ExecutionResource(
commandId,
command.getResources()
),
Lists.newArrayList(
new JobSpecification.ExecutionResource(
application0Id,
application0.getResources()
),
new JobSpecification.ExecutionResource(
application1Id,
application1.getResources()
)
),
environmentVariables,
jobRequest.getRequestedAgentConfig().isInteractive(),
jobDirectoryLocation,
ARCHIVE_LOCATION,
timeout
);
}
private JobEnvironment createJobEnvironment() {
final Map<String, Image> images = new HashMap<>();
final List<String> arguments = new ArrayList<>();
for (int i = 0; i < new Random().nextInt(10); i++) {
arguments.add(String.valueOf(i));
images.put(
UUID.randomUUID().toString(),
new Image.Builder()
.withName(UUID.randomUUID().toString())
.withTag(UUID.randomUUID().toString())
.withArguments(arguments)
.build()
);
}
return new JobEnvironment.Builder()
.withComputeResources(
new ComputeResources.Builder()
.withCpu(RandomSuppliers.INT.get() & Integer.MAX_VALUE)
.withGpu(RandomSuppliers.INT.get() & Integer.MAX_VALUE)
.withMemoryMb(RandomSuppliers.LONG.get() & Long.MAX_VALUE)
.withDiskMb(RandomSuppliers.LONG.get() & Long.MAX_VALUE)
.withNetworkMbps(RandomSuppliers.LONG.get() & Long.MAX_VALUE)
.build()
)
.withImages(images)
.build();
}
}
| 2,369 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceIntegrationTestBase.java | /*
*
* Copyright 2015 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.genie.web.data.services.impl.jpa;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.netflix.genie.common.internal.spring.autoconfigure.CommonTracingAutoConfiguration;
import com.netflix.genie.web.data.observers.PersistedJobStatusObserver;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCriterionRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaJobRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaTagRepository;
import com.netflix.genie.web.spring.autoconfigure.ValidationAutoConfiguration;
import com.netflix.genie.web.spring.autoconfigure.data.DataAutoConfiguration;
import org.junit.jupiter.api.AfterEach;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.sleuth.autoconfig.brave.BraveAutoConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
/**
* Base class to save on configuration.
*
* @author tgianos
* @since 4.0.0
*/
@DataJpaTest
@TestExecutionListeners(
{
DependencyInjectionTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class
}
)
@Import(
{
DataAutoConfiguration.class,
ValidationAutoConfiguration.class,
BraveAutoConfiguration.class,
CommonTracingAutoConfiguration.class
}
)
@MockBean(
{
PersistedJobStatusObserver.class //TODO: Needed for JobEntityListener but should be in DataAutoConfiguration
}
)
//@TestPropertySource(
// properties = {
// "logging.level.com.netflix.genie.web.data.services.impl.jpa=DEBUG", // Genie JPA package
// "logging.level.org.hibernate.SQL=DEBUG", // Show SQL queries
// "logging.level.org.hibernate.type.descriptor.sql=TRACE", // Parameters, extracted values and more
// }
//)
class JpaPersistenceServiceIntegrationTestBase {
@Autowired
protected JpaApplicationRepository applicationRepository;
@Autowired
protected JpaClusterRepository clusterRepository;
@Autowired
protected JpaCommandRepository commandRepository;
@Autowired
protected JpaJobRepository jobRepository;
@Autowired
protected JpaFileRepository fileRepository;
@Autowired
protected JpaTagRepository tagRepository;
@Autowired
protected JpaCriterionRepository criterionRepository;
@Autowired
protected JpaPersistenceServiceImpl service;
@Autowired
protected PersistedJobStatusObserver persistedJobStatusObserver;
@Autowired
protected TestEntityManager entityManager;
@AfterEach
void resetMocks() {
// Could use @DirtiesContext but seems excessive
Mockito.reset(this.persistedJobStatusObserver);
}
}
| 2,370 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/data/services/impl/jpa/package-info.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.
*
*/
/**
* Integration tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,371 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/services/impl/ArchivedJobServiceImplIntegrationTest.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.genie.web.services.impl;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.DirectoryManifest;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.dtos.ArchivedJobMetadata;
import com.netflix.genie.web.exceptions.checked.JobDirectoryManifestNotFoundException;
import com.netflix.genie.web.exceptions.checked.JobNotArchivedException;
import com.netflix.genie.web.exceptions.checked.JobNotFoundException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.services.ArchivedJobService;
import com.netflix.genie.web.spring.autoconfigure.CachingAutoConfiguration;
import com.netflix.genie.web.spring.autoconfigure.RetryAutoConfiguration;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import java.net.URI;
import java.util.Optional;
import java.util.UUID;
/**
* Integration tests for {@link ArchivedJobServiceImpl}.
*
* @author tgianos
* @since 4.0.0
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = {
ArchivedJobServiceImplIntegrationTest.ArchivedJobServiceConfig.class,
RetryAutoConfiguration.class,
CachingAutoConfiguration.class
},
loader = AnnotationConfigContextLoader.class
)
@TestPropertySource(
properties = {
ArchivedJobServiceImpl.GET_METADATA_NUM_RETRY_PROPERTY_NAME
+ "="
+ ArchivedJobServiceImplIntegrationTest.NUM_GET_RETRIES
}
)
class ArchivedJobServiceImplIntegrationTest {
@VisibleForTesting
static final int NUM_GET_RETRIES = 2;
private static final String JOB_ID = UUID.randomUUID().toString();
private static final String ARCHIVE_LOCATION = "file:/tmp/" + UUID.randomUUID().toString();
@Autowired
private ArchivedJobService archivedJobService;
@MockBean
private PersistenceService persistenceService;
/**
* Make sure that when the correct exception is thrown it retries the expected number of times.
*
* @throws Exception On unexpected error
*/
@Test
void testRetryOnMissingManifest() throws Exception {
Mockito
.when(this.persistenceService.getJobArchiveLocation(JOB_ID))
.thenReturn(Optional.of(ARCHIVE_LOCATION));
try {
this.archivedJobService.getArchivedJobMetadata(JOB_ID);
} catch (final JobDirectoryManifestNotFoundException ignored) {
Mockito
.verify(this.persistenceService, Mockito.times(NUM_GET_RETRIES))
.getJobArchiveLocation(JOB_ID);
}
}
/**
* Make sure that when the job isn't found the method isn't retried.
*
* @throws Exception On unexpected error
*/
@Test
void testNoRetryOnJobNotFound() throws Exception {
Mockito
.when(this.persistenceService.getJobArchiveLocation(JOB_ID))
.thenThrow(new NotFoundException("blah"));
try {
this.archivedJobService.getArchivedJobMetadata(JOB_ID);
} catch (final JobNotFoundException ignored) {
Mockito
.verify(this.persistenceService, Mockito.times(1))
.getJobArchiveLocation(JOB_ID);
}
}
/**
* Make sure that when a runtime exception is thrown it doesn't retry.
*
* @throws GenieCheckedException If this happens something really bizarre happened
*/
@Test
void testNoRetryOnUnexpectedException() throws GenieCheckedException {
Mockito
.when(this.persistenceService.getJobArchiveLocation(JOB_ID))
.thenReturn(Optional.of("Not a valid URI"));
try {
this.archivedJobService.getArchivedJobMetadata(JOB_ID);
} catch (final Exception ignored) {
Mockito
.verify(this.persistenceService, Mockito.times(1))
.getJobArchiveLocation(JOB_ID);
}
}
/**
* Make sure that when the job wasn't archived the method doesn't retry.
*
* @throws Exception On unexpected error
*/
@Test
void testNoRetryOnJobNotArchived() throws Exception {
Mockito
.when(this.persistenceService.getJobArchiveLocation(JOB_ID))
.thenReturn(Optional.empty());
try {
this.archivedJobService.getArchivedJobMetadata(JOB_ID);
} catch (final JobNotArchivedException ignored) {
Mockito
.verify(this.persistenceService, Mockito.times(1))
.getJobArchiveLocation(JOB_ID);
}
}
/**
* Make sure requesting a valid manifest successfully returns the right data.
*
* @throws Exception On unexpected error
*/
@Test
void canSuccessfullyGetArchivedJobMetadata() throws Exception {
final String archiveLocation = new ClassPathResource("archivedJobServiceImpl", this.getClass())
.getURI()
.toString();
final URI expectedArchiveRootUri = new URI(archiveLocation + "/").normalize();
final DirectoryManifest expectedManifest = GenieObjectMapper.getMapper().readValue(
new ClassPathResource("archivedJobServiceImpl/genie/manifest.json", this.getClass()).getFile(),
DirectoryManifest.class
);
Mockito
.when(this.persistenceService.getJobArchiveLocation(JOB_ID))
.thenReturn(Optional.of(archiveLocation));
final ArchivedJobMetadata metadata = this.archivedJobService.getArchivedJobMetadata(JOB_ID);
Assertions.assertThat(metadata.getJobId()).isEqualTo(JOB_ID);
Assertions.assertThat(metadata.getManifest()).isEqualTo(expectedManifest);
Assertions.assertThat(metadata.getArchiveBaseUri()).isEqualTo(expectedArchiveRootUri);
// Verify that subsequent gets resolved from the cache
final ArchivedJobMetadata cachedMetadata = this.archivedJobService.getArchivedJobMetadata(JOB_ID);
Assertions.assertThat(cachedMetadata).isEqualTo(metadata);
// This should only have actually been used one time despite two service API calls
Mockito
.verify(this.persistenceService, Mockito.times(1))
.getJobArchiveLocation(JOB_ID);
}
static class ArchivedJobServiceConfig {
@Bean
CacheManager cacheManager() {
// provide a cache manager to test caching
return new CaffeineCacheManager();
}
@Bean
ArchivedJobServiceImpl archivedJobService(
final DataServices dataServices,
final ResourceLoader resourceLoader,
final MeterRegistry meterRegistry
) {
return new ArchivedJobServiceImpl(dataServices, resourceLoader, meterRegistry);
}
@Bean
MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@Bean
DataServices dataServices(final PersistenceService persistenceService) {
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(persistenceService);
return dataServices;
}
}
}
| 2,372 |
0 | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/integTest/java/com/netflix/genie/web/services/impl/package-info.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.
*
*/
/**
* Integration tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.services.impl;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,373 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/TaskUtilsTest.java | /*
*
* Copyright 2016 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.genie.web.tasks;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
/**
* Unit tests for the utility methods for task.
*
* @author tgianos
* @since 3.0.0
*/
class TaskUtilsTest {
/**
* Make sure that since we're in the same package we can construct.
*/
@Test
void canConstruct() {
Assertions.assertThat(new TaskUtils()).isNotNull();
}
/**
* Make sure we can get exactly midnight UTC.
*/
@Test
void canGetMidnightUtc() {
final Instant midnightUTC = TaskUtils.getMidnightUTC();
final ZonedDateTime cal = ZonedDateTime.ofInstant(midnightUTC, ZoneId.of("UTC"));
Assertions.assertThat(cal.getNano()).isEqualTo(0);
Assertions.assertThat(cal.getSecond()).isEqualTo(0);
Assertions.assertThat(cal.getMinute()).isEqualTo(0);
Assertions.assertThat(cal.getHour()).isEqualTo(0);
}
}
| 2,374 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/TasksCleanupTest.java | /*
*
* Copyright 2016 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.genie.web.tasks;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* Tests the {@link TasksCleanup} class.
*
* @author tgianos
* @since 3.0.0
*/
class TasksCleanupTest {
private ThreadPoolTaskScheduler scheduler;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.scheduler = Mockito.mock(ThreadPoolTaskScheduler.class);
}
/**
* Make sure the thread pool scheduler is shutdown.
*/
@Test
void canShutdown() {
final ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class);
final TasksCleanup cleanup = new TasksCleanup(this.scheduler);
cleanup.onShutdown(event);
Mockito.verify(this.scheduler, Mockito.times(1)).shutdown();
}
}
| 2,375 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for tasks classes.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.tasks;
| 2,376 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/leader/LocalLeaderTest.java | /*
*
* Copyright 2016 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.genie.web.tasks.leader;
import com.netflix.genie.web.events.GenieEventBus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.integration.leader.event.OnGrantedEvent;
import org.springframework.integration.leader.event.OnRevokedEvent;
/**
* Unit tests for the LocalLeader class.
*
* @author tgianos
* @since 3.0.0
*/
class LocalLeaderTest {
private LocalLeader localLeader;
private GenieEventBus genieEventBus;
private ContextRefreshedEvent contextRefreshedEvent;
private ContextClosedEvent contextClosedEvent;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.genieEventBus = Mockito.mock(GenieEventBus.class);
this.contextRefreshedEvent = Mockito.mock(ContextRefreshedEvent.class);
this.contextClosedEvent = Mockito.mock(ContextClosedEvent.class);
}
/**
* Tear down the tests to prepare for the next iteration.
*/
@AfterEach
void tearDown() {
this.localLeader = null;
}
/**
* Ensure behavior in case of start, stop, start when already running and stop when not running in case the module
* is configured to be leader.
*/
@Test
void startAndStopIfLeader() {
this.localLeader = new LocalLeader(this.genieEventBus, true);
Assertions.assertThat(this.localLeader.isRunning()).isFalse();
Assertions.assertThat(this.localLeader.isLeader()).isFalse();
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
// Start with application context event
this.localLeader.startLeadership(this.contextRefreshedEvent);
Assertions.assertThat(this.localLeader.isRunning()).isTrue();
Assertions.assertThat(this.localLeader.isLeader()).isTrue();
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
// Start again
this.localLeader.start();
Assertions.assertThat(this.localLeader.isRunning()).isTrue();
Assertions.assertThat(this.localLeader.isLeader()).isTrue();
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
// Stop with application context event
this.localLeader.stopLeadership(this.contextClosedEvent);
Assertions.assertThat(this.localLeader.isRunning()).isFalse();
Assertions.assertThat(this.localLeader.isLeader()).isFalse();
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
// Stop again
this.localLeader.stopLeadership(this.contextClosedEvent);
Assertions.assertThat(this.localLeader.isRunning()).isFalse();
Assertions.assertThat(this.localLeader.isLeader()).isFalse();
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
}
/**
* Ensure behavior in case of start, stop in case the module is not configured to be leader.
*/
@Test
void startAndStopIfNotLeader() {
this.localLeader = new LocalLeader(this.genieEventBus, false);
Assertions.assertThat(this.localLeader.isRunning()).isFalse();
Assertions.assertThat(this.localLeader.isLeader()).isFalse();
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
// Start
this.localLeader.start();
Assertions.assertThat(this.localLeader.isRunning()).isTrue();
Assertions.assertThat(this.localLeader.isLeader()).isFalse();
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
// Stop
this.localLeader.stopLeadership(this.contextClosedEvent);
Assertions.assertThat(this.localLeader.isRunning()).isFalse();
Assertions.assertThat(this.localLeader.isLeader()).isFalse();
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnGrantedEvent.class));
Mockito.verify(this.genieEventBus, Mockito.never()).publishSynchronousEvent(Mockito.any(OnRevokedEvent.class));
}
}
| 2,377 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/leader/LeaderTasksCoordinatorTest.java | /*
*
* Copyright 2016 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.genie.web.tasks.leader;
import com.google.common.collect.Sets;
import com.netflix.genie.web.tasks.GenieTaskScheduleType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.integration.leader.Context;
import org.springframework.integration.leader.event.AbstractLeaderEvent;
import org.springframework.integration.leader.event.OnGrantedEvent;
import org.springframework.integration.leader.event.OnRevokedEvent;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
/**
* Unit tests for LeadershipTasksCoordinator.
*
* @author tgianos
* @since 3.0.0
*/
class LeaderTasksCoordinatorTest {
private LeaderTasksCoordinator coordinator;
private TaskScheduler scheduler;
private LeaderTask task1;
private LeaderTask task2;
private LeaderTask task3;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.scheduler = Mockito.mock(TaskScheduler.class);
this.task1 = Mockito.mock(LeaderTask.class);
this.task2 = Mockito.mock(LeaderTask.class);
this.task3 = Mockito.mock(LeaderTask.class);
final Set<LeaderTask> tasks = Sets.newHashSet(this.task1, this.task2, this.task3);
this.coordinator = new LeaderTasksCoordinator(this.scheduler, tasks);
}
/**
* Make sure all leadership activities are started when leadership is granted.
*/
@Test
void canStartLeadershipTasks() {
final long task1Period = 13238;
Mockito.when(this.task1.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_RATE);
Mockito.when(this.task1.getFixedRate()).thenReturn(task1Period);
final long task2Period = 3891082;
Mockito.when(this.task2.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_DELAY);
Mockito.when(this.task2.getFixedDelay()).thenReturn(task2Period);
final Trigger task3Trigger = Mockito.mock(Trigger.class);
Mockito.when(this.task3.getScheduleType()).thenReturn(GenieTaskScheduleType.TRIGGER);
Mockito.when(this.task3.getTrigger()).thenReturn(task3Trigger);
final OnGrantedEvent event = new OnGrantedEvent(this, null, "blah");
this.coordinator.onLeaderEvent(event);
Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);
Mockito.verify(this.task1, Mockito.never()).getFixedDelay();
Mockito.verify(this.task1, Mockito.never()).getTrigger();
Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);
Mockito.verify(this.task2, Mockito.never()).getFixedRate();
Mockito.verify(this.task2, Mockito.never()).getTrigger();
Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);
Mockito.verify(this.task3, Mockito.never()).getFixedRate();
Mockito.verify(this.task3, Mockito.never()).getFixedDelay();
//Make sure a second OnGrantedEvent doesn't do anything if it's already running
this.coordinator.onLeaderEvent(event);
Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);
Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);
Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);
}
/**
* Make sure all leadership activities are stopped when leadership is revoked.
*/
@Test
@SuppressWarnings("unchecked")
void canStopLeadershipTasks() {
final long task1Period = 13238;
Mockito.when(this.task1.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_RATE);
Mockito.when(this.task1.getFixedRate()).thenReturn(task1Period);
final long task2Period = 3891082;
Mockito.when(this.task2.getScheduleType()).thenReturn(GenieTaskScheduleType.FIXED_DELAY);
Mockito.when(this.task2.getFixedDelay()).thenReturn(task2Period);
final Trigger task3Trigger = Mockito.mock(Trigger.class);
Mockito.when(this.task3.getScheduleType()).thenReturn(GenieTaskScheduleType.TRIGGER);
Mockito.when(this.task3.getTrigger()).thenReturn(task3Trigger);
final ScheduledFuture future1 = Mockito.mock(ScheduledFuture.class);
Mockito.when(future1.cancel(true)).thenReturn(true);
Mockito.when(this.scheduler.scheduleAtFixedRate(this.task1, task1Period)).thenReturn(future1);
final ScheduledFuture future2 = Mockito.mock(ScheduledFuture.class);
Mockito.when(future2.cancel(true)).thenReturn(true);
Mockito.when(this.scheduler.scheduleWithFixedDelay(this.task2, task2Period)).thenReturn(future2);
final ScheduledFuture future3 = Mockito.mock(ScheduledFuture.class);
Mockito.when(future3.cancel(true)).thenReturn(false);
Mockito.when(this.scheduler.schedule(this.task3, task3Trigger)).thenReturn(future3);
final OnGrantedEvent grantedEvent = new OnGrantedEvent(this, null, "blah");
this.coordinator.onLeaderEvent(grantedEvent);
Mockito.verify(this.scheduler, Mockito.times(1)).scheduleAtFixedRate(this.task1, task1Period);
Mockito.verify(this.task1, Mockito.never()).getFixedDelay();
Mockito.verify(this.task1, Mockito.never()).getTrigger();
Mockito.verify(this.scheduler, Mockito.times(1)).scheduleWithFixedDelay(this.task2, task2Period);
Mockito.verify(this.task2, Mockito.never()).getFixedRate();
Mockito.verify(this.task2, Mockito.never()).getTrigger();
Mockito.verify(this.scheduler, Mockito.times(1)).schedule(this.task3, task3Trigger);
Mockito.verify(this.task3, Mockito.never()).getFixedRate();
Mockito.verify(this.task3, Mockito.never()).getFixedDelay();
// Should now be running
final OnRevokedEvent revokedEvent = new OnRevokedEvent(this, null, "blah");
this.coordinator.onLeaderEvent(revokedEvent);
Mockito.verify(future1, Mockito.times(1)).cancel(true);
Mockito.verify(future2, Mockito.times(1)).cancel(true);
Mockito.verify(future3, Mockito.times(1)).cancel(true);
// Call again to make sure nothing is invoked even though they were cancelled
this.coordinator.onLeaderEvent(revokedEvent);
Mockito.verify(future1, Mockito.times(1)).cancel(true);
Mockito.verify(future2, Mockito.times(1)).cancel(true);
Mockito.verify(future3, Mockito.times(1)).cancel(true);
}
/**
* Make sure unhandled commands are ignored.
*/
@Test
void doesIgnoreUnknownEvent() {
final AbstractLeaderEvent leaderEvent = new AbstractLeaderEvent(this) {
/**
* Gets the {@link Context} associated with this event.
*
* @return the context
*/
@Override
public Context getContext() {
return new Context() {
@Override
public boolean isLeader() {
return false;
}
@Override
public void yield() {
}
};
}
};
this.coordinator.onLeaderEvent(leaderEvent);
Mockito.verify(
this.scheduler, Mockito.never()).scheduleAtFixedRate(Mockito.any(Runnable.class), Mockito.anyLong()
);
}
}
| 2,378 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/leader/DatabaseCleanupTaskTest.java | /*
*
* Copyright 2016 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.genie.web.tasks.leader;
import com.netflix.genie.common.internal.dtos.ClusterStatus;
import com.netflix.genie.common.internal.dtos.CommandStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.jobs.JobConstants;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.DatabaseCleanupProperties;
import com.netflix.genie.web.tasks.GenieTaskScheduleType;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.CronTrigger;
import java.time.Instant;
import java.util.Calendar;
import java.util.EnumSet;
/**
* Unit tests for {@link DatabaseCleanupTask}.
*
* @author tgianos
* @since 3.0.0
*/
class DatabaseCleanupTaskTest {
private DatabaseCleanupProperties cleanupProperties;
private DatabaseCleanupProperties.ApplicationDatabaseCleanupProperties applicationCleanupProperties;
private DatabaseCleanupProperties.ClusterDatabaseCleanupProperties clusterCleanupProperties;
private DatabaseCleanupProperties.CommandDatabaseCleanupProperties commandCleanupProperties;
private DatabaseCleanupProperties.CommandDeactivationDatabaseCleanupProperties commandDeactivationProperties;
private DatabaseCleanupProperties.FileDatabaseCleanupProperties fileCleanupProperties;
private DatabaseCleanupProperties.JobDatabaseCleanupProperties jobCleanupProperties;
private DatabaseCleanupProperties.TagDatabaseCleanupProperties tagCleanupProperties;
private MockEnvironment environment;
private PersistenceService persistenceService;
private DatabaseCleanupTask task;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.cleanupProperties = Mockito.mock(DatabaseCleanupProperties.class);
this.applicationCleanupProperties
= Mockito.mock(DatabaseCleanupProperties.ApplicationDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getApplicationCleanup()).thenReturn(this.applicationCleanupProperties);
this.clusterCleanupProperties = Mockito.mock(DatabaseCleanupProperties.ClusterDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getClusterCleanup()).thenReturn(this.clusterCleanupProperties);
this.commandCleanupProperties = Mockito.mock(DatabaseCleanupProperties.CommandDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getCommandCleanup()).thenReturn(this.commandCleanupProperties);
this.commandDeactivationProperties
= Mockito.mock(DatabaseCleanupProperties.CommandDeactivationDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getCommandDeactivation()).thenReturn(this.commandDeactivationProperties);
this.fileCleanupProperties = Mockito.mock(DatabaseCleanupProperties.FileDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getFileCleanup()).thenReturn(this.fileCleanupProperties);
this.jobCleanupProperties = Mockito.mock(DatabaseCleanupProperties.JobDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getJobCleanup()).thenReturn(this.jobCleanupProperties);
this.tagCleanupProperties = Mockito.mock(DatabaseCleanupProperties.TagDatabaseCleanupProperties.class);
Mockito.when(this.cleanupProperties.getTagCleanup()).thenReturn(this.tagCleanupProperties);
this.environment = new MockEnvironment();
this.persistenceService = Mockito.mock(PersistenceService.class);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(this.persistenceService);
this.task = new DatabaseCleanupTask(
this.cleanupProperties,
this.environment,
dataServices,
new SimpleMeterRegistry()
);
}
/**
* Make sure the schedule type returns the correct thing.
*/
@Test
void canGetScheduleType() {
Assertions.assertThat(this.task.getScheduleType()).isEqualTo(GenieTaskScheduleType.TRIGGER);
}
/**
* Make sure the trigger returned is accurate.
*/
@Test
void canGetTrigger() {
final String expression = "0 0 1 * * *";
this.environment.setProperty(DatabaseCleanupProperties.EXPRESSION_PROPERTY, expression);
Mockito.when(this.cleanupProperties.getExpression()).thenReturn("0 0 0 * * *");
final Trigger trigger = this.task.getTrigger();
if (trigger instanceof CronTrigger) {
final CronTrigger cronTrigger = (CronTrigger) trigger;
Assertions.assertThat(cronTrigger.getExpression()).isEqualTo(expression);
} else {
Assertions.fail("Trigger was not of expected type: " + CronTrigger.class.getName());
}
}
/**
* Make sure the run method passes in the expected date.
*/
@Test
void canRun() {
final int days = 5;
final int negativeDays = -1 * days;
final int pageSize = 10;
final int batchSize = 100;
final int rollingWindow = 12;
final int batchDaysWithin = 3;
Mockito.when(this.cleanupProperties.getBatchSize()).thenReturn(batchSize);
Mockito.when(this.fileCleanupProperties.getBatchDaysWithin()).thenReturn(batchDaysWithin);
Mockito.when(this.fileCleanupProperties.getRollingWindowHours()).thenReturn(rollingWindow);
Mockito.when(this.jobCleanupProperties.getRetention()).thenReturn(days).thenReturn(negativeDays);
Mockito.when(this.jobCleanupProperties.getPageSize()).thenReturn(pageSize);
Mockito.when(this.commandDeactivationProperties.getCommandCreationThreshold()).thenReturn(60);
final ArgumentCaptor<Instant> argument = ArgumentCaptor.forClass(Instant.class);
final long deletedCount1 = 6L;
final long deletedCount2 = 18L;
final long deletedCount3 = 2L;
Mockito
.when(
this.persistenceService.deleteJobsCreatedBefore(
Mockito.any(Instant.class),
Mockito.eq(JobStatus.getActiveStatuses()),
Mockito.eq(pageSize)
)
)
.thenReturn(deletedCount1)
.thenReturn(0L)
.thenReturn(deletedCount2)
.thenReturn(deletedCount3)
.thenReturn(0L);
Mockito
.when(
this.persistenceService.deleteUnusedClusters(
Mockito.eq(EnumSet.of(ClusterStatus.TERMINATED)),
Mockito.any(Instant.class),
Mockito.eq(batchSize)
)
).thenReturn(1L, 0L, 2L, 0L);
Mockito
.when(this.persistenceService.deleteUnusedFiles(
Mockito.any(Instant.class), Mockito.any(Instant.class), Mockito.eq(batchSize)))
.thenReturn(3L, 0L, 4L, 0L);
Mockito
.when(this.persistenceService.deleteUnusedTags(Mockito.any(Instant.class), Mockito.eq(batchSize)))
.thenReturn(5L, 0L, 6L, 0L);
Mockito
.when(this.persistenceService.deleteUnusedApplications(Mockito.any(Instant.class), Mockito.eq(batchSize)))
.thenReturn(11L, 0L, 100L, 17L, 0L);
Mockito
.when(
this.persistenceService.updateStatusForUnusedCommands(
Mockito.eq(CommandStatus.INACTIVE),
Mockito.any(Instant.class),
Mockito.eq(EnumSet.of(CommandStatus.DEPRECATED, CommandStatus.ACTIVE)),
Mockito.anyInt()
)
)
.thenReturn(50, 0, 242, 0);
Mockito
.when(
this.persistenceService.deleteUnusedCommands(
Mockito.eq(EnumSet.of(CommandStatus.INACTIVE)),
Mockito.any(Instant.class),
Mockito.eq(batchSize)
)
)
.thenReturn(11L, 0L, 81L, 0L);
// The multiple calendar instances are to protect against running this test when the day flips
final Calendar before = Calendar.getInstance(JobConstants.UTC);
this.task.run();
this.task.run();
final Calendar after = Calendar.getInstance(JobConstants.UTC);
if (before.get(Calendar.DAY_OF_YEAR) == after.get(Calendar.DAY_OF_YEAR)) {
Mockito
.verify(this.persistenceService, Mockito.times(5))
.deleteJobsCreatedBefore(
argument.capture(),
Mockito.eq(JobStatus.getActiveStatuses()),
Mockito.eq(pageSize)
);
final Calendar date = Calendar.getInstance(JobConstants.UTC);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
date.add(Calendar.DAY_OF_YEAR, negativeDays);
Assertions.assertThat(argument.getAllValues().get(0).toEpochMilli()).isEqualTo(date.getTime().getTime());
Assertions.assertThat(argument.getAllValues().get(1).toEpochMilli()).isEqualTo(date.getTime().getTime());
Mockito.verify(this.persistenceService, Mockito.times(4)).deleteUnusedClusters(
Mockito.eq(EnumSet.of(ClusterStatus.TERMINATED)),
Mockito.any(Instant.class),
Mockito.eq(batchSize)
);
Mockito
.verify(this.persistenceService, Mockito.times(16))
.deleteUnusedFiles(Mockito.any(Instant.class), Mockito.any(Instant.class), Mockito.eq(batchSize));
Mockito
.verify(this.persistenceService, Mockito.times(4))
.deleteUnusedTags(Mockito.any(Instant.class), Mockito.eq(batchSize));
Mockito
.verify(this.persistenceService, Mockito.times(5))
.deleteUnusedApplications(Mockito.any(Instant.class), Mockito.eq(batchSize));
Mockito
.verify(this.persistenceService, Mockito.times(4))
.deleteUnusedCommands(
Mockito.eq(EnumSet.of(CommandStatus.INACTIVE)),
Mockito.any(Instant.class),
Mockito.eq(batchSize)
);
Mockito
.verify(this.persistenceService, Mockito.times(4))
.updateStatusForUnusedCommands(
Mockito.eq(CommandStatus.INACTIVE),
Mockito.any(Instant.class),
Mockito.eq(EnumSet.of(CommandStatus.DEPRECATED, CommandStatus.ACTIVE)),
Mockito.anyInt()
);
}
}
/**
* Make sure the run method throws when an error is encountered.
*/
@Test
void cantRun() {
final int days = 5;
final int negativeDays = -1 * days;
final int pageSize = 10;
final int batchSize = 100;
Mockito.when(this.cleanupProperties.getBatchSize()).thenReturn(batchSize);
Mockito.when(this.jobCleanupProperties.getRetention()).thenReturn(days).thenReturn(negativeDays);
Mockito.when(this.jobCleanupProperties.getPageSize()).thenReturn(pageSize);
Mockito
.when(
this.persistenceService.deleteJobsCreatedBefore(
Mockito.any(Instant.class),
Mockito.anySet(),
Mockito.anyInt()
)
)
.thenThrow(new RuntimeException("test"));
Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.task.run());
}
/**
* Make sure individual cleanup sub-tasks are skipped according to properties.
*/
@Test
void skipAll() {
this.environment.setProperty(
DatabaseCleanupProperties.ApplicationDatabaseCleanupProperties.SKIP_PROPERTY,
"true"
);
this.environment.setProperty(DatabaseCleanupProperties.CommandDatabaseCleanupProperties.SKIP_PROPERTY, "true");
this.environment.setProperty(
DatabaseCleanupProperties.CommandDeactivationDatabaseCleanupProperties.SKIP_PROPERTY,
"true"
);
this.environment.setProperty(DatabaseCleanupProperties.ClusterDatabaseCleanupProperties.SKIP_PROPERTY, "true");
this.environment.setProperty(DatabaseCleanupProperties.FileDatabaseCleanupProperties.SKIP_PROPERTY, "true");
this.environment.setProperty(DatabaseCleanupProperties.JobDatabaseCleanupProperties.SKIP_PROPERTY, "true");
this.environment.setProperty(DatabaseCleanupProperties.TagDatabaseCleanupProperties.SKIP_PROPERTY, "true");
Mockito.when(this.applicationCleanupProperties.isSkip()).thenReturn(false);
Mockito.when(this.commandCleanupProperties.isSkip()).thenReturn(false);
Mockito.when(this.commandDeactivationProperties.isSkip()).thenReturn(false);
Mockito.when(this.clusterCleanupProperties.isSkip()).thenReturn(false);
Mockito.when(this.fileCleanupProperties.isSkip()).thenReturn(false);
Mockito.when(this.tagCleanupProperties.isSkip()).thenReturn(false);
Mockito.when(this.jobCleanupProperties.isSkip()).thenReturn(false);
this.task.run();
Mockito
.verify(this.persistenceService, Mockito.never())
.deleteUnusedApplications(Mockito.any(Instant.class), Mockito.anyInt());
Mockito
.verify(this.persistenceService, Mockito.never())
.deleteUnusedCommands(Mockito.anySet(), Mockito.any(Instant.class), Mockito.anyInt());
Mockito
.verify(this.persistenceService, Mockito.never())
.updateStatusForUnusedCommands(
Mockito.any(CommandStatus.class),
Mockito.any(Instant.class),
Mockito.anySet(),
Mockito.anyInt()
);
Mockito
.verify(this.persistenceService, Mockito.never())
.deleteJobsCreatedBefore(
Mockito.any(Instant.class),
Mockito.anySet(),
Mockito.anyInt()
);
Mockito
.verify(this.persistenceService, Mockito.never())
.deleteUnusedClusters(Mockito.anySet(), Mockito.any(Instant.class), Mockito.anyInt());
Mockito
.verify(this.persistenceService, Mockito.never())
.deleteUnusedFiles(Mockito.any(Instant.class), Mockito.any(Instant.class), Mockito.anyInt());
Mockito
.verify(this.persistenceService, Mockito.never())
.deleteUnusedTags(Mockito.any(Instant.class), Mockito.anyInt());
}
}
| 2,379 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/leader/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for the leadership related classes.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.tasks.leader;
| 2,380 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/node/DiskCleanupTaskTest.java | /*
*
* Copyright 2016 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.genie.web.tasks.node;
import com.google.common.collect.Lists;
import com.netflix.genie.common.dto.Job;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieServerException;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.DiskCleanupProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.tasks.TaskUtils;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.apache.commons.exec.Executor;
import org.apache.commons.lang3.SystemUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;
/**
* Unit tests for the disk cleanup task.
*
* @author tgianos
* @since 3.0.0
*/
class DiskCleanupTaskTest {
@Test
public void cantConstruct() {
final JobsProperties properties = JobsProperties.getJobsPropertiesDefaults();
properties.getUsers().setRunAsUserEnabled(false);
final Resource jobsDir = Mockito.mock(Resource.class);
Mockito.when(jobsDir.exists()).thenReturn(false);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
Assertions
.assertThatIOException()
.isThrownBy(
() -> new DiskCleanupTask(
new DiskCleanupProperties(),
Mockito.mock(TaskScheduler.class),
jobsDir,
dataServices,
properties,
Mockito.mock(Executor.class),
new SimpleMeterRegistry()
)
);
}
@Test
void wontScheduleOnNonUnixWithSudo() throws IOException {
Assumptions.assumeTrue(!SystemUtils.IS_OS_UNIX);
final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
final Resource jobsDir = Mockito.mock(Resource.class);
Mockito.when(jobsDir.exists()).thenReturn(true);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
Assertions.assertThat(
new DiskCleanupTask(
new DiskCleanupProperties(),
scheduler,
jobsDir,
dataServices,
JobsProperties.getJobsPropertiesDefaults(),
Mockito.mock(Executor.class),
new SimpleMeterRegistry()
)
).isNotNull();
Mockito.verify(scheduler, Mockito.never()).schedule(Mockito.any(Runnable.class), Mockito.any(Trigger.class));
}
@Test
void willScheduleOnUnixWithSudo() throws IOException {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
final Resource jobsDir = Mockito.mock(Resource.class);
Mockito.when(jobsDir.exists()).thenReturn(true);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
Assertions.assertThat(
new DiskCleanupTask(
new DiskCleanupProperties(),
scheduler,
jobsDir,
dataServices,
JobsProperties.getJobsPropertiesDefaults(),
Mockito.mock(Executor.class),
new SimpleMeterRegistry()
)
).isNotNull();
Mockito.verify(scheduler, Mockito.times(1)).schedule(Mockito.any(Runnable.class), Mockito.any(Trigger.class));
}
@Test
void willScheduleOnUnixWithoutSudo() throws IOException {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final JobsProperties properties = JobsProperties.getJobsPropertiesDefaults();
properties.getUsers().setRunAsUserEnabled(false);
final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
final Resource jobsDir = Mockito.mock(Resource.class);
Mockito.when(jobsDir.exists()).thenReturn(true);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
Assertions.assertThat(
new DiskCleanupTask(
new DiskCleanupProperties(),
scheduler,
jobsDir,
dataServices,
properties,
Mockito.mock(Executor.class),
new SimpleMeterRegistry()
)
).isNotNull();
Mockito.verify(scheduler, Mockito.times(1)).schedule(Mockito.any(Runnable.class), Mockito.any(Trigger.class));
}
@Test
void canRunWithoutSudo(@TempDir final Path tempDir) throws IOException, GenieException {
final JobsProperties jobsProperties = JobsProperties.getJobsPropertiesDefaults();
jobsProperties.getUsers().setRunAsUserEnabled(false);
// Create some random junk file that should be ignored
final Path testFile = tempDir.resolve(UUID.randomUUID().toString());
Files.write(testFile, Lists.newArrayList("hi", "bye"));
final DiskCleanupProperties properties = new DiskCleanupProperties();
final Instant threshold = TaskUtils.getMidnightUTC().minus(properties.getRetention(), ChronoUnit.DAYS);
final String job1Id = UUID.randomUUID().toString();
final String job2Id = UUID.randomUUID().toString();
final String job3Id = UUID.randomUUID().toString();
final String job4Id = UUID.randomUUID().toString();
final String job5Id = UUID.randomUUID().toString();
final Job job1 = Mockito.mock(Job.class);
Mockito.when(job1.getStatus()).thenReturn(JobStatus.INIT);
final Job job2 = Mockito.mock(Job.class);
Mockito.when(job2.getStatus()).thenReturn(JobStatus.RUNNING);
final Job job3 = Mockito.mock(Job.class);
Mockito.when(job3.getStatus()).thenReturn(JobStatus.SUCCEEDED);
Mockito.when(job3.getFinished()).thenReturn(Optional.of(threshold.minus(1, ChronoUnit.MILLIS)));
final Job job4 = Mockito.mock(Job.class);
Mockito.when(job4.getStatus()).thenReturn(JobStatus.FAILED);
Mockito.when(job4.getFinished()).thenReturn(Optional.of(threshold));
this.createJobDir(job1Id, tempDir);
this.createJobDir(job2Id, tempDir);
this.createJobDir(job3Id, tempDir);
this.createJobDir(job4Id, tempDir);
this.createJobDir(job5Id, tempDir);
final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
final Resource jobDir = Mockito.mock(Resource.class);
Mockito.when(jobDir.exists()).thenReturn(true);
Mockito.when(jobDir.getFile()).thenReturn(tempDir.toFile());
final PersistenceService persistenceService = Mockito.mock(PersistenceService.class);
Mockito.when(persistenceService.getJob(job1Id)).thenReturn(job1);
Mockito.when(persistenceService.getJob(job2Id)).thenReturn(job2);
Mockito.when(persistenceService.getJob(job3Id)).thenReturn(job3);
Mockito.when(persistenceService.getJob(job4Id)).thenReturn(job4);
Mockito.when(persistenceService.getJob(job5Id)).thenThrow(new GenieServerException("blah"));
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(persistenceService);
final DiskCleanupTask task = new DiskCleanupTask(
properties,
scheduler,
jobDir,
dataServices,
jobsProperties,
Mockito.mock(Executor.class),
new SimpleMeterRegistry()
);
task.run();
Assertions.assertThat(new File(jobDir.getFile(), job1Id).exists()).isTrue();
Assertions.assertThat(new File(jobDir.getFile(), job2Id).exists()).isTrue();
Assertions.assertThat(new File(jobDir.getFile(), job3Id).exists()).isFalse();
Assertions.assertThat(new File(jobDir.getFile(), job4Id).exists()).isTrue();
Assertions.assertThat(new File(jobDir.getFile(), job5Id).exists()).isTrue();
}
private void createJobDir(final String id, final Path tmpDir) throws IOException {
final File dir = Files.createDirectory(tmpDir.resolve(id)).toFile();
for (int i = 0; i < 5; i++) {
new File(dir, UUID.randomUUID().toString());
}
for (int i = 0; i < 5; i++) {
final boolean success = new File(dir, UUID.randomUUID().toString()).mkdir();
if (!success) {
throw new IOException("Unable to create temporary directory.");
}
}
}
}
| 2,381 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/tasks/node/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for node tasks.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.tasks.node;
| 2,382 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/controllers/GenieExceptionMapperTest.java | /*
*
* Copyright 2015 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.genie.web.apis.rest.v3.controllers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.genie.common.exceptions.GenieBadRequestException;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieNotFoundException;
import com.netflix.genie.common.exceptions.GeniePreconditionException;
import com.netflix.genie.common.exceptions.GenieServerException;
import com.netflix.genie.common.exceptions.GenieServerUnavailableException;
import com.netflix.genie.common.exceptions.GenieTimeoutException;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException;
import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException;
import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieApplicationNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieClusterNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieCommandNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieIdAlreadyExistsException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobSpecificationNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException;
import com.netflix.genie.web.exceptions.checked.AttachmentTooLargeException;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.JobNotFoundException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.exceptions.checked.PreconditionFailedException;
import com.netflix.genie.web.exceptions.checked.SaveAttachmentException;
import com.netflix.genie.web.util.MetricsConstants;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import javax.validation.ConstraintViolationException;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Tests for the exception mapper.
*
* @author tgianos
* @since 3.0.0
*/
class GenieExceptionMapperTest {
private GenieExceptionMapper mapper;
private MeterRegistry registry;
private Counter counter;
/**
* Setup for the tests.
*/
@BeforeEach
void setup() {
this.registry = Mockito.mock(MeterRegistry.class);
this.counter = Mockito.mock(Counter.class);
Mockito
.when(
this.registry.counter(
Mockito.eq(GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME),
Mockito.anySet()
)
)
.thenReturn(this.counter);
this.mapper = new GenieExceptionMapper(this.registry);
}
/**
* Test Genie Exceptions.
*/
@Test
void canHandleGenieExceptions() {
final List<GenieException> exceptions = Arrays.asList(
new GenieBadRequestException("bad"),
new GenieNotFoundException("Not Found"),
new GeniePreconditionException("Precondition"),
new GenieServerException("server"),
new GenieServerUnavailableException("Server Unavailable"),
new GenieTimeoutException("Timeout"),
new GenieException(568, "Other")
);
for (final GenieException exception : exceptions) {
final ResponseEntity<GenieException> response = this.mapper.handleGenieException(exception);
final HttpStatus expectedStatus = HttpStatus.resolve(exception.getErrorCode()) != null
? HttpStatus.resolve(exception.getErrorCode())
: HttpStatus.INTERNAL_SERVER_ERROR;
Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(expectedStatus);
Mockito
.verify(this.registry, Mockito.times(1))
.counter(
GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME,
Sets.newHashSet(
Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName())
)
);
}
Mockito
.verify(this.counter, Mockito.times(exceptions.size()))
.increment();
}
/**
* Test constraint violation exceptions.
*/
@Test
void canHandleConstraintViolationExceptions() {
final ConstraintViolationException exception = new ConstraintViolationException("cve", null);
final ResponseEntity<GeniePreconditionException> response = this.mapper.handleConstraintViolation(exception);
Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.PRECONDITION_FAILED);
Mockito
.verify(this.registry, Mockito.times(1))
.counter(
GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME,
Sets.newHashSet(
Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName())
)
);
Mockito
.verify(this.counter, Mockito.times(1))
.increment();
}
/**
* Test method argument not valid exceptions.
*/
@Test
@SuppressFBWarnings(value = "DM_NEW_FOR_GETCLASS", justification = "It's needed for the test")
void canHandleMethodArgumentNotValidExceptions() {
// Method is a final class so can't mock it. Just use the current method.
final Method method = new Object() {
}.getClass().getEnclosingMethod();
final MethodParameter parameter = Mockito.mock(MethodParameter.class);
Mockito.when(parameter.getMethod()).thenReturn(method);
final Executable executable = Mockito.mock(Executable.class);
Mockito.when(parameter.getExecutable()).thenReturn(executable);
Mockito.when(executable.toGenericString()).thenReturn(UUID.randomUUID().toString());
final BindingResult bindingResult = Mockito.mock(BindingResult.class);
Mockito.when(bindingResult.getAllErrors()).thenReturn(Lists.newArrayList());
final MethodArgumentNotValidException exception = new MethodArgumentNotValidException(
parameter,
bindingResult
);
final ResponseEntity<GeniePreconditionException> response =
this.mapper.handleMethodArgumentNotValidException(exception);
Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.PRECONDITION_FAILED);
Mockito
.verify(this.registry, Mockito.times(1))
.counter(
GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME,
Sets.newHashSet(
Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName())
)
);
Mockito
.verify(this.counter, Mockito.times(1))
.increment();
}
/**
* Make sure the Runtime exceptions map to the expected error code.
*/
@Test
void canHandleGenieRuntimeExceptions() {
final Map<GenieRuntimeException, HttpStatus> exceptions = Maps.newHashMap();
exceptions.put(new GenieApplicationNotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new GenieClusterNotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new GenieCommandNotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new GenieJobNotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new GenieJobSpecificationNotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new GenieIdAlreadyExistsException(), HttpStatus.CONFLICT);
exceptions.put(new GenieRuntimeException(), HttpStatus.INTERNAL_SERVER_ERROR);
for (final Map.Entry<GenieRuntimeException, HttpStatus> exception : exceptions.entrySet()) {
final ResponseEntity<GenieRuntimeException> response =
this.mapper.handleGenieRuntimeException(exception.getKey());
Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(exception.getValue());
}
}
/**
* Make sure the Runtime exceptions map to the expected error code.
*/
@Test
void canHandleGenieCheckedExceptions() {
final Map<GenieCheckedException, HttpStatus> exceptions = Maps.newHashMap();
exceptions.put(new GenieJobResolutionException(), HttpStatus.PRECONDITION_FAILED);
exceptions.put(new JobArchiveException(), HttpStatus.INTERNAL_SERVER_ERROR);
exceptions.put(new GenieConversionException(), HttpStatus.INTERNAL_SERVER_ERROR);
exceptions.put(new GenieCheckedException(), HttpStatus.INTERNAL_SERVER_ERROR);
exceptions.put(new IdAlreadyExistsException(), HttpStatus.CONFLICT);
exceptions.put(new JobArchiveException(), HttpStatus.INTERNAL_SERVER_ERROR);
exceptions.put(new SaveAttachmentException(), HttpStatus.INTERNAL_SERVER_ERROR);
exceptions.put(new JobNotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new NotFoundException(), HttpStatus.NOT_FOUND);
exceptions.put(new PreconditionFailedException(), HttpStatus.BAD_REQUEST);
exceptions.put(new AttachmentTooLargeException(), HttpStatus.PAYLOAD_TOO_LARGE);
for (final Map.Entry<GenieCheckedException, HttpStatus> exception : exceptions.entrySet()) {
final ResponseEntity<GenieCheckedException> response =
this.mapper.handleGenieCheckedException(exception.getKey());
Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(exception.getValue());
}
}
}
| 2,383 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/controllers/ControllerUtilsTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.controllers;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
/**
* Unit tests for the ControllerUtils class.
*
* @author tgianos
* @since 3.0.0
*/
class ControllerUtilsTest {
/**
* Test the getRemainingPath method.
*/
@Test
void canGetRemainingPath() {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(null);
Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("");
Mockito
.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
.thenReturn("/api/v3/jobs/1234/output/genie/log.out");
Mockito
.when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))
.thenReturn("/api/v3/jobs/{id}/output/**");
Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("genie/log.out");
Mockito
.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
.thenReturn("/api/v3/jobs/1234/output");
Mockito
.when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))
.thenReturn("/api/v3/jobs/{id}/output");
Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("");
Mockito
.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
.thenReturn("/api/v3/jobs/1234/output/");
Mockito
.when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))
.thenReturn("/api/v3/jobs/{id}/output/");
Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("");
Mockito
.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
.thenReturn("/api/v3/jobs/1234/output/stdout");
Mockito
.when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))
.thenReturn("/api/v3/jobs/{id}/output/**");
Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("stdout");
}
/**
* Test {@link ControllerUtils#getRequestRoot(HttpServletRequest, String)}.
*
* @throws MalformedURLException shouldn't happen
*/
@Test
void canGetRequestRoot() throws MalformedURLException {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final URL requestURL = new URL("https://genie.com/api/v3/jobs/1234/output/genie/genie.done?query=hi#DIV");
final StringBuffer buffer = new StringBuffer(requestURL.toString());
Mockito.when(request.getRequestURL()).thenReturn(buffer);
Assertions
.assertThat(ControllerUtils.getRequestRoot(request, ""))
.isEqualTo(new URL("https://genie.com/api/v3/jobs/1234/output/genie/genie.done"));
Assertions
.assertThat(ControllerUtils.getRequestRoot(request, null))
.isEqualTo(new URL("https://genie.com/api/v3/jobs/1234/output/genie/genie.done"));
Assertions
.assertThat(ControllerUtils.getRequestRoot(request, UUID.randomUUID().toString()))
.isEqualTo(new URL("https://genie.com/api/v3/jobs/1234/output/genie/genie.done"));
Assertions
.assertThat(ControllerUtils.getRequestRoot(request, ".done"))
.isEqualTo(new URL("https://genie.com/api/v3/jobs/1234/output/genie/genie"));
Assertions
.assertThat(ControllerUtils.getRequestRoot(request, "genie/genie.done"))
.isEqualTo(new URL("https://genie.com/api/v3/jobs/1234/output/"));
}
}
| 2,384 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/controllers/JobRestControllerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.controllers;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.JobRequest;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieNotFoundException;
import com.netflix.genie.common.exceptions.GenieServerException;
import com.netflix.genie.common.exceptions.GenieServerUnavailableException;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.common.internal.jobs.JobConstants;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobExecutionModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobMetadataModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobRequestModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobSearchResultModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.RootModelAssembler;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.services.AttachmentService;
import com.netflix.genie.web.services.JobDirectoryServerService;
import com.netflix.genie.web.services.JobKillService;
import com.netflix.genie.web.services.JobLaunchService;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.mock.web.DelegatingServletOutputStream;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
/**
* Unit tests for the Job rest controller.
*
* @author tgianos
* @since 3.0.0
*/
// TODO move these tests over to JobRestControllerSpec
class JobRestControllerTest {
//Mocked variables
private AgentRoutingService agentRoutingService;
private PersistenceService persistenceService;
private String hostname;
private RestTemplate restTemplate;
private JobDirectoryServerService jobDirectoryServerService;
private JobsProperties jobsProperties;
private Environment environment;
private JobKillService jobKillService;
private JobRestController controller;
private static Stream<Arguments> forwardJobOutputTestArguments() {
final HttpHeaders headers = new HttpHeaders();
return Stream.of(
Arguments.of(
HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not found", headers, null, null),
GenieNotFoundException.class
),
Arguments.of(
HttpClientErrorException.create(HttpStatus.INTERNAL_SERVER_ERROR, "Error", headers, null, null),
GenieException.class
),
Arguments.of(
new RuntimeException("..."),
GenieException.class
)
);
}
@BeforeEach
void setup() {
this.persistenceService = Mockito.mock(PersistenceService.class);
this.agentRoutingService = Mockito.mock(AgentRoutingService.class);
this.hostname = UUID.randomUUID().toString();
this.restTemplate = Mockito.mock(RestTemplate.class);
this.jobDirectoryServerService = Mockito.mock(JobDirectoryServerService.class);
this.jobsProperties = JobsProperties.getJobsPropertiesDefaults();
this.environment = Mockito.mock(Environment.class);
this.jobKillService = Mockito.mock(JobKillService.class);
final MeterRegistry registry = Mockito.mock(MeterRegistry.class);
final Counter counter = Mockito.mock(Counter.class);
Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(this.persistenceService);
this.controller = new JobRestController(
Mockito.mock(JobLaunchService.class),
dataServices,
this.createMockResourceAssembler(),
new GenieHostInfo(this.hostname),
this.restTemplate,
this.jobDirectoryServerService,
this.jobsProperties,
registry,
this.agentRoutingService,
this.environment,
Mockito.mock(AttachmentService.class),
this.jobKillService
);
}
@Test
void wontForwardJobOutputRequestIfNotEnabled() throws GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(false);
final String jobId = UUID.randomUUID().toString();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito
.when(request.getRequestURL())
.thenReturn(new StringBuffer("https://localhost:8443/api/v3/jobs/1234/output"));
Mockito
.doNothing()
.when(this.jobDirectoryServerService)
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
Mockito.when(this.persistenceService.getJobStatus(jobId)).thenReturn(JobStatus.RUNNING);
this.controller.getJobOutput(jobId, null, request, response);
Mockito.verify(this.agentRoutingService, Mockito.never()).getHostnameForAgentConnection(jobId);
Mockito
.verify(this.jobDirectoryServerService, Mockito.times(1))
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
}
@Test
void wontForwardJobOutputRequestIfAlreadyForwarded() throws GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(true);
final String jobId = UUID.randomUUID().toString();
final String forwardedFrom = "https://localhost:8443/api/v3/jobs/1234/output";
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito
.doNothing()
.when(this.jobDirectoryServerService)
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
Mockito.when(this.persistenceService.getJobStatus(jobId)).thenReturn(JobStatus.RUNNING);
this.controller.getJobOutput(jobId, forwardedFrom, request, response);
Mockito
.verify(this.jobDirectoryServerService, Mockito.times(1))
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
}
@Test
void wontForwardJobOutputRequestIfOnCorrectHost() throws GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(true);
final String jobId = UUID.randomUUID().toString();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito
.when(request.getRequestURL())
.thenReturn(new StringBuffer("https://" + this.hostname + "/api/v3/jobs/1234/output"));
Mockito
.doNothing()
.when(this.jobDirectoryServerService)
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
Mockito
.when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
.thenReturn(Optional.of(this.hostname));
this.controller.getJobOutput(jobId, null, request, response);
Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
Mockito
.verify(this.restTemplate, Mockito.never())
.execute(
Mockito.anyString(),
Mockito.any(),
Mockito.any(),
Mockito.any(),
Mockito.anyString(),
Mockito.anyString()
);
Mockito
.verify(this.jobDirectoryServerService, Mockito.times(1))
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
}
@Test
void wontThrow404ForJobOutputRequestIfAgentNotFound() throws GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(true);
final String jobId = UUID.randomUUID().toString();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito
.when(request.getRequestURL())
.thenReturn(new StringBuffer("https://" + this.hostname + "/api/v3/jobs/1234/output"));
Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
Mockito.when(this.agentRoutingService.getHostnameForAgentConnection(jobId)).thenReturn(Optional.empty());
Assertions.assertThatThrownBy(
() -> this.controller.getJobOutput(jobId, null, request, response)
).isInstanceOf(GenieServerException.class);
Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(Mockito.eq(jobId));
}
@Test
void wontForwardJobOutputRequestIfForwardingRequestWasForwarded() throws GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(true);
final String jobId = UUID.randomUUID().toString();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito
.when(request.getRequestURL())
.thenReturn(new StringBuffer("https://" + this.hostname + "/api/v3/jobs/1234/output"));
Mockito
.doNothing()
.when(this.jobDirectoryServerService)
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
Mockito
.when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
.thenReturn(Optional.of(UUID.randomUUID().toString()));
Assertions.assertThatThrownBy(
() -> this.controller.getJobOutput(jobId, "https://some-node:1234", request, response)
).isInstanceOf(GenieServerException.class);
Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
Mockito
.verify(this.restTemplate, Mockito.never())
.execute(
Mockito.anyString(),
Mockito.any(),
Mockito.any(),
Mockito.any(),
Mockito.anyString(),
Mockito.anyString()
);
}
@ParameterizedTest(name = "Exception: {0} throws {1}")
@MethodSource("forwardJobOutputTestArguments")
void canHandleForwardJobOutputRequestWithError(
final Throwable forwardingException,
final Class<? extends Throwable> expectedException
) throws GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(true);
final String jobId = UUID.randomUUID().toString();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito
.when(request.getRequestURL())
.thenReturn(new StringBuffer("http://" + this.hostname + ":8080/api/v3/jobs/1234/output"));
Mockito
.doNothing()
.when(this.jobDirectoryServerService)
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
final String jobHostName = UUID.randomUUID().toString();
Mockito
.when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
.thenReturn(Optional.of(jobHostName));
//Mock parts of the http request
final String http = "http";
Mockito.when(request.getScheme()).thenReturn(http);
final int port = 8080;
Mockito.when(request.getServerPort()).thenReturn(port);
final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
Mockito.when(request.getRequestURI()).thenReturn(requestURI);
Mockito.when(request.getHeaderNames()).thenReturn(null);
Mockito.when(
this.restTemplate.execute(
Mockito.anyString(),
Mockito.any(),
Mockito.any(),
Mockito.any()
)
)
.thenThrow(forwardingException);
Assertions.assertThatThrownBy(
() -> this.controller.getJobOutput(jobId, null, request, response)
).isInstanceOf(expectedException);
Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
Mockito.verify(this.restTemplate, Mockito.times(1))
.execute(
Mockito.eq("http://" + jobHostName + ":8080/api/v3/jobs/" + jobId + "/output/"),
Mockito.eq(HttpMethod.GET),
Mockito.any(),
Mockito.any()
);
}
@Test
void canHandleForwardJobOutputRequestWithSuccess() throws IOException, GenieException, GenieCheckedException {
this.jobsProperties.getForwarding().setEnabled(true);
final String jobId = UUID.randomUUID().toString();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
final String jobHostName = UUID.randomUUID().toString();
Mockito
.when(request.getRequestURL())
.thenReturn(new StringBuffer("http://localhost:8080/api/v3/jobs/1234/output"));
Mockito
.doNothing()
.when(this.jobDirectoryServerService)
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
Mockito
.when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
.thenReturn(Optional.of(jobHostName));
//Mock parts of the http request
final String http = "http";
Mockito.when(request.getScheme()).thenReturn(http);
final int port = 8080;
Mockito.when(request.getServerPort()).thenReturn(port);
final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
Mockito.when(request.getRequestURI()).thenReturn(requestURI);
final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT);
Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames));
Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE);
//Mock parts of forward response
final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class);
final StatusLine statusLine = Mockito.mock(StatusLine.class);
Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine);
final int successCode = 200;
Mockito.when(statusLine.getStatusCode()).thenReturn(successCode);
final Header contentTypeHeader = Mockito.mock(Header.class);
Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE);
Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE);
Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[]{contentTypeHeader});
final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString();
final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
final HttpEntity entity = Mockito.mock(HttpEntity.class);
Mockito.when(entity.getContent()).thenReturn(bis);
Mockito.when(forwardResponse.getEntity()).thenReturn(entity);
final DelegatingServletOutputStream bos = new DelegatingServletOutputStream(new ByteArrayOutputStream());
Mockito.when(response.getOutputStream()).thenReturn(bos);
final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class);
final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class);
Mockito.when(clientHttpRequest.execute())
.thenReturn(new MockClientHttpResponse(text.getBytes(StandardCharsets.UTF_8), HttpStatus.OK));
Mockito.when(clientHttpRequest.getHeaders())
.thenReturn(new HttpHeaders());
Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest);
final RestTemplate template = new RestTemplate(factory);
final MeterRegistry registry = Mockito.mock(MeterRegistry.class);
final Counter counter = Mockito.mock(Counter.class);
Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter);
final DataServices dataServices = Mockito.mock(DataServices.class);
Mockito.when(dataServices.getPersistenceService()).thenReturn(this.persistenceService);
final JobRestController jobController = new JobRestController(
Mockito.mock(JobLaunchService.class),
dataServices,
this.createMockResourceAssembler(),
new GenieHostInfo(this.hostname),
template,
this.jobDirectoryServerService,
this.jobsProperties,
registry,
this.agentRoutingService,
this.environment,
Mockito.mock(AttachmentService.class),
this.jobKillService
);
jobController.getJobOutput(jobId, null, request, response);
Assertions.assertThat(bos.getTargetStream().toString()).isEqualTo(text);
Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT);
Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt());
Mockito
.verify(this.jobDirectoryServerService, Mockito.never())
.serveResource(
Mockito.eq(jobId),
Mockito.any(URL.class),
Mockito.anyString(),
Mockito.eq(request),
Mockito.eq(response)
);
}
/**
* Make sure when job submission is disabled it won't run the job and will return the proper error message.
*/
@Test
void whenJobSubmissionIsDisabledItThrowsCorrectError() {
final String errorMessage = UUID.randomUUID().toString();
Mockito.when(
this.environment.getProperty(
JobConstants.JOB_SUBMISSION_ENABLED_PROPERTY_KEY,
Boolean.class,
true
)
).thenReturn(false);
Mockito.when(
this.environment.getProperty(
JobConstants.JOB_SUBMISSION_DISABLED_MESSAGE_KEY,
JobConstants.JOB_SUBMISSION_DISABLED_DEFAULT_MESSAGE
)
).thenReturn(errorMessage);
Assertions
.assertThatExceptionOfType(GenieServerUnavailableException.class)
.isThrownBy(() ->
this.controller.submitJob(
Mockito.mock(JobRequest.class),
null,
null,
Mockito.mock(HttpServletRequest.class)
))
.withMessage(errorMessage);
}
private EntityModelAssemblers createMockResourceAssembler() {
return new EntityModelAssemblers(
Mockito.mock(ApplicationModelAssembler.class),
Mockito.mock(ClusterModelAssembler.class),
Mockito.mock(CommandModelAssembler.class),
Mockito.mock(JobExecutionModelAssembler.class),
Mockito.mock(JobMetadataModelAssembler.class),
Mockito.mock(JobRequestModelAssembler.class),
Mockito.mock(JobModelAssembler.class),
Mockito.mock(JobSearchResultModelAssembler.class),
Mockito.mock(RootModelAssembler.class)
);
}
}
| 2,385 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/controllers/package-info.java | /*
*
* Copyright 2015 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.
*
*/
/**
* Classes to test the controller classes.
*
* @author tgianos
*/
package com.netflix.genie.web.apis.rest.v3.controllers;
| 2,386 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobSearchResultModelAssemblerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.hateoas.assemblers;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.dto.search.JobSearchResult;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import java.time.Instant;
import java.util.UUID;
/**
* Unit tests for the {@link JobSearchResultModelAssembler}.
*
* @author tgianos
* @since 3.0.0
*/
class JobSearchResultModelAssemblerTest {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = UUID.randomUUID().toString();
private static final String USER = UUID.randomUUID().toString();
private static final Instant STARTED = Instant.now();
private static final Instant FINISHED = Instant.now();
private static final String CLUSTER_NAME = UUID.randomUUID().toString();
private static final String COMMAND_NAME = UUID.randomUUID().toString();
private JobSearchResult jobSearchResult;
private JobSearchResultModelAssembler assembler;
@BeforeEach
void setup() {
this.jobSearchResult
= new JobSearchResult(ID, NAME, USER, JobStatus.SUCCEEDED, STARTED, FINISHED, CLUSTER_NAME, COMMAND_NAME);
this.assembler = new JobSearchResultModelAssembler();
}
@Test
void canConstruct() {
Assertions.assertThat(this.assembler).isNotNull();
}
@Test
void canConvertToResource() {
final EntityModel<JobSearchResult> model = this.assembler.toModel(this.jobSearchResult);
Assertions.assertThat(model.getLinks()).hasSize(1);
Assertions.assertThat(model.getLink("self")).isNotNull();
}
}
| 2,387 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/ApplicationModelAssemblerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.hateoas.assemblers;
import com.netflix.genie.common.dto.Application;
import com.netflix.genie.common.dto.ApplicationStatus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import java.util.UUID;
/**
* Unit tests for the ApplicationResourceAssembler.
*
* @author tgianos
* @since 3.0.0
*/
class ApplicationModelAssemblerTest {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = UUID.randomUUID().toString();
private static final String USER = UUID.randomUUID().toString();
private static final String VERSION = UUID.randomUUID().toString();
private Application application;
private ApplicationModelAssembler assembler;
@BeforeEach
void setup() {
this.application = new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build();
this.assembler = new ApplicationModelAssembler();
}
@Test
void canConstruct() {
Assertions.assertThat(this.assembler).isNotNull();
}
@Test
void canConvertToModel() {
final EntityModel<Application> model = this.assembler.toModel(this.application);
Assertions.assertThat(model.getLinks()).hasSize(2);
Assertions.assertThat(model.getLink("self")).isPresent();
Assertions.assertThat(model.getLink("commands")).isPresent();
}
}
| 2,388 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobModelAssemblerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.hateoas.assemblers;
import com.netflix.genie.common.dto.Job;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import java.util.UUID;
/**
* Unit tests for the JobResourceAssembler.
*
* @author tgianos
* @since 3.0.0
*/
class JobModelAssemblerTest {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = UUID.randomUUID().toString();
private static final String USER = UUID.randomUUID().toString();
private static final String VERSION = UUID.randomUUID().toString();
private Job job;
private JobModelAssembler assembler;
@BeforeEach
void setup() {
this.job = new Job.Builder(NAME, USER, VERSION).withId(ID).build();
this.assembler = new JobModelAssembler();
}
@Test
public void canConstruct() {
Assertions.assertThat(this.assembler).isNotNull();
}
@Test
public void canConvertToModel() {
final EntityModel<Job> model = this.assembler.toModel(this.job);
Assertions.assertThat(model.getLinks()).hasSize(9);
Assertions.assertThat(model.getLink("self")).isPresent();
Assertions.assertThat(model.getLink("output")).isPresent();
Assertions.assertThat(model.getLink("request")).isPresent();
Assertions.assertThat(model.getLink("execution")).isPresent();
Assertions.assertThat(model.getLink("metadata")).isPresent();
Assertions.assertThat(model.getLink("status")).isPresent();
Assertions.assertThat(model.getLink("cluster")).isPresent();
Assertions.assertThat(model.getLink("command")).isPresent();
Assertions.assertThat(model.getLink("applications")).isPresent();
}
}
| 2,389 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/CommandModelAssemblerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.hateoas.assemblers;
import com.google.common.collect.Lists;
import com.netflix.genie.common.dto.Command;
import com.netflix.genie.common.dto.CommandStatus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import java.util.List;
import java.util.UUID;
/**
* Unit tests for the CommandResourceAssembler.
*
* @author tgianos
* @since 3.0.0
*/
public class CommandModelAssemblerTest {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = UUID.randomUUID().toString();
private static final String USER = UUID.randomUUID().toString();
private static final String VERSION = UUID.randomUUID().toString();
private static final List<String> EXECUTABLE_AND_ARGS = Lists.newArrayList(UUID.randomUUID().toString());
private Command command;
private CommandModelAssembler assembler;
@BeforeEach
void setup() {
this.command = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS)
.withId(ID)
.build();
this.assembler = new CommandModelAssembler();
}
@Test
void canConstruct() {
Assertions.assertThat(this.assembler).isNotNull();
}
@Test
void canConvertToResource() {
final EntityModel<Command> model = this.assembler.toModel(this.command);
Assertions.assertThat(model.getLinks()).hasSize(3);
Assertions.assertThat(model.getLink("self")).isPresent();
Assertions.assertThat(model.getLink("applications")).isPresent();
Assertions.assertThat(model.getLink("clusters")).isPresent();
}
}
| 2,390 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/ClusterModelAssemblerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.hateoas.assemblers;
import com.netflix.genie.common.dto.Cluster;
import com.netflix.genie.common.dto.ClusterStatus;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import java.util.UUID;
/**
* Unit tests for the ClusterResourceAssembler.
*
* @author tgianos
* @since 3.0.0
*/
class ClusterModelAssemblerTest {
private static final String ID = UUID.randomUUID().toString();
private static final String NAME = UUID.randomUUID().toString();
private static final String USER = UUID.randomUUID().toString();
private static final String VERSION = UUID.randomUUID().toString();
private Cluster cluster;
private ClusterModelAssembler assembler;
@BeforeEach
void setup() {
this.cluster = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build();
this.assembler = new ClusterModelAssembler();
}
@Test
void canConstruct() {
Assertions.assertThat(this.assembler).isNotNull();
}
@Test
void canConvertToModel() {
final EntityModel<Cluster> model = this.assembler.toModel(this.cluster);
Assertions.assertThat(model.getLinks()).hasSize(2);
Assertions.assertThat(model.getLink("self")).isPresent();
Assertions.assertThat(model.getLink("commands")).isPresent();
}
}
| 2,391 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/RootModelAssemblerTest.java | /*
*
* Copyright 2016 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.genie.web.apis.rest.v3.hateoas.assemblers;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.EntityModel;
import java.util.HashMap;
import java.util.Map;
/**
* Unit tests for the {@link RootModelAssembler}.
*
* @author tgianos
* @since 3.0.0
*/
class RootModelAssemblerTest {
private RootModelAssembler assembler;
@BeforeEach
void setup() {
this.assembler = new RootModelAssembler();
}
@Test
void canConstruct() {
Assertions.assertThat(this.assembler).isNotNull();
}
@Test
void canConvertToResource() {
final Map<String, String> metadata = new HashMap<>();
metadata.put("description", "blah");
final EntityModel<Map<String, String>> model = this.assembler.toModel(metadata);
Assertions.assertThat(model.getLinks()).hasSize(5);
Assertions.assertThat(model.getContent()).isNotNull();
Assertions.assertThat(model.getLink("self")).isNotNull();
Assertions.assertThat(model.getLink("applications")).isNotNull();
Assertions.assertThat(model.getLink("commands")).isNotNull();
Assertions.assertThat(model.getLink("clusters")).isNotNull();
Assertions.assertThat(model.getLink("jobs")).isNotNull();
}
}
| 2,392 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for the resource assemblers.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers;
| 2,393 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/util/UNIXUtilsTest.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.genie.web.util;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.Executor;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Unit Tests for {@link UNIXUtils} class.
*
* @author mprimi
* @since 4.0.0
*/
class UNIXUtilsTest {
private Executor executor;
@BeforeEach
void setUp() {
this.executor = Mockito.mock(Executor.class);
}
@Test
void testChangeOwnershipOfDirectoryMethodSuccess() throws IOException {
final String user = "user";
final String dir = "dir";
final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class);
final List<String> command = Arrays.asList("sudo", "chown", "-R", user, dir);
UNIXUtils.changeOwnershipOfDirectory(dir, user, executor);
Mockito.verify(this.executor).execute(argumentCaptor.capture());
Assertions.assertThat(argumentCaptor.getValue().toStrings()).containsExactlyElementsOf(command);
}
@Test
void testChangeOwnershipOfDirectoryMethodFailure() throws IOException {
final String user = "user";
final String dir = "dir";
Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException());
Assertions.assertThatIOException().isThrownBy(() -> UNIXUtils.changeOwnershipOfDirectory(dir, user, executor));
}
@Test
void testCreateUserMethodSuccessAlreadyExists() throws IOException {
final String user = "user";
final String group = "group";
final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class);
final List<String> command = Arrays.asList("id", "-u", user);
UNIXUtils.createUser(user, group, executor);
Mockito.verify(this.executor).execute(argumentCaptor.capture());
Assertions.assertThat(argumentCaptor.getValue().toStrings()).containsExactlyElementsOf(command);
}
@Test
void testCreateUserMethodSuccessDoesNotExist1() throws IOException {
final String user = "user";
final String group = "group";
final CommandLine idCheckCommandLine = new CommandLine("id");
idCheckCommandLine.addArgument("-u");
idCheckCommandLine.addArgument(user);
Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException());
final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class);
final List<String> command = Arrays.asList("sudo", "useradd", user, "-G", group, "-M");
try {
UNIXUtils.createUser(user, group, executor);
} catch (IOException ignored) {
}
Mockito.verify(this.executor, Mockito.times(3)).execute(argumentCaptor.capture());
Assertions.assertThat(argumentCaptor.getAllValues().get(2).toStrings()).containsExactlyElementsOf(command);
}
@Test
void testCreateUserMethodSuccessDoesNotExist2() throws IOException {
final String user = "user";
final String group = "group";
Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException());
Assertions.assertThatIOException().isThrownBy(() -> UNIXUtils.createUser(user, group, executor));
}
}
| 2,394 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/util/package-info.java | /*
*
* Copyright 2015 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.
*
*/
/**
* Classes to test the utility classes.
*
* @author tgianos
*/
package com.netflix.genie.web.util;
| 2,395 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/resources/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for any web resource related classes.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.resources;
| 2,396 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/resources | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/resources/writers/DefaultDirectoryWriterTest.java | /*
*
* Copyright 2016 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.genie.web.resources.writers;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.w3c.tidy.Tidy;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
/**
* Unit tests for the DefaultDirectoryWriter.
*
* @author tgianos
* @since 3.0.0
*/
class DefaultDirectoryWriterTest {
private static final String REQUEST_URL_BASE
= "https://genie.netflix.com:8080/api/v3/jobs/" + UUID.randomUUID() + "/output";
private static final String REQUEST_URL_WITH_PARENT = REQUEST_URL_BASE + "/" + UUID.randomUUID();
private static final long PARENT_SIZE = 0L;
private static final Instant PARENT_LAST_MODIFIED = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final String PARENT_NAME = "../";
private static final String PARENT_URL = REQUEST_URL_BASE;
private static final long DIR_1_SIZE = 0L;
private static final Instant DIR_1_LAST_MODIFIED = Instant.now().plus(13142, ChronoUnit.MILLIS);
private static final String DIR_1_NAME = UUID.randomUUID().toString();
private static final String DIR_1_URL = REQUEST_URL_WITH_PARENT + "/" + DIR_1_NAME;
private static final long DIR_2_SIZE = 0L;
private static final Instant DIR_2_LAST_MODIFIED = Instant.now().minus(1830, ChronoUnit.MILLIS);
private static final String DIR_2_NAME = UUID.randomUUID().toString();
private static final String DIR_2_URL = REQUEST_URL_WITH_PARENT + "/" + DIR_2_NAME;
private static final long FILE_1_SIZE = 73522431;
private static final Instant FILE_1_LAST_MODIFIED = Instant.now().plus(1832430, ChronoUnit.MILLIS);
private static final String FILE_1_NAME = UUID.randomUUID().toString();
private static final String FILE_1_URL = REQUEST_URL_WITH_PARENT + "/" + FILE_1_NAME;
private static final long FILE_2_SIZE = 735231;
private static final Instant FILE_2_LAST_MODIFIED = Instant.now().plus(1832443, ChronoUnit.MILLIS);
private static final String FILE_2_NAME = UUID.randomUUID().toString();
private static final String FILE_2_URL = REQUEST_URL_WITH_PARENT + "/" + FILE_2_NAME;
private DefaultDirectoryWriter writer;
private File directory;
private DefaultDirectoryWriter.Entry directoryEntry1;
private DefaultDirectoryWriter.Entry directoryEntry2;
private DefaultDirectoryWriter.Entry fileEntry1;
private DefaultDirectoryWriter.Entry fileEntry2;
/**
* Setup the tests.
*/
@BeforeEach
void setup() {
this.writer = new DefaultDirectoryWriter();
this.directory = Mockito.mock(File.class);
Mockito.when(this.directory.isDirectory()).thenReturn(true);
final String slash = "/";
this.directoryEntry1 = new DefaultDirectoryWriter.Entry();
this.directoryEntry1.setLastModified(DIR_1_LAST_MODIFIED);
this.directoryEntry1.setSize(DIR_1_SIZE);
this.directoryEntry1.setUrl(DIR_1_URL + slash);
this.directoryEntry1.setName(DIR_1_NAME + slash);
this.directoryEntry2 = new DefaultDirectoryWriter.Entry();
this.directoryEntry2.setLastModified(DIR_2_LAST_MODIFIED);
this.directoryEntry2.setSize(DIR_2_SIZE);
this.directoryEntry2.setUrl(DIR_2_URL + slash);
this.directoryEntry2.setName(DIR_2_NAME + slash);
this.fileEntry1 = new DefaultDirectoryWriter.Entry();
this.fileEntry1.setLastModified(FILE_1_LAST_MODIFIED);
this.fileEntry1.setSize(FILE_1_SIZE);
this.fileEntry1.setUrl(FILE_1_URL);
this.fileEntry1.setName(FILE_1_NAME);
this.fileEntry2 = new DefaultDirectoryWriter.Entry();
this.fileEntry2.setLastModified(FILE_2_LAST_MODIFIED);
this.fileEntry2.setSize(FILE_2_SIZE);
this.fileEntry2.setUrl(FILE_2_URL);
this.fileEntry2.setName(FILE_2_NAME);
}
/**
* Make sure if the argument passed in isn't a directory an exception is thrown.
*/
@Test
void cantGetDirectoryWithoutValidDirectory() {
Mockito.when(this.directory.isDirectory()).thenReturn(false);
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> this.writer.getDirectory(this.directory, UUID.randomUUID().toString(), false));
}
/**
* Make sure an exception is thrown when no request URL is passed in to the method.
*/
@Test
void cantGetDirectoryWithoutRequestUrl() {
Assertions
.assertThatIllegalArgumentException()
.isThrownBy(() -> this.writer.getDirectory(this.directory, null, false));
}
/**
* Make sure can get a directory with a parent.
*/
@Test
void canGetDirectoryWithParent() {
this.setupWithParent();
final DefaultDirectoryWriter.Directory dir
= this.writer.getDirectory(this.directory, REQUEST_URL_WITH_PARENT, true);
Assertions.assertThat(dir.getParent()).isNotNull();
Assertions.assertThat(dir.getParent().getName()).isEqualTo(PARENT_NAME);
Assertions.assertThat(dir.getParent().getUrl()).isEqualTo(PARENT_URL);
Assertions.assertThat(dir.getParent().getSize()).isEqualTo(PARENT_SIZE);
Assertions.assertThat(dir.getParent().getLastModified()).isEqualTo(PARENT_LAST_MODIFIED);
Assertions.assertThat(dir.getDirectories()).isNotNull();
Assertions
.assertThat(dir.getDirectories())
.containsExactlyInAnyOrder(this.directoryEntry1, this.directoryEntry2);
Assertions.assertThat(dir.getFiles()).isNotNull();
Assertions.assertThat(dir.getFiles()).containsExactlyInAnyOrder(this.fileEntry1, this.fileEntry2);
}
/**
* Make sure can get a directory without a parent.
*/
@Test
void canGetDirectoryWithoutParent() {
this.setupWithoutParent();
final DefaultDirectoryWriter.Directory dir
= this.writer.getDirectory(this.directory, REQUEST_URL_BASE, false);
Assertions.assertThat(dir.getParent()).isNull();
Assertions.assertThat(dir.getDirectories()).isNotNull();
Assertions.assertThat(dir.getDirectories().isEmpty()).isTrue();
Assertions.assertThat(dir.getFiles()).isNotNull();
Assertions.assertThat(dir.getFiles().isEmpty()).isTrue();
}
/**
* Make sure can get html representation of the directory.
*
* @throws Exception on any problem
*/
@Test
void canConvertToHtml() throws Exception {
this.setupWithParent();
final String html = this.writer.toHtml(this.directory, REQUEST_URL_WITH_PARENT, true);
Assertions.assertThat(html).isNotNull();
// Not going to parse the whole HTML to validate contents, too much work.
// So just make sure HTML is valid so at least it doesn't cause error in browser
final Tidy tidy = new Tidy();
final Writer stringWriter = new StringWriter();
tidy.parse(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), stringWriter);
Assertions.assertThat(tidy.getParseErrors()).isEqualTo(0);
Assertions.assertThat(tidy.getParseWarnings()).isEqualTo(0);
}
/**
* Make sure can get a json representation of the directory.
*
* @throws Exception on any problem
*/
@Test
void canConvertToJson() throws Exception {
this.setupWithParent();
final String json = this.writer.toJson(this.directory, REQUEST_URL_WITH_PARENT, true);
Assertions.assertThat(json).isNotNull();
final DefaultDirectoryWriter.Directory dir
= GenieObjectMapper.getMapper().readValue(json, DefaultDirectoryWriter.Directory.class);
Assertions.assertThat(dir.getParent()).isNotNull();
Assertions.assertThat(dir.getParent().getName()).isEqualTo(PARENT_NAME);
Assertions.assertThat(dir.getParent().getUrl()).isEqualTo(PARENT_URL);
Assertions.assertThat(dir.getParent().getSize()).isEqualTo(PARENT_SIZE);
Assertions.assertThat(dir.getParent().getLastModified()).isEqualTo(PARENT_LAST_MODIFIED);
Assertions.assertThat(dir.getDirectories()).isNotNull();
Assertions
.assertThat(dir.getDirectories())
.containsExactlyInAnyOrder(this.directoryEntry1, this.directoryEntry2);
Assertions.assertThat(dir.getFiles()).isNotNull();
Assertions
.assertThat(dir.getFiles())
.containsExactlyInAnyOrder(this.fileEntry1, this.fileEntry2);
}
private void setupWithoutParent() {
Mockito.when(this.directory.listFiles()).thenReturn(null);
}
private void setupWithParent() {
final File parent = Mockito.mock(File.class);
final File absoluteParent = Mockito.mock(File.class);
Mockito.when(parent.getAbsoluteFile()).thenReturn(absoluteParent);
Mockito.when(absoluteParent.length()).thenReturn(PARENT_SIZE);
Mockito.when(absoluteParent.lastModified()).thenReturn(PARENT_LAST_MODIFIED.toEpochMilli());
Mockito.when(parent.getName()).thenReturn(PARENT_NAME);
Mockito.when(this.directory.getParentFile()).thenReturn(parent);
final File dir1 = Mockito.mock(File.class);
final File absoluteDir1 = Mockito.mock(File.class);
Mockito.when(dir1.getAbsoluteFile()).thenReturn(absoluteDir1);
Mockito.when(absoluteDir1.length()).thenReturn(DIR_1_SIZE);
Mockito.when(absoluteDir1.lastModified()).thenReturn(DIR_1_LAST_MODIFIED.toEpochMilli());
Mockito.when(dir1.getName()).thenReturn(DIR_1_NAME);
Mockito.when(dir1.isDirectory()).thenReturn(true);
final File dir2 = Mockito.mock(File.class);
final File absoluteDir2 = Mockito.mock(File.class);
Mockito.when(dir2.getAbsoluteFile()).thenReturn(absoluteDir2);
Mockito.when(absoluteDir2.length()).thenReturn(DIR_2_SIZE);
Mockito.when(absoluteDir2.lastModified()).thenReturn(DIR_2_LAST_MODIFIED.toEpochMilli());
Mockito.when(dir2.getName()).thenReturn(DIR_2_NAME);
Mockito.when(dir2.isDirectory()).thenReturn(true);
final File file1 = Mockito.mock(File.class);
final File absoluteFile1 = Mockito.mock(File.class);
Mockito.when(file1.getAbsoluteFile()).thenReturn(absoluteFile1);
Mockito.when(absoluteFile1.length()).thenReturn(FILE_1_SIZE);
Mockito.when(absoluteFile1.lastModified()).thenReturn(FILE_1_LAST_MODIFIED.toEpochMilli());
Mockito.when(file1.getName()).thenReturn(FILE_1_NAME);
Mockito.when(file1.isDirectory()).thenReturn(false);
final File file2 = Mockito.mock(File.class);
final File absoluteFile2 = Mockito.mock(File.class);
Mockito.when(file2.getAbsoluteFile()).thenReturn(absoluteFile2);
Mockito.when(absoluteFile2.length()).thenReturn(FILE_2_SIZE);
Mockito.when(absoluteFile2.lastModified()).thenReturn(FILE_2_LAST_MODIFIED.toEpochMilli());
Mockito.when(file2.getName()).thenReturn(FILE_2_NAME);
Mockito.when(file2.isDirectory()).thenReturn(false);
final File[] files = new File[]{dir1, file1, dir2, file2};
Mockito.when(this.directory.listFiles()).thenReturn(files);
}
}
| 2,397 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/resources | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/resources/writers/package-info.java | /*
*
* Copyright 2016 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.
*
*/
/**
* Tests for the resource writers.
*
* @author tgianos
* @since 3.0.0
*/
package com.netflix.genie.web.resources.writers;
| 2,398 |
0 | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/test/java/com/netflix/genie/web/properties/DiskCleanupPropertiesTest.java | /*
*
* Copyright 2016 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.genie.web.properties;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.UUID;
/**
* Unit tests for DiskCleanupProperties.
*
* @author tgianos
* @since 3.0.0
*/
class DiskCleanupPropertiesTest {
private DiskCleanupProperties properties;
/**
* Setup for tests.
*/
@BeforeEach
void setup() {
this.properties = new DiskCleanupProperties();
}
/**
* Make sure constructor sets reasonable defaults.
*/
@Test
void canGetDefaultValues() {
Assertions.assertThat(this.properties.isEnabled()).isFalse();
Assertions.assertThat(this.properties.getExpression()).isEqualTo("0 0 0 * * *");
Assertions.assertThat(this.properties.getRetention()).isEqualTo(3);
}
/**
* Make sure can enable.
*/
@Test
void canEnable() {
this.properties.setEnabled(true);
Assertions.assertThat(this.properties.isEnabled()).isTrue();
}
/**
* Make sure can set a new cron expression.
*/
@Test
void canSetExpression() {
final String expression = UUID.randomUUID().toString();
this.properties.setExpression(expression);
Assertions.assertThat(this.properties.getExpression()).isEqualTo(expression);
}
/**
* Make sure can set a new retention time.
*/
@Test
void canSetRetention() {
final int retention = 2318;
this.properties.setRetention(retention);
Assertions.assertThat(this.properties.getRetention()).isEqualTo(retention);
}
}
| 2,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.