diff --git a/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java b/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java index 51422a7a04..4322fc1fd6 100644 --- a/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java +++ b/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java @@ -69,6 +69,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.zip.CRC32; import java.util.zip.Inflater; @@ -123,6 +124,9 @@ public class CodePipelineService { // monitor for its whole run, so counting under that monitor would block StartPipelineExecution // until the running execution finished. private final KeyedLockPool startLocks = new KeyedLockPool(); + // Serializes the create, delete and tag writes of each custom action type, so two creates cannot both + // pass the existence check and a tag write cannot bring back a deleted type. Package-private for tests. + final KeyedLockPool actionTypeLocks = new KeyedLockPool(); private final Map runtimeArtifacts = new ConcurrentHashMap<>(); // An execution's status turns Failed as soon as one action fails, while its runner is still waiting // on sibling actions. Retries check this set so they never overlap a runner that has not finished. @@ -1299,18 +1303,29 @@ public class CodePipelineService { private ObjectNode createCustomActionType(JsonNode request, String region, String account) { String id = actionTypeId(request.path("category").asText(), "Custom", request.path("provider").asText(), request.path("version").asText()); - if (itemStore.getForAccount(account, itemKey(region, "action", id)).isPresent()) { - throw new AwsException("ActionTypeAlreadyExistsException", "Action type already exists", 400); - } - ObjectNode actionType = mapper.createObjectNode(); - actionType.setAll((ObjectNode) request.deepCopy()); - actionType.putObject("id") - .put("category", request.path("category").asText()) - .put("owner", "Custom") - .put("provider", request.path("provider").asText()) - .put("version", request.path("version").asText()); - storeItem(account, region, "action", id, "Active", actionType); - return mapper.createObjectNode().set("actionType", actionType); + String key = itemKey(region, "action", id); + return actionTypeLocks.withLock(account + ":" + key, () -> { + if (itemStore.getForAccount(account, key).isPresent()) { + throw new AwsException("ActionTypeAlreadyExistsException", "Action type already exists", 400); + } + ObjectNode actionType = mapper.createObjectNode(); + actionType.setAll((ObjectNode) request.deepCopy()); + actionType.remove("tags"); + actionType.putObject("id") + .put("category", request.path("category").asText()) + .put("owner", "Custom") + .put("provider", request.path("provider").asText()) + .put("version", request.path("version").asText()); + CodePipelineStoredItem item = newItem(account, region, "action", id, "Active", actionType); + item.setTags(parseTags(request.path("tags"))); + putItem(item); + ObjectNode response = mapper.createObjectNode(); + response.set("actionType", actionType); + if (!item.getTags().isEmpty()) { + response.set("tags", tagsNode(item.getTags())); + } + return response; + }); } private ObjectNode updateActionType(JsonNode request, String region, String account) { @@ -1335,7 +1350,8 @@ public class CodePipelineService { private ObjectNode deleteCustomActionType(JsonNode request, String region, String account) { String id = actionTypeId(request.path("category").asText(), "Custom", request.path("provider").asText(), request.path("version").asText()); - itemStore.deleteForAccount(account, itemKey(region, "action", id)); + String key = itemKey(region, "action", id); + actionTypeLocks.withLock(account + ":" + key, () -> itemStore.deleteForAccount(account, key)); return mapper.createObjectNode(); } @@ -1472,22 +1488,63 @@ public class CodePipelineService { } private ObjectNode tagResource(JsonNode request, String region, String account) { - CodePipelinePipeline pipeline = requirePipelineByArn(account, region, text(request, "resourceArn")); - pipeline.getTags().putAll(parseTags(request.path("tags"))); - putPipeline(pipeline); + updateTags(account, region, text(request, "resourceArn"), tags -> { + tags.putAll(parseTags(request.path("tags"))); + return requireTagLimit(tags); + }); return mapper.createObjectNode(); } private ObjectNode untagResource(JsonNode request, String region, String account) { - CodePipelinePipeline pipeline = requirePipelineByArn(account, region, text(request, "resourceArn")); - request.path("tagKeys").forEach(k -> pipeline.getTags().remove(k.asText())); - putPipeline(pipeline); + updateTags(account, region, text(request, "resourceArn"), tags -> { + request.path("tagKeys").forEach(k -> tags.remove(k.asText())); + return tags; + }); return mapper.createObjectNode(); } private ObjectNode listTagsForResource(JsonNode request, String region, String account) { - CodePipelinePipeline pipeline = requirePipelineByArn(account, region, text(request, "resourceArn")); - return mapper.createObjectNode().set("tags", tagsNode(pipeline.getTags())); + String arn = text(request, "resourceArn"); + Map tags = actionTypeKey(account, region, arn) + .flatMap(key -> itemStore.getForAccount(account, key)) + .map(CodePipelineStoredItem::getTags) + .orElseGet(() -> requirePipelineByArn(account, region, arn).getTags()); + return mapper.createObjectNode().set("tags", tagsNode(tags)); + } + + /** + * Stores {@code update} applied to a copy of the resource's tags, under the lock its create and + * delete take. The map is replaced, never edited, since ListTagsForResource and the stores' + * serializers read it without that lock. + */ + private void updateTags(String account, String region, String arn, UnaryOperator> update) { + Optional actionTypeKey = actionTypeKey(account, region, arn); + if (actionTypeKey.isPresent()) { + String key = actionTypeKey.get(); + actionTypeLocks.withLock(account + ":" + key, () -> { + CodePipelineStoredItem item = itemStore.getForAccount(account, key) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Resource not found: " + arn, 400)); + item.setTags(update.apply(new LinkedHashMap<>(item.getTags()))); + putItem(item); + }); + return; + } + String name = requirePipelineByArn(account, region, arn).getName(); + sourcePollLocks.withLock(pipelineLockKey(account, region, name), () -> { + CodePipelinePipeline pipeline = requirePipelineByArn(account, region, arn); + pipeline.setTags(update.apply(new LinkedHashMap<>(pipeline.getTags()))); + putPipeline(pipeline); + }); + } + + private Optional actionTypeKey(String account, String region, String arn) { + return AwsArnUtils.parseIfArnIn(arn, "codepipeline", region) + .filter(parsed -> account.equals(parsed.accountId()) && parsed.resource().startsWith("actiontype:")) + // The ARN names the type as Owner/Category/Provider/Version. + .map(parsed -> parsed.resource().substring("actiontype:".length()).split("/")) + .filter(id -> id.length == 4) + .map(id -> itemKey(region, "action", actionTypeId(id[1], id[0], id[2], id[3]))); } /** @@ -2659,6 +2716,11 @@ public class CodePipelineService { private void storeItem(String account, String region, String type, String id, String status, JsonNode data) { + putItem(newItem(account, region, type, id, status, data)); + } + + private CodePipelineStoredItem newItem(String account, String region, String type, String id, + String status, JsonNode data) { CodePipelineStoredItem item = new CodePipelineStoredItem(); item.setAccountId(account); item.setRegion(region); @@ -2668,7 +2730,7 @@ public class CodePipelineService { item.setCreated(now()); item.setUpdated(item.getCreated()); item.setData(data.deepCopy()); - putItem(item); + return item; } private void putItem(CodePipelineStoredItem item) { @@ -3073,6 +3135,10 @@ public class CodePipelineService { tags.put(tag.path("key").asText(), tag.path("value").asText("")); } } + return requireTagLimit(tags); + } + + private static Map requireTagLimit(Map tags) { if (tags.size() > 50) { throw new AwsException("TooManyTagsException", "A resource can have at most 50 tags", 400); } diff --git a/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java b/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java index f8255e8913..88150525ea 100644 --- a/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java +++ b/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java @@ -4,6 +4,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JsonNode; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.LinkedHashMap; +import java.util.Map; + @RegisterForReflection @JsonInclude(JsonInclude.Include.NON_NULL) public class CodePipelineStoredItem { @@ -18,6 +21,7 @@ public class CodePipelineStoredItem { private Double created; private Double updated; private JsonNode data; + private Map tags = new LinkedHashMap<>(); public String getAccountId() { return accountId; @@ -82,4 +86,12 @@ public class CodePipelineStoredItem { public void setData(JsonNode data) { this.data = data; } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } } diff --git a/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java b/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java index 0eef3c50e9..9979f30785 100644 --- a/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java +++ b/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java @@ -22,6 +22,7 @@ import io.floci.aws.services.s3.model.S3Object; import io.floci.aws.testing.ThreadStates; import io.smallrye.config.SmallRyeConfigBuilder; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -32,9 +33,11 @@ import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.Set; +import java.util.StringJoiner; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -696,6 +699,122 @@ class CodePipelineServiceTest { assertEquals("Failed", summaries.get(0).path("status").asText()); } + @Test + void customActionTypeTagsAreResourceTagsOfItsArn() throws Exception { + String arn = "arn:aws:codepipeline:us-east-1:000000000000:actiontype:Custom/Build/TagProvider/1"; + JsonNode created = handle("CreateCustomActionType", """ + { + "category": "Build", + "provider": "TagProvider", + "version": "1", + "inputArtifactDetails": {"minimumCount": 0, "maximumCount": 1}, + "outputArtifactDetails": {"minimumCount": 0, "maximumCount": 1}, + "tags": [{"key": "team", "value": "red"}] + } + """); + + assertEquals(mapper.readTree("[{\"key\": \"team\", \"value\": \"red\"}]"), created.path("tags")); + assertFalse(created.path("actionType").has("tags")); + assertEquals(created.path("tags"), + handle("ListTagsForResource", "{\"resourceArn\": \"" + arn + "\"}").path("tags")); + + handle("TagResource", """ + {"resourceArn": "%s", "tags": [{"key": "env", "value": "dev"}]} + """.formatted(arn)); + handle("UntagResource", """ + {"resourceArn": "%s", "tagKeys": ["team"]} + """.formatted(arn)); + + assertEquals(mapper.readTree("[{\"key\": \"env\", \"value\": \"dev\"}]"), + handle("ListTagsForResource", "{\"resourceArn\": \"" + arn + "\"}").path("tags")); + AwsException missing = assertThrows(AwsException.class, () -> handle("ListTagsForResource", + "{\"resourceArn\": \"" + arn.replace("TagProvider", "OtherProvider") + "\"}")); + assertEquals("ResourceNotFoundException", missing.getErrorCode()); + } + + @Test + void tagResourceCountsTheTagsTheResourceAlreadyHas() throws Exception { + String arn = "arn:aws:codepipeline:us-east-1:000000000000:actiontype:Custom/Build/FullProvider/1"; + handle("CreateCustomActionType", customActionTypeRequest("FullProvider", 50)); + + AwsException tooMany = assertThrows(AwsException.class, () -> handle("TagResource", """ + {"resourceArn": "%s", "tags": [{"key": "k50", "value": "v"}]} + """.formatted(arn))); + assertEquals("TooManyTagsException", tooMany.getErrorCode()); + handle("TagResource", """ + {"resourceArn": "%s", "tags": [{"key": "k0", "value": "changed"}]} + """.formatted(arn)); + + JsonNode tags = handle("ListTagsForResource", "{\"resourceArn\": \"" + arn + "\"}").path("tags"); + assertEquals(50, tags.size()); + assertEquals("changed", tags.get(0).path("value").asText()); + } + + @Test + void secondCreateOfACustomActionTypeWaitsForTheFirstAndIsRefused() throws Exception { + String request = customActionTypeRequest("RaceProvider", 0); + Future second = handleWhileHoldingActionTypeLock("RaceProvider", "CreateCustomActionType", + request, () -> handle("CreateCustomActionType", request)); + + ExecutionException refused = assertThrows(ExecutionException.class, second::get); + assertEquals("ActionTypeAlreadyExistsException", ((AwsException) refused.getCause()).getErrorCode()); + } + + @Test + void tagWriteWaitsForACustomActionTypeDeleteAndDoesNotRestoreIt() throws Exception { + String arn = "arn:aws:codepipeline:us-east-1:000000000000:actiontype:Custom/Build/DeletedProvider/1"; + handle("CreateCustomActionType", customActionTypeRequest("DeletedProvider", 0)); + Future tagged = handleWhileHoldingActionTypeLock("DeletedProvider", "TagResource", """ + {"resourceArn": "%s", "tags": [{"key": "env", "value": "dev"}]} + """.formatted(arn), () -> handle("DeleteCustomActionType", """ + {"category": "Build", "provider": "DeletedProvider", "version": "1"} + """)); + + ExecutionException missing = assertThrows(ExecutionException.class, tagged::get); + assertEquals("ResourceNotFoundException", ((AwsException) missing.getCause()).getErrorCode()); + AwsException deleted = assertThrows(AwsException.class, + () -> handle("ListTagsForResource", "{\"resourceArn\": \"" + arn + "\"}")); + assertEquals("ResourceNotFoundException", deleted.getErrorCode()); + } + + /** + * Sends {@code operation} from another thread while this one holds the lock of the custom action + * type Build/{@code provider}/1, and runs {@code meanwhile} once the request waits on it. + */ + private Future handleWhileHoldingActionTypeLock(String provider, String operation, String body, + Executable meanwhile) { + String lockKey = ACCOUNT + ":" + REGION + ":action:Build:Custom:" + provider + ":1"; + try (ExecutorService requests = Executors.newSingleThreadExecutor()) { + AtomicReference requestThread = new AtomicReference<>(); + return service.actionTypeLocks.withLock(lockKey, () -> { + Future response = requests.submit(() -> { + requestThread.set(Thread.currentThread()); + return handle(operation, body); + }); + assertDoesNotThrow(() -> ThreadStates.awaitBlockedOrDone(requestThread, response)); + assertDoesNotThrow(meanwhile); + return response; + }); + } + } + + private static String customActionTypeRequest(String provider, int tagCount) { + StringJoiner tags = new StringJoiner(", "); + for (int i = 0; i < tagCount; i++) { + tags.add("{\"key\": \"k" + i + "\", \"value\": \"v\"}"); + } + return """ + { + "category": "Build", + "provider": "%s", + "version": "1", + "inputArtifactDetails": {"minimumCount": 0, "maximumCount": 1}, + "outputArtifactDetails": {"minimumCount": 0, "maximumCount": 1}, + "tags": [%s] + } + """.formatted(provider, tags); + } + private JsonNode handle(String action, String body) throws Exception { return service.handle(action, mapper.readTree(body), REGION, ACCOUNT); }