mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): scheduled actions that pause and resume provisioned clusters (#8260)
This commit is contained in:
1 parent
0b19c15e71
commit
d08c241d98
22 files changed
+1791
-66
No files matched your search
@@ -0,0 +1,62 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AwsCronScheduleTest {
|
||||
private static final Instant NOON = Instant.parse("2026-11-20T12:00:00Z");
|
||||
|
||||
private static ExecutionTime parse(String fields) {
|
||||
return AwsCronSchedule.parse(fields.split("\s+"), IllegalArgumentException::new);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nextAndLatestAreStrictlyAfterAndAtOrBefore() {
|
||||
ExecutionTime hourly = parse("0 * * * ? *");
|
||||
|
||||
assertEquals(Optional.of(Instant.parse("2026-11-20T13:00:00Z")), AwsCronSchedule.next(hourly, NOON));
|
||||
assertEquals(Optional.of(NOON), AwsCronSchedule.latest(hourly, NOON));
|
||||
assertEquals(Optional.of(NOON), AwsCronSchedule.latest(hourly, NOON.plusSeconds(1800)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBadExpressionRaisesTheCallersException() {
|
||||
assertEquals("The cron schedule needs six fields.",
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> AwsCronSchedule.parse(new String[] {"0", "*"}, IllegalStateException::new)).getMessage());
|
||||
assertThrows(IllegalArgumentException.class, () -> parse("0 * * * * *"));
|
||||
assertThrows(IllegalArgumentException.class, () -> parse("0 * ? * ? *"));
|
||||
assertThrows(IllegalArgumentException.class, () -> parse("99 * * * ? *"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void spacingUnderAnHourIsRefusedAndAnHourIsAccepted() {
|
||||
AwsCronSchedule.requireHourlySpacing(parse("0 * * * ? *"), IllegalArgumentException::new);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> AwsCronSchedule.requireHourlySpacing(parse("0/30 * * * ? *"), IllegalArgumentException::new));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWindowMovesTheSearchAndKeepsItsEndsInclusive() {
|
||||
Instant start = NOON.plusSeconds(3600);
|
||||
Instant end = NOON.plusSeconds(7200);
|
||||
|
||||
assertEquals(start.minusNanos(1), AwsCronSchedule.searchFrom(NOON, start));
|
||||
assertEquals(NOON, AwsCronSchedule.searchFrom(NOON, null));
|
||||
assertEquals(end, AwsCronSchedule.searchUpTo(NOON.plusSeconds(9000), end));
|
||||
assertEquals(NOON, AwsCronSchedule.searchUpTo(NOON, end));
|
||||
assertTrue(AwsCronSchedule.inWindow(start, start, end));
|
||||
assertTrue(AwsCronSchedule.inWindow(end, start, end));
|
||||
assertFalse(AwsCronSchedule.inWindow(end.plusSeconds(1), start, end));
|
||||
assertTrue(AwsCronSchedule.inWindow(NOON, null, null));
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
|
||||
import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftScheduledActionAuthorizerTest {
|
||||
private static final String ROLE = "arn:aws:iam::123456789012:role/scheduler";
|
||||
|
||||
private ServiceRoleAuthorizer roles;
|
||||
private RedshiftScheduledActionAuthorizer authorizer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
roles = mock(ServiceRoleAuthorizer.class);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.partitionForRegion("eu-west-1")).thenReturn("aws");
|
||||
authorizer = new RedshiftScheduledActionAuthorizer(roles, regionResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRoleIsCheckedForTheActionOfTheOperationOnTheClusterOfItsRegion() {
|
||||
when(roles.refusal(any(), any(), any(), any(), anyList())).thenReturn(Optional.of("denied"));
|
||||
|
||||
Optional<String> refusal = authorizer.refusal(ROLE, "123456789012", "eu-west-1", "PauseCluster", "analytics");
|
||||
|
||||
assertEquals(Optional.of("denied"), refusal);
|
||||
ArgumentCaptor<List<Permission>> permissions = ArgumentCaptor.forClass(List.class);
|
||||
verify(roles).refusal(eq(ROLE), eq("123456789012"), eq(ServicePrincipals.of("scheduler.redshift")), isNull(),
|
||||
permissions.capture());
|
||||
assertEquals(1, permissions.getValue().size());
|
||||
assertEquals("redshift:PauseCluster", permissions.getValue().get(0).action());
|
||||
assertEquals("arn:aws:redshift:eu-west-1:123456789012:cluster:analytics",
|
||||
permissions.getValue().get(0).resourceArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resumeIsCheckedAsItsOwnAction() {
|
||||
authorizer.refusal(ROLE, "123456789012", "eu-west-1", "ResumeCluster", "analytics");
|
||||
|
||||
ArgumentCaptor<List<Permission>> permissions = ArgumentCaptor.forClass(List.class);
|
||||
verify(roles).refusal(any(), any(), any(), any(), permissions.capture());
|
||||
assertEquals("redshift:ResumeCluster", permissions.getValue().get(0).action());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOperationTheTablesDoNotKnowIsRefusedInsteadOfCheckedOnNothing() {
|
||||
Optional<String> refusal = authorizer.refusal(ROLE, "123456789012", "eu-west-1", "NoSuchOperation", "analytics");
|
||||
|
||||
assertTrue(refusal.isPresent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.redshift.model.ScheduledAction;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftScheduledActionQueryTest {
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/scheduler";
|
||||
|
||||
private RedshiftQueryHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void setUp() {
|
||||
AccountAwareStorageBackend<ScheduledAction> store =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<String, ScheduledAction>(), null, ACCOUNT_ID);
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(eq("redshift"), eq("redshift-scheduled-actions.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
RedshiftService redshift = mock(RedshiftService.class);
|
||||
when(redshift.clusterExists(anyString(), anyString())).thenReturn(true);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
|
||||
RedshiftScheduledActionService scheduledActions = new RedshiftScheduledActionService(
|
||||
storageFactory, redshift, mock(RedshiftScheduledActionAuthorizer.class), regionResolver,
|
||||
Clock.fixed(Instant.parse("2026-11-20T12:15:00Z"), ZoneOffset.UTC));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
handler = new RedshiftQueryHandler(redshift, new RedshiftCredentialBroker(), config,
|
||||
mock(RedshiftIamDbUserResolver.class), regionResolver, null, null, null, scheduledActions);
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> createParams(String name) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("ScheduledActionName", name);
|
||||
params.add("IamRole", ROLE_ARN);
|
||||
params.add("Schedule", "cron(0 22 * * ? *)");
|
||||
params.add("TargetAction.PauseCluster.ClusterIdentifier", "analytics");
|
||||
params.add("ScheduledActionDescription", "pause at night");
|
||||
return params;
|
||||
}
|
||||
|
||||
private static String body(Response response) {
|
||||
return String.valueOf(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReturnsTheActionWithItsStateAndNextInvocations() {
|
||||
String xml = body(handler.handle("CreateScheduledAction", createParams("nightly")));
|
||||
|
||||
assertTrue(xml.contains("<ScheduledActionName>nightly</ScheduledActionName>"), xml);
|
||||
assertTrue(xml.contains("<TargetAction><PauseCluster><ClusterIdentifier>analytics</ClusterIdentifier>"
|
||||
+ "</PauseCluster></TargetAction>"), xml);
|
||||
assertTrue(xml.contains("<State>ACTIVE</State>"), xml);
|
||||
assertTrue(xml.contains("<ScheduledActionTime>2026-11-20T22:00:00Z</ScheduledActionTime>"), xml);
|
||||
assertTrue(xml.contains("<ScheduledActionDescription>pause at night</ScheduledActionDescription>"), xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeListsTheActionsFilteredByClusterAndModifyDisablesOne() {
|
||||
handler.handle("CreateScheduledAction", createParams("nightly"));
|
||||
MultivaluedMap<String, String> modify = new MultivaluedHashMap<>();
|
||||
modify.add("ScheduledActionName", "nightly");
|
||||
modify.add("Enable", "false");
|
||||
|
||||
assertTrue(body(handler.handle("ModifyScheduledAction", modify)).contains("<State>DISABLED</State>"));
|
||||
|
||||
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
|
||||
describe.add("Filters.ScheduledActionFilter.1.Name", "cluster-identifier");
|
||||
describe.add("Filters.ScheduledActionFilter.1.Values.item.1", "analytics");
|
||||
String xml = body(handler.handle("DescribeScheduledActions", describe));
|
||||
assertTrue(xml.contains("<ScheduledActions><ScheduledAction><ScheduledActionName>nightly"), xml);
|
||||
|
||||
describe.putSingle("Filters.ScheduledActionFilter.1.Values.item.1", "other");
|
||||
assertTrue(body(handler.handle("DescribeScheduledActions", describe))
|
||||
.contains("<ScheduledActions></ScheduledActions>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeFlagKeepsEnabledOrDisabledActionsAndAbsentMeansAll() {
|
||||
handler.handle("CreateScheduledAction", createParams("on"));
|
||||
handler.handle("CreateScheduledAction", createParams("off"));
|
||||
MultivaluedMap<String, String> disable = new MultivaluedHashMap<>();
|
||||
disable.add("ScheduledActionName", "off");
|
||||
disable.add("Enable", "false");
|
||||
handler.handle("ModifyScheduledAction", disable);
|
||||
|
||||
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
|
||||
String all = body(handler.handle("DescribeScheduledActions", describe));
|
||||
assertTrue(all.contains("<ScheduledActionName>on<") && all.contains("<ScheduledActionName>off<"), all);
|
||||
|
||||
describe.putSingle("Active", "false");
|
||||
String disabled = body(handler.handle("DescribeScheduledActions", describe));
|
||||
assertTrue(disabled.contains("<ScheduledActionName>off<") && !disabled.contains("<ScheduledActionName>on<"),
|
||||
disabled);
|
||||
|
||||
describe.putSingle("Active", "true");
|
||||
String enabled = body(handler.handle("DescribeScheduledActions", describe));
|
||||
assertTrue(enabled.contains("<ScheduledActionName>on<") && !enabled.contains("<ScheduledActionName>off<"),
|
||||
enabled);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonBooleanEnableOrActiveIsRefusedAndNeverChangesState() {
|
||||
MultivaluedMap<String, String> create = createParams("typo");
|
||||
create.add("Enable", "maybe");
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> handler.handle("CreateScheduledAction", create)).getErrorCode());
|
||||
|
||||
handler.handle("CreateScheduledAction", createParams("nightly"));
|
||||
MultivaluedMap<String, String> modify = new MultivaluedHashMap<>();
|
||||
modify.add("ScheduledActionName", "nightly");
|
||||
modify.add("Enable", "maybe");
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> handler.handle("ModifyScheduledAction", modify)).getErrorCode());
|
||||
|
||||
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
|
||||
describe.add("Active", "maybe");
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> handler.handle("DescribeScheduledActions", describe)).getErrorCode());
|
||||
|
||||
describe.remove("Active");
|
||||
assertTrue(body(handler.handle("DescribeScheduledActions", describe)).contains("<State>ACTIVE</State>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesTheActionAndAMissingOneIsNotFound() {
|
||||
handler.handle("CreateScheduledAction", createParams("nightly"));
|
||||
MultivaluedMap<String, String> delete = new MultivaluedHashMap<>();
|
||||
delete.add("ScheduledActionName", "nightly");
|
||||
|
||||
assertEquals(200, handler.handle("DeleteScheduledAction", delete).getStatus());
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> handler.handle("DeleteScheduledAction", delete));
|
||||
assertEquals("ScheduledActionNotFound", failure.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resizeAndAmbiguousTargetsAreRefused() {
|
||||
MultivaluedMap<String, String> resize = createParams("resize");
|
||||
resize.remove("TargetAction.PauseCluster.ClusterIdentifier");
|
||||
resize.add("TargetAction.ResizeCluster.ClusterIdentifier", "analytics");
|
||||
assertEquals("ScheduledActionTypeUnsupported", assertThrows(AwsException.class,
|
||||
() -> handler.handle("CreateScheduledAction", resize)).getErrorCode());
|
||||
|
||||
MultivaluedMap<String, String> both = createParams("both");
|
||||
both.add("TargetAction.ResumeCluster.ClusterIdentifier", "analytics");
|
||||
assertEquals("InvalidScheduledAction", assertThrows(AwsException.class,
|
||||
() -> handler.handle("CreateScheduledAction", both)).getErrorCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.redshift.model.ScheduledAction;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RedshiftScheduledActionScheduleTest {
|
||||
|
||||
private static ScheduledAction action(String schedule) {
|
||||
ScheduledAction action = new ScheduledAction();
|
||||
action.setSchedule(schedule);
|
||||
return action;
|
||||
}
|
||||
|
||||
@Test
|
||||
void atScheduleFiresOnceAtItsUtcTimestamp() {
|
||||
ScheduledAction action = action("at(2026-11-20T10:00:00)");
|
||||
|
||||
assertEquals(Optional.of(Instant.parse("2026-11-20T10:00:00Z")),
|
||||
RedshiftScheduledActionSchedule.next(action, Instant.parse("2026-11-19T00:00:00Z")));
|
||||
assertTrue(RedshiftScheduledActionSchedule.next(action, Instant.parse("2026-11-20T10:00:00Z")).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cronScheduleListsTheNextInvocationsInUtc() {
|
||||
ScheduledAction action = action("cron(0 18 * * ? *)");
|
||||
|
||||
assertEquals(List.of(Instant.parse("2026-11-20T18:00:00Z"), Instant.parse("2026-11-21T18:00:00Z")),
|
||||
RedshiftScheduledActionSchedule.upcoming(action, Instant.parse("2026-11-20T09:00:00Z"), 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void windowAndDisabledStateLimitInvocations() {
|
||||
ScheduledAction action = action("cron(0 18 * * ? *)");
|
||||
action.setStartTime(Instant.parse("2026-11-22T00:00:00Z"));
|
||||
action.setEndTime(Instant.parse("2026-11-23T20:00:00Z"));
|
||||
|
||||
assertEquals(List.of(Instant.parse("2026-11-22T18:00:00Z"), Instant.parse("2026-11-23T18:00:00Z")),
|
||||
RedshiftScheduledActionSchedule.upcoming(action, Instant.parse("2026-11-20T09:00:00Z"), 5));
|
||||
|
||||
action.setEnabled(false);
|
||||
assertTrue(RedshiftScheduledActionSchedule.upcoming(action, Instant.parse("2026-11-20T09:00:00Z"), 5).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void latestDueCoalescesMissedInvocations() {
|
||||
ScheduledAction action = action("cron(0 18 * * ? *)");
|
||||
|
||||
assertEquals(Optional.of(Instant.parse("2026-11-22T18:00:00Z")),
|
||||
RedshiftScheduledActionSchedule.latestDue(action,
|
||||
Instant.parse("2026-11-20T00:00:00Z"), Instant.parse("2026-11-22T19:00:00Z")));
|
||||
assertTrue(RedshiftScheduledActionSchedule.latestDue(action,
|
||||
Instant.parse("2026-11-22T18:00:00Z"), Instant.parse("2026-11-22T19:00:00Z")).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedSchedulesAreRejectedAsInvalidSchedule() {
|
||||
for (String schedule : List.of("rate(1 hour)", "at(tomorrow)", "cron(0 18 * * *)",
|
||||
"cron(0 18 * * * *)", "cron(0/30 * * * ? *)", "at(2026-11-20T10:00:00", "")) {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> RedshiftScheduledActionSchedule.validate(schedule), schedule);
|
||||
assertEquals("InvalidSchedule", failure.getErrorCode(), schedule);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.redshift.model.ScheduledAction;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftScheduledActionServiceTest {
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/scheduler";
|
||||
private static final Instant BASE_TIME = Instant.parse("2026-11-20T12:15:00Z");
|
||||
|
||||
private AccountAwareStorageBackend<ScheduledAction> store;
|
||||
private RedshiftService redshift;
|
||||
private RedshiftScheduledActionAuthorizer authorizer;
|
||||
private RedshiftScheduledActionService service;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void setUp() {
|
||||
store = spy(new AccountAwareStorageBackend<>(new InMemoryStorage<String, ScheduledAction>(), null, ACCOUNT_ID));
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(eq("redshift"), eq("redshift-scheduled-actions.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
redshift = mock(RedshiftService.class);
|
||||
when(redshift.clusterExists(anyString(), anyString())).thenReturn(true);
|
||||
authorizer = mock(RedshiftScheduledActionAuthorizer.class);
|
||||
when(authorizer.refusal(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
|
||||
when(regionResolver.getDefaultRegion()).thenReturn(REGION);
|
||||
when(regionResolver.getRegion()).thenReturn(REGION);
|
||||
when(regionResolver.buildArn(eq("redshift"), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(call -> "arn:aws:redshift:" + call.getArgument(1) + ":" + call.getArgument(2)
|
||||
+ ":" + call.getArgument(3));
|
||||
service = new RedshiftScheduledActionService(storageFactory, redshift, authorizer, regionResolver,
|
||||
Clock.fixed(BASE_TIME, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
private static ScheduledAction request(String name, String type, String schedule) {
|
||||
ScheduledAction request = new ScheduledAction();
|
||||
request.setScheduledActionName(name);
|
||||
request.setIamRole(ROLE_ARN);
|
||||
request.setSchedule(schedule);
|
||||
request.setTargetActionType(type);
|
||||
request.setClusterIdentifier("analytics");
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStoresTheActionEnabledAndRejectsADuplicateName() {
|
||||
ScheduledAction created = service.createScheduledAction(
|
||||
request("nightly-pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"));
|
||||
|
||||
assertTrue(created.isEnabled());
|
||||
assertEquals(BASE_TIME, created.getActivatedAt());
|
||||
AwsException duplicate = assertThrows(AwsException.class, () -> service.createScheduledAction(
|
||||
request("nightly-pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)")));
|
||||
assertEquals("ScheduledActionAlreadyExists", duplicate.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRefusesAnUnknownClusterAnUnsupportedTargetAndAnInvertedWindow() {
|
||||
doThrow(new AwsException("ClusterNotFound", "Cluster analytics not found", 404))
|
||||
.when(redshift).describeClusters("analytics");
|
||||
assertEquals("ClusterNotFound", assertThrows(AwsException.class, () -> service.createScheduledAction(
|
||||
request("a", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"))).getErrorCode());
|
||||
|
||||
assertEquals("InvalidScheduledAction", assertThrows(AwsException.class, () -> service.createScheduledAction(
|
||||
request("b", "ResizeCluster", "cron(0 22 * * ? *)"))).getErrorCode());
|
||||
|
||||
ScheduledAction inverted = request("c", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)");
|
||||
inverted.setStartTime(Instant.parse("2026-12-01T00:00:00Z"));
|
||||
inverted.setEndTime(Instant.parse("2026-11-01T00:00:00Z"));
|
||||
assertEquals("InvalidSchedule",
|
||||
assertThrows(AwsException.class, () -> service.createScheduledAction(inverted)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeFiltersAndPagesByName() {
|
||||
service.createScheduledAction(request("b-resume", ScheduledAction.RESUME_CLUSTER, "cron(0 6 * * ? *)"));
|
||||
service.createScheduledAction(request("a-pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"));
|
||||
|
||||
PaginatedResult<ScheduledAction> all = service.describeScheduledActions(
|
||||
null, null, null, null, null, List.of(), List.of(), null, null);
|
||||
assertEquals(List.of("a-pause", "b-resume"),
|
||||
all.items().stream().map(ScheduledAction::getScheduledActionName).toList());
|
||||
|
||||
PaginatedResult<ScheduledAction> pauses = service.describeScheduledActions(
|
||||
null, ScheduledAction.PAUSE_CLUSTER, null, null, null, List.of(), List.of(), null, null);
|
||||
assertEquals(1, pauses.items().size());
|
||||
|
||||
PaginatedResult<ScheduledAction> otherCluster = service.describeScheduledActions(
|
||||
null, null, null, null, false, List.of("other"), List.of(), null, null);
|
||||
assertTrue(otherCluster.items().isEmpty());
|
||||
|
||||
ScheduledAction disable = new ScheduledAction();
|
||||
disable.setScheduledActionName("b-resume");
|
||||
service.modifyScheduledAction(disable, false);
|
||||
assertEquals(List.of("b-resume"), service.describeScheduledActions(
|
||||
null, null, null, null, false, List.of(), List.of(), null, null).items().stream()
|
||||
.map(ScheduledAction::getScheduledActionName).toList());
|
||||
assertEquals(List.of("a-pause"), service.describeScheduledActions(
|
||||
null, null, null, null, true, List.of(), List.of(), null, null).items().stream()
|
||||
.map(ScheduledAction::getScheduledActionName).toList());
|
||||
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service.describeScheduledActions(
|
||||
null, null, null, null, null, List.of(), List.of(), 5, null)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyReplacesOnlyTheGivenMembersAndRestartsTheCountOnANewSchedule() {
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"));
|
||||
ScheduledAction changes = new ScheduledAction();
|
||||
changes.setScheduledActionName("pause");
|
||||
changes.setSchedule("cron(0 23 * * ? *)");
|
||||
|
||||
ScheduledAction modified = service.modifyScheduledAction(changes, false);
|
||||
|
||||
assertEquals("cron(0 23 * * ? *)", modified.getSchedule());
|
||||
assertEquals(ROLE_ARN, modified.getIamRole());
|
||||
assertEquals(ScheduledAction.PAUSE_CLUSTER, modified.getTargetActionType());
|
||||
assertTrue(!modified.isEnabled());
|
||||
assertEquals(BASE_TIME, modified.getActivatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAMissingActionIsNotFound() {
|
||||
assertEquals("ScheduledActionNotFound", assertThrows(AwsException.class,
|
||||
() -> service.deleteScheduledAction("missing")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describePagesWithMarkerAndFiltersByInvocationWindow() {
|
||||
for (int i = 0; i < 21; i++) {
|
||||
service.createScheduledAction(request(String.format("a%02d", i), ScheduledAction.PAUSE_CLUSTER,
|
||||
"cron(0 22 * * ? *)"));
|
||||
}
|
||||
PaginatedResult<ScheduledAction> first = service.describeScheduledActions(
|
||||
null, null, null, null, null, List.of(), List.of(), 20, null);
|
||||
assertEquals(20, first.items().size());
|
||||
assertNotNull(first.nextToken());
|
||||
PaginatedResult<ScheduledAction> second = service.describeScheduledActions(
|
||||
null, null, null, null, null, List.of(), List.of(), 20, first.nextToken());
|
||||
assertEquals(List.of("a20"), second.items().stream().map(ScheduledAction::getScheduledActionName).toList());
|
||||
|
||||
Instant farFuture = Instant.parse("2027-01-01T00:00:00Z");
|
||||
assertEquals(21, service.describeScheduledActions(
|
||||
null, null, farFuture, null, null, List.of(), List.of(), 100, null).items().size());
|
||||
assertTrue(service.describeScheduledActions(
|
||||
null, null, null, BASE_TIME.plusSeconds(60), null, List.of(), List.of(), 100, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepRunsOnlyTheLatestDueInvocationOnceAndRecordsIt() {
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
Instant tick = BASE_TIME.plusSeconds(3 * 3600);
|
||||
|
||||
service.runScheduledActions(tick);
|
||||
service.runScheduledActions(tick.plusSeconds(60));
|
||||
|
||||
verify(redshift, times(1)).pauseCluster("analytics");
|
||||
ScheduledAction stored = store.get("pause").orElseThrow();
|
||||
assertEquals(Instant.parse("2026-11-20T15:00:00Z"), stored.getLastCompletedInvocation());
|
||||
assertNull(stored.getLastFailure());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepResumesAtAOneOffTimeAndNeverRepeatsIt() {
|
||||
service.createScheduledAction(request("resume", ScheduledAction.RESUME_CLUSTER, "at(2026-11-20T13:00:00)"));
|
||||
|
||||
service.runScheduledActions(Instant.parse("2026-11-20T12:30:00Z"));
|
||||
verify(redshift, never()).resumeCluster(anyString());
|
||||
|
||||
service.runScheduledActions(Instant.parse("2026-11-20T13:05:00Z"));
|
||||
service.runScheduledActions(Instant.parse("2026-11-20T14:05:00Z"));
|
||||
verify(redshift, times(1)).resumeCluster("analytics");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledActionAndRefusedRoleDoNotRunAndAFailureIsRecorded() {
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
ScheduledAction changes = new ScheduledAction();
|
||||
changes.setScheduledActionName("pause");
|
||||
service.modifyScheduledAction(changes, false);
|
||||
service.runScheduledActions(BASE_TIME.plusSeconds(7200));
|
||||
verify(redshift, never()).pauseCluster(anyString());
|
||||
|
||||
service.modifyScheduledAction(changes, true);
|
||||
when(authorizer.refusal(eq(ROLE_ARN), eq(ACCOUNT_ID), anyString(), eq("PauseCluster"), anyString()))
|
||||
.thenReturn(Optional.of("the role does not trust the scheduler"));
|
||||
service.runScheduledActions(BASE_TIME.plusSeconds(4 * 3600));
|
||||
|
||||
verify(redshift, never()).pauseCluster(anyString());
|
||||
ScheduledAction stored = store.get("pause").orElseThrow();
|
||||
assertNotNull(stored.getLastFailure());
|
||||
assertNull(stored.getLastCompletedInvocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInvocationIsRecordedAndNotRetriedAndReEnablingDoesNotReplay() {
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
doThrow(new AwsException("InvalidClusterState", "not available", 400)).when(redshift).pauseCluster("analytics");
|
||||
Instant tick = BASE_TIME.plusSeconds(3 * 3600);
|
||||
|
||||
service.runScheduledActions(tick);
|
||||
service.runScheduledActions(tick.plusSeconds(60));
|
||||
|
||||
verify(redshift, times(1)).pauseCluster("analytics");
|
||||
assertEquals("not available", store.get("pause").orElseThrow().getLastFailure());
|
||||
|
||||
ScheduledAction changes = new ScheduledAction();
|
||||
changes.setScheduledActionName("pause");
|
||||
service.modifyScheduledAction(changes, false);
|
||||
service.modifyScheduledAction(changes, true);
|
||||
service.runScheduledActions(tick.plusSeconds(120));
|
||||
verify(redshift, times(1)).pauseCluster("analytics");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepAuthorizesAgainstTheArnOfTheRegionTheClusterLivesIn() {
|
||||
when(redshift.clusterRegion(ACCOUNT_ID, "analytics")).thenReturn(Optional.of("eu-west-1"));
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
|
||||
service.runScheduledActions(BASE_TIME.plusSeconds(3 * 3600));
|
||||
|
||||
verify(authorizer).refusal(ROLE_ARN, ACCOUNT_ID, "eu-west-1", ScheduledAction.PAUSE_CLUSTER, "analytics");
|
||||
verify(redshift).pauseCluster("analytics");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedOutcomeWriteIsNotSwallowedAndDoesNotAdvanceTheCheckpoint() {
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
doThrow(new IllegalStateException("disk full")).when(store).putAllAtomicallyForAccount(anyString(), any());
|
||||
Instant tick = BASE_TIME.plusSeconds(3 * 3600);
|
||||
|
||||
service.runScheduledActions(tick);
|
||||
|
||||
assertNull(store.get("pause").orElseThrow().getLastClaimedInvocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDropsTheActionWhenTheClusterIsDeletedBetweenValidationAndWrite() {
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
when(redshift.clusterExists(ACCOUNT_ID, "analytics")).thenReturn(true, false);
|
||||
ScheduledAction changes = new ScheduledAction();
|
||||
changes.setScheduledActionName("pause");
|
||||
changes.setDescription("changed");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.modifyScheduledAction(changes, null));
|
||||
|
||||
assertEquals("ClusterNotFound", failure.getErrorCode());
|
||||
assertTrue(store.get("pause").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingTheClusterDeletesItsActionsAndASweepDropsAnOrphan() {
|
||||
service.registerClusterRemoval();
|
||||
ArgumentCaptor<BiConsumer<String, String>> listener = ArgumentCaptor.forClass(BiConsumer.class);
|
||||
verify(redshift).onClusterRemoved(listener.capture());
|
||||
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
|
||||
listener.getValue().accept(ACCOUNT_ID, "analytics");
|
||||
assertTrue(store.get("pause").isEmpty());
|
||||
|
||||
service.createScheduledAction(request("again", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
|
||||
when(redshift.clusterExists(ACCOUNT_ID, "analytics")).thenReturn(false);
|
||||
service.runScheduledActions(BASE_TIME.plusSeconds(7200));
|
||||
assertTrue(store.get("again").isEmpty());
|
||||
verify(redshift, never()).pauseCluster(anyString());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user