diff --git a/CHANGELOG.md b/CHANGELOG.md index deb0be2..a5a6a2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## Release (2025-xx-xx) +- `core`: [v0.3.0](core/CHANGELOG.md#v030) + - **Feature:** Added core wait handler structure which can be used by every service waiter implementation. +- `resourcemanager`: [v0.3.0](services/resourcemanager/CHANGELOG.md#v030) + - **Feature:** Added waiter for project creation and project deletion + ## Release (2025-09-30) - `core`: [v0.2.0](core/CHANGELOG.md#v020) - **Feature:** Support for passing custom OkHttpClient objects diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 3986331..17a69e9 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -7,6 +7,9 @@ We greatly value your feedback, feature requests, additions to the code, bug rep - [Developer Guide](#developer-guide) - [Repository structure](#repository-structure) + - [Implementing a module waiter](#implementing-a-module-waiter) + - [Waiter structure](#waiter-structure) + - [Notes](#notes) - [Code Contributions](#code-contributions) - [Bug Reports](#bug-reports) @@ -39,6 +42,29 @@ The files located in `services/[service]` are automatically generated from the [ Inside the `core` submodule you can find several classes that are used by all service modules. Examples of usage of the SDK are located in the `examples` directory. +### Implementing a service waiter + +Waiters are routines that wait for the completion of asynchronous operations. They are located in a package named `wait` inside each service project. + +Let's suppose you want to implement the waiters for the `Create`, `Update` and `Delete` operations of a resource `bar` of service `foo`: + +1. Start by creating a new Java package `cloud.stackit.sdk..wait` inside `services/foo/` project, if it doesn't exist yet +2. Create a file `FooWait.java` inside your new Java package `cloud.stackit.sdk.resourcemanager.wait`, if it doesn't exist yet. The class should be named `FooWait`. +3. Refer to the [Waiter structure](./CONTRIBUTION.md/#waiter-structure) section for details on the structure of the file and the methods +4. Add unit tests to the wait functions + +#### Waiter structure + +You can find a typical waiter structure here: [Example](./services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/wait/ResourcemanagerWait.java) + +#### Notes + +- The success condition may vary from service to service. In the example above we wait for the field `Status` to match a successful or failed message, but other services may have different fields and/or values to represent the state of the create, update or delete operations. +- The `id` and the `state` might not be present on the root level of the API response, this also varies from service to service. You must always match the resource `id` and the resource `state` to what is expected. +- The timeout values included above are just for reference, each resource takes different amounts of time to finish the create, update or delete operations. You should account for some buffer, e.g. 15 minutes, on top of normal execution times. +- For some resources, after a successful delete operation the resource can't be found anymore, so a call to the `Get` method would result in an error. In those cases, the waiter can be implemented by calling the `List` method and check that the resource is not present. +- The main objective of the waiter functions is to make sure that the operation was successful, which means any other special cases such as intermediate error states should also be handled. + ## Code Contributions To make your contribution, follow these steps: diff --git a/core/src/main/java/cloud/stackit/sdk/core/exception/ApiException.java b/core/src/main/java/cloud/stackit/sdk/core/exception/ApiException.java index d7d6210..7f343cf 100644 --- a/core/src/main/java/cloud/stackit/sdk/core/exception/ApiException.java +++ b/core/src/main/java/cloud/stackit/sdk/core/exception/ApiException.java @@ -7,12 +7,9 @@ public class ApiException extends Exception { private static final long serialVersionUID = 1L; - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - /** Constructor for ApiException. */ - public ApiException() {} + private int code; + private Map> responseHeaders; + private String responseBody; /** * Constructor for ApiException. @@ -162,6 +159,7 @@ public String getResponseBody() { * * @return The exception message */ + @Override public String getMessage() { return String.format( "Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", diff --git a/core/src/main/java/cloud/stackit/sdk/core/exception/GenericOpenAPIException.java b/core/src/main/java/cloud/stackit/sdk/core/exception/GenericOpenAPIException.java new file mode 100644 index 0000000..0a795c7 --- /dev/null +++ b/core/src/main/java/cloud/stackit/sdk/core/exception/GenericOpenAPIException.java @@ -0,0 +1,76 @@ +package cloud.stackit.sdk.core.exception; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public class GenericOpenAPIException extends ApiException { + // Created with serialver + private static final long serialVersionUID = 3551449573139480120L; + // When a response has a bad status, this limits the number of characters that are shown from + // the response Body + public int apiErrorMaxCharacterLimit = 500; + + private final int statusCode; + private byte[] body; + private final String errorMessage; + + public GenericOpenAPIException(ApiException apiException) { + super(apiException.getMessage()); + this.statusCode = apiException.getCode(); + this.errorMessage = apiException.getMessage(); + } + + public GenericOpenAPIException(int statusCode, String errorMessage) { + this(statusCode, errorMessage, null); + } + + public GenericOpenAPIException(int statusCode, String errorMessage, byte[] body) { + super(errorMessage); + this.statusCode = statusCode; + this.errorMessage = errorMessage; + if (body != null) { + this.body = Arrays.copyOf(body, body.length); + } + } + + @Override + public String getMessage() { + // Prevent negative values + if (apiErrorMaxCharacterLimit < 0) { + apiErrorMaxCharacterLimit = 500; + } + + if (body == null) { + return String.format("%s, status code %d", errorMessage, statusCode); + } + + String bodyStr = new String(body, StandardCharsets.UTF_8); + + if (bodyStr.length() <= apiErrorMaxCharacterLimit) { + return String.format("%s, status code %d, Body: %s", errorMessage, statusCode, bodyStr); + } + + int indexStart = apiErrorMaxCharacterLimit / 2; + int indexEnd = bodyStr.length() - apiErrorMaxCharacterLimit / 2; + int numberTruncatedCharacters = indexEnd - indexStart; + + return String.format( + "%s, status code %d, Body: %s [...truncated %d characters...] %s", + errorMessage, + statusCode, + bodyStr.substring(0, indexStart), + numberTruncatedCharacters, + bodyStr.substring(indexEnd)); + } + + public int getStatusCode() { + return statusCode; + } + + public byte[] getBody() { + if (body == null) { + return new byte[0]; + } + return Arrays.copyOf(body, body.length); + } +} diff --git a/core/src/main/java/cloud/stackit/sdk/core/wait/AsyncActionHandler.java b/core/src/main/java/cloud/stackit/sdk/core/wait/AsyncActionHandler.java new file mode 100644 index 0000000..298a7d9 --- /dev/null +++ b/core/src/main/java/cloud/stackit/sdk/core/wait/AsyncActionHandler.java @@ -0,0 +1,189 @@ +package cloud.stackit.sdk.core.wait; + +import cloud.stackit.sdk.core.exception.ApiException; +import cloud.stackit.sdk.core.exception.GenericOpenAPIException; +import java.net.HttpURLConnection; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; + +public class AsyncActionHandler { + public static final Set RETRY_HTTP_ERROR_STATUS_CODES = + new HashSet<>( + Arrays.asList( + HttpURLConnection.HTTP_BAD_GATEWAY, + HttpURLConnection.HTTP_GATEWAY_TIMEOUT)); + + public static final String TEMPORARY_ERROR_MESSAGE = + "Temporary error was found and the retry limit was reached."; + public static final String TIMEOUT_ERROR_MESSAGE = "WaitWithContextAsync() has timed out."; + public static final String NON_GENERIC_API_ERROR_MESSAGE = "Found non-GenericOpenAPIError."; + + private final CheckFunction> checkFn; + + private long sleepBeforeWaitMillis; + private long throttleMillis; + private long timeoutMillis; + private int tempErrRetryLimit; + + // The linter is complaining about this but since we are using Java 8 the + // possibilities are restricted. + // @SuppressWarnings("PMD.DoNotUseThreads") + // private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + public AsyncActionHandler(CheckFunction> checkFn) { + this.checkFn = checkFn; + this.sleepBeforeWaitMillis = 0; + this.throttleMillis = TimeUnit.SECONDS.toMillis(5); + this.timeoutMillis = TimeUnit.MINUTES.toMillis(30); + this.tempErrRetryLimit = 5; + } + + /** + * SetThrottle sets the time interval between each check of the async action. + * + * @param duration + * @param unit + */ + public void setThrottle(long duration, TimeUnit unit) { + this.throttleMillis = unit.toMillis(duration); + } + + /** + * SetTimeout sets the duration for wait timeout. + * + * @param duration + * @param unit + */ + public void setTimeout(long duration, TimeUnit unit) { + this.timeoutMillis = unit.toMillis(duration); + } + + /** + * SetSleepBeforeWait sets the duration for sleep before wait. + * + * @param duration + * @param unit + */ + public void setSleepBeforeWait(long duration, TimeUnit unit) { + this.sleepBeforeWaitMillis = unit.toMillis(duration); + } + + /** + * SetTempErrRetryLimit sets the retry limit if a temporary error is found. The list of + * temporary errors is defined in the RetryHttpErrorStatusCodes variable. + * + * @param limit + */ + public void setTempErrRetryLimit(int limit) { + this.tempErrRetryLimit = limit; + } + + /** + * Runnable task which is executed periodically. + * + * @param future + * @param startTime + * @param retryTempErrorCounter + */ + private void executeCheckTask( + CompletableFuture future, long startTime, AtomicInteger retryTempErrorCounter) { + if (future.isDone()) { + return; + } + if (System.currentTimeMillis() - startTime >= timeoutMillis) { + future.completeExceptionally(new TimeoutException(TIMEOUT_ERROR_MESSAGE)); + } + try { + AsyncActionResult result = checkFn.execute(); + if (result != null && result.isFinished()) { + future.complete(result.getResponse()); + } + } catch (ApiException e) { + GenericOpenAPIException oapiErr = new GenericOpenAPIException(e); + // Some APIs may return temporary errors and the request should be retried + if (!RETRY_HTTP_ERROR_STATUS_CODES.contains(oapiErr.getStatusCode())) { + return; + } + if (retryTempErrorCounter.incrementAndGet() == tempErrRetryLimit) { + // complete the future with corresponding exception + future.completeExceptionally(new Exception(TEMPORARY_ERROR_MESSAGE, oapiErr)); + } + } catch (IllegalStateException e) { + future.completeExceptionally(e); + } + } + + /** + * WaitWithContextAsync starts the wait until there's an error or wait is done + * + * @return + */ + public CompletableFuture waitWithContextAsync() { + if (throttleMillis <= 0) { + throw new IllegalArgumentException("Throttle can't be 0 or less"); + } + + CompletableFuture future = new CompletableFuture<>(); + long startTime = System.currentTimeMillis(); + AtomicInteger retryTempErrorCounter = new AtomicInteger(0); + + // This runnable is called periodically. + Runnable checkTask = () -> executeCheckTask(future, startTime, retryTempErrorCounter); + + // start the periodic execution + ScheduledFuture scheduledFuture = + ScheduleExecutorSingleton.getInstance() + .getScheduler() + .scheduleAtFixedRate( + checkTask, + sleepBeforeWaitMillis, + throttleMillis, + TimeUnit.MILLISECONDS); + + // stop task when future is completed + future.whenComplete( + (result, error) -> { + scheduledFuture.cancel(true); + // scheduler.shutdown(); + }); + + return future; + } + + // Helper class to encapsulate the result of the checkFn + public static class AsyncActionResult { + private final boolean finished; + private final T response; + + public AsyncActionResult(boolean finished, T response) { + this.finished = finished; + this.response = response; + } + + public boolean isFinished() { + return finished; + } + + public T getResponse() { + return response; + } + } + + /** + * Helper function to check http status codes during deletion of a resource. + * + * @param e ApiException to check + * @return true if resource is gone otherwise false + */ + public static boolean checkResourceGoneStatusCodes(ApiException apiException) { + GenericOpenAPIException oapiErr = new GenericOpenAPIException(apiException); + return oapiErr.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND + || oapiErr.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN; + } +} diff --git a/core/src/main/java/cloud/stackit/sdk/core/wait/CheckFunction.java b/core/src/main/java/cloud/stackit/sdk/core/wait/CheckFunction.java new file mode 100644 index 0000000..69aef26 --- /dev/null +++ b/core/src/main/java/cloud/stackit/sdk/core/wait/CheckFunction.java @@ -0,0 +1,11 @@ +package cloud.stackit.sdk.core.wait; + +import cloud.stackit.sdk.core.exception.ApiException; + +// Since the Callable FunctionalInterface throws a generic Exception +// and the linter complains about catching a generic Exception this +// FunctionalInterface is needed. +@FunctionalInterface +public interface CheckFunction { + V execute() throws ApiException; +} diff --git a/core/src/main/java/cloud/stackit/sdk/core/wait/ScheduleExecutorSingleton.java b/core/src/main/java/cloud/stackit/sdk/core/wait/ScheduleExecutorSingleton.java new file mode 100644 index 0000000..8f53e99 --- /dev/null +++ b/core/src/main/java/cloud/stackit/sdk/core/wait/ScheduleExecutorSingleton.java @@ -0,0 +1,38 @@ +package cloud.stackit.sdk.core.wait; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; + +@SuppressWarnings("PMD.DoNotUseThreads") +public final class ScheduleExecutorSingleton { + // Pool size for the thread pool + private static final int POOL_SIZE = 1; + private final ScheduledExecutorService scheduler; + + private ScheduleExecutorSingleton() { + // Use Daemon threads to prevent that the user need to call shutdown + // even if its program was already terminated + ThreadFactory daemonThreadFactory = + runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + return thread; + }; + scheduler = Executors.newScheduledThreadPool(POOL_SIZE, daemonThreadFactory); + } + + public ScheduledExecutorService getScheduler() { + return scheduler; + } + + // In order to make the Linter happy this is the only solution which is accepted. + // Lock/ReentrantLock, synchronized and volatile are in general not accepted. + private static final class SingletonHolder { + public static final ScheduleExecutorSingleton INSTANCE = new ScheduleExecutorSingleton(); + } + + public static ScheduleExecutorSingleton getInstance() { + return SingletonHolder.INSTANCE; + } +} diff --git a/core/src/test/java/cloud/stackit/sdk/core/wait/AsyncWaitHandlerTest.java b/core/src/test/java/cloud/stackit/sdk/core/wait/AsyncWaitHandlerTest.java new file mode 100644 index 0000000..72f6cd1 --- /dev/null +++ b/core/src/test/java/cloud/stackit/sdk/core/wait/AsyncWaitHandlerTest.java @@ -0,0 +1,128 @@ +package cloud.stackit.sdk.core.wait; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +import cloud.stackit.sdk.core.exception.ApiException; +import cloud.stackit.sdk.core.wait.AsyncActionHandler.AsyncActionResult; +import java.net.HttpURLConnection; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class AsyncWaitHandlerTest { + + // Helper class for testing + public static class ApiHelper { + + private final String response = "APIResponse"; + + public ApiHelper() {} + + public String callApi() throws ApiException { + return response; + } + } + + @Mock private ApiHelper apiClient; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + // testWaitHandler just calls the ApiHelper function + public static AsyncActionHandler testWaitHandler(ApiHelper apiClient) { + CheckFunction> checkFn = + () -> { + try { + apiClient.callApi(); + return new AsyncActionResult<>(false, null); + } catch (ApiException | IllegalStateException e) { + throw e; + } + }; + return new AsyncActionHandler<>(checkFn); + } + + // Non GenericOpenAPIError + @Test + void testNonGenericOpenAPIError() throws Exception { + Exception nonApiException = new IllegalStateException(); + when(apiClient.callApi()).thenThrow(nonApiException); + + AsyncActionHandler handler = testWaitHandler(apiClient); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(40, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + ExecutionException.class, () -> handler.waitWithContextAsync().get(), ""); + assertTrue(thrown.getMessage().contains("IllegalStateException")); + } + + // GenericOpenAPIError(ApiException) not in RetryHttpErrorStatusCodes + @Test + void testOpenAPIErrorNotInList() throws Exception { + ApiException apiException = new ApiException(409, ""); + when(apiClient.callApi()).thenThrow(apiException); + + AsyncActionHandler handler = testWaitHandler(apiClient); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(40, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows(Exception.class, () -> handler.waitWithContextAsync().get(), ""); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TIMEOUT_ERROR_MESSAGE)); + } + + // GenericOpenAPIError(ApiException) in RetryHttpErrorStatusCodes -> max retries reached + @Test + void testOpenAPIErrorTimeoutBadGateway() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_BAD_GATEWAY, ""); + when(apiClient.callApi()).thenThrow(apiException); + + AsyncActionHandler handler = testWaitHandler(apiClient); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TEMPORARY_ERROR_MESSAGE)); + } + + // GenericOpenAPIError(ApiException) in RetryHttpErrorStatusCodes -> max retries reached + @Test + void testOpenAPIErrorTimeoutGatewayTimeout() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_GATEWAY_TIMEOUT, ""); + when(apiClient.callApi()).thenThrow(apiException); + + AsyncActionHandler handler = testWaitHandler(apiClient); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TEMPORARY_ERROR_MESSAGE)); + } +} diff --git a/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java b/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java index 34ed2aa..3cafab5 100644 --- a/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java +++ b/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java @@ -12,13 +12,22 @@ import cloud.stackit.sdk.resourcemanager.model.PartialUpdateFolderPayload; import cloud.stackit.sdk.resourcemanager.model.PartialUpdateProjectPayload; import cloud.stackit.sdk.resourcemanager.model.Project; +import cloud.stackit.sdk.resourcemanager.wait.ResourcemanagerWait; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.UUID; +import java.util.concurrent.ExecutionException; -class ResourcemanagerExample { - public static void main(String[] args) throws IOException { +final class ResourcemanagerExample { + + /** Prevent instantiation */ + private ResourcemanagerExample() {} + + // This is an example, we don't want to add a logger framework here. + @SuppressWarnings({"PMD.SystemPrintln"}) + public static void main(String[] args) + throws ApiException, IOException, InterruptedException, ExecutionException { // Credentials are read from the credentialsFile in `~/.stackit/credentials.json` or the env // STACKIT_SERVICE_ACCOUNT_KEY_PATH / STACKIT_SERVICE_ACCOUNT_KEY ResourceManagerApi resourceManagerApi = new ResourceManagerApi(); @@ -41,72 +50,80 @@ public static void main(String[] args) throws IOException { .role("project.owner") .subject(memberSubjectString); // replace with an existing subject - try { - /* create a project */ - Project project = - resourceManagerApi.createProject( - new CreateProjectPayload() - .containerParentId(containerParentId.toString()) - .name("java-test-project") - .addMembersItem(member) - .labels(Collections.singletonMap("foo", "bar"))); - System.out.println("Project:\n" + project.toString()); - - /* list projects */ - ListProjectsResponse responseListProject = - resourceManagerApi.listProjects( - organizationIdString, null, null, null, null, null); - System.out.println("Project List:\n" + responseListProject.toString()); - - /* create a folder */ - FolderResponse folder = - resourceManagerApi.createFolder( - new CreateFolderPayload() - .containerParentId(containerParentId.toString()) - .name("java-testing-folder") - .labels(Collections.singletonMap("foo", "bar"))); - System.out.println("Folder: \n" + folder.toString()); - - /* list folders */ - ListFoldersResponse responseListFolders = - resourceManagerApi.listFolders( - organizationIdString, null, null, null, null, null); - System.out.println("Folder List:\n" + responseListFolders.toString()); - - /* delete a project label */ - resourceManagerApi.deleteProjectLabels(project.getContainerId(), Arrays.asList("foo")); - - /* delete a folder label */ - resourceManagerApi.deleteFolderLabels(folder.getContainerId(), Arrays.asList("foo")); - - /* update folder labels */ - resourceManagerApi.partialUpdateFolder( - folder.getContainerId(), - new PartialUpdateFolderPayload() - .labels(Collections.singletonMap("foo2", "bar2"))); - - /* update project move to created folder */ - resourceManagerApi.partialUpdateProject( - project.getContainerId(), - new PartialUpdateProjectPayload().containerParentId(folder.getContainerId())); - - /* get organization details */ - OrganizationResponse organizationResponse = - resourceManagerApi.getOrganization(organizationIdString); - System.out.println("Organization List:\n" + organizationResponse.toString()); - - /* since you cannot delete a folder when a project is present we need to move the project out again */ - resourceManagerApi.partialUpdateProject( - project.getContainerId(), - new PartialUpdateProjectPayload().containerParentId(organizationIdString)); - - /* delete project */ - resourceManagerApi.deleteProject(project.getContainerId()); - - /* delete folder */ - resourceManagerApi.deleteFolder(folder.getContainerId(), true); - } catch (ApiException e) { - throw new RuntimeException(e); - } + String labelName = "foo"; + /* create a project */ + Project project = + resourceManagerApi.createProject( + new CreateProjectPayload() + .containerParentId(containerParentId.toString()) + .name("java-test-project") + .addMembersItem(member) + .labels(Collections.singletonMap(labelName, "bar"))); + System.out.println("Project:\n" + project.toString()); + + /* list projects */ + ListProjectsResponse responseListProject = + resourceManagerApi.listProjects(organizationIdString, null, null, null, null, null); + System.out.println("Project List:\n" + responseListProject.toString()); + + /* create a folder */ + FolderResponse folder = + resourceManagerApi.createFolder( + new CreateFolderPayload() + .containerParentId(containerParentId.toString()) + .name("java-test-folder") + .addMembersItem(member) + .labels(Collections.singletonMap(labelName, "bar"))); + System.out.println("Folder: \n" + folder.toString()); + + ResourcemanagerWait.createProjectWaitHandler(resourceManagerApi, project.getContainerId()) + .waitWithContextAsync() + .get(); + + /* list folders */ + ListFoldersResponse responseListFolders = + resourceManagerApi.listFolders(organizationIdString, null, null, null, null, null); + System.out.println("Folder List:\n" + responseListFolders.toString()); + + /* delete a project label */ + resourceManagerApi.deleteProjectLabels(project.getContainerId(), Arrays.asList(labelName)); + + /* delete a folder label */ + resourceManagerApi.deleteFolderLabels(folder.getContainerId(), Arrays.asList(labelName)); + + /* update folder labels */ + resourceManagerApi.partialUpdateFolder( + folder.getContainerId(), + new PartialUpdateFolderPayload().labels(Collections.singletonMap("foo2", "bar2"))); + + /* update project move to created folder */ + resourceManagerApi.partialUpdateProject( + project.getContainerId(), + new PartialUpdateProjectPayload().containerParentId(folder.getContainerId())); + + ResourcemanagerWait.updateProjectWaitHandler(resourceManagerApi, project.getContainerId()) + .waitWithContextAsync() + .get(); + + /* get organization details */ + OrganizationResponse organizationResponse = + resourceManagerApi.getOrganization(organizationIdString); + System.out.println("Organization List:\n" + organizationResponse.toString()); + + /* since you cannot delete a folder when a project is present we need to move the project out again */ + resourceManagerApi.partialUpdateProject( + project.getContainerId(), + new PartialUpdateProjectPayload().containerParentId(organizationIdString)); + + /* delete project */ + resourceManagerApi.deleteProject(project.getContainerId()); + + /* wait for the project deletion to complete */ + ResourcemanagerWait.deleteProjectWaitHandler(resourceManagerApi, project.getContainerId()) + .waitWithContextAsync() + .get(); + + /* delete folder */ + resourceManagerApi.deleteFolder(folder.getContainerId(), null); } } diff --git a/services/resourcemanager/CHANGELOG.md b/services/resourcemanager/CHANGELOG.md index d9d7ce4..6f99b24 100644 --- a/services/resourcemanager/CHANGELOG.md +++ b/services/resourcemanager/CHANGELOG.md @@ -1,3 +1,6 @@ +## v0.3.0 +- **Feature:** Added waiter for project creation and project deletion + ## v0.2.0 - **Feature:** Support for passing custom OkHttpClient objects - `ApiClient` diff --git a/services/resourcemanager/VERSION b/services/resourcemanager/VERSION index 0ea3a94..0d91a54 100644 --- a/services/resourcemanager/VERSION +++ b/services/resourcemanager/VERSION @@ -1 +1 @@ -0.2.0 +0.3.0 diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/wait/ResourcemanagerWait.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/wait/ResourcemanagerWait.java new file mode 100644 index 0000000..2bc192d --- /dev/null +++ b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/wait/ResourcemanagerWait.java @@ -0,0 +1,161 @@ +package cloud.stackit.sdk.resourcemanager.wait; + +import cloud.stackit.sdk.core.exception.ApiException; +import cloud.stackit.sdk.core.wait.AsyncActionHandler; +import cloud.stackit.sdk.core.wait.AsyncActionHandler.AsyncActionResult; +import cloud.stackit.sdk.core.wait.CheckFunction; +import cloud.stackit.sdk.resourcemanager.api.ResourceManagerApi; +import cloud.stackit.sdk.resourcemanager.model.GetProjectResponse; +import cloud.stackit.sdk.resourcemanager.model.LifecycleState; +import java.util.concurrent.TimeUnit; + +public final class ResourcemanagerWait { + + /** Prevent instantiation */ + private ResourcemanagerWait() {} + + /** + * createProjectWaitHandler will wait for project creation. Uses the default values for + * sleepBeforeWait (1 min) and timeout (45 min). + * + * @param apiClient + * @param containerId + * @return + */ + public static AsyncActionHandler createProjectWaitHandler( + ResourceManagerApi apiClient, String containerId) throws ApiException { + return createProjectWaitHandler(apiClient, containerId, 1, 45); + } + + /** + * createProjectWaitHandler will wait for project creation + * + * @param apiClient + * @param containerId + * @param sleepBeforeWait in Minutes + * @param timeout in Minutes + * @return + */ + public static AsyncActionHandler createProjectWaitHandler( + ResourceManagerApi apiClient, String containerId, long sleepBeforeWait, long timeout) + throws ApiException { + return createOrUpdateProjectWaitHandler(apiClient, containerId, sleepBeforeWait, timeout); + } + + /** + * updateProjectWaitHandler will wait until the project was updated. Uses the default values for + * sleepBeforeWait (1 min) and timeout (45 min). + * + * @param apiClient + * @param containerId + * @return + */ + public static AsyncActionHandler updateProjectWaitHandler( + ResourceManagerApi apiClient, String containerId) throws ApiException { + return updateProjectWaitHandler(apiClient, containerId, 1, 45); + } + + /** + * updateProjectWaitHandler will wait until the project was updated. + * + * @param apiClient + * @param containerId + * @param sleepBeforeWait in Minutes + * @param timeout in Minutes + * @return + */ + public static AsyncActionHandler updateProjectWaitHandler( + ResourceManagerApi apiClient, String containerId, long sleepBeforeWait, long timeout) + throws ApiException { + return createOrUpdateProjectWaitHandler(apiClient, containerId, sleepBeforeWait, timeout); + } + + /** + * Private helper function for create and update wait handler since the logic is the same. + * + * @param apiClient + * @param containerId + * @param sleepBeforeWait + * @param timeout + * @return + * @throws ApiException + */ + private static AsyncActionHandler createOrUpdateProjectWaitHandler( + ResourceManagerApi apiClient, String containerId, long sleepBeforeWait, long timeout) + throws ApiException { + CheckFunction> checkFn = + () -> { + GetProjectResponse projectResponse = apiClient.getProject(containerId, false); + if (projectResponse.getContainerId().equals(containerId) + && projectResponse.getLifecycleState().equals(LifecycleState.ACTIVE)) { + return new AsyncActionResult<>(true, projectResponse); + } + + if (projectResponse.getContainerId().equals(containerId) + && projectResponse + .getLifecycleState() + .equals(LifecycleState.CREATING)) { + return new AsyncActionResult<>(false, null); + } + // An invalid state was received which should not be possible. + throw new IllegalStateException( + "Creation failed: received project state '" + + projectResponse.getLifecycleState().getValue() + + "'"); + }; + AsyncActionHandler handler = new AsyncActionHandler<>(checkFn); + handler.setSleepBeforeWait(sleepBeforeWait, TimeUnit.MINUTES); + handler.setTimeout(timeout, TimeUnit.MINUTES); + return handler; + } + + /** + * deleteProjectWaitHandler will wait for project deletion. Uses the deault value for timeout + * (15 min). + * + * @param apiClient + * @param containerId + * @return + */ + public static AsyncActionHandler deleteProjectWaitHandler( + ResourceManagerApi apiClient, String containerId) { + return deleteProjectWaitHandler(apiClient, containerId, 15); + } + + /** + * deleteProjectWaitHandler will wait for project deletion + * + * @param apiClient + * @param containerId + * @param timeout in minutes + * @return + */ + public static AsyncActionHandler deleteProjectWaitHandler( + ResourceManagerApi apiClient, String containerId, long timeout) { + CheckFunction> checkFn = + () -> { + try { + GetProjectResponse projectResponse = + apiClient.getProject(containerId, false); + if (projectResponse.getContainerId().equals(containerId) + && projectResponse + .getLifecycleState() + .equals(LifecycleState.DELETING)) { + return new AsyncActionResult<>(true, null); + } + + // The call does throw an exception for HttpURLConnection.HTTP_NOT_FOUND and + // HttpURLConnection.HTTP_FORBIDDEN + return new AsyncActionResult<>(false, null); + } catch (ApiException e) { + if (AsyncActionHandler.checkResourceGoneStatusCodes(e)) { + return new AsyncActionResult<>(true, null); + } + throw e; + } + }; + AsyncActionHandler handler = new AsyncActionHandler<>(checkFn); + handler.setTimeout(timeout, TimeUnit.MINUTES); + return handler; + } +} diff --git a/services/resourcemanager/src/test/java/cloud/stackit/sdk/resourcemanager/ResourcemanagerWaitTestmanagerWaitTest.java b/services/resourcemanager/src/test/java/cloud/stackit/sdk/resourcemanager/ResourcemanagerWaitTestmanagerWaitTest.java new file mode 100644 index 0000000..824837f --- /dev/null +++ b/services/resourcemanager/src/test/java/cloud/stackit/sdk/resourcemanager/ResourcemanagerWaitTestmanagerWaitTest.java @@ -0,0 +1,308 @@ +package cloud.stackit.sdk.resourcemanager; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import cloud.stackit.sdk.core.exception.ApiException; +import cloud.stackit.sdk.core.wait.AsyncActionHandler; +import cloud.stackit.sdk.resourcemanager.api.ResourceManagerApi; +import cloud.stackit.sdk.resourcemanager.model.GetProjectResponse; +import cloud.stackit.sdk.resourcemanager.model.LifecycleState; +import cloud.stackit.sdk.resourcemanager.wait.ResourcemanagerWait; +import java.net.HttpURLConnection; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class ResourcemanagerWaitTestmanagerWaitTest { + + @Mock private ResourceManagerApi apiClient; + + private final String containerId = "my-test-container"; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testCreateProjectSuccess() throws Exception { + // First call returns "CREATING", second call returns "ACTIVE" + GetProjectResponse creatingResponse = new GetProjectResponse(); + creatingResponse.setContainerId(containerId); + creatingResponse.setLifecycleState(LifecycleState.CREATING); + + GetProjectResponse activeResponse = new GetProjectResponse(); + activeResponse.setContainerId(containerId); + activeResponse.setLifecycleState(LifecycleState.ACTIVE); + + AtomicInteger callCount = new AtomicInteger(0); + when(apiClient.getProject(containerId, false)) + .thenAnswer( + invocation -> { + if (callCount.getAndIncrement() < 1) { + return creatingResponse; + } + return activeResponse; + }); + + AsyncActionHandler handler = + ResourcemanagerWait.createProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(2, TimeUnit.SECONDS); + + GetProjectResponse result = handler.waitWithContextAsync().get(); + + assertNotNull(result); + verify(apiClient, times(2)).getProject(containerId, false); + } + + @Test + void testCreateProjectTimeout() throws Exception { + // Always return "CREATING" to trigger the timeout + GetProjectResponse creatingResponse = new GetProjectResponse(); + creatingResponse.setContainerId(containerId); + creatingResponse.setLifecycleState(LifecycleState.CREATING); + when(apiClient.getProject(containerId, false)).thenReturn(creatingResponse); + + AsyncActionHandler handler = + ResourcemanagerWait.createProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(500, TimeUnit.MILLISECONDS); + + Exception thrown = + assertThrows(Exception.class, () -> handler.waitWithContextAsync().get(), ""); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TIMEOUT_ERROR_MESSAGE)); + } + + // GenericOpenAPIError not in RetryHttpErrorStatusCodes + @Test + void testCreateProjectOpenAPIError() throws Exception { + // Trigger API Exception which is not in RetryHttpErrorStatusCodes + ApiException apiException = new ApiException(409, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.createProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TIMEOUT_ERROR_MESSAGE)); + } + + @Test + void testUpdateProjectSuccess() throws Exception { + // First call returns "CREATING", second call returns "ACTIVE" + GetProjectResponse updateResponse = new GetProjectResponse(); + updateResponse.setContainerId(containerId); + updateResponse.setLifecycleState(LifecycleState.CREATING); + + GetProjectResponse activeResponse = new GetProjectResponse(); + activeResponse.setContainerId(containerId); + activeResponse.setLifecycleState(LifecycleState.ACTIVE); + + AtomicInteger callCount = new AtomicInteger(0); + when(apiClient.getProject(containerId, false)) + .thenAnswer( + invocation -> { + if (callCount.getAndIncrement() < 1) { + return updateResponse; + } + return activeResponse; + }); + + AsyncActionHandler handler = + ResourcemanagerWait.updateProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(2, TimeUnit.SECONDS); + + GetProjectResponse result = handler.waitWithContextAsync().get(); + + assertNotNull(result); + verify(apiClient, times(2)).getProject(containerId, false); + } + + @Test + void testUpdateProjectTimeout() throws Exception { + // Always return "CREATING" to trigger the timeout + GetProjectResponse updateResponse = new GetProjectResponse(); + updateResponse.setContainerId(containerId); + updateResponse.setLifecycleState(LifecycleState.CREATING); + when(apiClient.getProject(containerId, false)).thenReturn(updateResponse); + + AsyncActionHandler handler = + ResourcemanagerWait.createProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(500, TimeUnit.MILLISECONDS); + + Exception thrown = + assertThrows(Exception.class, () -> handler.waitWithContextAsync().get(), ""); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TIMEOUT_ERROR_MESSAGE)); + } + + // GenericOpenAPIError in RetryHttpErrorStatusCodes -> max retries reached + @Test + void testOpenAPIErrorTimeoutBadGateway() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_BAD_GATEWAY, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.createProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TEMPORARY_ERROR_MESSAGE)); + } + + // GenericOpenAPIError in RetryHttpErrorStatusCodes -> max retries reached + @Test + void testOpenAPIErrorTimeoutGatewayTimeout() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_GATEWAY_TIMEOUT, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.createProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TEMPORARY_ERROR_MESSAGE)); + } + + @Test + void testDeleteProjectSuccessDeleting() throws Exception { + // First call returns "ACTIVE", second call returns "DELETING" + GetProjectResponse activeResponse = new GetProjectResponse(); + activeResponse.setContainerId(containerId); + activeResponse.setLifecycleState(LifecycleState.ACTIVE); + + GetProjectResponse deletingResponse = new GetProjectResponse(); + deletingResponse.setContainerId(containerId); + deletingResponse.setLifecycleState(LifecycleState.DELETING); + + AtomicInteger callCount = new AtomicInteger(0); + when(apiClient.getProject(containerId, false)) + .thenAnswer( + invocation -> { + if (callCount.getAndIncrement() < 1) { + return activeResponse; + } + return deletingResponse; + }); + + AsyncActionHandler handler = + ResourcemanagerWait.deleteProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(2, TimeUnit.SECONDS); + + handler.waitWithContextAsync().get(); + verify(apiClient, times(2)).getProject(containerId, false); + } + + @Test + void testDeleteProjectSuccessNotFoundExc() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_NOT_FOUND, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.deleteProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(2, TimeUnit.SECONDS); + handler.waitWithContextAsync().get(); + // Only one invocation since the project is gone (HTTP_NOT_FOUND) + verify(apiClient, times(1)).getProject(containerId, false); + } + + @Test + void testDeleteProjectSuccessForbiddenExc() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_FORBIDDEN, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.deleteProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(2, TimeUnit.SECONDS); + handler.waitWithContextAsync().get(); + // Only one invocation since the project is gone (HTTP_FORBIDDEN) + verify(apiClient, times(1)).getProject(containerId, false); + } + + @Test + void testDeleteProjectDifferentErrorCode() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_ENTITY_TOO_LARGE, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.deleteProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TIMEOUT_ERROR_MESSAGE)); + } + + @Test + void testOpenAPIErrorGatewayTimeout() throws Exception { + // Trigger API Exception + ApiException apiException = new ApiException(HttpURLConnection.HTTP_GATEWAY_TIMEOUT, ""); + when(apiClient.getProject(containerId, false)).thenThrow(apiException); + + AsyncActionHandler handler = + ResourcemanagerWait.deleteProjectWaitHandler(apiClient, containerId); + handler.setSleepBeforeWait(0, TimeUnit.SECONDS); + handler.setThrottle(10, TimeUnit.MILLISECONDS); + handler.setTimeout(100, TimeUnit.MILLISECONDS); + handler.setTempErrRetryLimit(2); + + Exception thrown = + assertThrows( + Exception.class, + () -> handler.waitWithContextAsync().get(), + apiException.getMessage()); + assertTrue(thrown.getMessage().contains(AsyncActionHandler.TEMPORARY_ERROR_MESSAGE)); + } +}